text
stringlengths
184
4.48M
const { test, expect } = require("../fixtures/base.fixture"); test.describe("Accounts Receivable Tests", () => { test.beforeEach(async ({ page, loginAsUser, siteURL }) => { await loginAsUser; await expect(page).toHaveURL(siteURL); }); test('should navigate to Receivable, check all entered values and verify "Great Job!" text', async ({ page, accountsReceivable }) => { const memoValue = 'Memo'; const amountValue = 100; await accountsReceivable.enterMemo(memoValue); await accountsReceivable.enterAmount(amountValue); const fromValue = await accountsReceivable.selectRequestFrom(); await accountsReceivable.clickContinue(); const fromValueOnPage = await accountsReceivable.getDisplayedFromValue(); expect(fromValueOnPage).toBe(fromValue); const memoValueOnPage = await accountsReceivable.getDisplayedMemoValue(); expect(memoValueOnPage).toBe(memoValue); const amountValueOnPage = await accountsReceivable.getDisplayedAmountValue(); expect(parseFloat(amountValueOnPage)).toBe(amountValue); await accountsReceivable.clickRequestPayment(); await accountsReceivable.waitForFormTitle(); const formTitleText = await accountsReceivable.getFormTitleText(); expect(formTitleText).toContain('Great Job!'); }); });
package com.bccv.zhuiyingzhihanju.adapter; import java.util.List; import com.bccv.zhuiyingzhihanju.R; import com.bccv.zhuiyingzhihanju.model.Movie; import com.bccv.zhuiyingzhihanju.model.Report; import com.bccv.zhuiyingzhihanju.model.TV; import com.nostra13.universalimageloader.core.ImageLoader; import com.utils.tools.GlobalParams; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class TVListAdapter extends BaseAdapter { private Context context; private List<TV> list; public TVListAdapter(Context context, List<TV> list) { // TODO Auto-generated constructor stub this.context = context; this.list = list; } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = View.inflate(context, R.layout.listitem_tvlist, null); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView); viewHolder.textView = (TextView) convertView.findViewById(R.id.textView); viewHolder.liveTextView = (TextView) convertView.findViewById(R.id.live_textView); viewHolder.nextTextView = (TextView) convertView.findViewById(R.id.next_textView); convertView.setTag(viewHolder); }else{ viewHolder = (ViewHolder) convertView.getTag(); } TV item=list.get(position); viewHolder.textView.setText(item.getTitle()); String images = (String) viewHolder.imageView.getTag(); if (images != null && images.equals(item.getPic())) { // viewHolder.imageView.setTag(item.getImages()); // ImageLoader imageLoader = ImageLoader.getInstance(); // imageLoader.displayImage(item.getImages(), viewHolder.imageView, GlobalParams.movieOptions); }else{ viewHolder.imageView.setTag(item.getPic()); ImageLoader imageLoader = ImageLoader.getInstance(); imageLoader.displayImage(item.getPic(), viewHolder.imageView, GlobalParams.movieOptions); } List<Report> reports = item.getReport(); if (reports != null && reports.size() > 0) { if (reports.size() < 2) { viewHolder.liveTextView.setText(reports.get(0).getTitle()); }else{ viewHolder.liveTextView.setText(reports.get(0).getTitle()); viewHolder.nextTextView.setText(reports.get(1).getTitle()); } } return convertView; } class ViewHolder { ImageView imageView; TextView textView; TextView liveTextView; TextView nextTextView; } }
<div class="container"> <div class="header"> <h2>Register here</h2> </div> <form class="form" (ngSubmit)="submitForm()" [formGroup]="loginForm1"> <div class="form-control"> <label><i class="fa fa-user"></i></label> <input type="text" placeholder="Enter your name" name="username" [(ngModel)]="username" formControlName="username" required> <div class="error" *ngIf="loginForm1.controls['username'].dirty&&loginForm1.controls['username'].dirty"> <small *ngIf="loginForm1.controls['username'].errors?.['required']">Please Enter username</small> <small *ngIf="loginForm1.controls['username'].errors?.['required']">User name-[7-15 characters and number (*no special character)</small> </div> </div> <div class="form-control"> <label><i class="fa fa-phone"></i></label> <input type="text" placeholder="Enter your mobile number" name="mobileno" [(ngModel)]="mobileno" formControlName="mobileno" required> <div class="error" *ngIf="loginForm1.controls['mobileno'].invalid&&loginForm1.controls['mobileno'].dirty"> <small *ngIf="loginForm1.controls['mobileno'].errors?.['required']">Please Enter your mobile no</small> <small *ngIf="loginForm1.controls['mobileno'].errors?.['pattern']">Please Enter correct mobile no</small> </div> </div> <div class="form-control"> <label><i class="fa fa-envelope"></i></label> <input type="email" placeholder="Enter your email id" name="email" [(ngModel)]="email" formControlName="email" required> <div class="error" *ngIf="loginForm1.controls['email'].invalid&&loginForm1.controls['email'].dirty"> <small *ngIf="loginForm1.controls['email'].errors?.['required']">Please Enter email</small> <small *ngIf="loginForm1.controls['email'].errors?.['pattern']">Please enter correct email *(gmail only)</small> </div> </div> <div class="form-control"> <label><i class="fa fa-lock"></i></label> <input type="password" placeholder="Set password" name="password" [(ngModel)]="password" formControlName="password" required> <div class="error" *ngIf="loginForm1.controls['password'].invalid&&loginForm1.controls['password'].dirty"> <small *ngIf="loginForm1.controls['password'].errors?.['required']">Please Enter password</small> <small *ngIf="loginForm1.controls['password'].errors?.['pattern']">7-15 characters-At least one numeric digit and special character</small> </div> </div> <div class="form-control"> <label><i class="fa fa-lock"></i></label> <input type="password" placeholder="Re-enter the password" name="confirmpass" [(ngModel)]="confirmpass" formControlName="confirmpass" required> <div class="error" *ngIf="loginForm1.controls['confirmpass'].invalid&&loginForm1.controls['confirmpass'].dirty"> <small *ngIf="loginForm1.controls['confirmpass'].errors?.['required']">Please Enter confirmpass</small> <small *ngIf="loginForm1.controls['confirmpass'].errors?.['ConfirmedValidator']">Please Enter correct confirmpass</small> </div> </div> <button [type]="'submit'">Register</button> <!-- onclick="return validateform()" --> </form> </div>
// Copyright 2023 PingCAP, 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 // // 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 aggfuncs import ( "bytes" "math/rand" "testing" "github.com/pingcap/tidb/pkg/parser/mysql" "github.com/pingcap/tidb/pkg/types" "github.com/pingcap/tidb/pkg/util/chunk" "github.com/stretchr/testify/require" ) var testLongStr1 string = getLongString("平p凯k星x辰c") var testLongStr2 string = getLongString("123aa啊啊aa") func getChunk() *chunk.Chunk { fieldTypes := make([]*types.FieldType, 1) fieldTypes[0] = types.NewFieldType(mysql.TypeBit) return chunk.NewChunkWithCapacity(fieldTypes, 100) } func getLongString(originStr string) string { returnStr := originStr for i := 0; i < 10; i++ { returnStr += returnStr } return returnStr } func getLargeRandBuffer() []byte { byteLen := 10000 ret := make([]byte, byteLen) randStart := rand.Int31() for i := 0; i < byteLen; i++ { ret[i] = byte((int(randStart) + i) % 8) } return ret } type bufferSizeChecker struct { lastCap int } func newBufferSizeChecker() *bufferSizeChecker { return &bufferSizeChecker{lastCap: -1} } // We need to ensure that buffer in `SerializeHelper` should be enlarged // when it serialize an object whose size is larger than it's capacity. func (b *bufferSizeChecker) checkBufferCapacity(helper *SerializeHelper) bool { newCap := cap(helper.buf) retVal := (newCap > b.lastCap) b.lastCap = newCap return retVal } func TestPartialResult4Count(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4Count{-123, 0, 123} serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4Count) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4Count(*(*partialResult4Count)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4Count, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4Count(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4Count)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinInt(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinInt{ {val: -123, isNull: true}, {val: 0, isNull: false}, {val: 123, isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinInt) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinInt(*(*partialResult4MaxMinInt)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinInt, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinInt(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinInt)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinUint(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinUint{ {val: 0, isNull: true}, {val: 1, isNull: false}, {val: 2, isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinUint) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinUint(*(*partialResult4MaxMinUint)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinUint, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinUint(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinUint)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinDecimal(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinDecimal{ {val: *types.NewDecFromInt(0), isNull: true}, {val: *types.NewDecFromUint(123456), isNull: false}, {val: *types.NewDecFromInt(99999), isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinDecimal) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinDecimal(*(*partialResult4MaxMinDecimal)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinDecimal, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinDecimal(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinDecimal)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinFloat32(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinFloat32{ {val: -123.123, isNull: true}, {val: 0.0, isNull: false}, {val: 123.123, isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinFloat32) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinFloat32(*(*partialResult4MaxMinFloat32)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinFloat32, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinFloat32(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinFloat32)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinFloat64(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinFloat64{ {val: -123.123, isNull: true}, {val: 0.0, isNull: false}, {val: 123.123, isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinFloat64) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinFloat64(*(*partialResult4MaxMinFloat64)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinFloat64, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinFloat64(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinFloat64)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinTime(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4MaxMinTime{ {val: types.NewTime(123, 10, 9), isNull: true}, {val: types.NewTime(0, 0, 0), isNull: false}, {val: types.NewTime(9876, 12, 10), isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinTime) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinTime(*(*partialResult4MaxMinTime)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinTime, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinTime(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinTime)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinString(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4MaxMinString{ {val: string("12312412312"), isNull: true}, {val: testLongStr1, isNull: false}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinString) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinString(*(*partialResult4MaxMinString)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinString, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinString(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinString)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinJSON(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4MaxMinJSON{ {val: types.BinaryJSON{TypeCode: 3, Value: []byte{}}, isNull: false}, {val: types.BinaryJSON{TypeCode: 6, Value: getLargeRandBuffer()}, isNull: true}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinJSON) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinJSON(*(*partialResult4MaxMinJSON)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinJSON, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinJSON(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinJSON)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinEnum(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4MaxMinEnum{ {val: types.Enum{Name: string(""), Value: 123}, isNull: true}, {val: types.Enum{Name: testLongStr1, Value: 0}, isNull: false}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinEnum) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinEnum(*(*partialResult4MaxMinEnum)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinEnum, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinEnum(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinEnum)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4MaxMinSet(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4MaxMinSet{ {val: types.Set{Name: string(""), Value: 123}, isNull: true}, {val: types.Set{Name: testLongStr1, Value: 0}, isNull: false}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4MaxMinSet) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4MaxMinSet(*(*partialResult4MaxMinSet)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4MaxMinSet, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4MaxMinSet(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4MaxMinSet)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4AvgDecimal(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4AvgDecimal{ {sum: *types.NewDecFromInt(0), count: 0}, {sum: *types.NewDecFromInt(12345), count: 123}, {sum: *types.NewDecFromInt(87654), count: -123}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4AvgDecimal) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4AvgDecimal(*(*partialResult4AvgDecimal)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4AvgDecimal, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4AvgDecimal(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4AvgDecimal)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4AvgFloat64(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4AvgFloat64{ {sum: 0.0, count: 0}, {sum: 123.123, count: 123}, {sum: -123.123, count: -123}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4AvgFloat64) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4AvgFloat64(*(*partialResult4AvgFloat64)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4AvgFloat64, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4AvgFloat64(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4AvgFloat64)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4SumDecimal(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4SumDecimal{ {val: *types.NewDecFromInt(0), notNullRowCount: 0}, {val: *types.NewDecFromInt(12345), notNullRowCount: 123}, {val: *types.NewDecFromInt(87654), notNullRowCount: -123}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4SumDecimal) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4SumDecimal(*(*partialResult4SumDecimal)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4SumDecimal, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4SumDecimal(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4SumDecimal)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4SumFloat64(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4SumFloat64{ {val: 0.0, notNullRowCount: 0}, {val: 123.123, notNullRowCount: 123}, {val: -123.123, notNullRowCount: -123}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4SumFloat64) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4SumFloat64(*(*partialResult4SumFloat64)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4SumFloat64, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4SumFloat64(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4SumFloat64)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestBasePartialResult4GroupConcat(t *testing.T) { var serializeHelper = NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []basePartialResult4GroupConcat{ {valsBuf: bytes.NewBufferString(""), buffer: bytes.NewBufferString("")}, {valsBuf: bytes.NewBufferString("xzxx"), buffer: bytes.NewBufferString(testLongStr2)}, {valsBuf: bytes.NewBufferString(testLongStr1), buffer: bytes.NewBufferString(testLongStr2)}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(basePartialResult4GroupConcat) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializeBasePartialResult4GroupConcat(*(*basePartialResult4GroupConcat)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]basePartialResult4GroupConcat, testDataNum+1) index := 0 for { success := deserializeHelper.deserializeBasePartialResult4GroupConcat(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, (*basePartialResult4GroupConcat)(serializedPartialResults[i]).valsBuf.String(), deserializedPartialResults[i].valsBuf.String()) require.Equal(t, (*basePartialResult4GroupConcat)(serializedPartialResults[i]).buffer.String(), deserializedPartialResults[i].buffer.String()) } } func TestPartialResult4BitFunc(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4BitFunc{0, 1, 2} serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4BitFunc) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4BitFunc(*(*partialResult4BitFunc)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4BitFunc, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4BitFunc(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4BitFunc)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4JsonArrayagg(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4JsonArrayagg{ {entries: []any{int64(1), float64(1.1), "", true, types.Opaque{TypeCode: 1, Buf: getLargeRandBuffer()}, types.NewTime(9876, 12, 10)}}, {entries: []any{int64(1), float64(1.1), false, types.NewDuration(1, 2, 3, 4, 5), testLongStr1}}, {entries: []any{"dw啊q", float64(-1.1), int64(0), types.NewDuration(1, 2, 3, 4, 5), types.NewTime(123, 1, 2), testLongStr1, types.BinaryJSON{TypeCode: 1, Value: []byte(testLongStr2)}, types.Opaque{TypeCode: 6, Buf: getLargeRandBuffer()}}}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4JsonArrayagg) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4JsonArrayagg(*(*partialResult4JsonArrayagg)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4JsonArrayagg, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4JsonArrayagg(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4JsonArrayagg)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4JsonObjectAgg(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4JsonObjectAgg{ {entries: map[string]any{"123": int64(1), "234": float64(1.1), "999": true, "235": "123"}, bInMap: 0}, {entries: map[string]any{"啊": testLongStr1, "我": float64(1.1), "反": int64(456)}, bInMap: 0}, {entries: map[string]any{"fe": testLongStr1, " ": int64(36798), "888": false, "": testLongStr2}, bInMap: 0}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4JsonObjectAgg) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4JsonObjectAgg(*(*partialResult4JsonObjectAgg)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4JsonObjectAgg, testDataNum+1) index := 0 for { success, _ := deserializeHelper.deserializePartialResult4JsonObjectAgg(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4JsonObjectAgg)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowDecimal(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowDecimal{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: *types.NewDecFromInt(0)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: *types.NewDecFromInt(123)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: *types.NewDecFromInt(12345)}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowDecimal) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowDecimal(*(*partialResult4FirstRowDecimal)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowDecimal, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowDecimal(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowDecimal)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowInt(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowInt{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: -123}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: 0}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: 123}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowInt) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowInt(*(*partialResult4FirstRowInt)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowInt, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowInt(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowInt)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowTime(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowTime{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.NewTime(0, 0, 1)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: types.NewTime(123, 0, 1)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: types.NewTime(456, 0, 1)}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowTime) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowTime(*(*partialResult4FirstRowTime)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowTime, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowTime(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowTime)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowString(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4FirstRowString{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: ""}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: testLongStr1}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowString) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowString(*(*partialResult4FirstRowString)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowString, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowString(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowString)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowFloat32(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowFloat32{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: -1.1}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: 0}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: 1.1}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowFloat32) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowFloat32(*(*partialResult4FirstRowFloat32)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowFloat32, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowFloat32(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowFloat32)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowFloat64(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowFloat64{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: -1.1}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: 0}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: 1.1}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowFloat64) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowFloat64(*(*partialResult4FirstRowFloat64)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowFloat64, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowFloat64(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowFloat64)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowDuration(t *testing.T) { serializeHelper := NewSerializeHelper() // Initialize test data expectData := []partialResult4FirstRowDuration{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.NewDuration(1, 2, 3, 4, 5)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: types.NewDuration(0, 0, 0, 0, 0)}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: true}, val: types.NewDuration(10, 20, 30, 40, 50)}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowDuration) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowDuration(*(*partialResult4FirstRowDuration)(pr)) chunk.AppendBytes(0, serializedData) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowDuration, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowDuration(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowDuration)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowJSON(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4FirstRowJSON{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: false, gotFirstRow: false}, val: types.BinaryJSON{TypeCode: 6, Value: []byte{}}}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.BinaryJSON{TypeCode: 8, Value: getLargeRandBuffer()}}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowJSON) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowJSON(*(*partialResult4FirstRowJSON)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowJSON, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowJSON(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowJSON)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowEnum(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4FirstRowEnum{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.Enum{Name: string(""), Value: 123}}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.Enum{Name: testLongStr2, Value: 999}}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowEnum) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowEnum(*(*partialResult4FirstRowEnum)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowEnum, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowEnum(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowEnum)(serializedPartialResults[i]), deserializedPartialResults[i]) } } func TestPartialResult4FirstRowSet(t *testing.T) { serializeHelper := NewSerializeHelper() bufSizeChecker := newBufferSizeChecker() // Initialize test data expectData := []partialResult4FirstRowSet{ {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.Set{Name: string(""), Value: 123}}, {basePartialResult4FirstRow: basePartialResult4FirstRow{isNull: true, gotFirstRow: false}, val: types.Set{Name: testLongStr1, Value: 999}}, } serializedPartialResults := make([]PartialResult, len(expectData)) testDataNum := len(serializedPartialResults) for i := range serializedPartialResults { pr := new(partialResult4FirstRowSet) *pr = expectData[i] serializedPartialResults[i] = PartialResult(pr) } // Serialize test data chunk := getChunk() for _, pr := range serializedPartialResults { serializedData := serializeHelper.serializePartialResult4FirstRowSet(*(*partialResult4FirstRowSet)(pr)) chunk.AppendBytes(0, serializedData) require.True(t, bufSizeChecker.checkBufferCapacity(serializeHelper)) } // Deserialize test data deserializeHelper := newDeserializeHelper(chunk.Column(0), testDataNum) deserializedPartialResults := make([]partialResult4FirstRowSet, testDataNum+1) index := 0 for { success := deserializeHelper.deserializePartialResult4FirstRowSet(&deserializedPartialResults[index]) if !success { break } index++ } chunk.Column(0).DestroyDataForTest() // Check some results require.Equal(t, testDataNum, index) for i := 0; i < testDataNum; i++ { require.Equal(t, *(*partialResult4FirstRowSet)(serializedPartialResults[i]), deserializedPartialResults[i]) } }
'use client'; import React, { useRef, ReactNode } from 'react'; import { useScroll, useTransform, motion } from 'framer-motion'; const TextReveal = ({value}) => { const element = useRef(null); const { scrollYProgress } = useScroll({ target: element, offset: ['start 0.9', 'start 0.25'] }) const words = value.split(" "); return( <h1 className="font-normal justify-center px-[0.75rem] md:justify-start md:px-0 text-[2rem] md:text-[3rem] max-w-[1200px] flex flex-wrap relative leading-8 text-[#0e0008]" ref = {element} > { words.map( (word, i) => { const start = i / words.length const end = start + (1 / words.length) return <Word key = {i} range={[start, end]} progress={scrollYProgress}>{ word }</Word> }) } </h1> ) } const Word = ({children, range, progress}) => { const chars = children.split(""); const extent = range[1] - range[0]; const step = extent/children.length; return ( <span className="m-2 md:m-3 relative"> { chars.map( (character, i) => { const start = range[0] + (step * i) const end = range[0] + (step * ( i + 1 )); return <Character key = {i} range = {[start, end]} progress = {progress} >{character}</Character> }) } </span> ) } const Character = ({children, range, progress}) => { const opacity = useTransform(progress, range, [0,1]) return ( <span> <span className="absolute opacity-10">{children}</span> <motion.span style={{opacity}}> {children} </motion.span> </span> ) } export default TextReveal
package test.deymer.excelsior.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import test.deymer.excelsior.databinding.ItemAlbumBinding import test.deymer.repository.models.SongModel class AlbumAdapter( private val albumList: List<SongModel> ): RecyclerView.Adapter<AlbumAdapter.ViewHolderAlbum>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AlbumAdapter.ViewHolderAlbum { val layout = LayoutInflater.from(parent.context) val itemBinding = ItemAlbumBinding.inflate(layout, parent, false) return ViewHolderAlbum(itemBinding) } override fun onBindViewHolder(holder: AlbumAdapter.ViewHolderAlbum, position: Int) { holder.binding(albumList[position]) } override fun getItemId(position: Int): Long { return position.toLong() } override fun getItemCount(): Int { return albumList.size } inner class ViewHolderAlbum( private val albumBinding: ItemAlbumBinding ) : RecyclerView.ViewHolder(albumBinding.root) { fun binding(song: SongModel) { with(albumBinding) { textViewNameSong.text = song.trackName textViewPriceSong.text = song.trackPrice } } } }
import { useState, Fragment } from "react"; import { Modal } from "../components/Modal/Modal"; import { Button } from "../components/Button/Button"; import { ArgsTable, Meta, Story, Canvas } from "@storybook/addon-docs"; <Meta title="Design System/Modal" component={Modal} /> # Modal Modal dialogs. When requiring users to interact with the application, but without jumping to a new page and interrupting the user's workflow, you can use `Modal` to create a new floating layer over the current page to get user feedback or display information. `Props` are listed at the end of this page. [View source](https://github.com/iamrishupatel/artemis-ui/tree/main/src/components/Modal) ## Imports ```js import { Modal } from "artemis-ui"; ``` ## Usage Basic modal. <Canvas> <Story name="base"> {() => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; return ( <Fragment> <Modal visible={isModalVisible} onClose={hideModal}> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quam modi illo, ut adipisci ducimus laboriosam. Omnis vel nesciunt perferendis facere quod non unde dolor, sequi similique accusantium eveniet nisi nam! </Modal> <Button variant="primary-light" onClick={showModal}> Click me to show Modal </Button> </Fragment> ); }} </Story> </Canvas> ### Rounded Modal Use `shape` prop to change the shape the modal <Canvas> <Story name="rounded"> {() => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; return ( <Fragment> <Modal shape="rounded" visible={isModalVisible} onClose={hideModal}> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quam modi illo, ut adipisci ducimus laboriosam. Omnis vel nesciunt perferendis facere quod non unde dolor, sequi similique accusantium eveniet nisi nam! </Modal> <Button variant="primary-light" onClick={showModal}> Click me to show Modal </Button> </Fragment> ); }} </Story> </Canvas> ### Placement You can change the placement of the modal by changing the `placement` prop. The default `placement` is `topCenter`. <Canvas> <Story name="placement"> {() => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; return ( <Fragment> <Modal placement="center" visible={isModalVisible} onClose={hideModal} > Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quam modi illo, ut adipisci ducimus laboriosam. Omnis vel nesciunt perferendis facere quod non unde dolor, sequi similique accusantium eveniet nisi nam! </Modal> <Button variant="primary-light" onClick={showModal}> Centered Modal </Button> </Fragment> ); }} </Story> </Canvas> ### Customizable Width Use `width` to set the width of the modal dialog. <Canvas> <Story name="custom-width"> {() => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; return ( <Fragment> <Modal title="Modal with 300px width" width="300px" placement="center" visible={isModalVisible} onClose={hideModal} > <p>Small modal content....</p> <p>Small modal content....</p> <p>Small modal content....</p> </Modal> <Button variant="primary-light" onClick={showModal}> 300px </Button> </Fragment> ); }} </Story> </Canvas> ### Modal With Footer You can provide a custom `footer` component to render at the bottom of the modal Use `footer` to set the footer of the modal dialog. <Canvas> <Story name="footer"> {() => { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; return ( <Fragment> <Modal title="Modal with footer" placement="center" visible={isModalVisible} onClose={hideModal} footer={ <div style={{ display: "flex", gap: "1rem", justifyContent: "flex-end", }} > <Button variant="danger-light" size="sm" onClick={hideModal}> Cancel </Button> <Button variant="success" size="sm"> Save </Button> </div> } > Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quam modi illo, ut adipisci ducimus laboriosam. Omnis vel nesciunt perferendis facere quod non unde dolor, sequi similique accusantium eveniet nisi nam! </Modal> <Button variant="primary-light" onClick={showModal}> Click me to show Modal </Button> </Fragment> ); }} </Story> </Canvas> ## Props <ArgsTable of={Modal} />
import Typography from '@mui/material/Typography'; import TableContainer from '@mui/material/TableContainer'; import Paper from '@mui/material/Paper'; import Table from '@mui/material/Table'; import TableHead from '@mui/material/TableHead'; import TableRow from '@mui/material/TableRow'; import TableCell from '@mui/material/TableCell'; import TableBody from '@mui/material/TableBody'; import IconButton from '@mui/material/IconButton'; import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'; import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'; import HistoryIcon from '@mui/icons-material/History'; import Collapse from '@mui/material/Collapse'; import * as React from 'react'; import Box from '@mui/material/Box'; import NumberFormat from 'react-number-format'; import { useDispatch, useSelector } from 'react-redux'; import { fetchUserTeacherGroupsAction, selectProfileState } from '../../../../redux/reducers/profile/profileReducer'; import { useEffect } from 'react'; import { IGroup } from '../../../../interfaces/IGroup'; import { Link } from 'react-router-dom'; import EditIcon from '@mui/icons-material/Edit'; import { Tooltip } from '@mui/material'; const TeacherGroupInfoTable = () => { const { isGridLoading, teacherGroups } = useSelector(selectProfileState); const dispatch = useDispatch(); useEffect(() => { dispatch(fetchUserTeacherGroupsAction()); }, []); const headerRows: { text: string; align: 'left' | 'center' | 'right' }[] = [ { text: 'Код', align: 'left', }, { text: 'Название', align: 'left', }, ]; return ( <> <Typography variant='h6'>Мои группы</Typography> <TableContainer component={Paper}> <Table aria-label='simple table'> <TableHead> <TableRow> <TableCell /> {headerRows.map(value => ( <> <TableCell align={value.align}> <b>{value.text}</b> </TableCell> </> ))} </TableRow> </TableHead> <TableBody> {' '} {teacherGroups.map(row => ( <> <GroupRow row={row} /> </> ))} </TableBody> </Table> </TableContainer> </> ); }; function GroupRow(props: { row: IGroup }) { const [open, setOpen] = React.useState(false); const { name, id, students } = props.row; return ( <> <TableRow sx={{ '& > *': { borderBottom: 'unset' } }} onClick={() => setOpen(!open)}> <TableCell> <IconButton size='small' onClick={() => setOpen(!open)}> {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />} </IconButton> </TableCell> <TableCell component='th' scope='row'> {id} </TableCell> <TableCell component='th' scope='row'> {name} </TableCell> </TableRow> <TableRow> <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}> <Collapse in={open} timeout='auto' unmountOnExit> <Box sx={{ margin: 1 }}> <Typography variant='h6' gutterBottom component='div'> Ученики </Typography> <Table size='small'> <TableHead> <TableRow> <TableCell>ФИО</TableCell> <TableCell>ФИО родителя</TableCell> <TableCell align='right'>Email родителя</TableCell> <TableCell align='right'>Контактный телефон родителя</TableCell> <TableCell align='right'>Действия</TableCell> </TableRow> </TableHead> <TableBody> {students?.map(student => ( <TableRow key={student.id}> <TableCell component='th' scope='row'> {student.firstName} {student.middleName} {student.lastName} </TableCell> <TableCell> {student.parentName} {student.parentMiddleName} {student.lastName} </TableCell> <TableCell align='right'>{student.parentEmail}</TableCell> <TableCell align='right'> <NumberFormat value={student.parentPhone} displayType={'text'} format='+ 7 (###) ### ##-##' /> </TableCell> <TableCell align='right'> <Tooltip title='Просмотреть историю расчётов'> <IconButton to={`/dashboard/calculations/history/student/${student.id}/group/${id}`} component={Link} > <HistoryIcon /> </IconButton> </Tooltip> </TableCell> </TableRow> ))} </TableBody> </Table> </Box> </Collapse> </TableCell> </TableRow> </> ); } export default TeacherGroupInfoTable;
/* * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.BorderLayout; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JFrame; /* * @test * @bug 4222508 * @library /java/awt/regtesthelpers * @build PassFailJFrame * @summary Tests the color chooser disabling * @run main/manual Test4222508 */ public final class Test4222508 { public static void main(String[] args) throws Exception { String instructions = "Click on colors in the JColorChooser.\n" + "Then uncheck the checkbox and click on colors again.\n" + "If the JColorChooser is disabled when the checkbox is unchecked, " + "then pass the test."; PassFailJFrame.builder() .title("Test4222508") .instructions(instructions) .rows(5) .columns(40) .testTimeOut(10) .testUI(Test4222508::test) .build() .awaitAndCheck(); } public static JFrame test() { JFrame frame = new JFrame("JColorChooser with enable/disable checkbox"); frame.setLayout(new BorderLayout()); JColorChooser chooser = new JColorChooser(); JCheckBox checkbox = new JCheckBox("Enable the color chooser below", true); checkbox.addItemListener(e -> chooser.setEnabled(checkbox.isSelected())); frame.add(chooser, BorderLayout.SOUTH); frame.add(checkbox, BorderLayout.NORTH); frame.pack(); return frame; } }
/* Sharelin - BSD/Linux terminal gnutella2-client Copyright (C) 2010 by Andrew Stroganov <savthe@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SHARECACHE_HPP #define SHARECACHE_HPP #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <string> #include "hashes.hpp" #include <set> #include <list> #include <map> #include <vector> #include "types.hpp" #include "idgen.hpp" #include "sharedefs.hpp" #include <boost/weak_ptr.hpp> namespace Share { using boost::multi_index_container; using namespace boost::multi_index; class Cache { public: struct CachedInfo { CachedInfo(FileInfoPtr p): path(p->path), sha1(p->sha1), ttr(p->ttr), ed2k(p->ed2k), md5(p->md5), id(p->id), pInfo(p) {} bool Compare(const FileInfo& f) const { return path == f.path && sha1 == f.sha1 && ttr == f.ttr && ed2k == f.ed2k && md5 == f.md5 && id == f.id; } std::string path; Hashes::SHA1 sha1; Hashes::TTR ttr; Hashes::ED2K ed2k; Hashes::MD5 md5; ID id; FileInfoPtr pInfo; }; typedef multi_index_container< CachedInfo, indexed_by< ordered_unique< tag<tags::path>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, std::string, path)>, ordered_unique< tag<tags::id>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, ID, id)>, ordered_unique< tag<tags::ptr>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, FileInfoPtr, pInfo)>, ordered_non_unique< tag<tags::sha1>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, Hashes::SHA1, sha1)>, ordered_non_unique< tag<tags::md5>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, Hashes::MD5, md5)>, ordered_non_unique< tag<tags::ed2k>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, Hashes::ED2K, ed2k)>, ordered_non_unique< tag<tags::ttr>, BOOST_MULTI_INDEX_MEMBER(CachedInfo, Hashes::TTR, ttr)> > > InfoContainer; typedef InfoContainer::iterator iterator; void Add(FileInfoPtr); void Update(FileInfoPtr); void Remove(FileInfoPtr); bool Empty() const { return cache_.empty(); } std::size_t Size() const { return cache_.size(); } iterator begin() const { return cache_.begin(); } iterator end() const { return cache_.end(); } template <typename tag, typename Key> FileInfoPtr Get(Key key) const { return GetIterator<tag>(key)->pInfo; } template <typename T> void Dump(T out) const { for(InfoContainer::iterator i = cache_.begin(); i != cache_.end(); ++i) *out++ = i->pInfo; } private: template <typename tag, typename Key> typename InfoContainer::index_iterator<tag>::type GetIterator(Key key) const { typename InfoContainer::index_iterator<tag>::type i = cache_.get<tag>().find(key); if(i != cache_.get<tag>().end()) return i; throw NotFound(); } InfoContainer cache_; }; } //namespace Share #endif //SHARECACHE_HPP
import './styles/style.css' import { useEffect, useState } from 'react' const Header = ({setSearch}) => { const[apiData, setApiData] = useState(); const[search, setSearchValue] = useState(); const date = new Date(apiData && Date.parse(apiData.location.localtime) || new Date()); const minutes = date.getMinutes(); const hours = date.getHours(); const month = date.getMonth(); const day = date.getDate(); const year = date.getFullYear(); useEffect(() => { const fetchData = async ()=>{ let params = new URLSearchParams() params.append('key', "e951c7d161764171ace132934232201"); params.append('q', search); try{ const res = await fetch(`http://api.weatherapi.com/v1/current.json?${params}`); const jsonData = await res.json(); if(res.ok){ setApiData(jsonData); }; } catch(error){ console.log(error); } } fetchData() }, [search]) return ( <div className="box"> <h1 className='focus-in-expand-fwd'>Weather <span>App</span></h1> <input className='slide-in-fwd-bottom' type="text" placeholder='search city' name='search' onChange={(e) => { setSearchValue(e.target.value); setSearch(e.target.value); } } value={search} /> {apiData? <div className='displayData'> <img src={apiData.current.condition.icon} alt="image" /> <p><span>City:</span> {apiData.location.name}</p> <p><span>Country:</span> {apiData.location.country}</p> <p><span>Temp: </span>{apiData.current.temp_c}°C</p> <p><span>Date: </span>{year}-{month}1-{day}</p> <p><span>Time: </span>{hours}:{minutes}</p> </div> : <p></p>} </div> ) } export default Header
""" URL configuration for backend project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, re_path, include from django.views.static import serve from decouple import config import debug_toolbar from common import constants from backend import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('backend.urls.api')), re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] # Configuration for the development mode if config('DEBUG', default=False, cast=bool): urlpatterns.append(path('__debug__/', include(debug_toolbar.urls))), else: urlpatterns.append(re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT})), # Custom Admin Titles admin.site.site_header = constants.TITLE admin.site.site_title = constants.TITLE admin.site.index_title = constants.TITLE
""" CODENAME BONSAI _[Bonsai](https://en.wikipedia.org/wiki/Bonsai), because it is a miniature [Trie](https://en.wikipedia.org/wiki/Trie)_ A self-contained, minimal and POD data structure that provides the fastest possible (?) lookup of numeric Ids by name. Names are UTF-8 strings, and with a word size of 8 bits you can have at most 255 words in a dictionary. A Bonsai dictionary is a simple array of "nodes". Each node in the array contains the following (potentially zero-length = empty) fields: 1. The size of the "common string" in words. 2. The actual common string, is potentially empty. 3. Numeric Id, if this node signifies the end of a name. 4. The number of child branches. 5. (for each child node) A pair of words: the first one is the label of the branch, the second one is the forward offset to the branch in the array from the end of this node. The first child branch does not store an offset because it is always zero. Instead of storing the absolute offset value, each offset is only the offset added by this child branch. In order to calculate the actual offset, you need to sum up the offset of all branches and including the target branch's. """ from typing import List, Tuple, Sequence, Dict, Optional WORD_SIZE: int = 8 # bits NO_ID: int = (2 ** WORD_SIZE) - 1 def find_common_string_length(names: Sequence[bytes]) -> int: assert len(names) > 0 reference_name: bytes = names[0] common_string_length: int = len(reference_name) for name in names[1:]: common_string_length = min(common_string_length, len(name)) for i in range(common_string_length): if name[i] != reference_name[i]: if i == 0: return 0 else: common_string_length = i break return common_string_length def create_bonsai(string_names: List[str]) -> bytes: if len(string_names) == 0: return b'' if len(set(string_names)) != len(string_names): raise ValueError("Names stored in a Bonsai must be unique") for string_name in string_names: if len(string_name) > NO_ID: raise ValueError(f'Names stored in a Bonsai must be <= {NO_ID} characters in size.\n' f'"{string_name}" is {len(string_name)} long.') def create_node_recursively(names: List[Tuple[bytes, int]]): assert len(names) > 0 # if there is a single name left, store all of it in this node if len(names) == 1: common_string, node_id = names[0] common_string_length: int = len(common_string) names.clear() else: # find the common substring at the start of all names of the input set common_string_length: int = find_common_string_length([name for name, _ in names]) common_string: bytes = names[0][0][:common_string_length] # check to see if the empty name is part of the input set node_id: int = NO_ID # if the empty name is part of the input set, this node has its id for name, index in names: if len(name) == common_string_length: node_id = index names.remove((name, index)) break # define the first part of the node: (common string size, common string) result.append(common_string_length) result.extend(list(common_string)) # may be empty # define the node index, may be NO ID result.append(node_id) # if there are no children, return here if len(names) == 0: result.append(0) return # find the child branches children_index: int = len(result) branches: Dict[int, List[Tuple[bytes, int]]] = {} for name, index in names: # remove the common string from the start of all names (they are still unique) and place the remainder # into buckets identified by the first letter first_letter: int = int(name[common_string_length]) if first_letter in branches: branches[first_letter].append((name[common_string_length + 1:], index)) else: branches[first_letter] = [(name[common_string_length + 1:], index)] # store the number of child branches result.append(len(branches)) # the first child does not need an offset, since we can calculate it from the number of siblings labels: List[int] = sorted(branches.keys()) result.append(labels[0]) # the remaining children need an offset, we are going to put zero in it for now and fill it up recursively later for label in labels[1:]: result.extend((label, 0)) node_end_index: int = len(result) # index one past the end of this node # create the first child branch create_node_recursively(branches[labels[0]]) # create and fill offset value for the remaining child branches last_offset: int = 0 for child_index in range(1, len(labels)): offset_index: int = children_index + 1 + (2 * child_index) actual_offset: int = len(result) - node_end_index offset: int = actual_offset - last_offset assert offset >= 0 if offset > NO_ID: raise ValueError(f'Cannot encode the given strings in a Bonsai dictionary ' f'because it would require an offset of {offset} (> {NO_ID})') result[offset_index] = offset last_offset = actual_offset create_node_recursively(branches[labels[child_index]]) result: List[int] = [] create_node_recursively(sorted( ((name.encode(), index) for index, name in enumerate(string_names)), key=lambda pair: pair[0])) return bytes(result) def find_in_bonsai(bonsai: bytes, word: str) -> Optional[int]: if len(bonsai) == 0: return None # we know that we will not find the word in an empty bonsai def traverse(remaining_word: bytes, start_index: int = 0) -> Optional[int]: assert start_index < len(bonsai) # subtract the common string from the beginning of the remaining word common_word_size: int = bonsai[start_index] if common_word_size > 0: common_string: bytes = bytes(bonsai[start_index + 1: start_index + 1 + common_word_size]) if not remaining_word.startswith(common_string): return None # word was not found remaining_word = remaining_word[common_word_size:] # if the word has been exhausted we have ended our journey if len(remaining_word) == 0: id_index: int = start_index + common_word_size + 1 assert id_index < len(bonsai) result: int = bonsai[id_index] return None if result == NO_ID else result # word was found but might not have an associated id # if the node has no child branches, there is nowhere to go from here child_count_index: int = start_index + common_word_size + 2 assert child_count_index < len(bonsai) child_count: int = bonsai[child_count_index] if child_count == 0: return None # word was not found # find the child branch to continue traversal target_branch_label: int = remaining_word[0] node_end_index: int = child_count_index + (child_count * 2) assert node_end_index - 1 < len(bonsai) # we can either take the first branch... branch_index: int = child_count_index + 1 if target_branch_label == bonsai[branch_index]: return traverse(remaining_word[1:], node_end_index) if target_branch_label < bonsai[branch_index]: return None # target label is smaller than the labels of all child branches # ...or do a linear search through the remaining child branches branch_index += 1 # advance to next unchecked branch index total_offset: int = 0 while branch_index < node_end_index: total_offset += bonsai[branch_index + 1] if target_branch_label == bonsai[branch_index]: return traverse(remaining_word[1:], node_end_index + total_offset) else: branch_index += 2 return None # target label does not denote a child branch return traverse(word.encode('utf-8')) def get_names_from_bonsai(bonsai: bytes) -> List[str]: if len(bonsai) == 0: return [] result: Dict[int, str] = {} def traverse(name: bytes, node_index: int) -> None: assert node_index < len(bonsai) common_word_size: int = bonsai[node_index] common_word_index: int = node_index + 1 id_index: int = common_word_index + common_word_size # add the common word to the name if common_word_size > 0: assert node_index + common_word_size < len(bonsai) name = name + bonsai[common_word_index: id_index] # if this node has an id, it is a new name node_id: int = bonsai[id_index] if node_id != NO_ID: assert node_id not in result result[node_id] = name.decode('utf-8') # no children child_count_index: int = id_index + 1 assert child_count_index < len(bonsai) child_count: int = bonsai[child_count_index] if child_count == 0: return # single child node_end_index: int = child_count_index + (child_count * 2) label_index: int = child_count_index + 1 assert node_end_index < len(bonsai) traverse(name + bytes(bonsai[label_index: label_index + 1]), node_end_index) # multiple children label_index += 1 total_offset: int = 0 for _ in range(1, child_count): offset_index: int = label_index + 1 total_offset += bonsai[offset_index] traverse(name + bytes(bonsai[label_index: offset_index]), node_end_index + total_offset) label_index += 2 traverse(b'', 0) return [result[key] for key in sorted(result.keys())] ######################################################################################################################## class Bonsai: def __init__(self, names: Optional[List[str]] = None): """ Constructor. If no names are given, this constructs an empty Bonsai. :param names: All names (in order) to store in the Bonsai. """ self._bonsai: bytes = create_bonsai(names or []) def __getitem__(self, name: str) -> int: if not isinstance(name, str): raise KeyError(f'Can not find "{name}" in Bonsai - only strings are allowed as key.') result: Optional[int] = find_in_bonsai(self._bonsai, name) if result is None: raise KeyError(f'Can not find "{name}" in Bonsai.') return result def __contains__(self, item: str) -> bool: return self.get(item) is not None def get(self, name: str) -> Optional[int]: if not isinstance(name, str): return None return find_in_bonsai(self._bonsai, name) def keys(self) -> List[str]: return get_names_from_bonsai(self._bonsai) def is_empty(self) -> bool: return len(self._bonsai) == 0
import React, {useEffect, useState} from 'react'; import {CSSTransition, TransitionGroup} from 'react-transition-group'; import TodoItem from '../components/TodoItem'; import AddNewTodo from '../components/AddNewTodo'; import useTodos from '../hooks/useTodos'; import useDnD from '../hooks/useDnD'; import TodoService from '../api/TodoService'; import Pagination from '../components/UI/Pagination'; import {usePagination} from '../hooks/usePagination'; import {getPagesCount} from '../utils'; const Main = () => { const [pagesCount, setPagesCount] = useState(0); const [limit, setLimit] = useState(10); const [page, setPage] = useState(1); const pagesArray = usePagination(pagesCount); const [todos, setTodos, changeTodo, deleteTodo, addTodo] = useTodos([]); const [dragStartHandle, dragEndHandler, dragOverHandler, dropHandler] = useDnD( todos, setTodos, ); const fetchTodos = async () => { const response = await TodoService.getTodos(limit, page); const totalCount = response.headers['x-total-count']; setTodos([...response.data]); setPagesCount(getPagesCount(totalCount, limit)); }; useEffect(() => { fetchTodos(); }, [page]); const changePage = change => { setPage(change); }; return ( <section className="flex flex-col items-center"> <AddNewTodo addTodo={addTodo} /> <TransitionGroup component="ul" className="w-full"> {todos.map(todo => ( <CSSTransition key={todo.id} timeout={500} classNames="todo"> <TodoItem dragStartHandle={dragStartHandle} dragEndHandler={dragEndHandler} dragOverHandler={dragOverHandler} dropHandler={dropHandler} todo={todo} changeTodo={changeTodo} deleteTodo={deleteTodo} /> </CSSTransition> ))} </TransitionGroup> <Pagination current={page} setPage={changePage} pagesArray={pagesArray} /> </section> ); }; export default Main;
#include <stdio.h> #include <string.h> #include <vtimer.h> #include <thread.h> #include <posix_io.h> #include <shell.h> #include <shell_commands.h> #include <board_uart0.h> #include "sys/net/sixlowpan/sixlowip.h" #include "sys/net/sixlowpan/sixlowpan.h" #include "sys/net/sixlowpan/sixlowerror.h" #include "sys/net/sixlowpan/rpl/rpl.h" #include "sys/net/sixlowpan/rpl/rpl_dodag.h" #define TR_WD_STACKSIZE (256) char tr_wd_stack[TR_WD_STACKSIZE]; void wakeup_thread(void) { while (1) { if (thread_getstatus(transceiver_pid) == STATUS_SLEEPING) { vtimer_usleep(500 * 1000); if (thread_getstatus(transceiver_pid) == STATUS_SLEEPING) { //puts("WAKEUP!"); thread_wakeup(transceiver_pid); } } vtimer_usleep(1000 * 1000); } } void init(char *str){ transceiver_command_t tcmd; msg_t m; uint8_t chan = 10; char command; uint16_t r_addr; int res = sscanf(str, "init %c %hu", &command, &r_addr); if(res < 1){ printf("Usage: init address\n"); printf("\tr\tinitialize as root\n"); printf("\tn\tinitialize as node router\n"); printf("\taddress must be an 8 bit integer\n"); } uint8_t state; switch (command) { case 'r': printf("INFO: Initialize as root on address %d\n", r_addr); if (r_addr > 255) { printf("ERROR: address not an 8 bit integer\n"); return; } state = rpl_init(TRANSCEIVER_CC1100, r_addr); if(state != SUCCESS){ printf("Error initializing RPL\n"); } rpl_init_root(); break; case 'n': printf("INFO: Initialize as node on address %d\n", r_addr); if (r_addr > 255) { printf("ERROR: address not an 8 bit integer\n"); return; } state = rpl_init(TRANSCEIVER_CC1100, r_addr); if(state != SUCCESS){ printf("Error initializing RPL\n"); } break; default: printf("ERROR: Unknown command '%c'\n", command); return; } /* set channel to 10 */ tcmd.transceivers = TRANSCEIVER_CC1100; tcmd.data = &chan; m.type = SET_CHANNEL; m.content.ptr = (void*) &tcmd; msg_send_receive(&m, &m, transceiver_pid); /* start transceiver watchdog */ thread_create(tr_wd_stack, TR_WD_STACKSIZE, PRIORITY_MAIN-3, CREATE_STACKTEST, wakeup_thread, "TX/RX WD"); } void loop(char *str){ rpl_routing_entry_t * rtable; while(1){ rtable = rpl_get_routing_table(); rpl_dodag_t * mydodag = rpl_get_my_dodag(); if(mydodag == NULL){ vtimer_usleep(20 * 1000 * 1000); continue; } printf("---------------------------\n"); printf("OUTPUT\n"); printf("my rank: %d\n", mydodag->my_rank); printf("my preferred parent:\n"); ipv6_print_addr(&mydodag->my_preferred_parent->addr); printf("parent lifetime: %d\n",mydodag->my_preferred_parent->lifetime); printf("---------------------------$\n"); for(int i=0;i<RPL_MAX_ROUTING_ENTRIES;i++){ if(rtable[i].used){ ipv6_print_addr(&rtable[i].address); puts("next hop"); ipv6_print_addr(&rtable[i].next_hop); printf("entry %d lifetime %d\n",i,rtable[i].lifetime); if(!rpl_equal_id(&rtable[i].address, &rtable[i].next_hop)){ puts("multi-hop"); } printf("---------------------------$\n"); } } printf("########################\n"); vtimer_usleep(20 * 1000 * 1000); } } void table(char *str){ rpl_routing_entry_t * rtable; rtable = rpl_get_routing_table(); printf("---------------------------\n"); printf("OUTPUT\n"); printf("---------------------------\n"); for(int i=0;i<RPL_MAX_ROUTING_ENTRIES;i++){ if(rtable[i].used){ ipv6_print_addr(&rtable[i].address); printf("entry %d lifetime %d\n",i,rtable[i].lifetime); if(!rpl_equal_id(&rtable[i].address, &rtable[i].next_hop)){ puts("multi-hop"); } printf("--------------\n"); } } printf("$\n"); } void dodag(char *str){ printf("---------------------------\n"); rpl_dodag_t * mydodag = rpl_get_my_dodag(); if(mydodag == NULL){ printf("Not part of a dodag\n"); printf("---------------------------$\n"); return; } printf("Part of Dodag:\n"); ipv6_print_addr(&mydodag->dodag_id); printf("my rank: %d\n", mydodag->my_rank); printf("my preferred parent:\n"); ipv6_print_addr(&mydodag->my_preferred_parent->addr); printf("---------------------------$\n"); } extern void cc1100_print_config(void); extern void cc1100_print_statistic(void); void cc1100_cfg(char* unused) { cc1100_print_config(); cc1100_print_statistic(); } void wakeup(char* unused) { thread_wakeup(10); } const shell_command_t shell_commands[] = { {"init", "", init}, {"table", "", table}, {"dodag", "", dodag}, {"cc1100", "", cc1100_cfg}, {"wakeup", "", wakeup}, {"loop", "", loop}, {NULL, NULL, NULL} }; int main(void) { printf("RPL Test Application\n"); posix_open(uart0_handler_pid, 0); shell_t shell; shell_init(&shell, shell_commands, uart0_readc, uart0_putc); shell_run(&shell); return 0; } int old_main(void) { timex_t mytime = timex_set(10,0); while(1){ rpl_routing_entry_t * rtable; rtable = rpl_get_routing_table(); printf("---------------------------\n"); printf("OUTPUT\n"); printf("---------------------------\n"); for(int i=0;i<RPL_MAX_ROUTING_ENTRIES;i++){ if(rtable[i].used){ ipv6_print_addr(&rtable[i].address); printf("--------------\n"); } } vtimer_sleep(mytime); }; }
import 'package:canteen_app/config/colors.dart'; import 'package:flutter/material.dart'; class SingleDeliveryItem extends StatelessWidget { final String title; final String address; final String number; final String addressType; // ignore: use_key_in_widget_constructors, prefer_const_constructors_in_immutables SingleDeliveryItem( {required this.title, required this.addressType, required this.address, required this.number}); @override Widget build(BuildContext context) { return Column( children: [ ListTile( title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(title), Container( width: 60, // ignore: prefer_const_constructors padding: EdgeInsets.all(1), height: 20, decoration: BoxDecoration( color: primaryColor, borderRadius: BorderRadius.circular(10)), child: Center( child: Text( addressType, // ignore: prefer_const_constructors style: TextStyle( fontSize: 13, color: Colors.black, ), ), ), ), ], ), leading: CircleAvatar( radius: 8, backgroundColor: primaryColor, ), subtitle: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(address), // ignore: prefer_const_constructors SizedBox( height: 5, ), Text(number), ], ), ), // ignore: prefer_const_constructors Divider( height: 35, ), ], ); } }
const asyncHandler = require("express-async-handler"); const paginatedResults = (model) => { return asyncHandler(async (req, res, next) => { const page = parseInt(req.query.page) || 1; // If page not defined set default to 1 const limit = parseInt(req.query.limit) || 12; // If limit not defined set default to 12 const startIndex = (page - 1) * limit; const endIndex = page * limit; // Set data for final result in "pagination" object const currentPage = page; const nextPage = page + 1 || null; const prevPage = page - 1 || null; const results = {}; const totalCount = await model.countDocuments().exec(); // Get total items in the mongo DB // Set next page parameters {page number, limit} before adding to result object if (endIndex < totalCount) { results.next = { page: page + 1, limit: limit, }; } // Set previous page parameters {page number, limit} before adding to result object if (startIndex > 0) { results.previous = { page: page - 1, limit: limit, }; } try { // Execute query by limit starting from the current index results.response = await model .find() .limit(limit) .skip(startIndex) .exec(); // Calculate total pages in rounded up const totalPages = Math.ceil(totalCount / limit); const totalCurrentRecords = results.response.length; res.paginatedResults = { ...results, pagination: { total_records: totalCount, total_current_records: totalCurrentRecords, current_page: currentPage, total_pages: totalPages, next_page: nextPage, prev_page: prevPage, }, }; next(); } catch (err) { res.status(500); throw new Error("Internal Server Error! Something went wrong.", err); } }); }; module.exports = paginatedResults;
import 'package:dnd/bloc/character_bloc/character_bloc.dart'; import 'package:dnd/components/snack_bar.dart'; import 'package:dnd/models/ch_race.dart'; import 'package:dnd/pages/character_selector/character_creation/creation_final.dart'; import 'package:dnd/shared_prefs.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_sizer/flutter_sizer.dart'; import '../../../bloc/information_bloc/information_bloc.dart'; import '../../../components/default_button.dart'; import '../../../components/our_colors.dart'; import '../../../global_vars.dart'; import '../../../models/ch_class.dart'; import '../../../models/character.dart'; class CreationClass extends StatefulWidget { const CreationClass({super.key}); static String routeName = "/creationClass"; @override State<CreationClass> createState() => _CreationClassState(); } class _CreationClassState extends State<CreationClass> { ChClass? currentClass; int currentNumber = 0; TextEditingController healthController = TextEditingController(); @override void initState() { informationBloc.add(LoadClassesEvent(context)); super.initState(); } @override Widget build(BuildContext context) { final args = (ModalRoute.of(context)?.settings.arguments ?? <String, dynamic>{}) as Map; ChRace? currentRace = args["currentRace"]; ChRace? currentSubRace = args["currentSubRace"]; int mod = args["mod"]; var size = MediaQuery.of(context).size; final double itemHeight = (size.height - kToolbarHeight - 40) / 2; final double itemWidth = size.width / 2.5; return BlocBuilder<CharacterBloc, CharacterState>( bloc: characterBloc, builder: (context, state) { if (mod == 1 && healthController.text == "") { healthController.text = characterBloc .state .characters[characterBloc.state.currentCharacter] .characterInfo .allHealth .toString(); } return Scaffold( appBar: AppBar( title: mod == 0 ? Text("Создание персонажа") : Text("Увеличение уровня"), leading: const BackButton( color: Colors.white, )), body: BlocBuilder<InformationBloc, InformationState>( bloc: informationBloc, builder: (context, state) { return SingleChildScrollView( child: Padding( padding: EdgeInsets.all(20.dp), child: Column( children: [ Container( padding: EdgeInsets.only(bottom: 10.w), alignment: Alignment.topLeft, child: mod == 0 ? Text("Выберите класс", style: Theme.of(context).textTheme.titleMedium) : Text( "Выберите класс, уровень в котором вы хотите поднять." " В случае, если вы выберите класс, уровень в котором у вас уже имеется, он увеличится на один." " В ином случае это будет считаться как мультиклассирование", style: Theme.of(context).textTheme.titleSmall)), ShaderMask( shaderCallback: (Rect bounds) { return LinearGradient( colors: [ OurColors.lightPink, Colors.white.withOpacity(0.05) ], stops: const [0.9, 1], tileMode: TileMode.mirror, ).createShader(bounds); }, child: SizedBox( width: 400.dp, height: informationBloc.state.classes.length > 4 ? 120.dp : 60.dp, child: GridView.count( shrinkWrap: true, childAspectRatio: (itemWidth / itemHeight), crossAxisCount: informationBloc.state.classes.length > 4 ? 2 : 1, physics: const ClampingScrollPhysics(), scrollDirection: Axis.horizontal, crossAxisSpacing: 10, mainAxisSpacing: 10, children: informationBloc.state.classes .map((e) => DefaultButton( primaryColor: currentClass == e ? OurColors.lightPink : OurColors.focusColor, text: e.name, onPress: () { debugPrint(currentClass?.name); debugPrint(e.name); setState(() { currentClass = e; }); }, )) .toList()), ), ), mod == 1 ? Padding( padding: EdgeInsets.symmetric(vertical: 4.h), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text( "Новое количество очков здоровья: ", style: Theme.of(context) .textTheme .bodySmall ?.copyWith(color: Colors.white), ), Container( height: 4.h, width: 15.w, padding: EdgeInsets.symmetric( horizontal: 10.dp, vertical: 2.dp), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Center( child: TextFormField( controller: healthController, style: Theme.of(context) .textTheme .bodySmall, inputFormatters: [ FilteringTextInputFormatter .digitsOnly, LengthLimitingTextInputFormatter(3), ], cursorColor: Colors.black45, textAlignVertical: TextAlignVertical.center, autofocus: false, decoration: InputDecoration( enabledBorder: const UnderlineInputBorder( borderSide: BorderSide( style: BorderStyle.none), ), focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( style: BorderStyle.none), ), hintStyle: Theme.of(context) .textTheme .bodySmall ?.copyWith( color: Colors.black45)), ), )) ], ), ) : Container(), currentClass != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: EdgeInsets.only(top: 10.w, bottom: 5.w), alignment: Alignment.topLeft, child: Text("Информация", style: Theme.of(context) .textTheme .titleMedium)), Container( alignment: Alignment.topLeft, child: Text( "${currentClass?.description}", textAlign: TextAlign.justify, style: Theme.of(context) .textTheme .bodySmall ?.copyWith(color: Colors.white))), Container( padding: EdgeInsets.symmetric(vertical: 4.w), alignment: Alignment.topLeft, child: Text("Умения", style: Theme.of(context) .textTheme .titleMedium)), Column( crossAxisAlignment: CrossAxisAlignment.start, children: currentClass!.classSkillsText .map((perc) => RichText( textScaleFactor: 1, selectionColor: Colors.white, textAlign: TextAlign.start, text: TextSpan( text: "${perc.title} ", style: Theme.of(context) .textTheme .bodyMedium ?.copyWith( color: Colors.white, fontWeight: FontWeight.bold), children: [ TextSpan( text: "${perc.text} \n", style: Theme.of(context) .textTheme .bodyMedium ?.copyWith( color: Colors.white)), ]))) .toList(), ), currentClass?.classSkillsPerLevel != null ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( "Умения за уровень", style: Theme.of(context) .textTheme .titleMedium, ), Padding( padding: EdgeInsets.only(left: 8.dp), child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular( 20), ), child: Row( children: [ Container( height: 5.h, width: 10.w, child: TextButton( onPressed: () { setState(() { if (currentNumber > 1) { currentNumber--; } }); }, child: Icon( Icons.remove, color: Colors.black, size: 10.dp, ), ), ), Text( (currentNumber + 1) .toString(), ), Container( alignment: Alignment.center, height: 5.h, width: 10.w, child: TextButton( onPressed: () { setState(() { if (currentNumber < 19) { currentNumber++; } }); }, child: Icon(Icons.add, color: Colors.black, size: 10.dp), ), ), ], ), ), ) ], ), Padding( padding: EdgeInsets.symmetric( vertical: 8.dp), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ RichText( textAlign: TextAlign.start, text: TextSpan( text: "Бонус мастерства: ", style: Theme.of(context) .textTheme .bodyMedium ?.copyWith( color: Colors .white, fontWeight: FontWeight .bold), children: [ TextSpan( style: Theme.of( context) .textTheme .bodyMedium ?.copyWith( color: Colors .white), text: "+${currentClass?.getSkillsByLevel(currentNumber)?.masteryBonus}") ])), RichText( textAlign: TextAlign.start, text: TextSpan( text: "Умения: ", style: Theme.of(context) .textTheme .bodyMedium ?.copyWith( color: Colors .white, fontWeight: FontWeight .bold), children: currentClass ?.getSkillsByLevel( currentNumber) ?.classSkills .asMap() .entries .map((e) => TextSpan( style: Theme.of(context) .textTheme .bodyMedium ?.copyWith( color: Colors .white), text: e.key + 1 == (currentClass?.getSkillsByLevel(currentNumber)!.classSkills.length) ? "${e.value.skillName}." : "${e.value.skillName}, ")) .toList())), currentClass ?.getSkillsByLevel( currentNumber) ?.numberKnownSpells != null ? RichText( textAlign: TextAlign.start, text: TextSpan( text: "Известные заклинания: ", style: Theme.of( context) .textTheme .bodyMedium ?.copyWith( color: Colors .white, fontWeight: FontWeight .bold), children: [ TextSpan( style: Theme.of( context) .textTheme .bodyMedium ?.copyWith( color: Colors .white), text: "${currentClass?.getSkillsByLevel(currentNumber)?.numberKnownSpells}") ])) : Container(), currentClass ?.getSkillsByLevel( currentNumber) ?.numberKnownFocuses != null ? RichText( textAlign: TextAlign.start, text: TextSpan( text: "Известные заговоры: ", style: Theme.of( context) .textTheme .bodyMedium ?.copyWith( color: Colors .white, fontWeight: FontWeight .bold), children: [ TextSpan( style: Theme.of( context) .textTheme .bodyMedium ?.copyWith( color: Colors .white), text: "${currentClass?.getSkillsByLevel(currentNumber)?.numberKnownFocuses}") ])) : Container(), ], ), ) ], ) : Container(), currentClass?.classSkillsPerLevel != null && currentClass ?.classSkillsPerLevel[ currentNumber] .spellSlots != null && currentClass?.getSkillsByLevel( currentNumber) != null ? Column( children: [ Text( "Ячейки заклинаний на уровень заклинаний", style: Theme.of(context) .textTheme .bodyMedium ?.copyWith(color: Colors.white), ), Padding( padding: EdgeInsets.symmetric( vertical: 10.dp), child: Container( padding: EdgeInsets.all(5.dp), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment .center, children: currentClass! .getSkillsByLevel( currentNumber)! .spellSlots! .keys .map((e) => Container( padding: EdgeInsets .all(10 .dp), child: Text(e))) .toList(), ), Row( mainAxisAlignment: MainAxisAlignment .center, children: currentClass! .getSkillsByLevel( currentNumber)! .spellSlots! .values .map((e) => Container( padding: EdgeInsets .all(10 .dp), child: Text(e .toString()))) .toList(), ), ], )), ), ], ) : Container() ], ) : Container(), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ SizedBox( height: currentClass == null && mod == 0 ? 55.h : currentClass == null && mod == 1 ? 40.h : 0), Container( alignment: Alignment.bottomRight, child: DefaultButton( primaryColor: OurColors.focusColorLight, text: mod == 0 ? "Далее" : "Сохранить", onPress: () { if (currentClass != null) { if (mod == 0) { Navigator.of(context).pushNamed( CreationFinal.routeName, arguments: { "currentClass": currentClass, "currentRace": currentRace, "currentSubRace": currentSubRace }); } else { Character character = characterBloc .state.characters[ characterBloc.state.currentCharacter]; if (character.chClass .contains(currentClass)) { character .chClass[character.chClass .indexOf(currentClass!)] .level++; } else { character.chClass.add(currentClass!); } character.characterInfo.allHealth = int.parse(healthController.text); character.level++; character.characterInfo.experiencePoints = 0; characterBloc .add(ChangeCharacterEvent(character)); Navigator.of(context).pop(); } } else { showSnackBar("Выберите класс"); } }, )), ], ) ], ), )); }, )); }, ); } }
import { DownloadIcon, EditIcon, ViewIcon } from "@chakra-ui/icons"; import { Badge, Box, Button, HStack, IconButton, Text, Tooltip, useColorModeValue, useMediaQuery, } from "@chakra-ui/react"; import { GoogleAuthProvider, signInWithPopup, User } from "firebase/auth"; import { useEffect, useState } from "react"; import { GrLogin } from "react-icons/gr"; import { ColorModeSwitcher } from "../ColorModeSwitcher"; import { useSettings } from "../contexts/SettingsContext"; import { auth } from "../utils/firebase"; import Leaderboard from "./Leaderboard"; import Rank from "./Rank"; export default function Header() { let [user, setUser] = useState<User | null>(auth.currentUser); useEffect(() => { auth.onAuthStateChanged((u) => { if (u) setUser(u); }); }, []); const handleLogin = () => { signInWithPopup(auth, new GoogleAuthProvider()); }; const [timer, setTimer] = useState("00:00:00"); const { settings, setSetting } = useSettings(); const bg = useColorModeValue("gray.100", "gray.700"); const [isDesktop] = useMediaQuery("(min-width: 600px)"); useEffect(() => { // Create a timer of time elapsed since the start of the class const start = new Date(); const interval = setInterval(() => { const now = new Date(); const diff = now.getTime() - start.getTime(); const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor((diff / (1000 * 60)) % 60); const seconds = Math.floor((diff / 1000) % 60); setTimer( `${hours.toString().padStart(2, "0")}:${minutes .toString() .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}` ); }, 1000); return () => clearInterval(interval); }, []); return ( <Box p={2} display={"flex"} alignItems={"center"} justifyContent={"space-between"} flexDirection={"row"} backgroundColor={bg} shadow={"sm"} > <Text fontSize={"md"} fontWeight={"bold"}> Software Engineering and Development I </Text> <HStack> {isDesktop && ( <> <Tooltip label={`You have been studying for ${timer}.`}> <Badge variant={"solid"} colorScheme={"gray"}> <Text fontSize={"sm"} fontWeight={"bold"}> {timer} </Text> </Badge> </Tooltip> {user ? ( <Rank points={settings.points || 0} /> ) : ( <Button leftIcon={<GrLogin />} variant={"solid"} colorScheme={"gray"} onClick={handleLogin} > <Text fontSize={"sm"} fontWeight={"bold"}> Login </Text> </Button> )} <Leaderboard /> </> )} <Tooltip label={ settings.interactiveMode ? "Interactive mode" : "View mode (no editing)" } > <IconButton size="md" fontSize="lg" variant="ghost" color="current" marginLeft="2" icon={settings.interactiveMode ? <EditIcon /> : <ViewIcon />} title="Toggle interactive mode" aria-label={ settings.interactiveMode ? "Interactive mode" : "View mode" } onClick={() => { setSetting("interactiveMode", !settings.interactiveMode); }} /> </Tooltip> <Tooltip label={"Download questions as a PDF."}> <IconButton size="md" fontSize="lg" variant="ghost" color="current" marginLeft="2" icon={<DownloadIcon />} aria-label={"Download questions"} title="Download questions" onClick={() => { window.open("/questions.pdf", "_blank"); }} /> </Tooltip> <ColorModeSwitcher /> </HStack> </Box> ); }
const express = require('express'); const app = express(); const mongoose = require("mongoose"); const morgan = require('morgan'); const bodyParser = require("body-parser"); var cookieParser = require('cookie-parser') const expressValidator = require("express-validator"); const fs = require("fs"); const cors = require("cors"); const dotenv = require("dotenv"); dotenv.config(); // NB: CORS USED FOR CROSS ORIGIN RESOURCE SHARING.. To share/allow access to our api from the frontend //db mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('DB Connected')) mongoose.connection.on("error", (err) => { console.log(`DB Connection error: ${err.message}`); }); // Bring in routes const postRoutes = require('./routes/post'); const authRoutes = require('./routes/auth'); const userRoutes = require('./routes/user'); // apiDocs app.get('/', (req, res) => { fs.readFile('docs/apiDocs.json', (err, data) => { if(err){ res.status(400).json({ error: err }) } const docs = JSON.parse(data); res.json(docs) }) }) // Middleware app.use(morgan('dev')); app.use(bodyParser.json()); // app.use(express.json()); app.use(cookieParser()); app.use(expressValidator()); app.use(cors()); app.use("/", postRoutes); app.use("/", authRoutes); app.use("/", userRoutes); // Middleware to handle unauthorized error for express-jwt app.use(function(err, req, res, next) { if(err.name === 'UnauthorizedError') { res.status(401).json({ error: "Unauthorized!"}); } }) const port = process.env.PORT || 8080; app.listen(port, () => { console.log("Listening on Port", port); }) // ATLAS PASSWORD: KVJjOdgQOy4oMjH8
// // TriviaData.swift // TriviaThis // // Created by johnekey on 6/11/19. // Copyright © 2019 johnekey. All rights reserved. // import Foundation import UIKit struct Category { let id: Int let category: String init(_ id: Int, _ category: String) { self.id = id self.category = category } } // This structure holds 1 answer, and whether or not it is the correct answer ( t/f) // If the user selects this answer as the "correct" answer - we set checked to true // We keep a randomized array of all of the answers for each question struct TriviaAnswer { let answer: String // either correct or incorrect Answer var checked: Bool // should it be checked var isCorrect: Bool // Is this the correct answer for the question init(answer: String, checked: Bool, isCorrect: Bool) { self.answer = answer self.checked = checked self.isCorrect = isCorrect } } class TriviaData { let category: String let type: String let level: String // one long comma separated string let question: String let correct: String let incorrect: [String] var randomizedAnswers = [TriviaAnswer]() init(result: TriviaResult) { self.category = result.category self.type = result.type self.level = result.level self.question = result.question.removingPercentEncoding ?? "" self.correct = result.correct.removingPercentEncoding ?? "" self.incorrect = result.incorrect self.randomizedAnswers = doRandomization() } func doRandomization() -> [TriviaAnswer] { var triviaAnswer = [TriviaAnswer]() triviaAnswer.append(TriviaAnswer(answer: correct, checked: false, isCorrect: true)) for wrongAnswer in incorrect { triviaAnswer.append(TriviaAnswer(answer: wrongAnswer.removingPercentEncoding ?? "", checked: false, isCorrect: false)) } return triviaAnswer.shuffled() } }
from django.views.generic.base import TemplateView from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.views.decorators.cache import cache_page from django.views.generic import ( ListView, UpdateView, DetailView ) TEMPLATE_BASE_FOOTNOTES = 'mydocumentations/legalpolicydocs/base-legal-docs.html' # CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) # class CacheMixin(object): # def get_cache_timeout(self): # return self.cache_timeout # def dispatch(self, *args, **kwargs): # return cache_page(self.get_cache_timeout())(super(self).dispatch)(*args, **kwargs) # ************************************ class LegalPolicyBaseClass(TemplateView): eff_dt = '07/30/2022' # ************************************ class PrivacyPolicy(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': "Privacy Policy", 'privacypolicy_notice': "Privacy Policy", } return context # ************************************ class TermsofUse(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Terms of Use', 'termsofuse_notice': "Terms of Use" } return context #2 # donot sell my info class DoNotSellMyInfo(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Donot Sell My Information (California Rights)', 'donotsellmyinfo_notice': "Donot sell my info" } return context #3 # general refund policy '''class RefundPolicyGeneral(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'General Refund Policy', 'refund_policy_gen': "General Refund Policy" } return context''' #4 # general cancellation policy class RefundPolicyCancel(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Cancellation & Refund Policy', 'cancel_refund_gen': "General Cancellaiton Policy" } return context #5 class RefundPolicyDispute(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Dispute & Refund Policy', 'dispute_refund_gen': "General Dispute Policy" } return context # 6 class CookiePolicy(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Cookie Policy', 'cookie_policy_notes': "Cookie Policy" } return context #7 class LegalPolicy(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Legal Policy', 'legal_policy_gen': "Legal Policy" } return context #8 class PaymentPolicy(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Payment Policy', 'payment_policy_gen': "Payment Policy" } return context #9 class SecurityPolicy(LegalPolicyBaseClass): template_name = TEMPLATE_BASE_FOOTNOTES def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'eff_dt': self.eff_dt, 'section_title': 'Security Policy', 'security_policy_gen': "Security Policy" } return context
## ------------------------------------------------------------------- ## Chapter 10 R code ## Handbook of Educational Measurement and Psychometrics Using R ## C. D. Desjardins & O. Bulut ## ------------------------------------------------------------------- install.packages("equate") library("equate") library("hemp") vignette("equatevignette") # equating designs hcre_data <- as.data.frame(table(hcre$score, hcre$form)) names(hcre_data) <- c("total", "form", "count") hcre_x <- as.freqtab(hcre_data[hcre_data$form == "x", c("total", "count")], scales = 20:50) hcre_y <- as.freqtab(hcre_data[hcre_data$form == "y", c("total", "count")], scales = 20:50) rbind(form_x = summary(hcre_x), form_y = summary(hcre_y)) plot(hcre_x) mean_yx <- equate(hcre_x, hcre_y, type = "mean") mean_yx head(mean_yx$concordance) form_yx <- mean_yx$concordance colnames(form_yx)[1] <- "total" hcre_xy <- merge(hcre_x, form_yx) head(hcre_xy) linear_yx <- equate(hcre_x, hcre_y, type = "linear") linear_yx # nonlinear function ---- equi_yx <- equate(hcre_x, hcre_y, type = "equipercentile") plot(equi_yx$concordance$yx ~ equi_yx$concordance$scale, type = "p", xlab = "Form X scores", ylab = "Adjusted X Scores on Form Y", ylim = c(20, 55)) points(linear_yx$concordance$yx ~ linear_yx$concordance$scale, pch = 4) # nonequivalent group design ---- negd$total <- rowSums(negd[, 1:25]) negd$anchor <- rowSums(negd[, 26:35]) negd_x <- freqtab(negd[1:1000, c("total", "anchor")], scales = list(0:25, 0:10)) negd_y <- freqtab(negd[1001:2000, c("total", "anchor")], scales = list(0:25, 0:10)) plot(negd_x, xlab = "Total Scores Form X", ylab = "Common Anchor Scores Form X") # presmoothing smooth_x <- presmoothing(negd_x, smoothmethod = "loglinear") smooth_y <- presmoothing(negd_y, smoothmethod = "loglinear") plot(smooth_x, xlab = "Total Scores Form X", ylab = "Common Anchor Scores Form X") # linear tucker equating ---- negd_tucker <- equate(negd_x, negd_y, type = "linear", method = "tucker") negd_tucker$concordance
import { get } from 'lodash' import type { NextPage } from 'next' import Image from 'next/image' import Link from 'next/link' import { useRouter } from 'next/router' import { useEffect, useState } from 'react' import { Row, Col, Table, Pagination } from 'react-bootstrap' import sortIcon from '../../../assets/img/sort.svg' import { BackButton } from '../../../components/BackButton/BackButton' import { Loading } from '../../../components/Loading/Loading' import { useGetBlockQuery, GetBlockQuery, GetTransactionsByBlockQuery, useGetTransactionsByBlockQuery, } from '../../../generated' import { useToast } from '../../../hooks' import { useFormatIntl } from '../../../hooks/useFormatIntl' import { formatTimeAgo, showShortHash } from '../../../lib/utils' import withApollo from '../../../lib/withApollo' const Block: NextPage = () => { const { format } = useFormatIntl() const router = useRouter() const hash = router.query?.hash as string const { data, loading, error } = useGetBlockQuery({ variables: { hash } }) const block = get(data, 'getBlock', []) as GetBlockQuery['getBlock'] const [pagination, setPagination] = useState({ skip: 0, take: 5, orderAsc: false, blockHash: block.hash || hash }) const { data: txData, loading: txLoading, error: txError } = useGetTransactionsByBlockQuery({ variables: pagination }) const transactions = get(txData, 'getTransactions', []) as GetTransactionsByBlockQuery['getTransactions'] const { showErrorToast } = useToast() const toogleOrder = () => { setPagination({ ...pagination, orderAsc: !pagination.orderAsc }) } const nextPage = () => { const { skip, take } = pagination if (transactions.length < take) return setPagination({ ...pagination, skip: skip + take }) } const previousPage = () => { const { skip, take } = pagination const newSkip = skip - take setPagination({ ...pagination, skip: newSkip < 0 ? 0 : newSkip }) } useEffect(() => { if (!!error || !!txError) showErrorToast(String(error)) }, [error]) return ( <> <Row> <Col className="mb-4 d-flex align-items-center"> <BackButton /> <h4 className="d-flex gap-4 align-items-center"> <b>{format('summary')}</b> {loading && <Loading />} </h4> </Col> </Row> <Row> <Col> <Table className="ink_table"> <tbody data-testid="tbody-block"> <tr> <td className="black">{format('header_number')}</td> <td>{block.number}</td> </tr> <tr> <td className="black">{format('header_hash')}</td> <td> <Link href={'/block/details/' + block.hash}> <a>{block.hash}</a> </Link> </td> </tr> <tr> <td className="black">{format('header_timestamp')}</td> <td>{formatTimeAgo(block.timestamp, router.locale)}</td> </tr> <tr> <td className="black">{format('header_parent')}</td> <td> <Link href={'/block/details/' + block.parentHash}> <a>{block.parentHash}</a> </Link> </td> </tr> <tr> <td className="black">{format('header_size')}</td> <td>{block.encodedLength} bytes</td> </tr> </tbody> </Table> </Col> </Row> <Row> <Col xs="12"> <Table responsive hover className="ink_table"> <thead> <tr> <th>{format('header_tx_hash')}</th> <th>{format('header_block')}</th> <th onClick={() => toogleOrder()} role="button" className="d-flex align-center gap-1"> <Image src={sortIcon} width={20} height={20} /> {format('header_time')} </th> <th>{format('header_method')}</th> <th>{format('header_section')}</th> <th>{format('header_signer')}</th> </tr> </thead> <tbody data-testid="tbody-tx"> {transactions.map((transaction) => ( <tr key={transaction.hash}> <td className="black"> <Link href={'/transaction/details/' + transaction.hash}>{showShortHash(transaction.hash)}</Link> </td> <td className="black"> <Link href={'/block/details/' + transaction.blockHash}> {showShortHash(transaction.blockHash || '')} </Link> </td> <td>{formatTimeAgo(transaction.timestamp, router.locale)}</td> <td>{transaction.method}</td> <td>{transaction.section}</td> <td className="black">{transaction.signer}</td> </tr> ))} </tbody> </Table> {txLoading && <Loading />} </Col> <Col xs="12" className="d-flex justify-content-center my-4"> <Pagination> <Pagination.Prev data-testid="prev-btn" onClick={() => previousPage()} /> <Pagination.Next data-testid="next-btn" onClick={() => nextPage()} /> </Pagination> </Col> </Row> </> ) } export default withApollo(Block)
<?php namespace App\DataTables; use App\Models\AdminOrder; use Illuminate\Database\Eloquent\Builder as QueryBuilder; use Yajra\DataTables\EloquentDataTable; use Yajra\DataTables\Html\Builder as HtmlBuilder; use Yajra\DataTables\Html\Button; use Yajra\DataTables\Html\Column; use Yajra\DataTables\Html\Editor\Editor; use Yajra\DataTables\Html\Editor\Fields; use Yajra\DataTables\Services\DataTable; use DB; class AdminOrdersDataTable extends DataTable { /** * Build DataTable class. * * @param QueryBuilder $query Results from query() method. * @return \Yajra\DataTables\EloquentDataTable */ public function dataTable($query) { return datatables()->query($query) ->addColumn('action', function ($row) { dump($row); // $actionBtn = '<a href="' . route('admin.orderDetails', $row->orderinfo_id) . '" class="btn details btn-primary">Details</a>'; // return $actionBtn; })->rawColumns(['action']) ->setRowId('id'); } /** * Get query source of dataTable. * * @param \App\Models\AdminOrder $model * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $orders = DB::table('customer as c')->join('orderinfo as o', 'o.customer_id', '=', 'c.customer_id') ->join('orderline as ol', 'o.orderinfo_id', '=', 'ol.orderinfo_id') ->join('item as i', 'ol.item_id', '=', 'i.item_id') ->select('o.orderinfo_id', 'c.fname', 'c.lname', 'c.addressline', 'o.date_placed', 'o.status', DB::raw("SUM(ol.quantity * i.sell_price) as total")) ->groupBy('o.orderinfo_id', 'o.date_placed', 'o.orderinfo_id', 'c.fname', 'c.lname', 'c.addressline', 'o.status'); // ->get(); // dd($orders); return $orders; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html(): HtmlBuilder { return $this->builder() ->setTableId('adminorders-table') ->columns($this->getColumns()) ->minifiedAjax() // ->dom('Bfrtip') ->orderBy(1) ->selectStyleSingle() ->parameters([ 'dom' => 'Blfrtip', 'buttons' => ['export', 'print', 'reset', 'reload'], ]); } /** * Get the dataTable columns definition. * * @return array */ public function getColumns(): array { return [ Column::computed('action') ->exportable(false) ->printable(false) ->width(60) ->addClass('text-center'), // Column::make('orderinfo_id'), ['data' => 'orderinfo_id', 'name' => 'o.orderinfo_id', 'title' => 'order id'], ['data' => 'lname', 'name' => 'c.lname', 'title' => 'last name'], ['data' => 'fname', 'name' => 'c.fname', 'title' => 'first Name'], ['data' => 'addressline', 'name' => 'c.addressline', 'title' => 'address'], ['data' => 'date_placed', 'name' => 'o.date_placed', 'title' => 'date ordered'], ['data' => 'status', 'name' => 'o.status', 'title' => 'status'], // Column::make('c.fname')->title('first name'), // Column::make('customer.addressline'), // Column::make('customer.date_placed'), // Column::make('orderinfo.status'), Column::make('total')->searchable(false) ]; } /** * Get filename for export. * * @return string */ protected function filename(): string { return 'AdminOrders_' . date('YmdHis'); } }
''' - Un conjunto es una colección de elementos pero que está desordenado es decir no hay un índice. - No se permite elementos duplicados, los ignora. - No se garantiza el orden de entra de los elementos (es decir la salida sera diferente). - Como todas las colecciones, permite elementos de diferentes tipos. - Se crean: {} -Cuidado que un coonjunto = {}, crea un diccionario, forma de crear un set vacio set() ''' conjunto = {'a', 'b', 'c', 'd', 'e', 'e'} print(conjunto) # {'b', 'e', 'd', 'c', 'a'} print(type(conjunto)) # <class 'set'> # Mas ejemplos # 'naranja' no es igul a "Naranja" frutas = {'Naranja', 'Naranja', 'Pera', 'Naranja', 'Platano'} # mostrar el conjunto por pantalla print(frutas) # mostrar el tipo del conjunto print(type(frutas)) # agregar fresas al conjunto frutas.add('Fresas') print(frutas) # Eliminar platano frutas.remove('Platano') print(frutas) # Longitud print(len(frutas)) # quitar repeticiones en lista lista = [1, 2, 3, 3, 3, 2] lista1 = set(lista) print(lista1) # copiar otra = frutas.copy() print(otra) # Borra todos os elementos frutas.clear() print(frutas) # set() print(frutas) print(otra) # tambien podemos utilizar in y not in print('Fresas' in otra) print('Fresas' not in otra) # recorrer conjuntos for fruta in otra: print(fruta, end=(' -> ')) print()
<?php /** * Handle product stock reservation during checkout. */ namespace Automattic\WooCommerce\Checkout\Helpers; use Automattic\WooCommerce\Utilities\OrderUtil; defined( 'ABSPATH' ) || exit; /** * Stock Reservation class. */ final class ReserveStock { /** * Is stock reservation enabled? * * @var boolean */ private $enabled = true; /** * Constructor */ public function __construct() { // Table needed for this feature are added in 4.3. $this->enabled = get_option( 'woocommerce_schema_version', 0 ) >= 430; } /** * Is stock reservation enabled? * * @return boolean */ protected function is_enabled() { return $this->enabled; } /** * Query for any existing holds on stock for this item. * * @param \WC_Product $product Product to get reserved stock for. * @param integer $exclude_order_id Optional order to exclude from the results. * * @return integer Amount of stock already reserved. */ public function get_reserved_stock( $product, $exclude_order_id = 0 ) { global $wpdb; if ( ! $this->is_enabled() ) { return 0; } // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $this->get_query_for_reserved_stock( $product->get_stock_managed_by_id(), $exclude_order_id ) ); } /** * Put a temporary hold on stock for an order if enough is available. * * @throws ReserveStockException If stock cannot be reserved. * * @param \WC_Order $order Order object. * @param int $minutes How long to reserve stock in minutes. Defaults to woocommerce_hold_stock_minutes. */ public function reserve_stock_for_order( $order, $minutes = 0 ) { $minutes = $minutes ? $minutes : (int) get_option( 'woocommerce_hold_stock_minutes', 60 ); if ( ! $minutes || ! $this->is_enabled() ) { return; } try { $items = array_filter( $order->get_items(), function( $item ) { return $item->is_type( 'line_item' ) && $item->get_product() instanceof \WC_Product && $item->get_quantity() > 0; } ); $rows = array(); foreach ( $items as $item ) { $product = $item->get_product(); if ( ! $product->is_in_stock() ) { throw new ReserveStockException( 'woocommerce_product_out_of_stock', sprintf( /* translators: %s: product name */ __( '&quot;%s&quot; is out of stock and cannot be purchased.', 'woocommerce' ), $product->get_name() ), 403 ); } // If stock management is off, no need to reserve any stock here. if ( ! $product->managing_stock() || $product->backorders_allowed() ) { continue; } $managed_by_id = $product->get_stock_managed_by_id(); /** * Filter order item quantity. * * @param int|float $quantity Quantity. * @param WC_Order $order Order data. * @param WC_Order_Item_Product $item Order item data. */ $item_quantity = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item ); $rows[ $managed_by_id ] = isset( $rows[ $managed_by_id ] ) ? $rows[ $managed_by_id ] + $item_quantity : $item_quantity; } if ( ! empty( $rows ) ) { foreach ( $rows as $product_id => $quantity ) { $this->reserve_stock_for_product( $product_id, $quantity, $order, $minutes ); } } } catch ( ReserveStockException $e ) { $this->release_stock_for_order( $order ); throw $e; } } /** * Release a temporary hold on stock for an order. * * @param \WC_Order $order Order object. */ public function release_stock_for_order( $order ) { global $wpdb; if ( ! $this->is_enabled() ) { return; } $wpdb->delete( $wpdb->wc_reserved_stock, array( 'order_id' => $order->get_id(), ) ); } /** * Reserve stock for a product by inserting rows into the DB. * * @throws ReserveStockException If a row cannot be inserted. * * @param int $product_id Product ID which is having stock reserved. * @param int $stock_quantity Stock amount to reserve. * @param \WC_Order $order Order object which contains the product. * @param int $minutes How long to reserve stock in minutes. */ private function reserve_stock_for_product( $product_id, $stock_quantity, $order, $minutes ) { global $wpdb; $product_data_store = \WC_Data_Store::load( 'product' ); $query_for_stock = $product_data_store->get_query_for_stock( $product_id ); $query_for_reserved_stock = $this->get_query_for_reserved_stock( $product_id, $order->get_id() ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared $result = $wpdb->query( $wpdb->prepare( " INSERT INTO {$wpdb->wc_reserved_stock} ( `order_id`, `product_id`, `stock_quantity`, `timestamp`, `expires` ) SELECT %d, %d, %d, NOW(), ( NOW() + INTERVAL %d MINUTE ) FROM DUAL WHERE ( $query_for_stock FOR UPDATE ) - ( $query_for_reserved_stock FOR UPDATE ) >= %d ON DUPLICATE KEY UPDATE `expires` = VALUES( `expires` ), `stock_quantity` = VALUES( `stock_quantity` ) ", $order->get_id(), $product_id, $stock_quantity, $minutes, $stock_quantity ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared if ( ! $result ) { $product = wc_get_product( $product_id ); throw new ReserveStockException( 'woocommerce_product_not_enough_stock', sprintf( /* translators: %s: product name */ __( 'Not enough units of %s are available in stock to fulfil this order.', 'woocommerce' ), $product ? $product->get_name() : '#' . $product_id ), 403 ); } } /** * Returns query statement for getting reserved stock of a product. * * @param int $product_id Product ID. * @param integer $exclude_order_id Optional order to exclude from the results. * @return string|void Query statement. */ private function get_query_for_reserved_stock( $product_id, $exclude_order_id = 0 ) { global $wpdb; $join = "$wpdb->posts posts ON stock_table.`order_id` = posts.ID"; $where_status = "posts.post_status IN ( 'wc-checkout-draft', 'wc-pending' )"; if ( OrderUtil::custom_orders_table_usage_is_enabled() ) { $join = "{$wpdb->prefix}wc_orders orders ON stock_table.`order_id` = orders.id"; $where_status = "orders.status IN ( 'wc-checkout-draft', 'wc-pending' )"; } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $query = $wpdb->prepare( " SELECT COALESCE( SUM( stock_table.`stock_quantity` ), 0 ) FROM $wpdb->wc_reserved_stock stock_table LEFT JOIN $join WHERE $where_status AND stock_table.`expires` > NOW() AND stock_table.`product_id` = %d AND stock_table.`order_id` != %d ", $product_id, $exclude_order_id ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared /** * Filter: woocommerce_query_for_reserved_stock * Allows to filter the query for getting reserved stock of a product. * * @since 4.5.0 * @param string $query The query for getting reserved stock of a product. * @param int $product_id Product ID. * @param int $exclude_order_id Order to exclude from the results. */ return apply_filters( 'woocommerce_query_for_reserved_stock', $query, $product_id, $exclude_order_id ); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>영화 리뷰 사이트</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <style> @import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"); </style> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> </head> <body> <nav class="navbar bg-body-tertiary"> <div class="container"> <a class="navbar-brand" href="/movie"> <img src="https://e7.pngegg.com/pngimages/593/726/png-clipart-film-director-clapperboard-film-festival-filmmaking-actor-celebrities-camera-icon.png" alt="Logo" width="120" height="90"> </a> <!-- 마이페이지 버튼 , 로그인하지 않으면 보이지 않음--> {% if g.user%} <ul class="navbar-nav ml-auto"> <span class="navbar-text mr-3">안녕하세요, {{ g.user.username }}</span> <a href="/mypage" class="btn btn-outline-secondary">마이페이지</a> </ul> {% endif %} </div> </nav> <!-- 영화 정보 --> <div class="container px-4 py-5" id="featured-3"> <h2> {{ data.movie_info.movieNm }}</h2> <h6 class="pb-2 border-bottom"> {{ data.movie_info.movieNmEn }} </h6> <div class="row g-4 py-5 row-cols-1 row-cols-lg-3"> <div class="feature col"> <div class="feature-icon d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-2 mb-3" style="width: 64px; height: 64px; border-radius: 50%;"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-film" viewBox="0 0 16 16"> <path d="M0 1a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1zm4 0v6h8V1zm8 8H4v6h8zM1 1v2h2V1zm2 3H1v2h2zM1 7v2h2V7zm2 3H1v2h2zm-2 3v2h2v-2zM15 1h-2v2h2zm-2 3v2h2V4zm2 3h-2v2h2zm-2 3v2h2v-2zm2 3h-2v2h2z"/> </svg> </div> <p>영화 개봉일</p> <h3 class="fs-2 text-body-emphasis">{{ data.movie_info.openDt }}</h3> <h6>{{ data.movie_info.prdtStatNm }}</h6> </div> <div class="feature col"> <div class="feature-icon d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-2 mb-3" style="width: 64px; height: 64px; border-radius: 50%;"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-people-fill" viewBox="0 0 16 16"> <path d="M7 14s-1 0-1-1 1-4 5-4 5 3 5 4-1 1-1 1zm4-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6m-5.784 6A2.24 2.24 0 0 1 5 13c0-1.355.68-2.75 1.936-3.72A6.3 6.3 0 0 0 5 9c-4 0-5 3-5 4s1 1 1 1zM4.5 8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5"/> </svg> </div> <p>장르</p> <h3 class="fs-2 text-body-emphasis">{{ data.movie_info.genreAlt }}</h3> </div> <div class="feature col"> <div class="feature-icon d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-2 mb-3" style="width: 64px; height: 64px; border-radius: 50%;"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-star-fill" viewBox="0 0 16 16"> <path d="M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z"/> </svg> </div> <p>관람 평점</p> <h3 class="fs-2 text-body-emphasis">{{ data.rating }}</h3> </div> </div> </div> <!-- 리뷰 작성/수정 모달창 --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content rounded-4 shadow"> <div class="modal-header p-5 pb-4 border-bottom-0"> <h1 class="fw-bold mb-0 fs-2">리뷰를 작성해 주세요!</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body p-5 pt-0"> <form id="reviewForm" action="{{ url_for('review_create') }}" method="POST"> <div class="form-floating mb-3"> <input type="hidden" id="reviewId" name="review_id" value=""> <!-- hidden 요소를 사용하여 사용자에게 보이지 않고 '영화 코드' 정보를 서버로 전송 --> <input type="hidden" class="form-control rounded-3" id="movieCd" name="movie_cd" value="{{ data.movie_info.movieCd }}"> <input type="hidden" class="form-control rounded-3" id="movieNm" name="movie_nm" value="{{ data.movie_info.movieNm }}"> </div> <div class="form-floating mb-3"> <p>이름 : {{ g.user.username }}</p> </div> <div class="form-floating mb-3"> <textarea class="form-control rounded-3" id="content" placeholder="Your message" style="height: 10rem;" name="content"></textarea> <label for="content">관람평</label> </div> <div class="input-group mb-3"> <label class="input-group-text" for="ratingSelect">별점</label> <select class="form-select" id="ratingSelect" name="rating"> <option selected disabled>Select rating...</option> <option value="1">⭐</option> <option value="2">⭐⭐</option> <option value="3">⭐⭐⭐</option> <option value="4">⭐⭐⭐⭐</option> <option value="5">⭐⭐⭐⭐⭐</option> </select> </div> <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">올리기</button> </form> </div> </div> </div> </div> <!-- 리뷰 --> <div class="container px-4 py-5"> <!-- 로그인하지 않으면 리뷰작성 버튼이 보이지 않는다. --> {% if g.user%} <div class="d-grid gap-2 d-md-flex justify-content-md-start mb-3"> <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">리뷰 작성하기</button> </div> {% endif %} <div class="list-group"> {% for review in data.reviews %} <a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3" aria-current="true"> <div class="d-flex gap-2 w-100 justify-content-between"> <div> <h6 class="mb-0">{{ review.user.username }}</h6> <p class="mb-0 opacity-75"> {% for _ in range( review.rating ) %} ⭐ {% endfor %} </p> <p class="mb-0 opacity-75">{{ review.content }}</p> </div> <small class="opacity-50 text-nowrap">{{ review.created_at }}</small> </div> <!-- 로그인한 사용자와 글쓴이가 같은 경우에만 버튼이 보이도록 함. --> {% if g.user == review.user %} <form action="{{ url_for('review_delete', review_id=review.id) }}" method="POST"> <button class="btn btn-outline-danger btn-sm" type="submit" style="width: 2rem; height: 2rem; padding: 0;"> <i class="bi bi-x" style="font-size: 1rem;"></i> </button> </form> <button class="btn btn-outline-warning btn-sm" type="button" style="width: 2rem; height: 2rem; padding: 0;" onclick="editReview('{{ review.id }}', '{{ review.rating }}', '{{ review.content }}')" data-bs-toggle="modal" data-bs-target="#exampleModal"> <i class="bi bi-pencil" style="font-size: 1rem;"></i> </button> {% endif %} </a> {% endfor %} </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> <script> function editReview(id, rating, content) { document.getElementById('reviewForm').action = "{{ url_for('review_update') }}"; document.getElementById('reviewId').value = id; document.getElementById('content').value = content; document.getElementById('ratingSelect').value = rating; var modal = new bootstrap.Modal(document.getElementById('exampleModal')); modal.show(); } </script> </body> </html>
/** * A type describes a valid set of values. * * (C) 2021 Malcolm Tyrrell * * Licensed under the GPLv3.0. See LICENSE file. **/ #pragma once #include <BabelWiresLib/TypeSystem/typeRef.hpp> #include <BabelWiresLib/TypeSystem/valueHolder.hpp> #include <Common/Identifiers/identifier.hpp> namespace babelwires { /// A type describes a valid set of values. /// Note that a value can be an instance of more than one type. /// A type is a subtypes of another type when all its values are valid /// values of the other. /// Information about subtype relationships is managed by the TypeSystem. class Type { public: DOWNCASTABLE_TYPE_HIERARCHY(Type); virtual ~Type(); /// Create a new Value representing a default instance of the type. virtual NewValueHolder createValue(const TypeSystem& typeSystem) const = 0; /// Is the value v an element of this type. virtual bool isValidValue(const TypeSystem& typeSystem, const Value& v) const = 0; /// Get a TypeRef that describes this type. /// Primitive types get an implementation of this method from the PRIMITIVE_TYPE macro. /// Complex types constructed by TypeConstructors must provide their own implementation. virtual TypeRef getTypeRef() const = 0; /// Return a short string which defines the kind of values this type handles. virtual std::string getKind() const = 0; /// Are two types constructed by this type constructor related by subtyping? /// By default, this returns IsUnrelated. virtual SubtypeOrder compareSubtypeHelper(const TypeSystem& typeSystem, const Type& other) const; /// Confirm that the supertype is the expected parent. /// The default implementation asserts. virtual bool verifySupertype(const Type& supertype) const; /// Convenience function which returns a human-readable version of the type's TypeRef. std::string getName() const; /// An identifier which can be used to group related types together. using Tag = MediumId; /// Get the tags associated with this type. const std::vector<Tag>& getTags() const; protected: /// Only intended for use during subclass construction. void addTag(Tag tag); private: /// The tags associated with this type. std::vector<Tag> m_tags; }; } // namespace babelwires
<?php /** * @file * Contains \Drupal\system\Plugin\system\imagetoolkit\GDToolkit;. */ namespace Drupal\system\Plugin\system\imagetoolkit; use Drupal\Component\Plugin\PluginBase; use Drupal\Component\Annotation\Plugin; use Drupal\Core\Annotation\Translation; use Drupal\system\Plugin\ImageToolkitInterface; /** * Defines the GD2 toolkit for image manipulation within Drupal. * * @Plugin( * id = "gd", * title = @Translation("GD2 image manipulation toolkit") * ) */ class GDToolkit extends PluginBase implements ImageToolkitInterface { /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::settingsForm(). */ public function settingsForm() { $form['image_jpeg_quality'] = array( '#type' => 'number', '#title' => t('JPEG quality'), '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'), '#min' => 0, '#max' => 100, '#default_value' => config('system.image.gd')->get('jpeg_quality'), '#field_suffix' => t('%'), ); return $form; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::settingsFormSubmit(). */ public function settingsFormSubmit($form, &$form_state) { config('system.image.gd') ->set('jpeg_quality', $form_state['values']['gd']['image_jpeg_quality']) ->save(); } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::resize(). */ public function resize($image, $width, $height) { $res = $this->createTmp($image, $width, $height); if (!imagecopyresampled($res, $image->resource, 0, 0, 0, 0, $width, $height, $image->info['width'], $image->info['height'])) { return FALSE; } imagedestroy($image->resource); // Update image object. $image->resource = $res; $image->info['width'] = $width; $image->info['height'] = $height; return TRUE; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::rotate(). */ public function rotate($image, $degrees, $background = NULL) { // PHP installations using non-bundled GD do not have imagerotate. if (!function_exists('imagerotate')) { watchdog('image', 'The image %file could not be rotated because the imagerotate() function is not available in this PHP installation.', array('%file' => $image->source)); return FALSE; } $width = $image->info['width']; $height = $image->info['height']; // Convert the hexadecimal background value to a color index value. if (isset($background)) { $rgb = array(); for ($i = 16; $i >= 0; $i -= 8) { $rgb[] = (($background >> $i) & 0xFF); } $background = imagecolorallocatealpha($image->resource, $rgb[0], $rgb[1], $rgb[2], 0); } // Set the background color as transparent if $background is NULL. else { // Get the current transparent color. $background = imagecolortransparent($image->resource); // If no transparent colors, use white. if ($background == 0) { $background = imagecolorallocatealpha($image->resource, 255, 255, 255, 0); } } // Images are assigned a new color palette when rotating, removing any // transparency flags. For GIF images, keep a record of the transparent color. if ($image->info['extension'] == 'gif') { $transparent_index = imagecolortransparent($image->resource); if ($transparent_index != 0) { $transparent_gif_color = imagecolorsforindex($image->resource, $transparent_index); } } $image->resource = imagerotate($image->resource, 360 - $degrees, $background); // GIFs need to reassign the transparent color after performing the rotate. if (isset($transparent_gif_color)) { $background = imagecolorexactalpha($image->resource, $transparent_gif_color['red'], $transparent_gif_color['green'], $transparent_gif_color['blue'], $transparent_gif_color['alpha']); imagecolortransparent($image->resource, $background); } $image->info['width'] = imagesx($image->resource); $image->info['height'] = imagesy($image->resource); return TRUE; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::crop(). */ public function crop($image, $x, $y, $width, $height) { $res = $this->createTmp($image, $width, $height); if (!imagecopyresampled($res, $image->resource, 0, 0, $x, $y, $width, $height, $width, $height)) { return FALSE; } // Destroy the original image and return the modified image. imagedestroy($image->resource); $image->resource = $res; $image->info['width'] = $width; $image->info['height'] = $height; return TRUE; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::desaturate(). */ public function desaturate($image) { // PHP installations using non-bundled GD do not have imagefilter. if (!function_exists('imagefilter')) { watchdog('image', 'The image %file could not be desaturated because the imagefilter() function is not available in this PHP installation.', array('%file' => $image->source)); return FALSE; } return imagefilter($image->resource, IMG_FILTER_GRAYSCALE); } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::load(). */ public function load($image) { $extension = str_replace('jpg', 'jpeg', $image->info['extension']); $function = 'imagecreatefrom' . $extension; if (function_exists($function) && $image->resource = $function($image->source)) { if (!imageistruecolor($image->resource)) { // Convert indexed images to true color, so that filters work // correctly and don't result in unnecessary dither. $new_image = $this->createTmp($image, $image->info['width'], $image->info['height']); imagecopy($new_image, $image->resource, 0, 0, 0, 0, $image->info['width'], $image->info['height']); imagedestroy($image->resource); $image->resource = $new_image; } return (bool) $image->resource; } return FALSE; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::save(). */ public function save($image, $destination) { $scheme = file_uri_scheme($destination); // Work around lack of stream wrapper support in imagejpeg() and imagepng(). if ($scheme && file_stream_wrapper_valid_scheme($scheme)) { // If destination is not local, save image to temporary local file. $local_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_LOCAL); if (!isset($local_wrappers[$scheme])) { $permanent_destination = $destination; $destination = drupal_tempnam('temporary://', 'gd_'); } // Convert stream wrapper URI to normal path. $destination = drupal_realpath($destination); } $extension = str_replace('jpg', 'jpeg', $image->info['extension']); $function = 'image' . $extension; if (!function_exists($function)) { return FALSE; } if ($extension == 'jpeg') { $success = $function($image->resource, $destination, config('system.image.gd')->get('jpeg_quality')); } else { // Always save PNG images with full transparency. if ($extension == 'png') { imagealphablending($image->resource, FALSE); imagesavealpha($image->resource, TRUE); } $success = $function($image->resource, $destination); } // Move temporary local file to remote destination. if (isset($permanent_destination) && $success) { return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE); } return $success; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::getInfo(). */ public function getInfo($image) { $details = FALSE; $data = getimagesize($image->source); if (isset($data) && is_array($data)) { $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png'); $extension = isset($extensions[$data[2]]) ? $extensions[$data[2]] : ''; $details = array( 'width' => $data[0], 'height' => $data[1], 'extension' => $extension, 'mime_type' => $data['mime'], ); } return $details; } /** * Creates a truecolor image preserving transparency from a provided image. * * @param object $image * An image object. * @param int $width * The new width of the new image, in pixels. * @param int $height * The new height of the new image, in pixels. * * @return resource * A GD image handle. */ public function createTmp($image, $width, $height) { $res = imagecreatetruecolor($width, $height); if ($image->info['extension'] == 'gif') { // Grab transparent color index from image resource. $transparent = imagecolortransparent($image->resource); if ($transparent >= 0) { // The original must have a transparent color, allocate to the new image. $transparent_color = imagecolorsforindex($image->resource, $transparent); $transparent = imagecolorallocate($res, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']); // Flood with our new transparent color. imagefill($res, 0, 0, $transparent); imagecolortransparent($res, $transparent); } } elseif ($image->info['extension'] == 'png') { imagealphablending($res, FALSE); $transparency = imagecolorallocatealpha($res, 0, 0, 0, 127); imagefill($res, 0, 0, $transparency); imagealphablending($res, TRUE); imagesavealpha($res, TRUE); } else { imagefill($res, 0, 0, imagecolorallocate($res, 255, 255, 255)); } return $res; } /** * Implements \Drupal\system\Plugin\ImageToolkitInterface::isAvailable(). */ public static function isAvailable() { if ($check = get_extension_funcs('gd')) { if (in_array('imagegd2', $check)) { // GD2 support is available. return TRUE; } } return FALSE; } }
====== Proposal ====== Add a ''has'' generic method to ''Array.prototype'' that determines if the array contains a given value, determined by the internal %%[[SameValue]]%% algorithm. ====== Spec ====== **15.5.4.27 Array.prototype.has (searchElement, fromIndex = 0)** **has** compares //searchElement// to the elements of the array, in ascending order, using the SameValue algorithm (9.12), and if found, returns **true**; otherwise, **false** is returned. When the **has** method is called with one or two arguments, the following steps are taken: - Let //O// be the result of calling ToObject passing the **this** value as the argument. - ReturnIfAbrupt(//O//). - Let //lenValue// be the result of calling the %%[[Get]]%% internal method of //O// with the argument **''"length"''**. - Let //len// be ToUint32(//lenValue//). - ReturnIfAbrupt(//len//). - If //len// is 0, return **false**. - Let //pos// be ToInteger(//position//). (If //position// is **undefined**, this step produces the value 0). - ReturnIfAbrupt(//pos//). - Let //k// be min(max(//pos//, 0), //len//). - Repeat, while //k// < //len//, - Let //kPresent// be the result of calling the %%[[HasProperty]]%% internal method of //O// with argument ToString(//k//). - If //kPresent// is **true**, then - Let //elementK// be the result of calling the %%[[Get]]%% internal method of //O// with the argument ToString(//k//). - ReturnIfAbrupt(//elementK//). - Let //same// be the result of performing SameValue(//searchElement//, //elementK//). - If same is **true**, return **true**. - Increase //k// by 1. - Return **false**. The **length** property of the **has** method is 1. NOTE The **has** function is intentionally generic; it does not require that its **this** value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the **has** function can be applied successfully to an exotic object that is not an Array is implementation-dependent. ====== Discussion ====== The name of this was initially proposed as ''contains'' to match [[http://dom.spec.whatwg.org/#interface-domstringlist|DOMStringList in the DOM spec]]. The latest ES6 draft also has ''String.prototype.contains'' so we need to unify these names. ====== References ====== [[https://mail.mozilla.org/pipermail/es-discuss/2012-February/020726.html|es-discuss]].
from typing import List, Tuple, Any from deepxube.utils import data_utils from deepxube.nnet import nnet_utils from deepxube.nnet.nnet_utils import HeurFnQ from deepxube.environments.environment_abstract import State, Environment, Goal from deepxube.updaters.updater import Updater from deepxube.search.greedy_policy import greedy_test import torch from torch import Tensor import torch.optim as optim from torch.optim.optimizer import Optimizer import torch.nn as nn import os import pickle import numpy as np from numpy.typing import NDArray import time import sys import shutil import random class Status: def __init__(self, env: Environment[Any, Any], step_max: int, num_test_per_step: int): self.itr: int = 0 self.update_num: int = 0 # generate data self.state_t_steps_l: List[int] = [] for step in range(step_max + 1): self.state_t_steps_l.extend([step] * num_test_per_step) random.shuffle(self.state_t_steps_l) self.states_start_t: List[State] self.goals_t: List[Goal] print(f"Generating {num_test_per_step} test states per step ({step_max} steps, " f"{format(len(self.state_t_steps_l), ',')} total test states)") self.states_start_t, self.goals_t = env.get_start_goal_pairs(self.state_t_steps_l) # Initialize per_solved_best print("Initializing per solved best") heur_fn_qs, heur_procs = nnet_utils.start_heur_fn_runners(1, "", torch.device("cpu"), False, env.get_v_nnet(), env, all_zeros=True) per_solved: float = greedy_test(self.states_start_t, self.goals_t, self.state_t_steps_l, env, heur_fn_qs, max_solve_steps=1) print("Greedy policy solved: %.2f%%" % per_solved) self.per_solved_best: float = per_solved def do_update(step_max: int, update_num: int, env: Environment[Any, Any], step_update_max: int, num_states: int, eps_max: float, heur_fn_qs: List[HeurFnQ], update_batch_size: int) -> Tuple[List[NDArray[Any]], NDArray[np.float_]]: update_steps: int = int(min(update_num + 1, step_update_max)) # num_states: int = int(np.ceil(num_states / update_steps)) if update_num == 0: eps_max = 1.0 # Do updates output_time_start = time.time() print(f"Updating cost-to-go with value iteration. Generating {format(num_states, ',')} training states.") step_probs: List[float] = list(np.ones(1 + step_max) / (step_max + 1)) if step_update_max > 1: print("Using greedy policy with %i step(s)" % update_steps) updater: Updater = Updater(env, num_states, step_max, step_probs, heur_fn_qs, update_steps, "greedy", update_batch_size=update_batch_size, eps_max=eps_max) nnet_rep: List[NDArray[Any]] ctgs: NDArray[np.float_] nnet_rep, ctgs, is_solved = updater.update() # Print stats # per_solved = 100.0 * np.mean(is_solved) print("Produced %s states, (%.2f seconds)" % (format(ctgs.shape[0], ","), time.time() - output_time_start)) mean_ctg = ctgs[:, 0].mean() min_ctg = ctgs[:, 0].min() max_ctg = ctgs[:, 0].max() print("Cost-to-go (mean/min/max): %.2f/%.2f/%.2f" % (mean_ctg, min_ctg, max_ctg)) return nnet_rep, ctgs def load_data(model_dir: str, nnet_file: str, env: Environment[Any, Any], num_test_per_step: int, step_max: int) -> Tuple[nn.Module, Status]: status_file: str = "%s/status.pkl" % model_dir if os.path.isfile(nnet_file): nnet = nnet_utils.load_nnet(nnet_file, env.get_v_nnet()) else: nnet = env.get_v_nnet() status: Status if os.path.isfile(status_file): status = pickle.load(open("%s/status.pkl" % model_dir, "rb")) print(f"Loaded with itr: {status.itr}, update_num: {status.update_num}, " f"per_solved_best: {status.per_solved_best}") else: status = Status(env, step_max, num_test_per_step) pickle.dump(status, open(status_file, "wb"), protocol=-1) return nnet, status def make_batches(nnet_rep: List[NDArray[Any]], ctgs: NDArray[np.float_], batch_size: int) -> List[Tuple[List[NDArray[Any]], NDArray[np.float_]]]: num_examples = ctgs.shape[0] rand_idxs = np.random.choice(num_examples, num_examples, replace=False) ctgs = ctgs.astype(np.float32) start_idx = 0 batches = [] while (start_idx + batch_size) <= num_examples: end_idx = start_idx + batch_size idxs = rand_idxs[start_idx:end_idx] inputs_batch = [x[idxs] for x in nnet_rep] ctgs_batch = ctgs[idxs] batches.append((inputs_batch, ctgs_batch)) start_idx = end_idx return batches def train_nnet(nnet: nn.Module, nnet_rep: List[NDArray[Any]], ctgs: NDArray[np.float_], device: torch.device, batch_size: int, num_itrs: int, train_itr: int, lr: float, lr_d: float, display_itrs: int) -> float: # optimization criterion = nn.MSELoss() optimizer: Optimizer = optim.Adam(nnet.parameters(), lr=lr) # initialize status tracking start_time = time.time() # train network batches = make_batches(nnet_rep, ctgs, batch_size) nnet.train() max_itrs: int = train_itr + num_itrs last_loss: float = np.inf batch_idx: int = 0 while train_itr < max_itrs: # zero the parameter gradients optimizer.zero_grad() lr_itr: float = lr * (lr_d ** train_itr) for param_group in optimizer.param_groups: param_group['lr'] = lr_itr # get data inputs_batch_np, ctgs_batch_np = batches[batch_idx] ctgs_batch_np = ctgs_batch_np.astype(np.float32) # send data to device inputs_batch: List[Tensor] = nnet_utils.to_pytorch_input(inputs_batch_np, device) ctgs_batch: Tensor = torch.tensor(ctgs_batch_np, device=device)[:, 0] # forward ctgs_nnet: Tensor = nnet(inputs_batch) # loss loss = criterion(ctgs_nnet[:, 0], ctgs_batch) # backwards loss.backward() # step optimizer.step() last_loss = loss.item() # display progress if (display_itrs > 0) and (train_itr % display_itrs == 0): print("Itr: %i, lr: %.2E, loss: %.2E, targ_ctg: %.2f, nnet_ctg: %.2f, " "Time: %.2f" % ( train_itr, lr_itr, loss.item(), ctgs_batch.mean().item(), ctgs_nnet.mean().item(), time.time() - start_time)) start_time = time.time() train_itr = train_itr + 1 batch_idx += 1 if batch_idx >= len(batches): random.shuffle(batches) batch_idx = 0 return last_loss def train(env: Environment[Any, Any], step_max: int, nnet_dir: str, num_test_per_step: int = 30, itrs_per_update: int = 5000, epochs_per_update: int = 1, num_update_procs: int = 1, update_batch_size: int = 10000, update_nnet_batch_size: int = 10000, greedy_update_step_max: int = 1, greedy_update_eps_max: float = 0.1, lr: float = 0.001, lr_d: float = 0.9999993, max_itrs: int = 1000000, batch_size: int = 1000, display: int = 100, debug: bool = False): """ Train a deep neural network heuristic (DNN) function with deep approximate value iteration (DAVI). A target DNN is maintained for computing the updated heuristic values. When the greedy policy improves on a fixed test set, the target DNN is updated to be the current DNN. The number of steps taken for testing the greedy policy is the minimum between the number of target DNN updates and step_max. This makes the test a lot faster in the earlier stages, espeicially when step_max is large. For more information see: - Agostinelli, Forest, et al. "Solving the Rubik’s cube with deep reinforcement learning and search." Nature Machine Intelligence 1.8 (2019): 356-363. - Bertsekas, D. P. & Tsitsiklis, J. N. Neuro-dynamic Programming (Athena Scientific, 1996). :param env: an Environment object :param step_max: maximum number of steps to take to generate start/goal pairs :param nnet_dir: directory where DNN will be saved :param num_test_per_step: Number of test states for each step between 0 and step_max :param itrs_per_update: How many iterations to do before checking if target network should be updated :param epochs_per_update: How many epochs for which train. Making this greater than 1 could increase risk of overfitting, however, one can train for more iterations without having to generate more data.) :param num_update_procs: Number of parallel workers used to compute updated cost-to-go values :param update_batch_size: Maximum number of start/goal pairs when computing updated cost-to-go that each parallel worker generates at a time. Since multiprocessing is used, memory issues can happen if trying to send objects that are too large across processes. Therefore, if you update step freezes for no apparent reason, it could be a memory issue. Lowering this value or making the DNN representation more memory efficient could solve it. :param update_nnet_batch_size: Batch size of each nnet used for each process update. Make smaller if running out of memory. :param greedy_update_step_max: Maximum number of epsilon greedy policy steps (update_steps) to take from generated start states to generate additional data. Value of 1 is the same as basic DAVI. Increasing this number could make the heuristic function more robust to depression regions. The number of steps taken for the update is the minimum between the number of target DNN updates and greedy_update_step_max. Number of start/goal pairs is states_per_update/update_steps. :param greedy_update_eps_max: epsilon greedy policy max. Each start/goal pair will have an eps uniformly distributed between 0 and greedy_update_eps_max :param lr: Initial learning rate :param lr_d: Learning rate decay for every iteration. Learning rate is decayed according to: lr * (lr_d ^ itr) :param max_itrs: Maximum number of iterations :param batch_size: Batch size :param display: Number of iterations to display progress. No display if 0. :param debug: Turns off logging to make typing during breakpoints easier :return: None """ # Initialization targ_file: str = f"{nnet_dir}/target.pt" curr_file = f"{nnet_dir}/current.pt" output_save_loc = "%s/output.txt" % nnet_dir if not os.path.exists(nnet_dir): os.makedirs(nnet_dir) if not debug: sys.stdout = data_utils.Logger(output_save_loc, "a") # type: ignore # Print basic info # print("HOST: %s" % os.uname()[1]) print("CPU: %i" % num_update_procs) print("Batch size: %i" % batch_size) if 'SLURM_JOB_ID' in os.environ: print("SLURM JOB ID: %s" % os.environ['SLURM_JOB_ID']) # get device on_gpu: bool device: torch.device device, devices, on_gpu = nnet_utils.get_device() print("device: %s, devices: %s, on_gpu: %s" % (device, devices, on_gpu)) # load nnet print("Loading nnet and status") nnet, status = load_data(nnet_dir, curr_file, env, num_test_per_step, step_max) nnet.to(device) nnet = nn.DataParallel(nnet) # training while status.itr < max_itrs: # update all_zeros: bool = not os.path.isfile(targ_file) heur_fn_qs, heur_procs = nnet_utils.start_heur_fn_runners(num_update_procs, targ_file, device, on_gpu, env.get_v_nnet(), env, all_zeros=all_zeros, clip_zero=True, batch_size=update_nnet_batch_size) states_per_update: int = itrs_per_update * batch_size num_update_states: int = int(states_per_update) nnet_rep, ctgs = do_update(step_max, status.update_num, env, greedy_update_step_max, num_update_states, greedy_update_eps_max, heur_fn_qs, update_batch_size) nnet_utils.stop_heuristic_fn_runners(heur_procs, heur_fn_qs) # train nnet num_train_itrs: int = epochs_per_update * np.ceil(ctgs.shape[0] / batch_size) print("Training model for update number %i for %i iterations" % (status.update_num, num_train_itrs)) last_loss = train_nnet(nnet, nnet_rep, ctgs, device, batch_size, num_train_itrs, status.itr, lr, lr_d, display) status.itr += num_train_itrs # save nnet torch.save(nnet.state_dict(), curr_file) # test start_time = time.time() heur_fn_qs, heur_procs = nnet_utils.start_heur_fn_runners(num_update_procs, curr_file, device, on_gpu, env.get_v_nnet(), env, all_zeros=False, clip_zero=False, batch_size=update_nnet_batch_size) max_solve_steps: int = min(status.update_num + 1, step_max) print("Testing greedy policy with %i states and %i steps" % (len(status.states_start_t), max_solve_steps)) per_solved: float = greedy_test(status.states_start_t, status.goals_t, status.state_t_steps_l, env, heur_fn_qs, max_solve_steps=max_solve_steps) print("Greedy policy solved (best): %.2f%% (%.2f%%)" % (per_solved, status.per_solved_best)) nnet_utils.stop_heuristic_fn_runners(heur_procs, heur_fn_qs) print("Test time: %.2f" % (time.time() - start_time)) # clear cuda memory torch.cuda.empty_cache() update_nnet: bool if per_solved > status.per_solved_best: print("Updating target network") status.per_solved_best = per_solved update_nnet = True else: update_nnet = False print("Last loss was %f" % last_loss) if update_nnet: # Update nnet shutil.copy(curr_file, targ_file) status.update_num = status.update_num + 1 pickle.dump(status, open("%s/status.pkl" % nnet_dir, "wb"), protocol=-1) print("Done")
import { useAccount, useContractRead } from 'wagmi' import ABI_Npng from '../utils/ABI_Npng.json' import { ethers } from 'ethers' import { useAddressNetwork } from '../utils/useAddressNetwork' import { Fragment } from 'react' function RankingHistory({ setModalResult, setContest }: { setModalResult: React.Dispatch<React.SetStateAction<boolean>>, setContest: React.Dispatch<React.SetStateAction<number>> }) { const { address } = useAccount() const addressNetwork = useAddressNetwork() const { data } = useContractRead({ addressOrName: addressNetwork.npngContract, contractInterface: ABI_Npng, functionName: 'getAccountTable', args: [address] }) const displayResult = (rank: number, nbParticpants: number, prize: string) => { if (rank === 0) { return (<div className="grid-content-typo no-particpation-grey-color" > No participation</div>) } else { if (rank < 11) { return (<div className="grid-content-typo win-typo">$ {prize}</div>) } else { const result = parseInt(ethers.utils.formatUnits(rank, 0)) / parseInt(ethers.utils.formatUnits(nbParticpants, 0)); if (result * 100 < 10) { return (<div className="grid-content-typo top10-typo">Top 10%</div>) } else { return (<div className="grid-content-typo">You can do better...</div>) } } } } const colorText = (rank: number, nbParticpants: number) => { rank = parseInt(ethers.utils.formatUnits(rank, 0)); nbParticpants = parseInt(ethers.utils.formatUnits(nbParticpants, 0)); if (rank === 0) { return ("grid-content-typo no-particpation-grey-color") } else { if (rank < 11) { return ("grid-content-typo win-typo") } else { const result = parseInt(ethers.utils.formatUnits(rank, 0)) / parseInt(ethers.utils.formatUnits(nbParticpants, 0)); if (result * 100 < 10) { return ("grid-content-typo top10-typo") } else { return ("grid-content-typo") } } } } return ( <div className="div-block-46"> <div className="column-names">Contest #</div> <div className="column-names">Ranking</div> <div className="column-names">Participants</div> <div className="column-names">Results</div> {data && data.filter(element => parseInt(ethers.utils.formatUnits(element[0]._hex, 0)) > 0).map(filteredElement => <Fragment key={filteredElement}> <div className={colorText(filteredElement[1]._hex, filteredElement[2]._hex) + " pourquoi"} onClick={() => { setContest(parseInt(ethers.utils.formatUnits(filteredElement[0]._hex, 0))) setModalResult(true) }} >#{ethers.utils.formatUnits(filteredElement[0]._hex, 0)}</div> <div className={colorText(filteredElement[1]._hex, filteredElement[2]._hex)}> {(ethers.utils.formatUnits(filteredElement[1]._hex, 0) === "0") ? "n/a" : ethers.utils.formatUnits(filteredElement[1]._hex, 0)} </div> <div className={colorText(filteredElement[1]._hex, filteredElement[2]._hex)}>{ethers.utils.formatUnits(filteredElement[2]._hex, 0)}</div> {displayResult(parseInt(ethers.utils.formatUnits(filteredElement[1]._hex, 0)), parseInt(ethers.utils.formatUnits(filteredElement[2]._hex, 0)), ethers.utils.formatUnits(filteredElement[3]._hex, 6))} </Fragment>)} </div> ) } export default RankingHistory;
<?php namespace App\Student\Twig; use App\Entity\Avatar; use Symfony\Component\Serializer\SerializerInterface; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Error\SyntaxError; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; class StudentExtension extends AbstractExtension { public function __construct(private readonly SerializerInterface $serializer) { } /** * Registers Twig functions. * * @return TwigFunction[] */ public function getFunctions(): array { return [ new TwigFunction("avatar", [$this, "renderAvatar"], [ 'needs_environment' => true, 'is_safe' => ['html'] ]) ]; } /** * Renders the student's avatar. The data is taken from the avatar's entity, * serialized and passed to the template as a json string so our Stimulus * controller can read it and convert it back to a JS object. * * @param Environment $environment * @param Avatar $avatar * @param string|null $id * @return string * @throws LoaderError * @throws RuntimeError * @throws SyntaxError */ public function renderAvatar(Environment $environment, Avatar $avatar, string $id = null): string { return $environment->render("student/avatar.html.twig", [ "id" => $id, "avatar" => $this->serializer->serialize($avatar, 'json', ['groups' => 'avatar']), ]); } }
import React from 'react'; import {useParams} from "react-router-dom"; import { makeStyles } from '@material-ui/core/styles'; import { Link } from 'react-router-dom'; import Container from '@material-ui/core/Container'; import Grid from '@material-ui/core/Grid'; // import Divider from '@material-ui/core/Divider'; import TextField from '@material-ui/core/TextField'; import Typography from '@material-ui/core/Typography'; import InputAdornment from '@material-ui/core/InputAdornment'; import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; import SearchIcon from '@material-ui/icons/Search'; // import IconButton from '@material-ui/core/IconButton'; // import MoreVertIcon from '@material-ui/icons/MoreVert'; // import CreateIcon from '@material-ui/icons/Create'; // import DeleteIcon from '@material-ui/icons/Delete'; // import PersonIcon from '@material-ui/icons/Person'; // import AccountCircle from '@material-ui/icons/AccountCircle'; import Button from '@material-ui/core/Button'; import Avatar from '@material-ui/core/Avatar'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import GridList from '@material-ui/core/GridList'; import GridListTile from '@material-ui/core/GridListTile'; // import GridListTileBar from '@material-ui/core/GridListTileBar'; // import ListSubheader from '@material-ui/core/ListSubheader'; // import Menu from '@material-ui/core/Menu'; // import MenuItem from '@material-ui/core/MenuItem'; // import ListItemIcon from '@material-ui/core/ListItemIcon'; // import Dialog from '@material-ui/core/Dialog'; // import DialogActions from '@material-ui/core/DialogActions'; // import DialogContent from '@material-ui/core/DialogContent'; // import DialogContentText from '@material-ui/core/DialogContentText'; // import DialogTitle from '@material-ui/core/DialogTitle'; import { deepOrange, deepPurple } from '@material-ui/core/colors'; import { Scrollbars } from 'react-custom-scrollbars'; // import toastr from 'toastr' // import 'toastr/build/toastr.min.css' import albumService from "../../services/albums"; import toastr from 'toastr' import 'toastr/build/toastr.min.css' const classNames = require("classnames"); const moment = require("moment"); const useStyles = makeStyles((theme) => ({ root: { maxWidth: 345, }, backdrop: { zIndex: theme.zIndex.drawer + 1, color: '#fff', }, media: { height: 0, paddingTop: '56.25%', // 16:9 }, card: { height: '100%', display: 'flex', flexDirection: 'column', }, cardMedia: { paddingTop: '56.25%', // 16:9 }, cardContent: { flexGrow: 1, }, cardGrid: { paddingTop: theme.spacing(2), paddingBottom: theme.spacing(8), }, gridContent: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', overflow: 'hidden', backgroundColor: theme.palette.background.paper, }, gridList: { width: 500, height: 250, }, orange: { color: theme.palette.getContrastText(deepOrange[500]), backgroundColor: deepOrange[500], }, purple: { color: theme.palette.getContrastText(deepPurple[500]), backgroundColor: deepPurple[500], }, })); function getTimeDiff(dateCreated){ let now = moment(Date.now()); let last = moment(dateCreated); let minutes = now.diff(last, 'minutes'), hours = now.diff(last, 'hours'), days = now.diff(last, 'days'), weeks = now.diff(last, 'weeks'), months = now.diff(last, 'months'), years = now.diff(last, 'years'); if(years>0){ if((months-years*12)>0) return years+" ans et "+(months-years*12)+" mois"; else return years+" ans"; } if(months>0){ if((days-months*30)>0) return months+" mois et "+(days-months*30)+" jours"; else return months+" mois"; } if(weeks>0){ if((days-weeks*7)>0) return weeks+" semaines et "+(days-weeks*7)+" jours"; else return weeks+" semaines"; } if(days>0){ if((hours-days*24)>0) return days+" jours et "+(hours-days*24)+" heures"; else return days+" jours"; } if(hours>0){ if((minutes-hours*60)>0) return hours+" heures et "+(minutes-hours*60)+" minutes"; else return hours+" heures" } if(minutes>0) return minutes+" minutes"; } export default function (props) { const classes = useStyles(); let { tag } = useParams(); const [error, setError] = React.useState(false); const [loading, setLoading] = React.useState(true); const [albums, setAlbums] = React.useState([]); const [search, setSearch] = React.useState(''); const handleSearch = (event) => { event.preventDefault(); setSearch(event.target.value); if(search !== ""){ albumService.findTag(event.target.value).then(rep =>{ setAlbums(rep.data); if(rep.data.length===0) setError("Aucuns résultats"); }, err => { if(err.response.status>400 && err.response.status<500) toastr.warning(err.response.data, "Erreur " + err.response.status); else toastr.error(err.response.data, "Erreur " + err.response.status); }); }; } React.useEffect(() => { if(!tag){ setLoading(false); // setError("Pas de tag"); }else{ setSearch(tag); albumService.findTag(tag).then(rep => { setAlbums(rep.data); if(rep.data.length===0) setError("Aucuns résultats"); setLoading(false); }, err => { setLoading(false); setError("Erreur "+err.response.status+" : "+err.response.data); }); } }, [tag]); return ( <Container className={classes.cardGrid} maxWidth={false}> {loading ? ( <Backdrop className={classes.backdrop} open={true}> <CircularProgress color="inherit" /> </Backdrop> ) : (error ? ( <Typography variant="body2" color="textSecondary" align="center">{error}</Typography> ) : ( <div> {/* <Card> <CardContent> <TextField variant="outlined" required fullWidth autoFocus id="email" label="Rechercher un album" value={search} onInput={handleSearch} name="email" autoComplete="Email, nom, prenom" InputProps={{ startAdornment: (<InputAdornment position="start"><SearchIcon color="textSecondary" /></InputAdornment>) }} /> <Typography variant="body2" color="textSecondary" align="right" style={{paddingTop:6}}>{albums.length>0 ? albums.length : "Aucuns"} albums trouvés</Typography> </CardContent> </Card>*/} <Grid container spacing={4}> {albums.map((album) => ( <Grid item key={album._id} xs={12} sm={6} md={4} > <Card className={classes.card}> <CardHeader avatar={ <Link to={"/Album/"+album._id} style={{ color:"inherit", textDecoration:"none" }}> <Avatar aria-label="recipe" className={classes.purple}> {album.name.charAt(0).toUpperCase()} </Avatar> </Link> } title={<Link to={"/Album/"+album._id} style={{ color:"inherit", textDecoration:"none" }}><Typography variant="h6" displayInline>{album.name}</Typography></Link>} subheader={<Typography variant="caption" gutterBottom displayInline>{"il y a "+getTimeDiff(album.dateCreated)}</Typography>} /> <CardContent className={classNames(classes.cardContent, classes.gridContent)}> <Scrollbars autoHide autoHeight> <GridList cellHeight={150}> {album.photos.map((photo) => ( <GridListTile key={photo._id} cols={1}> <img src={"/images/photos/medium/"+photo.src} alt={photo.src} /> </GridListTile> ))} </GridList> </Scrollbars> </CardContent> <CardActions> <Link to={"/Album/"+album._id}> <Button size="small" color="primary">{album.nbLikes} Likes</Button> </Link> <Link to={"/Album/"+album._id}> <Button size="small" color="primary">{album.nbCommentaires} Commentaires</Button> </Link> <Link to={"/Album/"+album._id}> <Button size="small" color="primary">{album.nbVues} Vues</Button> </Link> </CardActions> </Card> </Grid> ))} </Grid> </div> ) )} </Container> ); };
using GZCTF.Models.Request.Game; namespace GZCTF.Repositories.Interface; public interface IGameRepository : IRepository { /// <summary> /// 获取指定数量的比赛对象基本信息 /// </summary> /// <param name="count"></param> /// <param name="skip"></param> /// <param name="token"></param> /// <returns></returns> public Task<BasicGameInfoModel[]> GetBasicGameInfo(int count = 10, int skip = 0, CancellationToken token = default); /// <summary> /// 获取指定数量的比赛对象 /// </summary> /// <param name="count"></param> /// <param name="skip"></param> /// <param name="token"></param> /// <returns></returns> public Task<Game[]> GetGames(int count = 10, int skip = 0, CancellationToken token = default); /// <summary> /// 获取最近将要开始的比赛 id /// </summary> /// <param name="token"></param> /// <returns></returns> public Task<int[]> GetUpcomingGames(CancellationToken token = default); /// <summary> /// 根据Id获取比赛对象 /// </summary> /// <param name="id">比赛Id</param> /// <param name="token"></param> /// <returns></returns> public Task<Game?> GetGameById(int id, CancellationToken token = default); /// <summary> /// 创建比赛对象 /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> /// <returns></returns> public Task<Game?> CreateGame(Game game, CancellationToken token = default); /// <summary> /// 获取队伍Token /// </summary> /// <param name="game">比赛对象</param> /// <param name="team">参赛队伍对象</param> /// <returns></returns> public string GetToken(Game game, Team team); /// <summary> /// 获取排行榜 /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> /// <returns></returns> public Task<ScoreboardModel> GetScoreboard(Game game, CancellationToken token = default); /// <summary> /// 获取带有队伍成员信息的排行榜 /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> /// <returns></returns> public Task<ScoreboardModel> GetScoreboardWithMembers(Game game, CancellationToken token = default); /// <summary> /// 删除比赛 /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> /// <returns></returns> public Task<TaskStatus> DeleteGame(Game game, CancellationToken token = default); /// <summary> /// 删除比赛的全部 WriteUp /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> /// <returns></returns> public Task DeleteAllWriteUps(Game game, CancellationToken token = default); /// <summary> /// 生成排行榜 /// </summary> /// <param name="game">比赛对象</param> /// <param name="token"></param> public Task<ScoreboardModel> GenScoreboard(Game game, CancellationToken token = default); /// <summary> /// 刷新比赛信息缓存 /// </summary> public void FlushGameInfoCache(); }
;;;; Copyright (c) 2011-2014 jnjcc, Yste.org. All rights reserved. ;;;; ;;;; final QR code symbol (in-package #:cl-qrencode) (defclass qr-symbol () ((matrix :initform nil :initarg :matrix :reader matrix :documentation "qr code symbol as matrix") (modules :initform nil :initarg :modules :reader modules :documentation "qr code symbol modules"))) (defmethod print-object ((symbol qr-symbol) stream) (fresh-line stream) (with-slots (matrix modules) symbol (format stream "qr symbol ~A x ~A:~%" modules modules) (dotimes (i modules) (dotimes (j modules) (if (dark-module-p matrix i j) (format stream "1 ") (format stream "0 "))) (format stream "~%")))) ;;; FIXME: other encodings??? (defun ascii->bytes (text) (map 'list #'char-code text)) (defun bytes->input (bytes version level mode) (setf version (min (max version 1) 40)) (let ((input (make-instance 'qr-input :bytes bytes :version version :ec-level level :mode mode))) (data-encoding input) (ec-coding input) (structure-message input) (module-placement input) input)) (defun input->symbol (input) "encode qr symbol from a qr-input" (multiple-value-bind (matrix mask-ref) (data-masking input) (declare (ignore mask-ref)) (let ((modules (matrix-modules (version input)))) (make-instance 'qr-symbol :matrix matrix :modules modules)))) (defun encode-symbol-bytes (bytes &key (version 1) (level :level-m) (mode nil)) "encode final qr symbol from BYTES list" (let ((input (bytes->input bytes version level mode))) (dbg :dbg-input "version: ~A; segments: ~A~%" (version input) (segments input)) (input->symbol input))) ;;;----------------------------------------------------------------------------- ;;; One Ring to Rule Them All, One Ring to Find Them, ;;; One Ring to Bring Them All and In the Darkness Blind Them: ;;; This function wraps all we need. ;;;----------------------------------------------------------------------------- ;; (sdebug :dbg-input) (defun encode-symbol (text &key (version 1) (level :level-m) (mode nil)) "encode final qr symbol, unless you know what you are doing, leave MODE NIL" (let ((bytes (ascii->bytes text))) (encode-symbol-bytes bytes :version version :level level :mode mode)))
### Note: This was mini project for Data Structures and Algorithm Course - NMAMIT # Word Dictionary using Trie data structure Using a Trie data structure for storing a word dictionary has several advantages over using a direct dictionary (hashmap) where words are mapped to their meanings: ## Advantages of Trie over Hashmap ### 1. Space Efficiency - Trie typically consumes less memory compared to a hashmap, especially when storing a large number of words with common prefixes. This is because Trie shares common prefixes among words, resulting in space savings. ### 2. Prefix Search - Trie allows for efficient prefix search. You can easily find all words with a given prefix, which is useful in autocomplete functionality or searching for words with similar beginnings. ### 3. Ordered Iteration - Trie maintains the lexical order of words. It can be beneficial when you need to iterate through the dictionary in alphabetical order, which is not guaranteed with a hashmap. ### 4. Memory Optimization - In some cases, especially with large dictionaries, using a Trie can be more memory-efficient than a hashmap. This is because Tries store similar prefixes only once, whereas hashmaps may have overhead due to hash collisions and internal data structures. ### 5. Efficient Memory Usage - Tries tend to have a more predictable memory usage pattern compared to hashmaps, especially when dealing with datasets where the distribution of words' lengths is wide. ### 6. Specialized Use Cases - Tries are suitable for specialized use cases like spell checking, autocomplete, and dictionary search operations. They provide efficient algorithms for these tasks due to their structure. However, it's important to consider the trade-offs. Tries may have higher memory overhead per node compared to hashmaps, especially when dealing with small dictionaries or when words have few common prefixes. Additionally, Tries may have slower insertions and deletions compared to hashmaps in certain scenarios. Therefore, the choice between Trie and hashmap depends on the specific requirements of your application, such as memory constraints, the nature of the dataset, and the operations you need to perform frequently. ## Performance Comparison The performance comparison between Trie and hashmap depends on various factors, including the specific operations you perform and the characteristics of your dataset. Here's a general comparison: ### Insertion and Deletion - Hashmaps generally have faster average-case insertion and deletion times compared to Tries because they involve simple hash computation and direct memory access. However, in worst-case scenarios with hash collisions, insertion and deletion operations may degrade to O(n) time complexity. - Tries have predictable O(m) time complexity for insertion and deletion, where m is the length of the word. While this can be slower than hashmaps in some cases, it remains consistent regardless of the dataset's characteristics. ### Search - Hashmaps typically have O(1) average-case time complexity for search operations. However, worst-case scenarios can lead to O(n) time complexity due to hash collisions. - Tries have O(m) time complexity for search operations, where m is the length of the word. While this may seem slower than hashmaps, it's still efficient and remains consistent regardless of hash collisions. ### Prefix Search - Tries excel in prefix search operations, where you need to find all words with a given prefix. This operation has a time complexity of O(k), where k is the length of the prefix. Hashmaps would require additional preprocessing or a different data structure to achieve similar efficiency. ### Memory Usage - Hashmaps may have more predictable memory usage patterns and lower memory overhead per stored element compared to Tries, especially for datasets with many short words or where words have few common prefixes. - Tries may consume more memory due to storing individual characters at each node and sharing common prefixes among words. In summary, hashmaps are generally faster for average-case scenarios and have lower memory overhead per stored element. However, Tries provide predictable performance, efficient prefix search, and ordered iteration, making them suitable for specific use cases like autocomplete, spell checking, and dictionary search operations. Ultimately, the choice between Trie and hashmap depends on your specific requirements, the characteristics of your dataset, and the operations you perform most frequently.
import { html } from "lit-html"; import { Canvas, Meta, Story } from '@storybook/addon-docs'; import AzBanner from '@az-digital/az-web-components'; <Meta title="AzBanner" component={AzBanner} argTypes={{ theme: { options: ['az-red', 'az-blue'], control: { type: 'radio' } }, fluid: { options: ['fluid', ''], control: 'boolean', } }} /> export const Template = (args) => { return html`<az-banner ${args.fluid} theme="${args.theme}"></az-banner>`; }; # University of Arizona -- Banner <Canvas> <Story name="Primary" args={{ theme: 'primary', fluid: false, }}> {Template.bind({})} </Story> </Canvas>
const { expect } = require('chai'); const request = require('request'); describe('Index Page', () => { it('should respond with the correct status code', (done) => { request('http://localhost:7865', (error, res, body) => { if (error) return done(error); expect(res.statusCode).to.equal(200); done(); }); }); it('should have the correct content of the body', (done) => { request('http://localhost:7865', (error, res, body) => { if (error) return done(error); expect(body).to.contain('Welcome to the payment system'); done(); }); }); it('should have the correct Content-Type', (done) => { request('http://localhost:7865', (error, res, body) => { if (error) return done(error); expect(res.headers['content-type']).to.equal('text/html; charset=utf-8'); done(); }); }); it('should have the correct Content-Length', (done) => { request('http://localhost:7865', (error, res, body) => { if (error) return done(error); expect(res.headers['content-length']).to.equal('29'); done(); }); }); }); describe('Cart Page', () => { it('should have correct status code with numeric id parameter', (done) => { request('http://localhost:7865', (error, res, body) => { expect(res.statusCode).to.equal(200); done(error); }); }); it('should have correct result with numeric id parameter', (done) => { request('http://localhost:7865/cart/12', (error, res, body) => { expect(body).to.contain('Payment methods for cart 12'); done(error); }); }); it('should have correct status code when non-numeric id parameter is provided', (done) => { request('http://localhost:7865/cart/hello', (error, res, body) => { expect(res.statusCode).to.equal(404); done(error); }); }); it('should return the correct content-type given valid id parameter', (done) => { request('http://localhost:7865/cart/12', (error, res, body) => { expect(res.headers['content-type']).to.equal('text/html; charset=utf-8'); done(error); }); }); it('should return the correct content in the body when non-numeric id is provided', (done) => { request('http://localhost:7865/cart/hello', (error, res, body) => { expect(body).to.contain('Cannot GET /cart/hello'); done(error); }); }); it('should return the correct content length', (done) => { request('http://localhost:7865/cart/12', (error, res, body) => { expect(res.headers['content-length']).to.equal('27'); done(error); }); }); }); describe('/available_payments', () => { it('should return status code 200', () => { request.get('http://localhost:7865/available_payments', (error, res, body) => { expect(res.statusCode).to.be.equal(200); }); }); it("should return body content 'Welcome to the payment system'", () => { request.get('http://localhost:7865/available_payments', (error, res, body) => { expect(JSON.parse(body)).to.deep.equal( { payment_methods: { credit_cards: true, paypal: false } }); }); }); it('should have the correct content type', () => { request('http://localhost:7865/available_payments', (error, res, body) => { expect(res.headers['content-type']).to.equal('application/json; charset=utf-8'); }); }); it('should have the correct content length', () => { request('http://localhost:7865/available_payments', (error, res, body) => { expect(res.headers['content-length']).to.equal('56'); }); }); }); describe('/login', () => { it('should return status code of 200', () => { request.post({ url: 'http://localhost:7865/login', form: { userName: 'Peter' } }, (error, res, body) => { expect(res.statusCode).to.be.equal(200); }); }); it('should return Welcome Peter', () => { request.post({ url: 'http://localhost:7865/login', json: { userName: 'Peter' } }, (error, res, body) => { expect(body).to.be.equal('Welcome Peter'); }); }); it('should return the correct result with form data value', () => { const data = { userName: 'Peter', }; request.post({ url: 'http://localhost:7865/login', body: data, json: true, }, (error, res, body) => { expect(body).to.contain('Welcome Peter'); }); }); it('should return the correct content type', () => { const data = { userName: 'Peter', }; request.post({ url: 'http://localhost:7865/login', body: data, json: true, }, (error, res, body) => { expect(res.headers['content-type']).to.equal('text/html; charset=utf-8'); }); }); it('should return the correct content length', () => { const data = { userName: 'Peter', }; request.post({ url: 'http://localhost:7865/login', body: data, json: true, }, (error, res, body) => { expect(res.headers['content-length']).to.equal('13'); }); }); it('should return the correct status 404 with invalid route', () => { const data = { username: 'Peter', }; request.post({ url: 'http://localhost:7865/invalid_route', body: data, json: true, }, (error, res, body) => { expect(res.statusCode).to.equal(404); }); }); });
/** *Submitted for verification at Etherscan.io on 2021-01-15 */ pragma solidity ^0.4.24;/** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }/** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); }/** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); }/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } }// SPDX-License-Identifier: MIT contract TokenList is Pausable { bool public IsTokenFilterOn; uint256 public NumberOfTokens; mapping(address => bool) private _IsAllowed; mapping(uint256 => address) private _Tokens; constructor() public { NumberOfTokens = 0; IsTokenFilterOn = false; //true on prod } function SwapTokenFilter() public onlyOwner { IsTokenFilterOn = !IsTokenFilterOn; } function AddToken(address _address) public onlyOwner { require(!_IsAllowed[_address], "This Token in List"); _IsAllowed[_address] = true; _Tokens[NumberOfTokens] = _address; NumberOfTokens++; } function RemoveToken(address _address) public onlyOwner { require(_IsAllowed[_address], "This Token not in List"); _IsAllowed[_address] = false; } function IsValidToken(address _address) public view returns (bool) { return !IsTokenFilterOn || _IsAllowed[_address]; } }// SPDX-License-Identifier: MIT contract ERC20Helper is TokenList { event TransferOut(uint256 Amount, address To, address Token); event TransferIn(uint256 Amount, address From, address Token); modifier TestAllownce( address _token, address _owner, uint256 _amount ) { require( ERC20(_token).allowance(_owner, address(this)) >= _amount, "no allowance" ); _; } function TransferToken( address _Token, address _Reciver, uint256 _Amount ) internal { uint256 OldBalance = CheckBalance(_Token, address(this)); emit TransferOut(_Amount, _Reciver, _Token); ERC20(_Token).transfer(_Reciver, _Amount); require( (SafeMath.add(CheckBalance(_Token, address(this)), _Amount)) == OldBalance , "recive wrong amount of tokens" ); } function CheckBalance(address _Token, address _Subject) internal view returns (uint256) { return ERC20(_Token).balanceOf(_Subject); } function TransferInToken( address _Token, address _Subject, uint256 _Amount ) internal TestAllownce(_Token, _Subject, _Amount) { require(_Amount > 0); uint256 OldBalance = CheckBalance(_Token, address(this)); ERC20(_Token).transferFrom(_Subject, address(this), _Amount); emit TransferIn(_Amount, _Subject, _Token); require( (SafeMath.add(OldBalance, _Amount)) == CheckBalance(_Token, address(this)), "recive wrong amount of tokens" ); } }// SPDX-License-Identifier: MIT //True POZ Token will have this, interface IPOZBenefit { function IsPOZHolder(address _Subject) external view returns(bool); }// SPDX-License-Identifier: MIT contract PozBenefit is ERC20Helper { constructor() public { PozFee = 15; // *10000 PozTimer = 1000; // *10000 MinPoz = 80; // ^Token.decimals POZ_Address = address(0x0); POZBenefit_Address = address(0x0); } uint256 internal PozFee; // the fee for the first part of the pool uint256 internal PozTimer; //the timer for the first part fo the pool uint256 internal MinPoz; //minimum ammount ofpoz to be part of the discount address public POZ_Address; //The address of the POZ Token address public POZBenefit_Address; //the address for implementation of IPozBenefit - to get POZ benefit status from other contracts modifier PercentCheckOk(uint256 _percent) { if (_percent < 10000) _; else revert("Not in range"); } modifier LeftIsBigger(uint256 _left, uint256 _right) { if (_left > _right) _; else revert("Not bigger"); } function GetPozTimer() public view returns (uint256) { return PozTimer; } function SetPozTimer(uint256 _pozTimer) public onlyOwner PercentCheckOk(_pozTimer) { PozTimer = _pozTimer; } function GetPOZFee() public view returns (uint256) { return PozFee; } function GetMinPoz() public view returns (uint256) { return MinPoz; } function SetMinPoz(uint256 _MinPoz) public onlyOwner { MinPoz = _MinPoz; } function SetPOZBenefit_Address(address _POZBenefit_Address) public onlyOwner { POZBenefit_Address = _POZBenefit_Address; } function SetPozAdress(address _POZ_Address) public onlyOwner { POZ_Address = _POZ_Address; } function AmIPOZInvestor() public view returns (bool) { return IsPOZInvestor(msg.sender); } //@dev Taken from interface, To join the POZ Benefit club function IsPOZInvestor(address _investor) internal view returns (bool) { if (POZ_Address == address(0x0) && POZBenefit_Address == address(0x0)) return true; //false; // for testing stage, until got the address return ((POZ_Address != address(0x0) && CheckBalance(POZ_Address, _investor) >= MinPoz) || (POZBenefit_Address != address(0x0) && IPOZBenefit(POZBenefit_Address).IsPOZHolder(_investor))); } }// SPDX-License-Identifier: MIT contract ETHHelper is PozBenefit { constructor() public { IsPayble = false; } modifier ReceivETH(uint256 msgValue, address msgSender, uint256 _MinETHInvest) { require(msgValue >= _MinETHInvest, "Send ETH to invest"); emit TransferInETH(msgValue, msgSender); _; } //@dev not/allow contract to receive funds function() public payable { if (!IsPayble) revert(); } event TransferOutETH(uint256 Amount, address To); event TransferInETH(uint256 Amount, address From); bool internal IsPayble; function GetIsPayble() public view returns (bool) { return IsPayble; } function SwitchIsPayble() public onlyOwner { IsPayble = !IsPayble; } function TransferETH(address _Reciver, uint256 _ammount) internal { emit TransferOutETH(_ammount, _Reciver); uint256 beforeBalance = address(_Reciver).balance; _Reciver.transfer(_ammount); require( SafeMath.add(beforeBalance, _ammount) == address(_Reciver).balance, "The transfer did not complite" ); } }// SPDX-License-Identifier: MIT contract Manageable is ETHHelper { constructor() public { Fee = 20; // *10000 MinDuration = 0; //need to set PoolPrice = 0; // Price for create a pool MaxDuration = 60 * 60 * 24 * 30 * 6; // half year MinETHInvest = 10000; // for percent calc MaxETHInvest = 100 * 10**18; // 100 eth per wallet } mapping(address => uint256) FeeMap; //@dev for percent use uint16 uint256 internal Fee; //the fee for the pool uint256 internal MinDuration; //the minimum duration of a pool, in seconds uint256 internal MaxDuration; //the maximum duration of a pool from the creation, in seconds uint256 internal PoolPrice; uint256 internal MinETHInvest; uint256 internal MaxETHInvest; function SetMinMaxETHInvest(uint256 _MinETHInvest, uint256 _MaxETHInvest) public onlyOwner { MinETHInvest = _MinETHInvest; MaxETHInvest = _MaxETHInvest; } function GetMinMaxETHInvest() public view returns (uint256 _MinETHInvest, uint256 _MaxETHInvest) { return (MinETHInvest,MaxETHInvest); } function GetMinMaxDuration() public view returns (uint256, uint256) { return (MinDuration, MaxDuration); } function SetMinMaxDuration(uint256 _minDuration, uint256 _maxDuration) public onlyOwner { MinDuration = _minDuration; MaxDuration = _maxDuration; } function GetPoolPrice() public view returns (uint256) { return PoolPrice; } function SetPoolPrice(uint256 _PoolPrice) public onlyOwner { PoolPrice = _PoolPrice; } function GetFee() public view returns (uint256) { return Fee; } function SetFee(uint256 _fee) public onlyOwner PercentCheckOk(_fee) LeftIsBigger(_fee, PozFee) { Fee = _fee; } function SetPOZFee(uint256 _fee) public onlyOwner PercentCheckOk(_fee) LeftIsBigger(Fee, _fee) { PozFee = _fee; } function WithdrawETHFee(address _to) public onlyOwner { _to.transfer(address(this).balance); // keeps only fee eth on contract //To Do need to take 16% to burn!!! } function WithdrawERC20Fee(address _Token, address _to) public onlyOwner { uint256 temp = FeeMap[_Token]; FeeMap[_Token] = 0; TransferToken(_Token, _to, temp); } }// SPDX-License-Identifier: MIT contract MainCoinManager is Manageable { event MainCoinAdded (address Token); event MainCoinRemoved (address Token); mapping(address => bool) public ERC20MainCoins; //when approve new erc20 main coin - it will list here function AddERC20Maincoin(address _token) public onlyOwner { emit MainCoinAdded(_token); ERC20MainCoins[_token] = true; } function RemoveERC20Maincoin(address _token) public onlyOwner { emit MainCoinRemoved(_token); ERC20MainCoins[_token] = false; } function IsERC20Maincoin(address _token) public view returns (bool) { return ERC20MainCoins[_token]; } }// SPDX-License-Identifier: MIT contract Pools is MainCoinManager { event NewPool(address token, uint256 id); event FinishPool(uint256 id); event PoolUpdate(uint256 id); constructor() public { poolsCount = 0; //Start with 0 } uint256 public poolsCount; // the ids of the pool mapping(uint256 => Pool) public pools; //the id of the pool with the data mapping(address => uint256[]) public poolsMap; //the address and all of the pools id's struct Pool { address Token; //the address of the erc20 toke for sale address Creator; //the project owner uint256 FinishTime; //Until what time the pool is active uint256 Rate; //for eth Wei, in token, by the decemal. the cost of 1 token uint256 POZRate; //the rate for the until OpenForAll, if the same as Rate , OpenForAll = StartTime . address Maincoin; // on adress.zero = ETH uint256 StartAmount; //The total amount of the tokens for sale bool IsLocked; // true - the investors getting the tokens after the FinishTime. false - intant deal uint256 Lefttokens; // the ammount of tokens left for sale uint256 StartTime; // the time the pool open //TODO Maybe Delete this? uint256 OpenForAll; // The Time that all investors can invest uint256 UnlockedTokens; //for locked pools bool TookLeftOvers; //The Creator took the left overs after the pool finished bool Is21DecimalRate; //If true, the rate will be rate*10^-21 } function GetLastPoolId() public view returns (uint256) { return poolsCount; } //create a new pool function CreatePool( address _Token, //token to sell address uint256 _FinishTime, //Until what time the pool will work uint256 _Rate, //the rate of the trade uint256 _POZRate, //the rate for POZ Holders, how much each token = main coin uint256 _StartAmount, //Total amount of the tokens to sell in the pool bool _IsLocked, //False = DSP or True = TLP address _MainCoin, // address(0x0) = ETH, address of main token bool _Is21Decimal, //focus the for smaller tokens. uint256 _Now //Start Time - can be 0 to not change current flow ) public whenNotPaused payable { require(msg.value >= PoolPrice, "Need to pay for the pool"); require(IsValidToken(_Token), "Need Valid ERC20 Token"); //check if _Token is ERC20 require( _MainCoin == address(0x0) || IsERC20Maincoin(_MainCoin), "Main coin not in list" ); require(_FinishTime - now < MaxDuration, "Can't be that long pool"); require( _Rate <= _POZRate, "POZ holders need to have better price (or the same)" ); require(_POZRate > 0, "It will not work"); if (_Now < now) _Now = now; require( SafeMath.add(now, MinDuration) <= _FinishTime, "Need more then MinDuration" ); // check if the time is OK TransferInToken(_Token, msg.sender, _StartAmount); uint256 Openforall = (_Rate == _POZRate) ? _Now : SafeMath.add( SafeMath.div( SafeMath.mul( SafeMath.sub(_FinishTime, _Now), PozTimer ), 10000 ), _Now ); //register the pool pools[poolsCount] = Pool( _Token, msg.sender, _FinishTime, _Rate, _POZRate, _MainCoin, _StartAmount, _IsLocked, _StartAmount, _Now, Openforall, 0, false, _Is21Decimal ); poolsMap[msg.sender].push(poolsCount); emit NewPool(_Token, poolsCount); poolsCount = SafeMath.add(poolsCount, 1); //joke - overflowfrom 0 on int256 = 1.16E77 } }// SPDX-License-Identifier: MIT contract PoolsData is Pools { enum PoolStatus {Created, Open,PreMade , OutOfstock, Finished, Close} //the status of the pools function GetMyPoolsId() public view returns (uint256[]) { return poolsMap[msg.sender]; } function IsReadyWithdrawLeftOvers(uint256 _PoolId) public view returns (bool) { return pools[_PoolId].FinishTime <= now && pools[_PoolId].Lefttokens > 0 && !pools[_PoolId].TookLeftOvers; } //@dev no use of revert to make sure the loop will work function WithdrawLeftOvers(uint256 _PoolId) public returns (bool) { //pool is finished + got left overs + did not took them if (IsReadyWithdrawLeftOvers(_PoolId)) { pools[_PoolId].TookLeftOvers = true; TransferToken( pools[_PoolId].Token, pools[_PoolId].Creator, pools[_PoolId].Lefttokens ); return true; } return false; } //give the data of the pool, by id function GetPoolData(uint256 _id) public view returns ( PoolStatus, address, uint256, uint256, address, uint256, uint256 ) { require(_id < poolsCount, "Wrong Id"); return ( //check if sender POZ Invester? GetPoolStatus(_id), pools[_id].Token, pools[_id].Rate, pools[_id].POZRate, pools[_id].Maincoin, //incase of ETH will be address.zero pools[_id].StartAmount, pools[_id].Lefttokens ); } function GetMorePoolData(uint256 _id) public view returns ( bool, uint256, uint256, uint256, address, bool ) { require(_id < poolsCount, "Wrong Id"); return ( pools[_id].IsLocked, pools[_id].StartTime, pools[_id].FinishTime, pools[_id].OpenForAll, pools[_id].Creator, pools[_id].Is21DecimalRate ); } //calculate the status of a pool function GetPoolStatus(uint256 _id) public view returns (PoolStatus) { require(_id < poolsCount, "Wrong pool id, Can't get Status"); //Don't like the logic here - ToDo Boolean checks (truth table) if (now < pools[_id].StartTime) return PoolStatus.PreMade; if (now < pools[_id].OpenForAll && pools[_id].Lefttokens > 0) { //got tokens + only poz investors return (PoolStatus.Created); } if ( now >= pools[_id].OpenForAll && pools[_id].Lefttokens > 0 && now < pools[_id].FinishTime ) { //got tokens + all investors return (PoolStatus.Open); } if ( pools[_id].Lefttokens == 0 && pools[_id].IsLocked && now < pools[_id].FinishTime ) //no tokens on locked pool, got time { return (PoolStatus.OutOfstock); } if ( pools[_id].Lefttokens == 0 && !pools[_id].IsLocked ) //no tokens on direct pool { return (PoolStatus.Close); } if (now >= pools[_id].FinishTime && !pools[_id].IsLocked) { // After finish time - not locked if (pools[_id].TookLeftOvers) return (PoolStatus.Close); return (PoolStatus.Finished); } if ( (pools[_id].TookLeftOvers || pools[_id].Lefttokens == 0) && (pools[_id].UnlockedTokens + pools[_id].Lefttokens == pools[_id].StartAmount) ) return (PoolStatus.Close); return (PoolStatus.Finished); } }// SPDX-License-Identifier: MIT contract Invest is PoolsData { event NewInvestorEvent(uint256 Investor_ID, address Investor_Address); modifier CheckTime(uint256 _Time) { require(now >= _Time, "Pool not open yet"); _; } //using SafeMath for uint256; constructor() public { TotalInvestors = 0; } //Investorsr Data uint256 internal TotalInvestors; mapping(uint256 => Investor) Investors; mapping(address => uint256[]) InvestorsMap; struct Investor { uint256 Poolid; //the id of the pool, he got the rate info and the token, check if looked pool address InvestorAddress; // uint256 MainCoin; //the amount of the main coin invested (eth/dai), calc with rate bool IsPozInvestor; //If the blance of the address got > MinPoz, can get discout if got early uint256 TokensOwn; //the amount of Tokens the investor needto get from the contract uint256 InvestTime; //the time that investment made } //@dev Send in wei function InvestETH(uint256 _PoolId) external payable ReceivETH(msg.value, msg.sender,MinETHInvest) whenNotPaused CheckTime(pools[_PoolId].StartTime) { require(_PoolId < poolsCount, "Wrong pool id, InvestETH fail"); require(pools[_PoolId].Maincoin == address(0x0), "Pool is not for ETH"); require(msg.value >= MinETHInvest && msg.value <= MaxETHInvest, "Investment amount not valid"); require(msg.sender == tx.origin && !isContract(msg.sender), "Some thing wrong with the msgSender"); uint256 ThisInvestor = NewInvestor(msg.sender, msg.value, _PoolId); uint256 Tokens = CalcTokens(_PoolId, msg.value, msg.sender); if (pools[_PoolId].IsLocked) { Investors[ThisInvestor].TokensOwn = SafeMath.add( Investors[ThisInvestor].TokensOwn, Tokens ); } else { // not locked, will transfer the toke TransferToken(pools[_PoolId].Token, msg.sender, Tokens); } uint256 EthMinusFee = SafeMath.div( SafeMath.mul(msg.value, SafeMath.sub(10000, CalcFee(_PoolId))), 10000 ); TransferETH(pools[_PoolId].Creator, EthMinusFee); // send money to project owner - the fee stays on contract RegisterInvest(_PoolId, Tokens); } function InvestERC20(uint256 _PoolId, uint256 _Amount) external whenNotPaused CheckTime(pools[_PoolId].StartTime) { require(_PoolId < poolsCount, "Wrong pool id, InvestERC20 fail"); require( pools[_PoolId].Maincoin != address(0x0), "Pool is for ETH, use InvetETH" ); require(_Amount > 10000, "Need invest more then 10000"); require(msg.sender == tx.origin && !isContract(msg.sender), "Some thing wrong with the msgSender"); TransferInToken(pools[_PoolId].Maincoin, msg.sender, _Amount); uint256 ThisInvestor = NewInvestor(msg.sender, _Amount, _PoolId); uint256 Tokens = CalcTokens(_PoolId, _Amount, msg.sender); if (pools[_PoolId].IsLocked) { Investors[ThisInvestor].TokensOwn = SafeMath.add( Investors[ThisInvestor].TokensOwn, Tokens ); } else { // not locked, will transfer the tokens TransferToken(pools[_PoolId].Token, msg.sender, Tokens); } uint256 RegularFeePay = SafeMath.div( SafeMath.mul(_Amount, CalcFee(_PoolId)), 10000 ); uint256 RegularPaymentMinusFee = SafeMath.sub(_Amount, RegularFeePay); FeeMap[pools[_PoolId].Maincoin] = SafeMath.add( FeeMap[pools[_PoolId].Maincoin], RegularFeePay ); TransferToken( pools[_PoolId].Maincoin, pools[_PoolId].Creator, RegularPaymentMinusFee ); // send money to project owner - the fee stays on contract RegisterInvest(_PoolId, Tokens); } function RegisterInvest(uint256 _PoolId, uint256 _Tokens) internal { require( _Tokens <= pools[_PoolId].Lefttokens, "Not enough tokens in the pool" ); pools[_PoolId].Lefttokens = SafeMath.sub( pools[_PoolId].Lefttokens, _Tokens ); if (pools[_PoolId].Lefttokens == 0) emit FinishPool(_PoolId); else emit PoolUpdate(_PoolId); } function NewInvestor( address _Sender, uint256 _Amount, uint256 _Pid ) internal returns (uint256) { Investors[TotalInvestors] = Investor( _Pid, _Sender, _Amount, IsPOZInvestor(_Sender), 0, block.timestamp ); InvestorsMap[msg.sender].push(TotalInvestors); emit NewInvestorEvent(TotalInvestors,_Sender); TotalInvestors = SafeMath.add(TotalInvestors, 1); return SafeMath.sub(TotalInvestors, 1); } function CalcTokens( uint256 _Pid, uint256 _Amount, address _Sender ) internal view returns (uint256) { uint256 msgValue = _Amount; uint256 result = 0; if (GetPoolStatus(_Pid) == PoolStatus.Created) { if (!IsPOZInvestor(_Sender)) { revert("Need to be POZ Holder to invest"); } result = SafeMath.mul(msgValue, pools[_Pid].POZRate); } if (GetPoolStatus(_Pid) == PoolStatus.Open) { result = SafeMath.mul(msgValue, pools[_Pid].Rate); } if (result > 10**21) { if (pools[_Pid].Is21DecimalRate) { result = SafeMath.div(result, 10**21); } return result; } revert("Wrong pool status to CalcTokens"); } function CalcFee(uint256 _Pid) internal view returns (uint256) { if (GetPoolStatus(_Pid) == PoolStatus.Created) { return PozFee; } if (GetPoolStatus(_Pid) == PoolStatus.Open) { return Fee; } //will not get here, will fail on CalcTokens //revert("Wrong pool status to CalcFee"); } //@dev use it with require(msg.sender == tx.origin) function isContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size > 0); } }// SPDX-License-Identifier: MIT contract InvestorData is Invest { function IsReadyWithdrawInvestment(uint256 _id) public view returns (bool) { return _id <= TotalInvestors && Investors[_id].TokensOwn > 0 && pools[Investors[_id].Poolid].FinishTime <= now; } function WithdrawInvestment(uint256 _id) public returns (bool) { if (IsReadyWithdrawInvestment(_id)) { uint256 temp = Investors[_id].TokensOwn; Investors[_id].TokensOwn = 0; TransferToken( pools[Investors[_id].Poolid].Token, Investors[_id].InvestorAddress, temp ); pools[Investors[_id].Poolid].UnlockedTokens = SafeMath.add( pools[Investors[_id].Poolid].UnlockedTokens, temp ); return true; } return false; } //Give all the id's of the investment by sender address function GetMyInvestmentIds() public view returns (uint256[]) { return InvestorsMap[msg.sender]; } function GetInvestmentData(uint256 _id) public view returns ( uint256, address, uint256, bool, uint256, uint256 ) { require( Investors[_id].InvestorAddress == msg.sender || msg.sender == owner, "Only for the investor (or Admin)" ); return ( Investors[_id].Poolid, Investors[_id].InvestorAddress, Investors[_id].MainCoin, Investors[_id].IsPozInvestor, Investors[_id].TokensOwn, Investors[_id].InvestTime ); } }// SPDX-License-Identifier: MIT contract ThePoolz is InvestorData { event InvestorsWork(uint256 NewStart, uint256 TotalDone); event ProjectOwnerWork(uint256 NewStart, uint256 TotalDone); constructor() public { StartInvestor = 0; StartProjectOwner = 0; MinWorkInvestor = 0; MinWorkProjectOwner = 0; } uint256 internal MinWorkInvestor; uint256 internal MinWorkProjectOwner; uint256 internal StartInvestor; uint256 internal StartProjectOwner; function SetStartForWork(uint256 _StartInvestor, uint256 _StartProjectOwner) public onlyOwner { StartInvestor = _StartInvestor; StartProjectOwner = _StartProjectOwner; } function GetMinWorkInvestor() public view returns (uint256) { return MinWorkInvestor; } function SetMinWorkInvestor(uint256 _MinWorkInvestor) public onlyOwner { MinWorkInvestor = _MinWorkInvestor; } function GetMinWorkProjectOwner() public view returns (uint256) { return MinWorkProjectOwner; } function SetMinWorkProjectOwner(uint256 _MinWorkProjectOwner) public onlyOwner { MinWorkProjectOwner = _MinWorkProjectOwner; } //will revert if less than parameters function SafeWork() external returns (uint256, uint256) { require(CanWork(), "Need more than minimal work count"); return DoWork(); } function CanWork() public view returns (bool) { uint256 inv; uint256 pro; (inv, pro) = CountWork(); return (inv > MinWorkInvestor || pro > MinWorkProjectOwner); } function DoWork() public returns (uint256, uint256) { uint256 pro = WorkForProjectOwner(); uint256 inv = WorkForInvestors(); return (inv, pro); } function CountWork() public view returns (uint256, uint256) { uint256 temp_investor_count = 0; uint256 temp_projectowner_count = 0; for ( uint256 Investorindex = StartInvestor; Investorindex < TotalInvestors; Investorindex++ ) { if (IsReadyWithdrawInvestment(Investorindex)) temp_investor_count++; } for ( uint256 POindex = StartProjectOwner; POindex < poolsCount; POindex++ ) { if (IsReadyWithdrawLeftOvers(POindex)) temp_projectowner_count++; } return (temp_investor_count, temp_projectowner_count); } function WorkForInvestors() internal returns (uint256) { uint256 WorkDone = 0; for (uint256 index = StartInvestor; index < TotalInvestors; index++) { if (WithdrawInvestment(index)) WorkDone++; } SetInvestorStart(); emit InvestorsWork(StartInvestor, WorkDone); return WorkDone; } function SetInvestorStart() internal { for (uint256 index = StartInvestor; index < TotalInvestors; index++) { if (GetPoolStatus(Investors[index].Poolid) == PoolStatus.Close) StartInvestor = index; else return; } } function WorkForProjectOwner() internal returns (uint256) { uint256 WorkDone = 0; bool FixStart = true; for (uint256 index = StartProjectOwner; index < poolsCount; index++) { if (WithdrawLeftOvers(index)) WorkDone++; if ( FixStart && (pools[index].TookLeftOvers || pools[index].Lefttokens == 0) ) { StartProjectOwner = index; } else { FixStart = false; } } emit ProjectOwnerWork(StartProjectOwner, WorkDone); return WorkDone; } }
/* eslint-disable @typescript-eslint/no-unused-vars */ import { useCallback, useEffect, useState } from 'react'; import Box from '@mui/material/Box'; import CircularProgress from '@mui/material/CircularProgress'; import Paper from '@mui/material/Paper'; import Typography from '@mui/material/Typography'; import Grid from '@mui/material/Unstable_Grid2'; // Grid version 2 import { useShowNotifications } from '../../core/notifications/hooks'; import { delay } from '../../core/utils/async'; import { isPromise } from '../../core/utils/checkers'; import { CustomFontInput, CustomFontInputData, } from '../../fonts/components/CustomFontInput'; import { FontInput } from '../../fonts/components/FontInput'; import { DEFAULT_FONT_SIZE } from '../../fonts/constants'; import { useFontRegistry } from '../../fonts/hooks'; import { RegisteredFontData } from '../../fonts/types'; import { buildCssStringForFont } from '../../fonts/utils'; import { Services } from '../../Services'; import { useTextMeasurer } from '../hooks'; import { TextMeasurerType } from '../measurers/types'; import { TextMeasurer } from './TextMeasurer'; export type TextMeasurerPageProps = { initialText: string; measurerType: TextMeasurerType; selectedFontId?: string; measurerParams?: Record<string, unknown>; customFontsEnabled?: boolean; customFontUrl?: string; customFontIsBold?: boolean; customFontIsItalic?: boolean; initialFontSize?: number; }; function useTextMeasurerPageState( initialText: string, selectedFontId?: string, initialFontSize?: number, ) { const [text, setText] = useState<string>(initialText); const [currentFontId, setCurrentFontId] = useState<string>( selectedFontId ?? '', ); const [fontSize, setFontSize] = useState<number>( initialFontSize ?? DEFAULT_FONT_SIZE, ); const [measurementResult, setMeasurementResult] = useState<number | null>( null, ); const [isMeasuring, setIsMeasuring] = useState<boolean>(false); const [isCustomFontLoading, setIsCustomFontLoading] = useState<boolean>(false); const [servicesAreReady, setServicesAreReady] = useState<boolean>(false); return { text, currentFontId, fontSize, measurementResult, isMeasuring, isCustomFontLoading, servicesAreReady, setText, setCurrentFontId, setFontSize, setMeasurementResult, setIsMeasuring, setIsCustomFontLoading, setServicesAreReady, }; } export const TextMeasurerPage: React.FC<TextMeasurerPageProps> = ({ initialText, measurerType, selectedFontId, customFontsEnabled, customFontUrl, customFontIsBold, customFontIsItalic, initialFontSize, measurerParams, }) => { const { text, currentFontId, fontSize, measurementResult, isMeasuring, isCustomFontLoading, servicesAreReady, setText, setCurrentFontId, setFontSize, setMeasurementResult, setIsMeasuring, setIsCustomFontLoading, setServicesAreReady, } = useTextMeasurerPageState(initialText, selectedFontId, initialFontSize); const textMeasurer = useTextMeasurer(measurerType, measurerParams); const { selectedFontData, fonts, registerFont, isInitialized } = useFontRegistry(Services.FontRegistry, currentFontId); const { info, success, warning } = useShowNotifications(); useEffect(() => { if (isInitialized && !servicesAreReady) { delay(2500).then(() => { setServicesAreReady(true); if (!currentFontId && fonts.length > 0) { setCurrentFontId(fonts[0].id); } }); } }, [ isInitialized, servicesAreReady, fonts, currentFontId, setCurrentFontId, setServicesAreReady, ]); // const warmUpCallback = useCallback(() => { // return delay(4000).then(() => { // Services.TextMeasurerWorkersService.getWorker(); // }); // }, []); // useExecuteExactlyOnce(warmUpCallback); const isCustomFontEnabled = customFontsEnabled === true; let customFontInitialValues: undefined | CustomFontInputData; if (isCustomFontEnabled) { if (selectedFontData?.isCustom) { // Means that selected font is custom, and font has been registered customFontInitialValues = { name: selectedFontData.font, displayName: selectedFontData.displayName, url: selectedFontData.url, isBold: selectedFontData.isBold, isItalic: selectedFontData.isItalic, }; } else { // Means that selected font is custom, but font hasn't been registered yet customFontInitialValues = { name: '', displayName: '', url: customFontUrl ?? '', isBold: customFontIsBold ?? false, isItalic: customFontIsItalic ?? false, }; } } const selectedFontCssString = selectedFontData && buildCssStringForFont( selectedFontData.font, selectedFontData.isBold, selectedFontData.isItalic, fontSize, ); const handleMeasureClicked = useCallback( async (textToMeasure: string) => { if (!selectedFontData) { info('Please select a font to measure text with.'); return; } setIsMeasuring(true); const result = textMeasurer .withText(textToMeasure) .withBold(selectedFontData.isBold) .withItalic(selectedFontData.isItalic) .withFont(selectedFontData.font) .withSize(fontSize) .calculateWidth(); if (isPromise(result)) { const measurement = await result; setMeasurementResult(measurement); } else { setMeasurementResult(result); } setIsMeasuring(false); }, [ selectedFontData, textMeasurer, info, fontSize, setIsMeasuring, setMeasurementResult, ], ); const handleRegisterCustomFontClicked = useCallback( async ( name: string, url: string, isBold: boolean, isItalic: boolean, displayName?: string, ) => { setIsCustomFontLoading(true); try { await delay(1500); await registerFont({ font: name, displayName: displayName ? `${displayName} (custom)` : `${name} (custom)}`, url, isBold, isItalic, isCustom: true, }); success( `Custom font '${displayName ?? name}' registered successfully.`, ); } catch (error) { warning('Failed to register custom font.'); } finally { setIsCustomFontLoading(false); } }, [registerFont, success, warning, setIsCustomFontLoading], ); const handleFontChanged = useCallback( (font: RegisteredFontData) => { setCurrentFontId(font.id); }, [setCurrentFontId], ); return ( <Paper elevation={5}> <Grid container direction={'row'} justifyContent={'center'} alignItems={'center'} > <Grid xs={8}> <Typography textAlign={'center'} variant="h2"> {servicesAreReady ? 'Welcome' : 'Loading...'} </Typography> </Grid> {!servicesAreReady && ( <Grid> <Box sx={{ display: 'flex' }}> <CircularProgress /> </Box> </Grid> )} </Grid> <Grid container spacing={2} direction={'row'} padding={2}> <Grid container direction={'column'} spacing={2} xs={6}> <Grid> <FontInput fonts={fonts} fontSize={fontSize} selectedFont={selectedFontData} onFontSizeChanged={setFontSize} onFontSelected={handleFontChanged} ></FontInput> </Grid> <Grid> {isCustomFontEnabled && ( <CustomFontInput initialValues={customFontInitialValues} isLoading={isCustomFontLoading} onFontRegistered={handleRegisterCustomFontClicked} /> )} </Grid> </Grid> <Grid xs={6}> <TextMeasurer text={text} cssFontString={selectedFontCssString} measurementResult={measurementResult} onMeasureClicked={handleMeasureClicked} onTextChanged={setText} isLoading={isMeasuring} /> </Grid> </Grid> </Paper> ); };
import React, { useEffect } from 'react'; import { useParams } from 'react-router'; import { useDispatch } from 'react-redux'; import { useTable, usePagination } from 'react-table'; import { onGetChangeHistory } from '../SpecHistory.actions'; import SearchFilter from './SearchFilter'; import { ContentTable, Table, Tbody, Td, Th, Thead, PaginationContent, GoBackFollowingButton, UlPagination, LiPagination, } from '../SpecHistory.styles'; const StructureTableChangeHistory = ({ columns, changes, pagesCounter, pageCount: controlledPageCount, keyword, author, onChangeParams, onChangeAuthor, authors, queryParamsBuilder, actualPage, }) => { const { getTableProps, getTableBodyProps, headerGroups, prepareRow, page, canPreviousPage, canNextPage, nextPage, gotoPage, previousPage, setPageSize, state: { pageIndex, pageSize }, } = useTable( { columns, data: changes, initialState: { pageIndex: 0 }, manualPagination: true, pageCount: controlledPageCount, }, usePagination, ); const dispatch = useDispatch(); const { id: specID } = useParams(); let options = [{ id: 'allAuthors', name: 'Todos los autores' }]; options = options.concat(authors); const goToPreviousPage = () => { previousPage(); const queryParams = { limit: 7, page: pageIndex - 1, keyword }; if (pageIndex > 0) dispatch( onGetChangeHistory(specID, queryParamsBuilder(author, queryParams)), ); }; const goToNextPage = () => { nextPage(); const queryParams = { limit: 7, page: pageIndex + 1, keyword }; if (pageIndex < controlledPageCount - 1) dispatch( onGetChangeHistory(specID, queryParamsBuilder(author, queryParams)), ); }; const handleGoToPage = (currentPage) => () => { gotoPage(currentPage); const queryParams = { limit: 7, page: currentPage, keyword }; if (currentPage !== actualPage) dispatch( onGetChangeHistory(specID, queryParamsBuilder(author, queryParams)), ); }; const pagination = () => { const paginatedArray = []; const currentPage = actualPage + 1; const maxPageShow = 10; const medianPage = maxPageShow / 2; let firstPage = 0; let lastPage = 0; if (currentPage + medianPage >= controlledPageCount) { firstPage = Math.max(controlledPageCount - maxPageShow + 1, 1); } else { firstPage = currentPage - medianPage > 0 ? currentPage - medianPage : 1; } lastPage = Math.min(firstPage + maxPageShow - 1, controlledPageCount); // eslint-disable-next-line no-plusplus for (let i = firstPage; i <= lastPage; i++) { if (i === currentPage) { paginatedArray.push( <LiPagination key={i} onClick={handleGoToPage(Number(currentPage - 1))} active={currentPage - 1 === actualPage} > {currentPage} </LiPagination>, ); } else { paginatedArray.push( <LiPagination key={i} onClick={handleGoToPage(Number(i - 1))} active={i - 1 === actualPage} > {i} </LiPagination>, ); } } return paginatedArray; }; useEffect(() => { const pageLimit = 7; pagesCounter({ pageSize }); setPageSize(pageLimit); }, [pagesCounter, pageSize]); return ( <> <SearchFilter authors={options} keyword={keyword} onChangeParams={onChangeParams} onChangeAuthor={onChangeAuthor} author={author} /> <ContentTable> <Table {...getTableProps()}> <Thead> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map((headerRow) => ( <Th {...headerRow.getHeaderProps()}> {headerRow.render('Header')} </Th> ))} </tr> ))} </Thead> <Tbody {...getTableBodyProps()}> {page.map((row) => { prepareRow(row); return ( <tr {...row.getRowProps()}> {row.cells.map((cell) => ( <Td {...cell.getCellProps()}>{cell.render('Cell')}</Td> ))} </tr> ); })} </Tbody> </Table> </ContentTable> <PaginationContent> <GoBackFollowingButton className="fas fa-chevron-left" onClick={goToPreviousPage} disabled={!canPreviousPage} /> <UlPagination>{pagination()}</UlPagination> <GoBackFollowingButton className="fas fa-chevron-right" onClick={goToNextPage} disabled={!canNextPage} /> </PaginationContent> </> ); }; export default StructureTableChangeHistory;
package id.co.map.spk.services.impl; import id.co.map.spk.entities.SbuEntity; import id.co.map.spk.enums.ClientResponseStatus; import id.co.map.spk.model.response.ClientCompanyResponse; import id.co.map.spk.model.response.ClientSbuResponse; import id.co.map.spk.repositories.SbuRepository; import id.co.map.spk.services.SbuService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; @Service public class SbuServiceImpl implements SbuService { private static final Logger logger = LogManager.getLogger(SbuServiceImpl.class); private final SbuRepository sbuRepository; public SbuServiceImpl(SbuRepository sbuRepository) { this.sbuRepository = sbuRepository; } @Override public ClientSbuResponse add(SbuEntity sbu) { ClientSbuResponse response = new ClientSbuResponse(); try { sbuRepository.add(sbu); response.setResponseCode(ClientResponseStatus.SBU_ADDED.getCode()); response.setResponseMessage(ClientResponseStatus.SBU_ADDED.getMessage()); response.setSbu(sbu); } catch (ClassNotFoundException | SQLException e) { logger.error(e.getMessage()); e.printStackTrace(); response.setResponseCode(ClientResponseStatus.SERVER_ERROR.getCode()); response.setResponseMessage(ClientResponseStatus.SERVER_ERROR.getMessage() + e.getMessage()); response.setSbu(sbu); } return response; } @Override public Map<String, Object> findSbuPagination(String SbuId, String SbuDesc, Integer pageNumber, Integer size, Integer draw) { Map<String, Object> findResult = sbuRepository.findSbuForPagination(SbuId, SbuDesc, pageNumber, size); Map<String, Object> map = new HashMap<>(); map.put("draw", draw); map.put("recordsTotal", findResult.get("totalCount")); map.put("recordsFiltered", findResult.get("totalCount")); map.put("data", findResult.get("sbus")); return map; } @Override public ClientSbuResponse updateCodeDesc(SbuEntity sbu, String sbuId) { ClientSbuResponse response = new ClientSbuResponse(); try { sbuRepository.updateCodeDescbySbuId(sbu,sbuId); response.setResponseCode(ClientResponseStatus.SBU_CODEDESC_CHANGED.getCode()); response.setResponseMessage(ClientResponseStatus.SBU_CODEDESC_CHANGED.getMessage()); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); response.setResponseCode(ClientResponseStatus.SQL_ERROR.getCode()); response.setResponseMessage(ClientResponseStatus.SQL_ERROR.getMessage()); response.setSbu(null); } return response; } @Override public ClientSbuResponse updateRule(String rule, String sbuId){ ClientSbuResponse response = new ClientSbuResponse(); try { sbuRepository.updateRulebySbuId(rule,sbuId); response.setResponseCode(ClientResponseStatus.SBU_RULE_CHANGED.getCode()); response.setResponseMessage(ClientResponseStatus.SBU_RULE_CHANGED.getMessage()); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); response.setResponseCode(ClientResponseStatus.SQL_ERROR.getCode()); response.setResponseMessage(ClientResponseStatus.SQL_ERROR.getMessage()); response.setSbu(null); } return response; } }
import React, { useState, useEffect, useRef } from 'react'; import { useNavigate } from "react-router-dom"; import { confirmAlert } from 'react-confirm-alert'; import { Message, toaster, Popover, Whisper } from 'rsuite'; const RequestList = (props) => { const navigate = useNavigate(); const [data, setData] = useState(null); const fetchingComplete = useRef(false); useEffect(() => { if(fetchingComplete.current === false) { const getData = async () => { try { await fetch(`${process.env.REACT_APP_BACKEND_URL}?` + new URLSearchParams({ enviornment: window.location.hostname, action: 'get_custom', table: 'requests', orderby: 'datelogged', orderbydirec: 'DESC' })) .then((response) => { return response.json(); }) .then((result) => { setData(result); }, (error) => { console.log(error) toaster.push(<Message showIcon type="error">{error.message}</Message>, { duration: 3000 }); }); } catch (error) { console.log(error) toaster.push(<Message showIcon type="error">{error.message}</Message>, { duration: 3000 }); } } getData(); fetchingComplete.current = true; } }, []); const confirmDeleteData = (id) => { confirmAlert({ title: "Confirm to delete", message: "Are you sure to delete this.", buttons: [ { label: "Yes", onClick: () => deleteData(id) }, { label: "No" } ] }); }; const deleteData = async (id) => { try { await fetch(`${process.env.REACT_APP_BACKEND_URL}?` + new URLSearchParams({ enviornment: window.location.hostname, action: 'get_custom', table: 'requests', where: 'id=:id', params: `id:${id}` })); } catch (error) { console.log(error); toaster.push(<Message showIcon type="error">{error.message}</Message>, { duration: 3000 }); } finally { toaster.push(<Message showIcon type="success">Successfully Deleted</Message>, { duration: 3000 }); var newdata = data.filter(function(item){ return item.id !== id }); setData(newdata); } } return ( <> <div className='page-title site-page-title'> <div className='site-page-title-left'> <h1>Requests</h1> </div> </div> {data && Array.isArray(data) && <div className='page-table'> <div className='page-table-head'> <div className='page-table-column page-table-label'>Type</div> <div className='page-table-column page-table-label'>Requester</div> <div className='page-table-column page-table-label'>Date</div> <div className='page-table-column page-table-label'></div> </div> {data.map((item, index) => ( <div className='page-table-row-outter' key={index}> <div className='page-table-row-inner'> <div className='page-table-column'>{item.type}</div> <div className='page-table-column'>{item.email}</div> <div className='page-table-column'>{item.role}</div> <div className='page-table-column'> <Whisper placement="left" trigger="hover" controlId={`control-id-${index}`} speaker={<Popover> <div className='popover-link' onClick={(e) => navigate(`/request/edit/${item.id}`)}>Edit</div> <div className='popover-link' onClick={(e) => confirmDeleteData(item.id)}>Delete</div> </Popover>} enterable > <div className='page-table-more-button'>&middot;&middot;&middot;</div> </Whisper> </div> </div> </div> ))} </div> } </> ) } export default RequestList;
.\" -*- mode: nroff; coding: utf-8 -*- .\" Copyright (c) 2022 G. Weinholt .\" SPDX-License-Identifier: MIT .TH string-hash 3scm 2022-05-12 "" "Scheme Programmer's Manual" .SH NAME string-hash, string-ci-hash \- string hash functions . .SH LIBRARY .nf .BR "(import (rnrs))" " ;R6RS" .BR "(import (rnrs hashtables))" " ;R6RS" . .SH SYNOPSIS .nf .BI "(string-hash " string ) .BI "(string-ci-hash " string ) . .SH DESCRIPTION Returns an integer hash value for .IR string , based on its current contents. It is used with .BR make-hashtable (3scm). . .TP .B string-hash This hash function is suitable for use with .BR string=? (3scm) as an equivalence function. . .TP .B string-ci-hash This hash function ignores case. It is suitable for use with .BR string-ci=? (3scm) as an equivalence function. . . \" .SH "IMPLEMENTATION NOTES" \" . . .SH "RETURN VALUES" . Returns a single value; an integer. .SH EXAMPLES . .EX (= (string-hash "Quux") (string-hash "Quux")) => #t (= (string-ci-hash "quux") (string-hash "QUUX")) => #t (= (string-hash "foo") (string-hash "bar")) => #t or #f .EE . .SH "APPLICATION USAGE" . This procedure is used as an argument to .BR make-hashtable (3scm). \" .SH RATIONALE \" . \" .SH COMPATIBILITY \" . .SH ERRORS This procedure can raise exceptions with the following condition types: .TP .BR &assertion " (R6RS)" The wrong number of arguments was passed or an argument was outside its domain. . .SH "SEE ALSO" . .BR make-hashtable (3scm) .SH STANDARDS R6RS, SRFI-69 . .SH HISTORY . The first Scheme report to include this procedure was R6RS for its new hashtable library. There is a similar procedure in SRFI-69. .SH AUTHORS This page is part of the .I scheme-manpages project. It includes materials from the RnRS documents. More information can be found at .UR https://github.com/schemedoc/manpages/ .UE . \" . \" .SH BUGS \" .
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * Abstract adapter class for the {@link AsyncHandlerInterceptor} interface, * for simplified implementation of pre-only/post-only interceptors. * * @author Juergen Hoeller * @since 05.12.2003 */ public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor { /** * This implementation always returns {@code true}. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } /** * This implementation is empty. */ @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * This implementation is empty. */ @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } /** * This implementation is empty. */ @Override public void afterConcurrentHandlingStarted( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { } }
import React from 'react'; import AppRowContainer from '@crema/components/AppRowContainer'; import { Col } from 'antd'; import { StyledProductDetailItemTitle, StyledProductDetailSpecification, } from './index.styled'; const productInfo = [ { id: 1, title: 'Sweat Proof', desc: 'Yes', }, { id: 2, title: 'Deep Bass', desc: 'Yes', }, { id: 3, title: 'Water Resistant', desc: 'Yes', }, { id: 4, title: 'Designed For', desc: 'MOBILE, iPHONE, LAPTOP, ALL ANDRIOD PHONE', }, { id: 5, title: 'Series', desc: 'SH12', }, { id: 6, title: 'System Requirements', desc: 'BLUETOOTH', }, { id: 7, title: 'Circumaural/ Supraaural', desc: 'Circumaural', }, { id: 8, title: 'Open/Closed Back', desc: 'OPEN', }, { id: 9, title: 'indicators', desc: 'Connection Indicator, Power Indicator', }, { id: 10, title: 'Controls', desc: 'PLAY/PAUSE', }, { id: 11, title: 'Theme', desc: 'NA', }, { id: 12, title: 'Total Harmonic Distortion', desc: '0.%', }, { id: 13, title: 'Number of Pins', desc: '1', }, { id: 14, title: 'With Microphone', desc: 'Yes', }, ]; const ProductInfo = () => { return ( <StyledProductDetailSpecification> <StyledProductDetailItemTitle> Product Details </StyledProductDetailItemTitle> <AppRowContainer> {productInfo.map((data, index) => ( <React.Fragment key={index}> <Col xs={8}> <p className='text-secondary'>{data.title}</p> </Col> <Col xs={16}> <p> {data.desc}</p> </Col> </React.Fragment> ))} </AppRowContainer> </StyledProductDetailSpecification> ); }; export default ProductInfo;
import { Detail, Toast, showToast } from "@raycast/api"; import { useState, useEffect, ReactNode } from "react"; import * as google from "../auth/google"; import { supabase } from "../supabase"; import { Session } from "@supabase/supabase-js"; // Update the service name here for testing different providers export default function Protected({ serviceName = "google", children }: { serviceName?: string; children: ReactNode }) { const service = getService(serviceName); const [session, setSession] = useState<Session | null>(null); useEffect(() => { (async () => { try { await service.authorize(); const { data: { session }, error, } = await supabase.auth.getSession(); if (error) { showToast({ style: Toast.Style.Failure, title: String(error) }); } else { setSession(session); } } catch (error) { showToast({ style: Toast.Style.Failure, title: String(error) }); } })(); }, [service]); if (!session) { return <Detail isLoading={true} />; } return <>{children}</>; } // Services function getService(serviceName: string): Service { switch (serviceName) { case "google": return google as Service; default: throw new Error("Unsupported service: " + serviceName); } } interface Service { signOut(): Promise<void>; authorize(): Promise<void>; fetchItems(): Promise<{ id: string; title: string }[]>; }
// // ViewController.swift // WeatherTest // // Created by que on 14/12/2564 BE. // import UIKit import CoreLocation import SwiftyJSON import RxSwift import RxCocoa import SDWebImage import ActivityIndicatorManager class ViewController: UIViewController { @IBOutlet weak var weatherIconImageView: UIImageView! @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var temperatureUnitLabel: UILabel! @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var cityLabel: UILabel! var latitude: CLLocationDegrees = 0.0 var longitude: CLLocationDegrees = 0.0 var unit: String = "metric" var isSearchForCityName: Bool = false var cityName: String = "" private let forecastViewModel = ForecastViewModel() private let disposeBag = DisposeBag() lazy var locationManager: CLLocationManager = { let location = CLLocationManager() location.delegate = self location.desiredAccuracy = kCLLocationAccuracyKilometer location.requestWhenInUseAuthorization() return location }() override func viewDidLoad() { super.viewDidLoad() subscribeViewModel() if CLLocationManager.locationServicesEnabled() { locationManager.requestLocation() } } @IBAction func searchPressed(_ sender: UIButton) { self.presentSearchAlertController(withTitle: "Enter city name", message: nil, style: .alert) { [unowned self] city in isSearchForCityName = true cityName = city loadData() } } @IBAction func segmentedControlUnitAction(_ sender: UISegmentedControl) { AIMActivityIndicatorManager.sharedInstance.shouldShowIndicator() if sender.selectedSegmentIndex == 0 { unit = "metric" }else { unit = "imperial" } loadData() } @IBAction func fiveDaysAction(_ sender: UIBarButtonItem) { forecastViewModel.fetchForecast5(cityName: cityName, unit: unit) } } // MARK: - SubscribeViewModel extension ViewController { func subscribeViewModel() { // MARK: - CurrentWeatherSubject self.forecastViewModel.CurrentWeatherSubject.subscribe( onNext: { response in AIMActivityIndicatorManager.sharedInstance.forceHideIndicator() self.cityName = self.forecastViewModel.currentWeather?.name ?? "" self.cityLabel.text = self.forecastViewModel.currentWeather?.name self.temperatureLabel.text = self.forecastViewModel.currentWeather?.main?.temperatureString self.humidityLabel.text = self.forecastViewModel.currentWeather?.main?.humidityString self.temperatureUnitLabel.text = (self.unit == "metric") ? "°C":"°F" let img = self.forecastViewModel.currentWeather?.weather.first?.urlIconNameString self.weatherIconImageView.sd_setImage(with: URL(string: img!), placeholderImage: nil, options: .allowInvalidSSLCertificates) }).disposed(by: disposeBag) // MARK: - Forecast5Subject self.forecastViewModel.Forecast5Subject.subscribe( onNext: { response in let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let vc = storyBoard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController vc.dataFor5Days = self.forecastViewModel.dataFor5Days vc.cityName = self.cityName vc.unit = self.unit self.navigationController?.pushViewController(vc, animated: true) }).disposed(by: disposeBag) } func loadData() { if isSearchForCityName { forecastViewModel.fetchCurrentWeather(type: .cityName(city: cityName, unit: unit)) }else{ forecastViewModel.fetchCurrentWeather(type: .coordinate(latitude: latitude, longitude: longitude, unit: unit)) } } } // MARK: - CLLocationManagerDelegate extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorizedAlways, .authorizedWhenInUse: locationManager.startUpdatingLocation() case .denied: print("Location permission denied") case .restricted: print("Location permission restricted") case .notDetermined: print("Location permission notDetermined") @unknown default: fatalError() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } latitude = location.coordinate.latitude longitude = location.coordinate.longitude loadData() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } } // MARK: - SearchAlertController extension ViewController { func presentSearchAlertController(withTitle title: String?, message: String?, style: UIAlertController.Style, completionHandler: @escaping (String) -> Void) { let ac = UIAlertController(title: title, message: message, preferredStyle: style) ac.addTextField { (tf) in tf.placeholder = "Enter city Name" } let search = UIAlertAction(title: "Search", style: .default) { action in let textField = ac.textFields?.first guard let cityName = textField?.text else { return } if cityName != "" { let city = cityName.split(separator: " ").joined(separator: "%20") completionHandler(city) } } let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) ac.addAction(search) ac.addAction(cancel) present(ac, animated: true, completion: nil) } }
import ICar, { ICarMake } from "@/interfaces/car.interface"; import React, { useEffect, useState } from "react"; import * as API from "@/services/api"; import { GetCarBrandsResponseType } from "@/interfaces/api-response.interface"; const useCars = (props?: { query?: string; pagination?: GetCarBrandsResponseType["pagination"] }) => { const [highlightedCars, setHighlightedCars] = useState<ICar[]>([]); const [carBrands, setCarBrands] = useState<ICarMake[]>([]); const [carBrandsLoading, setCarBrandsLoading] = useState<boolean>(true); const [carsLoading, setCarsLoading] = useState<boolean>(true); const [pagination, setPagination] = useState<GetCarBrandsResponseType["pagination"] | null>(null); // Fetch Car Brands useEffect(() => { const controller = new AbortController(); const { signal } = controller; (async function () { const brands = await API.getCarBrands(); if (!signal.aborted) setCarBrands(brands.makeList); })() .then(() => { // if (!signal.aborted) setCarBrandsLoading(false); }) .catch(() => { setCarBrandsLoading(false); console.log("Network Error - API Request Error"); }); return () => controller.abort("Component Unmounted"); }, []); // Fetch Cars - Based on Query useEffect(() => { const controller = new AbortController(); const { signal } = controller; (async function () { if (!carsLoading) setCarsLoading(true); const cars = await API.searchCars({ query: props?.query || "" }); if (!signal.aborted) { setHighlightedCars(cars.result); setPagination(cars.pagination); } })() .then(() => { setCarsLoading(false); // Simulate loading exp setTimeout(function () { setCarsLoading(false); }, 1000); }) .catch(() => { setCarsLoading(false); console.log("Network Error - API Request Error"); }); return () => controller.abort("Component Unmounted"); // return ()=> { // if (loading) setLoading(false); // }; }, [props?.query]); return { cars: highlightedCars, carBrands, carsLoading, carBrandsLoading, pagination, }; }; export default useCars;
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Registration Form</title> <link rel="stylesheet" type="text/css" th:href="@{/css/registration.css}"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <form th:action="@{/packer/login}" method="get"> <button class="btn btn-md btn-warning btn-block" type="Submit">Go To Login Page</button> </form> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <form autocomplete="off" action="#" enctype="multipart/form-data" th:action="@{/packer/registration}" method="post" class="form-horizontal" role="form"> <h2>Registration Form</h2> <div class="form-group"> <div class="col-sm-9"> <label th:if="${#fields.hasErrors('packer.company_name')}" th:errors="${packer.company_name}" class="validation-message"></label> <input type="text" th:field="${packer.company_name}" placeholder="Company Name" class="form-control"/> </div> </div> <div class="form-group"> <div class="col-sm-9"> <label th:if="${#fields.hasErrors('packer.phonenumber')}" th:errors="${packer.phonenumber}" class="validation-message"></label> <input type="tel" th:field="${packer.phonenumber}" placeholder="Phone Number" class="form-control"/> </div> </div> <div class="form-group"> <div class="col-sm-9"> <input type="text" th:field="${packer.email}" placeholder="Email" class="form-control"/> <label th:if="${#fields.hasErrors('packer.email')}" th:errors="${packer.email}" class="validation-message"></label> </div> </div> <div class="form-group"> <div class="col-sm-9"> <input type="password" th:field="${packer.password}" placeholder="Password" class="form-control"/> <label th:if="${#fields.hasErrors('packer.password')}" th:errors="${packer.password}" class="validation-message"></label> </div> </div> <div class="form-group" > <div class="col-sm-9"> <label for="file">Packer Ceritficate</label> <input type="file" id="file" name="file" class="form-control" /> <!--<label th:field="${image.image}"--> <!--th:if="${#fields.hasErrors('image.image')}" th:errors="${image.image}"--> <!--class="validation-message"></label>--> </div> </div> <div class="form-group"> <div class="col-sm-9"> <button type="submit" class="btn btn-primary btn-block">Register User</button> </div> </div> <h2><span class="text-success" th:utext="${successMessage}"></span></h2> </form> </div> </div> </div> </body> </html>
<app-header></app-header> <div class="form-content"> <!-- employee payroll form --> <form class="form" [formGroup]="employeeForm" (ngSubmit)="submitForm()"> <!-- heading --> <div class="form-head">Employee Payroll Form</div> <br><br> <!-- Input FullName --> <div class="row-content"> <mat-label class="label text">Full Name</mat-label> <mat-form-field class="example-full-width" appearance="outline"> <input type="name" class="input" matInput formControlName="name" style="height: 10px" maxlength="25" #fullName> <mat-hint align="end">{{fullName.value.length||0}}/25</mat-hint> <mat-error *ngIf="myError('name', 'required')">This is a required field</mat-error> <mat-error *ngIf="myError('name', 'minlength')">Name should contain at least 3 characters</mat-error> <!-- <mat-error *ngIf="employeeForm.get('name')?.hasError('required')">This is a required field</mat-error> --> </mat-form-field> </div> <!-- profile pic radio button --> <div class="row-content"> <label class="label text" for="profile">Profile Image </label> <mat-radio-group formControlName="profilePic"> <mat-radio-button class=profile-width id="profile1" name="profile" color="primary" value="../assets/profile-images/Ellipse -1.png"> <img class="profile" id='image1' src="../assets/profile-images/Ellipse -1.png"> </mat-radio-button> <mat-radio-button class=profile-width id="profile2" name="profile" color="primary" value="../assets/profile-images/Ellipse -2.png"> <img class="profile" id='image2' src="../assets/profile-images/Ellipse -2.png"> </mat-radio-button> <mat-radio-button class=profile-width id="profile3" name="profile" color="primary" value="../assets/profile-images/Ellipse -3.png"> <img class="profile" id='image3' src="../assets/profile-images/Ellipse -3.png"> </mat-radio-button> <mat-radio-button class=profile-width id="profile4" name="profile" color="primary" value="../assets/profile-images/Ellipse -4.png"> <img class="profile" id='image4' src="../assets/profile-images/Ellipse -4.png"> </mat-radio-button> <mat-radio-button class=profile-width id="profile5" name="profile" color="primary" value="../assets/profile-images/Ellipse -5.png"> <img class="profile" id='image5' src="../assets/profile-images/Ellipse -5.png"> </mat-radio-button> </mat-radio-group> </div> <!-----Input Gender---------> <div class="row-content"> <label class="label text" for="gender">Gender</label> <div> <mat-radio-group formControlName="gender"> <mat-radio-button type="radio" name="gender" color="primary" value="Male"> <label class="text" for="Male">Male</label> </mat-radio-button> <mat-radio-button type="radio" name="gender" color="primary" value="Female"> <label class="text" for="Female">Female</label> </mat-radio-button> </mat-radio-group> </div> </div> <!------Input Department-------> <div class="row-content"> <label class="label text" for="department">Department</label> <div *ngFor="let department of departments"> <mat-checkbox #checkbox class="checkbox" type="checkbox" color="primary" [value]="department.value" (change)="onDepartmentChange($event)" [checked]="department.checked"> <label class="text">{{department.name}}</label> </mat-checkbox> </div> </div> <!-----Input Salary------> <div class="row-content"> <label class="label text" for="salary">Salary </label> <mat-slider color="primary" class="salary-ml" thumbLabel discrete [displayWith]="formatLabel" tickInterval="1000" step="10000" min="10000" max="100000"> <input matSliderThumb formControlName="salary" /> </mat-slider> </div> <!-------Input Date------> <div class="row-content"> <label class="label text" for="startDate"> Start Date </label> <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Choose a date" formControlName="startDate"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> </div> <!------Input Notes-------> <div class="row-content"> <mat-label class="label text">Notes</mat-label> <mat-form-field class="example-full-width" appearance="outline"> <textarea matInput id="notes" class="input" name="Notes" placeholder="Write the Note" style="height:100px" formControlName="note"></textarea> </mat-form-field> </div> <!-- button block --> <div class="buttonParent"> <!-- cancel button --> <a routerLink=""><button mat-raised-button class="resetButton button cancelButton" color="accent">Cancel</button></a> <!-- submit button --> <!-- [disabled]="employeeForm.invalid" --> <button mat-raised-button type="submit" class="button submitButton" id="submitButton">Submit</button> <!-- reset button --> <button mat-raised-button (click)="resetForm()" color="accent" type="reset" class="resetButton button">Reset</button> </div> </form> </div> <router-outlet></router-outlet>
@extends('layouts.header') @section('title', 'Rooms') @section('rooms_navbar_state', 'active') @section('additional_style') @vite(['resources/css/rooms-style.css']) @endsection @section('navbar_header_button') @role('admin') <a href="{{ route('admin.rooms.create') }}" class="add-new-button">Add new room</a> @endrole @role('receptionist') <span class="header-navbar">Rooms</span> @endrole @endsection @section('content') <div class="container-fluid"> <!-- Main container --> <div class="content-container main-container"> <!-- Content container --> <div class="content-header"> <!-- Content header --> <div class="container-fluid"> <!-- Inner container --> @if (session('success')) <div class="alert alert-success"> <!-- Success notification --> {{ session('success') }} </div> @endif @if ($errors->any()) <div class="custom-error-message"> <ul class="error-list"> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <div class="content-container text-center"> <!-- Content container --> <h4 class="font-weight-bold">Search form</h4> <!-- Search form --> @role('admin') <form id="searchForm" method="POST" action="{{ route('admin.rooms.search') }}"> @endrole @role('receptionist') <form id="searchForm" method="POST" action="{{ route('receptionist.rooms.search') }}"> @endrole @csrf <div class="row mt-4"> <!-- Toggles --> <div class="col-md-2"> <label class="toggle"> <input class="toggle-checkbox" id="switch-by-number" type="checkbox"> <div class="toggle-switch"></div> <span class="toggle-label">By number</span> </label> </div> <div class="col-md-4"> <label class="toggle"> <input class="toggle-checkbox" id="switch-by-guest" type="checkbox"> <div class="toggle-switch"></div> <span class="toggle-label">By guest name</span> </label> </div> </div> <div class="form-row"> <div class="col-md-2 pt-2"> <label for="roomNumber"></label> <input type="text" class="form-control text-center @error('roomNumber') is-invalid @enderror" id="roomNumber" name="roomNumber" placeholder="Room number" disabled required maxlength="255"> </div> <div class="col-md-4 pt-2"> <label for="guestName"></label> <input type="text" class="form-control text-center @error('guestName') is-invalid @enderror" id="guestName" name="guestName" placeholder="Guest name" disabled required maxlength="255"> </div> <div class="col-md-6 mt-2 d-none" id="searchTopBlock"> <label for="searchTopBlock"></label> <button type="submit" class="btn btn-primary w-100" name="searchTopBlock" id="searchTopBlock">Search</button> </div> </div> <div id="baseSearch"> <hr /> <div class="form-row"> <div class="col-md-2 mb-2 date-block"> <label for="startDate">Start date</label> <input type="date" class="form-control @error('startDate') is-invalid @enderror" id="startDate" name="startDate" value="{{ \Carbon\Carbon::now()->toDateString() }}" required> </div> <div class="col-md-2 mb-2 date-block"> <label for="endDate">End date</label> <input type="date" class="form-control @error('endDate') is-invalid @enderror" id="endDate" name="endDate" value="{{ \Carbon\Carbon::now()->addDay()->toDateString() }}" required> </div> </div> <div class="form-row"> <div class="col-md-2 pt-2"> <label for="type">Type</label> <select class="form-select text-center @error('type') is-invalid @enderror" id="type" name="type" required> <option value="0">Any</option> <option value="standard">Standard</option> <option value="deluxe">Deluxe</option> <option value="suite">Suite</option> <option value="penthouse">Penthouse</option> </select> </div> <div class="col-md-2 pt-2"> <label for="status">Status</label> <select class="form-select text-center @error('status') is-invalid @enderror" id="status" name="status" required> <option value="0">Any</option> <option value="available">Available</option> <option value="occupied">Occupied</option> <option value="under_maintenance">Maintenance</option> </select> </div> <div class="col-md-2 pt-2"> <label for="adultsBedsCount">Adults beds</label> <select class="form-select text-center @error('adultsBedsCount') is-invalid @enderror" id="adultsBedsCount" name="adultsBedsCount" required> <option value="0">Any</option> @for ($i = 1; $i <= 10; $i++) <option value="{{ $i }}">{{ $i }} persons</option> @endfor </select> </div> <div class="col-md-2 pt-2"> <label for="childrenBedsCount">Children beds</label> <select class="form-select text-center @error('childrenBedsCount') is-invalid @enderror" id="childrenBedsCount" name="childrenBedsCount" required> <option value="-1" selected>Any</option> <option value="0">NO CHILD BED</option> @for ($i = 1; $i <= 10; $i++) <option value="{{ $i }}">{{ $i }} child bed</option> @endfor </select> </div> <div class="col-md-4 pt-3" id="searchBlock"> <label for="searchButton"></label> <button type="submit" class="btn btn-primary w-100" name="searchButton" id="searchButton">Search</button> </div> </div> <div class="form-row mt-1"> <div class="col-md-12 pt-2"> <div class="border rounded p-3"> <div class="border-bottom pb-2 mb-3"> <button class="btn btn-outline-secondary w-100 font-weight-bold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseProperties" aria-expanded="false" aria-controls="collapseProperties"> Include additional properties </button> </div> <div class="collapse" id="collapseProperties"> @foreach ($room_properties as $property) <div class="form-check form-check-inline m-3 font-weight-bold"> <input class="form-check-input mt-1 mr-2" type="checkbox" id="property_{{ $property->id }}" value="{{ $property->id }}" name="additionalProperties[]"> <label class="form-check-label" for="property_{{ $property->id }}">{{ strtoupper($property->name) }}</label> </div> @endforeach </div> </div> </div> </div> </form> </div> <div class="mt-4 text-center"> <!-- Available rooms title --> <h4><b>Available rooms</b></h4> </div> <div id="main-container"> <!-- Main table container --> <table id="free-rooms-table" class="table table-bordered"> <thead> <tr class="text-center"> <th class="text-center">Room №</th> <th class="text-center">Type</th> <th class="text-center">Floor</th> <th class="text-center">Beds</th> <th class="text-center">Price/per night</th> <th class="text-center">Action</th> </tr> </thead> <tbody> @foreach ($rooms as $room) <tr> @role('admin') <td class="text-center"><a href="{{ route('admin.rooms.show', $room->id) }}">{{ $room->room_number }}</td> @endrole @role('receptionist') <td class="text-center"><a href="{{ route('receptionist.rooms.show', $room->id) }}">{{ $room->room_number }}</td> @endrole <td class="text-center">{{ strtoupper($room->type) }}</td> <td class="text-center"> {{ $room->floor_number }} </td> <td class="text-center"> <span class="badge badge-primary badge-big">{{ $room->adults_beds_count }}</span> @if ($room->children_beds_count > 0) <span class="badge badge-success badge-big"><i class="fa-solid fa-baby"></i></span> @endif </td> <td class="text-center"><b>{{ $room->price }}</b></td> <td class="text-center"> @role('admin') <form action="{{ route('admin.rooms.delete', $room->id) }}" method="POST"> @endrole <div class="btn-group" role="group" aria-label="Room actions"> @if ($room->status == "available") @role('admin') <a href="{{ route('admin.booking.create', $room->id) }}" class="btn btn-success">Book now</a> @endrole @role('receptionist') <a href="{{ route('receptionist.booking.create', $room->id) }}" class="btn btn-success">Book now</a> @endrole @endif @role('admin') <a href="{{ route('admin.rooms.show', $room->id) }}" class="btn btn-secondary">Details</a> @endrole @role('receptionist') <a href="{{ route('receptionist.rooms.show', $room->id) }}" class="btn btn-secondary">Details</a> @endrole @role('admin') <a href="{{ route('admin.rooms.edit', $room->id) }}" class="btn btn-warning"><i class="fas fa-pen"></i></a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger"><i class="fa-solid fa-trash"></i></button> </form> @endrole </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> @section('custom-scripts') @vite(['resources/js/rooms/index.js']) @endsection @endsection
// // UITableView+Drop.swift // UITableView+Drop // // Created by 逸风 on 2021/10/29. // import Foundation import UIKit import JFPopup extension Drop where Base: UITableView { @available(iOS 11.0, *) @discardableResult public func tableViewDidEnterDropSession(tableViewDidEnterDropSession: @escaping TableViewDidEnterDropSession) -> Drop { var muteSelf = self muteSelf._tableViewDidEnterDropSession = tableViewDidEnterDropSession return muteSelf } @available(iOS 11.0, *) @discardableResult public func tableViewDidEndDropSession(tableViewDidEndDropSession: @escaping TableViewDidEndDropSession) -> Drop { var muteSelf = self muteSelf._tableViewDidEndDropSession = tableViewDidEndDropSession return muteSelf } @available(iOS 11.0, *) @discardableResult public func tableViewDidExitDropSession(tableViewDidExitDropSession: @escaping TableViewDidExitDropSession) -> Drop { var muteSelf = self muteSelf._tableViewDidExitDropSession = tableViewDidExitDropSession return muteSelf } @available(iOS 11.0, *) @discardableResult public func tableViewDidUpdateDropSession(tableViewDidUpdateDropSession: @escaping TableViewDidUpdateDropSession) -> Drop { var muteSelf = self muteSelf._tableViewDidUpdateDropSession = tableViewDidUpdateDropSession return muteSelf } @available(iOS 11.0, *) @discardableResult public func tableViewDidReceivedDropSource(tableViewDidReceivedDropSource: @escaping TableViewDidReceivedDropSource) -> Drop { var muteSelf = self muteSelf._tableViewDidReceivedDropSource = tableViewDidReceivedDropSource return muteSelf } @available(iOS 11.0, *) @discardableResult public func enabled() -> Drop { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { base.dropDelegate = base } else if #available(iOS 15.0, *) { base.dropDelegate = base } return self } } extension UITableView: UITableViewDropDelegate { @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool { if self.drop.supportSources.count > 0 { return DropViewModel.canHandle(with: self.drop.supportSources, session: session) } return DropViewModel.canHandle(session) } @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, dropSessionDidEnter session: UIDropSession) { self.drop._tableViewDidEnterDropSession?(tableView,session) } @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, dropSessionDidEnd session: UIDropSession) { self.drop._tableViewDidEndDropSession?(tableView,session) } @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, dropSessionDidExit session: UIDropSession) { self.drop._tableViewDidExitDropSession?(tableView,session) } @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal { if let update = self.drop._tableViewDidUpdateDropSession { return update(tableView,session,destinationIndexPath) } var dropProposal = UITableViewDropProposal(operation: .cancel) if tableView.hasActiveDrag { dropProposal = UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } else { dropProposal = UITableViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath) } return dropProposal } @available(iOS 11.0, *) public func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) { coordinator.session.loadObjects(ofClass: DropSource.self) { dropSources in if let dropSources = dropSources as? [DropSource] { let sources = dropSources.filter { return self.drop.supportSources.contains($0.type) } self.drop._tableViewDidReceivedDropSource?(tableView,coordinator,sources) } } } }
from sqlalchemy import (Boolean, Column, Date, Enum, Float, ForeignKey, Integer, Unicode) from sqlalchemy.orm import relationship from bdgt.storage.database import Base class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) name = Column(Unicode, nullable=False) number = Column(Unicode, nullable=False) transactions = relationship("Transaction", backref="account", cascade='all, delete, delete-orphan') def __init__(self, name, number): self.name = name self.number = number class BudgetItem(Base): __tablename__ = 'budget_items' id = Column(Integer, primary_key=True) category_id = Column(Integer, ForeignKey('categories.id')) date = Column(Date, nullable=False) period = Column(Enum(u'week', u'month', u'quarter', u'year', name='period_types'), nullable=False) amount = Column(Float, nullable=False) def __init__(self, date, period, amount): self.date = date self.period = period self.amount = amount class Category(Base): __tablename__ = 'categories' id = Column(Integer, primary_key=True) name = Column(Unicode, nullable=False) budget_items = relationship("BudgetItem", backref="category", cascade='all, delete, delete-orphan') def __init__(self, name): self.name = name class Transaction(Base): __tablename__ = 'transactions' id = Column(Integer, primary_key=True) account_id = Column(Integer, ForeignKey('accounts.id')) date = Column(Date, nullable=False) description = Column(Unicode) amount = Column(Float, nullable=False) reconciled = Column(Boolean, default=False) category_id = Column(Integer, ForeignKey('categories.id')) category = relationship("Category", backref="transactions") def __init__(self, account, date, description, amount, reconciled=False): self.account = account self.date = date self.description = description self.amount = amount self.reconciled = reconciled def is_credit(self): return self.amount > 0 def is_debit(self): return self.amount < 0 def is_in_period(self, beg_date, end_date): return self.date >= beg_date and self.date <= end_date
import React, {useEffect } from "react"; import {createContext} from "react"; import {useState} from "react"; import axios from "axios"; import { useNavigate } from "react-router-dom"; export const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [isAuth, setIsAuth] = useState(""); const navigate = useNavigate(); const login = (email, password) => { axios .post("https://reqres.in/api/login", { email, password }) .then(({ data }) => { localStorage.setItem("token", data.token); setIsAuth(data.token); }); }; const logout = () => { localStorage.setItem("token", ""); setIsAuth(false); }; useEffect(() => { if (isAuth) { navigate("/cart"); } else { navigate("/"); } }, [isAuth]); return ( <AuthContext.Provider value={{ isAuth, login, logout }}> {children} </AuthContext.Provider> ); };
import { Inject, Injectable, Optional } from '@angular/core'; import { MatMomentDateAdapterOptions, MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter } from '@angular/material-moment-adapter'; import { MAT_DATE_LOCALE } from '@angular/material/core'; import * as moment from 'moment'; /** * @description custom date adapter which we can customize on our needs. Currently only needed to display in calendar the local date from PC ignoring the useUtc configuration */ @Injectable() export class CustomDateAdapter extends MomentDateAdapter { constructor( @Optional() @Inject(MAT_DATE_LOCALE) dateLocale: string, @Optional() @Inject(MAT_MOMENT_DATE_ADAPTER_OPTIONS) adapterOptions: MatMomentDateAdapterOptions ) { super(dateLocale, adapterOptions); } /** * @description overwrite the method from Moment Date Adapter * @returns the current date as date from PC ignoring the "useUtc" configuration */ override today(): any { return moment(); } }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QApplication> #include <QFile> #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QStackedLayout> #include <QString> #include <QStyleFactory> #include <QWidget> #include "gamescene.h" #include "introductionscene.h" #include "qtaquin.h" class MainWindow : public QMainWindow { Q_OBJECT public: /** * @brief MainWindow allows to create the main window of the game. * @param parent who will be in charge of its destruction. */ MainWindow(QWidget* parent = nullptr); ~MainWindow(); public slots: /** * @brief switchPage allows to change the page between the initialization page of the board and the game page. */ void switchPage(); private: /** * @brief taquin the game that is represented in this window. */ QTaquin* taquin; /** * @brief centralWidget the central widget of the main window that contains the QStackedLayout (the different pages). */ QWidget* centralWidget; /** * @brief iScene the Introductory scene allowing the player to enter the size of the game board and the difficulty of the game. */ IntroductionScene* iScene; /** * @brief gScene the Game scene to display it and play the game. */ GameScene* gScene; /** * @brief switchPageIndex the current page index. */ int switchPageIndex; /** * @brief actionNewGame allows to start a new game. */ QAction* actionNewGame; /** * @brief actionQuit allows to quit the game. */ QAction* actionQuit; /** * @brief actionNewImage allows to load a new image in the background of the cells. */ QAction* actionNewImage; /** * @brief actionShowNumbers allows to show or hide the number on the cells. */ QAction* actionShowNumbers; /** * @brief layout the layout that contains the two pages of the game. */ QStackedLayout* layout; /** * @brief initComponents initializes the components of the window. */ void initComponents(); /** * @brief arrangement correctly arranges the elements of the window. */ void arrangement(); /** * @brief behavior determines the behavior of the elements contained in the window. */ void behavior(); /** * @brief initMenuBar allows to initialize the menu bar. */ void initMenuBar(); }; #endif // MAINWINDOW_H
from sqlalchemy import Column, Integer, ForeignKey, DateTime from sqlalchemy.orm import relationship from db import Base from datetime import datetime, timezone class Like(Base): __tablename__ = 'likes' id = Column(Integer, primary_key=True) post_id = Column(Integer, ForeignKey('posts.id')) user_id = Column(Integer, ForeignKey('users.id')) timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc)) post = relationship('Post', back_populates='likes') user = relationship('User', back_populates='likes') def to_dict(self): return { 'id': self.id, 'post_id': self.post_id, 'user_id': self.user_id, 'timestamp': self.timestamp.isoformat() }
package com.jackdaw.jinjobbackenduserservice.controller.inner; import com.jackdaw.jinjobbackendmodel.common.ErrorCode; import com.jackdaw.jinjobbackendcommon.config.RedisUtils; import com.jackdaw.jinjobbackendmodel.exception.BusinessException; import com.jackdaw.jinjobbackendcommon.utils.JWTUtil; import com.jackdaw.jinjobbackendmodel.constant.Constants; import com.jackdaw.jinjobbackendmodel.entity.dto.appUser.AppUserLoginDto; import com.jackdaw.jinjobbackendmodel.entity.po.AppUserCollect; import com.jackdaw.jinjobbackendmodel.entity.po.AppUserInfo; import com.jackdaw.jinjobbackendserviceclient.service.user.UserFeignClient; import com.jackdaw.jinjobbackenduserservice.service.AppUserCollectService; import com.jackdaw.jinjobbackenduserservice.service.AppUserInfoService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * 该服务仅内部调用,不是给前端的 */ @RestController @RequestMapping("/inner") public class UserInnerController implements UserFeignClient { @Resource private AppUserInfoService userService; @Resource private JWTUtil<AppUserLoginDto> jwtUtil; @Resource private RedisUtils redisUtils; @Resource private AppUserCollectService appUserCollectService; @Override @GetMapping("/saveCollect") public void saveCollect(String userId, String objectId, Integer collectType) { appUserCollectService.saveCollect(userId,objectId,collectType); } @Override @GetMapping("/deleteAppUserCollectByUserIdAndObjectIdAndCollectType") public Integer deleteAppUserCollectByUserIdAndObjectIdAndCollectType(String userId, String objectId, Integer collectType) { return appUserCollectService.deleteAppUserCollectByUserIdAndObjectIdAndCollectType(userId,objectId,collectType); } @Override @GetMapping("/getAppUserCollectByUserIdAndObjectIdAndCollectType") public AppUserCollect getAppUserCollectByUserIdAndObjectIdAndCollectType(String userId, String objectId, Integer collectType) { return appUserCollectService.getAppUserCollectByUserIdAndObjectIdAndCollectType(userId,objectId,collectType); } /** * 根据 id 获取用户 * * @param userId * @return */ @Override @GetMapping("/get/id") public AppUserInfo getById(@RequestParam("userId") String userId) { return userService.getAppUserInfoByUserId(userId); } /** * 根据 token 获取用户 * * @param token * @return */ @Override @GetMapping("/get/token") public AppUserInfo getByToken(@RequestParam("token") String token) { AppUserLoginDto userAppDto = jwtUtil.getTokenData(Constants.JWT_KEY_LOGIN_TOKEN, token, AppUserLoginDto.class); if (userAppDto == null) { throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR); } return userService.getAppUserInfoByUserId(userAppDto.getUserId()); } /** * 根据 token 登录 * * @param token * @return */ @Override @GetMapping("/get/userCheckin") public String getUserCheckin(@RequestParam("token") String token){ AppUserInfo appUserLoginDto = getByToken(token); return userService.getCheckinInfo(appUserLoginDto.getUserId()); } /** * * @return */ @Override @GetMapping("/get/setCountOjQuestion") public boolean setCountOjQuestion(@RequestParam("token") String userId){ AppUserInfo appUser = getById(userId); appUser.setOjAcSum(appUser.getOjAcSum()+1); return userService.updateAppUserInfoByUserId(appUser,userId)>0; } /** * * @return */ @Override @GetMapping("/get/setCountExamQuestion") public boolean setCountExamQuestion(@RequestParam("token") String userId, @RequestParam("score") Float score){ AppUserInfo appUserLogin = getById(userId); appUserLogin.setExamAcSum(appUserLogin.getExamAcSum()+1); float result = (appUserLogin.getExamAcScore() * appUserLogin.getExamAcSum() + score) / (appUserLogin.getExamAcSum() + 1); appUserLogin.setExamAcScore((float) (Math.floor(result * 10) / 10)); return userService.updateAppUserInfoByUserId(appUserLogin,userId)>0; } }
import { createBrowserRouter } from "react-router-dom"; import Root from "../LayOut/Root"; import ErrorPage from "../Pages/ErrorPage"; import Home from "../Pages/Home/Home"; import Signin from "../Pages/Signin"; import SignUp from "../Pages/SignUp"; import Men from "../Pages/Men"; import Electnonics from "../Pages/Electnonics"; import Women from "../Pages/Women"; import MenDetails from "../Pages/MenDetails"; import ElectronicsDetails from "../Pages/ElectronicsDetails"; import WomenDetails from "../Pages/WomenDetails"; import Privetroute from "./Privetroute"; const router = createBrowserRouter([ { path: "/", element: <Root></Root>, errorElement: <ErrorPage></ErrorPage>, children: [ { path: "/", element: <Home></Home>, }, { path: "/men", element: <Men></Men>, }, { path: '/men_details/:id', loader: ({ params }) => fetch(`http://localhost:5000/allproducts/${params.id}`), element: <Privetroute><MenDetails></MenDetails></Privetroute> }, { path: "/electronics", element: <Electnonics></Electnonics>, }, { path: '/electronics_details/:id', loader: ({ params }) => fetch(`http://localhost:5000/allproducts/${params.id}`), element: <Privetroute><ElectronicsDetails></ElectronicsDetails></Privetroute> , }, { path: "/women", element: <Women></Women>, }, { path: '/women_details/:id', loader: ({ params }) => fetch(`http://localhost:5000/allproducts/${params.id}`), element: <Privetroute><WomenDetails></WomenDetails></Privetroute>, }, { path: "/signin", element: <Signin></Signin>, }, { path: "/signup", element: <SignUp></SignUp>, }, ] }, ]); export default router;
## Django Book Store [![GitHub stars](https://img.shields.io/github/stars/anasnashat/Book-store)](https://github.com/anasnashat/Book-store/stargazers) [![GitHub license](https://img.shields.io/github/license/anasnashat/Book-store)](https://github.com/anasnashat/Book-store/blob/master/LICENSE) Django Book Store is a web application built with Django, a high-level Python web framework, that allows users to browse and purchase books online. The application integrates with Stripe and PayPal for secure payment processing. [Live Demo](https://anas-books-store-django.up.railway.app/) ![Django Book Store](https://img001.prntscr.com/file/img001/LGGsdLKhSN-XOws4iXKgzQ.png) ## Features - Book Listings: Books are displayed with details such as title, author, description, price, and cover image. - Search and Filtering: Users can search for books by title, author, or genre, and filter the results based on various criteria. - Shopping Cart: Users can add books to their shopping cart and review the items before proceeding to checkout. - Secure Payment Processing: The application integrates with both Stripe and PayPal to ensure secure payment transactions. - Order Management: Users can view their order history and track the status of their orders. - Admin Interface: Administrators have access to an admin interface to manage books, user accounts, and orders. - Sales Reports: Generate visual reports of book sales using charts in the admin panel. ## Installation 1. Clone the repository: ```shell git clone https://github.com/anasnashat/Book-store.git ``` 2. Change to the project directory: ``` shell cd Book-store ``` 3. Create and activate a virtual environment: ```shell pip install pipenv pipenv shell ``` 4. Install the required dependencies: ```shell pipenv install -r requirements.txt ``` 5. Set up the database: ```shell python manage.py migrate ``` 6. Create a superuser account: ```shell python manage.py createsuperuser ``` ## Configure Stripe and PayPal API credentials: - Stripe: - Sign up for a Stripe account at https://stripe.com. - Obtain your Stripe API keys. - Update the settings.py file with your Stripe API keys: ``` python STRIPE_PUBLIC_KEY = 'your-stripe-public-key' STRIPE_SECRET_KEY = 'your-stripe-secret-key' ``` - PayPal: - Sign up for a PayPal Business account at https://www.paypal.com. - Obtain your PayPal API credentials. - Update the settings.py file with your PayPal API credentials: ``` python PAYPAL_CLIENT_ID = 'your-paypal-client-id' PAYPAL_SECRET_KEY = 'your-paypal-secret-key' ``` ## Run the development server: ``` shell python manage.py runserver ``` Open your web browser and visit http://localhost:8000 to access the application. ## Usage: Browse the book catalog and click on a book to view its details. Use the search bar to find specific books by title, author, or genre. Add books to the shopping cart by clicking the "Add to Cart" button. Review the items in your cart and click "Checkout" to proceed to the payment page. Enter your payment details and complete the transaction using either Stripe or PayPal. View your order history and track the status of your orders. Access the admin panel by visiting http://localhost:8000/admin and log in with your superuser account. Generate sales reports with charts in the admin panel to analyze book sales data. ## Contributing Contributions to Django Book Store are welcome! If you encounter any bugs, have feature requests, or want to contribute improvements, please open an issue or submit a pull request to the [GitHub repository](https://github.com/your-username/django-book-store). We appreciate your help in making the Django Book Store better! ## Issue Tracker If you find any bugs or have feature requests, please create an issue on the [issue tracker](https://github.com/your-username/django-book-store/issues). We'll do our best to address them as soon as possible. ## Pull Requests We welcome pull requests with bug fixes, feature enhancements, or any other improvements. Follow these steps to submit a pull request: 1. Fork the repository and create your branch from `main`. 2. Make the necessary changes and ensure that the tests pass. 3. Write tests, if applicable, to cover the changes you made. 4. Commit your changes and push them to your forked repository. 5. Open a pull request in the main repository, describing the changes you made and providing any relevant information or context. We'll review your pull request and provide feedback. Thank you for your contribution! ## Code Style Please follow the existing code style and conventions used in the project to maintain consistency. ## Deployment To deploy Django Book Store to a production environment, follow these steps: 1. Update the `ALLOWED_HOSTS` setting in the `settings.py` file to include the domain name or IP address of your production server: ```python ALLOWED_HOSTS = ['your-domain.com', 'your-ip-address'] ``` Configure the database settings in the settings.py file to connect to your production database. You can use database backends such as PostgreSQL, MySQL, or SQLite, depending on your needs. Set up static file serving for your production server. Refer to the Django documentation on [managing static files](https://docs.djangoproject.com/en/3.2/howto/static-files/deployment/). for detailed instructions. ## License By contributing to the Django Book Store project, you agree that your contributions will be licensed under the [MIT License](LICENSE).
var Voting = artifacts.require("./Voting.sol"); contract("Voting", function(accounts){ var votingInstance; it("initializes with 3 options", function(){ return Voting.deployed().then(function(instance){ return instance.optionsCount(); }).then(function(count){ assert.equal(count, 3); }); }); it("initializes the options with correct values", function(){ return Voting.deployed().then(function(instance){ votingInstance = instance; return votingInstance.options(1); }).then(function(option){ assert.equal(option[0], 1, "correct id"); assert.equal(option[1], "Option 1", "correct content"); assert.equal(option[2], 0, "correct count"); return votingInstance.options(2); }).then(function(option){ assert.equal(option[0], 2, "correct id"); assert.equal(option[1], "Option 2", "correct content"); assert.equal(option[2], 0, "correct count"); return votingInstance.options(3); }).then(function(option){ assert.equal(option[0], 3, "correct id"); assert.equal(option[1], "Option 3", "correct content"); assert.equal(option[2], 0, "correct count"); }); }); it("allows a voter to cast a vote", function(){ return Voting.deployed().then(function(instance){ votingInstance = instance; let voteCounts = [5, 3, 2]; return votingInstance.vote(voteCounts, {from: accounts[1]}); }).then(function(receipt){ return votingInstance.voters(accounts[1]); }).then(function(voted){ assert(voted, "the voter was marked as voted"); return votingInstance.options(1); }).then(function(option){ var voteCount = option[2]; assert.equal(voteCount, 5, "increments the count correctly"); return votingInstance.options(2); }).then(function(option){ var voteCount = option[2]; assert.equal(voteCount, 3, "increments the count correctly"); return votingInstance.options(3); }).then(function(option){ var voteCount = option[2]; assert.equal(voteCount, 2, "increments the count correctly"); return votingInstance.options(2); }) }); /*it("allows a voter to cast a vote", function(){ return Voting.deployed().then(function(instance){ votingInstance = instance; return votingInstance.vote(1, 5, {from: accounts[1]}); }).then(function(vote){ return votingInstance.options(1); }).then(function(result){ var voteCount = result[2]; assert.equal(voteCount, 5, "increments the count correctly") }); }); it("adds voter with correct values", function(){ return Voting.deployed().then(function(instance){ votingInstance = instance; return votingInstance.addVoter(accounts[1]); }).then(function(addVoter){ return votingInstance.votersCount(); }).then(function(votersCount){ assert.equal(votersCount, 1); return votingInstance.voters(accounts[1]); }).then(function(voter){ assert.equal(voter[0], 1, "correct id"); assert.equal(voter[1], 100,"correct voice creds"); assert.equal(voter[2], false, "havent voted"); }) });*/ })
interface MyInterface { fun print() var msg: String } class MyImplementation : MyInterface { override fun print() { println(msg) } override var msg: String = "To be, or not to be, that is the question:" fun updateMsg(newMsg: String) { msg = newMsg } } class CharacterInfoFormatter(base: MyInterface) : MyInterface by base { var start: String = "" var end: String = "" override fun print() = println("${this.msg} [${this.msg.length} characters]") } fun main() { val line = readln() val a = MyImplementation() a.updateMsg(line) val delegate = CharacterInfoFormatter(a) delegate.print() }
import { arrayUnion, doc, serverTimestamp, Timestamp, updateDoc } from 'firebase/firestore'; import React, { useContext, useState } from 'react' import { AuthContext } from '../context/AuthContext'; import { ChatContext } from '../context/ChatContext'; import { db, storage } from '../firebase'; import { v4 as uuid } from 'uuid'; import { getDownloadURL, ref, uploadBytesResumable } from 'firebase/storage'; const Input = () => { const [text, setText] = useState(""); const [img, setImg] = useState(null); const { currentUser } = useContext(AuthContext); const { data } = useContext(ChatContext); const handleSend = async () => { if(img){ const storageRef = ref(storage, uuid()); const uploadTask = uploadBytesResumable(storageRef, img); uploadTask.on( (error) => { // setErr(true); }, () => { getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => { await updateDoc(doc(db,"chats", data.chatId),{ messages: arrayUnion({ id: uuid(), text, senderId: currentUser.uid, date: Timestamp.now(), img: downloadURL }) }) }); } ); }else{ await updateDoc(doc(db,"chats", data.chatId),{ messages: arrayUnion({ id: uuid(), text, senderId: currentUser.uid, date: Timestamp.now() }) }) } await updateDoc(doc(db,"userChats",currentUser.uid),{ [data.chatId+".lastMessage"]: { text }, [data.chatId+".date"]: serverTimestamp() }) await updateDoc(doc(db,"userChats",data.user.uid),{ [data.chatId+".lastMessage"]: { text }, [data.chatId+".date"]: serverTimestamp() }) setImg(null); setText(""); }; return ( <div className='input'> <input type="text" placeholder='Type something...' onChange={e => setText(e.target.value)} value={text} /> <div className="send"> <img src="https://raw.githubusercontent.com/safak/youtube2022/react-chat/src/img/attach.png" alt="" /> <input type="file" style={{display:'none'}} id="file" onChange={e => setImg(e.target.files[0])}/> <label htmlFor="file"> <img src="https://raw.githubusercontent.com/safak/youtube2022/react-chat/src/img/img.png" alt="" /> </label> <button onClick={handleSend}>Send</button> </div> </div> ) } export default Input
/* * UVCCamera * library and sample to access to UVC web camera on non-rooted Android device * * Copyright (c) 2014-2017 saki t_saki@serenegiant.com * * File name: Parameters.cpp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * All files in the folder are under this Apache License, Version 2.0. * Files in the jni/libjpeg, jni/libusb, jin/libuvc, jni/rapidjson folder may have a different license, see the respective files. */ #define LOG_TAG "Parameters" #include "Parameters.h" #include "rapidjson/rapidjson.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "libuvc/libuvc_internal.h" using namespace rapidjson; static void write(Writer<StringBuffer> &writer, const char *key, const char *value) { writer.String(key); writer.String(value); } static void write(Writer<StringBuffer> &writer, const char *key, uint16_t value) { writer.String(key); writer.Uint(value); } static void write(Writer<StringBuffer> &writer, const char *key, int32_t value) { writer.String(key); writer.Int(value); } static void write(Writer<StringBuffer> &writer, const char *key, uint32_t value) { writer.String(key); writer.Uint(value); } static void write(Writer<StringBuffer> &writer, const char *key, int64_t value) { writer.String(key); writer.Int64(value); } static void write(Writer<StringBuffer> &writer, const char *key, uint64_t value) { writer.String(key); writer.Uint64(value); } static const char *_uvc_name_for_format_subtype(uint8_t subtype) { switch (subtype) { case UVC_VS_FORMAT_UNCOMPRESSED: return "UncompressedFormat"; case UVC_VS_FORMAT_MJPEG: return "MJPEGFormat"; default: return "Unknown"; } } #define INDEX "index" #define TYPE "type" #define SUBTYPE "subType" #define WIDTH "width" #define HEIGHT "height" #define VALUE "value" #define DETAIL "detail" #define DESCRIPTION "description" #define DESC_SUBTYPE SUBTYPE #define DESC_VENDERID "venderId" #define DESC_PRODUCTID "productId" #define DESC_SERIALNUMBER "serialNumber" #define DESC_MANIFUCTURE "manifuctureName" #define DESC_PRODUCT "productName" #define DESC_UVC "uvc" #define DESC_VIDEO_CONTROL "videoControl" #define DESC_INTERFACES "interfaces" #define INTERFACE_TYPE TYPE #define INTERFACE_TYPE_VIDEOSTREAM "videoStreaming" #define INTERFACE_TYPE_AUDIOSTREAM "audioStreaming" #define INTERFACE_INDEX INDEX #define INTERFACE_ENDPOINT_ADDR "endpointAddress" #define FORMATS "formats" #define FORMAT_INDEX INDEX #define FORMAT_NAME "format" #define FORMAT_DETAIL DETAIL #define FORMAT_BITS_PER_PIXEL "bitsPerPixel" #define FORMAT_GUID "GUID" #define FORMAT_DEFAULT_FRAME_INDEX "defaultFrameIndex" #define FORMAT_ASPECTRATIO_X "aspectRatioX" #define FORMAT_ASPECTRATIO_Y "aspectRatioY" #define FORMAT_INTERLACE_FLAGS "interlaceFlags" #define FORMAT_COPY_PROTECT "copyProtect" #define FORMAT_FRAMEDESCRIPTORS "frameDescriptors" #define FRAME_INDEX INDEX #define FRAME_CAPABILITIES "capabilities" #define FRAME_WIDTH WIDTH #define FRAME_HEIGHT HEIGHT #define FRAME_BITRATE_MIN "minBitRate" #define FRAME_BITRATE_MAX "maxBitRate" #define FRAME_FRAMEBUFFERSIZE_MAX "maxFrameBufferSize" #define FRAME_INTERVAL_DEFAULT "defaultFrameInterval" #define FRAME_FPS_DEFAULT "defaultFps" #define FRAME_INTERVALS "intervals" #define FRAME_INTERVAL_INDEX INDEX #define FRAME_INTERVAL_VALUE VALUE #define FRAME_INTERVAL_FPS "fps" #define FRAME_INTERVAL_MIN "minFrameInterval" #define FRAME_INTERVAL_MAX "maxFrameInterval" #define FRAME_INTERVAL_STEP "frameIntervalStep" static void writerFormat(Writer<StringBuffer> &writer, uvc_format_desc_t *fmt_desc) { uvc_frame_desc_t *frame_desc; char work[256]; writer.String(FORMAT_DETAIL); writer.StartObject(); { write(writer, FORMAT_BITS_PER_PIXEL, fmt_desc->bBitsPerPixel); sprintf(work, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", fmt_desc->guidFormat[0], fmt_desc->guidFormat[1], fmt_desc->guidFormat[2], fmt_desc->guidFormat[3], fmt_desc->guidFormat[4], fmt_desc->guidFormat[5], fmt_desc->guidFormat[6], fmt_desc->guidFormat[7], fmt_desc->guidFormat[8], fmt_desc->guidFormat[9], fmt_desc->guidFormat[10], fmt_desc->guidFormat[11], fmt_desc->guidFormat[12], fmt_desc->guidFormat[13], fmt_desc->guidFormat[14], fmt_desc->guidFormat[15]); write(writer, FORMAT_GUID, work); write(writer, FORMAT_DEFAULT_FRAME_INDEX, fmt_desc->bDefaultFrameIndex); write(writer, FORMAT_ASPECTRATIO_X, fmt_desc->bAspectRatioX); write(writer, FORMAT_ASPECTRATIO_Y, fmt_desc->bAspectRatioY); write(writer, FORMAT_INTERLACE_FLAGS, fmt_desc->bmInterlaceFlags); write(writer, FORMAT_COPY_PROTECT, fmt_desc->bCopyProtect); writer.String(FORMAT_FRAMEDESCRIPTORS); writer.StartArray(); DL_FOREACH(fmt_desc->frame_descs, frame_desc) { uint32_t *interval_ptr; writer.StartObject(); { write(writer, FRAME_INDEX, frame_desc->bFrameIndex); write(writer, FRAME_CAPABILITIES, frame_desc->bmCapabilities); write(writer, FRAME_WIDTH, frame_desc->wWidth); write(writer, FRAME_HEIGHT, frame_desc->wHeight); write(writer, FRAME_BITRATE_MIN, frame_desc->dwMinBitRate); write(writer, FRAME_BITRATE_MAX, frame_desc->dwMaxBitRate); write(writer, FRAME_FRAMEBUFFERSIZE_MAX, frame_desc->dwMaxVideoFrameBufferSize); write(writer, FRAME_INTERVAL_DEFAULT, frame_desc->dwDefaultFrameInterval); write(writer, FRAME_FPS_DEFAULT, 10000000 / frame_desc->dwDefaultFrameInterval); if (frame_desc->intervals) { writer.String(FRAME_INTERVALS); writer.StartArray(); for (interval_ptr = frame_desc->intervals; *interval_ptr; ++interval_ptr) { writer.StartObject(); write(writer, FRAME_INTERVAL_INDEX, (int ) (interval_ptr - frame_desc->intervals)); write(writer, FRAME_INTERVAL_VALUE, *interval_ptr); write(writer, FRAME_INTERVAL_FPS, 10000000 / *interval_ptr); writer.EndObject(); } writer.EndArray(); } else { // 最小fps writer.String(FRAME_INTERVAL_MIN); writer.StartObject(); { write(writer, FRAME_INTERVAL_INDEX, frame_desc->dwMinFrameInterval); write(writer, FRAME_INTERVAL_VALUE, frame_desc->dwMinFrameInterval); write(writer, FRAME_INTERVAL_FPS, 10000000 / frame_desc->dwMinFrameInterval); } writer.EndObject(); // 最大fps writer.String(FRAME_INTERVAL_MAX); writer.StartObject(); { write(writer, FRAME_INTERVAL_INDEX, frame_desc->dwMaxFrameInterval); write(writer, FRAME_INTERVAL_VALUE, frame_desc->dwMaxFrameInterval); write(writer, FRAME_INTERVAL_FPS, 10000000 / frame_desc->dwMaxFrameInterval); } writer.EndObject(); if (frame_desc->dwFrameIntervalStep) { // fpsステップ writer.String(FRAME_INTERVAL_STEP); writer.StartObject(); { write(writer, FRAME_INTERVAL_INDEX, frame_desc->dwFrameIntervalStep); write(writer, FRAME_INTERVAL_VALUE, frame_desc->dwFrameIntervalStep); write(writer, FRAME_INTERVAL_FPS, 10000000 / frame_desc->dwFrameIntervalStep); } writer.EndObject(); } } } writer.EndObject(); } writer.EndArray(); // end of FORMAT_FRAMEDESCRIPTORS } writer.EndObject(); // end of FORMAT_DETAIL } static void writerFormatDescriptions(Writer<StringBuffer> &writer, uvc_streaming_interface_t *stream_if) { uvc_format_desc_t *fmt_desc; int i; writer.String(FORMATS); writer.StartArray(); DL_FOREACH(stream_if->format_descs, fmt_desc) { writer.StartObject(); { write(writer, FORMAT_INDEX, fmt_desc->bFormatIndex); write(writer, DESC_SUBTYPE, fmt_desc->bDescriptorSubtype); write(writer, FORMAT_NAME, _uvc_name_for_format_subtype(fmt_desc->bDescriptorSubtype)); switch (fmt_desc->bDescriptorSubtype) { case UVC_VS_FORMAT_UNCOMPRESSED: case UVC_VS_FORMAT_MJPEG: writerFormat(writer, fmt_desc); break; default: break; } } writer.EndObject(); } writer.EndArray(); // end of FORMATS } UVCDiags::UVCDiags() {} UVCDiags::~UVCDiags() {}; char *UVCDiags::getDescriptions(const uvc_device_handle_t *deviceHandle) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); char work[256]; ENTER(); writer.StartObject(); { writer.String(DESCRIPTION); writer.StartObject(); { uvc_device_descriptor_t *desc; uvc_get_device_descriptor(deviceHandle->dev, &desc); write(writer, DESC_VENDERID, desc->idVendor); write(writer, DESC_PRODUCTID, desc->idProduct); write(writer, DESC_SERIALNUMBER, desc->serialNumber ? desc->serialNumber : "[none]"); write(writer, DESC_MANIFUCTURE, desc->manufacturer ? desc->manufacturer : "[unknown]"); // write(writer, DESC_PRODUCT, desc->product ? desc->product : "UVC Camera"); if (desc->product) write(writer, DESC_PRODUCT, desc->product); else { sprintf(work, "UVC Camera (%x:%x)", desc->idVendor, desc->idProduct); write(writer, DESC_PRODUCT, work); } uvc_free_device_descriptor(desc); if (deviceHandle->info->ctrl_if.bcdUVC) { writer.String(DESC_UVC); writer.StartObject(); { write(writer, DESC_VIDEO_CONTROL, deviceHandle->info->ctrl_if.bcdUVC); writer.String(DESC_INTERFACES); writer.StartArray(); { assert(deviceHandle->info->stream_ifs); uvc_streaming_interface_t *stream_if; int stream_idx = 0; DL_FOREACH(deviceHandle->info->stream_ifs, stream_if) { ++stream_idx; writer.StartObject(); { write(writer, INTERFACE_TYPE, INTERFACE_TYPE_VIDEOSTREAM); write(writer, INTERFACE_INDEX, stream_idx); write(writer, INTERFACE_ENDPOINT_ADDR, stream_if->bEndpointAddress); writerFormatDescriptions(writer, stream_if); } writer.EndObject(); } } writer.EndArray(); // end of DESC_INTERFACES } writer.EndObject(); // end of DESC_UVC } // XXX other interfaces } writer.EndObject(); // end of DESCRIPTION } writer.EndObject(); RETURN(strdup(buffer.GetString()), char *); } char *UVCDiags::getCurrentStream(const uvc_stream_ctrl_t *ctrl) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); ENTER(); writer.StartObject(); { write(writer, "hint", ctrl->bmHint); write(writer, "formatIndex", ctrl->bFormatIndex); write(writer, "frameIndex", ctrl->bFrameIndex); write(writer, "frameInterval", ctrl->dwFrameInterval); write(writer, "keyFrameRate", ctrl->wKeyFrameRate); write(writer, "frameRate", ctrl->wPFrameRate); write(writer, "compQuality", ctrl->wCompQuality); write(writer, "compWindowSize", ctrl->wCompWindowSize); write(writer, "delay", ctrl->wDelay); write(writer, "maxVideoFrameSize", ctrl->dwMaxVideoFrameSize); write(writer, "maxPayloadTransferSize", ctrl->dwMaxPayloadTransferSize); write(writer, "interfaceNumber", ctrl->bInterfaceNumber); } writer.EndObject(); RETURN(strdup(buffer.GetString()), char *); } char *UVCDiags::getSupportedSize(const uvc_device_handle_t *deviceHandle) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); char buf[256]; ENTER(); writer.StartObject(); { if (deviceHandle->info->stream_ifs) { uvc_streaming_interface_t *stream_if; int stream_idx = 0; writer.String("formats"); writer.StartArray(); DL_FOREACH(deviceHandle->info->stream_ifs, stream_if) { ++stream_idx; uvc_format_desc_t *fmt_desc; uvc_frame_desc_t *frame_desc; DL_FOREACH(stream_if->format_descs, fmt_desc) { writer.StartObject(); { switch (fmt_desc->bDescriptorSubtype) { case UVC_VS_FORMAT_UNCOMPRESSED: case UVC_VS_FORMAT_MJPEG: write(writer, "index", fmt_desc->bFormatIndex); write(writer, "type", fmt_desc->bDescriptorSubtype); write(writer, "default", fmt_desc->bDefaultFrameIndex); writer.String("size"); writer.StartArray(); DL_FOREACH(fmt_desc->frame_descs, frame_desc) { snprintf(buf, sizeof(buf), "%dx%d", frame_desc->wWidth, frame_desc->wHeight); buf[sizeof(buf)-1] = '\0'; writer.String(buf); } writer.EndArray(); break; default: break; } } writer.EndObject(); } } writer.EndArray(); // FIXME still image is not supported now } } writer.EndObject(); RETURN(strdup(buffer.GetString()), char *); }
// // SearchFilterView.swift // Forist-Test-SwiftUI // // Created by Hayden Wies on 2021-07-23. // import SwiftUI struct SearchFilterView: View { @Environment(\.presentationMode) var presentationMode @ObservedObject var filteredSearchManager = FilteredSearchManager() // Account type isSelected variables @State var creatorIsSelected = false @State var businessIsSelected = false @State var nonProfitIsSelected = false @State var showResults = false // Content selection tags @State var tagsCollection: [String : Bool] = [ "music": false, "art" : false ] // Platform isSelected variables @State var instagramIsSelected = false @State var youtubeIsSelected = false @State var tiktokIsSelected = false init() { // Cosmetic configuration for navigation bar let navBarAppearance = UINavigationBarAppearance() navBarAppearance.backgroundColor = UIColor.systemBackground navBarAppearance.shadowColor = UIColor.clear UINavigationBar.appearance().tintColor = UIColor.label UINavigationBar.appearance().standardAppearance = navBarAppearance UINavigationBar.appearance().compactAppearance = navBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance } var body: some View { NavigationView { VStack { // MARK: - Dismiss button HStack { Spacer() Button(action: { // Dismiss view presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: "xmark.circle.fill") .resizable() .frame(width: 25, height: 25) .foregroundColor(Color(UIColor.label)) .padding() .padding(.trailing, 10) }) } // MARK: - User type selection ScrollView { VStack { HStack { Text("Account Type") .font(.system(size: 18, weight: .semibold)) .padding(.leading, 30) .padding(.bottom, 10) Spacer() } HStack { Spacer() CheckBoxView(checked: $creatorIsSelected) Text("Creator") Spacer() CheckBoxView(checked: $businessIsSelected) Text("Business") Spacer() CheckBoxView(checked: $nonProfitIsSelected) Text("Non Profit") Spacer() } .padding(.bottom, 30) // MARK: - Content categories HStack { Text("Content Categories") .font(.system(size: 18, weight: .semibold)) .padding(.leading, 30) .padding(.bottom, 10) Spacer() } HStack { // Tag: Art Button(action: { tagsCollection["art"]!.toggle() }, label: { ZStack{ if tagsCollection["art"]!{ Color(UIColor.green) } else { Color(UIColor.red) } Text("Art") .foregroundColor(.black) .font(.system(size: 16)) } .frame(width: 40, height: 25) .cornerRadius(5) }) // Tag: Music Button(action: { tagsCollection["music"]!.toggle() }, label: { ZStack{ if tagsCollection["music"]!{ Color(UIColor.green) } else { Color(UIColor.red) } Text("Music") .foregroundColor(.black) .font(.system(size: 16)) } .frame(width: 60, height: 25) .cornerRadius(5) }) } .padding(.bottom, 30) // MARK: - Instagram VStack { HStack { CheckBoxView(checked: $instagramIsSelected) .padding(.leading, 30) Text("Instagram") .font(.system(size: 18, weight: .semibold)) Spacer() } if instagramIsSelected { // Stats selection box ZStack{ Color(UIColor.label) Text("Stats selection box") .foregroundColor(Color(UIColor.systemBackground)) } .frame(height: 100) .cornerRadius(10) .padding(.horizontal) } } .padding(.bottom, 30) // MARK: - YouTube VStack { HStack { CheckBoxView(checked: $youtubeIsSelected) .padding(.leading, 30) Text("YouTube") .font(.system(size: 18, weight: .semibold)) Spacer() } if youtubeIsSelected { // Stats selection box ZStack{ Color(UIColor.label) Text("Stats selection box") .foregroundColor(Color(UIColor.systemBackground)) } .frame(height: 100) .cornerRadius(10) .padding(.horizontal) } } .padding(.bottom, 30) // MARK: - TikTok VStack { HStack { CheckBoxView(checked: $tiktokIsSelected) .padding(.leading, 30) Text("TikTok") .font(.system(size: 18, weight: .semibold)) Spacer() } if tiktokIsSelected { // Stats selection box ZStack{ Color(UIColor.label) Text("Stats selection box") .foregroundColor(Color(UIColor.systemBackground)) } .frame(height: 100) .cornerRadius(10) .padding(.horizontal) } } // MARK: - Search with filter button NavigationLink(destination: SearchFilterResultsView(filteredSearchManager: filteredSearchManager), isActive: $showResults, label: { Button(action: { // Start loading of users filteredSearchManager.isLoading = true // Call search function filteredSearchManager.filterUsers(isCreatorSelected: creatorIsSelected, isBusinessSelected: businessIsSelected, isNonProfitSelected: nonProfitIsSelected, tagsCollection: tagsCollection) // Show results page showResults = true }, label: { ZStack { Color(UIColor.label) Text("Search with filter") .font(.system(size: 16, weight: .semibold)) .foregroundColor(Color(UIColor.systemBackground)) } .frame(width: 200, height: 60) .cornerRadius(30) }) .padding(30) }) Spacer() } } } .navigationBarHidden(true) } } } // MARK: - Preview struct FilterSearchView_Previews: PreviewProvider { static var previews: some View { SearchFilterView() } }
<?php namespace Drupal\hot_stocks\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Component\Serialization\Json; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Logger\LoggerChannelFactory; /** * User for form for personalization with with Charles Scwhab API. * */ class ClientForm extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'hot_stocks_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('hot_stocks.settings'); $form['fullname'] = [ '#type' => 'textfield', '#title' => $this->t('Full Name'), '#default_value' => $config->get('name'), '#description' => $this->t('Your name.'), ]; $form['email'] = [ '#type' => 'textfield', '#title' => $this->t('Email'), '#default_value' => $config->get('email'), '#description' => $this->t('The API key to authenticate with the remote REST server.'), ]; $form['brokage'] = [ '#type' => 'checkboxes', '#title' => $this->t('Brokage Account'), '#options' => [ 'charlesschwab' => $this->t('Charles Schwab'), 'ninjatrader' => $this->t('NinjaTrader'), 'robinhood' => $this->t('Robinhood'), ], ]; $form['offering'] = [ '#type' => 'checkboxes', '#title' => $this->t('Service of Interest'), '#options' => [ 'learning' => $this->t('Learn financial markets'), 'advicement' => $this->t('Seek financial advice'), 'investment' => $this->t('Invest in finacial markets'), 'management' => $this->t('Work with portfolio managers'), ], '#description' => $this->t('The service offerings you are interested in.'), ]; $form['actions'] = ['#type' => 'actions']; $form['actions']['send'] = [ '#type' => 'submit', '#value' => $this->t('Submit'), '#attributes' => [ 'class' => [ 'use-ajax', 'button--primary', ], ], '#ajax' => [ 'callback' => [$this, 'submitModalFormAjax'], 'event' => 'click', ], ]; $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('hot_stocks.settings') ->set('brokerage', $form_state->getValue('brokerage')) ->set('name', $form_state->getValue('name')) ->set('email', $form_state->getValue('email')) ->set('offerings', $form_state->getValue('offerings')) ->save(); } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $api_url = $form_state->getValue('api_url'); } }
using System; using System.IO; using System.Collections.Generic; using System.Net.Http; using SkiaSharp; using System.Threading.Tasks; namespace CatWorx.BadgeMaker { class Util { public static void PrintEmployees(List<Employee> employees) { for (int i=0 ; i < employees.Count; i++) { string template = "{0,-10}\t{1,-20}\t{2}"; Console.WriteLine(String.Format(template, employees[i].GetId(), employees[i].GetFullName(), employees[i].GetPhotoUrl())); } } public static void MakeCSV(List<Employee> employees) { if (!Directory.Exists("data")) { Directory.CreateDirectory("data"); } // this code block temporarily uses the StreamWriter file using (StreamWriter file = new StreamWriter("data/employees.csv")) { file.WriteLine("ID,Name,PhotoUrl"); // loop over employees for (int i=0; i < employees.Count; i++) { // write each employee to the file string template = "{0},{1},{2}"; file.WriteLine(String.Format(template, employees[i].GetId(), employees[i].GetFullName(), employees[i].GetPhotoUrl())); } } } // will use async/await syntax because the method we use from the HttpClient object is asynchronous // Task is the required return type for an async method that returns no value async public static Task MakeBadges(List<Employee> employees) { int BADGE_WIDTH = 669; int BADGE_HEIGHT = 1044; int PHOTO_LEFT_X = 184; int PHOTO_TOP_Y = 215; int PHOTO_RIGHT_X = 486; int PHOTO_BOTTOM_Y = 517; int COMPANY_NAME_Y = 150; int EMPLOYEE_NAME_Y = 600; int EMPLOYEE_ID_Y = 730; // Import the badge template image file that will work as the background image. // Customize each employee's badge by adding information specific to each employee—namely, the employee's name, picture, and id number. // Add this new image file to the data folder. using(HttpClient client = new HttpClient()) { for (int i=0; i < employees.Count; i++) { // Convert the photo URL into SKImage. SKImage photo = SKImage.FromEncodedData(await client.GetStreamAsync(employees[i].GetPhotoUrl())); // Convert badge template into SKImage. SKImage background = SKImage.FromEncodedData(File.OpenRead("badge.png")); // create the badge canvas SKBitmap badge = new SKBitmap(BADGE_WIDTH, BADGE_HEIGHT); SKCanvas canvas = new SKCanvas(badge); // Place the images onto a canvas. canvas.DrawImage(background, new SKRect(0, 0, BADGE_WIDTH, BADGE_HEIGHT)); canvas.DrawImage(photo, new SKRect(PHOTO_LEFT_X, PHOTO_TOP_Y, PHOTO_RIGHT_X, PHOTO_BOTTOM_Y)); SKPaint paint = new SKPaint(); paint.TextSize = 42.0f; paint.IsAntialias = true; paint.Color = SKColors.White; paint.IsStroke = false; paint.TextAlign = SKTextAlign.Center; paint.Typeface = SKTypeface.FromFamilyName("Arial"); // write the company name // Company name canvas.DrawText(employees[i].GetCompanyName(), BADGE_WIDTH / 2f, COMPANY_NAME_Y, paint); // write the employee name paint.Color = SKColors.Black; canvas.DrawText(employees[i].GetFullName(), BADGE_WIDTH / 2f, EMPLOYEE_NAME_Y, paint); // write the employee id number paint.Typeface = SKTypeface.FromFamilyName("Courier New"); canvas.DrawText(employees[i].GetId().ToString(), BADGE_WIDTH / 2f, EMPLOYEE_ID_Y, paint); // create a new file SKImage finalImage = SKImage.FromBitmap(badge); SKData data = finalImage.Encode(); string template = "data/{0}_badge.png"; data.SaveTo(File.OpenWrite(string.Format(template, employees[i].GetId()))); } } } } }
from rest_framework import viewsets, response, status from .models import Pereval from .serializers import PerevalSerializer # вьюсет для отправки пользователем данных о перевале class SubmitData(viewsets.ModelViewSet): queryset = Pereval.objects.all() serializer_class = PerevalSerializer filterset_fields = ["user__email"] # перепилим функцию create, чтобы ответ был таким, какой нам нужен def create(self, request, *args, **kwargs): serializer = PerevalSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response.Response({ 'status': status.HTTP_200_OK, 'message': 'Отправка успешна', 'id': serializer.data['id'], }) if status.HTTP_400_BAD_REQUEST: return response.Response({ 'status': status.HTTP_400_BAD_REQUEST, 'message': 'Bad Request', 'id': None, }) if status.HTTP_500_INTERNAL_SERVER_ERROR: return response.Response({ 'status': status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': 'Ошибка подключения к базе данных', 'id': None, }) def partial_update(self, request, *args, **kwargs): pereval = self.get_object() # если запись уже не новая if pereval.status != 'new': return response.Response({ 'state': 0, 'message': 'Запись уже ушла на модерацию', }) # если прошла проверку на новизну, то обновляем serializer = PerevalSerializer(pereval, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return response.Response({ 'state': 1, 'message': 'Запись успешно обновлена', }) else: return response.Response({ 'state': 0, 'message': serializer.errors, })
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Mandriva Linux Security Advisory MDVSA-2015:027. # The text itself is copyright (C) Mandriva S.A. # if (NASL_LEVEL < 3000) exit(0); include("compat.inc"); if (description) { script_id(80578); script_version("$Revision: 1.4 $"); script_cvs_date("$Date: 2015/03/05 14:23:33 $"); script_cve_id("CVE-2014-3688", "CVE-2014-6416", "CVE-2014-6417", "CVE-2014-6418", "CVE-2014-7841", "CVE-2014-7842", "CVE-2014-8133", "CVE-2014-8884", "CVE-2014-9090", "CVE-2014-9322", "CVE-2014-9419", "CVE-2014-9420", "CVE-2014-9529", "CVE-2014-9584", "CVE-2014-9585"); script_bugtraq_id(69805, 70393, 70395, 70768, 71078, 71081, 71097, 71250, 71684, 71685, 71717, 71794, 71880, 71883, 71990); script_xref(name:"MDVSA", value:"2015:027"); script_name(english:"Mandriva Linux Security Advisory : kernel (MDVSA-2015:027)"); script_summary(english:"Checks rpm output for the updated packages"); script_set_attribute( attribute:"synopsis", value: "The remote Mandriva Linux host is missing one or more security updates." ); script_set_attribute( attribute:"description", value: "Multiple vulnerabilities has been found and corrected in the Linux kernel : The SCTP implementation in the Linux kernel before 3.17.4 allows remote attackers to cause a denial of service (memory consumption) by triggering a large number of chunks in an association's output queue, as demonstrated by ASCONF probes, related to net/sctp/inqueue.c and net/sctp/sm_statefuns.c (CVE-2014-3688=. Buffer overflow in net/ceph/auth_x.c in Ceph, as used in the Linux kernel before 3.16.3, allows remote attackers to cause a denial of service (memory corruption and panic) or possibly have unspecified other impact via a long unencrypted auth ticket (CVE-2014-6416). net/ceph/auth_x.c in Ceph, as used in the Linux kernel before 3.16.3, does not properly consider the possibility of kmalloc failure, which allows remote attackers to cause a denial of service (system crash) or possibly have unspecified other impact via a long unencrypted auth ticket (CVE-2014-6417). net/ceph/auth_x.c in Ceph, as used in the Linux kernel before 3.16.3, does not properly validate auth replies, which allows remote attackers to cause a denial of service (system crash) or possibly have unspecified other impact via crafted data from the IP address of a Ceph Monitor (CVE-2014-6418). The sctp_process_param function in net/sctp/sm_make_chunk.c in the SCTP implementation in the Linux kernel before 3.17.4, when ASCONF is used, allows remote attackers to cause a denial of service (NULL pointer dereference and system crash) via a malformed INIT chunk (CVE-2014-7841). Race condition in arch/x86/kvm/x86.c in the Linux kernel before 3.17.4 allows guest OS users to cause a denial of service (guest OS crash) via a crafted application that performs an MMIO transaction or a PIO transaction to trigger a guest userspace emulation error report, a similar issue to CVE-2010-5313 (CVE-2014-7842). arch/x86/kernel/tls.c in the Thread Local Storage (TLS) implementation in the Linux kernel through 3.18.1 allows local users to bypass the espfix protection mechanism, and consequently makes it easier for local users to bypass the ASLR protection mechanism, via a crafted application that makes a set_thread_area system call and later reads a 16-bit value (CVE-2014-8133). Stack-based buffer overflow in the ttusbdecfe_dvbs_diseqc_send_master_cmd function in drivers/media/usb/ttusb-dec/ttusbdecfe.c in the Linux kernel before 3.17.4 allows local users to cause a denial of service (system crash) or possibly gain privileges via a large message length in an ioctl call (CVE-2014-8884). The do_double_fault function in arch/x86/kernel/traps.c in the Linux kernel through 3.17.4 does not properly handle faults associated with the Stack Segment (SS) segment register, which allows local users to cause a denial of service (panic) via a modify_ldt system call, as demonstrated by sigreturn_32 in the linux-clock-tests test suite (CVE-2014-9090). arch/x86/kernel/entry_64.S in the Linux kernel before 3.17.5 does not properly handle faults associated with the Stack Segment (SS) segment register, which allows local users to gain privileges by triggering an IRET instruction that leads to access to a GS Base address from the wrong space (CVE-2014-9322). The __switch_to function in arch/x86/kernel/process_64.c in the Linux kernel through 3.18.1 does not ensure that Thread Local Storage (TLS) descriptors are loaded before proceeding with other steps, which makes it easier for local users to bypass the ASLR protection mechanism via a crafted application that reads a TLS base address (CVE-2014-9419). The rock_continue function in fs/isofs/rock.c in the Linux kernel through 3.18.1 does not restrict the number of Rock Ridge continuation entries, which allows local users to cause a denial of service (infinite loop, and system crash or hang) via a crafted iso9660 image (CVE-2014-9420). Race condition in the key_gc_unused_keys function in security/keys/gc.c in the Linux kernel through 3.18.2 allows local users to cause a denial of service (memory corruption or panic) or possibly have unspecified other impact via keyctl commands that trigger access to a key structure member during garbage collection of a key (CVE-2014-9529). The parse_rock_ridge_inode_internal function in fs/isofs/rock.c in the Linux kernel before 3.18.2 does not validate a length value in the Extensions Reference (ER) System Use Field, which allows local users to obtain sensitive information from kernel memory via a crafted iso9660 image (CVE-2014-9584). The vdso_addr function in arch/x86/vdso/vma.c in the Linux kernel through 3.18.2 does not properly choose memory locations for the vDSO area, which makes it easier for local users to bypass the ASLR protection mechanism by guessing a location at the end of a PMD (CVE-2014-9585). The updated packages provides a solution for these security issues." ); script_set_attribute(attribute:"solution", value:"Update the affected packages."); script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:N/I:N/A:C"); script_set_cvss_temporal_vector("CVSS2#E:ND/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:cpupower"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:kernel-firmware"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:kernel-headers"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:kernel-server"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:kernel-server-devel"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:kernel-source"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:lib64cpupower-devel"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:lib64cpupower0"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:mandriva:linux:perf"); script_set_attribute(attribute:"cpe", value:"cpe:/o:mandriva:business_server:1"); script_set_attribute(attribute:"patch_publication_date", value:"2015/01/16"); script_set_attribute(attribute:"plugin_publication_date", value:"2015/01/19"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2015 Tenable Network Security, Inc."); script_family(english:"Mandriva Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/cpu", "Host/Mandrake/release", "Host/Mandrake/rpm-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Mandrake/release")) audit(AUDIT_OS_NOT, "Mandriva / Mandake Linux"); if (!get_kb_item("Host/Mandrake/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); cpu = get_kb_item("Host/cpu"); if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH); if (cpu !~ "^(amd64|i[3-6]86|x86_64)$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "Mandriva / Mandrake Linux", cpu); flag = 0; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"cpupower-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", reference:"kernel-firmware-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"kernel-headers-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"kernel-server-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"kernel-server-devel-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", reference:"kernel-source-3.4.105-2.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"lib64cpupower-devel-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"lib64cpupower0-3.4.105-2.1.mbs1")) flag++; if (rpm_check(release:"MDK-MBS1", cpu:"x86_64", reference:"perf-3.4.105-2.1.mbs1")) flag++; if (flag) { if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get()); else security_hole(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
import React, { Component } from "react"; import Switch from "./switch"; const ToggleContext = React.createContext({ on: false, toggle: () => {} }) export default class Toggle extends Component { static On = ({children}) => ( <ToggleContext.Consumer> {contextValue => (contextValue.on ? children : null)} </ToggleContext.Consumer>) static Off = ({children}) => ( <ToggleContext.Consumer> {contextValue => (contextValue.on ? null : children)} </ToggleContext.Consumer> ) static Button = (props) => ( <ToggleContext.Consumer> {contextValue => (<Switch on={contextValue.on} onClick={contextValue.toggle} {...props} />)} </ToggleContext.Consumer> ) state = { on: false }; toggle = () => { this.setState( ({ on }) => ({ on: !on }), () => { this.props.onToggle(this.state); } ); } render() { return ( <ToggleContext.Provider value={{on: this.state.on, toggle: this.toggle}}> {this.props.children} </ToggleContext.Provider> ) } }
import { IsEmail, IsNotEmpty, IsString, MaxLength, MinLength, } from 'class-validator'; export class CreateUserDTO { @MaxLength(50, { message: 'FullName is too long' }) @IsString() @IsNotEmpty({ message: 'Field cannot be empty' }) fullName: string; @MaxLength(50, { message: 'Email is too long' }) @IsString() @IsEmail({}, { message: 'Email is not valid' }) @IsNotEmpty({ message: 'Field cannot be empty' }) email: string; @MaxLength(50, { message: 'Password is too long' }) @IsString() @MinLength(8, { message: 'Password is too short' }) @IsNotEmpty({ message: 'Field cannot be empty' }) password: string; }
import React,{useContext, useState} from "react"; import Card from "../components/Card"; import { Link } from "react-router-dom"; import {EmojiFrown, SortNumericUp, SortNumericDown } from "react-bootstrap-icons"; import Ctx from "../Ctx"; import Pagination from "../components/Pagination"; import usePagination from "../hooks/usePagination"; export default () => { const {visibleGoods,user,PATH} = useContext(Ctx); const [sortGoods, setSortGoods] = useState(visibleGoods); const paginate = usePagination(sortGoods,9); const [btnType, setBtnType] = useState(""); let st ={ display:"flex", gap:"10px" } const updSort = (e) => { let el = e.currentTarget; let flag = false; if (el.classList.contains("sort")) { el.classList.remove("sort"); setBtnType(""); flag = true; } else { el.classList.add("sort"); setBtnType(el.title); } if (flag) { setSortGoods(visibleGoods); } else { let data = [...visibleGoods]; switch (el.title) { case "down": data.sort((a,b) => a.price - b.price); break; case "up": data.sort((a,b) => b.price - a.price); break; case "new": data = data.filter(d => d.tags.includes("new")); break; case "sale": data = data.filter(d => d.discount > 0); break; } setSortGoods(data); } } return <> {user && <> {visibleGoods.length > 0 ? <> <h1>Каталог товаров</h1> <div style={st}> <button className={`btn sort ${btnType === "up" ? "sort" : ""}`} title="up" onClick={updSort}><SortNumericUp/> Цены</button> <button className={`btn sort ${btnType === "down" ? "sort" : ""}`} title="down" onClick={updSort}><SortNumericDown/> Цены</button> <button className={`btn sort ${btnType === "new" ? "sort" : ""}`} title="new" onClick={updSort}>Новинки</button> <button className={`btn sort ${btnType === "sale" ? "sort" : ""}`} title="sale" onClick={updSort}>Скидка</button> </div> <Pagination hook={paginate}/> <div className="cards"> {paginate.setPageData().map((el, i) => <Link to={`/catalog/${el._id}`} key={el._id} > <Card key={"card_" + i} {...el} /> </Link>)} </div> </> : <div className="err-search"> <EmojiFrown/> <h4 >Простите, по вашему запросу товаров не найдено</h4> <Link to={PATH} className="butn-err">Вернуться на главную страницу</Link> </div> } </>} {!user && <div className="err-search"> <EmojiFrown/> <h4 >Простите, у вас нет доступа к товарам без авторизации</h4> <Link to={PATH} className="butn-err">Вернуться на главную страницу</Link> </div> } </> }
import React from 'react'; import {ROUTE_PATH} from '@/types/other'; import HomePage from '@/pages/HomePage/HomePage'; import HotelPage from '@/pages/HotelPage/HotelPage'; import LoginPage from '@/pages/LoginPage/LoginPage'; import SignupPage from '@/pages/SignupPage/SignupPage'; import ProfilePage from '@/pages/ProfilePage/ProfilePage'; import SearchPage from '@/pages/SearchPage/SearchPage'; import HotelManagePage from '@/pages/HotelManagePage/HotelManagePage'; import ReservationPage from '@/pages/ReservationPage/ReservationPage'; type Route = { path: string; Component: React.FC; }; export const publicRoutesArr : Route[] = [ { path: ROUTE_PATH.HOME, Component: HomePage }, { path: ROUTE_PATH.HOTEL, Component: HotelPage },{ path: ROUTE_PATH.SEARCH, Component: SearchPage } ]; export const privateRoutesArr : Route[] = [ { path: ROUTE_PATH.PROFILE, Component: ProfilePage }, { path: ROUTE_PATH.RESERVE, Component: ReservationPage, } ]; export const authRoutesArr : Route[] = [ { path: ROUTE_PATH.LOGIN, Component: LoginPage }, { path: ROUTE_PATH.SIGNUP, Component: SignupPage } ]; export const ownerRoutesArr: Route[] =[ { path: ROUTE_PATH.MANAGE, Component: HotelManagePage, } ]
/* Topic:- Fibonacci Modified Link:- https://www.hackerrank.com/challenges/fibonacci-modified/problem?isFullScreen=true Problem:- Implement a modified Fibonacci sequence using the following definition: Given terms t[i] and t[i+1] where i ∈ (1,∞), term t[i+2] is computed as: t(i+2) = ti + t(i+2)^2 Given three integers, t1, t2, and n, compute and print the nth term of a modified Fibonacci sequence. Example t1 = 0 t2 =0 n =6 t3 = 0+1^2 = 1 t4 = 1+1^2 = 2 t5 = 1+2^2 = 5 t6 = 2+5^2 = 27 Return 27. Function Description Complete the fibonacciModified function in the editor below. It must return the nth number in the sequence. fibonacciModified has the following parameter(s): int t1: an integer int t2: an integer int n: the iteration to report Returns int: the nth number in the sequence Note: The value of t[n] may far exceed the range of a 64-bit integer. Many submission languages have libraries that can handle such large results but, for those that don't (e.g., C++), you will need to compensate for the size of the result. Input Format A single line of three space-separated integers, the values of t1, t2, and n. Constraints 0 <= t1, t2 <= 2 3 <= n <= 20 tn may far exceed the range of a 64-bit integer. Solution :- */ import java.math.BigInteger; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); BigInteger a = BigInteger.valueOf(in.nextInt()); BigInteger b = BigInteger.valueOf(in.nextInt()); int n = in.nextInt(); for(int i = 2; i < n; i++) { BigInteger next = b.multiply(b).add(a); a = b; b = next; } System.out.println(b); } }
--- title: How To Unlock A Found Apple iPhone 12 mini? | Dr.fone date: 2024-05-19T07:27:54.341Z updated: 2024-05-20T07:27:54.341Z tags: - unlock - remove screen lock categories: - ios - iphone description: This article describes How To Unlock A Found Apple iPhone 12 mini? excerpt: This article describes How To Unlock A Found Apple iPhone 12 mini? keywords: apple id not active,change country on iphone app store,lock stolen iphone,unlock iphone 14,unlock iphone screen passcode,turn off restricted mode,iphone 11 passcode bypass,iphone backup unlocker,iphone auto lock greyed out,ios 17 lock screen thumbnail: https://www.lifewire.com/thmb/-bcmaokZfvwTgJE1q3LjnihDbBY=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-678913139-58a4ece73df78c345bcd781b.jpg --- ## How To Unlock A Found Apple iPhone 12 mini? What to do if you find an iPhone? If you are here, you might have found an iPhone, and now you want to know how to unlock someone's iPhone. Well, you should first try to find the owner, but if you can't find the owner, it's probably because you need help finding information about them. That is why you want to unlock that iPhone. So, in this article, we will teach you how to unlock someone's iPhone with different methods. These methods will be constructive for you to quickly unlock the Apple iPhone 12 mini so you can return it to the rightful owner. So, let's get started. ## 3 Efficient Ways to Unlock a Found iPhone Unlocking an iPhone seems challenging, especially when it's not yours, but it's not impossible. You have various ways to unlock a found iPhone, but most are a waste of time. So, to save time and energy, we have compiled 3 efficient ways to unlock a found iPhone. ![i found an iphone how do i unlock it](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-1.jpg) These methods will be easy to follow because of the detailed step-by-step guide. ### 1.Unlock it from Recovery mode Many people need to realize that you can unlock your Apple iPhone 12 mini in Recovery Mode. This built-in feature of the Apple iPhone 12 mini allows you to turn your device to its factory settings. ![unlock found iphone in recovery mode with itunes](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-2.jpg) But there are two ways to unlock a found iPhone from recovery mode. The old iPhones, like iPhone 5 to iPhone 7 and 7 Plus, can be unlocked from recovery mode differently, and the newer iPhone models have different methods. So, let's discuss both of them in detail. **Unlock iPhone 7 Plus and Older in Recovery Mode** If you want to unlock an iPhone 7 or older model in Recovery Mode, follow these instructions. ![put iphone 7 plus or older in recovery mode](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-3.jpg) 1. First, connect your Apple iPhone 12 mini to the computer with a lightning cable and launch iTunes. 2. Now, turn off your Apple iPhone 12 mini and then press and hold the Home button and Sleep/Wake button simultaneously. Keep holding both buttons until you see the recovery mode screen. 3. Once you see the recovery mode screen, release both buttons. Now, you will see a message in iTunes saying, "There is a problem with the Apple iPhone 12 mini that requires it to be updated or restored." 4. Click on the Update button, and iTunes will try reinstalling iOS erasing your data. Once the process is completed, your Apple iPhone 12 mini will be unlocked. Now, set up your Apple iPhone 12 mini, and you are good to go. **Unlock iPhone 8 and Update Models in Recovery Mode** The process of unlocking an iPhone 8 or newer model differs from the older models. So, follow these instructions if you want to unlock an iPhone 8 or later in Recovery Mode. ![put iphone 8 and newer iphones in recovery mode](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-4.jpg) 1. First, connect your Apple iPhone 12 mini to the computer with a lightning cable and launch iTunes. 2. Now, turn off your Apple iPhone 12 mini and press and quickly release the Volume Up button. After that, press and release the Volume Down button immediately, and hold the Side button until you are in the recovery mode screen. 3. Once you see the recovery mode screen, release the Side button. Now, you will see a message in iTunes that says, "There is a problem with the Apple iPhone 12 mini that requires it to be updated or restored." Or another message that says restore this iPhone. You can click on any option. 4. Click on the Update or Restore button, and iTunes will try reinstalling iOS while also erasing your data. Once the process is completed, your Apple iPhone 12 mini will be unlocked. Now, set up your Apple iPhone 12 mini, and you are good to go. ### 2\. Unlock it via the DNS server If the above method doesn't work or iTunes is not detecting that iPhone, you can follow this method. ![found iphone how to unlock via dns](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-5.jpg) 1. This method is easy to follow and doesn't require any technical skills. 2. All you need is the DNS server IP address. 3. Connect your Apple iPhone 12 mini to the Wi-Fi network and go to Settings -> Wi-Fi. Now, tap the "i" button next to the Wi-Fi network you need to connect to. 4. Scroll down and tap on the Configure DNS option. Now, select the Manual option and enter the DNS server IP address. 5. For US servers, you can use 74.82.42.42 or 208.67.222.222 6. For UK servers, you can use 8.8.8.8 or 8.8.4.4 7. For Canadian servers, you can use 199.85.126.10 or 208.67.222.222 8. For Australian servers, you can use 1.1.1.1 or 208.67.222.222 9. After that, tap the Save button and connect to the Wi-Fi network. Now, open the Safari browser, redirecting you to the activation screen. 10. Follow the instructions on the screen, and your Apple iPhone 12 mini will be unlocked. ### 3\. Dr.Fone-Screen Unlock If none of the above methods can be used for you, there is an ultimate method that will surely help you if you want to unlock a found iPhone. Here are the simple steps that can help you. 1. First, connect your Apple iPhone 12 mini to the computer with a lightning cable and launch Dr.Fone on your computer. ![drfone screen unlock](https://images.wondershare.com/drfone/guide/drfone-home.png) 2. Now, click on the Screen Unlock option from the main interface. 3. After that, click on the iOS Screen Unlock to begin the process. ![unlock found iphone via unlock ios screen](https://images.wondershare.com/drfone/guide/android-screen-unlock-2.png) 4. Now, put your Apple iPhone 12 mini in DFU mode or Recovery mode according to your Apple iPhone 12 mini model. 5. If you have no idea about it, don't worry. The software will provide on-screen instructions to help you put your Apple iPhone 12 mini in DFU mode or Recovery mode. ![dfu mode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) 6. Once your Apple iPhone 12 mini is in DFU mode or Recovery mode, the software will ask you to start downloading the necessary firmware for your device. So, choose an appropriate firmware according to the Apple iPhone 12 mini model. ![unlock ios screen by drfone](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) 7. After downloading the firmware, click the Unlock Now button to begin the unlocking process. ![start unlocking found iphone](https://images.wondershare.com/drfone/guide/unlock-ios-screen-6.png) 8. Once the process is completed, your Apple iPhone 12 mini will be unlocked, and you can set it up again. ![unlock ios screen](https://images.wondershare.com/drfone/guide/unlock-ios-screen-9.png) So that's how you can easily unlock a found iPhone. This method has been tested, and it will surely work for you. So, if you have an iPhone that is locked or disabled, you can use this method to unlock it without any problem. ## What Can I Do to Contact Its Owner? Once the found iPhone is successfully unlocked, you can contact its owner in many ways. Following are some of them that work. ### Contact the owner with the phone number in lost mode Many iPhone owners habitually put their phone numbers in lost mode. So, you can check if any phone number is available in the lost mode. If a phone number is available, you can contact the owner and return the Apple iPhone 12 mini to them. ![contact the owner with the phone number in lost mode](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-6.jpg) The rightful owner of the Apple iPhone 12 mini activates lost mode. You can see the lost mode on the notification panel, where a message will show that the phone is lost. The owner can also remotely lock the phone using this mode. ### Check medical ID in an emergency call There is a feature in the Apple iPhone 12 mini known as medical ID. This feature can help you contact the owner of the found iPhone if they are unavailable. ![contact the owner with the help of emergency medical id](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-7.jpg) To do this, go to the emergency call screen and tap on the Medical ID option. Here, you can find out the name and phone number of the owner. So, you can use this information to contact the owner and return the iPhone. ### Take photos to communicate with the owner via iCloud This is a great way to contact the owner of a lost iPhone. You can use this method if you cannot find the owner's phone number in the lost mode or medical ID. ![contact the owner with the picloud share photo library](https://images.wondershare.com/drfone/article/2022/11/i-found-an-iphone-how-do-i-unlock-it-8.jpg) To do this, go to Settings -> iCloud -> Photos and turn on the iCloud Photo Library. Now, take some pictures with the found iPhone, and they will be automatically uploaded to iCloud. Most people who have lost their iPhones often check their iCloud, and once they find out that someone is taking pictures and uploading them to their iCloud, they will try to communicate with you. And that's how you can also communicate with them and ask for contact details so that you can return their phone and be a good citizen. ### The Bottom Line So, that's how you can unlock a found iPhone and contact its owner. I hope this article will help you find the lost iPhone owner and return it to them. All the methods mentioned above have a high success ratio, but the last ultimate method is better than all because it will unlock the Apple iPhone 12 mini within minutes. Dr.Fone-Screen Unlock is one of the most effective ways can help you to unlock a found iPhone. This method has been tested, and it will surely work for you. So, if you have an iPhone that is locked or disabled, you can use this method to unlock it without any problem. ## Easy Steps on How To Create a New Apple ID Account On Apple iPhone 12 mini Your Apple ID is your gateway to a world of apps and services, making it an essential part of your Apple experience. Whether you're a new Apple user or simply looking to start fresh, **creating a new Apple ID** can open the doors to endless possibilities. This guide will walk you through creating a new account for Apple devices in an easy-to-understand manner. From setting up your email address to securing your account, this article covered you every step of the way. Embark on this journey and learn **how to create a new Apple ID account** effortlessly. ![create a free apple id](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-01.jpg) ## Part 1: Why Create a New Apple ID? You might need to create a new Apple ID to enhance your Apple experience. Let's dive into why it's a good idea: ### A. Reasons for Creating a New Apple ID Account Here's a breakdown of the reasons why you should **create a new Apple ID for your Apple iPhone 12 mini**: - Your Apple ID is like your digital identity. Creating a new one lets you choose a unique email address that suits you, adding a personal touch to your Apple journey. - Maybe you've been using an email for your Apple ID that you don't want to use anymore. Creating a new one helps keep your personal and Apple-related emails separate. - **Switching Devices.**When you switch to a new Apple device, like getting a new iPhone or iPad, creating a unique Apple ID ensures a fresh start tailored to your new gadget. - **Separation of Accounts.**Sometimes, you may want to keep your work-related apps and data separate from your ones. Creating a new Apple ID helps you achieve this separation. - If you're using Apple services for different purposes, such as work and personal use, having separate Apple IDs can help keep everything organized and distinct. ![create a free apple id account](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-02.jpg) ### B. Scenarios Where a New ID Is Needed Below are the common scenarios where a new Apple ID might be needed: - **New Apple Device.**When you purchase a new Apple device, like an iPhone or iPad, you'll need a new Apple ID to set it up and make it truly yours. - **Shared Device.**If multiple people use the same device, creating a new Apple ID for each user ensures that everyone has their own personalized experience. - **Change of Email.**If your current email address associated with your Apple ID is changed or you prefer a new one, creating a unique Apple ID with the updated email is the solution. - **Work and Personal.**To keep your work-related apps and data separate from your personal ones, having separate Apple IDs for each purpose is practical and organized. - **Starting Fresh.**Sometimes, you might want a fresh start with your Apple experience, and creating a new Apple ID provides a clean slate. **Creating a new Apple ID** isn't just about getting a new email; it's about tailoring your Apple experience to your needs, whether for personalization, privacy, or organization. Now that you know why it's essential, let's explore how to create it in the next section. ## Part 2: Step-by-Step Guide: How To Create a New Apple ID Account **Creating a new Apple ID for free** is a straightforward process. Let's break it down into simple steps: ### A. Registering a New Apple ID These are the steps for registering a new Apple ID: - **Step 1:** Open your web browser and visit the [<u>Apple ID account management page</u>](http://appleid.apple.com/). Click the **Create Your Apple ID** button to begin. ![apple id account management page](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-03.jpg) - **Step 2:** On the registration page, you'll be asked to provide your **First name** and **Last name**. Make sure to use the name associated with your new Apple ID. Next, you'll need to enter your preferred email address. This one will be your new Apple ID. **Tip:** Choose an email that's easy to remember and access. ![create your apple id step 1](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-04.jpg) - **Step 3:** Create a strong password that combines letters, numbers, and symbols. This password is essential for the security of your account, so make it unique and hard to guess. Confirm your password by entering it again in the designated field. ### B. Verifying Your Identity The next step is verifying your identity. Check out the steps below: - **Step 4:** Apple takes your security seriously. You may be asked to provide a phone number to verify your identity. This number can be used for account recovery or two-factor authentication. The phone number you provided will receive a verification code. Enter this code in the space provided to confirm your identity. **Note:** It's crucial to ensure that your phone number is accurate and accessible. This number will help you recover your account in case you forget your password or encounter any issues. Apple may use this phone number for two-factor authentication, adding an extra layer of security to your account. ![create your apple id step 2](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-05.jpg) - **Step 5:** Apple may sometimes ask you to complete a **CAPTCHA** or verify your identity to prevent automated account creation. ### C. Setting Up Security Questions The next process will be setting up security questions for your account: - **Step 6:** Apple asks you to choose and answer security questions. These questions provide an additional layer of protection for your account. Select questions that you can easily remember and that others can't guess. ### D. Finalizing the Process To finalize the creation process, refer to the steps given below: - **Step 7:** Read through Apple's Terms and Conditions and Privacy Policy. Once you've understood them, tick the box to confirm that you've read and agree to the iCloud and Apple Media Services Terms and Conditions. Then click **Agree** to proceed. Remember that it's essential to be familiar with Apple's policies to ensure a secure and smooth experience. ![create your apple id step 3](https://images.wondershare.com/drfone/article/2023/10/create-new-apple-id-account-06.jpg) - **Step 8:** After completing these steps, Apple will send a confirmation email to the address you provided. Go to your email and open the verification link to confirm your new Apple ID. Congratulations! You've successfully **created a new Apple ID**. With this account, you can now access Apple's services, including the App Store, iCloud, and more. Remember to keep your login credentials secure and use them to personalize your Apple experience fully. ## Part 3: Effortlessly Remove Your Apple ID Using [<u>Wondershare Dr.Fone - Screen Unlock (iOS)</u>](https://drfone.wondershare.com/guide/ios-unlock.html) You can embark on an enhanced Apple experience after successfully **creating your new Apple ID**. Removing the previous one is essential when you create it, especially if you've acquired a second-hand device or no longer want the previous user's associated credentials. This step ensures that your new Apple ID takes center stage, granting you full control over your device and its associated services. But if you encounter difficulties when removing the previous Apple ID from your device, Dr.Fone - Screen Unlock (iOS) is a reliable and user-friendly solution. ![drfone unlock ios screen](https://images.wondershare.com/drfone/guide/remove-apple-id-1.png) ### Key Features of Dr.Fone - Screen Unlock (iOS) This versatile tool offers the following key features in the context of Apple ID issues: - **User-Friendly Interface.**Fone - Screen Unlock (iOS) is designed to be straightforward, making it accessible to users of all levels of technical expertise. - It is usable with a wide range of iOS devices, ensuring you can [<u>remove the previous Apple ID from your device</u>](https://drfone.wondershare.com/apple-account/how-to-remove-apple-id-from-iphone-without-password.html), regardless of the model. - **Multiple Unlock Modes.**Fone offers various unlock modes to cater to different scenarios, including removing the previous Apple ID. This flexibility ensures that you have the right solution for your specific situation. - **Data Security.**Fone - Screen Unlock (iOS) prioritizes data security, ensuring that your personal information and content remain intact during the Apple ID removal process. ### Step-by-Step Guide on Using Dr.Fone Screen Unlock (iOS) Check out the steps on how to remove an Apple ID account using Dr.Fone below: - **Step 1:** Launch Wondershare Dr.Fone on your PC to use the **Screen Unlock** function and then navigate to **Toolbox**. Click the **Screen Unlock** section, then choose **iOS**. ![drfone v13 homepage](https://images.wondershare.com/drfone/guide/drfone-home.png) - **Step 2:** If you want to proceed with deleting your Apple ID, you'll need to go to the next window and select the **Remove AppleID** option from the menu. - **Step 3:** When you hook up your iOS device to a computer, the next screen will report on its connectivity. Select the **Unlock Now** button to proceed. ![remove apple id unlock now](https://images.wondershare.com/drfone/guide/remove-apple-id-2.png) - **Step 4:** Before the Apple ID can be unlocked, the next step is for the platform to ask a series of questions. Verify that a screen lock is active on your iOS device. However, please lock your iOS device before proceeding with the **Yes** option. ![set up screen lock](https://images.wondershare.com/drfone/guide/remove-apple-id-3.png) - **Step 5:** Check if **Two-Factor Authentication** is set up on all your iOS devices. If not, switch it on before confirming your decision to unlock your Apple ID. ![confirm two-factor authentication](https://images.wondershare.com/drfone/guide/remove-apple-id-4.png) - **Step 6:** After you have confirmed these settings, you will be taken to a screen with on-screen instructions for entering **Recovery Mode** on your iDevice. If the steps for your specific iOS device don't work, try tapping **Try DFU Mode** in the app's bottom left corner. To continue with the unlocking process, this will [<u>launch the DFU Mode</u>](https://drfone.wondershare.com/dfu-mode/tools-for-iphone-to-enter-dfu-mode.html) instructions. ![try dfu mode](https://images.wondershare.com/drfone/guide/remove-apple-id-5.png) - **Step 7:** Once **Recovery Mode** has been activated, the Apple iPhone 12 mini device's information will be shown on the subsequent screen. Once the **Device Model** has been identified, all that remains is to choose the appropriate **System Version** and click **Start**. However, if there are disagreements in recognition, pick the details by hand and move forward. ![choose device model](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) - **Step 8:** The appropriate iOS firmware begins downloading, showing its status on the following screen. Click the **Copy** button to copy the direct URL to [<u>download iOS firmware</u>](https://drfone.wondershare.com/ios-upgrade/how-to-upgrade-with-firmware-files.html) for systems with sluggish firmware download speeds. - **Step 9:** The platform checks the downloaded firmware and displays its details on the following screen. To proceed with unlocking your Apple ID, click the **Unlock Now** button. To proceed, you will be prompted to input a code into a confirmation window. Enter the code and then click the **Unlock** button. ![firmware complete](https://images.wondershare.com/drfone/guide/remove-apple-id-6.png) - **Step 10:** The following screen shows the unlocking status of your Apple ID. Don't let the Apple iPhone 12 mini device lose its connection under any circumstances. The screen prompts the process of completing the Apple ID once the ID has been unlocked. If the Apple ID has been unlocked, click **Done** to proceed. If that fails, click the **Try Again** button and give it another shot. ![apple id completely unlocked](https://images.wondershare.com/drfone/guide/remove-apple-id-8.png) ## Conclusion This guide has simplified the process of **creating a new Apple ID**, ensuring you can effortlessly personalize, secure, and organize your digital experience. **Creating a new Apple ID** is easy, and it allows you to tailor your Apple journey to your preferences. Remember, it's all about you, your privacy, and your convenience. Should you encounter any challenges while managing your Apple ID, such as removing a previous one, consider Dr.Fone - iOS Screen Unlock tool. This user-friendly resource stands ready to assist, ensuring a seamless and secure Apple experience. Explore the possibilities and make the most of your Apple adventure! ## What Does Jailbreaking Apple iPhone 12 mini i Do? Get Answers here Jailbreaking grants you root access to your smartphone, opening a range of features and functionalities. But **what does jailbreaking an iPhone do**? Jailbreaking your Apple iPhone 12 mini removes the restrictions imposed by Apple on its operating system, iOS. It offers more customization options and access to extra apps. However, is jailbreaking an iPhone safe and legal? It's a complex answer and not a decision to take lightly. While the process is legal in most countries, its applications can cross legal lines, like installing pirated apps. To learn more, read on and explore the capabilities of a jailbroken iPhone in the following sections. This article will also touch on its impact on [<u>iCloud Activation Lock</u>](https://drfone.wondershare.com/icloud/bypass-iphone-11-12-icloud-activation-lock.html). Let's start with the benefits and risks of jailbreaking your Apple iPhone 12 mini. ![iphone devices back view](https://images.wondershare.com/drfone/article/2024/01/what-does-jailbreaking-an-iphone-do-01.jpg) ## Part 1: What Does Jailbreaking an iPhone Do? Before trying to jailbreak your Apple iPhone 12 mini, it's crucial to understand, "**What can you do with a jailbroken iPhone**?" While it opens up exciting possibilities, it also introduces potential drawbacks. In this section, you'll learn both aspects. Benefits of Jailbreaking Apple's App Store and iOS offer a curated selection of features and functionalities. But for some users, this can feel restrictive. Here are some advantages of jailbreaking your Apple iPhone 12 mini: - **Install Unapproved Apps** Apple's App Store has strict guidelines limiting the type of apps available. Jailbreaking offers various third-party apps and tweaks not available on the App Store. These could include emulators, screen recorders, or apps that bypass certain limitations. - **Increased Customization Options** Users can customize their iPhones beyond the limitations imposed by Apple after Jailbreaking. It includes changing themes, icons, and even the look and feel of the user interface. This level of personalization can enhance your experience while using your iOS device. ![circleapps launcher tweak for jailbroken iphone](https://images.wondershare.com/drfone/article/2024/01/what-does-jailbreaking-an-iphone-do-02.jpg) - **Unlocking System-wide Features** Jailbreaking unlocks extra iPhone features. It lets you access advanced settings and functions. These aren't in the regular, non-jailbroken mode. More control means more customization. You can optimize your Apple iPhone 12 mini based on your preferences. - **Unlocking Network Restrictions** Jailbreaking frees the Apple iPhone 12 mini from carrier restrictions. You can then use it with different network providers. This is handy for travelers or those wanting better service options. However, these benefits come with caveats you should consider. Risks of Jailbreaking While jailbreaking itself isn't illegal, it does involve bypassing Apple's security measures. This increased freedom comes with its own set of potential pitfalls. Here are some potential downsides of jailbreaking your Apple iPhone 12 mini: - **Security Vulnerabilities** Bypassing Apple's security measures can expose your device to vulnerabilities. Malicious apps or tweaks can exploit these vulnerabilities, risking your data and privacy. It could lead to the theft of your data, including passwords, financial information, and photos. - **Voided Warranty** Jailbreaking is seen by Apple as a device modification. Doing so can void your device warranty. So, if jailbreaking causes any issues, Apple won't cover them under their support services—both hardware and software. - **Instability and Performance Issues** Jailbreaking may make your system unstable and cause performance problems. When you add unauthorized tweaks or apps, they can clash with iOS. This clash might result in [<u>crashes</u>](https://drfone.wondershare.com/iphone-problems/iphone-apps-crashing-on-ios-13.html), [<u>freezes</u>](https://drfone.wondershare.com/android-issue/fix-samsung-freeze.html), or a general drop in your Apple iPhone 12 mini's performance. ![iphone apps crashing message](https://images.wondershare.com/drfone/article/2024/01/what-does-jailbreaking-an-iphone-do-03.jpg) - **Difficulty in Updating** Jailbreaking may cause problems with new iOS updates. When Apple releases updates, jailbreak developers might take time to catch up. This delay can leave you without access to the latest features and security patches. - **Bricking Risk** Incorrect jailbreaking can "[<u>brick</u>](https://drfone.wondershare.com/iphone-problems/how-to-fix-bricked-iphone.html)" your Apple iPhone 12 mini, making it unusable. This risk goes up if you try it without enough knowledge or with unreliable tools. ## Part 2: What Can Jailbreak iPhone Do to iCloud Activation Lock? Jailbreaking an iPhone won't remove the iCloud Activation Lock, contrary to a common misconception. While jailbreaking provides extensive control over your device's system, it is not synonymous with bypassing iCloud Activation Lock. These are distinct concepts. Here's how they differ: - **Jailbreak** **If you jailbreak your Apple iPhone 12 mini, what happens** is you have root access to the iOS system. It opens customization and functionality beyond what is available. - **iCloud Activation Lock** iCloud Activation Lock is a security feature that ties an Apple iPhone 12 mini to the Apple ID used to set it up. If lost or stolen, it prevents unauthorized use even after a factory reset. ![icloud activation lock on an iphone](https://images.wondershare.com/drfone/article/2024/01/what-does-jailbreaking-an-iphone-do-04.jpg) While jailbreaking grants you deeper access to the system, it can't override or bypass the iCloud Activation Lock directly. However, third-party tools that can bypass iCloud activation lock use this access. These software, such as [<u>Wondershare Dr.Fone</u>](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/), leverage the jailbreak to access crucial system files and implement their bypass methods. ## Part 3: Easily Bypass iCloud Activation Lock Without Password Security risks? Warranty void? These are valid concerns when considering "**What does it mean to jailbreak an iPhone**?" Not only that, but if you jailbreak your Apple iPhone 12 mini and face issues, you may need the Apple ID and password for access. Retrieving them is easy with known iCloud credentials. But reactivation becomes challenging if you've forgotten or bought a used iOS device without the previous owner's details. To solve this, you can use software to bypass the Activation Lock on your Apple iPhone 12 mini. Several tools in the market can do it, and Wondershare Dr.Fone is a standout option. It's user-friendly, compatible with the latest iOS devices, and boasts an intuitive interface. Here are some things Dr.Fone - Screen Unlock tool can offer: - Can remove all types of locked screen - [<u>Remove SIM lock</u>](https://drfone.wondershare.com/sim-unlock/android-sim-unlock-code-generator.html)/ unlock iPhone carrier without losing data - Unlock Apple ID without a password - [<u>Bypass MDM without data loss</u>](https://drfone.wondershare.com/unlock/mdm-bypass-free.html) - Remove iTunes backup encryption Dr.Fone uses the responsible path of jailbreaking your iOS device, giving you back control. Now, let's walk through a step-by-step guide on how to bypass the iCloud Activation Lock using Dr.Fone - Screen Unlock (iOS): - **Step 1:** Download Dr.Fone and set up the software on your computer. - **Step 2:** Open the program and select **Screen Unlock** from the available options on the **Toolbox** page. ![dr.fone toolbox homepage](https://images.wondershare.com/drfone/guide/drfone-home.png) - **Step 3:** Choose **iOS** as your device type, then select **iCloud Activation Lock Removal** on the next window. ![dr.fone screen unlock tools](https://images.wondershare.com/drfone/guide/bypass-activation-lock-1.png) - **Step 4:** Click **Start** to initiate the bypass process. ![start to bypass activation lock](https://images.wondershare.com/drfone/guide/bypass-activation-lock-2.png) - **Step 5:** Use a USB cable to connect your Apple iPhone 12 mini to the computer. Ensure the software detects your device. ![in-app instructions to connect iphone](https://images.wondershare.com/drfone/guide/screen-unlock-2.png) - **Step 6:** Check your Apple iPhone 12 mini settings for a displayed MEID or ESN number to identify CDMA network support. If an IMEI number is present, the Apple iPhone 12 mini device supports GSM networks. The findings indicate support for both GSM and CDMA networks. Click **Unlock Now** to proceed. ![dr.fone unlock icloud activation lock](https://images.wondershare.com/drfone/guide/bypass-activation-lock-4.png) ****Note:******For GSM devices, removing the iCloud Activation Lock doesn't disrupt normal functioning. Conversely, for CDMA devices, calling features may be disabled. However, the Apple ID remains usable for essential functions like App Store access.** - **Step 7:** Dr.Fone will check if your device needs to be jailbroken. If it does, follow the on-screen instructions to jailbreak it. ![jailbreak iphone notice dialogue box](https://images.wondershare.com/drfone/guide/bypass-activation-lock-7.png) - **Step 8:** Allow the software to complete the bypass process. Once done, your Apple iPhone 12 mini will be successfully unlocked from the iCloud Activation Lock without a password. ![dr.fone bypass icloud activation lock](https://images.wondershare.com/drfone/guide/bypass-activation-lock-9.png) ## Part 4: Other Way To Remove iCloud Activation Lock Without Jailbreak If you're the rightful owner of the iPhone, the safest and most legitimate way to bypass the Activation Lock is to remove the associated Apple ID from the Apple iPhone 12 mini device. Here's how to remove iCloud Activation lock on the web without jailbreaking your Apple iPhone 12 mini: - **Step 1:** Go to appleid.apple.com, then sign in with your Apple ID and password. - **Step 2:** Select the Apple iPhone 12 mini device you want to remove the Activation Lock from, then click **Remove from account**. ![remove device from icloud account](https://images.wondershare.com/drfone/article/2024/01/what-does-jailbreaking-an-iphone-do-12.jpg) - **Step 3:** Confirm that you want to remove the Apple iPhone 12 mini device. ****Note:******If you're still having trouble removing Activation Lock, you can contact Apple Support for help**__.__ ## Conclusion With the question "**What does jailbreaking an iPhone do**?" answered, it's time to weigh the pros and cons. Jailbreaking an iPhone means bypassing restrictions for more functions and unauthorized apps. Although it provides customization and extra features, it poses risks. Jailbreaking your Apple iPhone 12 mini weakens its iOS security, possibly exposing your device to malware. If you plan to remove iCloud Activation Lock, use trustworthy tools like Dr.Fone. Weighing the benefits of jailbreaking against the potential downsides is crucial. Remember, customizing your Apple iPhone 12 mini comes at the cost of your device's security and stability. _**Tips:** Are you searching for a powerful Screen Unlock tool? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_ <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://iphone-unlock.techidaily.com/how-to-bypass-the-required-apple-store-verification-for-iphone-13-mini-drfone-by-drfone-ios/"><u>How To Bypass the Required Apple Store Verification For iPhone 13 mini | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/different-methods-to-unlock-your-apple-iphone-14-pro-max-drfone-by-drfone-ios/"><u>Different Methods To Unlock Your Apple iPhone 14 Pro Max | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-iphone-14-pro-max-drfone-by-drfone-ios/"><u>How to Unlock iPhone 14 Pro Max? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-different-methods-to-unlock-your-iphone-8-drfone-by-drfone-ios/"><u>In 2024, Different Methods To Unlock Your iPhone 8 | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-apple-iphone-15-plus-passcode-without-itunes-without-knowing-passcode-drfone-by-drfone-ios/"><u>How to Unlock Apple iPhone 15 Plus Passcode without iTunes without Knowing Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-disabling-iphone-15-pro-max-parental-restrictions-withwithout-password-drfone-by-drfone-ios/"><u>In 2024, Disabling iPhone 15 Pro Max Parental Restrictions With/Without Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/3-ways-to-unlock-iphone-13-mini-without-passcode-or-face-id-drfone-by-drfone-ios/"><u>3 Ways to Unlock iPhone 13 mini without Passcode or Face ID | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-apple-iphone-13-pro-max-without-passcode-4-easy-methods-drfone-by-drfone-ios/"><u>How To Unlock Apple iPhone 13 Pro Max Without Passcode? 4 Easy Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-your-apple-id-on-apple-iphone-13-mini-with-or-without-password-drfone-by-drfone-ios/"><u>How To Change Your Apple ID on Apple iPhone 13 mini With or Without Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/unlock-your-disabled-iphone-se-2020-without-itunes-in-5-ways-drfone-by-drfone-ios/"><u>Unlock Your Disabled iPhone SE (2020) Without iTunes in 5 Ways | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-stolen-apple-iphone-6-plus-in-different-conditionsin-drfone-by-drfone-ios/"><u>In 2024, How To Unlock Stolen Apple iPhone 6 Plus In Different Conditionsin | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-iphone-14-plus-with-an-apple-watch-and-what-to-do-if-it-doesnt-work-drfone-by-drfone-ios/"><u>In 2024, How to Unlock iPhone 14 Plus With an Apple Watch & What to Do if It Doesnt Work | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-iphone-11-without-swiping-up-6-ways-drfone-by-drfone-ios/"><u>In 2024, How To Unlock iPhone 11 Without Swiping Up? 6 Ways | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-country-on-app-store-for-iphone-14-pro-max-with-7-methods-drfone-by-drfone-ios/"><u>How To Change Country on App Store for iPhone 14 Pro Max With 7 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/forgot-apple-iphone-12-pro-backup-password-heres-what-to-do-drfone-by-drfone-ios/"><u>Forgot Apple iPhone 12 Pro Backup Password? Heres What to Do | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-locked-out-of-iphone-11-pro-5-ways-to-get-into-a-locked-iphone-11-pro-drfone-by-drfone-ios/"><u>In 2024, Locked Out of iPhone 11 Pro? 5 Ways to get into a Locked iPhone 11 Pro | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-reset-itunes-backup-password-of-apple-iphone-8-prevention-and-solution-drfone-by-drfone-ios/"><u>In 2024, Reset iTunes Backup Password Of Apple iPhone 8 Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-unlock-apple-iphone-12-mini-drfone-by-drfone-ios/"><u>How to Unlock Apple iPhone 12 mini? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-a-comprehensive-guide-to-apple-iphone-xs-blacklist-removal-tips-and-tools-drfone-by-drfone-ios/"><u>In 2024, A Comprehensive Guide to Apple iPhone XS Blacklist Removal Tips and Tools | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-can-i-unlock-my-apple-iphone-11-pro-after-forgetting-my-pin-code-drfone-by-drfone-ios/"><u>In 2024, How Can I Unlock My Apple iPhone 11 Pro After Forgetting my PIN Code? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-different-methods-to-unlock-your-apple-iphone-15-pro-drfone-by-drfone-ios/"><u>In 2024, Different Methods To Unlock Your Apple iPhone 15 Pro | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-remove-flashlight-from-apple-iphone-15-plus-lock-screen-drfone-by-drfone-ios/"><u>How To Remove Flashlight From Apple iPhone 15 Plus Lock Screen | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-remove-flashlight-from-apple-iphone-15-pro-max-lock-screen-drfone-by-drfone-ios/"><u>In 2024, How To Remove Flashlight From Apple iPhone 15 Pro Max Lock Screen | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-locked-out-of-apple-iphone-8-plus-5-ways-to-get-into-a-locked-apple-iphone-8-plus-drfone-by-drfone-ios/"><u>In 2024, Locked Out of Apple iPhone 8 Plus? 5 Ways to get into a Locked Apple iPhone 8 Plus | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/forgot-locked-iphone-13-mini-password-learn-the-best-methods-to-unlock-drfone-by-drfone-ios/"><u>Forgot Locked iPhone 13 mini Password? Learn the Best Methods To Unlock | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/what-does-jailbreaking-apple-iphone-6s-i-do-get-answers-here-drfone-by-drfone-ios/"><u>What Does Jailbreaking Apple iPhone 6s i Do? Get Answers here | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-what-does-jailbreaking-apple-iphone-13-mini-i-do-get-answers-here-drfone-by-drfone-ios/"><u>In 2024, What Does Jailbreaking Apple iPhone 13 mini i Do? Get Answers here | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-stolen-iphone-15-pro-in-different-conditionsin-drfone-by-drfone-ios/"><u>In 2024, How To Unlock Stolen iPhone 15 Pro In Different Conditionsin | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-unlock-apple-iphone-14-plus-without-passcode-or-face-id-drfone-by-drfone-ios/"><u>In 2024, How to Unlock Apple iPhone 14 Plus without Passcode or Face ID | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-forgot-locked-iphone-xr-password-learn-the-best-methods-to-unlock-drfone-by-drfone-ios/"><u>In 2024, Forgot Locked iPhone XR Password? Learn the Best Methods To Unlock | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-8-safe-and-effective-methods-to-unlock-your-iphone-14-pro-without-a-passcode-drfone-by-drfone-ios/"><u>In 2024, 8 Safe and Effective Methods to Unlock Your iPhone 14 Pro Without a Passcode | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-complete-guide-on-unlocking-iphone-xs-max-with-a-broken-screen-drfone-by-drfone-ios/"><u>In 2024, Complete Guide on Unlocking iPhone XS Max with a Broken Screen? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/guide-on-how-to-change-your-apple-id-email-address-on-iphone-13-pro-drfone-by-drfone-ios/"><u>Guide on How To Change Your Apple ID Email Address On iPhone 13 Pro | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-locked-out-of-apple-iphone-se-2022-5-ways-to-get-into-a-locked-apple-iphone-se-2022-drfone-by-drfone-ios/"><u>In 2024, Locked Out of Apple iPhone SE (2022)? 5 Ways to get into a Locked Apple iPhone SE (2022) | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-how-to-access-your-iphone-15-plus-when-you-forget-the-passcode-drfone-by-drfone-ios/"><u>In 2024, How to Access Your iPhone 15 Plus When You Forget the Passcode? | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/passfab-apple-iphone-14-backup-unlocker-top-4-alternatives-drfone-by-drfone-ios/"><u>PassFab Apple iPhone 14 Backup Unlocker Top 4 Alternatives | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-fix-apple-iphone-14-plus-unavailable-issue-with-ease-drfone-by-drfone-ios/"><u>How To Fix Apple iPhone 14 Plus Unavailable Issue With Ease | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-country-on-app-store-for-iphone-6s-plus-with-7-methods-drfone-by-drfone-ios/"><u>How To Change Country on App Store for iPhone 6s Plus With 7 Methods | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-reset-itunes-backup-password-of-apple-iphone-14-pro-prevention-and-solution-drfone-by-drfone-ios/"><u>In 2024, Reset iTunes Backup Password Of Apple iPhone 14 Pro Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/reset-itunes-backup-password-of-iphone-12-pro-max-prevention-and-solution-drfone-by-drfone-ios/"><u>Reset iTunes Backup Password Of iPhone 12 Pro Max Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/how-to-change-your-apple-id-on-apple-iphone-8-with-or-without-password-drfone-by-drfone-ios/"><u>How To Change Your Apple ID on Apple iPhone 8 With or Without Password | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/4-ways-to-unlock-apple-iphone-11-pro-max-to-use-usb-accessories-without-passcode-drfone-by-drfone-ios/"><u>4 Ways to Unlock Apple iPhone 11 Pro Max to Use USB Accessories Without Passcode | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-things-you-should-know-when-unlocking-total-wireless-of-apple-iphone-13-mini-drfone-by-drfone-ios/"><u>In 2024, Things You Should Know When Unlocking Total Wireless Of Apple iPhone 13 mini | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/reset-itunes-backup-password-of-apple-iphone-14-pro-prevention-and-solution-drfone-by-drfone-ios/"><u>Reset iTunes Backup Password Of Apple iPhone 14 Pro Prevention & Solution | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-unlock-your-disabled-iphone-13-mini-without-itunes-in-5-ways-drfone-by-drfone-ios/"><u>In 2024, Unlock Your Disabled iPhone 13 mini Without iTunes in 5 Ways | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-what-does-jailbreaking-iphone-11-pro-i-do-get-answers-here-drfone-by-drfone-ios/"><u>In 2024, What Does Jailbreaking iPhone 11 Pro i Do? Get Answers here | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-iphone-is-disabled-here-is-the-way-to-unlock-disabled-apple-iphone-xr-drfone-by-drfone-ios/"><u>In 2024, iPhone Is Disabled? Here Is The Way To Unlock Disabled Apple iPhone XR | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-3-easy-ways-to-factory-reset-a-locked-iphone-14-plus-without-itunes-drfone-by-drfone-ios/"><u>In 2024, 3 Easy Ways to Factory Reset a Locked iPhone 14 Plus Without iTunes | Dr.fone</u></a></li> <li><a href="https://iphone-unlock.techidaily.com/in-2024-the-best-methods-to-unlock-the-iphone-locked-to-owner-for-apple-iphone-13-mini-drfone-by-drfone-ios/"><u>In 2024, The Best Methods to Unlock the iPhone Locked to Owner for Apple iPhone 13 mini | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/3-solutions-to-find-your-oneplus-nord-n30-5g-current-location-of-a-mobile-number-drfone-by-drfone-virtual-android/"><u>3 Solutions to Find Your OnePlus Nord N30 5G Current Location of a Mobile Number | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/recover-iphone-12-mini-data-from-icloud-drfone-by-drfone-ios-data-recovery-ios-data-recovery/"><u>Recover iPhone 12 mini Data From iCloud | Dr.fone</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/new-free-online-face-makers-top-picks/"><u>New Free Online Face Makers Top Picks</u></a></li> <li><a href="https://screen-mirror.techidaily.com/a-guide-honor-magic-vs-2-wireless-and-wired-screen-mirroring-drfone-by-drfone-android/"><u>A Guide Honor Magic Vs 2 Wireless and Wired Screen Mirroring | Dr.fone</u></a></li> <li><a href="https://change-location.techidaily.com/in-2024-ultimate-guide-to-catch-the-regional-located-pokemon-for-vivo-x-fold-2-drfone-by-drfone-virtual-android/"><u>In 2024, Ultimate Guide to Catch the Regional-Located Pokemon For Vivo X Fold 2 | Dr.fone</u></a></li> <li><a href="https://techidaily.com/how-to-transfer-data-from-apple-iphone-11-to-other-iphone-devices-drfone-by-drfone-transfer-data-from-ios-transfer-data-from-ios/"><u>How To Transfer Data From Apple iPhone 11 To Other iPhone devices? | Dr.fone</u></a></li> <li><a href="https://location-fake.techidaily.com/3utools-virtual-location-not-working-on-realme-11-5g-fix-now-drfone-by-drfone-virtual-android/"><u>3uTools Virtual Location Not Working On Realme 11 5G? Fix Now | Dr.fone</u></a></li> <li><a href="https://ios-unlock.techidaily.com/in-2024-unlock-apple-iphone-12-without-passcode-easily-by-drfone-ios/"><u>In 2024, Unlock Apple iPhone 12 Without Passcode Easily</u></a></li> <li><a href="https://location-fake.techidaily.com/11-best-location-changers-for-motorola-moto-g04-drfone-by-drfone-virtual-android/"><u>11 Best Location Changers for Motorola Moto G04 | Dr.fone</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-forgotten-the-voicemail-password-of-vivo-y02t-try-these-fixes-by-drfone-android/"><u>In 2024, Forgotten The Voicemail Password Of Vivo Y02T? Try These Fixes</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-recommended-best-applications-for-mirroring-your-xiaomi-redmi-note-13-pro-5g-screen-drfone-by-drfone-android/"><u>In 2024, Recommended Best Applications for Mirroring Your Xiaomi Redmi Note 13 Pro 5G Screen | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/how-to-send-and-fake-live-location-on-facebook-messenger-of-your-huawei-nova-y91-drfone-by-drfone-virtual-android/"><u>How to Send and Fake Live Location on Facebook Messenger Of your Huawei Nova Y91 | Dr.fone</u></a></li> <li><a href="https://android-location-track.techidaily.com/how-to-intercept-text-messages-on-vivo-y100i-power-5g-drfone-by-drfone-virtual-android/"><u>How to Intercept Text Messages on Vivo Y100i Power 5G | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/complete-guide-for-recovering-video-files-on-motorola-moto-g84-5g-by-fonelab-android-recover-video/"><u>Complete guide for recovering video files on Motorola Moto G84 5G</u></a></li> <li><a href="https://techidaily.com/how-to-erase-apple-iphone-xs-max-data-permanently-drfone-by-drfone-ios-full-data-eraser-ios-full-data-eraser/"><u>How To Erase Apple iPhone XS Max Data Permanently | Dr.fone</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/in-2024-pokemon-go-no-gps-signal-heres-every-possible-solution-on-realme-11-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Pokemon Go No GPS Signal? Heres Every Possible Solution On Realme 11 5G | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/best-android-data-recovery-retrieve-lost-contacts-from-thinkphone-by-fonelab-android-recover-contacts/"><u>Best Android Data Recovery - Retrieve Lost Contacts from ThinkPhone.</u></a></li> <li><a href="https://ios-pokemon-go.techidaily.com/in-2024-how-can-i-create-my-pokemon-overworld-maps-on-apple-iphone-14-drfone-by-drfone-virtual-ios/"><u>In 2024, How Can I Create My Pokemon Overworld Maps On Apple iPhone 14? | Dr.fone</u></a></li> <li><a href="https://ios-location-track.techidaily.com/in-2024-how-to-spy-on-text-messages-from-computer-and-apple-iphone-11-pro-drfone-by-drfone-virtual-ios/"><u>In 2024, How to Spy on Text Messages from Computer & Apple iPhone 11 Pro | Dr.fone</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-track-imei-number-of-samsung-galaxy-a25-5g-through-google-earth-by-drfone-android/"><u>In 2024, How To Track IMEI Number Of Samsung Galaxy A25 5G Through Google Earth?</u></a></li> <li><a href="https://techidaily.com/the-way-to-recover-deleted-contacts-on-motorola-edge-40-neo-without-backup-by-fonelab-android-recover-contacts/"><u>The way to recover deleted contacts on Motorola Edge 40 Neo without backup.</u></a></li> <li><a href="https://pokemon-go-android.techidaily.com/how-to-get-the-dragon-scale-and-evolution-enabled-pokemon-on-honor-70-lite-5g-drfone-by-drfone-virtual-android/"><u>How to get the dragon scale and evolution-enabled pokemon On Honor 70 Lite 5G? | Dr.fone</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-15-best-strongest-pokemon-to-use-in-pokemon-go-pvp-leagues-for-oppo-find-n3-flip-drfone-by-drfone-virtual-android/"><u>In 2024, 15 Best Strongest Pokémon To Use in Pokémon GO PvP Leagues For Oppo Find N3 Flip | Dr.fone</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-talkshoplive-reviews-and-pro-tips-is-this-the-live-commerce-tool-you-need-in-2024/"><u>Updated Talkshoplive Reviews & Pro Tips Is This the Live Commerce Tool You Need, In 2024</u></a></li> <li><a href="https://fake-location.techidaily.com/ultimate-guide-to-free-pptp-vpn-for-beginners-on-oneplus-open-drfone-by-drfone-virtual-android/"><u>Ultimate Guide to Free PPTP VPN For Beginners On OnePlus Open | Dr.fone</u></a></li> <li><a href="https://screen-mirror.techidaily.com/in-2024-8-best-apps-for-screen-mirroring-samsung-galaxy-s24plus-pc-drfone-by-drfone-android/"><u>In 2024, 8 Best Apps for Screen Mirroring Samsung Galaxy S24+ PC | Dr.fone</u></a></li> <li><a href="https://android-frp.techidaily.com/how-to-bypass-oppo-a78-5g-frp-in-3-different-ways-by-drfone-android/"><u>How To Bypass Oppo A78 5G FRP In 3 Different Ways</u></a></li> </ul></div>
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: //www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Method to draw a qubit topology.""" from ...core.circuit import Circuit from ...device import QubitNode, QubitsTopology from ._config import _topology_default_style from .circuit_svg_drawer import Circle, Line, Rect, SVGContainer, Text, box, super_align def _ext_edges(circ: Circuit): out = [] for g in circ: all_qubits = g.obj_qubits + g.ctrl_qubits all_qubits.sort() if len(all_qubits) == 2: out.append((all_qubits[0], all_qubits[1])) elif len(all_qubits) > 2: raise ValueError(f"gate {g} too big, need to do decomposition first.") return set(out) class SVGQNode(SVGContainer): """Qubit node on topology svg graph.""" def __init__(self, qnode: QubitNode, svg_config): """Initialize a svg qubit node.""" super().__init__() q_circle = Circle(0, 0, svg_config['r']).fill(qnode.color) q_id = Text(0, 0, str(qnode.id)).fill(svg_config['id_color']).font_size(svg_config['id_fs']) self.add(q_circle) self.add(q_id) self.shift(qnode.poi_x * svg_config['f'], qnode.poi_y * svg_config['f']) # pylint: disable=too-many-locals def draw_topology(topo: QubitsTopology, circuit: Circuit = None, style: dict = None): """ Draw a qubit topology as a svg picture. Args: topo (QubitsTopology): The qubit topology. circuit (Circuit): The given quantum circuit you want to execute on given qubit topology. style (Dict): The picture style configuration. """ if style is None: style = _topology_default_style f = style['f'] if circuit is None: selected = [] else: selected = _ext_edges(circ=circuit) for q1, q2 in selected: if not topo.is_coupled_with(q1, q2): raise RuntimeError(f"Failed to execute circuit: qubit {q1} is not coupled with {q2}.") qubits_view = SVGContainer() for q_id in topo.all_qubit_id(): qubits_view.add(SVGQNode(topo[q_id], style)) edges_view = SVGContainer() for id1, id2 in topo.edges_with_id(): q1, q2 = topo[id1], topo[id2] x1, y1 = q1.poi_x, q1.poi_y x2, y2 = q2.poi_x, q2.poi_y line = Line(x1 * f, x2 * f, y1 * f, y2 * f) color = style['couple_color'] if (id1, id2) in selected or (id2, id1) in selected: color = style['selected_edge_c'] line.stroke(color).stroke_width(style['couple_w']) edges_view.add(line) qubits_box = box(qubits_view) background = Rect(0, 0, qubits_box['width'], qubits_box['height']) background.fill("#ffffff") super_align(background, qubits_view, 'middle', 'middle', 'h') super_align(background, qubits_view, 'middle', 'middle', 'v') new_q_box = box(qubits_view) edges_view.shift(new_q_box['left'] - qubits_box['left'], new_q_box['top'] - qubits_box['top']) view = SVGContainer() view.add(background) view.add(edges_view) view.add(qubits_view) return view
/* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { ChildProcess, spawn } from 'child_process'; import { readFile as fsReadFile } from 'fs/promises'; import { write as fsWrite } from 'fs'; import { join } from 'path'; import { file } from 'tmp-promise'; import { promisify } from 'util'; import { UserSettings } from 'n8n-core'; // eslint-disable-next-line import/no-cycle import { IBuildOptions } from '.'; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires const copyfiles = require('copyfiles'); // eslint-disable-next-line @typescript-eslint/no-unused-vars const fsReadFileAsync = promisify(fsReadFile); const fsWriteAsync = promisify(fsWrite); /** * Create a custom tsconfig file as tsc currently has no way to define a base * directory: * https://github.com/Microsoft/TypeScript/issues/25430 * * @export * @returns */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export async function createCustomTsconfig() { // Get path to simple tsconfig file which should be used for build const tsconfigPath = join(__dirname, '../../src/tsconfig-build.json'); // Read the tsconfi file const tsConfigString = await fsReadFile(tsconfigPath, { encoding: 'utf8' }); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const tsConfig = JSON.parse(tsConfigString); // Set absolute include paths const newIncludeFiles = []; // eslint-disable-next-line no-restricted-syntax for (const includeFile of tsConfig.include) { newIncludeFiles.push(join(process.cwd(), includeFile)); } tsConfig.include = newIncludeFiles; // Write new custom tsconfig file // eslint-disable-next-line @typescript-eslint/no-unsafe-call // eslint-disable-next-line @typescript-eslint/unbound-method const { fd, path, cleanup } = await file(); await fsWriteAsync(fd, Buffer.from(JSON.stringify(tsConfig, null, 2), 'utf8')); return { path, cleanup, }; } /** * Builds and copies credentials and nodes * * @export * @param {IBuildOptions} [options] Options to overwrite default behaviour * @returns {Promise<string>} */ export async function buildFiles(options?: IBuildOptions): Promise<string> { // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing, no-param-reassign options = options || {}; let typescriptPath; // Check for OS to designate correct tsc path if (process.platform === 'win32') { typescriptPath = '../../node_modules/TypeScript/lib/tsc'; } else { typescriptPath = '../../node_modules/.bin/tsc'; } const tscPath = join(__dirname, typescriptPath); const tsconfigData = await createCustomTsconfig(); const outputDirectory = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing options.destinationFolder || UserSettings.getUserN8nFolderCustomExtensionPath(); // Supply a node base path so that it finds n8n-core and n8n-workflow const nodeModulesPath = join(__dirname, '../../node_modules/'); let buildCommand = `${tscPath} --p ${ tsconfigData.path } --outDir ${outputDirectory} --rootDir ${process.cwd()} --baseUrl ${nodeModulesPath}`; if (options.watch === true) { buildCommand += ' --watch'; } let buildProcess: ChildProcess; try { buildProcess = spawn('node', buildCommand.split(' '), { windowsVerbatimArguments: true, cwd: process.cwd(), }); // Forward the output of the child process to the main one // that the user can see what is happening // @ts-ignore buildProcess.stdout.pipe(process.stdout); // @ts-ignore buildProcess.stderr.pipe(process.stderr); // Make sure that the child process gets also always terminated // when the main process does process.on('exit', () => { buildProcess.kill(); }); } catch (error) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment let errorMessage = error.message; if (error.stdout !== undefined) { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions errorMessage = `${errorMessage}\nGot following output:\n${error.stdout}`; } // Remove the tmp tsconfig file // eslint-disable-next-line @typescript-eslint/no-floating-promises tsconfigData.cleanup(); throw new Error(errorMessage); } // eslint-disable-next-line @typescript-eslint/no-unused-vars return new Promise((resolve, reject) => { ['*.png', '*.node.json'].forEach((filenamePattern) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-call copyfiles([join(process.cwd(), `./${filenamePattern}`), outputDirectory], { up: true }, () => resolve(outputDirectory), ); }); // eslint-disable-next-line @typescript-eslint/no-unused-vars buildProcess.on('exit', (code) => { // Remove the tmp tsconfig file // eslint-disable-next-line @typescript-eslint/no-floating-promises tsconfigData.cleanup(); }); }); }
/* eslint-disable import/no-nodejs-modules, import/max-dependencies */ import http from 'http'; import {createId} from '@paralleldrive/cuid2'; import {ErrorContext} from '@silver886/error-context'; import {ValidateError} from '@tsoa/runtime'; import bodyParser from 'body-parser'; import compression from 'compression'; import cookieParser from 'cookie-parser'; import cors from 'cors'; import express, {Router as router} from 'express'; import helmet from 'helmet'; import {StatusCodes} from 'http-status-codes'; import {getAbsoluteFSPath} from 'swagger-ui-dist'; import swaggerUI from 'swagger-ui-express'; import {HeaderName} from './config'; import swagger from './openapi/swagger.json'; // eslint-disable-line import/extensions import {RegisterRoutes as registerRoutes} from './routes/routes'; import type {BasicRequest} from './models/common'; import type {Express, NextFunction, Request, Response} from 'express'; import type {Server} from 'http'; import type {JsonObject} from 'swagger-ui-express'; // eslint-disable-next-line max-statements, max-lines-per-function export const APP = ((): Express => { const app = express(); app.use( cors({ credentials: true, }), ); app.use( bodyParser.json({ limit: '8MB', }), ); app.use(bodyParser.text()); app.use(express.json()); app.use( express.urlencoded({ extended: false, }), ); app.use(helmet()); app.use(compression()); app.use(cookieParser()); app.use( ( req: Partial<BasicRequest> & Request, res: Partial<BasicRequest> & Response, next: NextFunction, ): void => { const id = createId(); req.id = id; res.append(HeaderName.REQUEST_ID, id); next(); }, ); app.use(express.static(getAbsoluteFSPath())); const routing = router(); routing.use( '/api-doc', swaggerUI.serve, swaggerUI.setup(swagger as JsonObject, { customCss: '.swagger-ui .curl-command {display:none;}', }), ); registerRoutes(routing); app.use('/', routing); app.use( ( err: unknown, req: Request, res: Response, next: NextFunction, // eslint-disable-next-line @typescript-eslint/no-invalid-void-type, max-params, consistent-return ): Response | void => { if (err instanceof ValidateError) { // eslint-disable-next-line no-console console.error(`Caught Validation Error for ${req.path}:`, err); return res.status(StatusCodes.UNPROCESSABLE_ENTITY).json({ message: 'Validation Failed', details: err.fields, }); } if (err instanceof ErrorContext) { // eslint-disable-next-line no-console console.error(`Caught Internal Server Error for ${req.path}:`, err); return res.status(StatusCodes.SERVICE_UNAVAILABLE).json({ requestId: err.context.requestId, message: 'Service Unavailable', }); } if (err instanceof Error) { // eslint-disable-next-line no-console console.error(`Caught Unknown Error for ${req.path}:`, err); return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ message: 'Internal Server Error', }); } next(); }, ); return app; })(); // eslint-disable-next-line max-statements export function expressServer(): Server { const server = http.createServer(APP); return server; }
<template> <div> <el-table :data="table.data" text-align="center" stripe border> <el-table-column prop="id" label="权限编号" width="140" v-if="false" /> <el-table-column prop="name" label="权限名称" /> <el-table-column prop="description" label="权限描述" /> <el-table-column label="操作" width="170" align="center"> <template #default="scope"> <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改描述</el-button> </template> </el-table-column> </el-table> <el-pagination class="pageTop" background :page-sizes="[5, 10, 20, 30]" layout="sizes, prev, pager, next, jumper, total" :total="table.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="table.pageSize" /> <el-dialog v-model="dialogFormVisible" title="修改描述" width="500px" :close-on-click-modal="false" draggable> <el-form :model="form" @keyup.enter="editDescription(formRef)" ref="formRef"> <el-form-item label-width="100px" prop="id" v-if="false"> <el-input v-model="form.id" autocomplete="off" /> </el-form-item> <el-form-item label="权限名称" label-width="100px" prop="name"> <el-input v-model="form.name" autocomplete="off" disabled /> </el-form-item> <el-form-item label="权限描述" label-width="100px" prop="description"> <el-input v-model="form.description" placeholder="请输入权限描述" /> </el-form-item> </el-form> <template #footer> <span class="dialog-footer"> <el-button @click="dialogFormVisible = false;getPermission()">取消</el-button> <el-button type="primary" @click="editDescription(formRef)">修改描述</el-button> </span> </template> </el-dialog> </div> </template> <script lang="ts" setup> import { getCurrentInstance, ref, onMounted, reactive } from "vue"; import { ElMessage } from "element-plus"; import axios from 'axios'; const dialogFormVisible = ref(false); const table = reactive({ data: [], total: 0, pageSize: 5, currentPage: 1, orderDirection: "descending", orderField: "name" }); const form = ref({ id: "", name: "", description: "", }); const formRef = ref(); function getPermission() { let params = new URLSearchParams(); params.append("pageSize", String(table.pageSize)); params.append("currentPage", String(table.currentPage)); axios.post("security/getAllPermission", params).then((res: any) => { table.data = res.data.data.content; table.total = res.data.data.totalElements; }); } const handleSizeChange = function (val: number) { table.pageSize = val; getPermission(); }; const handleCurrentChange = function (val: number) { table.currentPage = val; getPermission(); }; const handleEdit = function (row: any) { form.value = row; dialogFormVisible.value = true; }; const editDescription = (formRef: any) => { let value = form.value; let params = new URLSearchParams(); params.append("id", value.id); params.append("description", value.description); axios.post("security/updateDescriptionByPermissionId", params).then((res: any) => { let result = res.data; if (result.code == 200) { ElMessage.success("更新成功"); dialogFormVisible.value = false; getPermission(); } else { ElMessage.error("更新失败"); } }); } onMounted(() => { getPermission(); }); </script> <style scoped> .pageTop { margin-top: 20px; } </style>
import allure import pytest from helpers.csv_helper import CSVHelper from src.ui.actions.backgrounds import BackgroundsActions from src.ui.actions.base_actions import BaseActions from src.ui.actions.spa_actions import SPAActions from test_data.constants import ExamResult @allure.feature('Labors tab as Test Center Owner') @pytest.mark.tc @pytest.mark.daily @pytest.mark.ui @pytest.mark.usefixtures('logout_after_test') class TestTCenterLabors: # pylint: disable=unused-argument, attribute-defined-outside-init @pytest.fixture() def pre_test(self, api): self.base_actions = BaseActions() self.spa_actions = SPAActions(api) self.csv_helper = CSVHelper() self.spa_actions = SPAActions(api) self.background_actions = BackgroundsActions(api) self.background_actions.create_entities_and_log_in(self.spa_actions.auth_api_actions, is_tcenter=True, is_tcenter_activate=True) @allure.title('Checking the ability to search entry by filters and clear filters on Labors table') def test_tc_search_entry_by_filters_on_labors_table(self, pre_test): self.spa_actions.verify_filters_on_labors_table() @allure.title('Checking counts on Labors tab') @pytest.mark.parametrize('exam_result', ExamResult.LIST_EXAM_RESULTS, ids=ExamResult.LIST_EXAM_RESULTS) def test_tc_counts_on_labors_tab(self, pre_test, exam_result): self.spa_actions.add_group(status=exam_result) self.spa_actions.verify_counts_on_labors_tab(exam_result) @allure.title('Checking all count on Labors tab') def test_tc_all_count_on_labors_tab(self, pre_test): self.spa_actions.verify_all_count_on_labors_tab() @allure.title('Checking pagination and search result value as Test Center on Labors tab') def test_tc_pagination_and_search_result_value(self, pre_test): self.spa_actions.verify_pagination_and_search_result_value() @allure.title('Checking the ability to edit email on Labors tab') def test_tc_edit_email_on_labors_tab(self, pre_test): self.spa_actions.edit_and_verify_email() @allure.title('Checking validation of edit email field on Labors tab') def test_tc_validation_edit_email_on_labors_tab(self, pre_test): self.spa_actions.verify_validation_edit_email_on_labors_tab(ExamResult.PENDING)
#include <stdio.h> #include <stdlib.h> void readArrayFromFile(const char *fileName, int *arr, int *n) { FILE *file = fopen(fileName, "r"); if (!file) { printf("File cannot be opened.\n"); exit(1); } fscanf(file, "%d", n); // Read the number of elements for (int i = 0; i < *n; i++) { fscanf(file, "%d", &arr[i]); } fclose(file); } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int removeDuplicates(int arr[], int n, int newArr[]) { int j = 0; for (int i = 0; i < n; i++) { int found = 0; for (int k = 0; k < j; k++) { if (arr[i] == newArr[k]) { found = 1; break; } } if (!found) { newArr[j++] = arr[i]; } } return j; // New size of the array without duplicates } int main() { int n; printf("Enter the size of the array: "); scanf("%d", &n); int *arr = (int *)malloc(n * sizeof(int)); int *newArr = (int *)malloc(n * sizeof(int)); readArrayFromFile("numbers.txt", arr, &n); printf("Original array:\n"); printArray(arr, n); int newSize = removeDuplicates(arr, n, newArr); printf("Array after removing duplicates:\n"); printArray(newArr, newSize); free(arr); free(newArr); return 0; }
from dataclasses import dataclass import torch from torch import nn from transformers import AutoModel, AutoTokenizer from ...utils.modeling import CLSPooling, AveragePooling, SelfAttentionPooling, LastTokenPooling from .base_dialogue_model import BaseDialogueModel @dataclass class BaselineDialogueEncoderConfig: hf_model: str = 'google-bert/bert-base-uncased' pooling: str = 'cls' # 'avg' or 'cls' or 'att' or 'last' truncation: bool = False max_length: int = 512 class BaselineDialogueEncoder(nn.Module, BaseDialogueModel): def __init__(self, config: BaselineDialogueEncoderConfig, **automodel_kwargs): super().__init__() self.config = config self.model = AutoModel.from_pretrained(config.hf_model, **automodel_kwargs) self.tokenizer = AutoTokenizer.from_pretrained(config.hf_model) if self.config.pooling == 'cls': self.pooler = CLSPooling() elif self.config.pooling == 'avg': self.pooler = AveragePooling() elif self.config.pooling == 'att': self.pooler = SelfAttentionPooling(self.model.config.hidden_size) elif self.config.pooling == 'last': self.pooler = LastTokenPooling() else: raise ValueError('unknown pooler name') @property def device(self): return self.model.device @staticmethod def _parse(dia): """ return list of strings of the following format: [ "0 Hello, dear!", "1 Hi.", "0 How can I help you?", "1 Tell me a joke." ] """ return [f'{item["speaker"]} {item["utterance"]}' for item in dia] @staticmethod def _tokenize(tokenizer: AutoTokenizer, batch, truncation=False, max_length=512): """ 1. convert each dialogue to a single string of the following format: "0 Hello, dear![SEP]1 Hi.[SEP]0 How can I help you?[SEP]1 Tell me a joke." 2. tokenize every string with the standard tokenizer of the provided hf model """ sep = tokenizer.sep_token if sep is None: sep = '\n' parsed = [sep.join(BaselineDialogueEncoder._parse(dia)) for dia in batch] inputs = tokenizer(parsed, padding=True, max_length=max_length, return_tensors='pt', truncation=truncation) return inputs def forward(self, batch): """ input: batch of dialogues output: (B,H) """ inputs = self._tokenize( self.tokenizer, batch, truncation=self.config.truncation, max_length=self.config.max_length ).to(self.device) outputs = self.model(**inputs) encodings = self.pooler(outputs.last_hidden_state, inputs.attention_mask) return encodings def get_all_hidden_states(self, batch, pooler, n_last): """ input: batch of dialogues output: embeddings (B,H), hidden_states (n_last,B,H), hidden_embeddings (n_last,B,H) """ inputs = self._tokenize( self.tokenizer, batch, truncation=self.config.truncation, max_length=self.config.max_length ).to(self.device) outputs = self.model(**inputs) embeddings = self.pooler(outputs.last_hidden_state, inputs.attention_mask) hidden_states = [] for hidden_state in outputs.hidden_states[-n_last:]: hidden_states.append(pooler(hidden_state, inputs.attention_mask)) hidden_states = torch.stack(hidden_states, dim=0) if not isinstance(self.pooler, AveragePooling): hidden_embeddings = [] for hidden_state in outputs.hidden_states[-n_last:]: hidden_embeddings.append(self.pooler(hidden_state, inputs.attention_mask)) hidden_embeddings = torch.stack(hidden_embeddings, dim=0) else: hidden_embeddings = None return embeddings, hidden_states, hidden_embeddings def get_hidden_size(self): return self.model.config.hidden_size
import { Request, Response } from "express"; import apiCaller from "@/ultis/apiCaller"; import { IMatchDetails, IMatchDetailStats, IMatchDetailsHeading } from "@projectb/shared"; import { AxiosResponse } from "axios"; import { logger } from "@/ultis/logger"; const getMatchDetails = async (req: Request, res: Response): Promise<void> => { const id = parseInt(req.params.id); await apiCaller("details", "get") .then((response: AxiosResponse) => { if (response.data) { const item: IMatchDetails = response.data.filter((element: IMatchDetails) => id === element.id)[0]; logger.info(item, "Details results"); const MatchDetailsHeading: IMatchDetailsHeading = { id: item.id, stage: item.stage, startDateTime: item.startDateTime, homeTeam: { name: item.homeTeam.name, logoUrl: item.homeTeam.logoUrl, score: item.homeTeam.score, penalty: item.homeTeam.penalty, goals: item.homeTeam.goals, }, awayTeam: { name: item.awayTeam.name, logoUrl: item.awayTeam.logoUrl, score: item.awayTeam.score, penalty: item.awayTeam.penalty, goals: item.awayTeam.goals, }, }; const MatchDetailStats: IMatchDetailStats = { id: item.id, homeTeam: { name: item.homeTeam.name, logoUrl: item.homeTeam.logoUrl, shots: item.homeTeam.shots, shotsTarget: item.homeTeam.shotsTarget, possession: item.homeTeam.possession, passes: item.homeTeam.passes, passAccuracy: item.homeTeam.passAccuracy, fouls: item.homeTeam.fouls, yellowCards: item.homeTeam.yellowCards, redCards: item.homeTeam.redCards, offsides: item.homeTeam.offsides, corners: item.homeTeam.corners, }, awayTeam: { name: item.awayTeam.name, logoUrl: item.awayTeam.logoUrl, shots: item.awayTeam.shots, shotsTarget: item.awayTeam.shotsTarget, possession: item.awayTeam.possession, passes: item.awayTeam.passes, passAccuracy: item.awayTeam.passAccuracy, fouls: item.awayTeam.fouls, yellowCards: item.awayTeam.yellowCards, redCards: item.awayTeam.redCards, offsides: item.awayTeam.offsides, corners: item.awayTeam.corners, }, stadium: item.stadium, }; res.status(200).json({ MatchDetailsHeading, MatchDetailStats }); } }) .catch((error: Error) => { logger.error(error, "Error when fetching match's details"); res.status(500).json({ error }); }); }; export default getMatchDetails;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package admin.member; import bean.Member; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import jdbc.JDBCUtility; /** * * @author USER */ @WebServlet(name = "ViewMemberProfileServlet", urlPatterns = {"/ksc-admin/ViewMemberProfileServlet"}) public class ViewMemberProfileServlet extends HttpServlet { private JDBCUtility jdbcUtility; private Connection con; public void init() throws ServletException { String driver = "com.mysql.jdbc.Driver"; String dbName = "db_futsal"; String url = "jdbc:mysql://localhost/" + dbName + "?"; String userName = "root"; String password = ""; jdbcUtility = new JDBCUtility(driver, url, userName, password); jdbcUtility.jdbcConnect(); con = jdbcUtility.jdbcGetConnection(); jdbcUtility.prepareSQLStatement(); } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); if((session != null) && (session.getAttribute("userSession") != null)){ String nric = request.getParameter("nric"); Member m = null; try { PreparedStatement preparedStatement = jdbcUtility.getPsSelectMemberViaNRIC(); preparedStatement.setString(1, nric); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()){ int id = rs.getInt("id"); String memberNo = rs.getString("memberNo"); String name = rs.getString("name"); String NRIC = rs.getString("NRIC"); String dateRegistered = rs.getString("dateRegistered"); String birthDate = rs.getString("birthDate"); String address = rs.getString("address"); String telNo = rs.getString("telNo"); String email = rs.getString("email"); String dateUpdate = rs.getString("dateUpdate"); //parse date string to Date object SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); Date dt = new Date(); Date dt2 = new Date(); try { date = formatter.parse(dateRegistered); dt = formatter.parse(dateUpdate); dt2 = sdf.parse(birthDate); } catch (Exception ex) { } //convert MYSQL format to other format formatter = new SimpleDateFormat("dd MMM yyyy, HH:mm:ss a"); sdf = new SimpleDateFormat("dd MMM yyyy "); dateRegistered = formatter.format(date); dateUpdate = formatter.format(dt); birthDate = sdf.format(dt2); m = new Member(); m.setId(id); m.setMemberNo(memberNo); m.setName(name); m.setAddress(address); m.setBirthDate(birthDate); m.setDateRegistered(dateRegistered); m.setDateUpdate(dateUpdate); m.setEmail(email); m.setNRIC(NRIC); m.setTelNo(telNo); } request.setAttribute("member", m); sendPage(request, response, "/pages/admin/viewmember.jsp"); } catch (SQLException ex) { out.println("dalam ex"); } }else { } } void sendPage(HttpServletRequest req, HttpServletResponse res, String fileName) throws ServletException, IOException { // Get the dispatcher; it gets the main page to the user RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(fileName); if (dispatcher == null) { System.out.println("There was no dispatcher"); // No dispatcher means the html file could not be found. res.sendError(res.SC_NO_CONTENT); } else dispatcher.forward(req, res); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Formulário 1</title> </head> <body> <header> <h1>Formulário de Envio</h1> </header> <main> <!--Form define um formulário--> <!--'Action' especifica para onde os dados do formulario serão enviados--> <form action="acao.html" method="post" enctype="multipart/form-data"> <!--method: get ou post. Especifica como os dados serão enviados: Get envia os dados como parâmetro da URl e post envia no corpo da solicitação HTPP--> <!--'enctype' especifíca que tipos de dados serão enviados pelo formulário--> <label>Nome: </label> <!--Label "etiqueta" o input, ou seja, informa o usuário qual o campo a ser preenchido--> <input type="text" name="name" id="name" required> <!--Input do tipo texto aceita somente caracteres do tipo texto--> <!--Atributo required informa que o campo é obrigatório--> <br> <br> <label> Email: </label> <input type="text" name="email" id="email" required> <!--Input tipo senha "esconde" o texto para o usuário para aumentar a segurança do dado--> <br> <br> <label> Senha: </label> <input type="password" name="senha" id="senha" required> <br> <br> <label>Selecione um arquivo:</label> <input type="file" name="file" id="file" accept=".png, .jpg, .jpeg" multiple> <!--input tipo file permite a submissão de arquivos por meio do formulário--> <!--'accep': tipos de arquivos aceitados--> <!--'multiple': permite enviar mais de um arquivo--> <br> <br> <label>Selecione a opção de envio: </label> <br> <input type="radio" name="option1" id="option1" value="1" > Expresso <br> <input type="radio" name="option1" id="option1" value="2" checked required> Padrão <br> <input type="radio" name="option1" id="option1" value="3" > Economica <!--Input do tipo radio funciona como uma 'lista' de seleção, para cada opção dessa lista deve-se colocar o mesmo "name" e "id", o atributo que deve mudar com base na opção é o atributo "value"--> <!--O atributo checked, deixa um opção marcada como padrão. Sempre que recarregar a página essa opção estará marcada--> <br> <br> <label></label> <input type="checkbox" name="math" id="math" required> Aceito os termos e condições <!--Input do tipo "checkbox" funciona de uma maneira semelhante a radio, só que com a opção de seleção de múltiplos dados--> <br> <br> <input type="submit" value="Enviar"> <input type="submit" value="Limpar"> </form> </main> </body> </html>
import is from '@sindresorhus/is' import { Datasource } from 'renovate/dist/modules/datasource/datasource' import { Release, ReleaseResult } from 'renovate/dist/modules/datasource/types' import { Versioning } from './config' import { isNotEmpty } from './utils' import { VersionFetcher, VersionFetchParams } from './VersionFetcher' export type RenovateDatasourceFactory = ((params: VersionFetchParams) => Datasource) export type RenovateReleaseFilter = (release: Release) => boolean export abstract class VersionFetcherRenovateDatasource extends VersionFetcher { protected constructor( private readonly renovateDatasourceApi: Datasource | RenovateDatasourceFactory, ) { super() } private getRenovateDatasource(params: VersionFetchParams = {}): Datasource { const renovateDatasourceApi = this.renovateDatasourceApi if (is.function_(renovateDatasourceApi)) { return renovateDatasourceApi(params) } else { return renovateDatasourceApi } } protected createRenovateReleaseFilter(params: VersionFetchParams): RenovateReleaseFilter { return release => release.isDeprecated !== true } async fetchVersions(params: VersionFetchParams): Promise<string[]> { params = { ...params } if (!this.withDependencies) { params.dependency = undefined } else if (!isNotEmpty(params.dependency)) { throw new Error('Empty dependency') } const dependency = params.dependency const renovateDatasource = this.getRenovateDatasource(params) const renovateReleaseFilter = this.createRenovateReleaseFilter(params) let repositories = params.repositories ?? [] if (!repositories.length) { const defaultRepositories = renovateDatasource.defaultRegistryUrls if (defaultRepositories == null) { repositories = [] } else if (is.function_(defaultRepositories)) { repositories = defaultRepositories() } else { repositories = defaultRepositories } } if (!isNotEmpty(repositories)) { throw new Error('No repositories passed') } const results: ReleaseResult[] = [] for (const currentRepository of repositories) { const result = await renovateDatasource.getReleases({ packageName: dependency ?? '', registryUrl: currentRepository, }) if (result != null) { results.push(result) } } const versions = results.flatMap(result => result.releases) .filter(renovateReleaseFilter) .map(release => release.version) .filter(isNotEmpty) if (versions.length) { return versions } let message = 'No versions found' if (isNotEmpty(dependency)) { message += ` of '${dependency}'` } message += ` in ${repositories.join(', ')}` throw new Error(message) } get defaultVersioning(): Versioning { const renovateDatasource = this.getRenovateDatasource() return renovateDatasource.defaultVersioning ?? super.defaultVersioning } }
import { useLocation } from 'react-router-dom'; import RecipeList from '../../components/RecipeList'; import { useFetch } from '../../hook/useFetch'; // Style import './Search.css' export default function Search() { const queryString = useLocation().search const queryParams = new URLSearchParams(queryString) const query = queryParams.get('q') const url = `http://localhost:3000/recipes?q=${query}` const { data, isPending, error } = useFetch(url) return ( <div> <h2 className="page-title">Recipes including "{query}"</h2> { error && <p className='error'>{error}</p> } { isPending && <p className="loading">Loading...</p> } { data && <RecipeList recipes={data} /> } </div> ); }
#include "driver/gpio.h" #include "esp_adc/adc_oneshot.h" #include "esp_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" const gpio_num_t LED4 = GPIO_NUM_12; const gpio_num_t LED5 = GPIO_NUM_13; const gpio_num_t ANALOG3 = GPIO_NUM_3; const adc_channel_t ANALOG3_CHANNEL = ADC_CHANNEL_3; const int ZERO_THRES = 450; const int ONE_THRES = 4000; const int LOOP_INTERVAL_MS = 20; adc_oneshot_unit_handle_t adc1Handle; int lastAnalogOutput = 0; int count = 0; void init(void) { ESP_ERROR_CHECK(gpio_set_direction(LED4, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(gpio_set_direction(LED5, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(gpio_set_level(LED4, 1)); ESP_ERROR_CHECK(gpio_set_level(LED5, 1)); adc_oneshot_unit_init_cfg_t adc1InitCfg = { .unit_id = ADC_UNIT_1, .ulp_mode = ADC_ULP_MODE_DISABLE, }; ESP_ERROR_CHECK(adc_oneshot_new_unit(&adc1InitCfg, &adc1Handle)); adc_oneshot_chan_cfg_t analog3Cfg = { .bitwidth = ADC_BITWIDTH_12, .atten = ADC_ATTEN_DB_12, }; ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1Handle, ANALOG3_CHANNEL, &analog3Cfg)); ESP_ERROR_CHECK(adc_oneshot_read(adc1Handle, ANALOG3_CHANNEL, &lastAnalogOutput)); } void loop(void) { int analogOutput = 0; adc_oneshot_read(adc1Handle, ANALOG3_CHANNEL, &analogOutput); if (analogOutput >= ONE_THRES && lastAnalogOutput <= ZERO_THRES) { count++; ESP_LOGI("LOG", "count = %d", count); } lastAnalogOutput = analogOutput; vTaskDelay(pdMS_TO_TICKS(LOOP_INTERVAL_MS)); } void app_main(void) { init(); while (1) { loop(); } }
import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets["gcp_service_account"] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) return query_job.result().to_dataframe() query_string =""" WITH cte_data_raw AS ( SELECT * FROM `idragon23.analytics_345872396.events_*` WHERE (_table_suffix BETWEEN '20230522' AND FORMAT_DATE('%Y%m%d',CURRENT_DATE()) ) ) SELECT DISTINCT RAW.user_pseudo_id, # Ma nguoi dung theo GA, RAW.user_id, # Ma khach hang ( C..., fbid,...) # loai nguoi dung ( KH HH, Trial, expire trial) RAW.device.mobile_model_name, RAW.device.category, RAW.device.operating_system, RAW.geo.city, RAW.geo.country, # DOB # Gender RAW.device.language, RAW.app_info.version, DATETIME_ADD(PARSE_DATETIME('%s', CAST(TRUNC( start_trial.event_timestamp /1000000) AS STRING)),INTERVAL 7 HOUR) AS start_trial, DATETIME_ADD(PARSE_DATETIME('%s', CAST(TRUNC( download_app.event_timestamp/1000000) AS STRING)),INTERVAL 7 HOUR) AS download_app, DATETIME_ADD(PARSE_DATETIME('%s', CAST(TRUNC( first_login.event_timestamp /1000000) AS STRING)),INTERVAL 7 HOUR) AS first_login FROM cte_data_raw AS RAW LEFT JOIN ( SELECT start_trial.user_id, start_trial.user_pseudo_id, start_trial.event_timestamp FROM ( SELECT event_timestamp, user_id, user_pseudo_id, ROW_NUMBER () OVER(PARTITION BY user_id ORDER BY event_timestamp ASC) AS row_num FROM `idragon23.analytics_345872396.events_*` WHERE ( SELECT value.string_value FROM UNNEST(user_properties) WHERE KEY = 'trial_register') IS NOT NULL ) AS start_trial WHERE start_trial.row_num =1 AND STARTS_WITH(start_trial.user_id, "C") = FALSE AND start_trial.user_id IS NOT NULL ) AS start_trial ON RAW.user_pseudo_id = start_trial.user_pseudo_id AND RAW.user_id = start_trial.user_id LEFT JOIN ( SELECT XXX.event_timestamp, XXX.user_id, XXX.user_pseudo_id FROM ( SELECT DISTINCT X.event_timestamp, Y.user_id, Y.user_pseudo_id, ROW_NUMBER () OVER(PARTITION BY Y.user_id ORDER BY X.event_timestamp ASC) AS row_num FROM ( SELECT DISTINCT event_timestamp, user_pseudo_id, device.vendor_id FROM `idragon23.analytics_345872396.events_*` WHERE event_name = 'first_open' ) AS X, ( SELECT DISTINCT user_id, user_pseudo_id, device.vendor_id FROM `idragon23.analytics_345872396.events_*` WHERE user_id IS NOT NULL )AS Y WHERE X.user_pseudo_id = Y.user_pseudo_id ) AS XXX WHERE XXX.row_num= 1 ) AS download_app ON RAW.user_pseudo_id = download_app.user_pseudo_id AND RAW.user_id = download_app.user_id LEFT JOIN ( SELECT * FROM ( SELECT event_date, event_timestamp, ( SELECT value.string_value FROM UNNEST(event_params) WHERE KEY = 'page_view') AS page_view, event_previous_timestamp, user_id, ( SELECT value.string_value FROM UNNEST(user_properties) WHERE KEY = 'account_name') AS account_name, user_pseudo_id, ROW_NUMBER () OVER(PARTITION BY user_id ORDER BY event_timestamp ASC) row_num FROM `idragon23.analytics_345872396.events_*` WHERE user_id IS NOT NULL ) AS X WHERE X.row_num = 1 ) AS first_login ON RAW.user_pseudo_id = first_login.user_pseudo_id AND RAW.user_id = first_login.user_id WHERE RAW.user_id IS NOT NULL ORDER BY user_id, user_pseudo_id """ rows = run_query(query_string) # Print results. st.write("Rong Viet User iDragon") st.dataframe(rows)
<template> <div class="card table-box"> <!-- card 背景颜色 table-box 高度处理--> <el-form class="search-form" :inline="true" :model="formInline" v-show="showSearch"> <el-form-item label="菜单名称"> <el-input v-model="formInline.menuName" placeholder="请输入" clearable style="width: 192px" /> </el-form-item> <el-form-item label="状态"> <el-select v-model="formInline.status" placeholder="请选择" clearable style="width: 192px"> <el-option v-for="item in commonStatus" :key="item.value" :label="item.label" :value="item.value" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="renderTable" ><el-icon><Search /></el-icon>搜索</el-button > <el-button @click="resetQuery"><el-icon><Refresh /></el-icon>重置</el-button> </el-form-item> </el-form> <div class="table-header"> <el-button type="primary" plain @click="addRow" v-hasPermi="['system:menu:add']" ><el-icon><Plus /></el-icon>新增</el-button > <el-button type="info" plain @click="toggleExpandAll" ><el-icon><Sort /></el-icon>折叠/展开</el-button > <span style="float: right"> <el-button circle @click="showSearch = !showSearch" ><el-icon><Search /></el-icon ></el-button> <el-button circle @click="renderTable" ><el-icon><Refresh /></el-icon ></el-button> </span> </div> <el-table v-loading="loading" v-if="refreshTable" row-key="menuId" :header-cell-style="{ background: '#f5f7fa' }" :data="tableData" style="width: 100%" :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" > <el-table-column v-for="item in tableColumns" :key="item.prop" :prop="item.prop" :label="item.label" :min-width="item.width || 80" > <template #default="{ row }"> <template v-if="item.prop == 'icon'"> <el-icon :size="18" v-if="row.icon && row.icon != '#'"> <component :is="row.icon" /> </el-icon> </template> <template v-else-if="item.prop == 'status'"> <dict-tag :options="commonStatus" :value="row.status" /> </template> <template v-else> {{ row[item.prop] }} </template> </template> </el-table-column> <el-table-column label="操作" width="230"> <template #default="{ row }"> <el-button type="primary" text @click="handleEdit(row)" v-hasPermi="['system:menu:edit']">修改</el-button> <el-button type="primary" text @click="handleAdd(row)" v-hasPermi="['system:menu:add']">新增</el-button> <el-button type="primary" text @click="handleDelete(row)" v-hasPermi="['system:menu:remove']">删除</el-button> </template> </el-table-column> </el-table> <!-- 新增编辑弹窗 --> <AddOrEdit @render-table="renderTable" ref="AddOrEditRef" :handle-type="handleType" :form-data="mainRow" :tree-data="treeData" /> </div> </template> <script lang="ts" setup name="menu"> import { getMenuList, deleteMenu } from '@/api/modules/system/menu' import { commonStatus } from '@/utils/serviceDict' import { Menu } from '@/api/interface/system' import AddOrEdit from './EditForm.vue' import { ref, reactive, onBeforeMount, computed, watch, nextTick } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' const loading = ref(false) // 折叠展开 const isExpandAll = ref(false) // 刷新 const refreshTable = ref(true) // 是否显示查询form const showSearch = ref(true) // 查询参数 const formInline = reactive({ menuName: '', status: '' }) const handleType = ref('add') // 使用ref修改子组件的数据 子组件中一定要使用 defineExpose({ dialogFormVisible }); 将数据暴露出去 const AddOrEditRef = ref() // 全局配置尺寸 处理分页组件的尺寸 import { useGlobalStore } from '@/stores/modules/global' const globalStore = useGlobalStore() const pageComponentSize = ref(false) const assemblySize = computed(() => globalStore.assemblySize) watch(assemblySize, (newV) => { pageComponentSize.value = newV == 'small' }) // 编辑参数 未处理成响应式 interface formDataInterface { menuId?: number; parentId: number; status: string; menuName: string; } let mainRow = ref<formDataInterface>({ menuId: 0, parentId: 0, status: '', menuName: '' }) // 表格列 const tableColumns = [ { prop: 'menuName', label: '菜单名称' }, { prop: 'icon', label: '图标', width: 70 }, { prop: 'orderTag', label: '排序', width: 70 }, { prop: 'perms', label: '权限标识',width: 110 }, { prop: 'component', label: '组件路径', width: 150 }, { prop: 'status', label: '状态', width: 70 }, { prop: 'addTime', label: '创建时间' } ] // 表格数据 let tableData = [] let treeData = [] // 生命周期钩子 类似vue2中 created onBeforeMount(async () => { renderTable() }) // 方法 const addRow = () => { mainRow.value = { menuId: 0, parentId: 0, status: '', menuName: '' } handleType.value = 'add' AddOrEditRef.value.dialogFormVisible = true } // 方法 const handleAdd = (row:formDataInterface) => { mainRow.value = { parentId: row.menuId || 0, status: '', menuName: '' } handleType.value = 'add' AddOrEditRef.value.dialogFormVisible = true } // 重置查询 const resetQuery = () => { formInline.menuName = '' formInline.status = '' } // 折叠/展开 const toggleExpandAll = () => { refreshTable.value = false isExpandAll.value = !isExpandAll.value nextTick(() => { refreshTable.value = true }) } // 编辑 const handleEdit = (row: formDataInterface) => { handleType.value = 'edit' mainRow.value = { menuId: row.menuId, parentId: row.menuId, status: row.status, menuName: row.menuName } AddOrEditRef.value.dialogFormVisible = true } // 删除 const handleDelete = (row: { id: number }) => { ElMessageBox.confirm('是否删除?', 'Warning', { confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning' }).then(async () => { await deleteMenu(String(row.id)) ElMessage.success('操作成功!') renderTable() }) } // 刷新tabel const renderTable = () => { getTableData() } // 获取表格数据 const getTableData = async () => { loading.value = true try { let { data } = await getMenuList(formInline) tableData = handleTree(data) treeData = [ { menuId: 0, menuName: '主类目', children: tableData } ] loading.value = false } catch (e) { loading.value = false } } const handleTree = (menuItems: Menu.ResMenuList[]) => { const menuMap = new Map<number, Menu.ResMenuList>() // 构建菜单项的映射,以menuId作为键 menuItems.forEach((item) => { if (!menuMap.has(item.menuId)) { menuMap.set(item.menuId, { ...item, children: [] }) } }) // 构建树状结构 const tree: Menu.ResMenuList[] = [] menuItems.forEach((item) => { const menuItem = menuMap.get(item.menuId) if (menuItem) { if (item.parentId === 0) { tree.push(menuItem) } else { const parentItem = menuMap.get(item.parentId) if (parentItem) { parentItem.children.push(menuItem) } } } }) return tree } </script>
// Package types implements all the types used by the Service Item (Wii Sports Club) protocol package types import ( "bytes" "fmt" "strings" "github.com/PretendoNetwork/nex-go" ) // ServiceItemUserInfo holds data for the Service Item (Wii Sports Club) protocol type ServiceItemUserInfo struct { nex.Structure NumTotalEntryTicket uint32 ApplicationBuffer []byte } // ExtractFromStream extracts a ServiceItemUserInfo structure from a stream func (serviceItemUserInfo *ServiceItemUserInfo) ExtractFromStream(stream *nex.StreamIn) error { var err error serviceItemUserInfo.NumTotalEntryTicket, err = stream.ReadUInt32LE() if err != nil { return fmt.Errorf("Failed to extract ServiceItemUserInfo.NumTotalEntryTicket from stream. %s", err.Error()) } serviceItemUserInfo.ApplicationBuffer, err = stream.ReadQBuffer() if err != nil { return fmt.Errorf("Failed to extract ServiceItemUserInfo.ApplicationBuffer from stream. %s", err.Error()) } return nil } // Bytes encodes the ServiceItemUserInfo and returns a byte array func (serviceItemUserInfo *ServiceItemUserInfo) Bytes(stream *nex.StreamOut) []byte { stream.WriteUInt32LE(serviceItemUserInfo.NumTotalEntryTicket) stream.WriteQBuffer(serviceItemUserInfo.ApplicationBuffer) return stream.Bytes() } // Copy returns a new copied instance of ServiceItemUserInfo func (serviceItemUserInfo *ServiceItemUserInfo) Copy() nex.StructureInterface { copied := NewServiceItemUserInfo() copied.SetStructureVersion(serviceItemUserInfo.StructureVersion()) copied.NumTotalEntryTicket = serviceItemUserInfo.NumTotalEntryTicket copied.ApplicationBuffer = serviceItemUserInfo.ApplicationBuffer return copied } // Equals checks if the passed Structure contains the same data as the current instance func (serviceItemUserInfo *ServiceItemUserInfo) Equals(structure nex.StructureInterface) bool { other := structure.(*ServiceItemUserInfo) if serviceItemUserInfo.StructureVersion() != other.StructureVersion() { return false } if serviceItemUserInfo.NumTotalEntryTicket != other.NumTotalEntryTicket { return false } if !bytes.Equal(serviceItemUserInfo.ApplicationBuffer, other.ApplicationBuffer) { return false } return true } // String returns a string representation of the struct func (serviceItemUserInfo *ServiceItemUserInfo) String() string { return serviceItemUserInfo.FormatToString(0) } // FormatToString pretty-prints the struct data using the provided indentation level func (serviceItemUserInfo *ServiceItemUserInfo) FormatToString(indentationLevel int) string { indentationValues := strings.Repeat("\t", indentationLevel+1) indentationEnd := strings.Repeat("\t", indentationLevel) var b strings.Builder b.WriteString("ServiceItemUserInfo{\n") b.WriteString(fmt.Sprintf("%sstructureVersion: %d,\n", indentationValues, serviceItemUserInfo.StructureVersion())) b.WriteString(fmt.Sprintf("%sNumTotalEntryTicket: %d,\n", indentationValues, serviceItemUserInfo.NumTotalEntryTicket)) b.WriteString(fmt.Sprintf("%sApplicationBuffer: %x,\n", indentationValues, serviceItemUserInfo.ApplicationBuffer)) b.WriteString(fmt.Sprintf("%s}", indentationEnd)) return b.String() } // NewServiceItemUserInfo returns a new ServiceItemUserInfo func NewServiceItemUserInfo() *ServiceItemUserInfo { return &ServiceItemUserInfo{} }
package com.example.studentsecurity.entity; import jakarta.persistence.*; @Entity @Table(name = "student") public class StudentEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="first_name") private String firstName; @Column(name="last_name") private String lastName; @Column(name="email") private String email; @Column(name="course") private String course; @Column(name="gpa") private Double gpa; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public Double getGpa() { return gpa; } public void setGpa(Double gpa) { this.gpa = gpa; } }
<script> /*----------------------------------- * Array *------------------------------------ */ //将ary拆分成size长度的区块,返回拆分后的二维数组 function chunk(ary, size = 1) { if (size >= ary.length) { return [ary.slice()] } let res = [] let len = ary.length for (let i = 0; i < len; i += size) { let temp = [] let end = (i + size) <= len ? i + size : len //end取不到 for (let j = i; j < end; j++) { temp.push(ary[j]) } res.push(temp) } return res } //返回无假值数组 假值:false、null、0、''、undefined、NaN function compact(ary) { let res = [] for (let i = 0; i < ary.length; i++) { if (ary[i]) { res.push(ary[i]) } } return res } //有展平一层的功能 function concat(ary, ...args) { let res = ary.slice() for (let i = 0; i < args.length; i++) { let item = args[i] if (Array.isArray(item)) { for (let j = 0; j < item.length; j++) { res.push(item[j]) } } else { res.push(item) } } return res } function method(path, ...args) { path = toPath(path) return function(v, k, o, ...args) { if(!(path[0] in v) || path.length < 1) { return } for(let i = 1; i < path.length; i++) { v = v[path[i - 1]] if((!path[i] in v)) { return } } return v[path[path.length - 1]] } } function range(start = 0, end, step = 1) { let result = [] start = Number(start) end = Number(end) step = Number(step) start = isNumber(start) && !isNaN(start) ? start : 0 end = isNumber(end) && !isNaN(end) ? end : 0 step = isNumber(step) && !isNaN(step) ? step : 0 if (arguments.length == 0) { return result } else if (arguments.length == 1) { if (start >= 0) { for (let i = 0; i < start; i++) { result.push(i) } } else { for (let i = 0; i > start; i--) { result.push(i) } } } else if (arguments.length == 2) { if (start <= end) { for (let i = start; i < end; i++) { result.push(i) } } else { for (let i = start; i > end; i--) { result.push(i) } } } else if (arguments.length == 3) { if (step == 0) { result = Array(end - start > 0 ? end - start : 0).fill(start) } else { if (step > 0 && end - start > 0) { for (let i = start; i < end; i += step) { result.push(i) } } else if (step < 0 && end - start < 0) { for (let i = start; i > end; i += step) { result.push(i) } } } } return result } // 二维数组变一维 function flatten(ary) { let result = [] for (let i = 0; i < ary.length; i++) { let item = ary[i] if (Array.isArray(item)) { for (let it of item) { result.push(it) } } else { result.push(item) } } return result } //深度展平为一维数组 function flattenDeep(ary) { let res = [] for (let i = 0; i < ary.length; i++) { let item = ary[i] if (Array.isArray(ary[i])) { //如果是数组就展平成一维数组 item = flattenDeep(ary[i]) for (let j = 0; j < item.length; j++) { res.push(item[j]) } } else { res.push(item) } } return res } function flattenDeep2(ary) { let res = [] for (let i = 0; i < ary.length; i++) { res = res.concat(Array.isArray(ary[i]) ? flattenDeep2(ary[i]) : ary[i]) } return res } function flattenDeep3(ary) { return ary.reduce((res, item) => res.concat(Array.isArray(item) ? flattenDeep3(item) : item), []) } //根据depth递归减少ary的层级 function flattenDepth(ary, depth = 1) { if (depth == 0) { return ary.slice() } let res = [] for (let i = 0; i < ary.length; i++) { if (Array.isArray(ary[i])) { let item = flattenDepth(ary[i], depth - 1) for (let j = 0; j < item.length; j++) { res.push(item[j]) } } else { res.push(ary[i]) } } return res } function difference(ary, ...values) { var result = [] var valuesAry = flattenDeep(values) for (let i = 0; i < ary.length; i++) { if (!valuesAry.includes(ary[i])) { result.push(ary[i]) } } return result } // _.differenceBy(array, [values], [iteratee=_.identity]) function differenceBy(ary, ...values) { var differ = values[values.length - 1] var valuesAry if (!Array.isArray(differ)) { differ = iteratee(differ) //_.property valuesAry = flattenDeep(values.slice(0, -1)).map((it) => differ(it)) } else { differ = identity // it => it valuesAry = flattenDeep(values).map((it) => differ(it)) } var result = [] for (let i = 0; i < ary.length; i++) { if (!valuesAry.includes(differ(ary[i], i))) { result.push(ary[i]) } } return result } function differenceWith(ary, ...values) { var differWith = values[values.length - 1] if (Array.isArray(differWith)) { differWith = isEqual values = flattenDeep(values) } else { //not ary, but function values = flattenDeep(values.slice(0, -1)) } return ary.filter(it => { for (let item of values) { if (differWith(it, item)) { return false } } return true }) } function intersection(...arys) { var ary = arys[0] var values = arys.slice(1) var result = [] for (var value of values) { //values二维数组 for (var item of ary) { if (value.includes(item)) { result.push(item) } } } return result } //_.intersectionBy([arrays], [iteratee=_.identity]) function intersectionBy(...arys) { var predicate = arys[arys.length - 1] var ary = arys[0] var values if (Array.isArray(predicate)) { //没传iteratee predicate = identity values = flattenDeep(arys.slice(1)).map(it => predicate(it)) } else { predicate = iteratee(predicate) values = flattenDeep(arys.slice(1, -1)).map(it => predicate(it)) } var result = [] for (let i = 0; i < ary.length; i++) { if (values.includes(predicate(ary[i]))) { result.push(ary[i]) } } return result } function intersectionWith(ary, ...arrays) { let comparator = arrays[arrays.length - 1] if (Array.isArray(comparator)) { comparator = isEqual arrays = flattenDeep(arrays) } else { comparator = iteratee(comparator) //maybe it needs arrays = flattenDeep(arrays.slice(0, -1)) } return ary.filter(it => { for (var item of arrays) { if (comparator(it, item)) { return true } } return false }) } //找到第一个插入位置 the lowest index at which value should be inserted into array in order to maintain its sort order. // _.sortedIndex(30, 40);返回NaN _.sortedIndex('512', 40);返回3 _.sortedIndex(30, 40);返回1 function sortedIndex(ary, value) { //ary为sorted if (!Array.isArray(ary) && typeof ary != 'string') { return NaN } let start = 0, end = ary.length; //不包括end //最后要取什么?取start:因为end取不到且end代表前面是>=value的位置。到最后只可能从[30,40,40]的前一个40的mid值返回,或者其他例子:[30,40,40,60] [40,40,40] 皆从 return mid处返回。 [50,50],80,从return start处返回 while (start < end) { let mid = (start + end) >> 1 if (value < ary[mid]) { end = mid } else if (value > ary[mid]) { start = mid + 1 } else { //相等 if (ary[mid - 1] != value) { return mid } else { end = mid } } } return start //start = end... [50,50],80。 这个位置即大于等于又小于value } //找到第一个插入位置 //sortedIndexBy([1,2,3,3,4,4,5],3) => 2 function sortedIndexBy(ary, value, predicate = identity) { if (!Array.isArray(ary) && typeof ary != 'string') { return NaN } predicate = iteratee(predicate) let v = predicate(value) let left = 0, right = ary.length //有可能插到ary.length while (left < right) { let mid = (left + right) >> 1 //奇数项正中间,偶数项右半部分第一个 let midVal = predicate(ary[mid]) if (midVal < v) { left = mid + 1 } else if (midVal > v) { right = mid } else { if ((mid - 1) < 0 || predicate(ary[mid - 1]) != v) { //(mid -1)<0说明left = mid = 0,找到最前面了且ary[mid - 1]无效索引值 return mid } else { //前面还有相等的 right = mid } } } return left //找到最右边了,即ary[ary.length - 1] < value //找到最左边了,即ary[right]>value } //binary search on a sorted ary. find first index of val which was in ary // sortedIndexOf([4, 5, 5, 5, 6], 5); => 1 function sortedIndexOf(ary, val) { if (val == undefined) { return -1 } let begin = 0, end = ary.length while (begin < end) { let mid = (begin + end) >> 1 if (ary[mid] >= val) { end = mid } else { begin = mid + 1 } } //begin为第一个大于等于val的位置 if (ary[begin] === val) { return begin } return -1 } //the highest index at which value should be inserted into array in order to maintain its sort order. //sortedLastIndex([4, 5, 5, 5, 6], 5); => 4 function sortedLastIndex(ary, val) { if (!Array.isArray(ary) && typeof ary != 'string') { return NaN } if (Number(val) != val) { return 0 } let begin = 0, end = ary.length while (begin < end) { let mid = (begin + end) >> 1 if (ary[mid] > val) { end = mid } else { begin = mid + 1 } } return begin } //every element of ary has been sorted by predicate in past time. function sortedLastIndexBy(ary, val, predicate = identity) { if (!Array.isArray(ary) && typeof ary != 'string') { return NaN } predicate = iteratee(predicate) let v = predicate(val) let begin = 0, end = ary.length while (begin < end) { let mid = (begin + end) >> 1 if (predicate(ary[mid]) > v) { end = mid } else { begin = mid + 1 } } return begin } //sortedLastIndexOf([4, 5, 5, 5, 6], 5) => 3 function sortedLastIndexOf(ary, val) { if (!Array.isArray(ary) || typeof val != 'number') { return -1 } //法1.找最后插入位置,看前项是否为val //法2.直接在相等时分情况讨论,能够出来循环说明begin=end,指向的值一定不等于val let begin = 0, end = ary.length while (begin < end) { let mid = (begin + end) >> 1 if (ary[mid] < val) { begin = mid + 1 } else if (ary[mid] > val) { end = mid } else { if (ary[mid + 1] != val) { return mid } else { begin = mid + 1 } } } return -1 } // a string can be dealed yet.This ary has been sorted. function sortedUniq(ary) { if ((!Array.isArray(ary) && typeof ary != 'string') || ary.length == 0) { return [] } if (typeof ary == 'string') { ary = ary.split('') } //方法1. res=ary.slice(),双指针游走,最后res.length = slow指针 //方法2. 遍历ary,ary[i]不等res的最后一项,res就把此项拿过来.时间复杂度是方法1的1/2,空间复杂度更少一点. let res = [ary[0]] //be careful with undefined because of ary.length = 0 let ri = 0, len = ary.length for (let i = 1; i < len; i++) { if (res[ri] !== ary[i]) { res[++ri] = ary[i] } } return res } function sortedUniqBy(ary, predicate = identity) { if ((!Array.isArray(ary) && typeof ary != 'string') || ary.length == 0) { return [] } if (typeof ary == 'string') { ary = ary.split() } let res = [ary[0]] predicate = iteratee(predicate) let ri = 0, len = ary.length for (let i = 1; i < len; i++) { if (predicate(res[ri]) !== predicate(ary[i])) { res[++ri] = ary[i] } } return res } //除了Set哈希表以外,去重都是n^2,最低不过nlogn(排序后遍历一遍) function uniq(ary) { // return Array.from(new Set(ary)) let set = new Set() for (let i = 0; i < ary.length; i++) { set.has(ary[i]) || set.add(ary[i]) } var result = [] for (var item of set) { result.push(item) } return result } // O(n^2)写法 function uniq2(ary) { let result = [] for (let i = 0; i < ary.length; i++) { if (!result.includes(ary[i])) { result.push(ary[i]) } } return result } //根据断言判断计算出的key是否相同,相同则去重 function uniqBy(ary, predicate = identity) { predicate = iteratee(predicate) let hashMap = new Map() for (let i = 0; i < ary.length; i++) { let key = predicate(ary[i], i, ary) hashMap.has(key) || hashMap.set(key, ary[i]) } let result = [] for (let item of hashMap) { result.push(item[1]) } return result } //xieran function uniqBy2(ary, predicate = identity) { predicate = iteratee(predicate) var result = [] var seen = new Set() for (var i = 0; i < ary.length; i++) { var computed = predicate(ary[i], i, ary) if (!seen.has(computed)) { result.push(ary[i]) seen.add(computed) } } return result } // _.uniqWith([{a:1,b:2},{a:2,b:5},{a:1,b:2},{a:2,b:5}],_.isEqual);返回[{a:1,b:2},{a:2,b:5}] //时间退化到O(n^2) function uniqWith(ary, comparator = isEqual) { if (ary.length < 1) { return [] } let result = [ary[0]] for (let i = 1; i < ary.length; i++) { let flag = true let item = ary[i] for (let j = 0; j < result.length; j++) { if (comparator(ary[j], item)) { flag = false //有重复 break } } if (flag) { result.push(ary[i]) } } return result } //xieran function uniqWith2(ary, comparator = isEqual) { var result = [] for (let i = 0; i < ary.length; i++) { if (!result.some(it => comparator(it, ary[i]))) { //遍历result,有一项和ary[i]深度相等就不放入result里 result.push(ary[i]) } } return result } //扔掉前0项的新数组 function drop(ary, n = 1) { return ary.slice(n) } //扔掉最后n项的新数组 function dropRight(ary, n = 1) { if (n >= ary.length) { return [] } else if (n <= 0) { return ary.slice() } return ary.slice(0, ary.length - n) } //前面通过测验的略过,从第一个没有通过测验的开始拿 function dropWhile(ary, predicate = identity) { predicate = iteratee(predicate) for (var i = 0; i < ary.length; i++) { if (!predicate(ary[i], i, ary)) { break } } return ary.slice(i) // i [0,length] } //从后向前测,删除通过的元素直至第一个没通过的元素出现 function dropRightWhile(ary, predicate = identity) { predicate = iteratee(predicate) for (var i = ary.length - 1; i >= 0; i--) { if (!predicate(ary[i], i, ary)) { break } } return ary.slice(0, i + 1) } function findIndex(ary, predicate = identity, fromIndex = 0) { predicate = iteratee(predicate) for (let i = fromIndex; i < ary.length; i++) { if (predicate(ary[i], i, ary)) { return i } } return -1 } function findLastIndex(ary, predicate = identity, fromIndex = ary.length - 1) { predicate = iteratee(predicate) for (let i = fromIndex; i >= 0; i--) { if (predicate(ary[i], i, ary)) { return i } } return -1 } function fromPairs(pairs) { var result = {} for (var item of pairs) { result[item[0]] = item[1] } return result } function head(ary) { return ary[0] } function indexOf(ary, val, fromIndex = 0) { for (let i = fromIndex; i < ary.length; i++) { if (ary[i] === val) { return i } } return -1 } function lastIndexOf(ary, val, fromIndex = ary.length - 1) { for (let i = fromIndex; i >= 0; i--) { if (val === ary[i]) { return i } } return -1 } function initial(ary) { let len = ary.length - 1 let result = [] for (let i = 0; i < len; i++) { result.push(ary[i]) } return result } function tail(ary) { let res = [] for (let i = 1; i < ary.length; i++) { res.push(ary[i]) } return res } function last(ary) { return ary[ary.length - 1] } function join(ary, separator = ',') { let str = '' for (let i = 0; i < ary.length - 1; i++) { str += ary[i].toString() + separator } str += ary[ary.length - 1] return str } function nth(ary, n = 0) { if (n < 0) { n = n + ary.length } return ary[n] } //移除和values相等的全部值 function pull(ary, ...values) { let set = new Set(values) let temp = [] for (let i = 0; i < ary.length; i++) { if (!set.has(ary[i])) { temp.push(ary[i]) } } ary = temp return ary } function pullAll(ary, values) { let set = new Set(values) let temp = [] for (let i = 0; i < ary.length; i++) { if (!set.has(ary[i])) { temp.push(ary[i]) } } ary = temp return ary } function pullAllBy(ary, values, predicate = identity) { predicate = iteratee(predicate) values = new Set(values.map(it => predicate(it))) ary = ary.filter(it => { var val = predicate(it) return !values.has(val) }) return ary } function pullAllWith(ary, values, comparator = isEqual) { ary = ary.filter(it => { for (let value of values) { if (comparator(it, value)) { return false } } return true }) return ary } function fill(ary, value, start = 0, end = ary.length) { for (let i = start; i < end; i++) { ary[i] = value } return ary } function reverse(ary) { let left = 0, right = ary.length - 1 while (left < right) { let temp = ary[left] ary[left] = ary[right] ary[right] = temp left++ right-- } return ary } //这里对数组的zip是挑选相同位置的元素归为一组 //允许每个数组长度不一,选最大长度数组迭代,没有值填入undefined function zip(...args) { let res = [] let maxLength = 0 for (let i = 0; i < args.length; i++) { maxLength = args[i].length > maxLength ? args[i].length : maxLength } for (let i = 0; i < maxLength; i++) { let temp = [] for (let j = 0; j < args.length; j++) { temp.push(args[j][i]) } res.push(temp) } return res } /* zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { return a + b + c; }); => [111, 222] */ function zipWith(...arys) { let predicate = arys.pop() if (typeof predicate != 'function') { arys.push(predicate) predicate = identity } let result = [] for (let i = 0; i < arys[0].length; i++) { let item = predicate.apply(null, arys.reduce((param, ary) => { param.push(ary[i]) return param }, [])) result.push(item) } return result } function unzip(ary) { let res = [] let len = ary[0].length for (let i = 0; i < len; i++) { let temp = [] for (let j = 0; j < ary.length; j++) { temp.push(ary[j][i]) } res.push(temp) } return res } function unzipWith(ary, predicate = identity) { predicate = iteratee(predicate) //ary is like as [[1, 10, 100], [2, 20, 200]] let res = [] let resLen = ary[0].length for (let i = 0; i < resLen; i++) { let temp = [] for (let j = 0; j < ary.length; j++) { temp.push(ary[j][i]) } let val = predicate.apply(null, temp) res.push(val) } return res } //zipObject(['a', 'b'], [1, 2]); => { 'a': 1, 'b': 2 } function zipObject(props = [], values = []) { if (typeof props != 'string' && !Array.isArray(props)) { return {} } let res = {} for (let i = 0; i < props.length; i++) { res[props[i]] = values[i] } return res } /*有点麻,Deep会误导人去想递归*/ function zipObjectDeep(props = [], values = []) { let res = {} for (let i = 0; i < props.length; i++) { let propAry = toPath(props[i]) let resPointer = res if (propAry.length > 0) { for (let j = 0; j < propAry.length - 1; j++) { if (Number(propAry[j + 1]) == propAry[j + 1] && !resPointer[propAry[j]]) { resPointer[propAry[j]] = [] } else if (!resPointer[propAry[j]]) { resPointer[propAry[j]] = {} } resPointer = resPointer[propAry[j]] } resPointer[propAry[propAry.length - 1]] = values[i] } } return res } // using `SameValueZero` for equality comparisons.Unique values is collected in order of ARYS. function union(...arys) { let res = [] arys.forEach(ary => { ary.forEach(val => { if (!res.includes(val)) { res.push(val) } }) }) return res } function unionBy(...arys) { let mapper = identity if (!Array.isArray(arys[arys.length - 1])) { mapper = arys.pop() } mapper = iteratee(mapper) let res = [] let compareRes = [] arys.forEach(ary => { ary.forEach(val => { let compareVal = mapper(val) if (!compareRes.includes(compareVal)) { compareRes.push(compareVal) res.push(val) } }) }) return res } //The comparator is invoked with two arguments: (arrVal, othVal). function unionWith(...arys) { let comparator = isEqual if (!Array.isArray(arys[arys.length - 1])) { comparator = arys.pop() } let result = [] arys.forEach(ary => { ary.forEach(item => { let flag = true forEach(result, val => { if (comparator(val, item)) { flag = false return false } }) if (flag) { result.push(item) } }) }) return result } // using SameValueZero for equality comparisons.filter ary has,but values dont have function without(ary, ...values) { let res = [] ary.forEach(item => { if (!values.includes(item)) { res.push(item) } }) return res } //ary.slice(1,~) function take(ary, n = 1) { if ((!Array.isArray(ary) && typeof ary != 'string') || n == 0) { return [] } if (typeof ary == 'string') { ary = ary.split('') } if (n > ary.length) { n = ary.length } else if (n < 0) { n = 0 } return ary.slice(0, n) } // 从前向后探测predicate(val),如不符合,结束探测 function takeWhile(ary, predicate = identity) { if (!Array.isArray(ary) && typeof ary == 'string') { return [] } if (typeof ary == 'string') { ary = ary.split('') } predicate = iteratee(predicate) let res = [], len = ary.length for (let i = 0; i < len; i++) { if (predicate(ary[i], i, ary)) { res.push(ary[i]) } else { break } } return res } //ary.slice(ary.length - n) function takeRight(ary, n = 1) { if ((!Array.isArray(ary) && typeof ary != 'string') || n == 0) { return [] } if (typeof ary == 'string') { ary = ary.split('') } let start = ary.length - n if (start < 0) { start = 0 } return ary.slice(start) } //从后向前探测predicate(val),如果不符合则探测结束 function takeRightWhile(ary, predicate = identity) { if (!Array.isArray(ary) && typeof ary != 'string') { return [] } if (typeof ary == 'string') { ary = split('') } predicate = iteratee(predicate) let res = [] for (let i = ary.length - 1; i >= 0; i--) { if (predicate(ary[i], i, ary)) { res.push(ary[i]) } else { break } } return res.reverse() } //异或:所有数组的值中只出现一次//数组交集后的补集取并集 //写法1,利用浏览器的map.forEach实现 function xor(...arys) { let map = new Map() let res = [] for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { if (map.has(ary[j])) { map.set(ary[j], 2) } else { map.set(ary[j], 1) } } } } map.forEach((v, k) => { //map.forEach能够保证遍历顺序是存入顺序 if (v == 1) { res.push(k) } }) return res } //写法2,非信任的map遍历 function xor2(...arys) { let map = new Map() let res = [] for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { if (map.has(ary[j])) { map.set(ary[j], 2) } else { map.set(ary[j], 1) } } } } for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { if (map.get(ary[j]) == 1) { res.push(ary[j]) } } } } return res } //space exchange time(timeless first) function xorBy(...arys) { let predicate if (Array.isArray(arys[arys.length - 1])) { predicate = identity } else { predicate = iteratee(arys.pop()) } let map = new Map() let res = [] for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { let val = predicate(ary[j]) if (map.has(val)) { map.set(val, 2) } else { map.set(val, 1) } } } } //非信任map.forEach写法 for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { let val = predicate(ary[j]) if (map.get(val) == 1) { res.push(ary[j]) } } } } return res } //没办法化为O(n)了,只能O(n^2) function xorWith(...arys) { let comparator if (typeof arys[arys.length - 1] == 'function') { comparator = arys.pop() } else { comparator = isEqual } let res = [] for (let i = 0; i < arys.length; i++) { let ary = arys[i] if (Array.isArray(ary)) { for (let j = 0; j < ary.length; j++) { let val = ary[j] let pushFlag = true //对比 for (let p = 0; p < arys.length; p++) { let aryTest = arys[p] if (Array.isArray(aryTest)) { for (let q = 0; q < aryTest.length; q++) { if (p == i && q == j) { continue } let valTest = aryTest[q] if (comparator(val, valTest)) { pushFlag = false break } } if (!pushFlag) { break } } } if (pushFlag) { res.push(val) } } } } return res } /* --------------------------Array-------------------------- */ /*----------------------------------- * Collection *------------------------------------ */ function groupBy(collection, predicate = identity) { if (typeof predicate == 'string') { predicate = property(predicate) // property(propPath) } let res = {} for (var cKey in collection) { var key = predicate(collection[cKey], cKey, collection) if (Array.isArray(res[key])) { res[key].push(collection[cKey]) } else { res[key] = [collection[cKey]] } } return res } //会出现覆盖的情况,即res.length <= collection.length function keyBy(collection, predicate = identity) { if (typeof predicate == 'string') { predicate = iteratee(predicate) } let res = {} for (var cKey in collection) { var key = predicate(collection[cKey], cKey, collection) res[key] = collection[cKey] } return res } //遍历对象自有可枚举属性 function forEach(collection, predicate = identity) { // forOwn(collection, action) predicate = iteratee(predicate) for (var key in collection) { if (predicate(collection[key], key, collection) === false) break } return collection } function forEachRight(collection, predicate = identity) { let keys = Object.keys(collection) for (let i = keys.length - 1; i >= 0; i--) { if (predicate(collection[keys[i]], keys[i], collection) == false) { break } } return collection } //_.map([1,2,3],function(v,i,o) {return v+i+o.length*2}) =>  [7, 9, 11] // lodash的map对于数组的key来说有Number(key)的行为,所以仍需划分obj还是ary function map(collection, mapper = identity) { // if (typeof mapper === 'string') { // mapper = property(mapper) //_.property('a.b') // } mapper = iteratee(mapper) var result = [] if (Array.isArray(collection)) { for (let i = 0; i < collection.length; i++) { result.push(mapper(collection[i], i, collection)) } } else { for (var key in collection) { if (collection.hasOwnProperty(key)) { result.push(mapper(collection[key], key, collection)) } } } return result } function filter(collection, predicate) { predicate = iteratee(predicate) var result = [] for (var key in collection) { if (predicate(collection[key], key, collection) === true) { result.push(collection[key]) } } return result } //支持对象reduce function reduce(collection, reducer = identity, initial) { let keyAry = [] for (let key in collection) { //对象也可能从1开始数 if (collection.hasOwnProperty(key)) { keyAry.push(key) } } //等同于Object.keys(collection) let startIdx = 0 if (arguments.length == 2) { startIdx = 1 initial = collection[keyAry[0]] } for (let i = startIdx; i < keyAry.length; i++) { initial = reducer(initial, collection[keyAry[i]], keyAry[i], collection) } return initial } function reduceRight(collection, reducer = identity, initial) { let keyAry = [] for (let key in collection) { if (collection.hasOwnProperty(key)) { keyAry.push(key) } } let len = keyAry.length let startIdx = len - 1 if (arguments.length == 2) { startIdx = len - 2 initial = collection[keyAry[len - 1]] } for (let i = startIdx; i >= 0; i--) { initial = reducer(initial, collection[keyAry[i]], keyAry[i], collection) } return initial } function every(collection, test = identity) { test = iteratee(test) for (var key in collection) { if (!test(collection[key])) { return false } } return true } function every1(ary, test) { let len = ary.length for (let i = 0; i < len; i++) { if (!test(ary[i], i)) { return false } } return true } function every2(ary, test) { return ary.reduce((res, item, idx) => { return res && test(item, idx) }, true) } function every3(ary, test) { return !some(ary, (item, idx) => { return !test(item, idx) }) } function some(collection, test = identity) { test = iteratee(test) for (var item of collection) { if (test(item)) { return true } } return false } function some1(ary, test) { let len = ary.length for (let i = 0; i < len; i++) { if (test(ary[i], i)) { return true } } return false } function some2(ary, test) { return ary.reduce((res, item, idx) => { return res || test(item, idx) }, false) } //随机打乱顺序 Fisher-Yates Shuffle function shuffle(collection) { let res = [] for (var k in collection) { res.push(collection[k]) } let len = res.length - 1 for (let i = len; i >= 0; i--) { let idx = Math.random() * (i + 1) | 0 swap(res, idx, i) } return res } function swap(ary, i, j) { let t = ary[i] ary[i] = ary[j] ary[j] = t return ary } //lodash可以取出对象里的值进行排序,返回新数组 function sortBy(collection, ary) { //ary could be [function(o) { return o.user; }] or ['user', 'age'] //need a compare func function compare(a, b, ary, idx = 0) { if (typeof ary[idx] == 'function') { if (ary[idx](a) < ary[idx](b)) { return -1 } else if (ary[idx](a) > ary[idx](b)) { return 1 } else { if (idx < ary.length - 1) { return compare(a, b, ary, idx + 1) } else { return 0 } } } if (typeof ary[idx] == 'string') { if (a[ary[idx]] < b[ary[idx]]) { return -1 } else if (a[ary[idx]] > b[ary[idx]]) { return 1 } else { if (idx < ary.length - 1) { return compare(a, b, ary, idx + 1) } else { return 0 } } } } // need return a new array if (typeof collection == 'object') { if (Array.isArray(collection)) { collection = collection.slice() } else { let temp = [] for (let k in collection) { if (collection.hasOwnProperty(k)) { temp.push(collection[k]) } } collection = temp } } //insertion sort for (let i = 1; i < collection.length; i++) { let temp = collection[i] for (var j = i - 1; j >= 0; j--) { if (compare(temp, collection[j], ary) < 0) { collection[j + 1] = collection[j] } else { break } } collection[j + 1] = temp } return collection } //创建一个数组,以谓词处理的结果升序排列。需要稳定排序。collection可以是Array|Object一个可迭代的集合。predicate谓词是函数。 function sortByWrong(collection, predicate = identity) { let res = [] if (!collection) { return [] } //插入排序是稳定的 if (Array.isArray(collection)) { for (let i = 1; i < collection.length; i++) { let t = collection[i] let temp = predicate(collection[i], i) for (var j = i - 1; j >= 0; j--) { if (predicate(collection[j]) > temp) { collection[j + 1] = collection[j] } else { break } } collection[j + 1] = t } //排好序了,按照特定格式输出 for (let i = 0; i < collection.length; i++) { let temp = [] for (let k in collection[i]) { temp.push(collection[i][k]) } res.push(temp) } } return res } // 根据谓词计数,谓词可以是函数也可以是属性 function countBy2(collection, predicate = identity) { if (typeof predicate === 'function') { return collection.reduce((res, item, idx) => { let key = predicate(item, idx) if (!(key in res)) { res[key] = 1 } else { res[key] += 1 } return res }, {}) } else { //把predicate当做一个属性看待 return collection.reduce((res, item, idx) => { let key = item[predicate] if (!(key in res)) { res[key] = 1 } else { res[key] += 1 } return res }, {}) } } //重构countBy,lodash里的collection似乎只支持函数 function countBy(collection, predicate = identity) { predicate = iteratee(predicate) //maybe need _.property return collection.reduce((accum, item, idx, collection) => { let key = predicate(item) if (key in accum) { accum[key]++ } else { accum[key] = 1 } return accum }, {}) } function find(collection, test = identity, fromIdx = 0) { test = iteratee(test) if (Array.isArray(collection)) { if (fromIdx < 0) { fromIdx += collection.length fromIdx = fromIdx < 0 ? 0 : fromIdx } for (let i = fromIdx; i < collection.length; i++) { if (test(collection[i], i, collection)) { return collection[i] } } } else { //object let count = 0 if (fromIdx < 0) { fromIdx += Object.keys(collection).length fromIdx = fromIdx < 0 ? 0 : fromIdx } for (let key in collection) { if (count >= fromIdx) { if (test(collection[key], key, collection)) { return collection[key] } } count++ } } return } //从右向前找到第一个元素. 这个函数可以用Object.keys简化代码 function findLast(collection, predicate = identity, fromIndex = collection.length - 1) { predicate = iteratee(predicate) let midAry = collection if (!Array.isArray(collection)) { midAry = reduce(collection, (accum, val, key) => { accum.push([key, val]) return accum }, []) } if (fromIndex >= midAry.length) { fromIndex = midAry.length - 1 } else if (fromIndex < 0) { fromIndex += midAry.length fromIndex = fromIndex < 0 ? 0 : fromIndex } if (Array.isArray(collection)) { for (let i = fromIndex; i >= 0; i--) { if (predicate(midAry[i], i, collection)) { return midAry[i] } } } else { for (let i = fromIndex; i >= 0; i--) { if (predicate(midAry[i][1], midAry[i][0], collection)) { return midAry[i][1] } } } return } //Creates a flattened array of values by running each element in collection thru iteratee and flattening the mapped results. function flatMap(collection, predicate = identity) { predicate = iteratee(predicate) let midAry = [] for (let key in collection) { midAry.push(predicate(collection[key], key, collection)) } return flatten(midAry) } function flatMapDeep(collection, predicate = identity) { predicate = iteratee(predicate) let midAry = [] for (let key in collection) { midAry.push(predicate(collection[key], key, collection)) } return flattenDeep(midAry) } function flatMapDepth(collection, predicate = identity, depth = 1) { predicate = iteratee(predicate) let midAry = [] for (let key in collection) { midAry.push(predicate(collection[key], key, collection)) } return flattenDepth(midAry, depth) } function includes(collection, val, fromIndex = 0) { if (typeof collection == 'string' && typeof val != 'string') { return false } let keys = Object.keys(collection) //string有效 if (fromIndex < 0) { fromIndex += keys.length fromIndex = fromIndex < 0 ? 0 : fromIndex } if (typeof collection == 'string') { let end = collection.length - val.length for (let i = fromIndex; i < end; i++) { let subStr = collection.substr(i, val.length) if (subStr == val) { return true } } } else { if (isNaN(val)) { for (let i = fromIndex; i < keys.length; i++) { if (isNaN(collection[keys[i]])) { return true } } } else { for (let i = fromIndex; i < keys.length; i++) { if (val === collection[keys[i]]) { return true } } } } return false } //内置函数路由,考察用字符串寻找函数名 function invokeMap(collection, path, ...args) { let result = [] let predicate let everyFlag = false if (Array.isArray(path)) { predicate = property(path) } else if (typeof path == 'function') { predicate = path } else if (typeof path == 'string') { everyFlag = true // 对每个元素调用元素上的方法,such as sort, reverse,and so on... for (let i = 0; i < path.length; i++) { if (path[i] == '[' || path[i] == '.') { everyFlag = false break } } if (!everyFlag) { predicate = property(path) // [a].b[0].c } } for (let key in collection) { if (collection.hasOwnProperty(key)) { if (everyFlag) { predicate = collection[key].__proto__[path] } let item = predicate.apply(collection[key], args) result.push(item) } } return result } //asc is default, dont need key but only value. function orderBy(collection, comparators = [identity], orders = ['asc']) { while (orders.length < comparators.length) { orders.push('asc') } //compare can assert relative position between a and b, this func will iterate all of functions in 'comparators'. function compare(a, b, ary, orderAry, idx = 0) { if (typeof ary[idx] == 'function') { if ((ary[idx](a) < ary[idx](b) && orderAry[idx] == 'asc') || (ary[idx](a) > ary[idx](b) && orderAry[idx] == 'desc')) { return -1 } else if ((ary[idx](a) > ary[idx](b) && orderAry[idx] == 'asc') || (ary[idx](a) < ary[idx](b) && orderAry[idx] == 'desc')) { return 1 } else if (idx < ary.length) { return compare(a, b, ary, orderAry, idx + 1) } else { return 0 } } else if (typeof ary[idx] == 'string') { if ((a[ary[idx]] < b[ary[idx]] && orderAry[idx] == 'asc') || (a[ary[idx]] > b[ary[idx]] && orderAry[idx] == 'desc')) { return -1 } else if ((a[ary[idx]] > b[ary[idx]] && orderAry[idx] == 'asc') || (a[ary[idx]] < b[ary[idx]] && orderAry[idx] == 'desc')) { return 1 } else if (idx < ary.length) { return compare(a, b, ary, orderAry, idx + 1) } else { return 0 } } else { return 0 //In this case that typeof every item in ary are neither func and string, we think a equals with b. By myself but not lodash official. } } //stable swapper algorithm need iterate array but not object, and return value belongs to type of array. if (typeof collection == 'object') { if (Array.isArray(collection)) { collection = collection.slice() } else { let temp = [] for (let k in collection) { //dont need key but only value if (collection.hasOwnProperty(k)) { temp.push(collection[k]) } } collection = temp } } else { console.log('collection parameter is wrong type!'); return collection } for (let i = 1; i < collection.length; i++) { let selectVal = collection[i] for (var j = i - 1; j >= 0; j--) { if (compare(selectVal, collection[j], comparators, orders) < 0) { collection[j + 1] = collection[j] } else { break } } collection[j + 1] = selectVal } return collection } //two groups: [true group, false group]. The predicate is invoked with one argument: (value). function partition(collection, predicate = identity) { predicate = iteratee(predicate) let result = [ [], [] ] for (let k in collection) { if (collection.hasOwnProperty(k)) { if (predicate(collection[k]) == true) { result[0].push(collection[k]) } else { result[1].push(collection[k]) } } } return result } //the opposite of filter(). function reject(collection, predicate = identity) { predicate = iteratee(predicate) let result = [] for (let key in collection) { if (collection.hasOwnProperty(key)) { if (predicate(collection[key], key, collection) == false) { result.push(collection[key]) } } } return result } //Gets a random element from collection. function sample(collection) { let keys = Object.keys(collection) let len = keys.length let idx = Math.random() * len | 0 return collection[keys[idx]] } // we need n * sample function sampleSize(collection, n = 1) { let keys = Object.keys(collection) let len = keys.length if (n <= 0) { return [] } else if (n > len) { n = len } let result = [] while (n) { let idx = Math.random() * keys.length | 0 swap(keys, idx, keys.length - 1) result.push(collection[keys.pop()]) n-- } return result } //Object.keys完成了for in + hasOwnProperty function size(collection) { if (collection && typeof collection == 'object') { if (Array.isArray(collection)) { return collection.length } return Object.keys(collection).length } else if (typeof collection == 'string') { return collection.length } return } //-------------------Collection-------------------------- /*----------------------------------- * Date *------------------------------------ */ /*----------------------------------- * Function *------------------------------------ */ //可跳跃绑定的bind bind.placeholder = window; function bind(f, thisArg, ...fixedArgs) { //bind(f, {}, 1, 2, _, 3, _, 4) return function(...args) { // 5,8, 9,10 var parameters = fixedArgs.slice() var j = 0 for (var i = 0; i < parameters.length; i++) { if (Object.is(parameters[i], bind.placeholder)) { //Object.is()能够做到NaN===NaN if (j < args.length) { parameters[i] = args[j++] } else { parameters[i] = undefined } } } while (j < args.length) { parameters.push(args[j++]) } return f.apply(thisArg, parameters) } } //延迟 1ms执行func function defer(func, ...args) { let timerId = setTimeout(() => { func.apply(null, args) }) return timerId - 1 } //setTimeout会自动进行'1000' => 1000,里面应该是用了Number()而非parseInt function delay(func, wait, ...args) { let timerId = setTimeout(() => { func.apply(null, args) }, wait) return timerId - 1 } //-----------------Function-------------------- /*----------------------------------- * Lang *------------------------------------ */ //判断obj是否全包含src,src的每个属性及值都在obj上找到并相等.支持深层 //测试用例 isMatch({a:1,b:2,c:3,d:{x:1,y:2}}, {b:2,d:{x:1}}) function isMatch(obj, src) { if (obj === src) { return true } if ((typeof obj == 'object') + (typeof src == 'object') == 1) { //不是都为对象 return false //lodash规则奇怪,src可以不是对象,也返回true } for (var key in src) { if (src.hasOwnProperty(key)) { if (typeof src[key] !== 'object') { if (!obj.hasOwnProperty(key) || obj[key] !== src[key]) { return false } } else { //src[key]是Object,深层判断 if (src[key] === null && obj[key] !== null) { return false } else if (!isMatch(obj[key], src[key])) { return false } } } } return true } function isMatchWith(obj, src, customizer = function() {}) { if (customizer(obj, src) || obj === src) { return true } if ((typeof obj == 'object') + (typeof src == 'object') == 1) { return false } for (let key in src) { if (src.hasOwnProperty(key)) { if (!obj.hasOwnProperty(key)) { return false } else { if (customizer(obj[key], src[key], key, obj, src)) { continue } if (typeof src[key] != 'object') { return src[key] === obj[key] } else { if ((src[key] === null) + (obj[key] === null) === 1) { return false } else if (!isMatchWith(obj[key], src[key], customizer)) { return false } } } } } return true } function isEqual(a, b) { if (a === b) { return true } var typea = typeof a var typeb = typeof b if (typea !== typeb) { //类型不同 return false } else { //类型相同,同为obj if (typea === 'object') { //数组、对象 if (Array.isArray(a) + Array.isArray(b) == 1) { //一个数组一个不是数组 return false } if (Array.isArray(a)) { //两个数组 if (a.length !== b.length) { return false } } else { //两个对象 if (Object.keys(a).length !== Object.keys(b).length) { return false } } for (let key in a) { if (!(key in b)) { return false } if (!isEqual(a[key], b[key])) { return false } } return true } else { return a == b } } } function isGreeting(val) { return /^h(?:i|ello)$/.test(val) } //The customizer is invoked with up to six arguments: (objValue, othValue [, index|key, object, other, stack]). function customizer(objValue, othValue, idx, obj, other, stack) { if (isGreeting(objValue) && isGreeting(othValue)) { return true } //否则返回undefined } // If customizer returns undefined, comparisons are handled by the method instead. function isEqualWith(val, other, customizer = function() {}) { if (customizer(val, other) || val === other) { //maybe undefined return true } let typeVal = typeof val let typeOther = typeof other if (typeVal != typeOther) { return false } else { if (val && typeVal == 'object') { let valKeys = keys(val) let otherKeys = keys(other) if (valKeys.length != otherKeys.length) { return false } for (let key in val) { if (val.hasOwnProperty(key)) { if (!other.hasOwnProperty(key)) { return false } if (customizer(val[key], other[key], key, val, other)) { //比较函数比较不出来会返回undefined,再进行相等比较 continue } if (!isEqualWith(val[key], other[key])) { return false } } } return true } else { return customizer(val, other) || val == other } } } //存疑 全局isNaN(undefined)=true,Number.isNaN(undefined)=false, // 全局 isNaN(new Number(NaN))=true Number.isNaN(new Number(NaN)) = false //该函数只检测作为数字的NaN。NaN与new Number(NaN) function isNaN(val) { if (typeof val === 'object') { return val.valueOf() !== val.valueOf() } return val !== val } function isNil(val) { if (val === null || val === undefined) { return true } return false } function isUndefined(val) { if (val === undefined) return true return false } function isNull(val) { if (val === null) { return true } return false } //Checks if value is classified as a Function object. function isFunction(val) { if (typeof val == 'function') { return true } return false } function isArguments(val) { return toString.call(val) === '[object Arguments]' } function isArray(val) { return toString.call(val) === '[object Array]' } function isArrayBuffer(val) { //指定字节长度的ArrayBuffer对象,表示通用的、固定长度的二进制数据缓冲区 return Object.prototype.toString.call(val) === '[object ArrayBuffer]' } //检测值是否为类数组,只要不是function且有有效length属性即可,包括字符串 function isArrayLike(val) { if (typeof val == 'function') { return false } //val.hasOwnProperty('length') document.body.children的length属性是个继承来的getter,故document.body.children.__proto__.hasOwnProperty('length')为true if (val.length >= 0 && val.length <= Number.MAX_SAFE_INTEGER) { //53位 return true } return false } //类数组对象:对象里有有效的length属性且不是函数对象 function isArrayLikeObject(val) { if (val && typeof val == 'object') { if (val.length >= 0 && val.length <= Number.MAX_SAFE_INTEGER) { return true } } return false } function isBoolean(val) { return Object.prototype.toString.call(val) === '[object Boolean]' } function isDate(val) { return Object.prototype.toString.call(val) === '[object Date]' } //dom元素从html开始皆继承于ELement.prototype function isElement(val) { while (val) { if (val.__proto__ == Element.prototype) { return true } val = val.__proto__ } return false } //https://lodash.com/docs/4.17.15#isEmpty //原子类型、对象、类数组对象、Map、Set function isEmpty(val) { if (typeof val != 'object' || !val) { return true } if (Object.prototype.toString(val) !== '[object Object]') { if (('size' in val && val.size == 0) || ('length' in val && val.length == 0)) { return true } return false } if (typeof val == 'object') { for (let key in val) { if (val.hasOwnProperty(key)) { return false } } return true } } //EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError object. function isError(val) { while (val) { if (val.__proto__ === Error.prototype) { return true } val = val.__proto__ } return false } //写法二 不循环 function isError2(val) { if (Object.prototype.toString.call(val) == '[object Error]') { return true } return false } //Number.MAX_VALUE + 10**(308-16) === Infinity //IEEE754规定,大于1.7976931348623158e+308的数才为Infinity.同 Number.isFinite(),不会进行强制转换 function isFinite(val) { if (typeof val == 'number' && Math.abs(val) !== Infinity) { return true } return false } //同 Number.isInterger() function isInteger(val) { // return val === (val | 0) //没法判断64位数 return typeof val == 'number' && val - Math.floor(val) === 0 } //类数组对象可用length,范围0到4字节 function toLength(val) { if (val >= 0) { if (val <= 4294967295) { // 2147483648 * 2 - 1 2^32 return val | 0 } return 4294967295 } return 0 } function isLength(val) { return val === toLength(val) } function isMap(val) { return Object.prototype.toString.call(val) == '[object Map]' } //Checks if value is a pristine native function. function isNative2(val) { if (val) { return val.__proto__ == Function.prototype } return false } function isNative(val) { return Object.prototype.toString.call(val) == '[object Function]' } // exclude Infinity, -Infinity, and NaN function isNumber(val) { if (Math.abs(val) == Infinity || val != val || isFinite(val)) { return true } return false } // (e.g. arrays, functions, objects, regexes, new Number(0), and new String('')) function isObject(val) { while (val) { if (val.__proto__ == Object.prototype) { return true } val = val.__proto__ } return false } //A value is object-like if it's not null and has a typeof result of "object". function isObjectLike(val) { if (val !== null && typeof val == 'object') { return true } return false } //朴素对象 function isPlainObject(val) { return val.__proto__ === Object.prototype || val.__proto__ === null } function toArray(value) { let res = [], type = typeof value if (type === 'object') { for (let k in value) { res.push(value[k]) } } else if (type === 'string') { for (let i = 0; i < value.length; i++) { res.push(value[i]) } } return res } function isRegExp(val) { return Object.prototype.toString.call(val) == '[object RegExp]' } //This method is based on Number.isSafeInteger. function isSafeInteger(val) { if (typeof val == 'number' && Math.round(val) === val && val >= Number.MIN_SAFE_INTEGER && val <= Number.MAX_SAFE_INTEGER) { //2^53 - 1 ~ -2^53 return true } return false } function isSet(val) { return Object.prototype.toString.call(val) == '[object Set]' } function isString(val) { //new String() is true return Object.prototype.toString.call(val) == '[object String]' } //Casts value as an array if it's not one. //array = [1, 2, 3]; console.log(_.castArray(array) === array);// => true function castArray(val) { if (arguments.length == 0) { return [] } if (Array.isArray(val)) { return val } else { return [val] } } //src属性对应着obj属性,src属性值是个检测obj属性值的函数。 function conformsTo(obj, src) { for (let key in src) { if (src.hasOwnProperty(key)) { if (!obj.hasOwnProperty(key) || !src[key](obj[key])) { return false } } } return true } //SameValueZero +0 === -0 === 0 function eq(val, other) { if (isNaN(val)) { return isNaN(other) } return val === other } // great than function gt(val, other) { if (val - other > Number.EPSILON) { return true } return false } function gte(val, other) { if (val - other > Number.EPSILON || Math.abs(val - other) < Number.EPSILON) { return true } return false } //如果other是String,就只解析它的第一位数字位,如果val也是String,就对比他俩的第一位 function lt(val, other) { let num1 = parseFloat(val) let type1 = typeof val let num2 = parseFloat(other) if (type1 != 'string' && type1 != 'number') { return false } if (typeof other == 'string') { if (num2 < 0) { num2 = parseFloat(other.substr(0, 2)) } if (type1 == 'string') { if (num1 < 0) { // num1 = parseFloat(val.subStr(0, 2)) //lt('-1','-5')=>true return true } else { //_.lt('1','-5')=>false _.lt('50','100')=>false _.lt('10','200')=>true if (num2 < 0) { return false } else { for (var i = 0; i < val.length; i++) { if (Number(val[i]) > Number(other[i])) { return false } } return true } } } else { return num1 < num2 } } else if (typeof other == 'number') { return num2 - num1 > Number.EPSILON } return false } function lte(val, other) { let type1 = typeof val let type2 = typeof other let num1 = parseFloat(val) let num2 = parseFloat(other) if (type1 == 'string' && type2 == 'string') { for (let i = 0; i < num1.length; i++) { if (!other[i] || val.charCodeAt(i) > other.charCodeAt(i)) { return false } } return true } else if ((type2 == 'number' && type1 == 'string') || (type1 == 'number' && type2 == 'string')) { return Number(val) <= Number(other) } else if (type2 == 'number' && type1 == 'number') { return Math.abs(other - val) < Number.EPSILON || other > val } return false } function isTypedArray(val) { if (!val) { return false } return Object.prototype.toString.call(val) === '[object Uint8Array]' } function isSymbol(val) { if (!val) { return false } return Object.prototype.toString.call(val) == '[object Symbol]' } function isWeakMap(val) { if (!val) { return false } return Object.prototype.toString.call(val) == '[object WeakMap]' } function isWeakSet(val) { if (!val) { return false } return Object.prototype.toString.call(val) == '[object WeakSet]' } function toFinite(val) { //Converts value to a finite number. if (Math.abs(val) == Infinity) { return val < 0 ? -Number.MAX_VALUE : Number.MAX_VALUE } return isNaN(Number(val)) ? 0 : Number(val) } /** * Let number be ? ToNumber(argument). * If number is NaN, return +0. * If number is +0, -0, +∞, or -∞, return number. * Return the number value that is the same sign as number and whose magnitude isfloor(abs(number)). */ // it will 去掉 last 位,正负数向0取整 function toInteger(val) { if (typeof val != 'number') { if (isNaN(Number(val))) { return +0 } val = Number(val) } if (Math.abs(val) == Infinity) { return val < 0 ? -Number.MAX_VALUE : Number.MAX_VALUE } return val < 0 ? -Math.floor(Math.abs(val)) : Math.floor(val) } function toNumber(val) { return Number(val) } //将srcs中每个src的实例可枚举属性 function assign(obj, ...srcs) { for (let i = 0; i < srcs.length; i++) { let src = srcs[i] if (typeof src == 'object') { for (let key in src) { if (src.hasOwnProperty(key)) { obj[key] = src[key] } } } } return obj } function assignIn(obj, ...srcs) { for (let i = 0; i < srcs.length; i++) { let src = srcs[i] if (typeof src == 'object') { for (let key in src) { obj[key] = src[key] } } } return obj } function toSafeInteger(val) { val = toInteger(val) if (val > Number.MAX_SAFE_INTEGER || val < Number.MIN_SAFE_INTEGER) { val = val < 0 ? Number.MIN_SAFE_INTEGER : Number.MAX_SAFE_INTEGER } return val } //----------------Lang----------------- /*----------------------------------- * Math *------------------------------------ */ function sum(ary) { let res = 0 for (let i = 0; i < ary.length; i++) { res += ary[i] } return res } function sum2(ary) { return ary.reduce((res, item) => { return res + item }) } function sum3(ary) { return sumBy(ary) } //根据谓词求和,谓词用来计算每项的值,或是在对象里作为属性传属性值 function sumBy(ary, predicate = identity) { //即predicate= it=>it predicate = iteratee(predicate) var result = 0 for (let i = 0; i < ary.length; i++) { result += predicate(ary[i], i, ary) } return result } function floor(num, precision = 0) { var digit = Math.pow(10, precision) var result = num * digit | 0 return result / digit } function max(ary) { if (isArray(ary)) { let result = ary.reduce((max, it) => { if (typeof it == 'string') { if (typeof max == 'number') { return Math.max(max, Number(it.charCodeAt(0))) } else if (typeof max == 'string') { return Math.max(Number(max)) } } else if (typeof it == 'number') { return Math.max() } }, -Infinity) } } function add(augend, addend) { return augend + addend } function ceil(number, precision = 0) { if (number == 0) { return 0 } if (!precision) { precision = 0 } precision = toInteger(precision) let result = number * Math.pow(10, precision) | 0 return result * Math.pow(10, -precision) == number ? result * Math.pow(10, -precision) : (result + 1) * Math.pow(10, -precision) } function ceilWrong(number, precision = 0) { // ???我在干嘛 if (number == 0) { return 0 } if (!precision) { // prevent undefined precision = 0 } precision = toInteger(precision) let absNumber = Math.abs(number) let sign = absNumber == number ? 1 : -1 let strNum = absNumber.toString() let dot = '.', dotIdx = strNum.length for (let i = 0; i < strNum.length; i++) { dotIdx = strNum[i] == dot ? i : dotIdx } if (precision >= 0) { if (dotIdx + precision >= strNum.length - 1) { return number } else { return Number(strNum.substr(0, dotIdx + precision + 1)) + 1 * Math.pow(10, -precision) } } else { //precision < 0 let dealedIdx = dotIdx - 1 dealedIdx = dealedIdx + precision if (dealedIdx > 0) { strNum.slice(0, dealedIdx) } } } function divide(dividend, devisor = 1) { dividend = Number(dividend) devisor = Number(devisor) return dividend / devisor } function max(ary) { if (typeof ary == 'string' || Array.isArray(ary)) { if (!ary.length) { return undefined } let max = -Infinity for (let i = 0; i < ary.length; i++) { max = ary[i] > max ? ary[i] : max } return max } return undefined } function maxBy(ary, predicate = identity) { predicate = iteratee(predicate) if (typeof ary == 'string' || Array.isArray(ary)) { if (!ary.length) { return undefined } let max = -Infinity, maxIdx = -1 for (let i = 0; i < ary.length; i++) { if (predicate(ary[i]) > max) { max = predicate(ary[i]) maxIdx = i } } if (maxIdx == -1) { return -Infinity } return ary[maxIdx] } return undefined } //average of ary function mean(ary) { if (!('length' in ary)) { return NaN } let len = ary.length let sumofAry = sum(ary) return sumofAry / len } function meanBy(ary, predicate = identity) { if (!('length' in ary)) { return NaN } let sum = 0 let len = ary.length predicate = iteratee(predicate) for (let i = 0; i < len; i++) { sum += predicate(ary[i]) } return sum / len } function min(ary) { if (typeof ary == 'string' || Array.isArray(ary)) { let len = ary.length if (!len) { return undefined } let result = Infinity for (let i = 0; i < len; i++) { result = ary[i] < result ? ary[i] : result } return result } return undefined } function minBy(ary, predicate = identity) { if (typeof ary == 'string' || Array.isArray(ary)) { let len = ary.length if (!len) { return undefined } predicate = iteratee(predicate) let min = Infinity, minIdx = -1 for (let i = 0; i < len; i++) { let val = predicate(ary[i]) if (val < min) { min = val minIdx = i } } if (minIdx == -1) { return Infinity } return ary[minIdx] } return undefined } function multiply(multiplier, multiplicand) { return multiplier * multiplicand } function round(number, precision = 0) { let temp = number * Math.pow(10, precision) let ft = Math.abs(temp - Math.floor(temp)) if (ft >= 0.5) { if (precision >= 0) { return Number(((Math.floor(temp) + 1) * Math.pow(10, -precision)).toFixed(precision)) } else { return (Math.floor(temp) + 1) * Math.pow(10, -precision) } } else { if (precision >= 0) { return Number((Math.floor(temp) * Math.pow(10, -precision)).toFixed(precision)) //round(0.25,1)=>0.30000000000000004× 0.3√ } else { return Math.floor(temp) * Math.pow(10, -precision) } } } function subtract(minuend, subtrahend) { return minuend - subtrahend } // -------------------Math-------------------- /*----------------------------------- * Number *------------------------------------ */ //类似夹逼定理的夹数 function clamp(num, lower, upper) { if (arguments.length == 2) { upper = lower return num > upper ? upper : num } else if (arguments.length == 3) { if (upper < lower) { return num < lower ? lower : num } else { if (num < lower) { return lower } else if (num >= lower && num < upper) { return num } else { return upper } } } else { return num } } //number is in range of [start, end) function inRange(number, start = 0, end) { if (arguments.length == 2) { end = start start = 0 } if (end < start) { let temp = start start = end end = temp } if (number >= start && number < end) { return true } return false } function random(lower = 0, upper = 1, floating = false) { if (typeof lower != 'number' && typeof lower != 'boolean') { lower = 0 } if (typeof upper != 'number' && typeof upper != 'boolean') { upper = 0 } if (lower - Math.floor(lower) > 0 || upper - Math.floor(upper) > 0) { floating = true } if (arguments.length == 0) { return Math.round(Math.random()) } if (arguments.length == 1) { if (typeof lower == 'number') { if (lower > 0) { upper = lower lower = 0 } else { upper = 0 } let result = lower + Math.random() * (upper - lower) if (floating) { return result } else { return Math.round(result) } } else { if (lower == true) { return Math.random() } else { return Math.round(Math.random()) } } } if (arguments.length == 2) { if (typeof upper == 'number') { if (upper < lower) { let temp = lower lower = upper upper = lower } let result = lower + Math.random() * (upper - lower) if (floating) { return result } else { return Math.round(result) } } else { //boolean if (upper == true) { floating = true } if (lower > 0) { upper = lower lower = 0 } else { upper = 0 } let result = lower + Math.random() * (upper - lower) if (floating) { return result } else { return Math.round(result) } } } if (arguments.length == 3) { if (lower > upper) { let temp = lower lower = upper upper = temp } let result = lower + Math.random() * (upper - lower) if (floating) { return result } else { return Math.round(result) } } } //----------------Number------------------ /*----------------------------------- * Object *------------------------------------ */ //获取object的'a.b.c'属性 //传参方式一:get(object, 'a[0].b.c',defalut) //传参方式二:get(object, ['a','0','b','c']) function get(object, path, defaultVal) { if (typeof path === 'string') { path = toPath(path) //将字符串path转为数组,如传参方式二 } for (let i = 0; i < path.length; i++) { if (object == undefined) { //null == undefined//true,或是循环中读到空。 不用reduce:reduce没有办法提前返回;null也读不到属性 return defaultVal } object = object[path[i]] } return object } //递归写法,获取object的path路径上的属性 function get2(object, path, defaultVal = undefined) { if (object == undefined) { //object传进来时可能为null,递归过程中可能为undefined return defaultVal } else if (path.length == 0) { return object } else { return get2(object[path[0]], path.slice(1), defaultVal) } } function forIn(obj, predicate = identity) { // predicate = for (var key in obj) { if (predicate(obj[key], key, obj) === false) { break } } return obj } function forInRight(obj, predicate = identity) { var keyAry = [] for (var key in obj) { keyAry.push(key) } for (let i = keyAry.length - 1; i >= 0; i--) { predicate(obj[keyAry[i]], keyAry[i], obj) if (predicate(obj[keyAry[i]], keyAry[i], obj) === false) { break } } return obj } function forOwn(obj, predicate = identity) { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (predicate(obj[key], key, obj) === false) { break } } } return obj } function forOwnRight(obj, predicate = identity) { var keyAry = [] for (var key in obj) { if (obj.hasOwnProperty(key)) { keyAry.push(key) } } for (let i = keyAry.length - 1; i >= 0; i--) { if (predicate(obj[keyAry[i]], keyAry[i], obj) === false) { break } } return obj } //将实例对象上的key:val变为[key,val] function toPairs(obj) { if (isMap(obj) || isSet(obj)) { return [...obj.entries()] } var result = [] for (let key in obj) { if (obj.hasOwnProperty(key)) { result.push([key, obj[key]]) } } return result } function toPairsIn(obj) { if (isMap(obj) || isSet(obj)) { return [...obj.entries()] } let result = [] // if(typeof obj[Symbol.iterator] == 'function'){ // // for(let item of obj) //需要生成器挂载到Object.prototype,并重写内容使其合法 // } for (let key in obj) { result.push([key, obj[key]]) } return result } //返回对象上的所有自有方法名组成的数组 function functions(obj) { var result = [] for (var key in obj) { if (obj.hasOwnProperty(key) && isFunction(obj[key])) { result.push(key) } } return result } //返回对象上所有 自有方法+原型继承方法的方法名组成的数组 function functionsIn(obj) { var result = [] for (let key in obj) { if (isFunction(obj[key])) { result.push(key) } } return result } function keys(obj) { let res = [] for (let k in obj) { if (obj.hasOwnProperty(k)) res.push(k) } return res } function keysIn(obj) { let res = [] for (let k in obj) { res.push(k) } return res } //对于obj的可枚举属性,依托断言函数修改这些属性名,返回新对象 function mapKeys(obj, mapper = identity) { let res = {} for (let k in obj) { if (obj.hasOwnProperty(k)) { res[mapper(obj[k], k, obj)] = obj[k] } } return res } //对于obj的可枚举属性,依托断言函数修改这些属性值,返回和原对象property相同的新对象 function mapValues(obj, mapper = identity) { mapper = iteratee(mapper) let res = {} for (let k in obj) { if (obj.hasOwnProperty(k)) { res[k] = mapper(obj[k], k, obj) } } return res } function mapValuesWrong(obj, mapper = identity) { mapper = iteratee(mapper) return reduce(obj, mapper, {}) } function values(obj) { let dealed = new Object(obj) let res = [] for (let k in dealed) { if (dealed.hasOwnProperty(k)) { res.push(dealed[k]) } } return res } function at(obj, path) { if (!Array.isArray(path) && typeof path != 'string') { return [] } let result = [] for (let i = 0; i < path.length; i++) { result.push(get(obj, path[i])) } return result } // 仅仅补全obj上不存在的属性啦 function defaults(obj, ...srcs) { for (let i = 0; i < srcs.length; i++) { let src = srcs[i] if (src && typeof src == 'object') { for (let key in src) { if (src.hasOwnProperty(key) && obj[key] == undefined) { obj[key] = src[key] } } } } return obj } function defaultsDeep(obj, ...srcs) { for (let i = 0; i < srcs.length; i++) { let src = srcs[i] if (src && typeof src == 'object') { for (let key in src) { if (src.hasOwnProperty(key)) { if (src[key] && typeof src[key] == 'object') { if (obj[key] === undefined) { obj[key] = {} } if (obj[key] && typeof obj[key] == 'object') { obj[key] = defaultsDeep(obj[key], src[key]) } } else { if (obj[key] === undefined) { obj[key] = src[key] } } } } } } return obj } function findKey(obj, predicate = identity) { predicate = iteratee(predicate) for (let key in obj) { if (predicate(obj[key], key, obj)) { return key } } } function findLastKey(obj, predicate = identity) { predicate = iteratee(predicate) let keys = Object.keys(obj) for (let i = keys.length - 1; i >= 0; i--) { if (predicate(obj[keys[i]], keys[i], obj)) { return keys[i] } } } function has(obj, path) { // own path = toPath(path) for (let i = 0; i < path.length; i++) { if (!obj.hasOwnProperty(path[i])) { return false } obj = obj[path[i]] } return true } function hasIn(obj, path) { //prototype included path = toPath(path) for (let i = 0; i < path.length; i++) { if (!(path[i] in obj)) { return false } obj = obj[path[i]] } return true } function invert(obj) { //no deep let result = {} let keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { let key = keys[i] result[obj[key]] = key } return result } function invertBy(obj, predicate = identity) { let result = {} let keys = Object.keys(obj) for (let i = 0; i < keys.length; i++) { //lodash很奇怪,By却不倒着遍历了 let key = predicate(obj[keys[i]]) let val = keys[i] if (key in result) { result[key].push(val) } else { result[key] = [val] } } return result } function invoke(obj, path, ...args) { path = toPath(path) for (var i = 0; i < path.length - 1; i++) { if (!(path[i] in obj)) { //insurance return -1 } obj = obj[path[i]] } return obj[path[i]].call(obj, ...args) } function merge(obj, ...srcs) { for (let i = 0; i < srcs.length; i++) { let src = srcs[i] for (let key in src) { if (src[key] && typeof src[key] == 'object' && obj[key] && typeof obj[key] == 'object') { obj[key] = merge(obj[key], src[key]) } else { obj[key] = src[key] } } } return obj } function mergeWith(obj, ...srcs) { let customizer = function() {} if (typeof srcs[srcs.length - 1] == 'function') { customizer = srcs.pop() } for (let i = 0; i < srcs.length; i++) { let src = srcs[i] for (let key in src) { let val = customizer(obj[key], src[key], key, obj, src) if (val === undefined) { if (src[key] && typeof src[key] == 'object' && obj[key] && typeof obj[key] == 'object') { obj[key] = mergeWith(obj[key], src[key]) } else { obj[key] = src[key] } } else { obj[key] = val } } } return obj } //就只剩path里没有的属性啦,每一项paths[i]都可能是数组||字符串,不deep只一层.toPath仅仅是解析成单个的属性 function omit(obj, ...paths) { let path = paths.reduce((accum, item) => { return accum.concat(toPath(item)) }, []) let pathSet = new Set(path) let result = {} for (let key in obj) { if (!pathSet.has(key)) { result[key] = obj[key] } } return result } function omitBy(obj, predicate = identity) { predicate = iteratee(predicate) let result = {} for (let key in obj) { if (predicate(obj[key], key) === false) { result[key] = obj[key] } } return result } function pick(obj, ...paths) { let path = paths.reduce((accum, item) => { return accum.concat(toPath(item)) }, []) let pathSet = new Set(path) let result = {} for (let key in obj) { if (pathSet.has(key)) { result[key] = obj[key] } } return result } function pickBy(obj, predicate = identity) { predicate = iteratee(predicate) let result = {} for (let key in obj) { if (predicate(obj[key], key) === true) { result[key] = obj[key] } } return result } function result(obj, path, defaultVal) { path = toPath(path) let flag = typeof defaultVal == 'function' if (obj == undefined) { return flag ? defaultVal.call(undefined) : defaultVal } for (let i = 0; i < path.length; i++) { let next = obj[path[i]] if (next == undefined) { return flag ? defaultVal.call(obj) : defaultVal } if (i == path.length - 1) { if (typeof next == 'function') { return next.call(obj) } } obj = next } return obj } function set(obj, path, val) { if (typeof obj != 'object' || !obj) { return obj } let p = obj path = toPath(path) for (var i = 0; i < path.length - 1; i++) { if (p.hasOwnProperty(path[i])) { p = p[path[i]] //可能这里还需要看看这一项是不是obj的type, } else { //p没有这一项,看看这一项应该是什么 let nextVal if (Number(path[i + 1]) == path[i + 1]) { nextVal = Array(Number(path[i + 1]) + 1) } else { nextVal = {} } p[path[i]] = nextVal p = p[path[i]] } } p[path[i]] = val return obj } function setWith(obj, path, val, customizer = function() {}) { //这个代码起码能够达到效果 path = toPath(path) if (customizer === Object) { let p = obj for (var i = 0; i < path.length - 1; i++) { let key = path[i] let nextVal = p[key] if (p.hasOwnProperty(key)) { if (typeof nextVal != 'object') { p[key] = {} } p = p[key] } else { p[key] = {} p = p[key] } } p[path[i]] = val return obj } else { return set(obj, path, val) } } //----------------------Object---------------------------- /*----------------------------------- * Seq *------------------------------------ */ /*----------------------------------- * String *------------------------------------ */ /*----------------------------------- * Util *------------------------------------ */ //根据不同类型生成不同的断言函数 function iteratee(maybePredicate) { if (typeof maybePredicate === 'function') { return maybePredicate } else if (typeof maybePredicate === 'string') { return property(maybePredicate) //输入属性,返回属性值 } else if (Array.isArray(maybePredicate)) { return matchesProperty(...maybePredicate) // 输入...[key,val],返回断言是否其超集 } else if (maybePredicate instanceof RegExp) { return isMatchByRegexp(maybePredicate) //输入正则,返回断言是否匹配string } else if (typeof maybePredicate === 'object') { return matches(maybePredicate) //输入对象,返回断言是否其超集 } } //传入什么属性名,它返回的函数就用来获取对象的属性值 function property(prop) { // return bind(get,null, _, prop) //当一个函数调用另一个函数,传入的参数不变的情况下,永远可以被优化为bind写法 return function(obj) { // return obj[prop] return get(obj, prop) //get(obj, path)得到深层路径下的属性值 } } //将String的路径转为数组 //假设路径合法, 'a[0].b.c[0][3][4].foo.bar[2]' ---> ['a','0','b','c','0','3','4','foo','bar'] 右括号必须遇到左括号或者.,单独的左括号和单独的. function toPath(val) { if (Array.isArray(val)) { return val } else { var res = val.split(/\]\[|\]\.|\.|\[|\]/) if (res[0] === '') { res.shift() } if (res[res.length - 1] === '') { res.pop() } return res } } function toPath2(val) { if (Array.isArray(val)) { return val } else { var result = val.split('][') .reduce((res, it) => res.concat(it.split('].')), []) .reduce((res, it) => res.concat(it.split('[')), []) .reduce((res, it) => res.concat(it.split('.')), []) var item = result[result.length - 1] if (item[item.length - 1] === ']') { //val最后属性为[2]时,该项为2],需要把]去掉 result[result.length - 1] = item.slice(0, item.length - 1) } return result } } //src为filter接收的对象,判断src是否是obj的子集.没有考虑深层次嵌套 //函数构造器matches,返回的函数传入的参数应是传入matches里的超集。不支持深层 function matches2(src) { return function(obj) { if (obj === src) { return true } for (var key in src) { if (!obj.hasOwnProperty(key) || obj[key] !== src[key]) { return false } } return true } } //对matches的优化改进,支持了深层比较 function matches(src) { // return bind(isMatch, null, window, src) return function(obj) { return isMatch(obj, src) } } //判断obj在path路径下的属性值与val是否深度相等 function matchesProperty(path, val) { return function(obj) { return isEqual(get(obj, path), val) } } //返回它自己 function identity(val) { return val } //调用iteratee n次,返回调用结果 function times(n, iteratee = identity) { let result = [] let idx = 0 while (n) { result.push(iteratee(idx)) idx++ n-- } return result } //常量函数,创建一个返回val的函数 function constant(val) { return function() { return val } } //------------------------Util--------------------- /*----------------------------------- * Properties *------------------------------------ */ /*----------------------------------- * Methods *------------------------------------ */ //递归下降parseJson str = '{"aa":"123","b":{"x":1,"y":[35,36,37],"z":null},"ccc":false}' function parseJson(str) { var i = 0 return parseValue() //将str的不同类型分发到各个函数 function parseValue() { var c = str[i] if (c === '[') { return parseArray() } if (c === '{') { return parseObject() } if (c === '"') { return parseString() } if (c === 't') { return parseTrue() } if (c === 'f') { return parseFalse() } if (c === 'n') { return parseNull() } return parseNumber() } function parseArray() { var thisAry = [] i++ while (str[i] !== ']') { var val = parseValue() thisAry.push(val) if (str[i] == ',') { i++ } } i++ return thisAry } function parseObject() { var thisObj = {} i++ while (str[i] !== '}') { var key = parseString() i++ var val = parseValue() thisObj[key] = val if (str[i] === ',') { i++ } } i++ return thisObj } function parseString() { var thisStr = '' i++ while (str[i] !== '"') { thisStr += str[i++] } i++ return thisStr } function parseNumber() { var thisNum = '' while (str[i] >= '0' && str[i] <= '9') { thisNum += str[i++] } return Number(thisNum) } function parseTrue() { var s = str.substr(i, 4) if (s === 'true') { i += 4 return true } else { throw new SyntaxError('unexpected token ' + s + ' in pos of ' + i) } } function parseFalse() { var s = str.substr(i, 5) if (s === 'false') { i += 5 return false } else { throw new SyntaxError('unexpected token ' + s + ' in pos of ' + i) } } function parseNull() { var s = str.substr(i, 4) if (s === 'null') { i += 4 return null } else { throw new SyntaxError('unexpected token ' + s + ' in pos of ' + i) } } } function stringifyJson(value) { if (value === null) { return null } else if (Array.isArray(value)) { let str = '[' for (let i = 0; i < value.length; i++) { str += stringifyJson(value[i]) + ',' } str = str.slice(0, -1) + ']' return str } else if (typeof value === 'object') { let str = '{' for (let key in value) { if (value.hasOwnProperty(key)) { if (value[key] === undefined) { continue } str += '"' + key + '":' + stringifyJson(value[key]) + ',' } } str = str.slice(0, -1) + '}' return str } else if (typeof value == 'string') { return '"' + value + '"' } else if (typeof value == 'number') { if (value !== value || Math.abs(value) === Infinity) { return null } return value } else if (typeof value == 'boolean') { return value ? 'true' : 'false' } else if (value === undefined || typeof value == 'function') { return null } } </script>
<?php declare(strict_types = 1); namespace Src\OutSourcing\User\Application\UseCases\Queries; use Src\Common\Domain\QueryInterface; use Src\OutSourcing\User\Domain\Model\User; use Src\OutSourcing\User\Domain\Policies\UserPolicy; use Src\OutSourcing\User\Domain\Repositories\UserRepositoryInterface; final class FindUserByIdQuery implements QueryInterface { private UserRepositoryInterface $repository; public function __construct( private readonly int $id, ) { $this->repository = app()->make(UserRepositoryInterface::class); } public function handle(): User { authorize('findUserById', UserPolicy::class); return $this->repository->findById($this->id); } }
create table products ( id serial primary key, name varchar(50), producer varchar(50), count integer default 0, price integer ); create table history_of_price ( id serial primary key, name varchar(50), price integer, date timestamp ); ---Триггер должен срабатывать после вставки данных, для любого товара и просто насчитывать налог на товар (нужно прибавить налог к цене товара). --Действовать он должен не на каждый ряд, а на запрос (statement уровень) create or replace function tax() returns trigger as $$ BEGIN update products set price = price + price * 0.2; return new; END; $$ LANGUAGE 'plpgsql'; create trigger tax_trigger after insert on products referencing new table as inserted for each statement execute procedure tax(); ---Триггер должен срабатывать до вставки данных и насчитывать налог на товар --(нужно прибавить налог к цене товара). Здесь используем row уровень. create or replace function tax_row() returns trigger as $$ BEGIN update products set price = price + price * 0.2 where id = (select id from inserted); return NEW; END; $$ LANGUAGE 'plpgsql'; create trigger tax_row_trigger after insert on products for each row execute procedure tax_row(); ---Нужно написать триггер на row уровне, который сразу после вставки продукта в таблицу products, --будет заносить имя, цену и текущую дату в таблицу history_of_price create or replace function history() returns trigger as $$ BEGIN insert into history_of_price(name, price, date) values (NEW.name,NEW.price,now()); return new; END; $$ LANGUAGE 'plpgsql'; create trigger history_trigger after insert on products FOR EACH ROW execute procedure history(); --За основу возьмите таблицу, с которой мы работали в описании. В описании мы рассмотрели вариант вставки данных, изменения данных. Добавьте процедуру и функцию, которая будет удалять записи. --Условия выбирайте сами – удаление по id, удалить если количество товара равно 0 и т.п. create or replace function f_delete_data(u_count integer, u_id integer) returns integer language 'plpgsql' as $$ declare result integer; begin ---Если кол-во меньше 10, то удаляем if u_count < 10 THEN delete from products where id = u_id; end if; return result; end; $$;
c# MineSweeper with a Twist This is a Python implementation of the classic Minesweeper game. The codebase consists of several key functions and components to create and play the game. ## Key Functions and Components Here's a brief overview of the key functions and components in the code: - **generate_mines():** This function generates 8 unique mine locations within a 7x7 grid. - **select_def(mines, defuser):** This function selects a defuser location and removes it from the list of generated mines. - **set_cols(letter):** A function to map letters (columns) to numerical indices. - **make_grid_game(mines, defuser):** Sets up the initial game grid with mines and the defuser. - **count_surrounding_mines(grid):** Counts the surrounding mines for each cell in the grid. - **game_look(display_unopened):** Displays the game's current state, including the grid and the number of mines left. - **game_options():** Displays the available game controls and options for the player. - **handle_user_choice():** Handles the player's input and game options. - **reveal_chosen_cell(display_unopened, actual_grid, reference_of_grid):** Reveals a chosen cell and handles game logic. - **expansion_mechanism(display_unopened, actual_grid, reference_of_grid, r, c):** Implements the expansion mechanism for the game. - **get_valid_coordinate():** Prompts the player for a valid coordinate input. - **flag_chosen_cell(display_unopened):** Allows the player to flag or unflag a cell. - **use_power_up(display_unopened, actual_grid, reference_of_grid, grid):** Handles the use of the defuser power-up. - **defuse_adjacent_mines(display_unopened, actual_grid, reference_of_grid, r, c):** Defuses adjacent mines when the defuser is used. - **count_flagged_cells(display_unopened):** Counts the cells flagged as mines. - **mines_initial(display_unopened):** Calculates the number of mines left based on flagged cells. - **check_game_state(display_unopened, actual_grid):** Checks the game's state for a win, loss, or ongoing. - **game_loop():** Executes the main game loop. ## Getting Started ### Prerequisites You need to have Python installed on your system to run this game. ## Explanation per Function **import itertools import random as rand from string import ascii_uppercase # Created function to generate 8 unique mine locations within a 7x7 grid def generate_mines(): return [ascii_uppercase[a] + str(b + 1) for a, b in rand.sample(list(itertools.product(range(7), repeat=2)), k=8)] # Function to select a defuser by technically removing it from the list of genererated mines def select_def(mines, defuser): mines.remove(defuser) return mines**
/** * Tween.js - Licensed under the MIT license * https://github.com/tweenjs/tween.js * ---------------------------------------------- * * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors. * Thank you all, you're awesome! */ var TWEEN = TWEEN || (function () { var _tweens = []; return { getAll: function () { return _tweens; }, removeAll: function () { _tweens = []; }, add: function (tween) { _tweens.push(tween); }, remove: function (tween) { var i = _tweens.indexOf(tween); if (i !== -1) { _tweens.splice(i, 1); } }, update: function (time, preserve) { if (_tweens.length === 0) { return false; } var i = 0; time = time !== undefined ? time : TWEEN.now(); while (i < _tweens.length) { if (_tweens[i].update(time) || preserve) { i++; } else { _tweens.splice(i, 1); } } return true; } }; })(); // Include a performance.now polyfill. // In node.js, use process.hrtime. if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') { TWEEN.now = function () { var time = process.hrtime(); // Convert [seconds, nanoseconds] to milliseconds. return time[0] * 1000 + time[1] / 1000000; }; } // In a browser, use window.performance.now if it is available. else if (typeof (window) !== 'undefined' && window.performance !== undefined && window.performance.now !== undefined) { // This must be bound, because directly assigning this function // leads to an invocation exception in Chrome. TWEEN.now = window.performance.now.bind(window.performance); } // Use Date.now if it is available. else if (Date.now !== undefined) { TWEEN.now = Date.now; } // Otherwise, use 'new Date().getTime()'. else { TWEEN.now = function () { return new Date().getTime(); }; } TWEEN.Tween = function (object) { var _object = object; var _valuesStart = {}; var _valuesEnd = {}; var _valuesStartRepeat = {}; var _duration = 1000; var _repeat = 0; var _repeatDelayTime; var _yoyo = false; var _isPlaying = false; var _reversed = false; var _delayTime = 0; var _startTime = null; var _easingFunction = TWEEN.Easing.Linear.None; var _interpolationFunction = TWEEN.Interpolation.Linear; var _chainedTweens = []; var _onStartCallback = null; var _onStartCallbackFired = false; var _onUpdateCallback = null; var _onCompleteCallback = null; var _onStopCallback = null; this.to = function (properties, duration) { _valuesEnd = properties; if (duration !== undefined) { _duration = duration; } return this; }; this.start = function (time) { TWEEN.add(this); _isPlaying = true; _onStartCallbackFired = false; _startTime = time !== undefined ? time : TWEEN.now(); _startTime += _delayTime; for (var property in _valuesEnd) { // Check if an Array was provided as property value if (_valuesEnd[property] instanceof Array) { if (_valuesEnd[property].length === 0) { continue; } // Create a local copy of the Array with the start value at the front _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]); } // If `to()` specifies a property that doesn't exist in the source object, // we should not set that property in the object if (_object[property] === undefined) { continue; } // Save the starting value. _valuesStart[property] = _object[property]; if ((_valuesStart[property] instanceof Array) === false) { _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings } _valuesStartRepeat[property] = _valuesStart[property] || 0; } return this; }; this.stop = function () { if (!_isPlaying) { return this; } TWEEN.remove(this); _isPlaying = false; if (_onStopCallback !== null) { _onStopCallback.call(_object, _object); } this.stopChainedTweens(); return this; }; this.end = function () { this.update(_startTime + _duration); return this; }; this.stopChainedTweens = function () { for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) { _chainedTweens[i].stop(); } }; this.delay = function (amount) { _delayTime = amount; return this; }; this.repeat = function (times) { _repeat = times; return this; }; this.repeatDelay = function (amount) { _repeatDelayTime = amount; return this; }; this.yoyo = function (yoyo) { _yoyo = yoyo; return this; }; this.easing = function (easing) { _easingFunction = easing; return this; }; this.interpolation = function (interpolation) { _interpolationFunction = interpolation; return this; }; this.chain = function () { _chainedTweens = arguments; return this; }; this.onStart = function (callback) { _onStartCallback = callback; return this; }; this.onUpdate = function (callback) { _onUpdateCallback = callback; return this; }; this.onComplete = function (callback) { _onCompleteCallback = callback; return this; }; this.onStop = function (callback) { _onStopCallback = callback; return this; }; this.update = function (time) { var property; var elapsed; var value; if (time < _startTime) { return true; } if (_onStartCallbackFired === false) { if (_onStartCallback !== null) { _onStartCallback.call(_object, _object); } _onStartCallbackFired = true; } elapsed = (time - _startTime) / _duration; elapsed = elapsed > 1 ? 1 : elapsed; value = _easingFunction(elapsed); for (property in _valuesEnd) { // Don't update properties that do not exist in the source object if (_valuesStart[property] === undefined) { continue; } var start = _valuesStart[property] || 0; var end = _valuesEnd[property]; if (end instanceof Array) { _object[property] = _interpolationFunction(end, value); } else { // Parses relative end values with start as base (e.g.: +10, -3) if (typeof (end) === 'string') { if (end.charAt(0) === '+' || end.charAt(0) === '-') { end = start + parseFloat(end); } else { end = parseFloat(end); } } // Protect against non numeric properties. if (typeof (end) === 'number') { _object[property] = start + (end - start) * value; } } } if (_onUpdateCallback !== null) { _onUpdateCallback.call(_object, value); } if (elapsed === 1) { if (_repeat > 0) { if (isFinite(_repeat)) { _repeat--; } // Reassign starting values, restart by making startTime = now for (property in _valuesStartRepeat) { if (typeof (_valuesEnd[property]) === 'string') { _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property]); } if (_yoyo) { var tmp = _valuesStartRepeat[property]; _valuesStartRepeat[property] = _valuesEnd[property]; _valuesEnd[property] = tmp; } _valuesStart[property] = _valuesStartRepeat[property]; } if (_yoyo) { _reversed = !_reversed; } if (_repeatDelayTime !== undefined) { _startTime = time + _repeatDelayTime; } else { _startTime = time + _delayTime; } return true; } else { if (_onCompleteCallback !== null) { _onCompleteCallback.call(_object, _object); } for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) { // Make the chained tweens start exactly at the time they should, // even if the `update()` method was called way past the duration of the tween _chainedTweens[i].start(_startTime + _duration); } return false; } } return true; }; }; TWEEN.Easing = { Linear: { None: function (k) { return k; } }, Quadratic: { In: function (k) { return k * k; }, Out: function (k) { return k * (2 - k); }, InOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k; } return - 0.5 * (--k * (k - 2) - 1); } }, Cubic: { In: function (k) { return k * k * k; }, Out: function (k) { return --k * k * k + 1; }, InOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); } }, Quartic: { In: function (k) { return k * k * k * k; }, Out: function (k) { return 1 - (--k * k * k * k); }, InOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return - 0.5 * ((k -= 2) * k * k * k - 2); } }, Quintic: { In: function (k) { return k * k * k * k * k; }, Out: function (k) { return --k * k * k * k * k + 1; }, InOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); } }, Sinusoidal: { In: function (k) { return 1 - Math.cos(k * Math.PI / 2); }, Out: function (k) { return Math.sin(k * Math.PI / 2); }, InOut: function (k) { return 0.5 * (1 - Math.cos(Math.PI * k)); } }, Exponential: { In: function (k) { return k === 0 ? 0 : Math.pow(1024, k - 1); }, Out: function (k) { return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k); }, InOut: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2); } }, Circular: { In: function (k) { return 1 - Math.sqrt(1 - k * k); }, Out: function (k) { return Math.sqrt(1 - (--k * k)); }, InOut: function (k) { if ((k *= 2) < 1) { return - 0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); } }, Elastic: { In: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI); }, Out: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1; }, InOut: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } k *= 2; if (k < 1) { return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI); } return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1; } }, Back: { In: function (k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, Out: function (k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, InOut: function (k) { var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); } }, Bounce: { In: function (k) { return 1 - TWEEN.Easing.Bounce.Out(1 - k); }, Out: function (k) { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; } else if (k < (2.5 / 2.75)) { return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; } else { return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; } }, InOut: function (k) { if (k < 0.5) { return TWEEN.Easing.Bounce.In(k * 2) * 0.5; } return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5; } } }; TWEEN.Interpolation = { Linear: function (v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); var fn = TWEEN.Interpolation.Utils.Linear; if (k < 0) { return fn(v[0], v[1], f); } if (k > 1) { return fn(v[m], v[m - 1], m - f); } return fn(v[i], v[i + 1 > m ? m : i + 1], f - i); }, Bezier: function (v, k) { var b = 0; var n = v.length - 1; var pw = Math.pow; var bn = TWEEN.Interpolation.Utils.Bernstein; for (var i = 0; i <= n; i++) { b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i); } return b; }, CatmullRom: function (v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); var fn = TWEEN.Interpolation.Utils.CatmullRom; if (v[0] === v[m]) { if (k < 0) { i = Math.floor(f = m * (1 + k)); } return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); } else { if (k < 0) { return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]); } if (k > 1) { return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); } return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); } }, Utils: { Linear: function (p0, p1, t) { return (p1 - p0) * t + p0; }, Bernstein: function (n, i) { var fc = TWEEN.Interpolation.Utils.Factorial; return fc(n) / fc(i) / fc(n - i); }, Factorial: (function () { var a = [1]; return function (n) { var s = 1; if (a[n]) { return a[n]; } for (var i = n; i > 1; i--) { s *= i; } a[n] = s; return s; }; })(), CatmullRom: function (p0, p1, p2, p3, t) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; var t2 = t * t; var t3 = t * t2; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; } } }; // UMD (Universal Module Definition) (function (root) { if (typeof define === 'function' && define.amd) { // AMD define([], function () { return TWEEN; }); } else if (typeof module !== 'undefined' && typeof exports === 'object') { // Node.js module.exports = TWEEN; } else if (root !== undefined) { // Global variable root.TWEEN = TWEEN; } })(this);