text
stringlengths 27
775k
|
---|
#coding=utf-8
from __future__ import division
import os, os.path
import zipfile
import math
from file_utils import *
# 压缩文件夹
def ZipFile(dirname, zipfilename):
fileList = FileUtils.GetAllFiles(dirname)
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
for index, tar in enumerate(fileList):
arcname = tar[len(dirname):]
zf.write(tar,arcname)
Progressbar(index + 1, len(fileList))
zf.close()
# 压缩文件
def ZipSingleFile(filename, zipfilename):
zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
arcname = os.path.split(filename)[1]
zf.write(filename, arcname)
zf.close()
# 解压缩文件
def UnzipFile(zipfilename, unziptodir):
if not os.path.exists(unziptodir):
os.makedirs(unziptodir, 0777)
zfobj = zipfile.ZipFile(zipfilename)
for index, name in enumerate(zfobj.namelist()):
name = name.replace('\\','/')
if name.endswith('/'):
os.makedirs(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir= os.path.dirname(ext_filename)
if not os.path.exists(ext_dir):
os.makedirs(ext_dir,0777)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
outfile.close()
Progressbar(index + 1, len(zfobj.namelist()))
# 定义一个进度条 用来显示进度
def Progressbar(cur, total):
percent = '{:.2%}'.format(cur / total)
sys.stdout.write('\r')
sys.stdout.write("[%-50s] %s" % (
'=' * int(math.floor(cur * 50 / total)),
percent))
sys.stdout.flush()
if __name__ == '__main__':
if 2 > len(sys.argv):
print("use python zip_utils -h for help")
sys.exit()
if "-h" == sys.argv[1]:
print("usage: python zip_utils.py [option] [arg]")
print("-a arg :use to zip, arg is dirname zipfilename")
print("-b arg :use to unzip, arg is zipfilename unziptodir")
print("sample: python zip_utils.py -b ../test_zip.zip ../Update/etc/newest")
elif "-a" == sys.argv[1]:
try:
ZipFile(sys.argv[2], sys.argv[3])
except:
print("porgram is error")
elif "-b" == sys.argv[1]:
try:
UnzipFile(sys.argv[2], sys.argv[3])
except:
print("porgram is error")
elif "-c" == sys.argv[1]:
ZipSingleFile(sys.argv[2], sys.argv[3]) |
<?php
namespace App\Http\Controllers;
use App\Admin;
use App\Brand;
use App\Banner;
use App\User;
use App\Order;
use App\Seller;
use App\Slider;
use App\Product;
use App\Promote;
use App\Category;
use App\Customer;
use App\Coupon;
use App\Subcategory;
use App\Singlepage;
use App\Categorybanner;
use App\Undersubcategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Intervention\Image\Facades\Image;
class AdminController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.home');
}
public function Slidermanage()
{
return view('admin.setting.addslider');
}
public function BannerManage()
{
return view('admin.setting.addbanner');
}
public function CategoryBannermanage()
{
return view('admin.setting.addcategorybanner');
}
public function AddSlider(Request $request, $id)
{
$image = $request->slider;
$imageName = time().'-'.$image->getClientOriginalName();
$path = base_path();
$public_path = str_replace("dpunch", "dpunch.com", $path);
$destinationPath =$public_path.'/assets/img/slider';
$img = Image::make($image->getRealPath());
$img->resize(1170, 400)->save($destinationPath.'/'.$imageName);
$flight = Slider::updateOrCreate(
['slider_id' => $id],
[
'slidertext' => $request->slidertext,
'sliderimg' => $imageName,
'slidelink' => $request->sliderlink,
]
);
Session::flash('message', 'Slider Add Successfully!');
return back();
}
public function AddBanner(Request $request, $id)
{
$image = $request->banner;
$imageName = time().'-'.$image->getClientOriginalName();
$path = base_path();
$public_path = str_replace("dpunch", "dpunch.com", $path);
$destinationPath = $public_path .'/assets/img/banner';
$img = Image::make($image->getRealPath());
$img->resize(1160, 180)->save($destinationPath.'/'.$imageName);
$flight = Banner::updateOrCreate(
['id' => $id],
['banner' => $imageName,
'bannerlink' =>$request->bannerlink]
);
Session::flash('message', 'Banner Add Successfully!');
return back();
}
public function AddCAtegoryBanner(Request $request, $category)
{
$image = $request->bannerimg;
$imageName = time().'-'.$image->getClientOriginalName();
$path = base_path();
$public_path = str_replace("dpunch", "dpunch.com", $path);
$destinationPath = $public_path .'/assets/img/categorybanner';
$img = Image::make($image->getRealPath());
$img->resize(338, 478)->save($destinationPath.'/'.$imageName);
$flight = Categorybanner::updateOrCreate(
['category' => $category],
[
'bannerimg' => $imageName,
'bannerlink' => $request->bannerlink,
]
);
Session::flash('message', 'Slider Add Successfully!');
return back();
}
public function generalSetting()
{
return view('admin.setting.site-setting');
}
public function menuManage()
{
$mainmenu = Category::all();
return view('admin.setting.menu',compact('mainmenu'));
}
public function addMenu()
{
$allcategory = Category::all();
// $subcat = Subcategory::find($id);
return view('admin.setting.add-menu')->with(compact('allcategory'));
}
public function addCategory(Request $request)
{
$category = new Category;
$category->slug = str_slug($request->category, "-");
$category->name = $request->category;
$category->save();
Session::flash('menustatus', 'Category Add Successfully!');
return redirect('admin/addmenu');
}
public function addSubcategory(Request $request)
{
$subcategory = new Subcategory;
$subcategory->category_id = $request->category_id;
$subcategory->slug = str_slug($request->subcategory, "-");
$subcategory->name = $request->subcategory;
$subcategory->save();
Session::flash('submenustatus', 'Subcategory Add Successfully!');
return redirect('admin/addmenu');
}
public function addUndersubcategory(Request $request)
{
$childcategory = new Undersubcategory;
$childcategory->category_id = $request->category_id;
$childcategory->subcategory_id = $request->subcategory_id;
$childcategory->slug = str_slug($request->undersubcategory, "-");
$childcategory->name = $request->undersubcategory;
$childcategory->save();
Session::flash('childmenustatus', 'Child category Add Successfully!');
return redirect('admin/addmenu');
}
public function addBrand(Request $request)
{
$brand = new Brand;
$brand->category_id = $request->category_id;
$brand->subcategory_id = $request->subcategory_id;
$brand->undersubcategory_id = $request->undersubcategory_id;
$brand->slug = str_slug($request->brand, "-");
$brand->name = $request->brand;
$brand->save();
Session::flash('brandstatus', 'Brand Add Successfully!');
return redirect('admin/addmenu');
}
public function ajaxForSubCategory(Request $request)
{
if ($request->isMethod('post')){
$cat_id= $request->id;
$subcat = Subcategory::where('category_id', $cat_id)->get();
return response()->json($subcat);
}
return response()->json(['response' => 'This is get method']);
}
public function ajaxForUnderSubCategory(Request $request)
{
if ($request->isMethod('post')){
$subcat_id= $request->id;
$undersubcat = Undersubcategory::where('subcategory_id', $subcat_id)->get();
return response()->json($undersubcat);
}
return response()->json(['response' => 'This is get method']);
}
public function ajaxForBrand(Request $request)
{
if ($request->isMethod('post')){
$unsubcat_id= $request->id;
$brand = Brand::where('undersubcategory_id', $unsubcat_id)->get();
return response()->json($brand);
}
return response()->json(['response' => 'This is get method']);
}
public function ajaxForBrandBySubcat(Request $request)
{
if ($request->isMethod('post')){
$subcat_id= $request->id;
$brand = Brand::where('subcategory_id', $subcat_id)->get();
return response()->json($brand);
}
return response()->json(['response' => 'This is get method']);
}
public function allSeller()
{
$allseller = Seller::all();
return view('admin.seller',compact('allseller'));
}
public function updateSeller(Request $request)
{
if ($request->isMethod('post')){
$id= $request->id;
$status = $request->status;
$seller = Seller::findOrFail($id);
$seller->status = $status;
$seller->save();
return response()->json($status);
}
}
public function allProduct()
{
$allprodutcs = Product::all();
return view('admin.product',compact('allprodutcs'));
}
public function publishProduct(Request $request)
{
if ($request->isMethod('post')){
$id= $request->id;
$status = $request->status;
$product = Product::findOrFail($id);
$product->status = $status;
$product->save();
return response()->json($status);
}
}
public function allArchiveProduct()
{
$archiveproducts = Product::onlyTrashed()->get();
return view('admin.product-archive',compact('archiveproducts'));
}
public function viewProduct($id)
{
$product = Product::findOrFail($id);
return view('admin.product-view',compact('product'));
}
public function addProductForm()
{
$allcategory = Category::all();
return view('admin.product-add',compact('allcategory'));
}
public function addProduct(Request $request)
{
// return $request->all();
$productimage = array();
if ($request->image != '') {
foreach ($request->image as $image){
$imageName = time().'-'.$image->getClientOriginalName();
$productimage[] = $imageName;
$path = base_path();
$public_path = str_replace("dpunch", "dpunch.com", $path);
$destinationPathsmall = $public_path .'/images/small';
$destinationPaththumbnail = $public_path .'/images/thumbnail';
$destinationPathzoom = $public_path .'/images/zoom';
$img = Image::make($image->getRealPath());
$img->resize(800, 800, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPathzoom.'/'.$imageName);
$img->resize(450, 450, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPaththumbnail.'/'.$imageName);
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPathsmall.'/'.$imageName);
}
}
$image0="";
$image1="";
$image2="";
$image3="";
$image4="";
$image5="";
if (isset($productimage[0]) && $productimage[0] != null) {
$image0 = $productimage[0];
}
if (isset($productimage[1]) && $productimage[1] != null) {
$image1 = $productimage[1];
}
if (isset($productimage[2]) && $productimage[2] != null) {
$image2 = $productimage[2];
}
if (isset($productimage[3]) && $productimage[3] != null) {
$image3 = $productimage[3];
}
if (isset($productimage[4]) && $productimage[4] != null) {
$image4 = $productimage[4];
}
if (isset($productimage[5]) && $productimage[5] != null) {
$image4 = $productimage[5];
}
if (Auth::guard('admin')->check()) {
$seller_name = Auth::guard('admin')->user()->name;
$seller_id = Auth::guard('admin')->user()->id;
}
$subcategoris = Subcategory::findOrFail($request->subcategory_id);
$subcategory = $subcategoris->name;
$sku = "DPN".$seller_id.strtoupper(substr($subcategory,0,3)).date("s", time());
$product = new Product;
$product->seller = $seller_name;
$product->sku = $sku;
$product->category_id = $request->category_id;
$product->subcategory_id = $request->subcategory_id;
$product->undersubcategory_id = $request->undersubcategory_id;
$product->brand_id = $request->brand_id;
$product->product_condition = $request->product_condition;
$product->product_origin = $request->product_origin;
$product->title = $request->title;
$product->slug = str_slug($request->title, "-");
$product->color = $request->color;
$product->main_price = $request->price;
$product->discount = $request->discount;
$product->price = $request->price-($request->price*($request->discount/100));
$product->size_1 = $request->size_1;
$product->size_2 = $request->size_2;
$product->size_3 = $request->size_3;
$product->size_4 = $request->size_4;
$product->size_5 = $request->size_5;
$product->size_6 = $request->size_6;
$product->availability = $request->availability;
$product->image0 = $image0;
$product->image1 = $image1;
$product->image2 = $image2;
$product->image3 = $image3;
$product->image4 = $image4;
$product->image5 = $image5;
$product->detailes = $request->detailes;
$product->specification = $request->specification;
$product->status = 1;
$product->save();
Session::flash('productstatus', 'Product Add Successfully!');
return back();
}
public function editProductForm($id)
{
$allcategory = Category::all();
$product = Product::findOrFail($id);
return view('admin.product-edit',compact('allcategory','product'));
}
public function updateProduct(Request $request,$id)
{
$prev_img0 = $request->prev_img0;
$prev_img1 = $request->prev_img1;
$prev_img2 = $request->prev_img2;
$prev_img3 = $request->prev_img3;
$prev_img4 = $request->prev_img4;
$prev_img5 = $request->prev_img5;
$productimage = array();
if ($request->image != '') {
// if($prev_img0){
// unlink(base_path('dpunch.com/images/small'.$prev_img0));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img0));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img0));
// }
// if($prev_img1){
// unlink(base_path('dpunch.com/images/small'.$prev_img1));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img1));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img1));
// }
// if($prev_img2){
// unlink(base_path('dpunch.com/images/small'.$prev_img2));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img2));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img2));
// }
// if($prev_img3){
// unlink(base_path('dpunch.com/images/small'.$prev_img3));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img3));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img3));
// }
// if($prev_img4){
// unlink(base_path('dpunch.com/images/small'.$prev_img4));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img4));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img4));
// }
// if($prev_img5){
// unlink(base_path('dpunch.com/images/small'.$prev_img5));
// unlink(base_path('dpunch.com/images/thumbnail'.$prev_img5));
// unlink(base_path('dpunch.com/images/zoom'.$prev_img5));
// }
foreach ($request->image as $image){
$imageName = time().'-'.$image->getClientOriginalName();
$productimage[] = $imageName;
$path = base_path();
$public_path = str_replace("dpunch", "dpunch.com", $path);
$destinationPathsmall = $public_path .'/images/small';
$destinationPaththumbnail = $public_path .'/images/thumbnail';
$destinationPathzoom = $public_path .'/images/zoom';
$img = Image::make($image->getRealPath());
$img->resize(800, 800, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPathzoom.'/'.$imageName);
$img->resize(450, 450, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPaththumbnail.'/'.$imageName);
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();})->save($destinationPathsmall.'/'.$imageName);
}
}
$image0=$prev_img0;
$image1=$prev_img1;
$image2=$prev_img2;
$image3=$prev_img3;
$image4=$prev_img4;
$image5=$prev_img5;
if (isset($productimage[0]) && $productimage[0] != null) {
$image0 = $productimage[0];
}
if (isset($productimage[1]) && $productimage[1] != null) {
$image1 = $productimage[1];
}
if (isset($productimage[2]) && $productimage[2] != null) {
$image2 = $productimage[2];
}
if (isset($productimage[3]) && $productimage[3] != null) {
$image3 = $productimage[3];
}
if (isset($productimage[4]) && $productimage[4] != null) {
$image4 = $productimage[4];
}
if (isset($productimage[5]) && $productimage[5] != null) {
$image4 = $productimage[5];
}
$product = Product::findOrFail($id);
$product->category_id = $request->category_id;
$product->subcategory_id = $request->subcategory_id;
$product->undersubcategory_id = $request->undersubcategory_id;
$product->brand_id = $request->brand_id;
$product->product_condition = $request->product_condition;
$product->product_origin = $request->product_origin;
$product->title = $request->title;
$product->color = $request->color;
$product->main_price = $request->price;
$product->discount = $request->discount;
$product->price = $request->price-($request->price*($request->discount/100));
$product->size_1 = $request->size_1;
$product->size_2 = $request->size_2;
$product->size_3 = $request->size_3;
$product->size_4 = $request->size_4;
$product->size_5 = $request->size_5;
$product->size_6 = $request->size_6;
$product->availability = $request->availability;
$product->image0 = $image0;
$product->image1 = $image1;
$product->image2 = $image2;
$product->image3 = $image3;
$product->image4 = $image4;
$product->image5 = $image5;
$product->detailes = $request->detailes;
$product->specification = $request->specification;
$product->save();
Session::flash('message', 'Product Edit Successfully!');
return Redirect::to('admin/manageproduct');
}
public function deleteProduct($id)
{
// delete
$product = Product::findOrFail($id);
$product->delete();
// redirect
Session::flash('message', 'Successfully deleted the Product!');
return Redirect::to('admin/manageproduct');
}
public function promoteProductList()
{
$promotelist = Promote::all();
return view('admin.product-promote-list',compact('promotelist'));
}
public function promoteProductView($id)
{
$promote = Promote::where('product_id', $id)->firstOrFail();
return view('admin.product-promote',compact('promote'));
}
public function promoteProduct(Request $request,$id)
{
$promote = Promote::where('product_id', $id)->firstOrFail();
$promote->promote_status = 1;
$promote->save();
return back();
}
public function allCustomer()
{
$allcustomer = User::all();
return view('admin.customer',compact('allcustomer'));
}
public function allOrder()
{
$allorder = Order::where('status','0')->get();
return view('admin.order',compact('allorder'));
}
public function Orderdetailes($id)
{
$orderdetailes = Order::find($id);
// return $orderdetailes;
return view('admin.order-detailes',compact('orderdetailes'));
}
public function ConfirmOrder($id)
{
$confirm = Order::findOrFail($id);
$confirm->status = 1;
$confirm->save();
Session::flash('message', 'Order Confirmed Successfully!');
return redirect('admin/manageconfirmedorder');
}
public function CancleOrder($id)
{
$confirm = Order::findOrFail($id);
$confirm->status = 2;
$confirm->save();
Session::flash('message', 'Order Cancled Successfully!');
return redirect('admin/managecancledorder');
}
public function OrderdetailesPrint($id)
{
$orderdetailes = Order::find($id);
// return $orderdetailes;
return view('admin.print-order-detailes',compact('orderdetailes'));
}
public function allCancleOrder()
{
$allorder = Order::where('status','2')->get();
return view('admin.cancledorder',compact('allorder'));
}
public function allConfirmedOrder()
{
$allorder = Order::status()->get();
// return $allorder;
return view('admin.confirmedorder',compact('allorder'));
}
public function ViewAllPage()
{
$singlepages = Singlepage::all();
return view('admin.setting.single-page',compact('singlepages'));
}
public function AddsinglePage()
{
return view('admin.setting.add-single-page');
}
public function AddPage(Request $request)
{
$singlepage = new Singlepage;
$singlepage->title = $request->page_title;
$singlepage->slug = str_slug($request->page_title, "-");
$singlepage->description = $request->description;
$singlepage->save();
Session::flash('message', 'Page add Successfully!');
return back();
}
public function EditPage($id)
{
$singlepage = Singlepage::findOrFail($id);
return view('admin.setting.edit-single-page',compact('singlepage'));
}
public function UpdatePage(Request $request, $id)
{
$singlepage = Singlepage::findOrFail($id);
$singlepage->title = $request->page_title;
$singlepage->description = $request->description;
$singlepage->save();
Session::flash('message', 'Page Edit Successfully!');
return back();
}
public function allCuppon()
{
$coupons = Coupon::all();
return view('admin.cuppon',compact('coupons'));
}
public function addCupponform()
{
return view('admin.cuppon-add');
}
public function addCuppon(Request $request)
{
$coupon = new Coupon;
$coupon->code = $request->code;
$coupon->type = $request->cupon_type;
$coupon->value = $request->value;
$coupon->discription = $request->discription;
$coupon->validity = 1;
$coupon->save();
Session::flash('cupponstatus', 'Cupon Add Successfully!');
return back();
}
public function editCupponform($id)
{
$coupon = Coupon::findOrFail($id);
return view('admin.cuppon-edit',compact('coupon'));
}
public function editCuppon(Request $request, $id)
{
$coupon = Coupon::findOrFail($id);
$coupon->code = $request->code;
$coupon->type = $request->cupon_type;
$coupon->value = $request->value;
$coupon->discription = $request->discription;
$coupon->save();
Session::flash('cupponstatus', 'Cupon Update Successfully!');
return back();
}
public function manageCuppon(Request $request,$id)
{
$coupon = Coupon::findOrFail($id);
$coupon->validity = $request->validity;
$coupon->save();
Session::flash('message', 'Cupon Update Successfully!');
return back();
}
}
|
import EmberObject, { computed } from '@ember/object';
export default EmberObject.extend({
initialState: null,
currentState: computed({
get() {
let name = this.get('initialState');
return this.get(name);
},
set(_key, val) {
return val;
}
}),
transitionTo(path) {
let current = this.get('currentState');
while (current) {
let nextState = current.get(path);
if (nextState) {
allBetween(current, nextState).forEach(state => state.enter && state.enter(this));
this.set("currentState", nextState);
return;
}
current = current.get('parent');
}
throw new Error(`Can't transition to ${path}`);
},
send(name, ...args) {
let state = this.get('currentState');
return state.send(name, ...args);
}
});
function allBetween(start, end) {
let parent = end.get('parent');
let intermediate = [end];
while (parent) {
intermediate.push(parent);
parent = parent.get('parent');
if (parent === start) {
break;
}
}
return intermediate;
}
|
# BAT大牛带你横扫初级前端JavaScript面试
## 第1章 课程简介
### 1-1 课程简介
基础知识
- 原型、原型链
- 作用域、闭包
- 异步、单线程
JS API
- DOM 操作
- Ajax
- 事件绑定
开发环境
- 版本管理
- 模块化
- 打包工具
运行环境
- 页面渲染
- 性能优化
### 1-2 前言
关于面试
- 基层工程师 - 基础知识
- 高级工程师 - 项目经验
- 架构师 - 解决方案
关于基础
- 工程师的自我修养 - 基础
- 扎实的基础会让你高效学习新技术
### 1-3 几个面试题
先从几道面试题说起
- JS 中使用 `typeof ` 能得到的哪些类型?
- 何时使用 `===` ,何时使用 `==` ?
- `window.onload` 和 `DOMContentLoaded` 的区别?
- 用 JS 创建 10 个 `<a>` 标签,点击的时候弹出对应的序号
- 简述如何实现一个模块加载器,实现类似 `require.js` 的基本功能
- 实现数组的随机排序
思考
- 拿到一个面试题,你第一时间看到的是什么?
- 又如何看待网上搜出来的永远看不完的题海?
- 如何对待接下来遇到的面试题?
### 1-4 如何搞定所有面试题
上一节思考问题的结论
- 拿到一个面试题,你第一时间看到的是什么?- **考点**
- 又如何看待网上搜出来的永远看不完的题海?- **不变应万变**
- 如何对待接下来遇到的面试题?- **题目到知识再到题目**
题目考察的知识点
- JS 中使用 `typeof` 能得到的哪些类型?
考点:**JS 变量类型**
- 何时使用 `===` ,何时使用 `==` ?
考点:**强制类型转换**
- `window.onload` 和 `DOMContentLoaded` 的区别?
考点:**浏览器渲染过程**
- 用 JS 创建 10 个 `<a>` 标签,点击的时候弹出来对应的序号
考点:**作用域**
- 简述如何实现一个模块加载器,实现类似 `require.js` 的基本功能
考点:**JS 模块化**
- 实现数组的随机排序
考点:**JS 基础算法**
## 第2章 JS 基础知识(上)
### 2-1 变量类型和计算 - 1
题目
- JS 中使用 `typeof` 能得到的哪些类型?
- 何时使用 `===` ,何时使用 `==` ?
- JS 中有哪些内置函数?
- JS 变量按照存储方式区分为哪些类型,并描述其特点?
- 如何理解 JSON ?
知识点
- 变量类型
- 变量计算
**变量类型**
- 值类型、引用类型
- `typeof` 运算符
值类型
```js
let a = 100
let b = a
a = 200
console.log(b) // 100
```
引用类型
```js
let a = { age: 20 }
let b = a
b.age = 21
console.log(a.age) // 21
```
`typeof` 运算符
```js
typeof undefined // "undefined"
typeof 'abc' // "string"
typeof 123 // "number"
typeof true // "boolean"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
typeof console.log // "function"
```
**变量计算 - 强制类型转换**
字符串拼接
```js
let a = 100 + 10 // 110
let b = 100 + '10' // "10010"
```
`==` 运算符
```js
100 == '100' // true
0 == '' // true
null = undefined // true
```
`if` 语句
```js
let a = true
if (a) {}
let b = 100
if (b) {}
let c = ''
if (c) {}
```
逻辑运算符
```js
console.log(10 && 0) // 0
console.log('' || 'abc') // "abc"
console.log(!window.abc) // true
// 判断一个变量会被当做 true 还是 false
let a = 100
console.log(!!a) // true
```
### 2-2 变量类型和计算 - 2
**解答**
JS 中使用 `typeof` 能得到的哪些类型?
答:`undefined` 、`string` 、`number` 、`boolean` 、`object` 、`function` 、`symbol`
```js
let sym = Symbol('commet')
console.log(typeof sym) // "symbol"
```
何时使用 `===` ,何时使用 `==` ?
答:判断对象的某个属性是否存在或为 `null` 时可以使用 `==` ,因为 jQuery 源码这么使用
```js
if (obj.a == null) {
// 这里相当于 obj.a === null || obj.a === undefined 的简写形式
// 这是 jQuery 源码中推荐的写法
}
```
JS 中有哪些内置函数?
答:数据封装类对象,包括 `String` 、`Number` 、`Boolean` 、`Object` 、`Array` 、`Function` 、`Date` 、`RegExp` 、`Error`
JS 变量按照存储方式区分为哪些类型,并描述其特点?
答:值类型和引用类型,一个存储值,一个存储引用地址,引用类型可以无限拓展属性
### 2-3 变量类型和计算 - 3
如何理解 JSON ?
答:JSON 只不过是一个 JS 对象而已,也是一种数据格式
```js
JSON.stringify({ a: 10, b: 20 })
JSON.parse('{"a":10,"b":20}')
```
### 2-4 变量类型和计算 - 代码演示
`if` 语句中条件为 `false` 的情况有哪些?
答:`''` 、`0` 、`NaN` 、`false`、`null` 、`undefined`
JS 中有哪些内置对象?
答:`JSON` 、`Math`
### 2-5 typeof symbol
```js
let s = Symbol()
typeof s // "symbol"
let s1 = Symbol()
console.log(s === s1) // false
let s2 = Symbol('s2s2')
console.log(s2) // Symbol(s2s2)
let s3 = s2
console.log(s3 === s2) // true
let sym1 = Symbol('111')
let sym2 = Symbol('222')
let obj = { [sym1]: 'hello world' }
obj[sym2] = 123
console.log(obj) // {Symbol(111): "hello world", Symbol(222): 123}
console.log(obj[sym1]) // "hello world"
console.log(obj[sym2]) // 123
```
### 2-6 原型和原型链
题目
- 如何准确判断一个变量是数组类型
- 写一个原型链继承的例子
- 描述 `new` 一个对象的过程
- zepto 或其他框架源码中如何使用原型链
知识点
- 构造函数
- 构造函数 - 扩展
- 原型规则和示例
- 原型链
- `instanceof`
构造函数
```js
function Foo(name, age) {
this.name = name
this.age = age
this.class = 'class__1'
// return this // 默认有这一行
}
let f = new Foo('negrochn', 18)
// let f2 = new Foo('lexiaodai', 17) // 创建多个对象
```
构造函数 - 扩展
```js
let a = {} // 其实是 let a = new Object() 的语法糖
let b = [] // 其实是 let b = new Array() 的语法糖
function Foo() {} // 其实是 let Foo = new Function()
// 使用 instanceof 判断一个函数是否是一个变量的构造函数
console.log(b instanceof Array) // true
```
### 2-7 原型和原型链 - 5 条原型规则
5 条原型规则
1. 所有的引用类型(数组、对象、函数),都具有对象特性,即可自由扩展属性(除了 `null` 以外)
2. 所有的引用类型(数组、对象、函数),都有一个 `__proto__`(隐式原型)属性,属性值是一个普通的对象
3. 所有的函数,都有一个 `prototype`(显式原型)属性,属性值也是一个普通的对象
4. 所有的引用类型(数组、对象、函数),`__proto__` 属性值指向它的构造函数的 `prototype` 属性值
5. 当试图得到一个对象的某个属性时,如果这个对象本身没有这个属性,那么会去它的 `__proto__`(即它的构造函数的 `prototype`)中寻找
```js
// 原则 1
let obj = {}
obj.a = 100
let arr = []
arr.a = 100
function fn() {}
fn.a = 100
// 原则 2
console.log(obj.__proto__)
console.log(arr.__proto__)
console.log(fn.__proto__)
// 原则 3
console.log(fn.prototype)
// 原则 4
console.log(obj.__proto__ === Object.prototype) // true
```
```js
// 构造函数
function Foo(name) {
this.name = name
}
Foo.prototype.alertName = function() {
alert(this.name)
}
// 创建实例
let f = new Foo('negrochn')
f.printName = function() {
console.log(this.name)
}
// 测试
f.printName()
f.alertName() // 原则 5
```
### 2-8 原型和原型链 - 5 条原型规则 补充 2 点
```js
for (let key in f) {
// 高级浏览器已经在 for in 中屏蔽了来自原型的属性
// 但是这里建议大家还是加上这个判断,保证程序的健壮性
if (f.hasOwnProperty(key)) {
console.log(key)
}
}
```
### 2-9 原型和原型链 - 原型链
```js
// 构造函数
function Foo(name) {
this.name = name
}
Foo.prototype.alertName = function() {
alert(this.name)
}
// 创建实例
let f = new Foo('negrochn')
f.printName = function() {
console.log(this.name)
}
// 测试
f.printName()
f.alertName()
f.toString() // 要去 f.__proto__.__proto__ 中查找
```

### 2-10 原型和原型链 - instanceof
```js
// instanceof 用于判断引用类型属于哪个构造函数的方法
console.log(f instanceof Foo) // true, f 的 __proto__ 一层一层往上,能否对应到 Foo.prototype
console.log(f instanceof Object) // true
```
### 2-11 原型和原型链 - 解答 1
如何准确判断一个变量是数组类型
答:使用 `instanceof Array`
```js
let arr = []
console.log(arr instanceof Array) // true
console.log(typeof arr) // "object" ,typeof 是无法判断是否是数组的
```
写一个原型链继承的例子
```js
// 动物
function Animal() {
this.eat = function() {
console.log('animal eat')
}
}
// 狗
function Dog() {
this.bark = function() {
console.log('dog bark')
}
}
Dog.prototype = new Animal()
// 哈士奇
let hashiqi = new Dog()
// 接下来代码演示时,会推荐更加贴近实战的原型继承示例
```
描述 `new` 一个对象的过程
答:
1. 创建一个新对象
2. `this` 指向这个新对象
3. 执行代码,即对 `this` 赋值
4. 返回 `this`
```js
function Foo(name, age) {
this.name = name
this.age = age
this.class = 'class__1'
// return this // 默认有这一行
}
let f = new Foo('negrochn', 18)
```
zepto 或其他框架源码中如何使用原型链
答:
- 阅读源码是高效提高技巧的方式
- 但不能“埋头苦钻”,有技巧在其中
- 慕课网搜索“zepto 设计和源码分析”
### 2-12 原型和原型链 - 解答 2
写一个封装 DOM 查询的例子
```js
function Elem(id) {
this.elem = document.getElementById(id)
}
Elem.prototype.html = function(val) {
let elem = this.elem
if (val) {
elem.innerHTML = val
return this // 为了链式操作
} else {
return elem.innerHTML
}
}
Elem.prototype.on = function(type, fn) {
let elem = this.elem
elem.addEventListener(type, fn)
return this // 为了链式操作
}
let div1 = new Elem('div1')
div1.html('<p>Hello World</p>').on('click', function() {
alert('clicked')
})
```
### 2-13 原型和原型链 - 代码演示
无
## 第3章 JS 基础知识(中)
### 3-1 作用域和闭包 - 执行上下文
题目
- 说一下对变量提升的理解
- 说明 `this` 几种不同的使用场景
- 创建 10 个 `<a>` 标签,点击的时候弹出对应的序号
- 如何理解作用域
- 实际开发中闭包的应用
知识点
- 执行上下文
- `this`
- 作用域
- 作用域链
- 闭包
执行上下文
- 范围:一段 `<script>` 或者一个函数
- 全局上下文:执行前,会先把变量定义、函数声明拿出来(注意函数声明和函数表达式的区别)
- 函数上下文:执行前,先把变量定义、函数声明、`this` 、`arguments` 拿出来
```js
console.log(a) // undefined
var a = 100
fn('negrochn') // "negrochn" 20
function fn(name) {
age = 20
console.log(name, age)
var age
}
```
### 3-2 作用域和闭包 - 执行上下文 代码演示
无
### 3-3 作用域和闭包 - this
`this` ,要在执行时才能确认值,定义时无法确认
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- `call` 、`apply` 、`bind`
```js
var a = {
name: 'A',
fn: function() {
console.log(this.name)
}
}
a.fn() // this === a
a.fn.call({ name: 'B' }) // this 作为 { name: 'B' }
var fn1 = a.fn
fn1() // this === window
```
### 3-4 作用域和闭包 - this 代码演示
```js
// 作为构造函数执行
function Foo(name) {
this.name = name
}
let f = new Foo('negrochn')
f.name // "negrochn"
```
```js
// 作为对象属性执行
let obj = {
name: 'A',
printName: function() {
console.log(this.name)
}
}
obj.printName() // "A"
```
```js
// 作为普通函数执行
function fn() {
console.log(this)
}
fn() // window
```
```js
// call 、apply 、bind
function fn1(name, age) {
console.log(name)
console.log(this)
}
fn1.call({ x: 1 }, 'negrochn', 20) // "negrochn" { x: 1 }
fn1.apply({ x: 200 }, ['negrochn', 20]) // "negrochn" { x: 200 }
let fn2 = function(name, age) {
console.log(name)
console.log(this)
}.bind({ x: 300 })
fn2('negrochn', 20) // "negrochn" { x: 300 }
```
### 3-5 作用域和闭包 - 作用域
作用域
- 没有块级作用域
- 只有函数和全局作用域
```js
// 无块级作用域
if (true) {
var name = 'negrochn'
}
console.log(name) // "negrochn"
// 只有函数和全局作用域
var a = 100
function fn() {
var a = 200
console.log('fn', a)
}
console.log('global', a) // "global" 100
fn() // "fn" 200
```
作用域链
```js
var a = 100
function fn() {
var b = 200
// 当前作用域没有定义的变量,即“自由变量”
console.log(a)
console.log(b)
}
fn()
```
```js
var a = 100
function f1() {
var b = 200
function f2() {
var c = 300
console.log(a) // a 是自由变量
console.log(b) // b 是自由变量
console.log(c)
}
f2()
}
f1()
```
### 3-6 作用域和闭包 - 作用域 代码演示
无
### 3-7 补充 - ES6 块级作用域
JS 没有块级作用域,ES6 有块级作用域
### 3-8 作用域和闭包 - 闭包
闭包
```js
function f1() {
var a = 100
// 返回一个函数(函数作为返回值)
return function() {
console.log(a)
}
}
// f1 得到一个函数
var f = f1()
var a = 200
f() // 100
```
闭包的使用场景
- 函数作为返回值
- 函数作为参数传递
### 3-9 作用域和闭包 - 闭包 代码演示
```js
// 闭包 1 ,函数作为返回值
function f1() {
var a = 100
return function() {
console.log(a) // a 是自由变量,向父级作用域去寻找,函数定义时的父作用域
}
}
var f = f1()
var a = 200
f() // 100
```
```js
// 闭包 2 ,函数作为参数传递
function f1() {
var a = 100
return function() {
console.log(a)
}
}
var f = f1()
function f2(fn) {
var a = 200
fn()
}
f2(f) // 100
```
### 3-10 作用域和闭包 - 解题
说一下对变量提升的理解
- 变量定义
- 函数声明(注意和函数表达式的区别)
说明 `this` 几种不同的使用场景
- 作为构造函数执行
- 作为对象属性执行
- 作为普通函数执行
- `call` 、`apply` 、`bind`
创建 10 个 `<a>` 标签,点击的时候弹出对应的序号
```js
// 这是一个错误的写法
var i, a
for(i = 0; i < 10; i++) {
a = document.createElement('a')
a.innerHTML = i + '<br>'
a.addEventListener('click', function(e) {
e.preventDefault()
alert(i) // 自由变量,要去父作用域获取值
})
document.body.appendChild(a)
}
```
```js
// 这是正确的写法
var i
for(i = 0; i < 10; i++) {
(function(i) {
var a = document.createElement('a')
a.innerHTML = i + '<br>'
a.addEventListener('click', function(e) {
e.preventDefault()
alert(i)
})
document.body.appendChild(a)
})(i)
}
```
如果理解作用域
- 自由变量
- 作用域链,即自由变量的查找
- 闭包的两个场景
实际开发中闭包的应用
```js
// 闭包实际应用中主要用于封装变量,收敛权限
function isFirstLoad() {
var _list = []
return function(id) {
if (_list.indexOf(id) >= 0) {
return false
} else {
_list.push(id)
return true
}
}
}
// 使用
var firstLoad = isFirstLoad()
console.log(firstLoad(10)) // true
console.log(firstLoad(10)) // false
console.log(firstLoad(20)) // true
// 你在 isFirstLoad 函数外,根本不可能修改掉 _list 的值
```
### 3-11 作用域和闭包 - 解题 代码演示
无
## 第4章 JS 基础知识(下)
### 4-1 异步和单线程 - 什么是异步
题目
- 同步和异步的区别是什么?分别举一个同步和异步的例子
- 一个关于 setTimeout 的笔试题
- 前端使用异步的场景有哪些?
知识点
- 什么是异步(对比同步)
- 前端使用异步的场景
- 异步和单线程
什么是异步
- 同步阻塞后续代码执行
- 异步不会阻塞程序的运行
```js
console.log(100)
setTimeout(function() {
console.log(200)
}, 1000)
console.log(300)
```
对比同步
```js
console.log(100)
alert(200) // 1 秒之后手动点击确认
console.log(300)
```
何时需要异步
- 在可能发生等待的情况
- 等待过程中不能像 `alert` 一样阻塞程序运行
- 因此,所有的“等待的情况”都需要异步
前端使用异步的场景
- 定时任务,`setTimeout` 、`setInterval`
- 网络请求,Ajax 请求、动态 `<img>` 加载
- 事件绑定
```js
// Ajax 请求
console.log('start')
$.get('./data1.json', function(data1) {
console.log(data1)
})
console.log('end')
```
```js
// 动态 <img> 加载
console.log('start')
var img = document.createElement('img')
img.onload = function() {
console.log('loaded')
}
img.src = '/xxx.png'
console.log('end')
```
```js
// 事件绑定
console.log('start')
document.getElementById('btn1').addEventListener('click', function() {
alert('clicked')
})
console.log('end')
```
### 4-2 异步和单线程 - 什么是异步 代码演示
无
### 4-3 异步和单线程 - 单线程
```js
console.log(100)
setTimeout(function() {
console.log(200)
})
console.log(300)
```
1. 执行第 1 行,打印 100
2. 执行 `setTimeout` 后,传入 `setTimeout` 的函数会被暂存起来,不会立即执行(单线程的特点,不能同时干两件事)
3. 执行第 5 行,打印 300
4. 待所有程序执行完,处于空闲状态时,会立马看有没有暂存起来要执行的
5. 发现暂存起来的 setTimeout 中的函数,无须等待时间,就立即过来执行
单线程
- JS 是单线程语言,即一次只能干一件事,如果同时有两件事,另一件就先上一边排队去,我先干完这件事再说,如果没有异步,那就会出现阻塞现象
- 由于 JS 是单线程,在代码执行的时候又不能因为执行需要等待的代码而造成阻塞,因此 JS 会首先将无需等待的(同步)代码执行完成后,再来处理异步代码,如果达到异步代码的执行条件的话,就会执行
### 4-4 异步和单线程 - 解答
同步和异步的区别是什么?分别举一个同步和异步的例子
- 同步会阻塞代码执行,而异步不会
- `alert` 是同步,`setTimeout` 是异步
一个关于 setTimeout 的笔试题
```js
console.log(1)
setTimeout(function() {
console.log(2)
}, 0)
console.log(3)
setTimeout(function() {
console.log(4)
}, 1000)
console.log(5)
// 1
// 3
// 5
// 2
// 4 ,一秒后
```
前端使用异步的场景有哪些?
- 定时任务,`setTimeout` 、`setInterval`
- 网络请求,Ajax 请求、动态 `<img>` 加载
- 事件绑定
重点总结
- 异步和同步的区别
- 异步和单线程的关系
- 异步在前端的使用场景
### 4-5 其他知识点 - Date 和 Math
题目
- 获取 `2020-02-24` 格式的日期
- 获取随机数,要求长度一致的字符串格式
- 写一个能遍历对象和数组的通用 `forEach` 函数
知识点
- Date
- Math
- 数组 API
- 对象 API
Date
```js
Date.now() // 获取当前时间毫秒数
var dt = new Date()
dt.getTime() // 获取毫秒数
dt.getFullYear() // 年
dt.getMonth() // 月(0-11)
dt.getDate() // 日(1-31)
dt.getHours() // 时(0-23)
dt.getMinutes() // 分(0-59)
dt.getSeconds() // 秒(0-59)
```
Math
```js
Math.random() // 获取随机数
```
### 4-6 其他知识点 - 数组和对象的 API
数组 API
- `forEach` ,遍历所有元素
- `every` ,判断所有元素是否都符合条件
- `some` ,判断是否有至少一个元素符合条件
- `sort` ,排序
- `map` ,对元素重新组装,生成新数组
- `filter` ,过滤符合条件的元素
```js
// forEach
var arr = [1, 2, 3]
arr.forEach(function(item, index) {
// 遍历数组的所有元素
console.log(index, item)
})
// 0 1
// 1 2
// 2 3
```
```js
// every
var arr = [1, 2, 3]
var result = arr.every(function(item, index) {
// 用来判断所有的数组元素,都满足条件
if (item < 4) {
return true
}
})
console.log(result) // true
```
```js
// some
var arr = [1, 2, 3]
var result = arr.some(function(item, index) {
// 用来判断只要有一个数组元素满足条件
if (item < 2) {
return true
}
})
console.log(result) // true
```
```js
// sort
var arr = [1, 4, 2, 3, 5]
var result = arr.sort(function(a, b) {
// 从小到大排序
return a - b // 从大到小排序 return b - a
})
console.log(result) // [1, 2, 3, 4, 5]
```
```js
// map
var arr = [1, 2, 3]
var result = arr.map(function(item, index) {
// 将元素重新组装并返回
return '<b>' + item + '</b>'
})
console.log(result) // ["<b>1</b>", "<b>2</b>", "<b>3</b>"]
```
```js
// filter
var arr = [1, 2, 3]
var result = arr.filter(function(item, index) {
// 通过某一个条件过滤数组
if (item >= 2) {
return true
}
})
console.log(result) // [2, 3]
```
对象 API
```js
var obj = {
x: 100,
y: 200,
z: 300
}
var key
for (key in obj) {
// 注意这里的 hasOwnProperty ,在将原型链的时候讲过了
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key])
}
}
// x 100
// y 200
// z 300
```
### 4-7 其他知识点 - 知识点 代码演示
无
### 4-8 其他知识点 - 解答
获取 `2020-02-24` 格式的日期
```js
function formatDate(dt) {
if (!dt) {
dt = new Date()
}
var year = dt.getFullYear()
var month = dt.getMonth() + 1
var date = dt.getDate()
return year + '-' + month.toString().padStart(2, '0') + '-' + date.toString().padStart(2, '0')
}
formatDate(new Date()) // "2021-02-24"
```
获取随机数,要求长度一致的字符串格式
```js
var random = Math.random()
random = random + '0000000000'
random = random.slice(0, 10)
console.log(random)
```
写一个能遍历对象和数组的通用 `forEach` 函数
```js
function forEach(obj, fn) {
var key
if (obj instanceof Array) {
obj.forEach(function(item, index) {
fn(index, item)
})
} else {
for (key in obj) {
fn(key, obj[key])
}
}
}
var arr = [1, 2, 3]
forEach(arr, function(key, value) {
console.log(key, value)
})
// 0 1
// 1 2
// 2 3
var obj = {
x: 100,
y: 200
}
forEach(obj, function(key, value) {
console.log(key, value)
})
// x 100
// y 200
```
重点总结
- Date
- Math
- 数组 API
- 对象 API
### 4-9 其他知识点 - 代码演示
## 第5章 JS Web API(上)
### 5-1 从基础知识到 JS Web API
回顾 JS 基础知识
- 变量类型和计算
- 原型和原型链
- 闭包和作用域
- 异步和单线程
- 其他(如 Date 、Math 、各种常用 API)
- 特点:表面看起来并不能用于工作中开发代码
- 内置函数:Object 、Array 、Boolean 、String ...
- 内置对象:Math 、JSON ...
- 我们连在网页弹出一句 `Hello World` 都不能实现
JS Web API
- JS 基础知识:ECMA262 标准
- JS Web API:W3C 标准
W3C 标准中关于 JS 的规定有
- DOM 操作
- BOM 操作
- 事件绑定
- Ajax 请求(包括 http 协议)
- 存储
页面弹框是 `window.alert(123)` ,浏览器需要做
- 定义一个 `window` 全局变量,对象类型
- 给他定义一个 `alert` 属性,属性值是一个函数
获取元素 `document.getElementById(id)` ,浏览器需要
- 定义一个 `document` 全局变量,对象类型
- 给它定义一个 `getElementById` 的属性,属性值是一个函数
但是 W3C 标准没有规定任何 JS 基础相关的东西
- 不管什么变量类型、原型、作用域和异步
- 只管定义用于浏览器中 JS 操作页面的 API 和全局变量
全面考虑,JS 内置的全局函数和对象有哪些?
- 之前讲过的 Object 、Array 、Boolean 、String 、Math 、JSON 等
- 刚刚提到的 window 、document
- 接下来还有继续讲到的所有未定义的全局变量,如 `navigator.userAgent`
总结
常说的 JS(浏览器执行的 JS)包含两部分
- JS 基础知识(ECMA262 标准)
- JS Web API(W3C 标准)
### 5-2 DOM 本质
DOM ,全称 Document Object Model
题目
- DOM 是哪种基本的数据结构?
- DOM 操作的常用 API 有哪些?
- DOM 节点的 Attribute 和 Property 有何区别?
知识点
- DOM 本质
- DOM 节点操作
- DOM 结构操作
DOM 本质
```xml
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
<other>
<a></a>
<b></b>
</other>
</note>
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<p>this is p</p>
</div>
</body>
</html>
```
DOM 本质:浏览器拿到 HTML 代码后,DOM 把 HTML 代码结构化成浏览器可识别以及 JS 可识别的东西。
HTML 代码就是一个字符串,但是浏览器已经把字符串结构化成树形结构了。
### 5-3 DOM 节点操作
DOM 可以理解为:浏览器把拿到的 HTML 代码,结构化成一个浏览器能识别并且 JS 可操作的一个模型而已。
DOM 节点操作
- 获取 DOM 节点
- Property ,JS 对象属性
- Attribute ,HTML 标签属性
获取 DOM 节点
```js
var div1 = document.getElementById('div1') // 元素
var divList = document.getElementsByTagName('div') // 集合
console.log(divList.length)
console.log(divList[0])
var containerList = document.getElementsByClassName('container') // 集合
var pList = document.querySelectorAll('p') // 集合
```
Property ,JS 对象属性
```js
var pList = document.querySelectorAll('p')
var p = pList[0]
console.log(p.style.width) // 获取样式
p.style.width = '100px' // 修改样式
console.log(p.className) // 获取 class
p.className = 'p1' // 修改 class
// 获取 nodeName 和 nodeType
console.log(p.nodeName) // "P"
console.log(p.nodeType) // 1
```
Attribute ,HTML 标签属性
```js
var pList = document.querySelectorAll('p')
var p = pList[0]
p.getAttribute('data-name')
p.setAttribute('data-name', 'imooc')
p.getAttribute('style')
p.setAttribute('style', 'font-size: 30px;')
```
### 5-4 DOM 节点操作 - 代码演示
无
### 5-5 DOM 结构操作
DOM 结构操作
- 新增节点
- 获取父元素
- 获取子元素
- 删除节点
新增节点
```js
var div1 = document.getElementById('div1')
// 添加新节点
var p = document.createElement('p')
p.innerHTML = 'new p'
div1.appendChild(p) // 添加新创建的元素
// 移动已有节点
var p4 = document.getElementById('p4')
div1.appendChild(p4)
```
获取父元素和子元素
```js
var div1 = document.getElementById('div1')
var parent = div1.parentNode
var children = div1.childNodes
```
删除节点
```js
div1.removeChild(children[0])
```
### 5-6 DOM 结构操作 - 代码演示
无
### 5-7 DOM 结构操作 - 解答
DOM 是哪种基本的数据结构?
答:树
DOM 操作的常用 API 有哪些?
答:
- 获取 DOM 节点,以及节点的 Property 和 Attribute
- 获取父节点,获取子节点
- 新增节点,删除节点
DOM 节点的 Attribute 和 Property 有何区别?
答:
- Property 只是一个 JS 对象的属性的修改
- Attribute 是对 HTML 标签属性的修改
重点总结
- DOM 本质
- DOM 节点操作
- DOM 结构操作
### 5-8 BOM 操作
题目
- 如何检测浏览器的类型
- 拆解 URL 的各部分
知识点
- `navigator`
- `srceen`
- `location`
- `history`
navigator & screen
```js
// navigator
var ua = navigator.userAgent
var isChrome = ua.indexOf('Chrome')
console.log(isChrome) // 81
// screen
console.log(screen.width) // 1920
console.log(screen.height) // 1080
```
location & history
```js
// location ,以 http://localhost:8080/login?username=negrochn&password=123456#mid=1 为例
console.log(location.href) // http://localhost:8080/login?username=negrochn&password=123456#mid=1
console.log(location.protocol) // http:
console.log(location.host) // localhost:8080
console.log(location.hostname) // localhost
console.log(location.port) // 8080
console.log(location.pathname) // /login
console.log(location.search) // ?username=negrochn&password=123456
console.log(location.hash) // #mid=1
// history
history.back()
history.forward()
```
### 5-9 BOM 操作 - 代码演示
无
## 第6章 JS Web API(下)
### 6-1 事件
题目
- 编写一个通用的事件监听函数
- 描述事件冒泡流程
- 对一个无限下拉加载图片的页面,如何给每个图片绑定事件
知识点
- 通用事件绑定
- 事件冒泡
- 代理
通用事件绑定
```js
var btn = document.getElementById('btn1')
btn.addEventListener('click', function(e) {
console.log('clicked')
})
function bindEvent(elem, type, fn) {
elem.addEventListener(type, fn)
}
var a = document.getElementById('link1')
bindEvent(a, 'click', function(e) {
e.preventDefault() // 阻止默认行为
alert('clicked')
})
```
关于 IE 低版本的兼容性
- IE 低版本使用 `attachEvent` 绑定事件,和 W3C 标准不一样
- IE 低版本使用量已非常少,很多网站都早已不支持
- 建议对 IE 低版本的兼容性:了解即可,无需深究
- 如果遇到对 IE 低版本要求苛刻的面试,果断放弃
事件冒泡
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件冒泡</title>
</head>
<body>
<div id="div1">
<p id="p1">激活</p>
<p id="p2">取消</p>
<p id="p3">取消</p>
<p id="p4">取消</p>
</div>
<div id="div2">
<p id="p5">取消</p>
<p id="p6">取消</p>
</div>
<script>
function bindEvent(elem, type, fn) {
elem.addEventListener(type, fn)
}
var p1 = document.getElementById('p1')
var body = document.body
bindEvent(p1, 'click', function(e) {
e.stopPropagation()
alert('激活')
})
bindEvent(body, 'click', function(e) {
alert('取消')
})
</script>
</body>
</html>
```
代理
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件冒泡</title>
</head>
<body>
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
<!-- 会随时新增更多 a 标签 -->
</div>
<script>
var div1 = document.getElementById('div1')
div1.addEventListener('click', function(e) {
var target = e.target
if (target.nodeName === 'A') {
alert(target.innerHTML)
}
})
</script>
</body>
</html>
```
完善通用绑定事件的函数
```js
function bindEvent(elem, type, selector, fn) {
if (fn == null) {
fn = selector
selector = null
}
elem.addEventListener(type, function(e) {
var target
if (selector) {
target = e.target
if (target.matches(selector)) {
fn.call(target, e)
}
} else {
fn(e)
}
})
}
// 使用代理
var div1 = document.getElementById('div1')
bindEvent(div1, 'click', 'a', function(e) {
console.log(this.innerHTML)
})
// 不使用代理
var a = document.getElementById('a1')
bindEvent(div1, 'click', function(e) {
console.log(a.innerHTML)
})
```
代理的好处
- 代码简洁
- 减少浏览器内存占用
### 6-2 事件 - 代码演示
无
### 6-3 事件 - 解答
编写一个通用的事件监听函数
答:
```js
function bindEvent(elem, type, selector, fn) {
if (fn == null) {
fn = selector
selector = null
}
elem.addEventListener(type, function(e) {
let target
if (selector) {
target = e.target
if (target.matches(selector)) {
fn.call(target, e)
}
} else {
fn(e)
}
})
}
```
描述事件冒泡流程
答:
1. DOM 树形结构
2. 事件冒泡
3. 阻止冒泡
4. 冒泡的应用
对一个无限下拉加载图片的页面,如何给每个图片绑定事件
答:
- 使用代理
- 代理的两个优点(代码简洁、减少浏览器内存占用)
重点总结
- 通用事件绑定
- 事件冒泡
- 事件代理
### 6-4 Ajax - XMLHttpRequest
题目
- 手写一个 Ajax ,不依赖第三方库
- 跨域的几种实现方式
知识点
- XMLHttpRequest
- 状态码说明
- 跨域
XMLHttpRequest
```js
var xhr = new XMLHttpRequest()
xhr.open('GET', '/api', false)
xhr.onreadystatechange = function() {
// 这里的函数异步执行
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText)
}
}
}
xhr.send(null)
```
IE 兼容性问题
- IE 低版本使用 ActiveXObject ,和 W3C 标准不一样
- IE 低版本使用量已非常少,很多网站都早已不支持
- 建议对 IE 低版本的兼容性:了解即可,无需深究
- 如果遇到对 IE 低版本要求苛刻的面试,果断放弃
readyState
- 0 - 未初始化,还没有调用 send() 方法
- 1 - 载入,已调用 send() 方法,正在发送请求
- 2 - 载入完成,send() 方法执行完成,已经接收到全部响应内容
- 3 - 交互,正在解析响应内容
- 4 - 完成,响应内容解析完成,可以在客户端调用了
status
- 1XX - 信息,服务器收到请求,需要请求者继续执行操作
- 2XX - 成功,操作被成功接收并处理
- 3XX - 重定向,需要进一步的操作以完成请求
- 4XX - 客户端错误,请求包含语法错误或无法完成请求
- 5XX - 服务器错误,服务器在处理请求的过程中发生了错误
| 状态码 | 英文描述 | 中文描述 |
| ------ | --------------------- | ------------------------------------------------------------ |
| 100 | Continue | 继续。客户端应继续其请求。 |
| 200 | OK | 请求成功。 |
| 204 | No Content | 无内容。服务器成功处理,但未返回内容。 |
| 206 | Partial Content | 部分内容。服务器成功处理了部分 GET 请求。 |
| 301 | Moved Permanently | 永久移动。请求的资源已被永久的移动到新 URI ,返回信息会包括新的 URI ,浏览器会自动定向到新 URI 。 |
| 302 | Found | 临时移动。客户端应继续使用原有 URI 。 |
| 304 | Not Modified | 未修改。所请求的资源未修改,服务器返回此状态码时,不会返回任何资源。 |
| 307 | Temporary Redirect | 临时重定向。使用 GET 请求重定向。 |
| 400 | Bad Request | 客户端请求的语法错误,服务器无法理解。 |
| 401 | Unauthorized | 请求要求用户的身份认证。 |
| 403 | Forbidden | 服务器理解请求客户端的请求,但是拒绝执行此请求。 |
| 404 | Not Found | 服务器无法根据客户端的请求找到资源(网页)。 |
| 500 | Internal Server Error | 服务器内部错误,无法完成请求。 |
| 502 | Bad Gateway | 作为网关或代理工作的服务器尝试执行请求时,从远程服务器接收到了一个无效的响应。 |
| 503 | Service Unavailable | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。 |
### 6-5 Ajax - 跨域
什么是跨域
- 浏览器有同源策略,不允许 Ajax 访问其他域接口
- 跨域条件:协议、域名、端口,有一个不同就算跨域
- 有三个标签允许跨域加载资源
- `<img src=xxx>` ,用于打点统计,统计网站可能是其他域
- `<link href=xxx>` ,可以使用 CDN
- `<script src=xxx>` ,可以使用 CDN ,用于 JSONP
跨域注意事项
- 所有的跨域请求都必须经过信息提供方允许
- 如果未经允许即可获取,那是浏览器同源策略出现漏洞
JSONP 实现原理
- 加载 https://coding.imooc.com/lesson/115.html#mid=5387
- 不一定服务器端真正有一个 115.html 文件
- 服务器可以根据请求,动态生成一个文件返回
- 同理,`<script src="http://coding.imooc.com/api.js">`
- 例如你的网站要跨域访问慕课网的一个接口
- 慕课给你一个地址 http://coding.imooc.com/api.js
- 返回内容格式如 `callback({ x: 100, y: 200 })`(可动态生成)
```html
<script>
window.callback = function(data) {
// 这是我们跨域得到的信息
console.log(data)
}
</script>
<script src="http://coding.imooc.com/api.js"></script>
<!-- 以上将返回 callback({ x: 100, y: 200 }) -->
```
服务器设置 http header
- 另外一个解决跨域的简洁方法,需要服务器来做
- 但是作为交互方,我们必须知道这个方法
- 是将来解决跨域问题的一个趋势
```js
// 注意:不同后端语言的写法可能不一样
// 第二个参数填写允许跨域的域名称,不建议直接写 *
response.setHeader('Access-Control-Allow-Origin', 'http://a.com, http://b.com')
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With')
response.setHeader('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
// 接收跨域的 Cookie
response.setHeader('Access-Control-Allow-Credentials', 'true')
```
手写一个 Ajax ,不依赖第三方库
```js
var xhr = new XMLHttpRequest()
xhr.open('GET', '/api', false)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert(xhr.responseText)
}
}
}
xhr.send(null)
```
跨域的几种实现方式
- JSONP
- 服务器端设置 http header
重点总结
- XMLHttpRequest
- 状态码
- 跨域
### 6-6 存储
题目
- 请描述一下 Cookie 、sessionStorage 和 localStorage 的区别?
知识点
- Cookie
- sessionStorage 和 localStorage
Cookie
- 本身用于客户端和服务器端通信
- 但是它有本地存储的功能,于是就被“借用”
- 使用 `document.cookie` 获取和修改
Cookie 用于存储的缺点
- 存储量太小,只有 4KB
- 所有 http 请求都带着,会影响获取资源的效率
- API 简单,需要封装才能用 `document.cookie`
localStorage 和 sessionStorage
- HTML5 专门为存储而设计,最大容量 5MB
- API 简单易用,`getItem(key)` 、`setItem(key, value)`
- iOS Safari 隐藏模式下,localStorage.getItem 会报错,建议统一使用 try-catch 封装
请描述一下 Cookie 、sessionStorage 和 localStorage 的区别?
- 容量
- 是否携带到请求中
- API 易用性
## 第7章 开发环境
### 7-1 介绍
关于开发环境
- 面试官想通过开发环境了解面试者的经验
- 开发环境,最能体现工作产出的效率
- 会以聊天的形式为主,而不是出具体的问题
开发环境包含
- IDE(写代码的效率)
- Git(代码版本管理,多人协作开发)
- JS 模块化
- 打包工具
- 上线回滚的流程
### 7-2 IDE
IDE
- WebStorm
- Sublime
- VS Code(推荐)
- Atom
### 7-3 Git - 常用命令
Git
- 正式项目都需要代码版本管理
- 大型项目需要多人协作开发
- Git 和 Linux 是一个作者
- 网络 Git 服务器,如 github
- 一般公司代码非开源,都有自己的 Git 服务器
- 搭建 Git 服务器无需你了解太多
- Git 的基本操作必须很熟练
常用 Git 命令
- `git add .`
- `git checkout xxx` ,还原文件
- `git commit -m 'xxx'` ,提交到本地仓库
- `git push origin master` ,提交到远程仓库
- `git pull origin master` ,下载远程仓库的文件
- `git branch` ,创建分支
- `git checkout -b xxx`/`git checkout xxx` ,新建一个分支/切换到另一个分支
- `git merge xxx` ,把之前的分支拷贝到这里
### 7-4 Git - 代码演示
无
### 7-5 Git - 代码演示 多人协作
多人开发
- 为了编写属于自己的功能,可以创建自己的分支,而不要在主分支上改动,最后进行合并即可
步骤
1. `git checkout -b dev` ,创建一个 dev 分支
2. `vi a.js`修改内容(vi 属于 Linux 命令,`git status` 查看是否被修改,`git diff` 查看修改的内容)
3. `git add .`
4. `git commit -m 'update dev'`
5. `git push origin dev` ,提交到远程仓库的 dev 分支
6. 半个月之后,合并到 master 分支
7. `git checkout master` ,切换到 master 分支
8. `git pull origin master` ,下载远程仓库的 master 分支的文件
9. `git merge dev` ,把 dev 分支的修改内容拷贝到 master 分支
10. `git push origin master` ,提交到远程仓库的 master 分支
附加命令
- `cat 文件名`,查看文件内容
- `git diff` ,查看修改的内容
- `git branch` ,查看分支和当前在哪条分支上
- `git status` ,查看文件是否被修改的状态
- `vi 文件` ,新建文件并打开文件
- `esc + :wq` ,退出并保存文件
### 7-6 模块化 - AMD
不使用模块化
```js
// util.js
function getFormatDate(date, type) {
// type === 1 返回 2021-03-06
// type === 2 返回 2021年3月6日
// ...
}
```
```js
// a-util.js
function aGetFormatDate(date) {
// 要求返回 2021年3月6日格式
return getFormatDate(date, 2)
}
```
```js
// a.js
var dt = new Date()
console.log(aGetFormatDate(dt))
```
```html
<script src="util.js"></script>
<script src="a-util.js"></script>
<script src="a.js"></script>
<!-- 1. 这些代码中的函数必须是全局变量,才能暴露给使用方。全局变量污染。 -->
<!-- 2. a.js 知道要引用 a-util.js ,但是他知道还需要依赖于 util.js 吗 -->
```
AMD
- require.js
- 全局 `define` 函数
- 全局 `require` 函数
- 依赖 JS 会自动、异步加载
使用 require.js
```js
// util.js
define(function() {
return {
getFormatDate: function(date, type) {
if (type === 1) {
return '2021-03-06'
} else if (type === 2) {
return '2021年3月6日'
}
}
}
})
```
```js
// a-util.js
define(['./util.js'], function(util) {
return {
aGetFormatDate: function(date) {
return util.getFormatDate(date, 2)
}
}
})
```
```js
// a.js
define(['./a-util.js'], function(aUtil) {
return {
printDate: function(date) {
console.log(aUtil.aGetFormatDate(date))
}
}
})
```
```js
// main.js
require(['./a.js'], function(a) {
var date = new Date()
a.printDate(date)
})
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AMD</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/require.js/2.3.6/require.min.js" data-main="./main.js"></script>
</body>
</html>
```
### 7-7 模块化 - AMD 代码演示
无
### 7-8 模块化 - CommonJS
CommonJS
- Node.js 模块化规范,现在被前端大量使用,原因:
- 前端开发依赖的插件和库,都可以从 npm 中获取
- 构建工具的高度自动化,使得使用 npm 的成本非常低
- CommonJS 不会异步加载 JS ,而是同步一次性加载出来
使用 CommonJS
```js
// util.js
module.exports = {
getFormatDate: function(date, type) {
if (type === 1) {
return '2021-03-06'
} else if (type === 2) {
return '2021年3月6日'
}
}
}
```
```js
// a-util.js
var util = require('util.js')
module.exports = {
aGetFormatDate: function(date) {
return util.getFormatDate(date, 2)
}
}
```
AMD 和 CommonJS 的使用场景
- 需要异步加载 JS ,使用 AMD
- 使用了 npm 之后建议使用 CommonJS
重点总结
- AMD
- CommonJS
- 两者的区别
### 7-9 构建工具 - 安装 Node.js
### 7-10 构建工具 - 安装 Webpack
### 7-11 构建工具 - 配置 Webpack
### 7-12 构建工具 - 使用 jQuery
### 7-13 构建工具 - 压缩 JS
### 7-14 上线回滚 - 上线回滚流程
### 7-15 上线回滚 - Linux 基础命令
## 8章 运行环境
### 8-1 介绍
运行环境
- 浏览器就可以通过访问链接来得到页面的内容
- 通过绘制和渲染,显示出页面的最终的样子
- 整个过程中,我们需要考虑什么问题?
知识点
- 页面加载过程
- 性能优化
- 安全性
### 8-2 页面加载 - 渲染过程
题目
- 从输入 URL 到得到 HTML 的详细过程
- `window.onload` 和 `DOMContentLoaded` 的区别
知识点
- 加载资源的形式
- 加载一个资源的过程
- 浏览器渲染页面的过程
加载资源的形式
- 输入 URL(或跳转页面)加载 HTML
- 加载 HTML 中的静态资源
加载一个资源的过程
- 浏览器根据 DNS 服务器得到域名的 IP 地址
- 向这个 IP 的机器发送 HTTP 请求
- 服务器收到、处理并返回 HTTP 请求
- 浏览器得到返回内容
浏览器渲染页面的过程
- 根据 HTML 结构生成 DOM Tree
- 根据 CSS 生成 CSSOM
- 将 DOM 和 CSSOM 整合形成 Render Tree
- 根据 Render Tree 开始渲染和展示
- 遇到 `<script>` 时,会执行并阻塞渲染
### 8-3 页面加载 - 几个示例
为何要把 CSS 放在 head 中?
答:保证先加载 CSS ,接着渲染,不然要渲染两次,用户体验差。
为何要把 JS 放在 body 最下面?
答:不会阻塞渲染过程,提高性能。
`window.onload` 和 `DOMContentLoaded`
```js
window.addEventListener('load', function() {
// 页面的全部资源加载完才会执行,包括图片、视频等
})
document.addEventListener('DOMContentLoaded', function() {
// DOM 渲染完即可执行,此时图片、视频还可能没有加载完
})
```
### 8-4 页面加载 - 解答
从输入 URL 到得到 HTML 的详细过程
- 浏览器根据 DNS 服务器得到域名的 IP 地址
- 向这个 IP 的机器发送 HTTP 请求
- 服务器收到、处理并返回 HTTP 请求
- 浏览器得到返回内容
`window.onload` 和 `DOMContentLoaded` 的区别
- 页面的全部资源加载完才会执行,包括图片、视频等
- DOM 渲染完即可执行,此时图片、视频还没有加载完
### 8-5 性能优化 - 优化策略
性能优化
- 这本身就是一个综合性的问题
- 没有标准答案,如果要非常全面,能写一本书
- 只关注核心店,针对面试
原则
- 多使用内存、缓存或者其他方法
- 减少 CPU 计算、减少网络
从哪里入手
- 加载页面和静态资源
- 页面渲染
加载资源优化
- 静态资源的压缩合并
- 静态资源缓存
- 使用 CDN 让资源加载更快
- 使用 SSR 后端渲染,数据直接输出到 HTML 中
渲染优化
- CSS 放前面,JS 放后面
- 懒加载(图片懒加载、下拉加载更多)
- 减少 DOM 操作,对 DOM 查询做缓存,多个操作尽量合并在一起执行
- 事件节流
- 尽早执行操作,如 DOMContentLoaded
### 8-6 性能优化 - 几个示例
资源合并
```html
<script src=a.js></script>
<script src=b.js></script>
<script src=c.js></script>
```
```html
<script src="abc.js"></script>
```
缓存
- 通过链接名称控制缓存
- 只有内容改变的时候,链接名称才会改变
CDN
```html
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
```
使用 SSR 后端渲染
- 现在 Vue/React 提出了这样的概念
- 其实 JSP/PHP/ASP 都属于后端渲染
懒加载
```html
<img id="img1" src="preview.png" data-realsrc="abc.png" />
<script>
var img1 = document.getElementById('img1')
img1.src = img1.getAttribute('data-realsrc')
</script>
```
缓存 DOM 查询
```js
// 未缓存 DOM 查询
var i
for (i = 0; i < document.getElementByTagName('p').length; i++) {
}
// 缓存了 DOM 查询
var pList = document.getElementByTagName('p')
var i
for (i = 0; i < pList.length; i++) {
}
```
合并 DOM 插入
```js
var listNode = document.getElementById('list')
// 要插入 10 个 li 标签
var frag = document.createDocumentFragment()
var x, li
for (x = 0; x < 10; x++) {
li = document.createElement('li')
li.innerHTML = 'List item ' + x
frag.appendChild(li)
}
listNode.appendChild(frag)
```
事件节流
```js
var textarea = document.getElementById('text')
var timeoutid
textarea.addEventListener('keyup', function() {
if (timeoutid) {
clearTimeout(timeoutid)
}
timeoutid = setTimeout(function() {
// 触发 change 事件
}, 100)
})
```
尽早操作
```js
window.addEventListener('load', function() {
// 页面的全部资源加载完才会执行,包括图片、视频等
})
document.addEventListener('DOMContentLoaded', function() {
// DOM 渲染完即可执行,此时图片、视频还可能没有加载完
})
```
### 8-7 安全性 - XSS
知识点
- XSS 跨站请求攻击
- XSRF 跨站请求伪造
XSS
- 在新浪博客写一篇文章,同时偷偷插入一段 `<script>`
- 攻击代码中,获取 Cookie ,发送自己的服务器
- 发布博客,有人查看博客内容
- 会把查看者的 Cookie 发送到攻击者的服务器
- 前端替换关键字,例如替换 `<` 为 `<` ,`>` 为 `>`
- 后端替换
### 8-8 安全性 - XSRF
XSRF
- 你已登录一个购物网站,正在浏览商品
- 该网站付费接口是 xxx.com/pay?id=100 ,但是没有任何验证
- 然后你收到一封邮件,隐藏着 `<img src="xxx.com/pay?id=100" />`
- 你查看邮件的时候,就已经悄悄的付费购买了
- 增加验证流程,如输入指纹、密码、短信验证码
### 8-9 面试技巧
简历
- 简洁明了,重点突出项目经理和解决方案
- 把个人博客放在简历中,并且定期维护更新博客
- 把个人的开源项目放在简历中,并维护开源项目
- 简历千万不要造假,要保持能力和经历上的真实性
面试过程中
- 如何看待加班?加班就像借钱,救急不救穷
- 千万不要挑战面试官,不要反考面试官
- 学会给面试官惊喜,但不要太多
- 遇到不会回答的问题,说出你知道的也可以
- 谈谈你的缺点——说一下你最近正在学什么就可以了
## 第9章 真题模拟
1. **`var` 和 `let` 、`const` 的区别**
答:
- `var` 是 ES5 语法,`let` 、`const` 是ES6 语法,`var` 有变量提升
- `var` 和 `let` 是变量,可修改,`const` 是常量,不可修改
- `let` 、`const` 有块级作用域,`var` 没有
2. **`typeof` 返回哪些类型**
答:
- undefined 、string 、number 、boolean 、symbol
- object(注意,`typeof null === 'object'`)
- function
3. **列举强制类型转换和隐式类型转换**
答:
- 强制:`parseInt` 、`parseFloat` 、`toString` 等
- 隐式:if 、逻辑运算、== 、+ 拼接字符串
4. **手写深度比较,模拟 lodash 的 `isEqual`**
答:
```js
// 判断是否是对象或数组
function isObject(obj) {
return typeof obj === 'object' && obj !== null
}
function isEqual(obj1, obj2) {
if (!isObject(obj1) || !isObject(obj2)) {
// 值类型(注意,参与 equal 的一般不会是函数)
return obj1 === obj2
}
if (obj1 === obj2) {
return true
}
// 两个都是对象或数组,而且不相等
// 1. 先取出 obj1 和 obj2 的 keys ,比较个数
const obj1Keys = Object.keys(obj1)
const obj2Keys = Object.keys(obj2)
if (obj1Keys.length !== obj2Keys.length) {
return false
}
// 2. 以 obj1 为基准,和 obj2 一次递归比较
for (let key in obj1) {
if (!isEqual(obj1[key], obj2[key])) {
return false
}
}
// 3. 全相等
return true
}
const obj1 = {
a: 100,
b: {
x: 100,
y: 200
}
}
const obj2 = {
a: 100,
b: {
x: 100,
y: 200
}
}
console.log(obj1 === obj2) // false
console.log(isEqual(obj1, obj2)) // true
```
5. **`split` 和 `join` 的区别**
答:
```js
'1-2-3'.split('-') // [1, 2, 3]
[1, 2, 3].join('-') /// '1-2-3'
```
6. **数组的 `pop` 、`push` 、`unshift` 、`shift` 分别做什么**
答:
- 功能是什么?
- 返回值是什么?
- 是否会对原数组造成影响?
```js
const arr = [10, 20, 30, 40]
const result = arr.pop()
console.log(result, arr) // 40, [10, 20, 30]
```
```js
const arr = [10, 20, 30, 40]
const result = arr.push(50) // 返回 length
console.log(result, arr) // 5, [10, 20, 30, 40, 50]
```
```js
const arr = [10, 20, 30, 40]
const result = arr.unshift(5) // 返回 length
console.log(result, arr) // 5, [5, 10, 20, 30, 40]
```
```js
const arr = [10, 20, 30, 40]
const result = arr.shift()
console.log(result, arr) // 10, [20, 30, 40]
```
纯函数:1. 不改变源数组;2. 返回一个数组
```js
// 纯函数
const arr = [10, 20, 30, 40]
const cArr = arr.concat([50, 60, 70]) // [10, 20, 30, 40, 50, 60, 70]
const mArr = arr.map(item => item * 10) // [100, 200, 300, 400]
const fArr = arr.filter(item => item > 20) // [30, 40]
const sArr = arr.slice() // [10, 20, 30, 40]
// 非纯函数
// push 、pop 、shift 、unshift
// forEach
// some every reduce
```
7. **数组 `slice` 和 `splice` 的区别**
答:
- 功能区别,`slice` 是切片,`splice` 是剪接
- 参数和返回值
- 是否纯函数?
```js
const arr = [10, 20, 30, 40, 50]
// slice 是纯函数
const sliceArr = arr.slice(1, 4)
// splice 不是纯函数
const spliceArr = arr.splice(1, 2, 'a', 'b', 'c')
console.log(arr, spliceArr) // [10, "a", "b", "c", 40, 50],[20, 30]
```
8. **`[10, 20, 30].map(parseInt)` 返回结果是什么?**
答:
- `map` 的参数和返回值
- `parseInt` 的参数和返回值
```js
[10, 20, 30].map(parseInt)
// 相当于
[10, 20, 30].map((item, index) => {
return parseInt(item, index)
})
// 分解为
parseInt(10, 0) // 10
parseInt(20, 1) // NaN
parseInt(30, 2) // NaN
```
9. **Ajax 请求 get 和 post 的区别?**
答:
- get 一般用于查询操作,post 一般用于提交操作
- get 参数拼接在 url 上,post 放在请求体内(数据体积可更大)
- 安全性,post 易于防止 CSRF
10. **函数 call 和 apply 的区别?**
答:
```js
fn.call(this, p1, p2, p3)
fn.apply(this, arguments)
```
11. **事件代理(委托)是什么?**
答:
```js
function bindEvent(elem, type, selector, fn) {
if (fn == null) {
fn = selector
selector = null
}
elem.addEventListener(type, function(e) {
var target
if (selector) {
target = e.target
if (target.matches(selector)) {
fn.call(target, e)
}
} else {
fn(e)
}
})
}
// 使用代理
var div1 = document.getElementById('div1')
bindEvent(div1, 'click', 'a', function(e) {
console.log(this.innerHTML)
})
// 不使用代理
var a = document.getElementById('a1')
bindEvent(div1, 'click', function(e) {
console.log(a.innerHTML)
})
```
12. **闭包是什么,有什么特性?有什么负面影响?**
答:
- 回顾作用域和自由变量
- 回顾闭包应用场景:作为参数被传入,作为返回值被返回
- 回顾:自由变量的查找,要在函数定义的地方(而非执行的地方)
- 影响:变量会常驻内存,得不到释放。闭包不要乱用
13. **如何阻止事件冒泡和默认行为?**
答:
- `event.stopPropagation()`
- `event.preventDefault()`
14. **查找、添加、删除、移动 DOM 节点的方法?**
答:
- `getElementById` 、`getElementsByTagName` 、`getElementsByClassName` 、`querySelectorAll`
- `appendChild`(添加和移动)
- `removeChild`
- `parentNode` 、`childNodes`
15. **如何减少 DOM 操作?**
答:
- 缓存 DOM 查询结果
- 多次 DOM 操作,合并到一次插入
16. **解释 JSONP 的原理,为何它不是真正的 Ajax ?**
答:
- 浏览器的同源策略(服务端没有同源策略)和跨域
- 哪些 HTML 标签能绕过跨域?
- JSONP 的原理
17. **`document` 的 load 和 ready 的区别**
答:
```js
window.addEventListener('load', function() {
// 页面的全部资源加载完才会执行,包括图片、视频等
})
document.addEventListener('DOMContentLoaded', function() {
// DOM 渲染完即可执行,此时图片、视频还可能没有加载完
})
```
18. **`==` 和 `===` 的不同**
答:
- `==` 会尝试类型转换
- `===` 严格相等
- 哪些场景才会用 `==` ?
19. **函数声明和函数表达式的区别**
答:
- 函数声明 `function fn() {}`
- 函数表达式 `const fn = function() {}`
- 函数声明会在代码执行前预加载,而函数表达式不会
20. **`new Object()` 和 `Object.create()` 的区别**
答:
- `{}` 等同于 `new Object()` ,原型是 `Object.prototype`
- `Object.create(null)` 没有原型
- `Object.crate({...})` 可指定原型
```js
const obj1 = {
a: 10,
b: 20,
sum() {
return this.a + this.b
}
}
const obj2 = new Object({
a: 10,
b: 20,
sum() {
return this.a + this.b
}
})
const obj3 = new Object(obj1)
console.log(obj1 === obj2) // false
console.log(obj1 === obj3) // true
const obj4 = Object.create(null) // {} ,但没有原型
const obj5 = new Object() // {}
const obj6 = Object.create(obj1) // 创建一个空对象,把空对象的原型指向 obj1
console.log(obj1 === obj6) // false
console.log(obj1 === obj6.__proto__) // true
```
21. **关于 `this` 的场景题**
```js
const User = {
count: 1,
getCount: function() {
return this.count
}
}
console.log(User.getCount()) // 1
const func = User.getCount
console.log(func()) // undefined
```
22. **关于作用域和自由变量的场景题(1)**
```js
let i
for (i = 1; i <= 3; i++) {
setTimeout(function() {
console.log(i)
}, 0)
}
// 4
// 4
// 4
```
23. **判断字符串以字母开头,后面字母数字下划线,长度 6-30**
答:
```js
const reg = /^[a-zA-Z]\w{5,29}$/
```
24. **关于作用域和自由变量的场景题(2)**
```js
let a = 100
function test() {
alert(a) // 100
a = 10
alert(a) // 10
}
test()
alert(a) // 10
```
25. **手写字符串 `trim` 方法,保证浏览器兼容性**
答:
```js
String.prototype.trim = function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '')
}
// (原型、this 、正则表达式)
```
26. **如何获取多个数字中的最大值**
答:
```js
function max() {
const nums = Array.prototype.slice.call(arguments) // 变为数组
let max = -Infinity
nums.forEach(n => {
if (n > max) {
max = n
}
})
return max
}
// 或者使用 Math.max()
```
27. **如何用 JS 实现继承?**
答:
- class 继承
- prototype 继承
28. **如何捕获 JS 程序中的异常?**
答:
```js
// 第一种方式
try {
// TODO
} catch(error) {
console.error(error) // 手动捕获
} finally {
// TODO
}
// 第二种方式
// 自动捕获
window.onerror = function(message, source, lineNum, colNum, error) {
// 第一,对跨域的 JS ,如 CDN 的不会有详细的报错信息
// 第二,对于压缩的 JS ,还要配合 SourceMap 反查到未压缩代码的行、列
}
```
29. **什么是 JSON ?**
答:
- JSON 是一种数据格式,本质是一段字符串
- JSON 格式和 JS 对象结构一致,对 JS 语言更友好
- `window.JSON` 是一个全局对象,`JSON.stringify` 和 `JSON.parse`
30. **获取当前页面 URL 参数**
答:
- 传统方式,查找 `location.search`
- 新 API ,`URLSearchParams`
```js
// 传统方式
function query(name) {
const search = location.search.substr(1)
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
const res = search.match(reg)
if (res === null) {
return null
}
return res[2]
}
```
```js
// URLSearchParams
function query(name) {
const search = location.search
const p = new URLSearchParams(search)
return p.get(name)
}
```
31. **将 URL 参数解析为 JS 对象**
答:
```js
// 传统方式,分析 search
function query2Obj() {
const res = {}
const search = location.search.substr(1) // 去掉前面的 ?
search.split('&').forEach(paramStr => {
const arr = paramStr.split('=')
const [key, val] = arr
res[key] = val
})
return res
}
```
```js
// 使用 URLSearchParams
function query2Obj() {
const res = {}
const pList = new URLSearchParams(location.search)
pList.forEach((val, key) => {
res[key] = val
})
return res
}
```
32. **手写数组 faltern ,考虑多层级**
答:
```js
function flat(arr) {
// 验证 arr 中,还有没有深层数组
const isDeep = arr.some(item => item instanceof Array)
if (!isDeep) {
return arr
}
return flat(Array.prototype.concat.apply([], arr))
}
const res = flat([1, 2, [3, 4], [5, [6, 7]]])
console.log(res) // [1, 2, 3, 4, 5, 6, 7]
```
33. **数组去重**
答:
- 传统方式,遍历元素挨个比较、去重
- 使用 Set
- 考虑计算效率
```js
// 传统方式
function unique(arr) {
const res = []
arr.forEach(item => {
if (res.indexOf(item) < 0) {
res.push(item)
}
})
return res
}
console.log(unique([1, 2, 3, 1, 2, 3, 4])) // 1 2 3 4
```
```js
// 使用 Set(无序、不重复)
function unique(arr) {
const set = new Set(arr)
return [...set]
}
console.log(unique([1, 2, 3, 1, 2, 3, 4])) // 1 2 3 4
```
34. **手写深拷贝**
答:
```js
function deepClone(obj = {}) {
// 如果不是数组或对象,直接返回
if (typeof obj !== 'object' || obj == null) {
return obj
}
// 初始化返回结果
let result
if (obj instanceof Array) {
result = []
} else {
result = {}
}
// 遍历数组或对象的属性
for (let key in obj) {
// 保证 key 不是原型的属性
if (obj.hasOwnProperty(key)) {
// 递归调用
result[key] = deepClone(obj[key])
}
}
// 返回结果
return result
}
// 注意 Object.assign 不是深拷贝
```
35. **介绍一下 RAF(`requestAnimationFrame`)**
答:
- 要想动画流畅,更新频率要 60 帧/秒,即 16.67ms 更新一次视图
- `setTimeout` 要手动更新频率,而 RAF 浏览器会自动控制
- 后台标签或隐藏 iframe 中,RAF 会暂停,而 `setTimeout` 依然执行
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setTimeout</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
#div1, #div2 {
width: 100px;
height: 50px;
margin-bottom: 20px;
background-color: red;
}
</style>
</head>
<body>
<div id="div1">setTimeout</div>
<div id="div2">requestAnimateFrame</div>
<script>
const $div1 = $('#div1')
let curWidth = 100
const maxWidth = 640
function animate() {
curWidth += 3
$div1.css('width', curWidth)
if (curWidth < maxWidth) {
setTimeout(animate, 16.7)
}
}
animate()
const $div2 = $('#div2')
let curWidth2 = 100
function animate2() {
curWidth2 += 3
$div2.css('width', curWidth2)
if (curWidth2 < maxWidth) {
window.requestAnimationFrame(animate2)
}
}
animate2()
</script>
</body>
</html>
```
36. **前端性能如何优化?一般从哪几个方面考虑?**
答:
- 原则:多使用内存、缓存,减少计算、减少网络请求
- 方向:加载页面,页面渲染,页面操作流畅度
|
/*
Copyright 2019-2020 Netfoundry, Inc.
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
https://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.
*/
const isNull = require('lodash.isnull');
/**
* Inject err msg into the Identity Modal.
*
*/
exports.setMessage = (errorMessage) => {
var el = document.getElementById("ziti-keypair-error");
if (!isNull(el)) {
if (typeof errorMessage != "undefined") {
el.textContent = errorMessage;
} else {
el.textContent = "";
}
}
}
exports.setProgress = (progressMessage) => {
var el = document.getElementById("ziti-keypair-progress");
if (!isNull(el)) {
if (typeof progressMessage != "undefined") {
el.textContent = progressMessage;
} else {
el.textContent = "";
}
}
}
|
---
region: CEWA
country: Nigeria
name: Rights Monitoring Group (RMG)
acronym: RMG
is_member: yes
no_gndem_member_countries:
regional_network:
website: http://rightsgroup.org/about-us/
---
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Speedometer extends Model
{
protected $tables = 'speedometers';
protected $fillable = [
'baku_mutu',
'emisi_sumber',
'udara_ambient',
'no_incident',
'impact',
'unique_id',
];
}
|
class BodyTypeController < ApplicationController
def index
@body_types = BodyType.all.includes(:bodies)
end
def show
@body_type = BodyType.find(params[:id])
@bodies = Body.where(body_type: @body_type).order("name ASC")
end
end
|
package slack
import (
"fmt"
"github.com/slack-go/slack"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
type conf struct {
Token string `yaml:"slack_api_token"`
Channel string `yaml:"slack_channel"`
}
func UploadFile(configFilePath,reportFilePath string) error {
c, err := GetCredentials(configFilePath)
if err != nil {
return err
}
api := slack.New(c.Token)
params := slack.FileUploadParameters{
Title: "OlTP ",
Filetype: "json",
File: reportFilePath,
Channels: []string{c.Channel},
InitialComment: "This is sample OLTP",
}
_, err = api.UploadFile(params)
if err != nil {
return err
}
return nil
}
func GetCredentials(configFilePath string) (*conf, error) {
//Read from the config file
var c conf
fmt.Println(os.Getwd())
yamlFile, err := ioutil.ReadFile(configFilePath)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(yamlFile, &c)
if err != nil {
return nil, err
}
return &c, nil
}
|
/*
* @test /nodynamiccopyright/
* @bug 8003280
* @summary Add lambda tests
* speculative cache contents are overwritten by deferred type-checking of nested stuck expressions
* @compile/fail/ref=MostSpecific07.out -XDrawDiagnostics MostSpecific07.java
*/
import java.util.*;
class MostSpecific07 {
interface Predicate<X, Y> {
Y accept(X x);
}
interface VoidMapper {
void accept();
}
interface ExtPredicate<X, Y> extends Predicate<X, Y> { }
void test(boolean cond, ArrayList<String> als, VoidMapper vm) {
m(u -> ()->{}, als, als, vm);
m((u -> ()->{}), als, als, vm);
m(cond ? u -> ()->{} : u -> ()->{}, als, als, vm);
}
<U, V> U m(Predicate<U, V> p, List<U> lu, ArrayList<U> au, V v) { return null; }
<U, V> U m(ExtPredicate<U, V> ep, ArrayList<U> au, List<U> lu, V v) { return null; }
}
|
<?php
namespace App\Observers;
use App\Jobs\TaskReminder;
use App\Mail\TaskCreatedMail;
use App\Models\Task;
use App\Notifications\SampleNotification;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use PharIo\Manifest\Email;
class TaskObserver
{
public function creating(Task $task)
{
info("creating: " . $task->id);
$task->title = $task->title . " " . "creating";
}
public function created(Task $task)
{
//$task->notify(new SampleNotification($task));
dispatch(new TaskReminder($task));
// $newdate = Carbon::parse($task->reminder);
// $current = Carbon::now();
$delay = $newdate->diffindays($current);
$task->notify((new SampleNotification($task))->delay(now()->addDays($delay)));
$task->notify((new SampleNotification($task))->delay(now()->addDays($delay -1)));
// dispatch(new TaskReminder($task))
// ->delay(now()->addWeek());
// $task->reminder_date->subDays(2);
// $task->created_at->addDays(2);
// Mail::to($task->user->email)
// ->send(new TaskCreatedMail($task));
// dispatch(new TaskReminder($task))
// ->delay($task->due);
// info("created: " . $task->id);
// $task->update([
// 'title' => $task->title . " " . "created"
// ]);
}
// public function created(Task $task) {
// // $task->user->sendEmail("تسک ساخته شد."); # این روش تستی بود.
// }
//
// public function retrieved(Task $task) {
// info("retrieved task id: " . $task->id);
// }
public function forceDeleted(Task $task) {
//info("forceDeleted " . $task);
Storage::disk('s3')->delete($task->image);
}
}
|
import { R5_BackboneElement } from './R5_BackboneElement'
import { R5_DeviceMetricCalibrationStateEnum } from './R5_DeviceMetricCalibrationStateEnum'
import { R5_DeviceMetricCalibrationTypeEnum } from './R5_DeviceMetricCalibrationTypeEnum'
import { R5_DomainResource } from './R5_DomainResource'
export class R5_DeviceMetric_Calibration extends R5_BackboneElement
{
static def : string = 'DeviceMetric_Calibration';
type : R5_DeviceMetricCalibrationTypeEnum ;
state : R5_DeviceMetricCalibrationStateEnum ;
time : string ;
}
|
# This file is a part of Simple-XX/SimpleKernel (https://github.com/Simple-XX/SimpleKernel).
#
# bochs.sh for Simple-XX/SimpleKernel.
#!/bin/bash
if ! [ -x "$(command -v pkg-config)" ]; then
echo 'Error: pkg-config is not installed.'
exit 1
elif ! [ -x "$(command -v sdl2)" ]; then
echo 'Error: sdl2 is not installed.'
exit 1
elif ! [ -x "$(command -v wget)" ]; then
echo 'Error: wget is not installed.'
exit 1
elif ! [ -x "$(command -v tar)" ]; then
echo 'Error: tar is not installed.'
exit 1
else
wget https://downloads.sourceforge.net/project/bochs/bochs/2.6.9/bochs-2.6.9.tar.gz
tar zxvf bochs-2.6.9.tar.gz
cd bochs-2.6.9
./configure \
--with-nogui \
--enable-disasm \
--disable-docbook \
--enable-x86-64 \
--enable-pci \
--enable-all-optimizations \
--enable-plugins \
--enable-cdrom \
--enable-a20-pin \
--enable-fpu \
--enable-alignment-check \
--enable-large-ramfile \
--enable-debugger-gui \
--enable-readline \
--enable-iodebug \
--enable-show-ips \
--enable-logging \
--enable-usb \
--enable-cpu-level=6 \
--enable-clgd54xx \
--enable-avx \
--enable-vmx=2 \
--enable-long-phy-address \
--with-term \
--with-sdl2
make
make install
fi
|
package me.hvkcoder.java_basic.java8.lambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
/**
* java.util.function.Function<T, R> 接口定义了一个 apply 方法,它接受一个泛型 T 对象,并返回一个泛型 R 的对象
*
* <p>如果需要定义一个 Lambda ,将输入对象的信息映射到输出,就可以使用该接口
*
* @author h-vk
* @since 2020/7/25
*/
public class FunctionUsage {
public static void main(String[] args) {
List<String> languages = Arrays.asList("C", "C#", "C++", "Java", "Golang", "Python", "Ruby");
List<Integer> result = map(languages, s -> s.length());
System.out.println(result);
}
public static <T, R> List<R> map(List<T> lists, Function<T, R> func) {
List<R> result = new ArrayList<>();
for (T t : lists) {
result.add(func.apply(t));
}
return result;
}
}
|
%%%-------------------------------------------------------------------
%%% @author halid
%%% @copyright (C) 2015, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 26. Sep 2015 1:30 PM
%%%-------------------------------------------------------------------
-module(tk_lib).
-author("halid").
%% API
-export([read_file/1]).
-export([uuid4/0]).
-export([echo1/2, echo2/1]).
-export([writeout/2, writeout/6]).
-export([iso_timestamp/1, to_timestamp/1, tdiff_seconds/2]).
-define(VARIANT10, 2#10).
-define(MAX_UNSIGNED_INT_32, 4294967296).
-define(OUTPUT_FILE, "output/file1.csv").
read_file(Fname) ->
Content1 = case file:open(Fname, [read, raw, binary]) of
{ok, _} ->
{ok, Content2} = file:read_file(Fname),
Content2;
{error, Reason} ->
{error, Reason}
end,
Content1.
uuid4() ->
<<A:32, B:16, C:16, D:16, E:48>> = crypto:strong_rand_bytes(16),
Str = io_lib:format("~8.16.0b-~4.16.0b-4~3.16.0b-~4.16.0b-~12.16.0b",
[A, B, C band 16#0fff, D band 16#3fff bor 16#8000, E]),
list_to_binary(Str).
%%------------ECHO---------------------------------------
echo1(NameArg1, Arg1) ->
io:format("~n =============== ~n ~p : ~p ~n =============== ~n",
[NameArg1, Arg1]).
echo2(ArgList) ->
io:format("~n ==============="),
lists:foreach(
fun(X) ->
case is_tuple(X) of
true ->
{NameArg, Arg} = X;
_ ->
Arg = X, NameArg = var
end,
io:format("~n ~p : ~p ~n -----",
[NameArg, Arg])
end
, ArgList),
io:format("~n =============== ~n ~n").
%%------------WRITE TO FILE------------------------------
writeout(A1, A2) ->
file:write_file(?OUTPUT_FILE,
io_lib:fwrite("\n~p;~p;~p", [calendar:local_time(),A1, A2]), [append]).
writeout(A1, A2, A3, A4, A5, A6) ->
file:write_file(?OUTPUT_FILE,
io_lib:fwrite("\n~p;~p;~p;~p;~p;~p", [A1, A2, A3, A4, A5, A6]), [append]).
%%------------TIME---------------------------------------
iso_timestamp(TS) ->
{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:now_to_local_time(TS),
lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0wT~2..0w:~2..0w:~2..0w",[Year,Month,Day,Hour,Minute,Second])).
to_timestamp({{Year,Month,Day},{Hours,Minutes,Seconds}}) ->
(calendar:datetime_to_gregorian_seconds(
{{Year,Month,Day},{Hours,Minutes,Seconds}}
) - 62167219200)*1000000.
tdiff_seconds(T1, T2) ->
round(abs(timer:now_diff(T1, T2) / 1000000)).
t() ->
erlang:monotonic_time().
tdiff(A, B) ->
B - A.
|
trait Expr { type T }
def foo[A](e: Expr { type T = A }) = e match
case e1: Expr { type T <: Int } => // error: type test cannot be checked at runtime
val i: Int = ??? : e1.T |
/*
* Copyright 2019 The Starlark in Rust Authors.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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
*
* https://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.
*/
pub use exported::exported_symbols;
pub use types::{LineColSpan, Lint};
use crate::{analysis::types::LintT, syntax::AstModule};
mod bind;
mod dubious;
mod exported;
mod flow;
mod incompatible;
mod names;
mod types;
pub fn lint(module: &AstModule, globals: Option<&[&str]>) -> Vec<Lint> {
let mut res = Vec::new();
res.extend(flow::flow_issues(module).into_iter().map(LintT::erase));
res.extend(
incompatible::incompatibilities(module)
.into_iter()
.map(LintT::erase),
);
res.extend(dubious::dubious(module).into_iter().map(LintT::erase));
res.extend(
names::name_warnings(module, globals)
.into_iter()
.map(LintT::erase),
);
res
}
|
// ==========================================================================
// NumberField.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using Squidex.Domain.Apps.Core.Schemas.Validators;
namespace Squidex.Domain.Apps.Core.Schemas
{
public sealed class NumberField : Field<NumberFieldProperties>
{
public NumberField(long id, string name, Partitioning partitioning)
: this(id, name, partitioning, new NumberFieldProperties())
{
}
public NumberField(long id, string name, Partitioning partitioning, NumberFieldProperties properties)
: base(id, name, partitioning, properties)
{
}
protected override IEnumerable<IValidator> CreateValidators()
{
if (Properties.IsRequired)
{
yield return new RequiredValidator();
}
if (Properties.MinValue.HasValue || Properties.MaxValue.HasValue)
{
yield return new RangeValidator<double>(Properties.MinValue, Properties.MaxValue);
}
if (Properties.AllowedValues != null)
{
yield return new AllowedValuesValidator<double>(Properties.AllowedValues.ToArray());
}
}
public override T Accept<T>(IFieldVisitor<T> visitor)
{
return visitor.Visit(this);
}
public override object ConvertValue(JToken value)
{
return (double?)value;
}
}
}
|
extern crate bincode;
extern crate core;
extern crate libc;
extern crate rustler;
extern crate serde;
extern crate siphasher;
mod atoms;
mod bindings;
mod nif;
rustler::init!("crypt3_nif", [nif::encrypt], load = nif::on_load);
|
2020年08月14日15时数据
Status: 200
1.张雨绮光脚跳屋顶着火
微博热度:2774989
2.央视再评大胃王吃播
微博热度:1192961
3.郑恺带了一朵什么花
微博热度:1192815
4.吴亦凡保安
微博热度:1191329
5.乘风破浪的姐姐复活换位战
微博热度:1170938
6.陕西镇安回应7.1亿建豪华中学
微博热度:717676
7.警方通报女游客无故推倒景区设施
微博热度:573278
8.全球43%的学校缺基本洗手设施
微博热度:482843
9.商务部发文称将开展数字人民币试点
微博热度:475141
10.阿朵缘分一道桥 鸡皮疙瘩
微博热度:474444
11.厦门机场辟谣飞机跑出机场
微博热度:471719
12.阿里云回应注册新公司京西
微博热度:467890
13.凌霄温柔
微博热度:463441
14.荆州禁向发热者售卖退热止咳药
微博热度:457917
15.网贷平台从五六千家降至29家
微博热度:452978
16.爱奇艺遭美国证监会调查
微博热度:450876
17.孟佳赢了张含韵
微博热度:445846
18.袁崇焕墓第17代守墓人去世
微博热度:439959
19.穿衣镜被碰倒爸爸飞身护娃
微博热度:435966
20.麦莉分手
微博热度:435909
21.当代年轻人吃外卖
微博热度:434115
22.超新星运动会
微博热度:429889
23.女孩免费给农村女性化妆
微博热度:280458
24.洪水中救崽的狗妈一家被收养
微博热度:280052
25.蔡卓宜MV太美了
微博热度:258853
26.张艺兴翼人造型
微博热度:234454
27.贺子秋式直男
微博热度:208841
28.有人将择良驹赠英雄马马主
微博热度:190149
29.统计局回应猪肉价格上涨
微博热度:190140
30.郑爽斥装修公司
微博热度:189885
31.杨幂瑞丽25周年封面
微博热度:189668
32.霍格沃茨学院妆
微博热度:189578
33.江西入室杀人案受害者家属发声
微博热度:189401
34.测谎结果不属于合法证据形式
微博热度:188683
35.宋妍霏木色冷漠裸妆
微博热度:188605
36.UNINE ReadyGo舞台
微博热度:188548
37.雪顶气泡葡萄冰
微博热度:188390
38.NBA
微博热度:164197
39.琉璃改名大赛
微博热度:163380
40.张颜齐脚被鸡汤烫伤
微博热度:163172
41.八佰
微博热度:154058
42.南京一新冠阳性检测者泉州活动轨迹
微博热度:147665
43.巴塞罗那灯火
微博热度:143056
44.央视专访郭树清
微博热度:138662
45.堡垒之夜开发商起诉苹果
微博热度:135110
46.在世慰安妇制度受害者已不足20位
微博热度:134610
47.沈枫 真香型恋爱选手
微博热度:127441
48.官方回应洪崖洞收费
微博热度:124144
49.哈利波特与魔法石重映
微博热度:122902
50.RAIN近照
微博热度:122596
|
<?php
namespace Chamilo\Core\Home\Rights;
use Chamilo\Libraries\Architecture\Application\Application;
use Chamilo\Libraries\Format\Structure\BreadcrumbTrail;
/**
* Manager for the components
*
* @author Sven Vanpoucke - Hogeschool Gent
*/
abstract class Manager extends Application
{
// Parameters
const PARAM_BLOCK_TYPE = 'block_type';
// Actions
const ACTION_BROWSE_BLOCK_TYPE_TARGET_ENTITIES = 'BrowseBlockTypeTargetEntities';
const ACTION_SET_BLOCK_TYPE_TARGET_ENTITIES = 'SetBlockTypeTargetEntities';
const DEFAULT_ACTION = self::ACTION_BROWSE_BLOCK_TYPE_TARGET_ENTITIES;
/**
* Returns the URL to the SetBlockTypeTargetEntities Component
*
* @param string $blockType
*
* @return string
*/
public function get_set_block_type_target_entities_url($blockType)
{
$parameters = array(
self::PARAM_ACTION => self::ACTION_SET_BLOCK_TYPE_TARGET_ENTITIES,
self::PARAM_BLOCK_TYPE => $blockType);
return $this->get_url($parameters);
}
/**
*
* @return \Chamilo\Core\Admin\Core\BreadcrumbGenerator
*/
public function get_breadcrumb_generator()
{
return new \Chamilo\Core\Admin\Core\BreadcrumbGenerator($this, BreadcrumbTrail::getInstance());
}
}
|
<?php
/**
* Created by JetBrains PhpStorm.
* User: thuan
* Date: 4/29/14
* Time: 8:39 AM
* To change this template use File | Settings | File Templates.
*/
namespace Goxob\Catalog\Model;
use Goxob\Core\Model\Model;
class Vendor extends Model{
protected $table = 'vendor';
protected $primaryKey = 'vendor_id';
protected $fillable = array(
'vendor_id',
'vendor_name',
'country',
'url',
'email',
'description'
);
} |
---
name: Bug report
about: Report a bug in the software
labels: bug
---
**Description**
<!-- Please provide a clear and concise description of what the bug is. -->
**Steps To Reproduce**
<!-- Please provide instructions on how to reproduce the bug. -->
1.
2.
3.
4.
**Expected Behavior**
<!-- Please prpovide a clear and concise description of what you expected to happen. -->
**Additional Information**
<!-- Add here any other information you think may be relevent to the problem. -->
|
#!/usr/bin/env python3
# The following line will rename a file
import shutil
import os
os.chdir('/home/student/mycode/')
shutil.move('raynor.obj', 'ceph_storage/')
xname = input('What is the new name for kerrigan.obj? ')
shutil.move('ceph_storage/kerrigan.obj', 'ceph_storage/' + xname)
|
import { isLeafNode } from '../../common-utils'
import { transformColumn } from '../utils'
export default function visible(visibleCodes: string[]) {
const set = new Set(visibleCodes)
return transformColumn((column) => {
if (!isLeafNode(column)) {
return column
}
return set.has(column.code) ? column : { ...column, hidden: true }
})
}
|
package persistence
import (
"bytes"
"encoding/gob"
"github.com/google/uuid"
. "ivory/model"
)
type CredentialRepository struct {
common common
secretBucket []byte
credentialBucket []byte
encryptedRefKey string
decryptedRefKey string
}
func (r CredentialRepository) UpdateRefs(encrypted string, decrypted string) error {
var err error
err = r.common.update(r.secretBucket, r.encryptedRefKey, encrypted)
err = r.common.update(r.secretBucket, r.decryptedRefKey, decrypted)
return err
}
func (r CredentialRepository) GetEncryptedRef() string {
get, err := r.common.get(r.secretBucket, r.encryptedRefKey)
if err != nil {
return ""
}
var str string
buff := bytes.NewBuffer(get)
_ = gob.NewDecoder(buff).Decode(&str)
return str
}
func (r CredentialRepository) GetDecryptedRef() string {
get, err := r.common.get(r.secretBucket, r.decryptedRefKey)
if err != nil {
return ""
}
var str string
buff := bytes.NewBuffer(get)
_ = gob.NewDecoder(buff).Decode(&str)
return str
}
func (r CredentialRepository) CreateCredential(credential Credential) (uuid.UUID, error) {
key, err := uuid.NewUUID()
err = r.common.update(r.credentialBucket, key.String(), credential)
return key, err
}
func (r CredentialRepository) UpdateCredential(id uuid.UUID, credential Credential) (uuid.UUID, error) {
err := r.common.update(r.credentialBucket, id.String(), credential)
return id, err
}
func (r CredentialRepository) DeleteCredential(key uuid.UUID) error {
return r.common.delete(r.credentialBucket, key.String())
}
func (r CredentialRepository) DeleteCredentials() error {
return r.common.deleteAll(r.credentialBucket)
}
func (r CredentialRepository) GetCredentialMap() map[string]Credential {
bytesList, _ := r.common.getList(r.credentialBucket)
credentialMap := make(map[string]Credential)
for _, el := range bytesList {
var credential Credential
buff := bytes.NewBuffer(el.value)
_ = gob.NewDecoder(buff).Decode(&credential)
credential.Password = "configured"
credentialMap[el.key] = credential
}
return credentialMap
}
func (r CredentialRepository) GetCredential(uuid uuid.UUID) (Credential, error) {
value, err := r.common.get(r.credentialBucket, uuid.String())
var credential Credential
buff := bytes.NewBuffer(value)
_ = gob.NewDecoder(buff).Decode(&credential)
return credential, err
}
|
@if (Auth::guard('org')->check())
@include('partials.org-nav-links')
@else
@include('partials.vol-nav-links')
@endif |
# encoding: UTF-8
class Preference < ActiveRecord::Base
belongs_to :reviewer
belongs_to :track
belongs_to :audience_level
has_one :user, through: :reviewer
validates :accepted, inclusion: {in: [true, false]}, reviewer_track: {if: :accepted?}
validates :reviewer, existence: true
validates :audience_level_id, presence: true, existence: true, same_conference: {target: :reviewer}, if: :accepted?
validates :track_id, presence: true, existence: true, same_conference: {target: :reviewer}, if: :accepted?
end |
<?php
namespace Error;
/**
* 4xx User errors.
*/
abstract class User extends HttpException
{
public function __construct(int $code = 400, $message = null, \Throwable $reason = null)
{
parent::__construct($code, $message, $reason);
}
}
|
# coconutchain
一个用来学习的区块链实现
# 编译
```
mvn clean compile assembly:single
```
上面的命令会把所有依赖库都打包在一个jar中
# 运行
```
java -jar target/coconut-chain-1.0-SNAPSHOT-jar-with-dependencies.jar
```
# 使用的第三方库
* [Spark](https://github.com/perwendel/spark) 一款轻量级的web框架,用来对外提供REST接口
* [Bouncy Castle](http://bouncycastle.org/java.html) 使用它来生成钱包的公私钥
* [FasterXML Jackson](https://github.com/FasterXML/jackson) 用来进行POJO和JSON之间的转换
* [lombok](https://projectlombok.org/) 在POJO类加上注解,从而免去手写getter/setter等常见函数
* [Slf4j](http://www.slf4j.org/) 记录日志
* [Netty](https://www.netty.io/) p2p通信
|
using System;
using System.Collections.Generic;
namespace Bakery
{
public class Pastry
{
public int QuantityPastry { get; set;}
public int TotalPastry { get; set;}
public int PerPastry { get; set; }
public Pastry(int quantityPatry, int totalPastry)
{
QuantityPastry = quantityPatry;
TotalPastry = totalPastry;
PerPastry = 2;
}
public int DeterminePricePastry(int quantityPatry)
{
TotalPastry= 0;
TotalPastry= (QuantityPastry * PerPastry);
if (QuantityPastry == 3)
{
TotalPastry --;
}
return TotalPastry;
}
}
} |
using HyperFabric.Logging;
namespace HyperFabric.Factories
{
internal interface ILoggingFactory
{
ILogger Create(string[] names);
}
}
|
<?php
namespace App\Http\Controllers;
use App\Service;
use App\SubService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ServiceController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$allService = Service::all();
$allSericeMarge = $allService;
foreach ($allService as $key => $service){
$findSubService = SubService::where('service_id', $service->id)->get();
$stackName = array();
$stackAlias = array();
foreach ($findSubService as $item){
array_push($stackName, $item->sub_service_name);
array_push($stackAlias, $item->sub_service_alias);
}
$allSericeMarge[$key] -> {'uslugi'} = $stackName;
$allSericeMarge[$key] -> {'alias_sub'} = $stackAlias;
}
return view('offer', ['groupeService' => $allService, 'groupeServiceTest' => $allSericeMarge]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function showAll()
{
if (Auth::check()) {
$allService = Service::all();
return view('admin.category', ['allService' => $allService]);
}
else{
return redirect ('/');
}
}
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if (Auth::check()) {
$this->validate($request,[
'description' => 'required|min:5'
]);
$upload_path = 'public/img/category';
$name = $request->file('img')->hashName();
$path = $request->file('img')->move(public_path('img/category/'), $name);
$alias_new = Service::ConvertToPolish($request->name);
$service = new Service();
$service->name = $request->name;
$service->alias = $alias_new;
$service->image = $name;
$detail=$request->description;
$dom = new \domdocument();
$dom->loadHtml('<?xml encoding="UTF-8">'.$detail);
$images = $dom->getelementsbytagname('img');
foreach($images as $k => $img) {
$data = $img->getattribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = time() . $k . '.png';
$path = public_path() . '/img/description/' . $image_name;
file_put_contents($path, $data);
$img->removeattribute('src');
$img->setattribute('src', asset('/img/description/'. $image_name));
$img->setattribute('old', true);
}
$detail = $dom->savehtml();
$service->main_description = $detail;
$service-> save();
return redirect('/admin/kategorie/')->with('sucess', 'Kategoria dodana prawidłowo');;
}
else{
return redirect ('/');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
if (Auth::check()) {
$service = Service::find($id);
$findSubService = SubService::where('service_id', $service->id)->get();
return view('admin.showCategory', ['service' => $service, 'test' => $findSubService]);
}
else{
return redirect ('/');
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
if (Auth::check()) {
$service = Service::findOrFail($id);
return view('admin.editCategory', ['service' => $service]);
}
else{
return redirect ('/');
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
if (Auth::check()) {
$service = Service::find($id);
$service->name = $request->name;
$detail=$request->description;
$alias_new = Service::ConvertToPolish($request->name);
$dom = new \domdocument();
$dom->loadHtml(mb_convert_encoding($detail, 'HTML-ENTITIES', 'UTF-8'));
$images = $dom->getelementsbytagname('img');
foreach($images as $k => $img) {
$data = $img->getattribute('src');
$data1 = $img->getattribute('old');
if($data1 == true){
continue;
}
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name = time() . $k . '.png';
$path = public_path() . '/img/description/' . $image_name;
file_put_contents($path, $data);
$img->removeattribute('src');
$img->setattribute('src', asset('/img/description/'. $image_name));
$img->setattribute('old', true);
}
$detail = $dom->savehtml();
$service->main_description = $detail;
$service->alias = $alias_new;
if ($request->file('img')){
$upload_path = '/public/img/category';
$name = $request->file('img')->hashName();
$path = $request->file('img')->move(public_path('img/category/'), $name);
$service->image = $name;
}
$service->save();
return redirect('/admin/kategorie')->with('sucess', 'Podkategoria zedtydowana prawidłowo');;
}
else{
return redirect ('/');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Service::where(['id' => $id])->delete();
return redirect('/admin/kategorie/')->with('sucess', 'Podkategoria usunięta prawidłowo');;
}
}
|
/*
* 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.ignite.spi.discovery;
import java.util.HashMap;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
import org.apache.ignite.internal.processors.cache.CacheMetricsSnapshot;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.MarshallerContextTestImpl;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
/** */
public class ClusterMetricsSnapshotSerializeCompatibilityTest extends GridCommonAbstractTest {
/** */
public ClusterMetricsSnapshotSerializeCompatibilityTest() {
super(false /*don't start grid*/);
}
/** Marshaller. */
private OptimizedMarshaller marshaller = marshaller();
/** */
@Test
public void testSerializationAndDeserialization() throws IgniteCheckedException {
HashMap<Integer, CacheMetricsSnapshot> metrics = new HashMap<>();
metrics.put(1, createMetricsWithBorderMarker());
metrics.put(2, createMetricsWithBorderMarker());
byte[] zipMarshal = U.zip(U.marshal(marshaller, metrics));
HashMap<Integer, CacheMetricsSnapshot> unmarshalMetrics = U.unmarshalZip(marshaller, zipMarshal, null);
assertTrue(isMetricsEquals(metrics.get(1), unmarshalMetrics.get(1)));
assertTrue(isMetricsEquals(metrics.get(2), unmarshalMetrics.get(2)));
}
/**
* @return Test metrics.
*/
private CacheMetricsSnapshot createMetricsWithBorderMarker() {
CacheMetricsSnapshot metrics = new CacheMetricsSnapshot();
GridTestUtils.setFieldValue(metrics, "rebalancingKeysRate", 1234);
GridTestUtils.setFieldValue(metrics, "reads", 3232);
return metrics;
}
/**
* @param obj Object.
* @param obj1 Object 1.
*/
private boolean isMetricsEquals(CacheMetricsSnapshot obj, CacheMetricsSnapshot obj1) {
return obj.getRebalancingKeysRate() == obj1.getRebalancingKeysRate() && obj.getCacheGets() == obj1.getCacheGets();
}
/**
* @return Marshaller.
*/
private OptimizedMarshaller marshaller() {
U.clearClassCache();
OptimizedMarshaller marsh = new OptimizedMarshaller();
marsh.setContext(new MarshallerContextTestImpl());
return marsh;
}
}
|
var ejs = require('ejs');
var SprintModel = function (params) {
this.log = function(message) {
if (this.params.debug) {
console.log(message);
}
}.bind(this);;
this.get = function (param) {
return this.params[param];
}.bind(this);
this.set = function(param, value) {
this.params[param] = value;
}.bind(this);
this.countdown = function () {
if (this.params.seconds === 0 && this.params.minutes === 0) {
clearInterval(this.interval);
if (typeof this.params.callback === 'function') {
this.params.callback()
}
} else {
this.params.minutes = (this.params.seconds === 0 ? this.params.minutes - 1 : this.params.minutes);
this.params.seconds = (this.params.seconds === 0 ? 59 : this.params.seconds - 1);
this.render();
}
}.bind(this);
this.start = function () {
this.interval = setInterval(this.countdown, 1000)
}.bind(this);
this.pause = function () {
clearInterval(this.interval);
}.bind(this);
this.render = function () {
ejs.renderFile(this.params.template, this.params, {}, (err, str) => {
if (err) {
this.log('render error: ' + err);
return;
}
this.params.el.innerHTML = str;
});
}.bind(this);
this.init = (function () {
if (!params.el) {
this.log('A valid element to render to was not passed in.');
}
if (!params.template) {
this.log('A valid template to render was not passed in.');
}
this.params = params;
this.params.minutes = parseInt(this.params.SprintTime);
this.params.seconds = 0;
this.interval = null;
}).bind(this)();
return {
get: this.get,
set: this.set,
render: this.render,
start: this.start,
pause: this.pause
};
};
module.exports = SprintModel;
|
using ScriptableObjectArchitecture.Utility;
using UnityEngine;
namespace ScriptableObjectArchitecture.Collections
{
[CreateAssetMenu(
fileName = "IntCollection.asset",
menuName = SoArchitectureUtility.COLLECTION_SUBMENU + "int",
order = SoArchitectureUtility.ASSET_MENU_ORDER_COLLECTIONS + 4)]
public class IntCollection : Collection<int>
{
}
} |
package bridges.core
trait Renderer[A] {
def render(decl: DeclF[A]): String
def render(decls: List[DeclF[A]]): String =
decls.map(render).mkString("\n\n")
}
|
require_relative 'helpers'
class TestTaskList < IWNGTest
def test_task_list
tasks = client.tasks.list()
code_names = {}
tasks.each do |t|
puts "#{t.code_name} - #{t.status}"
code_names[t.code_name] ||= 0
code_names[t.code_name] += 1
end
puts "num codes: #{code_names.size}"
assert code_names.size > 0
tasks = client.tasks.list(:code_name=>"hello")
code_names = {}
tasks.each do |t|
p t.code_name
code_names[t.code_name] ||= 0
code_names[t.code_name] += 1
end
puts "num codes: #{code_names.size}"
end
end
|
namespace YunXun.Entity
{
/// <summary>
/// Defines the <see cref="BaseEntity{Tkey}" />.
/// </summary>
/// <typeparam name="Tkey">.</typeparam>
public class BaseEntity<Tkey> : IEntity<Tkey>
{
/// <summary>
/// Gets or sets the id.
/// </summary>
public Tkey id { get; set; }
}
}
|
import { Callable, Constructor, isObject } from '../reflectable';
import { Expression, Property, getProperty } from '../property';
import { Observable, isObservable } from './observable';
/**
* Observables factory.
*/
export class ObservableFactory {
/**
* @param PropertyConstructor - Observable property constructor.
* @param ExpressionConstructor - Observable expression constructor.
*/
constructor(
private PropertyConstructor: Constructor<Property & Observable>,
private ExpressionConstructor: Constructor<Expression & Observable>,
) {}
/**
* Creates an observable for an object property.
* @param object - The target object.
* @param property - The property name.
* @returns The observable property.
*/
make<T, K extends keyof T>(object: T, property: K): Property<T[K]> & Observable<T[K]>;
/**
* Creates an observable for an expression.
* @param expression - The expression.
* @returns The observable expression.
*/
make<T, U extends any[]>(expression: Callable<T, U>): Expression<T> & Observable<T>;
make<T>(...args: [Callable<T>] | [any, keyof T]): Observable<T> {
if (args.length === 1) {
return this.makeExpression(args[0]);
}
return this.makeProperty(args[0], args[1]);
}
protected makeExpression<T>(value: Callable<T> | Observable<T>): Expression<T> & Observable<T> {
return (isObservable(value) ? (value as unknown) : new this.ExpressionConstructor(value)) as Expression<T> &
Observable<T>;
}
protected makeProperty<T, K extends keyof T>(object: T, property: K): Property<T[K]> & Observable<T[K]> {
const descriptor = getProperty(object, property);
if (isObservable(descriptor)) {
return descriptor as Property<T[K]> & Observable<T[K]>;
}
if (isObservable(object[property])) {
return (object[property] as unknown) as Property<T[K]> & Observable<T[K]>;
}
if (isObject(object[property])) {
Object.defineProperties(
object[property],
Object.fromEntries(
Object.keys(object[property]).map((key) => [key, this.makeProperty(object[property], key as keyof T[K])]),
),
);
}
return new this.PropertyConstructor(object, property) as Property<T[K]> & Observable<T[K]>;
}
}
|
<?php
class Controller
{
const APP_URL = "localhost/index.php";
private $vars = [];
private $notification = [];
public function getVars() { return $this->vars; }
public function hasNotification(){ return !empty($this->notification); }
public function GetNotificationLevel() { return $this->notification['level']; }
public function getNotificationMessage() { return $this->notification['message']; }
public function set($name, $value = null)
{
if (is_array($name)) {
foreach($name as $k => $v) {
$this->vars[$k] = $v;
}
return;
}
$this->vars[$name] = $value;
}
public function redirect($url, $params = array())
{
$query = http_build_query($params);
if (strlen($query) > 0) {
$query = '?' . $query;
}
if ($url === '/') {
$url = self::APP_URL . $query;
} elseif (strpos($url, 'http') === 0) {
$url = $url . $query;
} else {
$url = self::APP_URL . $url . $query;
}
header('Location: ' . $url);
exit;
}
public function setNotification($message, $level)
{
Session::set('notification_level', $level);
Session::set('notification_message', $message);
}
}
|
import { Quota, QuotaManager } from '../src';
import { sleep } from '../src/util';
import test from 'ava';
test('invocations are logged', async t => {
const quota: Quota = { rate: 3, interval: 500, concurrency: 2 };
const qm: QuotaManager = new QuotaManager(quota);
t.true(qm.start(1), 'should start job 1');
t.true(qm.start(2), 'should start job 2');
t.false(qm.start(3), 'starting job 3 would exceed max concurrency of 2');
qm.end();
t.true(qm.start(2), 'should start job 3');
t.is(qm.activeCount, 2, '2 jobs should be running');
t.false(qm.start(3), 'we’ve used up our quota of 3 per 1/2 second');
t.is(qm.activeCount, 2, '2 jobs still running');
qm.end();
t.is(qm.activeCount, 1, '1 job remains running');
qm.end();
t.is(qm.activeCount, 0, 'all jobs done');
});
test('throws if an incomplete rate-limit quota is used', t => {
t.throws(() => new QuotaManager({ interval: 100 }), { message: /Invalid Quota/ });
t.throws(() => new QuotaManager({ rate: 42 }), { message: /Invalid Quota/ });
});
|
from setuptools import setup
install_requires = [
'rdflib',
'lepl',
'lxml',
'six',
]
schemato_validators = [
'rnews=schemato.schemas.rnews:RNewsValidator',
'opengraph=schemato.schemas.opengraph:OpenGraphValidator',
'schemaorg=schemato.schemas.schemaorg:SchemaOrgValidator',
'schemaorg_rdf=schemato.schemas.schemaorg_rdf:SchemaOrgRDFaValidator',
'parselypage=schemato.schemas.parselypage:ParselyPageValidator',
]
setup(
name="schemato",
version="1.3.0",
author='Emmett Butler',
author_email='[email protected]',
url='https://github.com/Parsely/schemato',
keywords='microdata rdf metadata',
packages=['schemato', 'schemato.schemas'],
description='Unified semantic metadata validator',
platforms='any',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=install_requires,
entry_points={'schemato_validators': schemato_validators}
)
|
function all() {
var f = confirm("Are you sure you want to make changes to this website? Please note changes will not be immediate");
if (f == false) {
exit();
}
else {
while (true) {
var name = prompt("What is your name? (Optional)");
var subject = prompt("What is the subject you would like to fix?");
var body = prompt("What exactly would you like to fix?");
if (subject == null||subject == null||name == null) {
alert("One or more catagory was cancelled");
if (name == null) {
alert("when answering name, if you would like to have no name click ok without typing and not cancel");
}
}
else {
break;
}
}
subject = "Fix: " + subject + " From: " + name;
body = "A user has requested to fix: " + body;
var popupBlockerChecker = {
check: function(popup_window) {
var _scope = this;
if (popup_window) {
if(/chrome/.test(navigator.userAgent.toLowerCase())){
setTimeout(function () {
_scope._is_popup_blocked(_scope, popup_window);
},200);
}else{
popup_window.onload = function () {
_scope._is_popup_blocked(_scope, popup_window);
};
}
}else {
_scope._displayError();
}
},
_is_popup_blocked: function(scope, popup_window) {
if ((popup_window.innerHeight > 0)==false){ scope._displayError(); }
},
_displayError: function(){
alert("Popup Blocker is enabled! Please add this site to your exception list.");
}
};
var popup = window.open("mailto:[email protected]" + "?subject=" + subject + "&body=" + body);
popupBlockerChecker.check(popup);
}
}
|
package org.dstadler.csv.fuzz;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import com.code_intelligence.jazzer.api.FuzzedDataProvider;
class FuzzComplexTest {
@Test
public void test() {
FuzzedDataProvider provider = mock(FuzzedDataProvider.class);
FuzzComplex.fuzzerTestOneInput(provider);
when(provider.consumeRemainingAsBytes()).thenReturn("abc".getBytes(StandardCharsets.UTF_8));
FuzzComplex.fuzzerTestOneInput(provider);
}
} |
import 'package:dlxapp/apps/saucetv/MediaController.dart';
import 'package:dlxapp/apps/saucetv/components/PlaybackControls.dart';
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/widgets.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';
class NowPlayingDraggable extends StatefulWidget {
final Widget child;
NowPlayingDraggable({this.child});
@override
_NowPlayingDraggableState createState() => _NowPlayingDraggableState();
}
class _NowPlayingDraggableState extends State<NowPlayingDraggable>
with SingleTickerProviderStateMixin {
AnimationController _controller;
/// The alignment of the card as it is dragged or being animated.
///
/// While the card is being dragged, this value is set to the values computed
/// in the GestureDetector onPanUpdate callback. If the animation is running,
/// this value is set to the value of the [_animation].
Alignment _bottomAlignment = Alignment(0.0, 0.8666);
Alignment _topAlignment = Alignment.topCenter;
Alignment _dragAlignment;
bool _finalTop = false;
Animation<Alignment> _animation;
/// Calculates and runs a [SpringSimulation].
void _runAnimation(Offset pixelsPerSecond, Size size) {
_animation = _controller.drive(
AlignmentTween(
begin: _dragAlignment,
// end: Alignment.center,
end: _finalTop ? _topAlignment : _bottomAlignment),
);
// Calculate the velocity relative to the unit interval, [0,1],
// used by the animation controller.
final unitsPerSecondX = pixelsPerSecond.dx / size.width;
final unitsPerSecondY = pixelsPerSecond.dy / size.height;
final unitsPerSecond = Offset(unitsPerSecondX, unitsPerSecondY);
final unitVelocity = unitsPerSecond.distance;
const spring = SpringDescription(
mass: 30,
stiffness: 1,
damping: 1,
);
final simulation = SpringSimulation(spring, 0, 1, -unitVelocity);
_controller.animateWith(simulation);
}
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this);
_dragAlignment = _bottomAlignment;
_controller.addListener(() {
setState(() {
_dragAlignment = _animation.value;
});
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
var log = Logger();
double containerWidth = 6000;
double containerHeight = 80;
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return GestureDetector(
onDoubleTap: () {
// setState(() {
// _finalTop = !_finalTop;
// _runAnimation(Offset(0, 30), size);
// });
},
onPanDown: (details) {
_controller.stop();
},
onPanUpdate: (details) {
setState(() {
_dragAlignment += Alignment(
details.delta.dx / (size.width / 2),
details.delta.dy / (size.height - 80 / 2),
);
// log.i(_dragAlignment.y);
// log.e(_dragAlignment.y > -0.8 && _dragAlignment.y < -0.3 && _dragAlignment.y < 0);
if (_dragAlignment.y > -0.8 &&
_dragAlignment.y < -0.3 &&
_dragAlignment.y < 0) {
_finalTop = false;
// containerHeight = size.height;
} else if (_dragAlignment.y < 1 && _dragAlignment.y > 0.3) {
_finalTop = true;
}
// log.e((_dragAlignment.y * 10000) / 80);
});
},
onPanEnd: (details) {
// log.wtf(details);
_runAnimation(details.velocity.pixelsPerSecond, size);
},
child: Align(
alignment: _dragAlignment,
child: AnimatedContainer(
// Use the properties stored in the State class.
width: containerWidth,
height: containerHeight,
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10), topRight: Radius.circular(10)),
),
// Define how long the animation should take.
duration: Duration(seconds: 1),
// Provide an optional curve to make the animation feel smoother.
curve: Curves.fastOutSlowIn,
padding: EdgeInsets.all(8),
child: Row(
children: <Widget>[
//
// Video/Cover Art
//
AspectRatio(
aspectRatio: 16 / 9,
child: Consumer<MediaController>(
builder: (context, mediaController, child) {
var log = Logger();
// log.i(mediaController.controller.value.position);
return Container(
color: Colors.lightBlueAccent,
);
// return VideoPlayer(mediaController.controller);
},
),
),
//
// Meta Data
//
SizedBox(
width: 16,
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Title', style: Theme.of(context).textTheme.title
// .copyWith(fontSize: 16),
),
Text('Subtitle',
style: Theme.of(context).textTheme.subtitle.copyWith(
color: Colors.white.withOpacity(.7), fontSize: 12)),
],
),
//
// Controls
//
Flexible(
flex: 1,
child: Container(),
),
Row(
children: <Widget>[
// IconButton(
// onPressed: () {},
// icon: Icon(Icons.skip_previous),
// ),
PlayPauseButton(),
IconButton(
onPressed: () {},
icon: Icon(Icons.skip_next),
),
],
),
SizedBox(
width: 16,
)
],
),
)),
);
}
}
|
% Acting on Data
The patterns for Acting on Data provide solutions for performing actions on
lists of data, individual data objects, and object metadata. You may enable
these actions in the Action Bar of any panel within your app.
The Action Bar provides a consistent location for actions performed in the
context of the current panel or current state of the panel. Common actions
include: Filter, Sort, Search, Edit, Move, Delete, Switch View, Share To, Add
To, Favorite, Download, Buy, Rent, etc.
While, in general, actions should be placed in the Action Bar whenever possible,
there are times when it makes more sense to present actions either inline or on
top of fullscreen content.
If Inline Actions are needed, they should appear close to the focused object.
When presenting a list of objects, choose familiar icons or standard text
buttons that are only displayed when the actionable object receives focus. When
you need to place actions near an object that is both not in a list and not the
primary object in the panel, use a contextual popup.
When displaying fullscreen content, actions (e.g., Share To, Add To, Record,
Favorite, Queue, Slideshow) should be included with the playback controls.
Fullscreen Content Actions may open popups with additional sets of actions if
needed (e.g., "Share to Facebook" controls or recording options).
webOS Moonstone icons for common actions will soon be available for download.
## Patterns for Acting on Data
* [Sort and Filter](acting-on-data/sort-and-filter.html) (Action Menu)
* [Multi-Select Mode](acting-on-data/multi-select-mode.html) (Share To, Add To,
Delete, Favorite, etc.)
* [Edit Mode](acting-on-data/edit-mode.html) (Move)
## Related Topics
Patterns: Lists and Grids
Controls: [Header/List Actions](../controls/header-list-actions.html)
|
<?php
use TheClinicDataStructures\DataStructures\User\DSUser;
$privileges = [
"accountsRead",
"accountRead",
"selfAccountRead",
"accountCreate",
"accountDelete",
"selfAccountDelete",
"accountUpdate",
"selfAccountUpdate",
"selfLaserOrdersRead",
"selfLaserOrderCreate",
"selfLaserOrderDelete",
"selfRegularOrdersRead",
"selfRegularOrderCreate",
"selfRegularOrderDelete",
"regularOrdersRead",
"regularOrderCreate",
"regularOrderDelete",
"laserOrderCreate",
"laserOrderDelete",
"laserOrdersRead",
"selfLaserVisitRetrieve",
"selfLaserVisitCreate",
"selfLaserVisitDelete",
"selfRegularVisitRetrieve",
"selfRegularVisitCreate",
"selfRegularVisitDelete",
"laserVisitRetrieve",
"laserVisitCreate",
"laserVisitDelete",
"regularVisitRetrieve",
"regularVisitCreate",
"regularVisitDelete",
];
$namespace = "TheClinicDataStructures\\DataStructures\\User\\";
/** @var string[] $attributes */
$attributes = [];
foreach (scandir(__DIR__ . '/../') as $value) {
if (in_array($value, ['.', '..', 'ICheckAuthentication.php']) || is_dir(__DIR__ . '/../' . $value)) {
continue;
}
$value = array_reverse(explode('/', str_replace("\\", '/', $value)))[0];
$value = str_replace('.php', '', $value);
$class = $namespace . $value;
if (!class_exists($class)) {
throw new \RuntimeException('Failure!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', 500);
}
if (
(new \ReflectionClass($class))->getParentClass() === false ||
(
(new \ReflectionClass($class))->getParentClass() !== false &&
(new \ReflectionClass($class))->getParentClass()->getName() !== DSUser::class
)
) {
continue;
}
foreach ($class::getAttributes() as $attribute => $types) {
if ($attribute === 'ruleName') {
continue;
}
foreach ($types as $type) {
if (strpos($type, 'TheClinicDataStructures') !== false) {
continue 2;
}
}
if (array_search($attribute, $attributes) === false) {
$attributes[] = $attribute;
}
}
}
$updatePrivileges = [];
$selfUpdatePrivileges = [];
foreach ($attributes as $attribute) {
$updatePrivileges[] = 'accountUpdate' . ucfirst($attribute);
$selfUpdatePrivileges[] = 'selfAccountUpdate' . ucfirst($attribute);
}
$privileges = array_merge($privileges, $updatePrivileges, $selfUpdatePrivileges);
return $privileges;
|
DO
$$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns
WHERE table_schema=current_schema AND table_name = 'encrypted_secret' AND column_name = 'secret_type') THEN
ALTER TABLE "encrypted_secret" ALTER COLUMN "secret_type" type VARCHAR(255);
END IF;
END;
$$ |
[VisibleToOtherModulesAttribute] // RVA: 0xC1B30 Offset: 0xC1C31 VA: 0xC1B30
internal enum CodegenOptions // TypeDefIndex: 2766
{
// Fields
public int value__; // 0x0
public const CodegenOptions Auto = 0;
public const CodegenOptions Custom = 1;
public const CodegenOptions Force = 2;
}
|
print "Wpisz wartość liczby a: "
a = gets.chomp().to_f
print "Wpisz wartośc liczby b: "
b = gets.chomp().to_f
def nwd(k, n)
while k != n
if k > n
k -= n
else
n -= k
end
end
return k
end
def nww(k, n)
result = nwd(k, n)
return (k * n) / result
end
puts "NWD: #{ nwd(a, b) }"
puts "NWW: #{ nww(a, b) }" |
// import action constants
import {
PAGE_SET_DB_SOURCE,
PAGE_PAGINATE, PAGE_PAGINATE_NETWORK_BEGINN, PAGE_PAGINATE_NETWORK_END, PAGE_PROCESS_ARTICLES_SUCCESS, PAGE_RELOAD,
PAGE_RELOAD_FINISHED, PAGE_REQUEST, PAGE_REQUEST_FAILURE, PAGE_REQUEST_SUCCESS
} from './../actions/pages';
import {PAGE_PROCESS_ARTICLES_FAILURE} from "../actions/pages";
const initialPageState = {
isReloading: false,
isLoading: false,
isFetching: false,
pageNumber: 1,
nextPageToken: undefined,
articles: [],
};
const initialPagesByBlogAndCategory = {};
function page(state = initialPageState, action) {
switch (action.type) {
case PAGE_SET_DB_SOURCE: {
return Object.assign({}, state, {
articles: action.articles
});
}
case PAGE_RELOAD: {
return Object.assign({}, state, {
isReloading: true,
pageNumber: 1,
nextPageToken: undefined,
});
}
case PAGE_RELOAD_FINISHED: {
return Object.assign({}, state, {
isReloading: false,
lastReload: action.timestamp,
});
}
case PAGE_PAGINATE: {
return Object.assign({}, state, {
pageNumber: action.nextPage,
lastPaginate: action.timestamp,
});
}
case PAGE_PAGINATE_NETWORK_BEGINN: {
return Object.assign({}, state, {
isLoading: true,
});
}
case PAGE_PAGINATE_NETWORK_END: {
return Object.assign({}, state, {
isLoading: false,
lastNetworkPaginate: action.timestamp,
});
}
case PAGE_REQUEST: {
return Object.assign({}, state, {
isFetching: true,
});
}
case PAGE_REQUEST_SUCCESS: {
return Object.assign({}, state, {
isFetching: false,
etag: action.etag,
error: undefined,
nextPageToken: action.nextPageToken,
lastRequest: action.timestamp,
});
}
case PAGE_REQUEST_FAILURE: {
return Object.assign({}, state, {
isFetching: false,
error: action.error,
lastRequestError: action.timestamp,
});
}
case PAGE_PROCESS_ARTICLES_SUCCESS:
case PAGE_PROCESS_ARTICLES_FAILURE: {
return Object.assign({}, state, {
error: action.error,
lastArticleProcessing: action.timestamp,
});
}
default: {
return state;
}
}
}
function pagesByBlogAndCategory(state = initialPagesByBlogAndCategory, action) {
switch (action.type) {
case PAGE_SET_DB_SOURCE:
case PAGE_RELOAD:
case PAGE_RELOAD_FINISHED:
case PAGE_PAGINATE:
case PAGE_PAGINATE_NETWORK_BEGINN:
case PAGE_PAGINATE_NETWORK_END:
case PAGE_REQUEST:
case PAGE_REQUEST_SUCCESS:
case PAGE_REQUEST_FAILURE:
case PAGE_PROCESS_ARTICLES_SUCCESS:
case PAGE_PROCESS_ARTICLES_FAILURE: {
const { blogId, category } = action;
const selector = !category ? blogId : blogId + '_' + category;
return Object.assign({}, state, {
[selector]: page(state[selector], action),
});
}
default: {
return state;
}
}
}
export default pagesByBlogAndCategory; |
module Aula13 where
import Control.Applicative
-- um data constructor com value constructor de mesmo nome,
-- dois campos usando record syntax
data Produtoz = Produtoz {produtozNome :: String,
produtozValor :: Double
} deriving Show
-- EX. 1 (COBRAR MEIO PONTO NA PROVA)
-- let f = Just (\x -> x + 1)
-- f <*> Just 5 = Just 6
{--
f com funtor e x com funtor = <*>
f sem funtor e x com funtor = <$>
f sem funtor e x sem funtor = $ ou nada
--}
-- let soma = \x y -> x+y = soma 5 3 = 8
-- let f = Just soma (soma ficou dentro de um funtor)
-- f <*> Just 5 <*> Just 3 = Just 8
-- quanto mais parametro na função colocar <*>
{--
soma <$> Just 5 <*> Just 3
usa-se <$> pois soma está sem funtor
f <*> Just 5 <*> Just 3,
usa-se <*> pois f possui funtor
===================================
(soma <$> Just 5) <*> Just 3
soma <$> Just 5 = (<$> Just 5 entra no LAMBDA)
(\x y -> x + y) <$> Just 5 =
Just ((\x y -> x + y) 5) =
Just (\y -> 5 + y)
==================================
Produtoz <$> (Just "Algo valido") <*> (Just 1200)
Just (Produtoz {produtozNome = "Algo valido", produtozValor = 1200.0})
Produto estava fora do Just, então o Produto todo foi para dentro do Just
--} |
enumerate start length =
if length == 0
then []
else start : enumerate (start + 1) (length - 1)
main = do
print $ enumerate 6 10 |
---
layout: post
title: Dark theme
comments: false
---
<p style="text-align:justify;">
Add dark theme to my webpage.
</p>
The website contains a slider allowing user to switch between **light** ore **dark** theme:
```html
<label class="theme-switch" for="checkbox">
<input type="checkbox" id="checkbox" />
<div class="slider round"></div>
</label>
<em>Dark theme</em>
```
The following CSS code allow style switch:
```css
:root {
--body-bg-color: #fff;
--body-font-color: #333;
--h1-font-color: #333;
--a-font-color: #4183C4;
--footer-bg-color: #eee;
}
[theme="dark"] {
--body-bg-color: #161625;
--body-font-color: #e1e1ff;
--h1-font-color: #49fb35;
--a-font-color: #9A97FA;
--footer-bg-color: #42408F;
}
```
For more information about the javascript code behind, look a the [code](https://github.com/veben/veben.github.io)
|
require 'vagrant/plugins/berkshelf/vagrant'
module Berkshelf
module Vagrant
class Plugin < ::Vagrant.plugin("2")
name "berkshelf"
description <<-DESC
Automatically make available cookbooks to virtual machines provisioned by Chef Solo
or Chef Client using Berkshelf.
DESC
[:machine_action_up, :machine_action_reload, :machine_action_provision].each do |action|
action_hook(:berkshelf_provision, action) do |hook|
hook.after(::Vagrant::Action::Builtin::ConfigValidate, Action.setup)
hook.before(::Vagrant::Action::Builtin::Provision, Action.install)
end
end
action_hook(:berkshelf_cleanup, :machine_action_destroy) do |hook|
hook.before(::Vagrant::Action::Builtin::DestroyConfirm, Action.clean)
hook.before(::Vagrant::Action::Builtin::DestroyConfirm, Action.setup)
end
config(:berkshelf) do
Berkshelf::Vagrant::Config
end
command "berks-ls" do
require_relative "command/list"
Command::List
end
end
end
end
|
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cosmwasm_std::{Binary, CosmosMsg, CustomQuery, HumanAddr, QueryRequest};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InitMsg {}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HandleMsg {
ReflectMsg { msgs: Vec<CosmosMsg<CustomMsg>> },
ChangeOwner { owner: HumanAddr },
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
Owner {},
/// This will call out to SpecialQuery::Capitalized
Capitalized {
text: String,
},
/// Queries the blockchain and returns the result untouched
Chain {
request: QueryRequest<SpecialQuery>,
},
/// Queries another contract and returns the data
Raw {
contract: HumanAddr,
key: Binary,
},
}
// We define a custom struct for each query response
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct OwnerResponse {
pub owner: HumanAddr,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct CapitalizedResponse {
pub text: String,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct ChainResponse {
pub data: Binary,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct RawResponse {
/// The returned value of the raw query. Empty data can be the
/// result of a non-existent key or an empty value. We cannot
/// differentiate those two cases in cross contract queries.
pub data: Binary,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
/// CustomMsg is an override of CosmosMsg::Custom to show this works and can be extended in the contract
pub enum CustomMsg {
Debug(String),
Raw(Binary),
}
impl Into<CosmosMsg<CustomMsg>> for CustomMsg {
fn into(self) -> CosmosMsg<CustomMsg> {
CosmosMsg::Custom(self)
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
/// An implementation of QueryRequest::Custom to show this works and can be extended in the contract
pub enum SpecialQuery {
Ping {},
Capitalized { text: String },
}
impl CustomQuery for SpecialQuery {}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
/// The response data for all `SpecialQuery`s
pub struct SpecialResponse {
pub msg: String,
}
|
using System.Collections.Generic;
using UnityEngine;
public static class CreateCurvedMeshBake
{
public static Mesh BakedMesh(CreateCurvedGrass.MeshCluster cluster, int maxAllowedVertices)
{
Mesh baseMesh = cluster.clusterMesh;
float clusterArea = cluster.clusterArea;
float clusterHeight = cluster.clusterHeigth;
float clusterRandomHeightVariation = cluster.clusterRandomHeightVariation;
float clusterScale = cluster.clusterScale;
float clusterRandomScale = cluster.clusterRandomScale;
Color clusterColor = cluster.clusterColor;
CreateCurvedGrass.CLUSTER_TYPE clusterType = cluster.clusterType;
List<CreateCurvedGrass.NodeInfo> nodes = cluster.clusterLine;
if (baseMesh.vertexCount > maxAllowedVertices)
{
Debug.LogError("Select a smaller mesh!");
return null;
}
//Create Mesh
Mesh mesh = new Mesh();
//Amount
int nodesCount = nodes.Count;
int scatterMaxAmount = 0;
for (int i = 0; i < nodesCount - 1; i++)
{
scatterMaxAmount += nodes[i].scatterAmount;
}
int amount = scatterMaxAmount;
//Line Information Position
List<Vector3> linePositionScatter = new List<Vector3>();
int arrayIndex = 0;
int nodeIndex = 0;
for (int i = 0; i < amount; i++)
{
Vector3 pos = Vector3.Lerp(nodes[arrayIndex].nodePosition, nodes[arrayIndex + 1].nodePosition,
(float) nodeIndex / nodes[arrayIndex].scatterAmount);
linePositionScatter.Add(pos);
nodeIndex++;
if (nodes[arrayIndex].scatterAmount == 0)
{
nodeIndex = 0;
if (arrayIndex < nodesCount - 2)
{
arrayIndex++;
}
}
else if (nodeIndex % nodes[arrayIndex].scatterAmount == 0)
{
nodeIndex = 0;
if (arrayIndex < nodesCount - 2)
{
arrayIndex++;
}
}
}
//Last one should be in last node
if (linePositionScatter.Count > 2)
{
linePositionScatter[linePositionScatter.Count - 1] = nodes[nodes.Count - 1].nodePosition;
}
//Vertices
Vector3[] vertices = new Vector3[baseMesh.vertices.Length * amount];
Vector3[] baseVertices = baseMesh.vertices;
int baseVerticesIndex = 0;
//Random Height
float randomHeight = Random.Range(1f, clusterRandomHeightVariation);
//Random Scale
float randomScale = Random.Range(1f, clusterRandomScale);
//Vertex ID and Pivot Point
Vector4[] tangents = new Vector4[baseMesh.vertices.Length * amount];
//Area Position
float randonXPosision = 0;
float randonZPosision = 0;
float width = clusterArea;
//Rotation
float rotYRandom = Random.Range(-90f, 90f);
float rotXRandom = Random.Range(-90f, 90f);
float rotZRandom = Random.Range(-90f, 90f);
arrayIndex = 0;
for (int i = 0; i < vertices.Length; i++)
{
//Copy base vertices position
vertices[i] = baseVertices[baseVerticesIndex];
Vector3 vertexPosition = vertices[i];
//Rotation
if (cluster.clusterRandomRotate)
{
switch (cluster.clusterType)
{
case CreateCurvedGrass.CLUSTER_TYPE.grass:
//Rotate Y only
vertexPosition = Quaternion.Euler(0, rotYRandom, 0) * vertexPosition;
break;
case CreateCurvedGrass.CLUSTER_TYPE.particle:
//Rotate All
vertexPosition = Quaternion.Euler(rotXRandom, rotYRandom, rotZRandom) * vertexPosition;
break;
case CreateCurvedGrass.CLUSTER_TYPE.fixedObject:
vertexPosition = Quaternion.Euler(0, rotYRandom, 0) * vertexPosition;
break;
default:
break;
}
}
else
{
//Try to Follow Line, im bad with quaternions
if (arrayIndex < linePositionScatter.Count - 1)
{
Vector3 direction = (linePositionScatter[arrayIndex + 1] - linePositionScatter[arrayIndex]);
Quaternion rot =
Quaternion.LookRotation(Vector3.RotateTowards(Vector3.forward, direction.normalized, Mathf.PI,
0));
vertexPosition = rot * vertexPosition;
}
else if (arrayIndex >= linePositionScatter.Count - 1)
{
//Fix Last object
Vector3 direction = (linePositionScatter[arrayIndex] - linePositionScatter[arrayIndex - 1]);
Quaternion rot =
Quaternion.LookRotation(Vector3.RotateTowards(Vector3.forward, direction.normalized, Mathf.PI,
0));
vertexPosition = rot * vertexPosition;
}
}
//Scale
switch (cluster.clusterType)
{
case CreateCurvedGrass.CLUSTER_TYPE.grass:
//Add Random height
vertexPosition *= clusterScale;
vertexPosition *= randomScale;
vertexPosition.y *= clusterHeight;
vertexPosition.y *= randomHeight;
break;
case CreateCurvedGrass.CLUSTER_TYPE.particle:
//Fall
case CreateCurvedGrass.CLUSTER_TYPE.particleFall:
//Add random Scale All
vertexPosition *= clusterScale;
vertexPosition *= randomScale;
vertexPosition.y *= clusterHeight;
vertexPosition.y *= randomHeight;
break;
case CreateCurvedGrass.CLUSTER_TYPE.fixedObject:
//Add Fixed Value
vertexPosition *= clusterScale;
vertexPosition *= randomScale;
vertexPosition.y *= clusterHeight;
vertexPosition.y *= randomHeight;
break;
default:
break;
}
//Position
vertexPosition.x += (linePositionScatter[arrayIndex].x + randonXPosision);
vertexPosition.y += (linePositionScatter[arrayIndex].y);
vertexPosition.z += (linePositionScatter[arrayIndex].z + randonZPosision);
//Set
vertices[i].x = vertexPosition.x;
vertices[i].y = vertexPosition.y;
vertices[i].z = vertexPosition.z;
//Pivot ID
tangents[i] = new Vector4((int) clusterType, (linePositionScatter[arrayIndex].x + randonXPosision),
(linePositionScatter[arrayIndex].y), (linePositionScatter[arrayIndex].z + randonZPosision));
baseVerticesIndex++;
//Set Next batch
if (baseVerticesIndex % baseMesh.vertices.Length == 0)
{
//Height Variation
randomHeight = Random.Range(1f, clusterRandomHeightVariation);
//Scale Variation
randomScale = Random.Range(1f, clusterRandomScale);
//Set new random position and rotation for next batch
randonXPosision = Random.Range(-width / 2f, width / 2f);
randonZPosision = Random.Range(-width / 2f, width / 2f);
//Rotation for next Batch
if (cluster.clusterRandomRotate)
{
rotXRandom = Random.Range(-90f, 90f);
rotYRandom = Random.Range(-90f, 90f);
rotZRandom = Random.Range(-90f, 90f);
}
baseVerticesIndex = 0;
arrayIndex++;
}
}
mesh.vertices = vertices;
// 4 triangles * 3 vertices (Make a triangles) = 12
int[] triangles = new int[baseMesh.triangles.Length * amount];
int[] baseTriangles = baseMesh.triangles;
int baseTriangleIndex = 0;
for (int i = 0; i < triangles.Length; i++)
{
triangles[i] = baseTriangles[baseTriangleIndex];
baseTriangleIndex++;
if (baseTriangleIndex % baseTriangles.Length == 0)
{
baseTriangleIndex = 0;
for (int j = 0; j < baseTriangles.Length; j++)
{
baseTriangles[j] += baseMesh.vertexCount;
}
}
}
mesh.triangles = triangles;
//UV
Vector2[] uvs = new Vector2[baseMesh.vertices.Length * amount];
Vector2[] baseUV = baseMesh.uv;
int baseUvsIndex = 0;
for (int i = 0; i < uvs.Length; i++)
{
uvs[i] = baseUV[baseUvsIndex];
baseUvsIndex++;
if (baseUvsIndex % baseMesh.vertices.Length == 0)
{
baseUvsIndex = 0;
}
}
mesh.uv = uvs;
//Normals
Vector3[] normals = new Vector3[baseMesh.vertices.Length * amount];
for (int i = 0; i < normals.Length; i++)
{
normals[i] = Vector3.up;
}
mesh.normals = normals;
//Vertex Color
float blueRandom = Random.Range(0f, 1f);
Color[] vertexFinalColor;
//Particle
Color[] vertexColor = new Color[baseMesh.vertexCount * amount];
int baseVertexColorIndex = 0;
for (int i = 0; i < vertexColor.Length; i++)
{
vertexColor[i].r = clusterColor.r;
vertexColor[i].g = clusterColor.g;
vertexColor[i].b = clusterColor.b;
vertexColor[i].a = blueRandom; // A is random offset
baseVertexColorIndex++;
if (baseVertexColorIndex % baseMesh.vertexCount == 0)
{
blueRandom = Random.Range(0f, 1f);
baseVertexColorIndex = 0;
}
}
vertexFinalColor = vertexColor;
mesh.colors = vertexFinalColor;
//Use Tangents for ID and Pivot
mesh.tangents = tangents;
return mesh;
}
}
|
package encoder
import (
"log"
"github.com/giongto35/cloud-game/v2/pkg/encoder/yuv"
)
type VideoPipe struct {
Input chan InFrame
Output chan OutFrame
done chan struct{}
encoder Encoder
// frame size
w, h int
}
// NewVideoPipe returns new video encoder pipe.
// By default it waits for RGBA images on the input channel,
// converts them into YUV I420 format,
// encodes with provided video encoder, and
// puts the result into the output channel.
func NewVideoPipe(enc Encoder, w, h int) *VideoPipe {
return &VideoPipe{
Input: make(chan InFrame, 1),
Output: make(chan OutFrame, 2),
done: make(chan struct{}),
encoder: enc,
w: w,
h: h,
}
}
// Start begins video encoding pipe.
// Should be wrapped into a goroutine.
func (vp *VideoPipe) Start() {
defer func() {
if r := recover(); r != nil {
log.Println("Warn: Recovered panic in encoding ", r)
}
close(vp.Output)
close(vp.done)
}()
yuvProc := yuv.NewYuvImgProcessor(vp.w, vp.h)
for img := range vp.Input {
yCbCr := yuvProc.Process(img.Image).Get()
frame := vp.encoder.Encode(yCbCr)
if len(frame) > 0 {
vp.Output <- OutFrame{Data: frame, Timestamp: img.Timestamp}
}
}
}
func (vp *VideoPipe) Stop() {
close(vp.Input)
<-vp.done
if err := vp.encoder.Shutdown(); err != nil {
log.Println("error: failed to close the encoder")
}
}
|
<!-- Sidebar menu-->
<div class="app-sidebar__overlay" data-toggle="sidebar"></div>
<aside class="app-sidebar">
<!-- Images -->
<div class="app-sidebar__user">
<img class="app-sidebar__user-avatar" src="<?php echo base_url() ?>assets/images/logo.png" alt="Rental Mobil">
<div>
<p class="app-sidebar__user-name">PT. KELOMPOK V</p>
<p class="app-sidebar__user-designation">© 2019</p>
</div>
</div>
<ul class="app-menu">
<!-- Menu Dashboard -->
<li>
<a class="app-menu__item" href="#">
<i class="app-menu__icon fa fa-dashboard"></i>
<span class="app-menu__label">Dashboard</span>
</a>
</li>
<!-- Menu Users -->
<li>
<a class="app-menu__item" href="<?= base_url('user') ?>">
<i class="app-menu__icon fa fa-user"></i>
<span class="app-menu__label">Users</span>
</a>
</li>
<!-- Menu Logout -->
<li>
<a class="app-menu__item" href="<?= base_url('product') ?>">
<i class="app-menu__icon fa fa-folder"></i>
<span class="app-menu__label">Product</span>
</a>
</li>
<!-- Menu Logout -->
<li>
<a class="app-menu__item" href="<?= base_url('auth/logout/'.$data['role']) ?>">
<i class="app-menu__icon fa fa-sign-out"></i>
<span class="app-menu__label">Logout</span>
</a>
</li>
</ul>
</aside> |
---
title: Backpropagation
localeTitle: 反向传播
---
## 反向传播
Backprogapation是[神经网络](../neural-networks/index.md)的子主题,是计算网络中每个节点的梯度的过程。这些梯度测量每个节点对输出层有贡献的“误差”,因此在训练神经网络时,这些梯度被最小化。
注意:反向传播和机器学习一般需要非常熟悉线性代数和矩阵操作。在尝试理解本文的内容之前,强烈建议您阅读或阅读此主题。
### 计算
反向传播的过程可以分三个步骤来解释。
鉴于以下内容
* m个L层神经网络的训练样例(x,y)
* g = sigmoid函数
* Theta(i)=从第i层到第i + 1层的过渡矩阵
* a(l)= g(z(l));基于一个训练示例的层l中的节点的值的数组
* z(l)= Theta(l-1)a(l-1)
* Delta一组L矩阵表示第i层和第i + 1层之间的过渡
* d(l)=一个训练示例的层l的梯度阵列
* D一组L矩阵,每个节点具有最终梯度
* lambda网络的规范化术语
在这种情况下,对于矩阵M,M'将表示矩阵M的转置
1. 分配Delta(i)的所有条目,对于i,从1到L,为零。
2. 对于从1到m的每个训练示例t,执行以下操作:
* 在每个示例上执行前向传播以计算每个层的(1)和z(l)
* 计算d(L)= a(L) - y(t)
* 计算d(l)=(Theta(l)'•d(l + 1))•g(z(l))表示l从L-1到1
* 增量Delta(l)乘以delta(l + 1)•a(l)'
1. 将Delta matricies插入我们的偏导数矩阵中 D(l)= 1 \\ m(Delta(1)+ lambda·Theta(l));如果l≠0 D(l)= 1 \\ m•Delta(l);如果l = 0
当然,只是看到这篇文章看起来非常复杂,应该只在神经网络和机器学习的更大背景下理解。请查看加密的参考资料,以便更好地理解整个主题。
#### 更多信息:
* [第4讲CS231n神经网络简介](https://youtu.be/d14TUNcbn1k?t=354)
* [Siraj Raval - 5分钟内的反向传播](https://www.youtube.com/watch?v=q555kfIFUCM)
* [Andrew Ng的ML课程](https://www.coursera.org/learn/machine-learning/)
* [深入,维基风格的文章](https://brilliant.org/wiki/backpropagation/)
* [维基百科上的Backprop](https://en.wikipedia.org/wiki/Backpropagation)
* [逐步反向传播示例](https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/) |
/*
* Copyright 2021 IBM Corp.
* SPDX-License-Identifier: Apache-2.0
*/
package org.apache.spark.sql.execution.datasources.xskipper
import io.xskipper.Registration
import io.xskipper.configuration.XskipperConf
import io.xskipper.metadatastore.MetadataStoreManager
import io.xskipper.search.{DataSkippingFileFilter, DataSkippingFileFilterEvaluator}
import io.xskipper.utils.Utils
import org.apache.hadoop.fs.Path
import org.apache.spark.internal.Logging
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.datasources._
import org.apache.spark.sql.execution.streaming.{FileStreamSink, MetadataLogFileIndex}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import scala.collection.JavaConverters._
object DataSkippingUtils extends Logging {
/**
* This function contains the same logic for creating the FileIndex as appears in
* FileTable class and replaces the InMemoryFileIndex with
* InMemoryDataSkippingIndex.
* The reason for keeping the same logic is that the original variable is lazy
* so we can rely on not having the FileIndex created until this function is called.
*/
def getFileIndex(sparkSession: SparkSession,
options: CaseInsensitiveStringMap,
paths: Seq[String],
userSpecifiedSchema: Option[StructType],
isDataSourceV2: Boolean = true): PartitioningAwareFileIndex = {
val caseSensitiveMap = options.asCaseSensitiveMap.asScala.toMap
// Hadoop Configurations are case sensitive.
val hadoopConf = sparkSession.sessionState.newHadoopConfWithOptions(caseSensitiveMap)
if (FileStreamSink.hasMetadata(paths, hadoopConf, sparkSession.sessionState.conf)) {
// We are reading from the results of a streaming query. We will load files from
// the metadata log instead of listing them using HDFS APIs.
new MetadataLogFileIndex(sparkSession, new Path(paths.head),
options.asScala.toMap, userSpecifiedSchema)
} else {
// This is a non-streaming file based datasource.
val globPaths = Option(options.get(DataSource.GLOB_PATHS_KEY))
.map(_ == "true").getOrElse(true)
val rootPathsSpecified = DataSource.checkAndGlobPathIfNecessary(paths, hadoopConf,
checkEmptyGlobPath = true, checkFilesExist = true, enableGlobbing = globPaths)
val fileStatusCache = FileStatusCache.getOrCreate(sparkSession)
val fileIndex = new InMemoryFileIndex(
sparkSession, rootPathsSpecified, caseSensitiveMap, userSpecifiedSchema, fileStatusCache)
val metadataStoreManager = Registration.getActiveMetadataStoreManager()
// TODO: FIX WHEN DATA SOURCE V2 STATS ISSUE IS FIXED
// see https://github.com/xskipper-io/xskipper/issues/79
// if this is a datasource V2, disable the skipped object stats
// since they are unreliable in the presence of joins
if (isDataSourceV2) {
metadataStoreManager.disableSkippedObjectStats()
}
val tableIdentifiers = paths.map(p => Utils.getTableIdentifier(new Path(p).toUri)).distinct
val ff = tableIdentifiers.map(tid => getFileFilter(fileIndex,
tid, metadataStoreManager, sparkSession,
XskipperConf.getConf(XskipperConf.XSKIPPER_EVALUATION_ENABLED)))
new InMemoryDataSkippingIndex(
sparkSession,
rootPathsSpecified,
caseSensitiveMap,
Option(fileIndex.partitionSchema),
fileStatusCache,
None,
None,
tableIdentifiers,
ff,
Registration.getCurrentMetadataFilterFactories(),
Registration.getCurrentClauseTranslators(),
Registration.getActiveMetadataStoreManagerType())
}
}
/**
* Gets an inMemoryFileIndex and reconstructs the FileStatusCache
* The way the FileStatusCache is implemented in spark makes it to not be shareable between
* instances meaning that calling FileStatusCache.getOrCreate(spark) will result in an empty
* cache and thus will require a new listing when the FileIndex is being replaced with a data
* skipping FileIndex.
* To avoid this code reconstructs the cache using the existing FileIndex and then it can be
* used by the new FileIndex.
* Note: the reason we can't get the FileStatusCache of the original inMemoryFileIndex is
* because it is handed over to it in the constructor and is not defined there as var/val
* so we can't access it once we have an instance of inMemoryFileIndex
*
* @param spark a spark session - used to get a new cache
* @param inMemoryFileIndex the inMemoryFileIndex to construct the cache from
* @return a FileStatusCache populated with the root paths from the given inMemoryFileIndex
*/
def recreateFileStatusCache(spark: SparkSession,
inMemoryFileIndex: InMemoryFileIndex): FileStatusCache = {
// reconstructing FileStatusCache to avoid re listing
val fileStatusCache = FileStatusCache.getOrCreate(spark)
inMemoryFileIndex.rootPaths.foreach(path =>
fileStatusCache.putLeafFiles(path,
inMemoryFileIndex.listLeafFiles(Seq(path)).toArray))
fileStatusCache
}
/**
* Gets the DataSkippingFileFilter relevant for this tid, FileIndex and backend
*
* @param fileIndex the fileIndex for which we create a DataSkippingFileFilter
* @param tid the table identifier
* @param metadataStoreManager the backend to be used to create the DataSkippingFileFilter
* @param sparkSession the spark session
* @param evaluate whether we create an evaluate DataSkippingFileFilter which only
* report skipping stats
* @return
*/
def getFileFilter(fileIndex: FileIndex,
tid: String,
metadataStoreManager: MetadataStoreManager,
sparkSession: SparkSession,
evaluate: Boolean = false) : DataSkippingFileFilter = {
if (evaluate) {
new DataSkippingFileFilterEvaluator(
tid,
metadataStoreManager,
sparkSession,
metadataStoreManager.getDataSkippingFileFilterParams(tid, sparkSession, fileIndex))
} else {
new DataSkippingFileFilter(tid,
metadataStoreManager, sparkSession,
metadataStoreManager.getDataSkippingFileFilterParams(tid, sparkSession, fileIndex))
}
}
/**
* Inject a rule as part extendedOperatorOptimizationRule
*/
def injectRuleExtendedOperatorOptimizationRule(
sparkSession: SparkSession,
rule: Rule[LogicalPlan]) : Unit = {
// insert the rule as extendedOperatorOptimizationRule
// Note: if this is called multiple time the rule will be injected multiple times, though it
// won't have effect on the correctness.
// The reason we can't remove an existing rule is because the variable optimizerRules in
// SparkSessionExtensions is private[this].
// Also, another option is to build the optimization rules using the buildOptimizerRules method
// in SparkSessionExtensions and check whether the rule is already there, however,
// this option is not good enough since we don't know if building the existing rules will have
// any side effect.
logInfo(s"Injecting rule ${rule.getClass.getCanonicalName}" +
s" as part of the extended operator optimization rules")
sparkSession.extensions.injectOptimizerRule(_ => rule)
}
}
|
using System;
namespace cv19ResSupportV3.V3.Domain.Commands
{
public class CreateHelpRequestCall
{
public int HelpRequestId { get; set; }
public string CallType { get; set; }
public string CallDirection { get; set; }
public string CallOutcome { get; set; }
public DateTime CallDateTime { get; set; }
public string CallHandler { get; set; }
}
}
|
module ResearchMetadata
# Semantic version number
#
VERSION = "2.1.0"
end
|
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.gameobjects.player;
import com.aionemu.gameserver.model.trade.TradePSItem;
import java.util.LinkedHashMap;
/**
* @author Xav Modified by Simple
*/
public class PrivateStore {
private Player owner;
private LinkedHashMap<Integer, TradePSItem> items;
private String storeMessage;
/**
* This method binds a player to the store and creates a list of items
*
* @param owner
*/
public PrivateStore(Player owner) {
this.owner = owner;
this.items = new LinkedHashMap<Integer, TradePSItem>();
}
/**
* This method will return the owner of the store
*
* @return Player
*/
public Player getOwner() {
return owner;
}
/**
* This method will return the items being sold
*
* @return LinkedHashMap<Integer, TradePSItem>
*/
public LinkedHashMap<Integer, TradePSItem> getSoldItems() {
return items;
}
/**
* This method will add an item to the list and price
*
* @param tradeList
* @param price
*/
public void addItemToSell(int itemObjId, TradePSItem tradeItem) {
items.put(itemObjId, tradeItem);
}
/**
* This method will remove an item from the list
*
* @param item
*/
public void removeItem(int itemObjId) {
if (items.containsKey(itemObjId)) {
LinkedHashMap<Integer, TradePSItem> newItems = new LinkedHashMap<Integer, TradePSItem>();
for (int itemObjIds : items.keySet()) {
if (itemObjId != itemObjIds) {
newItems.put(itemObjIds, items.get(itemObjIds));
}
}
this.items = newItems;
}
}
/**
* @param itemId return tradeItem
*/
public TradePSItem getTradeItemByObjId(int itemObjId) {
return items.get(itemObjId);
}
/**
* @param storeMessage the storeMessage to set
*/
public void setStoreMessage(String storeMessage) {
this.storeMessage = storeMessage;
}
/**
* @return the storeMessage
*/
public String getStoreMessage() {
return storeMessage;
}
}
|
//-----------------------------------------------------------------------
// <copyright file="DialogStateMachine.cs" company="Lost Signal LLC">
// Copyright (c) Lost Signal LLC. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Lost
{
using UnityEngine;
public class DialogStateMachine : StateMachineBehaviour
{
private static readonly int ShownHash = Animator.StringToHash("Show");
private static readonly int HiddenHash = Animator.StringToHash("Hide");
private State state;
public bool IsDoneShowing
{
get { return this.state == State.Shown; }
}
public bool IsDoneHiding
{
get { return this.state == State.Hidden; }
}
public bool IsInitialized
{
get { return this.state == State.Initialized; }
}
public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
base.OnStateUpdate(animator, stateInfo, layerIndex);
if (stateInfo.shortNameHash == ShownHash && stateInfo.normalizedTime >= 1.0f)
{
this.state = State.Shown;
}
else if (stateInfo.shortNameHash == HiddenHash && stateInfo.normalizedTime >= 1.0f)
{
this.state = State.Hidden;
}
}
private enum State
{
Initialized,
Hidden,
Shown,
}
}
}
|
# Component card
Membership hero component
## License
Copyright (c) 2021 Co-operative Group Limited.
Licensed [MIT](https://github.com/coopdigital/coop-frontend/blob/master/LICENSE).
|
from __future__ import print_function
import os
import shutil
import six
import numpy as np
from stompy.io.local import cimis
# os.environ['CIMIS_KEY']='FILL_THIS_IN'
def test_cimis():
"""
Fetch CIMIS data for station 171. This requires a network connection
and defining CIMIS_KEY (freely available application key) in the environment
or above in this file.
"""
# Start anew
print("Get pristine cache dir")
cache_dir='test_cache'
os.path.exists(cache_dir) and shutil.rmtree(cache_dir)
os.mkdir(cache_dir)
print("Fetch first time")
# 2/5/2001 is start of record for union city
period=[np.datetime64('2016-01-01'),
np.datetime64('2016-03-01')]
df=cimis.cimis_fetch_to_xr(171,period[0],period[1],station_meta=True,
days_per_request='10D',cache_dir=cache_dir)
print("Fetch second time")
df2=cimis.cimis_fetch_to_xr(171,period[0],period[1],station_meta=True,
days_per_request='10D',cache_dir=cache_dir)
print("Done")
return df2
|
# Updatable Timer Sample
A helper structure that supports blocking sleep that can be rescheduled at any moment.
Demonstrates:
* Timer and its cancellation
* Signal Channel
* Selector used to wait on both timer and channel
### Steps to run this sample:
1) You need a Temporal service running. See details in README.md
2) Run the following command to start the worker
```
go run updatabletimer/worker/main.go
```
3) Run the following command to start the example
```
go run updatabletimer/starter/main.go
```
4) Run the following command to update the timer wake-up time
```
go run updatabletimer/updater/main.go
``` |
package com.linkedin.android.tachyon
data class DayViewConfig(
val startHour: Int,
val endHour: Int,
val dividerHeight: Int,
val halfHourHeight: Int,
val hourDividerColor: Int,
val halfHourDividerColor: Int,
val hourLabelWidth: Int,
val hourLabelMarginEnd: Int,
val eventMargin: Int
) |
# frozen_string_literal: true
module API
module Entities
class Environment < Entities::EnvironmentBasic
include RequestAwareEntity
include Gitlab::Utils::StrongMemoize
expose :project, using: Entities::BasicProjectDetails
expose :last_deployment, using: Entities::Deployment, if: { last_deployment: true }
expose :state
expose :enable_advanced_logs_querying, if: -> (*) { can_read_pod_logs? } do |environment|
environment.elastic_stack_available?
end
expose :logs_api_path, if: -> (*) { can_read_pod_logs? } do |environment|
if environment.elastic_stack_available?
elasticsearch_project_logs_path(environment.project, environment_name: environment.name, format: :json)
else
k8s_project_logs_path(environment.project, environment_name: environment.name, format: :json)
end
end
expose :gitlab_managed_apps_logs_path, if: -> (*) { can_read_pod_logs? && cluster } do |environment|
::Clusters::ClusterPresenter.new(cluster, current_user: current_user).gitlab_managed_apps_logs_path # rubocop: disable CodeReuse/Presenter
end
private
alias_method :environment, :object
def can_read_pod_logs?
strong_memoize(:can_read_pod_logs) do
current_user&.can?(:read_pod_logs, environment.project)
end
end
def cluster
strong_memoize(:cluster) do
environment&.last_deployment&.cluster
end
end
def current_user
options[:current_user]
end
end
end
end
|
s = Runners::Testing::Smoke
default_version = Runners::VERSION
s.add_test_with_git_metadata(
"success",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "hello.rb",
location: nil,
message: "hello.rb: loc = 7, last commit datetime = 2021-01-01T10:00:00+09:00",
links: [],
object: {
lines_of_code: 7,
last_committed_at: "2021-01-01T10:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"binary_files",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "image.png",
location: nil,
message: "image.png: loc = (no info), last commit datetime = 2021-01-01T13:00:00+09:00",
links: [],
object: {
lines_of_code: nil,
last_committed_at: "2021-01-01T13:00:00+09:00"
},
git_blame_info: nil
}, {
id: "metrics_fileinfo",
path: "no_text.txt",
location: nil,
message: "no_text.txt: loc = (no info), last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: nil,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"unknown_extension",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "foo.my_original_extension",
location: nil,
message: "foo.my_original_extension: loc = 2, last commit datetime = 2021-01-01T11:00:00+09:00",
links: [],
object: {
lines_of_code: 2,
last_committed_at: "2021-01-01T11:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"multi_language",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "euc_jp.txt",
location: nil,
message: "euc_jp.txt: loc = 1, last commit datetime = 2021-01-01T12:00:00+09:00",
links: [],
object: {
lines_of_code: 1,
last_committed_at: "2021-01-01T12:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "iso_2022_jp.txt",
location: nil,
message: "iso_2022_jp.txt: loc = 1, last commit datetime = 2021-01-01T13:00:00+09:00",
links: [],
object: {
lines_of_code: 1,
last_committed_at: "2021-01-01T13:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "shift_jis.txt",
location: nil,
message: "shift_jis.txt: loc = 1, last commit datetime = 2021-01-01T11:00:00+09:00",
links: [],
object: {
lines_of_code: 1,
last_committed_at: "2021-01-01T11:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "utf8.txt",
location: nil,
message: "utf8.txt: loc = 7, last commit datetime = 2021-01-01T10:00:00+09:00",
links: [],
object: {
lines_of_code: 7,
last_committed_at: "2021-01-01T10:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"multi_commit",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "hello.rb",
location: nil,
message: "hello.rb: loc = 9, last commit datetime = 2021-01-01T12:00:00+09:00",
links: [],
object: {
lines_of_code: 9,
last_committed_at: "2021-01-01T12:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"directory_hierarchy",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "README.txt",
location: nil,
message: "README.txt: loc = 2, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 2,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "lib/about_libs.txt",
location: nil,
message: "lib/about_libs.txt: loc = 1, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 1,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "lib/libbar/libbar.rb",
location: nil,
message: "lib/libbar/libbar.rb: loc = 5, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 5,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "lib/libfoo/libfoo.rb",
location: nil,
message: "lib/libfoo/libfoo.rb: loc = 5, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 5,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "src/main.rb",
location: nil,
message: "src/main.rb: loc = 5, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 5,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "src/module_piyo/piyo.rb",
location: nil,
message: "src/module_piyo/piyo.rb: loc = 6, last commit datetime = 2021-01-01T14:00:00+09:00",
links: [],
object: {
lines_of_code: 6,
last_committed_at: "2021-01-01T14:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
s.add_test_with_git_metadata(
"with_ignore_setting",
{ type: "success",
issues: [
{
id: "metrics_fileinfo",
path: "hello.rb",
location: nil,
message: "hello.rb: loc = 7, last commit datetime = 2021-01-01T10:00:00+09:00",
links: [],
object: {
lines_of_code: 7,
last_committed_at: "2021-01-01T10:00:00+09:00"
},
git_blame_info: nil
},
{
id: "metrics_fileinfo",
path: "sider.yml",
location: nil,
message: "sider.yml: loc = 2, last commit datetime = 2021-01-01T10:00:00+09:00",
links: [],
object: {
lines_of_code: 2,
last_committed_at: "2021-01-01T10:00:00+09:00"
},
git_blame_info: nil
}
],
analyzer: { name: "Metrics File Info", version: default_version } }
)
|
use super::{Window, WindowId};
use bevy_utils::HashMap;
#[derive(Default)]
pub struct Windows {
windows: HashMap<WindowId, Window>,
}
impl Windows {
pub fn add(&mut self, window: Window) {
self.windows.insert(window.id, window);
}
pub fn get(&self, id: WindowId) -> Option<&Window> {
self.windows.get(&id)
}
pub fn get_mut(&mut self, id: WindowId) -> Option<&mut Window> {
self.windows.get_mut(&id)
}
pub fn get_primary(&self) -> Option<&Window> {
self.get(WindowId::primary())
}
pub fn iter(&self) -> impl Iterator<Item = &Window> {
self.windows.values()
}
}
|
using BehaviorDesigner.Runtime.Tasks;
namespace Module
{
public class AgentConditional : Conditional, IAgentAction
{
public float GetArgs(int index)
{
return ((AgentBehaviorTree) this.Owner.ExternalBehavior).args[index];
}
}
} |
import 'package:json_annotation/json_annotation.dart';
part 'prediction_stats.g.dart';
@JsonSerializable()
class PredictionStats {
String? databaseName;
String? collectionName;
double? avgObjectSize;
int? dataSize;
Map<String, int>? indexSizes;
Map<String, int>? objectCounts;
int? objectCount;
bool? isOk;
int? storageSize;
int? totalIndexSize;
int? activeCount;
PredictionStats({
this.databaseName,
this.collectionName,
this.avgObjectSize,
this.dataSize,
this.indexSizes,
this.objectCounts,
this.objectCount,
this.isOk,
this.storageSize,
this.totalIndexSize,
this.activeCount,
});
factory PredictionStats.fromJson(
Map<String, dynamic> json,
) =>
_$PredictionStatsFromJson(json);
static List<PredictionStats> listFromJson(
List<dynamic> json,
) =>
json
.map(
(value) => PredictionStats.fromJson(value),
)
.toList();
static Map<String, PredictionStats> mapFromJson(
Map<String, dynamic> json,
) =>
json.map(
(key, value) => MapEntry(
key,
PredictionStats.fromJson(value),
),
);
Map<String, dynamic> toJson() => _$PredictionStatsToJson(this);
}
|
unit Test.REST.Base;
interface
uses
DUnitX.TestFramework, nePimlico.REST.Types;
type
[TestFixture]
TTestRESTBase = class(TObject)
private
fREST: IPimlicoRESTBase;
public
[SetupFixture]
procedure setupFixture;
[Test]
procedure request;
end;
implementation
uses
nePimlico.REST.Base, nePimlico.mService.Types, nePimlico.mService.Base;
{ TTestRESTBase }
procedure TTestRESTBase.request;
var
serv: ImService;
begin
Assert.WillRaise(procedure
begin
fREST.request(nil, '');
end);
serv:=TmServiceBase.Create;
Assert.AreEqual('', fREST.request(serv, ''));
end;
procedure TTestRESTBase.setupFixture;
begin
fREST:=TPimlicoRESTBase.Create;
end;
initialization
TDUnitX.RegisterTestFixture(TTestRESTBase);
end.
|
class C
def to_str
puts 'to_str'
'xxx'
end
end
class Regexp
def =~(*args)
puts "=~#{args}"
end
def !~(*args)
puts "=~#{args}"
end
end
c = C.new
puts '-- match'
/foo/ =~ c
puts '-- not match'
/foo/ !~ c |
---
layout: default
title: frontpage
description: DIVD
---
<!-- Highlights -->
<header class="special">
<h2>our mission</h2>
<p>We aim to make the digital world safer by reporting vulnerabilities we find in digital systems to the people who can fix them. We have a global reach, but do it Dutch style: open, honest, collaborative and for free.</p>
<h2>Our statistics</h2>
{% include stats.html %}
</header>
<div class="highlights">
<section>
<div class="content">
<header>
<a href="/team" class="icon fa-vcard-o"><span class="label">Icon</span></a>
<h3>Team</h3>
</header>
<p>DIVD is a platform for security researchers to report vulnerabilities, supported by volunteers.</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/code" class="icon fa-balance-scale"><span class="label">Icon</span></a>
<h3>Code of Conduct</h3>
</header>
<p>How and why we scan and report.</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/news" class="icon fa-calendar-o"><span class="label">Icon</span></a>
<h3>News & Events</h3>
</header>
<p>Just getting started with some presentations here and there</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/reports" class="icon fa-files-o"><span class="label">Icon</span></a>
<h3>REPORTS</h3>
</header>
<p>Reports on closed research</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="https://csirt.divd.nl" class="icon fa-bell-o"><span class="label">Icon</span></a>
<h3>CSIRT</h3>
</header>
<p>Blog on current research by our Computer Security Incident Response Team</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/security" class="icon fa-shield"><span class="label">Icon</span></a>
<h3>SECURITY</h3>
</header>
<p>Public documents and reports about (our) security</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/contact" class="icon fa-envelope-o"><span class="label">Icon</span></a>
<h3>CONTACT</h3>
</header>
<p>We are a network of security researchers who mainly work online.</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/join" class="icon fa-handshake-o"><span class="label">Icon</span></a>
<h3>JOIN</h3>
</header>
<p>Join DIVD</p>
</div>
</section>
<section>
<div class="content">
<header>
<a href="/donate" class="icon fa-eur"><span class="label">Icon</span></a>
<h3>DONATE</h3>
</header>
<p>We need your support for our mission.</p>
</div>
</section>
</div>
{% include open-cases.html %}
{% include last-10-posts.html %}
|
One should use the equivalent file from the sample platform as an example.
The pdn.cfg file defines rules used to generate the power grid of designs on this platform.
This must be manually adjusted based on the user’s preference, as well as the underlying technology.
|
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Model\Product\Edit;
class WeightResolver
{
/**
* Product has weight
*/
const HAS_WEIGHT = 1;
/**
* Product don't have weight
*/
const HAS_NO_WEIGHT = 0;
/**
* @param \Magento\Catalog\Model\Product $product
* @return bool
*/
public function resolveProductHasWeight(\Magento\Catalog\Model\Product $product)
{
return (bool) ($product->getData('product_has_weight') == self::HAS_WEIGHT);
}
}
|
#!/usr/bin/env bash
set -e
# Copyright (c) 2019 Anton Semjonov
# Licensed under the MIT License
# input and output
INFILE=${1:?input file required}
OUTDIR=${2:?output directory required}
OUTFILE="${OUTDIR}/$(basename "${INFILE}")"
# ocrmypdf location
OCRMYPDF=${OCRMYPDF:-/appenv/bin/ocrmypdf}
# ocrmypdf options
OPTIONS=${OCR_OPTIONS:---clean --deskew --output-type pdfa --skip-text}
LANGUAGE=${OCR_LANGUAGE:-deu+eng}
# run ocr processing
echo "PROCESSING $(basename "${INFILE}")"
${OCRMYPDF} ${OPTIONS} --language ${LANGUAGE} "${INFILE}" "${OUTFILE}"
# fix permissions if root
if [[ ${EUID} -eq 0 ]]; then
chmod --reference "${INFILE}" "${OUTFILE}"
chown --reference "${INFILE}" "${OUTFILE}"
fi
# remove original file
if [[ ${REMOVE_ORIGINAL} =~ true|y(es)|on ]]; then
rm -f "${INFILE}"
fi
|
module Wordle.Validation (checkGuess, Checked) where
import Data.List (elemIndex)
import Data.Maybe (isJust)
import Wordle.State (Checked (..), GameState (guess, word))
checkChar :: GameState -> Char -> Checked
checkChar state c
| isInWord && indexInGuess == indexInWord = CGreen c
| isInWord && indexInGuess /= indexInWord = CYellow c
| not isInWord = CRed c
where
indexInWord = elemIndex c $ word state
indexInGuess = elemIndex c $ guess state
isInWord = elem c $ word state
checkGuess :: GameState -> [Checked]
checkGuess state = fmap (checkChar state) (guess state) |
#!/usr/bin/perl
#RedRep Utility fastq2fasta.pl
#Copyright 2016 Shawn Polson, Keith Hopper, Randall Wisser
#reads from stdin
$i=0;
while(<>)
{ if(/^\@/&&$i==0)
{ s/^\@/\>/;
print;
}
elsif($i==1)
{ print;
$i=-3;
}
$i++;
}
|
using System;
using System.Collections.Generic;
using TestStack.Dossier.DataSources.Generators;
namespace TestStack.Dossier.DataSources.Picking
{
/// <summary>
/// Implements the repeatable sequence strategy
/// </summary>
public class RepeatingSequenceSource<T> : DataSource<T>
{
/// <inheritdoc />
public RepeatingSequenceSource(IList<T> list)
: base(new SequentialGenerator())
{
Data = list;
Generator.StartIndex = 0;
Generator.ListSize = Data.Count;
}
/// <inheritdoc />
protected override IList<T> InitializeDataSource()
{
// This method will never be called as the list is set in the constructor.
throw new NotImplementedException();
}
}
} |
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Models\Guild;
use Inertia\Inertia;
class GuildController extends Controller
{
public function allGuilds()
{
}
public function getGuildById($id)
{
return Inertia::render('Guild', [
'guild' => Guild::query()
->where('guild_id', '=', $id)
->firstOrFail(),
'guild_members' => DB::table('players')
->join('guild_members', 'players.player_id', '=', 'guild_members.player_id')
->select('players.*', 'guild_members.guild_rank')
->where('guild_members.guild_id', '=', $id)
->paginate(30)
->withQueryString()
]);
}
}
|
import axios from 'axios';
import { API_URL } from '../constants/index';
export const apiService = axios.create({
baseURL: API_URL
});
|
import { Module } from '@nestjs/common';
import { RoomsController } from './rooms.controller';
import { RoomsService } from './rooms.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RoomRepository } from './room.repository';
import { FacilityRepository } from '../facility/facility.repository';
import { BookingRepository} from '../booking/booking.repository';
import { BookingModule } from 'src/booking/booking.module';
import { UserRepository } from 'src/auth/user.repository';
import {Room} from 'src/rooms/entity/room.entity'
import { DefaultAdminSite, DefaultAdminModule } from 'nestjs-admin';
import { RoomAdmin } from './rooms.admin';
@Module({
imports: [
TypeOrmModule.forFeature([Room,RoomRepository]),
TypeOrmModule.forFeature([FacilityRepository]),
TypeOrmModule.forFeature([BookingRepository]),
TypeOrmModule.forFeature([UserRepository]),
BookingModule,
DefaultAdminModule
],
controllers: [RoomsController],
providers: [RoomsService],
exports: [RoomsService],
})
export class RoomsModule {
constructor(private readonly adminSite: DefaultAdminSite) {
adminSite.register('Room',RoomAdmin )
}
}
|
module HealthMonitor
class Configuration
attr_accessor :providers, :error_callback, :basic_auth_credentials
def initialize
@providers = [:database]
end
end
end
|
#! /bin/bash
wget https://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm
rpm -Uvh erlang-solutions-1.0-1.noarch.rpm
rpm --import https://packages.erlang-solutions.com/rpm/erlang_solutions.asc
rpm --import https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
rpm --import https://packagecloud.io/gpg.key
rpm --import https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
|
package com.katana.koin.data.local.db
import androidx.lifecycle.LiveData
import com.katana.koin.data.local.db.entities.Mail
import com.katana.koin.data.local.db.entities.Member
import io.reactivex.Observable
interface DbHelper {
fun getAllMember(): List<Member>
fun insertMember(member: Member): Observable<Long>
fun getAllMail(): List<Mail>
fun insertMail(mail: Mail): Observable<Long>
fun deleteMemberByEmail(email:String): Observable<Int>
} |
---
title: Pallindromic array
date: 2019-09-30
author: varuntheruler
categories:
- Data Structures
- arrays
---
### PALINDROMIC ARRAY
#### programme description:
<br>
You are given an array of size n.
Your task is to find an the minimum number of operations
to convert the given array to palindromic array.
### ALGORITHM:
<br>
Let number operations be count.
First of all take two indices i,j and assign them to
0 and n-1 respectively.
If array[i]==array[j],then then no need to do any
merging operations at index i or index j.and make
i = i+1 and j = j-1 and count becomrs count+=1
Elseif array[i]>array[j],then merging operation
takes place at j and array[j] = array[j]+array[j-1]
and j becomes j-1 and count becomes count+=1
Else if array[i]<array[j],then merging operation
takes place at i and array[i]+=array[i+1] and i becomes
i+1.
### Python PROGRAMME:
```python
def min_number_of_operators(a,n):
count = 0
i =0
j=n-1
while(i<=j):
if a[i] == a[j]:
i = i+1
j = j-1
elif a[i]>a[j]:
j =j-1
a[j] = a[j]+a[j+1]
count+=1
else:
i = i+1
a[i]+=a[i-1]
count+=1
return count
a =list(map(int,input().split()))
n = len(a)
print(min_number_of_operators(a,n))
```
### INPUT:
<br>
1 2 3 4 5
### OUTPUT:
<br>
2
### EXPLANATION FOR INPUT AND OUTPUT:
<br>
When input is given with integers with spaces first it converts
them into an array as we have used map() function.
for example 1 2 3 4 5 wil be coverted as[1,2,3,4,5].
Now we check weather array[i]==array[j-1] or not and as 1!=5
it goes with which is greater as 1<5 then merging takes place array[i].
i.e.,array[i]+=array[i+1]
i.e.., 1--->3
and i becomes 1. it continues and prints total number of operations took
place for getting a palindromic array.
### TIME COMPLEXITY:
<br>
Time complexity for the above given programme is O(n),since only one
for loop is used. |
package types
import (
"reflect"
. "github.com/101loops/bdd"
)
var _ = Describe("Query", func() {
It("should initialize", func() {
qry := NewQuery("my-kind")
Check(*qry, Equals, Query{
Filter: make([]Filter, 0),
Order: make([]Order, 0),
TypeOf: FullQuery,
kind: "my-kind",
Limit: -1,
})
})
It("should be cloneable", func() {
qry := &Query{
kind: "my-kind",
Order: []Order{Order{"age", true}, Order{"name", false}},
Filter: []Filter{Filter{"age >", 18}},
Projection: []string{"name", "age"},
Ancestor: NewKey("my-kind", "", 42, nil),
}
copy := qry.Clone()
Check(qry, Equals, copy)
Check(addrOf(qry.Order), Not(Equals), addrOf(copy.Order))
Check(addrOf(qry.Filter), Not(Equals), addrOf(copy.Filter))
Check(addrOf(qry.Projection), Not(Equals), addrOf(copy.Projection))
})
It("should convert to dastastore Query", func() {
qry := &Query{
kind: "my-kind",
Order: []Order{Order{"age", true}, Order{"name", false}},
Filter: []Filter{Filter{"age >", 18}},
Projection: []string{"name", "age"},
Ancestor: NewKey("my-kind", "", 42, nil),
Start: "my-start-cursor",
End: "my-end-cursor",
TypeOf: KeysOnlyQuery,
Eventual: true,
Distinct: true,
Offset: 10,
Limit: 10,
}
// we are just exercising each possible combination, the functionality is tested elsewhere
dsQry := qry.ToDSQuery(ctx)
Check(dsQry, NotNil)
})
})
func addrOf(val interface{}) uintptr {
return reflect.ValueOf(val).Pointer()
}
|
var playerContainer_;
var player_ = null;
var playerContext_ = {};
var playerUI_ = null;
var isEnableAnalyticsOverlay = true;
var analyticsInfo;
// UI Elements
var nIntervId;
var idAnalyticsOverlay = null;
var idAnalytics_playerVersion = null;
var idAnalytics_startupTime = null;
var idAnalytics_playTime = null;
var idAnalytics_streamType = null;
var idAnalytics_bufferingTime = null;
var idAnalytics_resolution = null;
var idAnalytics_bandwidth = null;
var idAnalytics_aveBandwidth = null;
var idAnalytics_playlistBitrate = null;
var idAnalytics_streamingFps = null;
var idAnalytics_adaptations = null;
var idAnalytics_totalFrames = null;
var idAnalytics_droppedFrames = null;
var idAnalytics_downloadTime = null;
var idAnalytics_downloadBytes = null;
var idAnalytics_droppedBytes = null;
var idAnalytics_videoLinkURL = null;
function initUI() {
idAnalyticsOverlay = document.getElementById('idAnalyticsOverlay');
idAnalytics_playerVersion = document.getElementById('idAnalytics_playerVersion');
idAnalytics_startupTime = document.getElementById('idAnalytics_startupTime');
idAnalytics_playTime = document.getElementById('idAnalytics_playTime');
idAnalytics_streamType = document.getElementById('idAnalytics_streamType');
idAnalytics_bufferingTime = document.getElementById('idAnalytics_bufferingTime');
idAnalytics_resolution = document.getElementById('idAnalytics_resolution');
idAnalytics_bandwidth = document.getElementById('idAnalytics_bandwidth');
idAnalytics_aveBandwidth = document.getElementById('idAnalytics_aveBandwidth');
idAnalytics_playlistBitrate = document.getElementById('idAnalytics_playlistBitrate');
idAnalytics_streamingFps = document.getElementById('idAnalytics_streamingFps');
idAnalytics_adaptations = document.getElementById('idAnalytics_adaptations');
idAnalytics_totalFrames = document.getElementById('idAnalytics_totalFrames');
idAnalytics_droppedFrames = document.getElementById('idAnalytics_droppedFrames');
idAnalytics_downloadTime = document.getElementById('idAnalytics_downloadTime');
idAnalytics_downloadBytes = document.getElementById('idAnalytics_downloadBytes');
idAnalytics_droppedBytes = document.getElementById('idAnalytics_droppedBytes');
idAnalytics_videoLinkURL = document.getElementById('idAnalytics_videoLinkURL');
idAnalyticsOverlay.style.display = 'block';
};
function onPlayerOpenFinished() {
if (isEnableAnalyticsOverlay) {
if (nIntervId) {
clearInterval(nIntervId);
}
nIntervId = setInterval(updateAnaylicsInfo, 3000);
}
};
function onFullscreenChanged() {
if (!idAnalyticsOverlay)
return;
var flagIsFullscreen = player_.isFullscreen();
if (flagIsFullscreen) {
idAnalyticsOverlay.classList.add("vop-fullscreen-analyticsoverlay");
idAnalyticsOverlay.classList.remove("vop-normal-analyticsoverlay");
} else {
idAnalyticsOverlay.classList.remove("vop-fullscreen-analyticsoverlay");
idAnalyticsOverlay.classList.add("vop-normal-analyticsoverlay");
}
}
function setAnalyticsTrackInfo() {
if (!isEnableAnalyticsOverlay || !analyticsInfo) {
return;
}
// Update analytics info
if (idAnalytics_playerVersion) {
idAnalytics_playerVersion.innerText = analyticsInfo.playerVersion;
}
if (idAnalytics_startupTime) {
idAnalytics_startupTime.innerText = analyticsInfo.startupTime;
}
if (idAnalytics_playTime) {
idAnalytics_playTime.innerText = analyticsInfo.playTime;
}
if (idAnalytics_streamType) {
idAnalytics_streamType.innerText = analyticsInfo.streamType;
}
if (idAnalytics_bufferingTime) {
idAnalytics_bufferingTime.innerText = analyticsInfo.bufferingTime;
}
if (idAnalytics_resolution) {
idAnalytics_resolution.innerText = analyticsInfo.resolution;
}
if (idAnalytics_bandwidth) {
idAnalytics_bandwidth.innerText = analyticsInfo.bandwidth;
}
if (idAnalytics_aveBandwidth) {
idAnalytics_aveBandwidth.innerText = analyticsInfo.aveBandwidth;
}
if (idAnalytics_playlistBitrate) {
idAnalytics_playlistBitrate.innerText = analyticsInfo.playlistBitrate;
}
if (idAnalytics_streamingFps) {
idAnalytics_streamingFps.innerText = analyticsInfo.streamingFps;
}
if (idAnalytics_adaptations) {
idAnalytics_adaptations.innerText = analyticsInfo.adaptations;
}
if (idAnalytics_totalFrames) {
idAnalytics_totalFrames.innerText = analyticsInfo.totalFrames;
}
if (idAnalytics_droppedFrames) {
idAnalytics_droppedFrames.innerText = analyticsInfo.droppedFrames;
}
if (idAnalytics_downloadTime) {
idAnalytics_downloadTime.innerText = analyticsInfo.downloadTime;
}
if (idAnalytics_downloadBytes) {
idAnalytics_downloadBytes.innerText = analyticsInfo.downloadBytes;
}
if (idAnalytics_droppedBytes) {
idAnalytics_droppedBytes.innerText = analyticsInfo.droppedBytes;
}
if (idAnalytics_videoLinkURL) {
idAnalytics_videoLinkURL.innerText = analyticsInfo.videoLinkURL;
}
};
function updateAnaylicsInfo() {
analyticsInfo = player_.getAnalyticsInfo();
if (!analyticsInfo) {
return;
}
setAnalyticsTrackInfo();
};
function initPlayer() {
playerContainer_ = document.getElementById('player-container');
// build player
player_ = new voPlayer.Player(playerContainer_);
player_.init(common_config);
player_.addEventListener(voPlayer.events.VO_OSMP_SRC_CB_OPEN_FINISHED, onPlayerOpenFinished, playerContext_);
player_.addEventListener(voPlayer.events.VO_OSMP_FULLSCREEN_CHANGE, onFullscreenChanged, playerContext_);
// attach ui engine
playerUI_ = new voPlayer.UIEngine(player_);
playerUI_.buildUI();
player_.open(DASH_Clear_stream);
}
window.onload = function () {
initUI();
initPlayer();
};
|
# SEGY reader
###
Designed to be a very light weight seismic reader that is easy and flexible.
Because of the history of SEGY standard there have been lots of places
where people tended to use as default byte positions and data formats,
For that reason we do minimal (no) checking to make sure the bit positions have
the information that is expected.
We instead rely on highly flexible configuration files.
the default segy 1 and segy 0 files can be extened and adapted with custom config files.
If there is something that is missing that is needed you can use a constant and it will override whatever
is in the byte positions.
|
import Data from './Data';
import {API_URL} from '../constants';
class NewsData {
static getAll(page = 1, limit = 5, langId = 1) {
return Data.get(`${API_URL}news/list?page=${page}&limit=${limit}&langId=${langId}`);
}
static getNewsDetails(id, langId = 1) {
return Data.get(`${API_URL}news/view?id=${id}&langId=${langId}`);
}
static getNewsCount(langId = 1) {
return Data.get(`${API_URL}news/count?langId=${langId}`);
}
}
export default NewsData; |
import { injectable } from 'inversify'
import fetch from 'cross-fetch'
import { gaTrackingId, logger } from '../../../config'
import IGaPageViewForm from '../ga/types/IGaPageViewForm'
import { generateCookie } from '../ga'
const gaEndpoint = 'https://www.google-analytics.com/collect'
@injectable()
export class AnalyticsLoggerService {
logRedirectAnalytics: (pageViewHit: IGaPageViewForm) => void = (
pageViewHit,
) => {
if (!gaTrackingId) return
const body = new URLSearchParams(
pageViewHit as unknown as Record<string, string>,
)
fetch(gaEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
}).then((response) => {
if (!response.ok) {
logger.error(
`GA tracking failure:\tError: ${response.statusText}\thttpResponse: ${response}\t body:${response.body}`,
)
}
})
}
generateCookie: (
cookie?: string,
) => [string, string, { maxAge: number }] | null = (cookie) => {
if (!gaTrackingId) return null
return generateCookie(cookie)
}
}
export default AnalyticsLoggerService
|
import sys
import torch
from args import get_argparser, parse_args, get_aligner, get_bbox
from os.path import join
if __name__ == '__main__':
parser = get_argparser()
parser.add_argument('--align_start',
help='align without vector voting the 2nd & 3rd sections, otherwise copy them', action='store_true')
args = parse_args(parser)
args.tgt_path = join(args.dst_path, 'image')
# only compute matches to previous sections
args.forward_matches_only = True
a = get_aligner(args)
bbox = get_bbox(args)
z_range = range(args.bbox_start[2], args.bbox_stop[2])
a.dst[0].add_composed_cv(args.bbox_start[2], inverse=False)
field_k = a.dst[0].get_composed_key(args.bbox_start[2], inverse=False)
field_cv= a.dst[0].for_read(field_k)
dst_cv = a.dst[0].for_write('dst_img')
z_offset = 1
uncomposed_field_cv = a.dst[z_offset].for_read('field')
vector_mip = args.render_low_mip
image_mip = 2
mip = args.mip
composed_range = z_range[3:]
if args.align_start:
copy_range = z_range[0:1]
uncomposed_range = z_range[1:3]
else:
copy_range = z_range[0:3]
uncomposed_range = z_range[0:0]
# copy first section
for z in copy_range:
print('Copying z={0}'.format(z))
a.copy_section(z, dst_cv, z, bbox, mip)
a.downsample(dst_cv, z, bbox, a.render_low_mip, a.render_high_mip)
# align without vector voting
for z in uncomposed_range:
print('Aligning without vector voting z={0}'.format(z))
src_z = z
tgt_z = z-1
a.compute_section_pair_residuals(src_z, tgt_z, bbox)
a.render_to_low_mip(src_z, uncomposed_field_cv, src_z, dst_cv, src_z, bbox,
image_mip, vector_mip)
#a.render_section_all_mips(src_z, uncomposed_field_cv, src_z,
# dst_cv, src_z, bbox, mip)
# align with vector voting
for z in composed_range:
print('Aligning with vector voting z={0}'.format(z))
a.generate_pairwise([z], bbox, render_match=False)
a.compose_pairwise([z], args.bbox_start[2], bbox, mip,
forward_compose=True,
inverse_compose=False)
a.render_to_low_mip(z, field_cv, z, dst_cv, z, bbox, image_mip, vector_mip)
#a.render_section_all_mips(z, field_cv, z, dst_cv, z, bbox, mip)
|
<?php
include "connection.php";
// Group by year
$month = array();
$year = array();
$region = array();
$season = array();
$table_name="disease";
# dengue_cases
if(!isset($disease['Dengue_Cases'])){
$dengue_cases = array();
$query1="select Month, AVG(Dengue_Cases) as avgdeng from ".$table_name." GROUP BY Month;";
//echo $query1;
$deng_cases_by_month = $con->query($query1);
while($row = mysqli_fetch_array($deng_cases_by_month)){
/*echo $row['district']."</br>";*/
$dengue_cases[] = floatval($row['avgdeng']);
$month[] = $row['Month'];
};
//print_r($dengue_cases) ;
}
# flu_cases
$flu_cases = array();
$query2="select Month, AVG(Flu_Cases) as avgflu from ".$table_name." GROUP BY Month;";
$flu_cases_by_month = $con->query($query2);
while($row = mysqli_fetch_array($flu_cases_by_month)){
/*echo $row['district']."</br>";*/
$flu_cases[] = floatval($row['avgflu']);
$month[] = $row['Month'];
};
//print_r($flu_cases) ;
#typhoid_cases
$typhoid_cases = array();
$query3="select Month, AVG(Typhoid) as avgtyphoid from ".$table_name." GROUP BY Month;";
$typhoid_cases_by_month = $con->query($query3);
while($row = mysqli_fetch_array($typhoid_cases_by_month)){
/*echo $row['district']."</br>";*/
$typhoid_cases[] = floatval($row['avgtyphoid']);
$month[] = $row['Month'];
};
//print_r($typhoid_cases) ;
include "monthlygraph.php";
?> |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class EndNode : BaseNode {
private void OnEnable()
{
AddInput();
}
public override void SetWindowRect(Vector2 mousePos)
{
width = 100;
height = 80;
WindowTitle = "End";
base.SetWindowRect(mousePos);
}
public override void DrawWindow()
{
DrawInterfaces();
}
public override void Tick(float DeltaTime)
{
}
} |
import numpy as np
from MSnet.cfp import cfp_process
from MSnet.utils import get_split_lists, get_split_lists_vocal, select_vocal_track, csv2ref
import argparse
import h5py
import pickle
def seq2map(seq, CenFreq):
CenFreq[0] = 0
gtmap = np.zeros((len(CenFreq), len(seq)))
for i in range(len(seq)):
for j in range(len(CenFreq)):
if seq[i] < 0.1:
gtmap[0, i] = 1
break
elif CenFreq[j] > seq[i]:
gtmap[j, i] = 1
break
return gtmap
def batchize(data, gt, xlist, ylist, size=430):
if data.shape[-1] != gt.shape[-1]:
new_length = min(data.shape[-1], gt.shape[-1])
data = data[:, :, :new_length]
gt = gt[:, :new_length]
num = int(gt.shape[-1]/size)
if gt.shape[-1] % size != 0:
num += 1
for i in range(num):
if (i+1)*size > gt.shape[-1]:
batch_x = np.zeros((data.shape[0], data.shape[1], size))
batch_y = np.zeros((gt.shape[0], size))
tmp_x = data[:, :, i*size:]
tmp_y = gt[:, i*size:]
batch_x[:, :, :tmp_x.shape[-1]] += tmp_x
batch_y[:, :tmp_y.shape[-1]] += tmp_y
xlist.append(batch_x)
ylist.append(batch_y)
break
else:
batch_x = data[:, :, i*size:(i+1)*size]
batch_y = gt[:, i*size:(i+1)*size]
xlist.append(batch_x)
ylist.append(batch_y)
return xlist, ylist
def batchize_val(data, size=430):
xlist = []
num = int(data.shape[-1]/size)
if data.shape[-1] % size != 0:
num += 1
for i in range(num):
if (i+1)*size > data.shape[-1]:
batch_x = np.zeros((data.shape[0], data.shape[1], size))
tmp_x = data[:, :, i*size:]
batch_x[:, :, :tmp_x.shape[-1]] += tmp_x
xlist.append(batch_x)
break
else:
batch_x = data[:, :, i*size:(i+1)*size]
xlist.append(batch_x)
return np.array(xlist)
def main(data_folder, model_type, output_folder):
if 'vocal' in model_type:
train_ids, val_ids, test_ids = get_split_lists_vocal(data_folder)
xlist = []
ylist = []
for chunk_id in train_ids:
filepath = data_folder + '/audio/synth_mix_' + chunk_id + '.wav'
data, CenFreq, time_arr = cfp_process(filepath, model_type=model_type, sr=44100, hop=256)
ypath = data_folder + '/annotations/melody/synth_mix_' + chunk_id + '.csv'
lpath = data_folder + '/annotations/activations/synth_mix_' + chunk_id + '.lab'
ref_arr = select_vocal_track(ypath, lpath)
gt_map = seq2map(ref_arr[:, 1], CenFreq)
xlist, ylist = batchize(data, gt_map, xlist, ylist, size=430)
xlist = np.array(xlist)
ylist = np.array(ylist)
hf = h5py.File('./data/train_vocal.h5', 'w')
hf.create_dataset('x', data=xlist)
hf.create_dataset('y', data=ylist)
hf.close()
xlist = []
ylist = []
for chunk_id in val_ids:
filepath = data_folder + '/audio/synth_mix_' + chunk_id + '.wav'
data, CenFreq, time_arr = cfp_process(filepath, model_type=model_type, sr=44100, hop=256)
data = batchize_val(data)
ypath = data_folder + '/annotations/melody/synth_mix_' + chunk_id + '.csv'
lpath = data_folder + '/annotations/activations/synth_mix_' + chunk_id + '.lab'
ref_arr = select_vocal_track(ypath, lpath)
xlist.append(data)
ylist.append(ref_arr)
with open(output_folder+'/val_x_vocal.pickle', 'wb') as fp:
pickle.dump(xlist, fp)
with open(output_folder+'/val_y_vocal.pickle', 'wb') as fp:
pickle.dump(ylist, fp)
elif 'melody' in model_type:
train_ids, val_ids, test_ids = get_split_lists()
xlist = []
ylist = []
for chunk_id in train_ids:
filepath = data_folder + '/audio/synth_mix_' + chunk_id + '.wav'
data, CenFreq, time_arr = cfp_process(filepath, model_type=model_type, sr=44100, hop=256)
ypath = data_folder + '/annotations/melody/synth_mix_' + chunk_id + '.csv'
ref_arr = csv2ref(ypath)
gt_map = seq2map(ref_arr[:,1], CenFreq)
xlist, ylist = batchize(data, gt_map, xlist, ylist, size=430)
xlist = np.array(xlist)
ylist = np.array(ylist)
hf = h5py.File(output_folder+'/train.h5', 'w')
hf.create_dataset('x', data=xlist)
hf.create_dataset('y', data=ylist)
hf.close()
xlist = []
ylist = []
for chunk_id in val_ids:
filepath = data_folder + '/audio/synth_mix_' + chunk_id + '.wav'
data, CenFreq, time_arr = cfp_process(filepath, model_type=model_type, sr=44100, hop=256)
data = batchize_val(data)
ypath = data_folder + '/annotations/melody/synth_mix_' + chunk_id + '.csv'
ref_arr = csv2ref(ypath)
xlist.append(data)
ylist.append(ref_arr)
with open(output_folder+'/val_x.pickle', 'wb') as fp:
pickle.dump(xlist, fp)
with open(output_folder+'/val_y.pickle', 'wb') as fp:
pickle.dump(ylist, fp)
def parser():
p = argparse.ArgumentParser()
p.add_argument('-df', '--data_folder',
help='Path to the dataset folder (default: %(default)s',
type=str, default='./data/MedleyDB/Source/')
p.add_argument('-t', '--model_type',
help='Model type: vocal or melody (default: %(default)s',
type=str, default='vocal')
p.add_argument('-o', '--output_folder',
help='Path to output foler (default: %(default)s',
type=str, default='./data/')
return p.parse_args()
if __name__ == '__main__':
args = parser()
main(args.data_folder, args.model_type, args.output_folder)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.