row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
43,171
docker local FROM another Dockerfile
8e0f772ce4a226269abe6d63ace06a61
{ "intermediate": 0.38391512632369995, "beginner": 0.2664394676685333, "expert": 0.34964537620544434 }
43,172
allocate a pointer to a pointer is not a valid reason to use dynamic allocation, why?
2e3539b16319447ceba5d3dffcb3f23d
{ "intermediate": 0.5270683765411377, "beginner": 0.165088951587677, "expert": 0.3078426718711853 }
43,173
Как сгенерировать запоминающиеся названия для ПК
7bf0180edb141fc63ce4cc269daed69a
{ "intermediate": 0.2765072286128998, "beginner": 0.2393103837966919, "expert": 0.4841824471950531 }
43,174
Hi
fb7ba441b43894c2152ddc25dedf6924
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
43,175
comment mettre en place le fait de pouvoir perdre sur le snake en flutter/dart, garde une architecture clean : import 'dart:math'; import 'package:flutter_snake/models/food_model.dart'; import 'package:flutter_snake/models/snake_model.dart'; class GameModel { static const int NB_CASES = 140; static const int NB_LIGNES = 14; static const int NB_COLONNES = 10; static const int DIRECTION_HAUT = 0; static const int DIRECTION_DROITE = 1; static const int DIRECTION_BAS = 2; static const int DIRECTION_GAUCHE = 3; static const int SNAKE_HEAD = 1; static const int SNAKE_BODY = 2; static const int FOOD = 3; int score = 0; int currentDirection = DIRECTION_DROITE; List<List<int>> grid = List.generate(NB_LIGNES, (i) => List.filled(NB_COLONNES, 0)); late FoodModel foodModel; late SnakeModel snakeModel; GameModel(){ foodModel = FoodModel(gameModel: this); snakeModel = SnakeModel(gameModel: this); } // Add your class properties and methods here void start(){ // on réinitialise la matrice for(int i = 0; i < NB_LIGNES; i++){ for(int j = 0; j < NB_COLONNES; j++){ grid[i][j] = 0; } } foodModel.createFood(); snakeModel.reset(); } static List<int> getRandomCoordinates(){ Random random = Random(); int randomX = random.nextInt(NB_COLONNES); int randomY = random.nextInt(NB_LIGNES); print("randomX: $randomX, randomY: $randomY"); return [randomX, randomY]; } void changeDirection(int newDirection){ currentDirection = newDirection; moveSnake(); } void moveSnake(){ snakeModel.moveSnake(currentDirection); } bool isFood(int x, int y){ return grid[y][x] == FOOD; } bool isInGrid(int x, int y){ return x >= 0 && x < NB_COLONNES && y >= 0 && y < NB_LIGNES; } void increaseScore(){ score++; } void eatFood(){} }import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_snake/models/game_model.dart'; class SnakePage extends StatefulWidget { const SnakePage({Key? key}) : super(key: key); @override State<SnakePage> createState() => _SnakePageState(); } class _SnakePageState extends State<SnakePage> { GameModel gameModel = GameModel(); Timer? timer; @override void initState() { // TODO: implement initState print("start"); gameModel.start(); timer = Timer.periodic(Duration(milliseconds: 500), (timer) { setState(() { gameModel.moveSnake(); }); }); } void resetTimer() { timer?.cancel(); timer = Timer.periodic(Duration(milliseconds: 500), (timer) { setState(() { gameModel.moveSnake(); }); }); } @override void dispose() { // TODO: implement dispose timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () { // TODO: Implement your back button logic here Navigator.pop(context); }, ), title: Text('Snake Game. Score: ' + gameModel.score.toString()), actions: <Widget>[ PopupMenuButton<String>( onSelected: (String result) { // TODO: Implement your menu actions here }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'Pause', child: Text('Pause'), ), const PopupMenuItem<String>( value: 'Replay', child: Text('Replay'), ), ], ), ], ), body: Column( children: <Widget>[ Expanded( flex: 7, child: Container( color: Colors.green, child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 10, // Change this number as per your need ), itemBuilder: (BuildContext context, int index) { int y = index ~/ GameModel.NB_COLONNES; int x = index - ((index ~/ GameModel.NB_COLONNES) * GameModel.NB_COLONNES); Color cellColor; switch (gameModel.grid[y][x]) { case GameModel.SNAKE_HEAD: cellColor = Colors.yellow; break; case GameModel.SNAKE_BODY: cellColor = Colors.green; break; case GameModel.FOOD: print(index.toString() + " " + x.toString() + " " + y.toString()); cellColor = Colors.red; break; default: cellColor = Colors.lightGreen; } return GridTile( child: Container( decoration: BoxDecoration( color: cellColor, border: Border.all(color: Colors.white), ), // TODO: Add your game cell here ), ); }, itemCount: GameModel.NB_CASES, // Change this number as per your need ), ), ), Expanded( flex: 2, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ ElevatedButton( onPressed: () { // TODO: Implement left direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_GAUCHE); }); }, child: Icon(Icons.arrow_left), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () { // TODO: Implement up direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_HAUT); }); }, child: Icon(Icons.arrow_upward), ), ElevatedButton( onPressed: () { // TODO: Implement down direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_BAS); }); }, child: Icon(Icons.arrow_downward), ), ], ), ElevatedButton( onPressed: () { // TODO: Implement right direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_DROITE); }); }, child: Icon(Icons.arrow_right), ), ], ), ), ], ), ); } } import 'dart:ffi'; import 'package:flutter_snake/models/game_model.dart'; class FoodModel{ GameModel gameModel; FoodModel({required this.gameModel}); void createFood(){ List<int> coordinates = GameModel.getRandomCoordinates(); gameModel.grid[coordinates[1]][coordinates[0]] = GameModel.FOOD; } }import 'package:flutter_snake/models/game_model.dart'; class SnakeModel{ int x; int y; int size = 1; GameModel gameModel; SnakeModel({required this.gameModel, this.x = 0, this.y = 0}); void reset(){ x = GameModel.NB_COLONNES ~/ 2; y = GameModel.NB_LIGNES ~/ 2; size = 2; displaySnake(); } void displaySnake(){ if (gameModel.isFood(x, y)){ growSnake(); gameModel.increaseScore(); gameModel.foodModel.createFood(); } gameModel.grid[y][x] = GameModel.SNAKE_HEAD; print("new snake head: x: $x, y: $y"); } void moveSnake(int direction){ switch(direction){ case GameModel.DIRECTION_HAUT: if (gameModel.isInGrid(x, y-1)){ gameModel.grid[y][x] = 0; y--; } break; case GameModel.DIRECTION_DROITE: if (gameModel.isInGrid(x+1, y)){ gameModel.grid[y][x] = 0; x++; } break; case GameModel.DIRECTION_BAS: if (gameModel.isInGrid(x, y+1)){ gameModel.grid[y][x] = 0; y++; } break; case GameModel.DIRECTION_GAUCHE: if (gameModel.isInGrid(x-1, y)){ gameModel.grid[y][x] = 0; x--; } break; } displaySnake(); } void growSnake(){ size++; } }
d43e32612e564b9f4fe434009c1f0cf0
{ "intermediate": 0.3139013350009918, "beginner": 0.4883827567100525, "expert": 0.19771592319011688 }
43,176
how to read from std::istringstream to enum value
25300b2dd7175cfb2982cf3f54555d77
{ "intermediate": 0.6024703979492188, "beginner": 0.19564582407474518, "expert": 0.20188377797603607 }
43,177
based on this code # -*- coding: utf-8 -*- """GPT_for_chatbot_main.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1_Jue7uz455TpSfZpBmX5O6MtUXIyQ6ZP """ from google.colab import drive drive.mount('/content/drive') ! pip install transformers import numpy as np from transformers import AutoTokenizer, AutoConfig, AutoModelForPreTraining, \ TrainingArguments, Trainer import torch from torch.utils.data import Dataset !pip install datasets from datasets import load_dataset dataset = load_dataset('daily_dialog') def load_conversations(data): context = [] response = [] for i in range(len(dataset[data])): for j in range(len(dataset[data][i]['dialog'])-1): context.append(dataset[data][i]['dialog'][j]) response.append(dataset[data][i]['dialog'][j+1]) return context, response SPECIAL_TOKENS = { "bos_token": "<|BOS|>", "eos_token": "<|EOS|>", "unk_token": "<|UNK|>", "pad_token": "<|PAD|>", "sep_token": "<|SEP|>"} MAXLEN = 60 class myDataset(Dataset): def __init__(self, data, tokenizer): context, response = [], [] for k, v in data.items(): context.append(v[0]) response.append(v[1]) self.tokenizer = tokenizer self.response = response self.context = context def __len__(self): return len(self.context) def __getitem__(self, i): input = SPECIAL_TOKENS['bos_token'] + self.context[i] + \ SPECIAL_TOKENS['sep_token'] + \ self.response[i] + SPECIAL_TOKENS['eos_token'] encodings_dict = tokenizer(input, truncation=True, max_length=MAXLEN, padding="max_length") input_ids = encodings_dict['input_ids'] attention_mask = encodings_dict['attention_mask'] return {'label': torch.tensor(input_ids), 'input_ids': torch.tensor(input_ids), 'attention_mask': torch.tensor(attention_mask)} tokenizer = AutoTokenizer.from_pretrained('gpt2') tokenizer.add_special_tokens(SPECIAL_TOKENS) config = AutoConfig.from_pretrained('gpt2', bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id, sep_token_id=tokenizer.sep_token_id, pad_token_id=tokenizer.pad_token_id, output_hidden_states=False) model = AutoModelForPreTraining.from_pretrained('gpt2', config=config) model.resize_token_embeddings(len(tokenizer)) model.cuda() context_train, response_train = load_conversations('train') context_val, response_val = load_conversations('validation') train_data = dict() i=0 for context, response in zip (context_train, response_train): train_data[i] = [context, response] i += 1 #******************************************** val_data = dict() i=0 for context, response in zip (context_val, response_val): val_data[i] = [context, response] i += 1 train_dataset = myDataset(train_data, tokenizer) val_dataset = myDataset(val_data, tokenizer) # load_model_path = '/content/drive/MyDrive/models/checkpoint-1000/pytorch_model.bin' # model.load_state_dict(torch.load(load_model_path)) training_args = TrainingArguments( output_dir="/content/drive/MyDrive/models", num_train_epochs=3, eval_steps = 2000, save_steps=2000, warmup_steps=500, prediction_loss_only=True, learning_rate = 5e-4, do_eval = True, evaluation_strategy = 'steps' ) trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, tokenizer=tokenizer ) trainer.train() trainer.save_model('/content/drive/MyDrive/final model') load_model_path = '/content/drive/MyDrive/models/checkpoint-26000/pytorch_model.bin' tokenizer = AutoTokenizer.from_pretrained('gpt2') tokenizer.add_special_tokens(SPECIAL_TOKENS) config = AutoConfig.from_pretrained('gpt2', bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id, sep_token_id=tokenizer.sep_token_id, pad_token_id=tokenizer.pad_token_id, output_hidden_states=False) model = AutoModelForPreTraining.from_pretrained('gpt2', config=config) model.resize_token_embeddings(len(tokenizer)) model.load_state_dict(torch.load(load_model_path)) model.cuda() model.eval() def generate_response(text): inp_context = SPECIAL_TOKENS['bos_token'] + text + SPECIAL_TOKENS['sep_token'] generated = torch.tensor(tokenizer.encode(inp_context)).unsqueeze(0) device = torch.device("cuda") generated = generated.to(device) sample_outputs = model.generate(generated, do_sample=True, top_k=0, min_length=5, max_length=30, num_return_sequences=10 ) for i, sample_output in enumerate(sample_outputs): text_gen = tokenizer.decode(sample_output, skip_special_tokens=True) a = len(text) print("{}: {}\n\n".format(i+1, text_gen)) return generate_response('Where have you been?') generate_response('What is your favourite color?') generate_response('What do you want to eat?') write it for this data { "conversations": [ { "conversation_id": "3c091d14-fd54-4e25-b1e3-d348f8dd73fb", "messages": [ { "name": "John Doe", "type": "customer", "message": "Hey, Jane! How's it going?" }, { "name": "agent 1", "type": "agent", "message": "Hey John! I'm good, thanks. How about you?" }, { "name": "John Doe", "type": "customer", "message": "Can't complain. Hey, do you happen to know what the minimum age is to open an account here?" }, { "name": "agent 1", "type": "agent", "message": "I think it's 18 years. At least that's what I was told when I opened mine." } ] }, { "conversation_id": "ad5e3b21-36a2-4c0f-b0b6-63f3816e0f4e", "messages": [ { "name": "Jane Doe", "type": "customer", "message": "Hi John! How have you been?" }, { "name": "agent 2", "type": "agent", "message": "Hey Jane! I've been good, thank you. How about yourself?" }, { "name": "Jane Doe", "type": "customer", "message": "Not too bad. By the way, do you know what the minimum balance is to maintain an account here?" }, { "name": "agent 2", "type": "agent", "message": "I believe it's $10. That's what they mentioned when I signed up." } ] }, { "conversation_id": "2c90e715-193e-4938-8153-f23fd1be9473", "messages": [ { "name": "Customer", "type": "customer", "message": "I wish to request chargeback" }, { "name": "Agent", "type": "agent", "message": "May I know the date, amount and merchant name?" }, { "name": "Customer", "type": "customer", "message": "The amount is 198.20 and date is: '10-OCT-2022' from" }, { "name": "Agent", "type": "agent", "message": "I have found this transaction and it is not qualified for chargeback, is there other transaction I can help you with" }, { "name": "Customer", "type": "customer", "message": "Yes, amount is amount 7849.90 from LG on December 12" } ] }, { "conversation_id": "7d2fb18d-9f29-4a8e-936a-7da06e5fb746", "messages": [ { "name": "Jack Williams", "type": "customer", "message": "Hello, I want to request a chargeback." }, { "name": "Agent 3", "type": "agent", "message": "May I know the date, amount and merchant name?" }, { "name": "Jack Williams", "type": "customer", "message": "The amount is 198.20 and date is: \"10-OCT-2022\" from " }, { "name": "Agent 3", "type": "agent", "message": "I have found this transaction and it is not qualified for chargeback, is there other transaction I can help you with" }, { "name": "Jack Williams", "type": "customer", "message": "Yes, amount is amount 7849.90 from LG on December 12" }, { "name": "Agent 3", "type": "agent", "message": "This transaction is qualified for chargeback, the reference ID is 304712, do you wish to proceed and do you agree with our terms of service?" } ] } ] }
da537bd159a2711d81d70aed9f0ca394
{ "intermediate": 0.3290996253490448, "beginner": 0.31484320759773254, "expert": 0.35605719685554504 }
43,178
что за ошибка? Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property '' of bean class [com.ncs.support.dto.CompanyDto]: Bean property '' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? at deployment.acq-support-web.war//org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:631) at deployment.acq-support-web.war//org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622) at deployment.acq-support-web.war//org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:99) at deployment.acq-support-web.war//org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:229) at deployment.acq-support-web.war//org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:118) at deployment.acq-support-web.war//org.springframework.web.servlet.tags.BindTag.doStartTagInternal(BindTag.java:117) at deployment.acq-support-web.war//org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80) at org.apache.jsp.tag.webinputField_tag.doTag(webinputField_tag.java:367)
5ca45be3a5b3bf9dd63711f5358a6567
{ "intermediate": 0.5696510672569275, "beginner": 0.25119563937187195, "expert": 0.17915333807468414 }
43,179
pourquoi depuis que j'essaie de gérer la taille du serpent qui s'agrandit j'ai cette erreur lorsque je vais sur la page du snake : "Bad state : No element. Qee also : https://fluter/.dev/docs/testing/errors" Voici le code utilisée : import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_snake/models/game_model.dart'; class SnakePage extends StatefulWidget { const SnakePage({Key? key}) : super(key: key); @override State<SnakePage> createState() => _SnakePageState(); } class _SnakePageState extends State<SnakePage> { GameModel gameModel = GameModel(); Timer? timer; @override void initState() { // TODO: implement initState print("start"); gameModel.start(); timer = Timer.periodic(Duration(milliseconds: 500), (timer) { setState(() { gameModel.moveSnake(); }); }); } void resetTimer() { timer?.cancel(); timer = Timer.periodic(Duration(milliseconds: 500), (timer) { setState(() { gameModel.moveSnake(); }); }); } @override void dispose() { // TODO: implement dispose timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () { // TODO: Implement your back button logic here Navigator.pop(context); }, ), title: Text('Snake Game. Score: ' + gameModel.score.toString()), actions: <Widget>[ PopupMenuButton<String>( onSelected: (String result) { // TODO: Implement your menu actions here }, itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[ const PopupMenuItem<String>( value: 'Pause', child: Text('Pause'), ), const PopupMenuItem<String>( value: 'Replay', child: Text('Replay'), ), ], ), ], ), body: Column( children: <Widget>[ Expanded( flex: 7, child: Container( color: Colors.green, child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 10, // Change this number as per your need ), itemBuilder: (BuildContext context, int index) { int y = index ~/ GameModel.NB_COLONNES; int x = index - ((index ~/ GameModel.NB_COLONNES) * GameModel.NB_COLONNES); Color cellColor; switch (gameModel.grid[y][x]) { case GameModel.SNAKE_HEAD: cellColor = Colors.yellow; break; case GameModel.SNAKE_BODY: cellColor = Colors.green; break; case GameModel.FOOD: print(index.toString() + " " + x.toString() + " " + y.toString()); cellColor = Colors.red; break; default: cellColor = Colors.lightGreen; } return GridTile( child: Container( decoration: BoxDecoration( color: cellColor, border: Border.all(color: Colors.white), ), // TODO: Add your game cell here ), ); }, itemCount: GameModel.NB_CASES, // Change this number as per your need ), ), ), Expanded( flex: 2, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ ElevatedButton( onPressed: () { // TODO: Implement left direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_GAUCHE); }); }, child: Icon(Icons.arrow_left), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () { // TODO: Implement up direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_HAUT); }); }, child: Icon(Icons.arrow_upward), ), ElevatedButton( onPressed: () { // TODO: Implement down direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_BAS); }); }, child: Icon(Icons.arrow_downward), ), ], ), ElevatedButton( onPressed: () { // TODO: Implement right direction logic setState(() { resetTimer(); gameModel.changeDirection(GameModel.DIRECTION_DROITE); }); }, child: Icon(Icons.arrow_right), ), ], ), ), ], ), ); } } import 'package:flutter_snake/models/game_model.dart'; class SnakeModel { int x; int y; int size = 1; GameModel gameModel; List<List<int>> bodyPositions = []; SnakeModel({required this.gameModel, this.x = 0, this.y = 0}); void reset() { x = GameModel.NB_COLONNES ~/ 2; y = GameModel.NB_LIGNES ~/ 2; size = 2; bodyPositions = [ [x, y], [y, x - 1] ]; displaySnake(); } void displaySnake() { if (gameModel.isFood(x, y)) { growSnake(); gameModel.increaseScore(); gameModel.foodModel.createFood(); } else { bodyPositions.removeLast(); } bodyPositions.insert(0, [x, y]); print("new snake head: x: $x, y: $y"); } void moveSnake(int direction) { switch (direction) { case GameModel.DIRECTION_HAUT: if (gameModel.isInGrid(x, y - 1)) { gameModel.grid[y][x] = 0; y--; } break; case GameModel.DIRECTION_DROITE: if (gameModel.isInGrid(x + 1, y)) { gameModel.grid[y][x] = 0; x++; } break; case GameModel.DIRECTION_BAS: if (gameModel.isInGrid(x, y + 1)) { gameModel.grid[y][x] = 0; y++; } break; case GameModel.DIRECTION_GAUCHE: if (gameModel.isInGrid(x - 1, y)) { gameModel.grid[y][x] = 0; x--; } break; } displaySnake(); } void growSnake() { size++; } } import 'dart:math'; import 'package:flutter_snake/models/food_model.dart'; import 'package:flutter_snake/models/snake_model.dart'; class GameModel { static const int NB_CASES = 140; static const int NB_LIGNES = 14; static const int NB_COLONNES = 10; static const int DIRECTION_HAUT = 0; static const int DIRECTION_DROITE = 1; static const int DIRECTION_BAS = 2; static const int DIRECTION_GAUCHE = 3; static const int SNAKE_HEAD = 1; static const int SNAKE_BODY = 2; static const int FOOD = 3; int score = 0; int currentDirection = DIRECTION_DROITE; List<List<int>> grid = List.generate(NB_LIGNES, (i) => List.filled(NB_COLONNES, 0)); late FoodModel foodModel; late SnakeModel snakeModel; GameModel() { foodModel = FoodModel(gameModel: this); snakeModel = SnakeModel(gameModel: this); } // Add your class properties and methods here void start() { // on réinitialise la matrice for (int i = 0; i < NB_LIGNES; i++) { for (int j = 0; j < NB_COLONNES; j++) { grid[i][j] = 0; } } foodModel.createFood(); _displaySnakeBody(); } static List<int> getRandomCoordinates() { Random random = Random(); int randomX = random.nextInt(NB_COLONNES); int randomY = random.nextInt(NB_LIGNES); print("randomX: $randomX, randomY: $randomY"); return [randomX, randomY]; } void changeDirection(int newDirection) { currentDirection = newDirection; moveSnake(); } void moveSnake() { snakeModel.moveSnake(currentDirection); } bool isFood(int x, int y) { return grid[y][x] == FOOD; } bool isInGrid(int x, int y) { return x >= 0 && x < NB_COLONNES && y >= 0 && y < NB_LIGNES; } void increaseScore() { score++; } void _displaySnakeBody() { for (var position in snakeModel.bodyPositions) { int y = position[0]; int x = position[1]; grid[y][x] = GameModel.SNAKE_BODY; } var head = snakeModel.bodyPositions.first; grid[head[0]][head[1]] = GameModel.SNAKE_HEAD; } void eatFood() {} } import 'dart:ffi'; import 'package:flutter_snake/models/game_model.dart'; class FoodModel{ GameModel gameModel; FoodModel({required this.gameModel}); void createFood(){ List<int> coordinates = GameModel.getRandomCoordinates(); gameModel.grid[coordinates[1]][coordinates[0]] = GameModel.FOOD; } }
23e9cb56d4e22cf5cd912ca998e6702b
{ "intermediate": 0.39084291458129883, "beginner": 0.47195184230804443, "expert": 0.13720524311065674 }
43,180
I'm trying to make a ClojureScript website using re-frame, reagent, and bootstrap. I'm trying to get subscriptions to work globally instead of locally. Here's the test page: (ns jimmystore.pages.test-page (:require [ajax.core :as ajax] [jimmystore.image-utils :as image-utils] [re-frame.core :as rf] [reagent.core :as ra])) (rf/reg-event-fx ::test-upload-file (fn [{:keys [db]} [_ reference-id type]] (let [form-data (js/FormData.) {:keys [file size]} (get db :upload)] (.append form-data "file" file) {:db (assoc-in db [:api-service :block-ui] true) :http-xhrio {:method :post :uri "/test-upload" :timeout 60000 :body form-data :response-format (ajax/json-response-format {:keywords? true}) :on-success [::get-items-test] :on-failure [:no-op]}}))) (rf/reg-event-db ::retrieve-item-picture-success (fn [db [_ response]] (assoc db ::img response))) (rf/reg-sub ::img (fn [db _] (::img db))) (rf/reg-sub ::items (fn [db _] (::items db))) (rf/reg-event-fx ::get-items-test (fn [_ _] {:http-xhrio {:method :get :uri "/get-items" :response-format (ajax/json-response-format {:keywords? true}) :on-success [::get-items-test-success]}})) (rf/reg-event-db ::get-items-test-success (fn [db [_ response]] (assoc db ::items response))) (defn get-file [file-event] (-> file-event .-target .-files (aget 0))) (defn- upload-form [] [:div {:class "mb-3"} [:label {:for "formFile" :class "form-label"} "Upload test"] [:div {:class "input-group"} [:input {:id "formFile" :class "form-control" :type :file :aria-describedby "inputGroupFileAddon" :aria-label "Upload" :on-change #(rf/dispatch [:set-file-to-upload (get-file %)])}] [:button {:id "inputGroupFileAddon" :class "btn btn-outline-secondary" :type :button :disabled (nil? @(rf/subscribe [:upload])) :on-click #(rf/dispatch [::test-upload-file])} "Upload"]]]) (defn page [] (ra/with-let [_ (rf/dispatch [::get-items-test]) img (rf/subscribe [::img]) items (rf/subscribe [::items]) txt (ra/atom "")] [:section.section>div.container>div.content [upload-form] [:input {:place-holder "Enter id here" :on-change #(reset! txt (-> % .-target .-value))}] [:button {:on-click #(rf/dispatch [:retrieve-item-picture @txt [::retrieve-item-picture-success]])} "Retrieve"] (when @img [:img {:src (image-utils/img-blob->img-src @img)} ]) [:p (str @items)]])) (def page-info {:page-id :test-page :view #'page}) And here's the events.cljs file: (ns jimmystore.events (:require [re-frame.core :as rf] [ajax.core :as ajax] [reitit.frontend.easy :as rfe] [reitit.frontend.controllers :as rfc])) ;;dispatchers (rf/reg-event-db :common/navigate (fn [db [_ match]] (def foo match) (let [old-match (:common/route db) new-match (assoc match :controllers (rfc/apply-controllers (:controllers old-match) match))] (assoc db :common/route new-match)))) (rf/reg-fx :common/navigate-fx! (fn [[k & [params query]]] (rfe/push-state k params query))) (rf/reg-event-fx :common/navigate! (fn [_ [_ url-key params query]] {:common/navigate-fx! [url-key params query]})) (rf/reg-event-db :set-docs (fn [db [_ docs]] (assoc db :docs docs))) (rf/reg-event-fx :fetch-docs (fn [_ _] {:http-xhrio {:method :get :uri "/docs" :response-format (ajax/raw-response-format) :on-success [:set-docs]}})) (rf/reg-event-fx :test-get-api (fn [_ _] {:http-xhrio {:method :get :uri "/test-get" :response-format (ajax/json-response-format {:keywords? true}) :on-success [:set-docs]}})) (rf/reg-event-fx :test-post-api (fn [_ _] {:http-xhrio {:method :post :uri "/test-post" :params {:test-post {:data 1 :foo :bar 2 "ASDASD"}} :format (ajax/json-request-format) :response-format (ajax/json-response-format {:keywords? true}) :on-success [:no-op]}})) (defn- get-file-size [file] (.-size file)) (defn- get-file-name [file] (.-name file)) (defn- get-file-type [file] (.-type file)) (rf/reg-event-db :set-file-to-upload (fn [db [_ file]] ;; Local url (for previews etc.) (assoc db :upload {:object-url (js/window.webkitURL.createObjectURL file) :file file :size (get-file-size file) :name (get-file-name file) :type (get-file-type file)}))) (rf/reg-sub :upload (fn [db _] (-> db :upload))) (rf/reg-event-db :common/set-error (fn [db [_ error]] (assoc db :common/error error))) (rf/reg-event-fx :page/init-home (fn [_ _] {:dispatch [:fetch-docs]})) (rf/reg-event-db :no-op (fn [db _] db)) ;;subscriptions (rf/reg-sub :common/route (fn [db _] (-> db :common/route))) (rf/reg-sub :common/page-id :<- [:common/route] (fn [route _] (-> route :data :name))) (rf/reg-sub :common/page :<- [:common/route] (fn [route _] (-> route :data :view))) (rf/reg-sub :docs (fn [db _] (:docs db))) (rf/reg-sub :common/error (fn [db _] (:common/error db))) (rf/reg-sub :img (fn [db _] (:img db))) (rf/reg-sub :items (fn [db _] (:items db))) The test_page.cljs is in a "pages" subfolder. What do I need to do in order to remove the duplicate img and items subscription code from the test page and have it work for all pages?
7cc2d504312845dfb465a811be88a776
{ "intermediate": 0.5876859426498413, "beginner": 0.32992231845855713, "expert": 0.08239169418811798 }
43,181
comment permettre au serpent de perdre d'une part en touchant une limite et d'autre part en se mordant la queue (garde un code clean) : import 'package:flutter_snake/models/game_model.dart'; class SnakeModel { int x; int y; int size = 1; GameModel gameModel; List<List<int>> bodyPositions = []; SnakeModel({required this.gameModel, this.x = 0, this.y = 0}); void reset() { x = GameModel.NB_COLONNES ~/ 2; y = GameModel.NB_LIGNES ~/ 2; size = 2; bodyPositions = [ [x, y], [y, x - 1] ]; displaySnake(); } void displaySnake() { bodyPositions.insert(0, [x, y]); gameModel.grid[y][x] = GameModel.SNAKE_HEAD; for (int i = 1; i < bodyPositions.length; i++) { gameModel.grid[bodyPositions[i][1]][bodyPositions[i][0]] = GameModel.SNAKE_HEAD; } print("new snake head: x: $x, y: $y"); print("new snake body: x: ${bodyPositions}"); } void moveSnake(int direction) { int newX = x; int newY = y; switch (direction) { case GameModel.DIRECTION_HAUT: newY--; break; case GameModel.DIRECTION_DROITE: newX++; break; case GameModel.DIRECTION_BAS: newY++; break; case GameModel.DIRECTION_GAUCHE: newX--; break; } if (!gameModel.isInGrid(newX, newY)) { return; } gameModel.grid[y][x] = 0; x = newX; y = newY; bool ateFood = gameModel.isFood(x, y); if (ateFood) { growSnake(); gameModel.increaseScore(); gameModel.foodModel.createFood(); } else if (bodyPositions.isNotEmpty && bodyPositions.length > size) { List<int> lastBodyPart = bodyPositions.removeLast(); gameModel.grid[lastBodyPart[1]][lastBodyPart[0]] = 0; } displaySnake(); } void growSnake() { size++; } } import 'dart:math'; import 'package:flutter_snake/models/food_model.dart'; import 'package:flutter_snake/models/snake_model.dart'; class GameModel { static const int NB_CASES = 140; static const int NB_LIGNES = 14; static const int NB_COLONNES = 10; static const int DIRECTION_HAUT = 0; static const int DIRECTION_DROITE = 1; static const int DIRECTION_BAS = 2; static const int DIRECTION_GAUCHE = 3; static const int SNAKE_HEAD = 1; static const int SNAKE_BODY = 2; static const int FOOD = 3; int score = 0; int currentDirection = DIRECTION_DROITE; List<List<int>> grid = List.generate(NB_LIGNES, (i) => List.filled(NB_COLONNES, 0)); late FoodModel foodModel; late SnakeModel snakeModel; GameModel() { foodModel = FoodModel(gameModel: this); snakeModel = SnakeModel(gameModel: this); } // Add your class properties and methods here void start() { // on réinitialise la matrice for (int i = 0; i < NB_LIGNES; i++) { for (int j = 0; j < NB_COLONNES; j++) { grid[i][j] = 0; } } foodModel.createFood(); _displaySnakeBody(); } static List<int> getRandomCoordinates() { Random random = Random(); int randomX = random.nextInt(NB_COLONNES); int randomY = random.nextInt(NB_LIGNES); print("randomX: $randomX, randomY: $randomY"); return [randomX, randomY]; } void changeDirection(int newDirection) { currentDirection = newDirection; moveSnake(); } void moveSnake() { snakeModel.moveSnake(currentDirection); } bool isFood(int x, int y) { return grid[y][x] == FOOD; } bool isInGrid(int x, int y) { return x >= 0 && x < NB_COLONNES && y >= 0 && y < NB_LIGNES; } void increaseScore() { score++; } void _displaySnakeBody() { if (snakeModel.bodyPositions.isNotEmpty) { for (var position in snakeModel.bodyPositions) { int y = position[0]; int x = position[1]; grid[y][x] = GameModel.SNAKE_BODY; } var head = snakeModel.bodyPositions.first; grid[head[0]][head[1]] = GameModel.SNAKE_HEAD; } } void eatFood() {} }
98b86719cfb20d43483d141e6cc98423
{ "intermediate": 0.32666972279548645, "beginner": 0.4206063151359558, "expert": 0.25272396206855774 }
43,182
comment permettre au serpent de perdre d'une part en touchant une limite et d'autre part en se mordant la queue (garde un code clean) : import 'package:flutter_snake/models/game_model.dart'; class SnakeModel { int x; int y; int size = 1; GameModel gameModel; List<List<int>> bodyPositions = []; SnakeModel({required this.gameModel, this.x = 0, this.y = 0}); void reset() { x = GameModel.NB_COLONNES ~/ 2; y = GameModel.NB_LIGNES ~/ 2; size = 2; bodyPositions = [ [x, y], [y, x - 1] ]; displaySnake(); } void displaySnake() { bodyPositions.insert(0, [x, y]); gameModel.grid[y][x] = GameModel.SNAKE_HEAD; for (int i = 1; i < bodyPositions.length; i++) { gameModel.grid[bodyPositions[i][1]][bodyPositions[i][0]] = GameModel.SNAKE_HEAD; } print("new snake head: x: $x, y: $y"); print("new snake body: x: ${bodyPositions}"); } void moveSnake(int direction) { int newX = x; int newY = y; switch (direction) { case GameModel.DIRECTION_HAUT: newY--; break; case GameModel.DIRECTION_DROITE: newX++; break; case GameModel.DIRECTION_BAS: newY++; break; case GameModel.DIRECTION_GAUCHE: newX--; break; } if (!gameModel.isInGrid(newX, newY)) { return; } gameModel.grid[y][x] = 0; x = newX; y = newY; bool ateFood = gameModel.isFood(x, y); if (ateFood) { growSnake(); gameModel.increaseScore(); gameModel.foodModel.createFood(); } else if (bodyPositions.isNotEmpty && bodyPositions.length > size) { List<int> lastBodyPart = bodyPositions.removeLast(); gameModel.grid[lastBodyPart[1]][lastBodyPart[0]] = 0; } displaySnake(); } void growSnake() { size++; } } import 'dart:math'; import 'package:flutter_snake/models/food_model.dart'; import 'package:flutter_snake/models/snake_model.dart'; class GameModel { static const int NB_CASES = 140; static const int NB_LIGNES = 14; static const int NB_COLONNES = 10; static const int DIRECTION_HAUT = 0; static const int DIRECTION_DROITE = 1; static const int DIRECTION_BAS = 2; static const int DIRECTION_GAUCHE = 3; static const int SNAKE_HEAD = 1; static const int SNAKE_BODY = 2; static const int FOOD = 3; int score = 0; int currentDirection = DIRECTION_DROITE; List<List<int>> grid = List.generate(NB_LIGNES, (i) => List.filled(NB_COLONNES, 0)); late FoodModel foodModel; late SnakeModel snakeModel; GameModel() { foodModel = FoodModel(gameModel: this); snakeModel = SnakeModel(gameModel: this); } // Add your class properties and methods here void start() { // on réinitialise la matrice for (int i = 0; i < NB_LIGNES; i++) { for (int j = 0; j < NB_COLONNES; j++) { grid[i][j] = 0; } } foodModel.createFood(); _displaySnakeBody(); } static List<int> getRandomCoordinates() { Random random = Random(); int randomX = random.nextInt(NB_COLONNES); int randomY = random.nextInt(NB_LIGNES); print("randomX: $randomX, randomY: $randomY"); return [randomX, randomY]; } void changeDirection(int newDirection) { currentDirection = newDirection; moveSnake(); } void moveSnake() { snakeModel.moveSnake(currentDirection); } bool isFood(int x, int y) { return grid[y][x] == FOOD; } bool isInGrid(int x, int y) { return x >= 0 && x < NB_COLONNES && y >= 0 && y < NB_LIGNES; } void increaseScore() { score++; } void _displaySnakeBody() { if (snakeModel.bodyPositions.isNotEmpty) { for (var position in snakeModel.bodyPositions) { int y = position[0]; int x = position[1]; grid[y][x] = GameModel.SNAKE_BODY; } var head = snakeModel.bodyPositions.first; grid[head[0]][head[1]] = GameModel.SNAKE_HEAD; } } void eatFood() {} }
a138056abd4a2dd5afee7e8c1e788c1f
{ "intermediate": 0.32666972279548645, "beginner": 0.4206063151359558, "expert": 0.25272396206855774 }
43,183
//+------------------------------------------------------------------+ //| ProjectName | //| Copyright 2020, CompanyName | //| http://www.companyname.net | //+------------------------------------------------------------------+ input ENUM_TIMEFRAMES TimeFrame = PERIOD_M1; datetime lastBarTime = 0; input double InitialLots = 0.1; bool send_b = false; bool send_s = false; //±-----------------------------------------------------------------+ //| | //±-----------------------------------------------------------------+ //±-----------------------------------------------------------------+ //| | //±-----------------------------------------------------------------+ bool YesOrNo() { MqlRates rates_array[]; // Получаем данные последней закрытой свечи if(CopyRates(_Symbol, _Period, 1, 1, rates_array) > 0) { double openCloseDifference = MathAbs(rates_array[0].open - rates_array[0].close); double highLowDifference = MathAbs(rates_array[0].high - rates_array[0].low); double bodyToShadowRatio = openCloseDifference / highLowDifference; double lowerBodyEnd; // Нижняя часть тела свечи if(rates_array[0].open > rates_array[0].close) { // Медвежья свеча lowerBodyEnd = rates_array[0].close; } else { // Бычья свеча lowerBodyEnd = rates_array[0].open; } double bodyPositionRatio = (lowerBodyEnd - rates_array[0].low) / highLowDifference; // Проверяем, удовлетворяет ли тело свечи всем условиям if(bodyToShadowRatio <= 0.3 && bodyPositionRatio >= 0.5) { Print("ДА"); return true; } } else { Print("Ошибка при получении данных свечи."); } Print("НЕТ"); return false; } //±-----------------------------------------------------------------+ //| | //±-----------------------------------------------------------------+ int OnInit() { //— MqlRates rates[]; if(CopyRates(_Symbol, TimeFrame, 0, 1, rates) > 0) { lastBarTime = rates[0].time; } else { Print("Ошибка при получении информации о барах: ", GetLastError()); return (INIT_FAILED); } //— return(INIT_SUCCEEDED); } //±-----------------------------------------------------------------+ //| Expert deinitialization function | //±-----------------------------------------------------------------+ void OnDeinit(const int reason) { //— } //±-----------------------------------------------------------------+ //| Expert tick function | //±-----------------------------------------------------------------+ void OnTick() { //— send_b = false; send_s = false; datetime currentTime = TimeCurrent(); ENUM_TIMEFRAMES Time = TimeFrame; if(Time > 16000) { Time = (ENUM_TIMEFRAMES)((Time - 16384) * 60); } if(currentTime >= lastBarTime+Time*60) { if(YesOrNo() == true) { while(send_b != true) { OpenOrder(ORDER_TYPE_BUY, InitialLots, "B"); } } lastBarTime = lastBarTime+Time*60; } } //±-----------------------------------------------------------------+ //| | //±-----------------------------------------------------------------+ void OpenOrder(ENUM_ORDER_TYPE type, double lots, string orderMagic) { MqlRates rates_array[]; // Получаем данные последней закрытой свечи if(CopyRates(_Symbol, _Period, 1, 1, rates_array) > 0) { double highLowDifference = MathAbs(rates_array[0].high - rates_array[0].low); double StopLoss = rates_array[0].low; double TakeProfit = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + highLowDifference*2; Print(StopLoss); Print(TakeProfit); MqlTradeRequest request = {}; MqlTradeResult result = {}; // Заполнение полей структуры запроса на сделку request.action = TRADE_ACTION_DEAL; request.symbol = Symbol(); request.volume = lots; request.type = type; request.deviation = 5; request.magic = StringToInteger(orderMagic + IntegerToString(GetTickCount())); request.sl = StopLoss; request.tp = TakeProfit; //request.comment = “Auto trade order”; if(type == ORDER_TYPE_BUY) request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); else if(type == ORDER_TYPE_SELL) request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); if(!OrderSend(request, result)) { Print("OrderSend failed with error #", GetLastError()); Print("Details: symbol=", request.symbol, ", volume=", request.volume, ", type=", (request.type==ORDER_TYPE_BUY?"BUY":"SELL"), ", price=", request.price); if(request.type == ORDER_TYPE_BUY) { send_b = false; } else if(request.type == ORDER_TYPE_SELL) { send_s = false; } } else if(request.type == ORDER_TYPE_BUY) { send_b = true; } else if(request.type == ORDER_TYPE_SELL) { send_s = true; } PrintFormat("retcode=%u deal=%I64u order=%I64u",result.retcode,result.deal,result.order); } } //±-----------------------------------------------------------------+ //±-----------------------------------------------------------------+ //±-----------------------------------------------------------------+ //±-----------------------------------------------------------------+ //+------------------------------------------------------------------+ в эту программу нужн одобавить что он будет заходить в сделки только если не открыто других сделок
6a777051d95df6005b43d4ccc8f21c85
{ "intermediate": 0.3639839291572571, "beginner": 0.4785464406013489, "expert": 0.15746967494487762 }
43,184
explain this solr query:
d15c1f389e9ac7e08a445498569ba730
{ "intermediate": 0.36080291867256165, "beginner": 0.2973450720310211, "expert": 0.34185200929641724 }
43,185
import ollama res = ollama.chat( model="llava", messages=[ { 'role': 'user', 'content': 'Describe this image:', 'images': ("./2.png") } ] ) print(res['message']['content']) why this code don't work?
552ad425c8ff6f354b051eccff9e7fd1
{ "intermediate": 0.404356449842453, "beginner": 0.3453053832054138, "expert": 0.25033825635910034 }
43,186
give a logic to pass column name and sortorder to a stored procedure and write the dynamic sorting logic in an sql query using mysql
d49c1376069ad83d2756dcc04239b8db
{ "intermediate": 0.5761534571647644, "beginner": 0.12392377853393555, "expert": 0.29992279410362244 }
43,187
set the whole sql query in a SET @sql='' variable with appropriate changes in sql quotes and all WITH filtered_result AS ( SELECT DISTINCT t_asm_detail.asm_id, t_asm_detail.wafer_no AS `wafer_no`, t_pcsjb_info.carrier_id AS `pcsjbInfo.carrier_id`, t_asm_detail.chamber_id AS chamber_id, t_chamber_recipe_info.recipe_no AS `chamberRecipeInfo.recipe_no`, t_chamber_recipe_info.recovery_flg AS `chamberRecipeInfo.recovery_flg`, t_asm_detail.process_recipe_name AS `process_recipe_name`, t_asm_detail.start_date AS `start_date`, t_asm_detail.end_date AS `end_date` FROM t_asm_detail LEFT JOIN t_chamber_recipe_info ON t_asm_detail.recipe_no = t_chamber_recipe_info.recipe_no LEFT JOIN t_chamber_unique_info As tcui ON t_asm_detail.chamber_id = tcui.chamber_unique_id LEFT JOIN t_pcsjb_info ON tcui.device_unique_id = t_pcsjb_info.device_unique_id AND SUBSTRING(process_recipe_name, LOCATE(' ', process_recipe_name) + 1) = t_pcsjb_info.seq_rcp_name AND start_date >= t_pcsjb_info.pj_start_time AND t_pcsjb_info.pj_end_time >= end_date WHERE t_chamber_recipe_info.recipe_no != 0 AND t_chamber_recipe_info.recovery_flg = 0 AND FIND_IN_SET(TRIM(REGEXP_REPLACE(chamber_id, '[[:space:]]+', ' ')) ,chamber_id_param) AND start_date >= start_date_param AND end_date <= end_date_param ), sorted_result AS ( SELECT *, IF(@prev_key != asm_id, @row_index := @row_index + 1, @row_index) AS row_index, @prev_key := asm_id FROM filtered_result ORDER BY case when sortClause_param='`wafer_no` ' then `wafer_no` else `wafer_no` end , asm_id ) SELECT TRIM(REGEXP_REPLACE(sr.asm_id, '[[:space:]]+', ' ')) AS `asm_id`, TRIM(REGEXP_REPLACE(sr.wafer_no, '[[:space:]]+', ' ')) AS `wafer_no`, TRIM(REGEXP_REPLACE(sr.start_date, '[[:space:]]+', ' ')) AS `start_date`, TRIM(REGEXP_REPLACE(sr.end_date, '[[:space:]]+', ' ')) AS `end_date`, TRIM(REGEXP_REPLACE(sr.`pcsjbInfo.carrier_id`, '[[:space:]]+', ' ')) AS `pcsjbInfo.carrier_id`, TRIM(REGEXP_REPLACE(cui.device_name, '[[:space:]]+', ' ')) AS `chamberUniqueInfo.device_name`, TRIM(REGEXP_REPLACE(dui.device_name, '[[:space:]]+', ' ')) AS `chamberUniqueInfo.deviceUniqueInfoDomain.device_name`, TRIM(REGEXP_REPLACE(sr.`chamberRecipeInfo.recipe_no`, '[[:space:]]+', ' ')) AS `chamberRecipeInfo.recipe_no`, TRIM(REGEXP_REPLACE(sr.process_recipe_name, '[[:space:]]+', ' ')) AS `process_recipe_name`, TRIM(REGEXP_REPLACE(m.measure_hash, '[[:space:]]+', ' ')) AS `trnMapping.measure_hash`, (SELECT COUNT(asm_id) FROM filtered_result) as total FROM sorted_result sr LEFT JOIN t_chamber_unique_info cui ON sr.chamber_id = cui.chamber_unique_id LEFT JOIN t_device_unique_info dui ON cui.device_unique_id = dui.device_unique_id LEFT JOIN t_mapping m ON sr.asm_id = m.asm_id AND m.del_flg = '1' -- WHERE row_index >=row_offset AND row_index < row_offset + row_count; -- (uncomment for pagination) WHERE row_index >= row_offset AND row_index < (CASE WHEN row_count = 0 THEN (SELECT COUNT(asm_id) FROM filtered_result) ELSE row_offset + row_count END);
d4691890a38e42b1fc6ba6259827734c
{ "intermediate": 0.2515067756175995, "beginner": 0.5173600912094116, "expert": 0.23113320767879486 }
43,188
how to print the SET @sql statement in mysql stored procedure
2633be87c7eb4f24459ed04624039c88
{ "intermediate": 0.3557145893573761, "beginner": 0.47730717062950134, "expert": 0.16697828471660614 }
43,189
I have a custom-scoped application. We haven't implemented the workspace yet but temporarily when the clients log in to the instance they'd like to see the list view of all their records. Right now the landing page is reports and dashboards. Is there a way to change this from reports and dashboards to the List view of a table in this custom-scoped application?
81a20e6d45e093206ccb13ecb2591557
{ "intermediate": 0.5016675591468811, "beginner": 0.2535940110683441, "expert": 0.24473842978477478 }
43,190
firefox: create extension to click on some links redirect to unode web resource - change subdomain
f5b1b866b9324d48eba6d4dd2d8b1c2e
{ "intermediate": 0.3829239308834076, "beginner": 0.3042011857032776, "expert": 0.3128748834133148 }
43,191
could create a next js to do app
a1060147c57074343c0bf0008a5eb093
{ "intermediate": 0.32601773738861084, "beginner": 0.3036966025829315, "expert": 0.37028563022613525 }
43,192
Show me only the partition column name and ranges for below ddl: CREATE SET TABLE CDMTDFMGR.sample_WA_sales_csv_multipartition_order ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL, CHECKSUM = DEFAULT, DEFAULT MERGEBLOCKRATIO, MAP = TD_MAP1 ( product_id INTEGER, Seller_Country VARCHAR(14) CHARACTER SET LATIN NOT CASESPECIFIC, Channel_Type VARCHAR(11) CHARACTER SET LATIN NOT CASESPECIFIC, Store_Type VARCHAR(22) CHARACTER SET LATIN NOT CASESPECIFIC, Product_Category VARCHAR(24) CHARACTER SET LATIN NOT CASESPECIFIC, Product_Line VARCHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC, Product VARCHAR(33) CHARACTER SET LATIN NOT CASESPECIFIC, Years INTEGER, Quarter VARCHAR(7) CHARACTER SET LATIN NOT CASESPECIFIC, Sales_Value FLOAT, Units_Sold INTEGER, Margin FLOAT) PRIMARY INDEX ( product_id ) PARTITION BY CASE_N( Years > 2013 , Years > 2012 , Years > 2011 , NO CASE, UNKNOWN);
6fc4bb7527ebd747a36790cdd322149e
{ "intermediate": 0.30961787700653076, "beginner": 0.2662965655326843, "expert": 0.4240855872631073 }
43,193
Please generate insert statements for ddl CREATE SET TABLE CDMTDFMGR.sample_WA_sales_csv_multipartition_order ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL, CHECKSUM = DEFAULT, DEFAULT MERGEBLOCKRATIO, MAP = TD_MAP1 ( product_id INTEGER, Seller_Country VARCHAR(14) CHARACTER SET LATIN NOT CASESPECIFIC, Channel_Type VARCHAR(11) CHARACTER SET LATIN NOT CASESPECIFIC, Store_Type VARCHAR(22) CHARACTER SET LATIN NOT CASESPECIFIC, Product_Category VARCHAR(24) CHARACTER SET LATIN NOT CASESPECIFIC, Product_Line VARCHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC, Product VARCHAR(33) CHARACTER SET LATIN NOT CASESPECIFIC, Years INTEGER, Quarter VARCHAR(7) CHARACTER SET LATIN NOT CASESPECIFIC, Sales_Value FLOAT, Units_Sold INTEGER, Margin FLOAT) PRIMARY INDEX ( product_id ) PARTITION BY CASE_N( Years > 2013 , Years > 2012 , Years > 2011 , NO CASE, UNKNOWN);
5a8b216cb4b019e95a98edefac19e9fd
{ "intermediate": 0.3004439175128937, "beginner": 0.43500375747680664, "expert": 0.2645522654056549 }
43,194
def AdaBoost_scratch(X,y, M=10, learning_rate = 1): # инициалиазция служебных переменных N = len(y) estimator_list, y_predict_list, estimator_error_list, estimator_weight_list, sample_weight_list = [], [],[],[],[] # инициализация весов sample_weight = np.ones(N) / N sample_weight_list.append(sample_weight.copy()) # цикл по длине М for m in range(M): # обучим базовую модель и получим предсказание estimator = DecisionTreeClassifier(max_depth=1, max_leaf_nodes=2, max_features=2) estimator.fit(X, y, sample_weight=sample_weight) y_predict = estimator.predict(X) # Маска для ошибок классификации incorrect = (y_predict != y) # Оцениваем ошибку estimator_error = np.mean( np.average(incorrect, weights=sample_weight, axis=0)) # Вычисляем вес нового алгоритма estimator_weight = learning_rate * np.log((1. - estimator_error) / estimator_error) # Получаем новые веса объектов sample_weight *= np.exp(estimator_weight * incorrect * ((sample_weight > 0) | (estimator_weight < 0))) # Сохраяем результаты данной итерации estimator_list.append(estimator) y_predict_list.append(y_predict.copy()) estimator_error_list.append(estimator_error.copy()) estimator_weight_list.append(estimator_weight.copy()) sample_weight_list.append(sample_weight.copy()) # Для удобства переведем в numpy.array estimator_list = np.asarray(estimator_list) y_predict_list = np.asarray(y_predict_list) estimator_error_list = np.asarray(estimator_error_list) estimator_weight_list = np.asarray(estimator_weight_list) sample_weight_list = np.asarray(sample_weight_list) # Получим предсказания preds = (np.array([np.sign((y_predict_list[:,point] * estimator_weight_list).sum()) for point in range(N)])) print('Accuracy = ', (preds == y).sum() / N) return estimator_list, estimator_weight_list, sample_weight_list # Вызов функции AdaBoost для выполнения классификации методом бустинга estimator_list, estimator_weight_list, sample_weight_list = AdaBoost_scratch(X,y, M=10, learning_rate = 1) Accuracy = 0.21159882206090866 Как увеличить точность
3488f679a2d9cc1d3b46b3e5f421af62
{ "intermediate": 0.21974046528339386, "beginner": 0.5111861824989319, "expert": 0.2690733075141907 }
43,195
the toast does not show when i add a product to cart by clicking the navlink: import { useState, useEffect } from "react"; import styled from "styled-components"; import { FaCheck } from "react-icons/fa"; import CartAmountToggle from "./CartAmountToggle"; import { NavLink } from "react-router-dom"; import { Button } from "../styles/Button"; import { useCartContext } from "../context/cart_context"; import { useToast } from '@chakra-ui/react'; const AddToCart = ({ product }) => { const { addToCart } = useCartContext(); const toast = useToast(); const { id, colors, stock } = product; const [color, setColor] = useState(colors[0]); const [amount, setAmount] = useState(1); const setDecrease = () => { amount > 1 ? setAmount(amount - 1) : setAmount(1); }; const setIncrease = () => { amount < stock ? setAmount(amount + 1) : setAmount(stock); }; useEffect(() => { // Show a toast message using the `toast` hook. toast({ title: 'Product Added', description: `Product was successfully added to your cart.`, status: 'success', duration: 3000, isClosable: true, }); }, [addToCart]); return ( <Wrapper> <div className="colors"> <p> Color: {colors.map((curColor, index) => { return ( <button key={index} style={{ backgroundColor: curColor }} className={color === curColor ? "btnStyle active" : "btnStyle"} onClick={() => setColor(curColor)}> {color === curColor ? <FaCheck className="checkStyle" /> : null} </button> ); })} </p> </div> {/* add to cart */} <CartAmountToggle amount={amount} setDecrease={setDecrease} setIncrease={setIncrease} /> <NavLink onClick={() => addToCart(id, color, amount, product)}> <Button className="btn">Add To Cart</Button> </NavLink> </Wrapper> ); }; const Wrapper = styled.section` .colors p { display: flex; justify-content: flex-start; align-items: center; } .btnStyle { width: 2rem; height: 2rem; background-color: #000; border-radius: 50%; margin-left: 1rem; border: none; outline: none; opacity: 0.5; cursor: pointer; &:hover { opacity: 1; } } .active { opacity: 1; } .checkStyle { font-size: 1rem; color: #fff; } /* we can use it as a global one too */ .amount-toggle { margin-top: 3rem; margin-bottom: 1rem; display: flex; justify-content: space-around; align-items: center; font-size: 1.4rem; button { border: none; background-color: #fff; cursor: pointer; } .amount-style { font-size: 2.4rem; color: ${({ theme }) => theme.colors.btn}; } } `; export default AddToCart;
669603c19471a391ac3c6c9c09318a61
{ "intermediate": 0.3438938856124878, "beginner": 0.40002357959747314, "expert": 0.2560825049877167 }
43,196
correct the code for react: const Wrapper = styled.section<br/> // Existing styles<br/> <br/> // Adjust the background styles<br/> ${(props) =&gt; background: /* Black overlay with 60% opacity / linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), / URL of the background image */ url(${props.image}) center/cover no-repeat; }<br/> <br/> // The rest of your styles<br/>;
3bfd20b6c4a0fc12193ce66c27adba47
{ "intermediate": 0.3758679926395416, "beginner": 0.2872275114059448, "expert": 0.3369044363498688 }
43,197
! pip install datasets !pip install accelerate -U import numpy as np from transformers import AutoTokenizer, AutoConfig, AutoModelForPreTraining, \ TrainingArguments, Trainer import torch from torch.utils.data import Dataset import json with open('/content/conversations.json') as file: data = json.load(file) def load_conversations_from_json(json_data): context = [] response = [] conversations = json_data['conversations'] for conv in conversations: messages = conv['messages'] for i in range(len(messages)-1): if messages[i]['type'] == 'customer' and messages[i+1]['type'] == 'agent': context.append(messages[i]['message']) response.append(messages[i+1]['message']) return context, response SPECIAL_TOKENS = { "bos_token": "<|BOS|>", "eos_token": "<|EOS|>", "unk_token": "<|UNK|>", "pad_token": "<|PAD|>", "sep_token": "<|SEP|>"} MAXLEN = 60 class myDataset(Dataset): def __init__(self, data, tokenizer): context, response = [], [] for k, v in data.items(): context.append(v[0]) response.append(v[1]) self.tokenizer = tokenizer self.response = response self.context = context def __len__(self): return len(self.context) def __getitem__(self, i): input = SPECIAL_TOKENS['bos_token'] + self.context[i] + \ SPECIAL_TOKENS['sep_token'] + \ self.response[i] + SPECIAL_TOKENS['eos_token'] encodings_dict = tokenizer(input, truncation=True, max_length=MAXLEN, padding="max_length") input_ids = encodings_dict['input_ids'] attention_mask = encodings_dict['attention_mask'] return {'label': torch.tensor(input_ids), 'input_ids': torch.tensor(input_ids), 'attention_mask': torch.tensor(attention_mask)} tokenizer = AutoTokenizer.from_pretrained('gpt2') tokenizer.add_special_tokens(SPECIAL_TOKENS) config = AutoConfig.from_pretrained('gpt2', bos_token_id=tokenizer.bos_token_id, eos_token_id=tokenizer.eos_token_id, sep_token_id=tokenizer.sep_token_id, pad_token_id=tokenizer.pad_token_id, output_hidden_states=False) model = AutoModelForPreTraining.from_pretrained('gpt2', config=config) model.resize_token_embeddings(len(tokenizer)) model.cuda() context_train, response_train = load_conversations_from_json(data) context_val, response_val = load_conversations_from_json(data) train_data = dict() i=0 for context, response in zip (context_train, response_train): train_data[i] = [context, response] i += 1 #******************************************** val_data = dict() i=0 for context, response in zip (context_val, response_val): val_data[i] = [context, response] i += 1 train_dataset = myDataset(train_data, tokenizer) val_dataset = myDataset(val_data, tokenizer) training_args = TrainingArguments( output_dir="/content", num_train_epochs=3, eval_steps = 2000, save_steps=2000, warmup_steps=500, prediction_loss_only=True, learning_rate = 5e-4, do_eval = True, evaluation_strategy = 'steps' ) trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, tokenizer=tokenizer ) trainer.train() trainer.save_model('/content/drive/MyDrive/final model') based on this code i want to add this knowledge based md file # Knowledge Base ## Chargeback - Chargebacks beyond 90 days are not possible. - Chargebacks above $1000 are not allowed - Chargebacks for transactions with a valid 3D secure are not allowed
2d74ed241cbf6a983a681f81854b137f
{ "intermediate": 0.2957107722759247, "beginner": 0.5321601033210754, "expert": 0.17212913930416107 }
43,198
@using Products @page "/Catalog" @page "/Catalog/{CategoryName}" @inject NavigationManager NavigationManager @code { public List<Product> _products = new(); public List<string> _categories = Keeper.GetCategories(); public string? _category = null; public string? _showedCategory = ""; public List<Product> _showedProducts = new(); [Parameter] public string? CategoryName { get; set; } InvalidOperationException: No writer was cached for the property 'CategoryName' on type 'BlazorAppPetrovich2024.Components.Pages.Catalog'. Microsoft.AspNetCore.Components.Reflection.ComponentProperties.ThrowForUnknownIncomingParameterName(Type targetType, string parameterName) Microsoft.AspNetCore.Components.Reflection.ComponentProperties.SetProperties(ref ParameterView parameters, object target) Microsoft.AspNetCore.Components.ComponentBase.SetParametersAsync(ParameterView parameters) Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters) Microsoft.AspNetCore.Components.Rendering.ComponentState.SupplyCombinedParameters(ParameterView directAndCascadingParameters) Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters(ParameterView parameters) Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.InitializeNewComponentFrame(ref DiffContext diffContext, int frameIndex) В чем проблема?
250d7e838f16414f053a97571deb7e3f
{ "intermediate": 0.575134813785553, "beginner": 0.18727359175682068, "expert": 0.23759157955646515 }
43,199
write code which calculates area of bounding box with (x1,y1,x2,y2) format
4c1eb584c31d302622f1a0a0266cff17
{ "intermediate": 0.3013143539428711, "beginner": 0.24189548194408417, "expert": 0.45679014921188354 }
43,200
hi
a99ea563228bc46f8a33859cb591dbba
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,201
######################################################## # In this lab we'll see various examples of network visualization, # using different design idioms and layout options, # including adjacency matrix, dendrogram, circular tree and treemap ######################################################## # first set the working directory on your computer setwd('~/Dropbox/IS teaching/IS4335 data_vis/lab/R_codes') # load the libraries library(igraph) library(ggplot2) library(reshape2) # load the network data load("~/Dropbox/IS teaching/IS4335 data_vis/2024_files/NetData/data/kracknets.rda") krack_full_data <- cbind(advice_data_frame, friendship_tie = friendship_data_frame$friendship_tie, reports_to_tie = reports_to_data_frame$reports_to_tie) krack_full_nonzero_edges <- subset(krack_full_data_frame, (advice_tie > 0 | friendship_tie > 0 | reports_to_tie > 0)) attributes2 <- cbind(id = 1:nrow(attributes), attributes) # bind node id with attribute columns krack_full <- graph_from_data_frame(d = krack_full_nonzero_edges, directed = F, vertices = attributes2) ############################################################################## # 1. network properties ############################################################################## # last time in the lecture we have discussed network properties, # such as degree distribution, diameter/path length, and clustering coefficient # Many initial analyses of networks begin with degree distributions & distance, # and then move towards global summary statistics of the network. # # As a reminder, entering a question mark followed by a function # name (e.g., ?graph.density) pulls up the help file for that function. # This can be helpful to understand how, exactly, stats are calculated. # let's first see an example of degree distribution # in network language, degree is the number of connections that a node has deg_full <- degree(krack_full, mode="all") is.directed(krack_full) # if the graph is directed, we can check indegree and outdegree distributions separately # but since the graph is undirected, there is no need for that deg_full # the degree distribution shows how many ties that each node has mean(deg_full) #check average degree sd(deg_full) #check standard deviation # network diameter and average distance diameter(krack_full) mean_distance(krack_full) # diameter and average distance is very small given everyone is connected. # let's compare the full network to friendship and reports-to networks krack_friendship_only <- delete_edges(krack_full, E(krack_full)[edge_attr(krack_full, name = "friendship_tie") == 0]) krack_reports_to_only <- delete_edges(krack_full, E(krack_full)[edge_attr(krack_full, name = "reports_to_tie") == 0]) diameter(krack_friendship_only) diameter(krack_reports_to_only) # we see the diameters of the latter graphs are longer, since there are fewer ties # connecting people. however, everyone in the company is related to each other in someway # so the overall diameter and distance are very small # Density: the portion of potential connections in a network that are realized graph.density(krack_friendship_only) graph.density(krack_reports_to_only) # Transitivity: if a and b are connected, b and c are connected, # what's the likelihood that a and c are also connected? transitivity(krack_full) transitivity(krack_friendship_only) transitivity(krack_reports_to_only) ############################################################################## # 2. network visualization examples: graph layout and adjacency matrix ############################################################################## # last time we saw visualization of network connections # the Fruchterman and Reingold's layout in week 8 lab uses a force-directed placement algorithm. # let's play with other layout functions # first Reingold-Tilford tree plot(krack_full, vertex.color=dept_vertex_colors, layout = layout_as_tree(krack_full)) # alternatively, you can first calculate the layout and then pass it into the plot layout <- layout_as_tree(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) # circle layout <- layout_in_circle(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) # star layout <- layout_as_star(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) ############################################################################## # 3. community structure + adjacency matrix ############################################################################## # the friendship pattern is unclear and it's better to cluster nodes by community memberships # ties within communities are denser since nodes have closer relationships. # there are several ways to create communities, a common method is to use edge betweenness: # The betweenness score of an edge measures the number of # shortest paths from one node to another that go through it. # The idea of the edge-betweenness based community structure # is that it is likely that edges connecting separate # cluster have high edge-betweenness, as all the shortest paths # from one cluster to another must traverse through them. So if we # iteratively remove the edge with the highest betweenness # score we will get a hierarchical map of the communities in the graph. # The following function performs community detection using the edge betweenness algorithm friend_comm <- cluster_edge_betweenness(krack_friendship_only, weights = NULL, directed=F) friend_comm # community membership of each node can be queried as follows: friend_comm$membership # Visualize the network with community memberships plot(friend_comm, krack_friendship_only) # communities are colored in different shades, and nodes within the same communities are clustered together # This process also lends itself to visualization as a dendrogram. # The y-axis reflects the distance metric used by the edge betweenness algorithm plot(as.dendrogram(friend_comm)) # the tree branches show membership hierarchies. nodes belonging to the same community share common roots # the y-axis is a distance measure showing how far apart are nodes # now we can rearrange nodes by their community memberships # first create a data frame that records node id and communities # and reorder node id's by membership affiliation membership <- data.frame(cbind(friend_comm$membership, friend_comm$names)) names(membership) <- c('group','id') class(membership$group). # string var membership$group <- as.numeric(membership$group) membership <- membership[order(membership$group),] # sort data frame by the group column ######################################################################## # 4. Adjacency matrix plots ######################################################################## # the previous graphs all show node-link diagrams. but how do we visualize networks as adjacency matrix? # let's first get the adjacency matrix of krack_full using friendship ties only: krack_friend <- as.matrix(as_adjacency_matrix(krack_full, attr='friendship_tie')) krack_friend # some of the edges are redundant since there are multiple tie types, so the matrix cell values could be > 1 # we want to remove the redundant ties by converting matrix to binary 0/1 values krack_friend[krack_friend>1] <- 1 # convert matrix to binary # we'll use the ggplot2 library to plot the adjacency matrix. but first we need to convert the matrix into a data frame. # this could be done using the melt function from reshape2: krack_friend_long <-melt(krack_friend) head(krack_friend_long) names(krack_friend_long) <- c('from','to','tie') # convert first two columns to factors, since id's are discrete categories krack_friend_long$from <- factor(krack_friend_long$from) krack_friend_long$to <- factor(krack_friend_long$to) # Create the adjacency matrix plot using ggplot2 # we plot the matrix using color tiles, each tile represent the friendship relations btw two nodes. # nodes with friendship ties are colored as red, otherwise left blank # baseline plot ggplot(krack_friend_long[krack_friend_long$tie>0,], aes(x = from, y = to, fill = factor(tie))) + geom_raster() + # create rectangular tiles when all the tiles are the same size. can also use geom_tile() labs(x='', y='', fill='Friend') + scale_fill_manual(values=c('red','grey90'), # manually define colors that correspond to the levels in fill breaks=c(1,0), # how to order legend for fill labels=c('yes','no')) + # legend label. here we only have "yes" theme_bw() + theme(aspect.ratio = 1) # Force the plot into a square aspect ratio # how do we reorder the graph based on community affiliations? # recall we have membership affiliations from before: membership # Reorder edge list "from" and "to" factor levels based on the ids ordered by membership affiliations # in factor(), arg "levels" can specify how we want the factor levels to be ordered krack_friend_long$from <- factor(krack_friend_long$from, levels = membership$id) krack_friend_long$to <- factor(krack_friend_long$to, levels = membership$id) # include membership info of from and to nodes using join function. # first change the names of the membership columns to be matched with plot_data names(membership) <- c('from_group','from') # memebership of ego plot_data <- krack_friend_long %>% plyr::join(membership, by='from') # plyr::join calls the join function from plyr library names(membership) <- c('to_group','to') # memebership of alter plot_data <- plot_data %>% plyr::join(membership, by='to') names(plot_data) # membership info added # adding membership affiliations of nodes allow us to color in-group and out-group ties separately # here we want to color in-group ties by communities, and out-group ties as grey # how do we do that? # first we identify ties between members of the same community for in-group ties: from_group = to_group # if from_group != to_group, then the tie is an out-group tie # the info is stored in memb_tie variable plot_data$memb_tie <- 0 # default is out-group plot_data$memb_tie[plot_data$from_group==plot_data$to_group] <- 1 # mark out within-group ties plot_data$memb_tie[plot_data$memb_tie==1] <- plot_data$from_group[plot_data$memb_tie==1] # replace the marker with group info plot_data$memb_tie # Now run the ggplot code again, include ties with non-zero values and color ties based on membership # within-group ties have different colors, while between-group ties are all grey # improved plot ggplot(plot_data[plot_data$tie>0,], aes(x = from, y = to, fill = factor(memb_tie))) + geom_raster() + labs(x='', y='', fill='Within-community ties') + scale_fill_manual(values = c('grey','magenta','darkgreen','royalblue')) + # manually set community colors scale_x_discrete(drop = FALSE) + scale_y_discrete(drop = FALSE) + theme_bw() + theme(aspect.ratio = 1) # nodes of the same communities are placed close to each other, # and we can now see some group structure from this adjacency matrix plot. # between-group ties are colored as grey, and within-group ties are colored according to membership affiliations # the advantage of adjacency matrix representation is that: # a) scalable, less messy than node-link diagrams when the number of nodes is large # b) community structures are easier to spot ######################################################################## # 5. radial tree & treemaps ######################################################################## # A treemap is a space-filling visualization of hierarchical structures. The treemap package offers great flexibility to draw it install.packages('treemap') library(treemap) library(dplyr) # radial tree: # use the treegraph function in the treemap package. # index: vector of column names that specify the aggregation indices. It could # contain only one column name, which results in a treemap without hierarchy. # If multiple column names are provided, the first name is the highest aggregation level, # the second name the second-highest aggregation level, and so on. treegraph(krack_friend_long[krack_friend_long$tie==1,], index = c('from','to'), directed=F, show.labels=T) # here we map out the friendship connections among nodes using hierarchical tree structure. # there's an artificial root in the center, and each node in the second layer corresponds to a node in the "from" column # the third layer consists of nodes in the "to" column connected to the source node in the "from" column # calculate degrees of source nodes by counting number of connections krack_friend_degree <- krack_friend_long %>% group_by(from) %>% summarise(degree = sum(tie)) krack_treemap <- plyr::join(krack_friend_long, krack_friend_degree, by='from') # index treemap: colors are determined by the index argument # different branches in the hierarchical tree get different colors. # in this case, colors are defined by the source nodes # size of the rectangles are defined by the vSize argument, # the higher the degree count, the bigger the rectangle size treemap(krack_treemap[krack_treemap$tie==1,], index = c('from','to'), vSize = 'degree', type="index") ######################################################################## # 6. week 9 assignment: due on Sunday midnight ######################################################################## # Task 1. visualize all network ties in krack_full using the adjacency matrix. # color edges according to friendship, advice, and reports-to ties # Task 2. cluster nodes by community membership using the friendship network, and replot the adjacency matrix # with nodes belonging to the same communities placed close to each other. # construct a new variable, tie strength, which is the combination of friendship, advice, and reports-to ties # this counts the types of relationships between two nodes # Task 3. use radial tree to visualize the reports-to network, and a treemap to show the advice network. # in the treemap, set size proportional to ego's degrees from the advice and reports-to networks help me to do the task and write all R code
e3843c6220b5117605f5ddd7696a259b
{ "intermediate": 0.4504823088645935, "beginner": 0.2639535963535309, "expert": 0.2855640649795532 }
43,202
Given this WPF form, please show me how to make the SettingsButton clickable when the blur is occurring: <UserControl x:Class="AGRIS.One.CheckIn.Client.Views.PromptView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:AGRIS.One.CheckIn.Client.Views" mc:Ignorable="d" d:DesignWidth="1024" d:DesignHeight="768"> <UserControl.Resources> <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" TrueValue="Visible" FalseValue="Hidden"/> <local:BoolToVisibilityConverter x:Key="BoolToVisCollapseConverter" TrueValue="Collapsed" FalseValue="Visible"/> <local:BoolToVisibilityConverter x:Key="BoolToInvisibilityConverter" TrueValue="Hidden" FalseValue="Visible"/> <local:BoolToVisibilityConverter x:Key="BoolToInvisCollapseConverter" TrueValue="Collapsed" FalseValue="Visible"/> <local:BoolToBoolConverter x:Key="InverseBoolConverter" TrueValue="False" FalseValue="True"/> </UserControl.Resources> <Grid> <Grid x:Name="MainGrid" IsEnabled="{Binding Path=ShowPopup, Converter={StaticResource InverseBoolConverter}}"> <Grid.Effect> <BlurEffect Radius="0"/> </Grid.Effect> <Grid.Resources> <DoubleAnimation x:Key="BlurGrid" Storyboard.TargetProperty="(UIElement.Effect).(BlurEffect.Radius)" From="0" To="20" Duration="0:0:0.5"/> <DoubleAnimation x:Key="UnblurGrid" Storyboard.TargetProperty="(UIElement.Effect).(BlurEffect.Radius)" From="20" To="0" Duration="0:0:0.5"/> </Grid.Resources> <Grid.Style> <Style TargetType="{x:Type Grid}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=ShowPopup}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="BlurGrid"/> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <DataTrigger.ExitActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="UnblurGrid"/> </Storyboard> </BeginStoryboard> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> </Grid.Style> <Grid.RowDefinitions> <RowDefinition Height="7*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <local:PromptTextBoxView Grid.Row="0" Visibility="{Binding Path=IsTextBox, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True"/> <local:PromptListView Grid.Row="0" Visibility="{Binding Path=IsList, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True"/> <local:PromptMessageView Grid.Row="0" Visibility="{Binding Path=IsMessage, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True"/> <local:PromptFinishMessageView Grid.Row="0" Visibility="{Binding Path=IsFinishMessage, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True"/> <local:PromptHoldMessageView Grid.Row="0" Visibility="{Binding Path=IsHoldMessage, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True"/> <Grid Grid.Row="1" Style="{StaticResource StylesGridNavigation}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Viewbox Grid.Column="0" HorizontalAlignment="Left"> <StackPanel Orientation="Horizontal"> <Button Command="{Binding CancelCommand}" Style="{StaticResource StylesButtonCancel}" Visibility="{Binding Path=HideBackCancelButtons, Converter={StaticResource BoolToInvisCollapseConverter}}"/> <Button Command="{Binding BackCommand}" Style="{StaticResource StylesButtonBack}" Visibility="{Binding Path=HideBackCancelButtons, Converter={StaticResource BoolToInvisCollapseConverter}}"/> </StackPanel> </Viewbox> <Viewbox Grid.Column="1" Visibility="{Binding Path=IsLiveScaleWeight, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width=".25*"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid Grid.Column="0"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Viewbox Grid.Row="0" Margin="5,0,0,0"> <TextBlock Style="{DynamicResource LiveWeightText}">Current</TextBlock> </Viewbox> <Viewbox Grid.Row="1" Margin="5,0,0,0"> <TextBlock Style="{DynamicResource LiveWeightText}">Weight</TextBlock> </Viewbox> </Grid> <Viewbox Grid.Column="1" Margin="3,0,0,0"> <TextBlock Style="{DynamicResource LiveWeightText}">:</TextBlock> </Viewbox> <Viewbox Grid.Column="2" Margin="5,0"> <Label Content="{Binding DataContext.LiveScaleWeight, FallbackValue=LSW, RelativeSource={RelativeSource AncestorType={x:Type local:PromptView}}}" Style="{DynamicResource LiveWeightLabel}"/> </Viewbox> </Grid> </Viewbox> <Viewbox Grid.Column="1" Visibility="{Binding Path=IsLiveScaleWeight, Converter={StaticResource BoolToInvisibilityConverter}}"> <Label Content="{Binding DataContext.MessageToUser, FallbackValue=Steps, RelativeSource={RelativeSource AncestorType={x:Type local:PromptView}}}" Style="{DynamicResource LiveWeightLabel}"/> </Viewbox> <Viewbox Grid.Column="2" HorizontalAlignment="Right"> <Button Command="{Binding NextCommand}" Style="{StaticResource StylesButtonNext}" Visibility="{Binding Path=HideNext, Converter={StaticResource BoolToVisCollapseConverter}}"/> </Viewbox> <Viewbox Grid.Column="2" HorizontalAlignment="Right"> <Button Command="{Binding SettingsCommand}" Style="{DynamicResource StylesButtonSettings}" Visibility="{Binding ShowSettingsBtn, Converter={StaticResource BoolToVisibilityConverter}}" x:Name="SettingButton"/> </Viewbox> </Grid> </Grid> <Grid x:Name="PopupGrid" IsEnabled="{Binding Path=ShowConnectionAlert, Converter={StaticResource InverseBoolConverter}}"> <Grid.Effect> <BlurEffect Radius="0"/> </Grid.Effect> <Grid.Resources> <DoubleAnimation x:Key="BlurGrid" Storyboard.TargetProperty="(UIElement.Effect).(BlurEffect.Radius)" From="0" To="20" Duration="0:0:0.5"/> <DoubleAnimation x:Key="UnblurGrid" Storyboard.TargetProperty="(UIElement.Effect).(BlurEffect.Radius)" From="20" To="0" Duration="0:0:0.5"/> </Grid.Resources> <Grid.Style> <Style TargetType="{x:Type Grid}"> <Style.Triggers> <DataTrigger Binding="{Binding Path=ShowConnectionAlert}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="BlurGrid"/> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <DataTrigger.ExitActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="UnblurGrid"/> </Storyboard> </BeginStoryboard> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> </Grid.Style> <Grid Visibility="{Binding Path=ShowCancelConfirm, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="1*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:CancelView Width="Auto" Height="Auto" Grid.IsSharedSizeScope="True"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowAutoIdConfirm, Converter={StaticResource BoolToVisibilityConverter}}" Grid.IsSharedSizeScope="True" > <Grid.RowDefinitions> <RowDefinition Height=".5*"/> <RowDefinition Height="3*"/> <RowDefinition Height=".5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.IsSharedSizeScope="True" Stretch="Uniform"> <local:PromptAutoIdConfirmView Width="Auto" Height="Auto" Grid.IsSharedSizeScope="True"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowNameIdConfirm, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="3*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:PromptNameIdConfirmView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowSplitPercentConfirm, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height=".5*"/> <RowDefinition Height="3*"/> <RowDefinition Height=".5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:PromptSplitDetailsConfirmView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowAlert, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="2*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:AlertView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowPLCAlert, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height=".5*"/> <RowDefinition Height="3*"/> <RowDefinition Height=".5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:PLCAlertView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> <Grid Visibility="{Binding Path=ShowCountdownAlert, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height=".5*"/> <RowDefinition Height="3*"/> <RowDefinition Height=".5*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".5*"/> <ColumnDefinition Width="3*"/> <ColumnDefinition Width=".5*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:CountdownAlertView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> </Grid> <Grid Visibility="{Binding Path=ShowConnectionAlert, Converter={StaticResource BoolToVisibilityConverter}}"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="2*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Viewbox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <local:ConnectionAlertView Grid.IsSharedSizeScope="True" Width="Auto" Height="Auto"/> </Viewbox> </Grid> </Grid> </UserControl>
1053eaacd9cf4dfc815acf421c55cef9
{ "intermediate": 0.47642844915390015, "beginner": 0.39868542551994324, "expert": 0.12488618493080139 }
43,203
######################################################## # In this lab we'll see various examples of network visualization, # using different design idioms and layout options, # including adjacency matrix, dendrogram, circular tree and treemap ######################################################## # first set the working directory on your computer setwd('~/Dropbox/IS teaching/IS4335 data_vis/lab/R_codes') # load the libraries library(igraph) library(ggplot2) library(reshape2) # load the network data load("~/Dropbox/IS teaching/IS4335 data_vis/2024_files/NetData/data/kracknets.rda") krack_full_data <- cbind(advice_data_frame, friendship_tie = friendship_data_frame$friendship_tie, reports_to_tie = reports_to_data_frame$reports_to_tie) krack_full_nonzero_edges <- subset(krack_full_data_frame, (advice_tie > 0 | friendship_tie > 0 | reports_to_tie > 0)) attributes2 <- cbind(id = 1:nrow(attributes), attributes) # bind node id with attribute columns krack_full <- graph_from_data_frame(d = krack_full_nonzero_edges, directed = F, vertices = attributes2) ############################################################################## # 1. network properties ############################################################################## # last time in the lecture we have discussed network properties, # such as degree distribution, diameter/path length, and clustering coefficient # Many initial analyses of networks begin with degree distributions & distance, # and then move towards global summary statistics of the network. # # As a reminder, entering a question mark followed by a function # name (e.g., ?graph.density) pulls up the help file for that function. # This can be helpful to understand how, exactly, stats are calculated. # let's first see an example of degree distribution # in network language, degree is the number of connections that a node has deg_full <- degree(krack_full, mode="all") is.directed(krack_full) # if the graph is directed, we can check indegree and outdegree distributions separately # but since the graph is undirected, there is no need for that deg_full # the degree distribution shows how many ties that each node has mean(deg_full) #check average degree sd(deg_full) #check standard deviation # network diameter and average distance diameter(krack_full) mean_distance(krack_full) # diameter and average distance is very small given everyone is connected. # let's compare the full network to friendship and reports-to networks krack_friendship_only <- delete_edges(krack_full, E(krack_full)[edge_attr(krack_full, name = "friendship_tie") == 0]) krack_reports_to_only <- delete_edges(krack_full, E(krack_full)[edge_attr(krack_full, name = "reports_to_tie") == 0]) diameter(krack_friendship_only) diameter(krack_reports_to_only) # we see the diameters of the latter graphs are longer, since there are fewer ties # connecting people. however, everyone in the company is related to each other in someway # so the overall diameter and distance are very small # Density: the portion of potential connections in a network that are realized graph.density(krack_friendship_only) graph.density(krack_reports_to_only) # Transitivity: if a and b are connected, b and c are connected, # what's the likelihood that a and c are also connected? transitivity(krack_full) transitivity(krack_friendship_only) transitivity(krack_reports_to_only) ############################################################################## # 2. network visualization examples: graph layout and adjacency matrix ############################################################################## # last time we saw visualization of network connections # the Fruchterman and Reingold's layout in week 8 lab uses a force-directed placement algorithm. # let's play with other layout functions # first Reingold-Tilford tree plot(krack_full, vertex.color=dept_vertex_colors, layout = layout_as_tree(krack_full)) # alternatively, you can first calculate the layout and then pass it into the plot layout <- layout_as_tree(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) # circle layout <- layout_in_circle(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) # star layout <- layout_as_star(krack_full) plot(krack_full, vertex.color=dept_vertex_colors, layout = layout) ############################################################################## # 3. community structure + adjacency matrix ############################################################################## # the friendship pattern is unclear and it's better to cluster nodes by community memberships # ties within communities are denser since nodes have closer relationships. # there are several ways to create communities, a common method is to use edge betweenness: # The betweenness score of an edge measures the number of # shortest paths from one node to another that go through it. # The idea of the edge-betweenness based community structure # is that it is likely that edges connecting separate # cluster have high edge-betweenness, as all the shortest paths # from one cluster to another must traverse through them. So if we # iteratively remove the edge with the highest betweenness # score we will get a hierarchical map of the communities in the graph. # The following function performs community detection using the edge betweenness algorithm friend_comm <- cluster_edge_betweenness(krack_friendship_only, weights = NULL, directed=F) friend_comm # community membership of each node can be queried as follows: friend_comm$membership # Visualize the network with community memberships plot(friend_comm, krack_friendship_only) # communities are colored in different shades, and nodes within the same communities are clustered together # This process also lends itself to visualization as a dendrogram. # The y-axis reflects the distance metric used by the edge betweenness algorithm plot(as.dendrogram(friend_comm)) # the tree branches show membership hierarchies. nodes belonging to the same community share common roots # the y-axis is a distance measure showing how far apart are nodes # now we can rearrange nodes by their community memberships # first create a data frame that records node id and communities # and reorder node id's by membership affiliation membership <- data.frame(cbind(friend_comm$membership, friend_comm$names)) names(membership) <- c('group','id') class(membership$group). # string var membership$group <- as.numeric(membership$group) membership <- membership[order(membership$group),] # sort data frame by the group column ######################################################################## # 4. Adjacency matrix plots ######################################################################## # the previous graphs all show node-link diagrams. but how do we visualize networks as adjacency matrix? # let's first get the adjacency matrix of krack_full using friendship ties only: krack_friend <- as.matrix(as_adjacency_matrix(krack_full, attr='friendship_tie')) krack_friend # some of the edges are redundant since there are multiple tie types, so the matrix cell values could be > 1 # we want to remove the redundant ties by converting matrix to binary 0/1 values krack_friend[krack_friend>1] <- 1 # convert matrix to binary # we'll use the ggplot2 library to plot the adjacency matrix. but first we need to convert the matrix into a data frame. # this could be done using the melt function from reshape2: krack_friend_long <-melt(krack_friend) head(krack_friend_long) names(krack_friend_long) <- c('from','to','tie') # convert first two columns to factors, since id's are discrete categories krack_friend_long$from <- factor(krack_friend_long$from) krack_friend_long$to <- factor(krack_friend_long$to) # Create the adjacency matrix plot using ggplot2 # we plot the matrix using color tiles, each tile represent the friendship relations btw two nodes. # nodes with friendship ties are colored as red, otherwise left blank # baseline plot ggplot(krack_friend_long[krack_friend_long$tie>0,], aes(x = from, y = to, fill = factor(tie))) + geom_raster() + # create rectangular tiles when all the tiles are the same size. can also use geom_tile() labs(x='', y='', fill='Friend') + scale_fill_manual(values=c('red','grey90'), # manually define colors that correspond to the levels in fill breaks=c(1,0), # how to order legend for fill labels=c('yes','no')) + # legend label. here we only have "yes" theme_bw() + theme(aspect.ratio = 1) # Force the plot into a square aspect ratio # how do we reorder the graph based on community affiliations? # recall we have membership affiliations from before: membership # Reorder edge list "from" and "to" factor levels based on the ids ordered by membership affiliations # in factor(), arg "levels" can specify how we want the factor levels to be ordered krack_friend_long$from <- factor(krack_friend_long$from, levels = membership$id) krack_friend_long$to <- factor(krack_friend_long$to, levels = membership$id) # include membership info of from and to nodes using join function. # first change the names of the membership columns to be matched with plot_data names(membership) <- c('from_group','from') # memebership of ego plot_data <- krack_friend_long %>% plyr::join(membership, by='from') # plyr::join calls the join function from plyr library names(membership) <- c('to_group','to') # memebership of alter plot_data <- plot_data %>% plyr::join(membership, by='to') names(plot_data) # membership info added # adding membership affiliations of nodes allow us to color in-group and out-group ties separately # here we want to color in-group ties by communities, and out-group ties as grey # how do we do that? # first we identify ties between members of the same community for in-group ties: from_group = to_group # if from_group != to_group, then the tie is an out-group tie # the info is stored in memb_tie variable plot_data$memb_tie <- 0 # default is out-group plot_data$memb_tie[plot_data$from_group==plot_data$to_group] <- 1 # mark out within-group ties plot_data$memb_tie[plot_data$memb_tie==1] <- plot_data$from_group[plot_data$memb_tie==1] # replace the marker with group info plot_data$memb_tie # Now run the ggplot code again, include ties with non-zero values and color ties based on membership # within-group ties have different colors, while between-group ties are all grey # improved plot ggplot(plot_data[plot_data$tie>0,], aes(x = from, y = to, fill = factor(memb_tie))) + geom_raster() + labs(x='', y='', fill='Within-community ties') + scale_fill_manual(values = c('grey','magenta','darkgreen','royalblue')) + # manually set community colors scale_x_discrete(drop = FALSE) + scale_y_discrete(drop = FALSE) + theme_bw() + theme(aspect.ratio = 1) # nodes of the same communities are placed close to each other, # and we can now see some group structure from this adjacency matrix plot. # between-group ties are colored as grey, and within-group ties are colored according to membership affiliations # the advantage of adjacency matrix representation is that: # a) scalable, less messy than node-link diagrams when the number of nodes is large # b) community structures are easier to spot ######################################################################## # 5. radial tree & treemaps ######################################################################## # A treemap is a space-filling visualization of hierarchical structures. The treemap package offers great flexibility to draw it install.packages('treemap') library(treemap) library(dplyr) # radial tree: # use the treegraph function in the treemap package. # index: vector of column names that specify the aggregation indices. It could # contain only one column name, which results in a treemap without hierarchy. # If multiple column names are provided, the first name is the highest aggregation level, # the second name the second-highest aggregation level, and so on. treegraph(krack_friend_long[krack_friend_long$tie==1,], index = c('from','to'), directed=F, show.labels=T) # here we map out the friendship connections among nodes using hierarchical tree structure. # there's an artificial root in the center, and each node in the second layer corresponds to a node in the "from" column # the third layer consists of nodes in the "to" column connected to the source node in the "from" column # calculate degrees of source nodes by counting number of connections krack_friend_degree <- krack_friend_long %>% group_by(from) %>% summarise(degree = sum(tie)) krack_treemap <- plyr::join(krack_friend_long, krack_friend_degree, by='from') # index treemap: colors are determined by the index argument # different branches in the hierarchical tree get different colors. # in this case, colors are defined by the source nodes # size of the rectangles are defined by the vSize argument, # the higher the degree count, the bigger the rectangle size treemap(krack_treemap[krack_treemap$tie==1,], index = c('from','to'), vSize = 'degree', type="index") ######################################################################## # 6. week 9 assignment: due on Sunday midnight ######################################################################## # Task 1. visualize all network ties in krack_full using the adjacency matrix. # color edges according to friendship, advice, and reports-to ties # Task 2. cluster nodes by community membership using the friendship network, and replot the adjacency matrix # with nodes belonging to the same communities placed close to each other. # construct a new variable, tie strength, which is the combination of friendship, advice, and reports-to ties # this counts the types of relationships between two nodes # Task 3. use radial tree to visualize the reports-to network, and a treemap to show the advice network. # in the treemap, set size proportional to ego's degrees from the advice and reports-to networks
b62ec9cc757d6fc7a6e2475522e54e8d
{ "intermediate": 0.4504823088645935, "beginner": 0.2639535963535309, "expert": 0.2855640649795532 }
43,204
# Task 1. visualize all network ties in krack_full using the adjacency matrix. # color edges according to friendship, advice, and reports-to ties # Task 2. cluster nodes by community membership using the friendship network, and replot the adjacency matrix # with nodes belonging to the same communities placed close to each other. # construct a new variable, tie strength, which is the combination of friendship, advice, and reports-to ties # this counts the types of relationships between two nodes # Task 3. use radial tree to visualize the reports-to network, and a treemap to show the advice network. # in the treemap, set size proportional to ego's degrees from the advice and reports-to networks
3b270d4bc5d7f4a5cb1a251663a80005
{ "intermediate": 0.3853549361228943, "beginner": 0.25620871782302856, "expert": 0.35843634605407715 }
43,205
from tkinter import * from tkinter.colorchooser import askcolor class Paint(object): DEFAULT_PEN_SIZE = 5.0 DEFAULT_COLOR = 'black' def __init__(self): self.root = Tk() self.pen_button = Button(self.root, text='pen', command=self.use_pen) self.pen_button.grid(row=0, column=0) self.brush_button = Button(self.root, text='brush', command=self.use_brush) self.brush_button.grid(row=0, column=1) self.color_button = Button(self.root, text='color', command=self.choose_color) self.color_button.grid(row=0, column=2) self.eraser_button = Button(self.root, text='eraser', command=self.use_eraser) self.eraser_button.grid(row=0, column=3) self.choose_size_button = Scale(self.root, from_=1, to=100, orient=HORIZONTAL) self.choose_size_button.grid(row=0, column=4) self.c = Canvas(self.root, bg='white', width=600, height=600) self.c.grid(row=1, columnspan=5) self.setup() self.root.mainloop() def setup(self): self.old_x = None self.old_y = None self.line_width = self.choose_size_button.get() self.color = self.DEFAULT_COLOR self.eraser_on = False self.active_button = self.pen_button self.c.bind('<B1-Motion>', self.paint) self.c.bind('<ButtonRelease-1>', self.reset) def use_pen(self): self.activate_button(self.pen_button) def use_brush(self): self.activate_button(self.brush_button) def choose_color(self): self.eraser_on = False self.color = askcolor(color=self.color)[1] def use_eraser(self): self.activate_button(self.eraser_button, eraser_mode=True) def activate_button(self, some_button, eraser_mode=False): self.active_button.config(relief=RAISED) some_button.config(relief=SUNKEN) self.active_button = some_button self.eraser_on = eraser_mode def paint(self, event): self.line_width = self.choose_size_button.get() paint_color = 'white' if self.eraser_on else self.color if self.old_x and self.old_y: self.c.create_line(self.old_x, self.old_y, event.x, event.y, width=self.line_width, fill=paint_color, capstyle=ROUND, smooth=TRUE, splinesteps=36) self.old_x = event.x self.old_y = event.y def reset(self, event): self.old_x, self.old_y = None, None if __name__ == '__main__': Paint() Here is my paint app. add features as rectangle, circle, inserting text, changing brushes, save, load,background color select
1145a450694713d6f2b6f865700a6ee3
{ "intermediate": 0.34728413820266724, "beginner": 0.47566840052604675, "expert": 0.177047461271286 }
43,206
write in arm 64 bit assembly using a 64 bit linux system a program that takes user input an prints it
58b476ba18ad27e14d4f99bc9198f2b1
{ "intermediate": 0.3074670433998108, "beginner": 0.41437235474586487, "expert": 0.27816057205200195 }
43,207
hi
4589db21f58db18fd249b0b8807d70eb
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,208
how did transformers tokenizer to encode special tokens
4b89c8fbc27a9738e9accbf5704b3719
{ "intermediate": 0.2599467635154724, "beginner": 0.15230803191661835, "expert": 0.587745189666748 }
43,209
Abel and Cain are interested in investing, so they decide to pool their money to buy some stocks. They talk to a consultant, who explained some of their investment types and their returns as compared to the market average. Their choices are to invest in high or low capital stocks and domestic or international. The follow is a summary of the data for the last quarter: Domestic International High Capital Stock 300 50 Low Capital Stock 175 20 High Capital stock with below average showing 60 9 Low Capital stock with below average showing 9 3 1. Draw a Venn diagram that models this information, including labels
8b11b61b7dbf8c56a02bfef4b75e420f
{ "intermediate": 0.3412313759326935, "beginner": 0.407318651676178, "expert": 0.25144997239112854 }
43,210
Hello
039fed28f165ca39c8b2cdc30709041c
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
43,211
hi
b82f81971a8c8ea54b448fb54e187af6
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,212
Netlist code: NM0 (net11 IN1 net10 net10) n_12_llhvt l=L1 w=W1 sa=0.175u sb=0.175u nf=1 mis_flag=1 sd=0.23u as=0.175u ad=0.175u ps=0 pd=0 sca=8.8889e-08 scb=2.64566e-09 scc=1.05426e-09 m=1 mf=1 PM0 (net11 net11 vdd! vdd!) p_12_llhvt l=L5 w=W5 sa=0.175u sb=0.175u nf=1 mis_flag=1 sd=0.23u as=0.175u ad=0.175u ps=0 pd=0 sca=8.8889e-08 scb=2.64566e-09 scc=1.05426e-09 m=1 mf=1 For this above netlist code, i am getting the following phrasing expression, nmos_pattern = re.compile(r'(NM\d+) \((.*?)\) .* l=([\d\.]+(?:e[\+\-]?\d+)?|\w+) w=([\d\.]+(?:e[\+\-]?\d+)?|\w+)') pmos_pattern = re.compile(r'(PM\d+) \((.*?)\) .* l=([\d\.]+(?:e[\+\-]?\d+)?|\w+) w=([\d\.]+(?:e[\+\-]?\d+)?|\w+)') Similarly i need to phrasing expression for the below netlist code M0 (net3 IN1 net1 0) n_18_mm w=W1/1 l=L1 nf=1 mis_flag=1 \ ad=((1.4e-07+400.0n)*W1/1*(1-1)/2)+((9e-08+400.0n)*W1/1)/1 \ as=((1.4e-07+400.0n)*W1/1*(1-1)/2)+((9e-08+400.0n)*W1/1)/1 \ pd=(2*((1.4e-07+400.0n)+W1/1)*(1-1)/2+2*((9e-08+400.0n)+W1/1))/1 \ ps=(2*((1.4e-07+400.0n)+W1/1)*(1-1)/2+2*((9e-08+400.0n)+W1/1))/1 \ m=(1)*(1) mf=(1)*(1) M5 (VOUT net2 vdd! vdd!) p_18_mm w=W6/1 l=L6 nf=1 mis_flag=1 \ ad=((1.4e-07+400.0n)*W6/1*(1-1)/2)+((9e-08+400.0n)*W6/1)/1 \ as=((1.4e-07+400.0n)*W6/1*(1-1)/2)+((9e-08+400.0n)*W6/1)/1 \ pd=(2*((1.4e-07+400.0n)+W6/1)*(1-1)/2+2*((9e-08+400.0n)+W6/1))/1 \ ps=(2*((1.4e-07+400.0n)+W6/1)*(1-1)/2+2*((9e-08+400.0n)+W6/1))/1 \ m=(1)*(1) mf=(1)*(1) Here All the transistors (nmos/pmos) are represents as M (M1, M2,...), but the transistor belongs to 'nmos' has 'n_18_mm' in its netlist code and the transistor belongs to 'pmos' has 'p_18_mm' in its netlist code. For the 'nmos_pattern' we need to write phrasing pattern where the netlist has the 'n_18_mm' in it, similarly for the 'pmos_pattern', 'p_18_mm'.
16f5db3da430dc425892b9806bd92038
{ "intermediate": 0.3160034418106079, "beginner": 0.4352661967277527, "expert": 0.2487303614616394 }
43,213
In Python programming language what is the difference between recursions, exceptions and loops? Explain like I am a layperson.
192dc10908d3e019a19a2458c2dc127d
{ "intermediate": 0.15190711617469788, "beginner": 0.6811004281044006, "expert": 0.16699248552322388 }
43,214
what is I/O : Direct memory access
65829729c5e60d34cfeaeb37c8f397a6
{ "intermediate": 0.282595694065094, "beginner": 0.4083443284034729, "expert": 0.3090599775314331 }
43,215
i have historical data of some cryptocurrencies containing OHLCV data Give me the proper python code to calculate different time frames of rsi indicators for it
3c11ea175badbf18a75201908ecfdb1d
{ "intermediate": 0.5575100779533386, "beginner": 0.15206454694271088, "expert": 0.2904253602027893 }
43,216
i have historical data of some cryptocurrencies containing OHLCV data Give me the proper python code to calculate different ranges of rsi indicators for it (12 days,15 days,30days,...) and ad them to file as new column
5186426348bff7b399f2829b0225d8d8
{ "intermediate": 0.5708820223808289, "beginner": 0.15483088791370392, "expert": 0.2742871046066284 }
43,217
как из cashBox достать owner, а из owner INN Subgraph<Product> productSubgraph = acquiringOperationSubgraph.addSubgraph("product"); productSubgraph.addAttributeNodes("cashBox");
09c119faa06aa3d44468e3715943adbb
{ "intermediate": 0.3133363127708435, "beginner": 0.3307264447212219, "expert": 0.3559372127056122 }
43,218
create an express app for my mernstack app . it needs to connect to mongodo atlas. it needs to have login and signup functionality
c486f1cdd8c95b1cdf8b5a32c22e95bf
{ "intermediate": 0.46133944392204285, "beginner": 0.19989775121212006, "expert": 0.3387628197669983 }
43,219
Mendel used pea plants and discovered that some traits completely cover another up. This type of inheritance is known as
b3e826cfbdfc8e7ff934e232f8089d49
{ "intermediate": 0.3816106617450714, "beginner": 0.2920784652233124, "expert": 0.326310932636261 }
43,220
@Prop() targetDisks: any[] @Prop() takenTargetDisks: { [key: string]: boolean } как переписать на vue 3 composition api
0c859aa732c3968469f77553068aab87
{ "intermediate": 0.5112100839614868, "beginner": 0.2740144729614258, "expert": 0.21477536857128143 }
43,221
give me the pyhton code of calculating ma,ema ,sma using ralib library python just send code quick
9517c09ff0cd6711b2dfd94c62f26b40
{ "intermediate": 0.5940715074539185, "beginner": 0.1008065864443779, "expert": 0.30512186884880066 }
43,222
#!/usr/bin/env python """Example of a simple chatbot that just passes current conversation state back and forth between server and client. """ from typing import List, Union from fastapi import FastAPI from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langserve import add_routes from langserve.pydantic_v1 import BaseModel, Field app = FastAPI( title="LangChain Server", version="1.0", description="Spin up a simple api server using Langchain's Runnable interfaces", ) # Declare a chain prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful, professional assistant named Cob."), MessagesPlaceholder(variable_name="messages"), ] ) chain = prompt | ChatGoogleGenerativeAI(model="gemini-pro",google_api_key="AIzaSyDvzDtQvKAOpRPP9KNVo_naMSwPhFxnkZM",transport="rest",convert_system_message_to_human=True) class InputChat(BaseModel): """Input for the chat endpoint.""" messages: List[Union[HumanMessage, AIMessage, SystemMessage]] = Field( ..., description="The chat messages representing the current conversation.", ) add_routes( app, chain.with_types(input_type=InputChat), enable_feedback_endpoint=True, enable_public_trace_link_endpoint=True, playground_type="chat", ) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="localhost", port=8000). 看一下这个代码有什么问题?
089b20a016ef9280c8bf2daba09395ce
{ "intermediate": 0.3739755153656006, "beginner": 0.3529990017414093, "expert": 0.2730255126953125 }
43,223
Get random position between two points unity
eceea768c886426922d7f6bd02166518
{ "intermediate": 0.2964487075805664, "beginner": 0.24389895796775818, "expert": 0.4596523344516754 }
43,224
create am express app for my mern stack app/ it needs to connect to mongodb atlas. it needs to have login and register functionality. i want to use jsonwebokens
e3f7df541326f4e9c4612daecf942432
{ "intermediate": 0.5599969029426575, "beginner": 0.2061796337366104, "expert": 0.2338234931230545 }
43,225
program to play music with pc speaker linux
248036acb8ae8f75c68d0db96b5b367d
{ "intermediate": 0.3192735016345978, "beginner": 0.28510501980781555, "expert": 0.39562147855758667 }
43,226
can you give me a curl command that will upload files from my gitlab pipeline into my nexus repository?
7b31dfe9a12266372e1e91b1a54db130
{ "intermediate": 0.5973899364471436, "beginner": 0.1673843115568161, "expert": 0.23522576689720154 }
43,227
write a django python decorators that allows for multi processing the function if it is cpu bound or multi threading if it is I/O ( identfied by ean argument to the decorator )
71c58b5c61398d03dac7c0668b6d07ae
{ "intermediate": 0.5814663767814636, "beginner": 0.15787075459957123, "expert": 0.2606629431247711 }
43,228
Create an express app that will connect to mongodb atlas . it needs to have login., and register functionality. i wan to use jsonwebtokens. the user needs to th
eb88b6400687c0c20c228093d14e4f66
{ "intermediate": 0.4262183606624603, "beginner": 0.3095981478691101, "expert": 0.26418352127075195 }
43,230
tell me about std::unique_ptr
8652f21b6ec435dd694e5cd44b02a21f
{ "intermediate": 0.4856577217578888, "beginner": 0.2872295379638672, "expert": 0.2271127700805664 }
43,231
Hello
64fe8a87a49d880d9448f1934c08c618
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
43,232
connect to someone elses local ip mysql database using python db=mysql.connector.connect(host = '10.2.138.227',user = "nilanjana",password = "Ni07-De10",database = "project")
5e0929e57b095ab2d66359ea050c943e
{ "intermediate": 0.3485381603240967, "beginner": 0.27233362197875977, "expert": 0.37912821769714355 }
43,233
Is there a way to capture the client local ip in chrome
b30a03b35b5fc48380bd5826facbe7d2
{ "intermediate": 0.39685356616973877, "beginner": 0.2720581293106079, "expert": 0.33108824491500854 }
43,234
Is there a way to capture the client local ip using typescript?
c9e948ed280a939330eb9e1f4c6e3e82
{ "intermediate": 0.3807543218135834, "beginner": 0.28579458594322205, "expert": 0.33345112204551697 }
43,235
How to merge these arrays Collider[] hitColliders = Physics.OverlapSphere(transform.position, detectionRadius, targetLayer, QueryTriggerInteraction.Collide); Collider[] hitColliders = Physics.OverlapSphere(transform.position, detectionRadius, buildingsLayer, QueryTriggerInteraction.Collide);
079815a252b9c6306c1cb955e4dac7a1
{ "intermediate": 0.49491676688194275, "beginner": 0.23641614615917206, "expert": 0.268667072057724 }
43,236
import numpy as np import plotly.graph_objects as go import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection from skimage import measure from skimage.draw import ellipsoid import nibabel as nib import plotly.express as px fig= plt.figure() brain_path = "C:\\Users\\reddy\\Downloads\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\\BraTS20_Training_170\\BraTS20_Training_170_flair.nii" seg_path = "C:\\Users\\reddy\\Downloads\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\\BraTS20_Training_170\\BraTS20_Training_170_seg.nii" im = nib.load(brain_path).get_fdata() seg = nib.load(seg_path).get_fdata() ellip_base = ellipsoid(6, 10, 16, levelset=True) verts, faces, normals, values = measure.marching_cubes(ellip_base, 0) x, y, z = verts.T i, j, k = faces.T brain_parts = [ {'img':im, 'color':'gray', 'level':0}, {'img':seg, 'color':'purple', 'level':0}, {'img':seg, 'color':'red', 'level':1}, {'img':seg, 'color':'yellow', 'level':2}, {'img':seg, 'color':'blue', 'level':3} ] meshes = [] for part in brain_parts: print(part['color'],part['level']) verts, faces, normals, values = measure.marching_cubes(part['img'], part['level']) x, y, z = verts.T i, j, k = faces.T mesh = go.Mesh3d(x=x, y=y, z=z,color=part['color'], opacity=0.5, i=i, j=j, k=k) meshes.append(mesh) verts, faces, normals, values = measure.marching_cubes(im, 0) x, y, z = verts.T i, j, k = faces.T mesh = go.Mesh3d(x=x, y=y, z=z, opacity=0.5, i=i, j=j, k=k) full = go.Figure(data=[mesh]) full.show() verts, faces, normals, values = measure.marching_cubes(im, 0) x, y, z = verts.T i, j, k = faces.T mesh1 = go.Mesh3d(x=x, y=y, z=z,color='gray', opacity=0.5, i=i, j=j, k=k) verts, faces, normals, values = measure.marching_cubes(seg, 2) x, y, z = verts.T i, j, k = faces.T mesh2 = go.Mesh3d(x=x, y=y, z=z, color='yellow', opacity=0.5, i=i, j=j, k=k) tumor = go.Figure(data=[mesh1, mesh2]) tumor.show() complete = go.Figure(data=meshes) complete.show() make it so that each plot is shown in a different html file
ef220f86edba937a546c8c4e48c25926
{ "intermediate": 0.3775123655796051, "beginner": 0.33376041054725647, "expert": 0.2887272536754608 }
43,237
hi
6e6bca94a4de85f3d9684b6230132936
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
43,238
voglio trasformare questo indicatore in un EA per mt4. //------------------------------------------------------------------ #property copyright "www.forex-station.com" #property link "www.forex-station.com" //------------------------------------------------------------------ #property indicator_separate_window #property indicator_buffers 10 #property indicator_color1 clrSilver #property indicator_color2 clrSilver #property indicator_color3 clrSilver #property indicator_color4 clrDimGray #property indicator_color5 clrDimGray #property indicator_color6 clrLightGray #property indicator_style2 STYLE_DOT #property strict // // // // // enum enMaTypes { avgSma, // Simple moving average avgEma, // Exponential moving average avgSmma, // Smoothed MA avgLwma // Linear weighted MA }; enum enColorOn { cc_onSlope, // Change color on slope change cc_onMiddle, // Change color on middle line cross cc_onLevels // Change color on outer levels cross }; extern ENUM_TIMEFRAMES TimeFrame = PERIOD_CURRENT; // Time frame extern string ForSymbol = ""; // For symbol (leave empty for current chart symbol) input int MomentumPeriod = 25; // Momentum period input int AvgPeriod = 0; // Momentum average period (0 -> same as momentum period) input enMaTypes AvgType = avgEma; // Momentum average method input int SmoPeriod = 0; // Smoothing average period (0 -> same as momentum period) input double ZoneUp = 70; // Upper zone limit input double ZoneDown = 30; // Lower zone limit extern enColorOn ColorOn = cc_onLevels; // Color change : extern color ColorUp = clrLimeGreen; // Color for up extern color ColorDown = clrOrangeRed; // Color for down extern int LineWidth = 3; // Main line width extern bool Interpolate = true; // Interpolate in multi time frame? // // // // // double mom[]; double momUa[]; double momUb[]; double momDa[]; double momDb[]; double levup[]; double levmi[]; double levdn[]; double trend[],shadowa[],shadowb[],diff[]; string indicatorFileName,shortName; bool returnBars; //------------------------------------------------------------------ // //------------------------------------------------------------------ // // // // // int init() { IndicatorBuffers(12); SetIndexBuffer(0,levup); SetIndexBuffer(1,levmi); SetIndexBuffer(2,levdn); SetIndexBuffer(3,shadowa); SetIndexStyle(3,EMPTY,EMPTY,LineWidth+4); SetIndexBuffer(4,shadowb); SetIndexStyle(4,EMPTY,EMPTY,LineWidth+4); SetIndexBuffer(5,mom); SetIndexStyle(5,EMPTY,EMPTY,LineWidth); SetIndexBuffer(6,momUa); SetIndexStyle(6,EMPTY,EMPTY,LineWidth,ColorUp); SetIndexBuffer(7,momUb); SetIndexStyle(7,EMPTY,EMPTY,LineWidth,ColorUp); SetIndexBuffer(8,momDa); SetIndexStyle(8,EMPTY,EMPTY,LineWidth,ColorDown); SetIndexBuffer(9,momDb); SetIndexStyle(9,EMPTY,EMPTY,LineWidth,ColorDown); SetIndexBuffer(10,trend); SetIndexBuffer(11,diff); // // // // // indicatorFileName = WindowExpertName(); returnBars = (TimeFrame==-99); TimeFrame = MathMax(TimeFrame,_Period); if (ForSymbol=="") ForSymbol = _Symbol; shortName = ForSymbol+" "+timeFrameToString(TimeFrame)+" momentum pinball ("+(string)MomentumPeriod+","+(string)AvgPeriod+","+(string)SmoPeriod+")"; IndicatorShortName(shortName); return(0); } int deinit() { return (0); } //------------------------------------------------------------------ // //------------------------------------------------------------------ // // // // // int start() { int counted_bars=IndicatorCounted(); if(counted_bars < 0) return(-1); if(counted_bars > 0) counted_bars--; int window = WindowFind(shortName); int limit = MathMin(Bars-counted_bars,Bars-1); if (returnBars) { levup[0] = limit+1; return(0); } if (TimeFrame != _Period || ForSymbol!=_Symbol) { limit = (int)MathMax(limit,MathMin(Bars-1,iCustom(ForSymbol,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period())); if (trend[limit]== 1) { CleanPoint(limit,momUa,momUb); CleanPoint(limit,shadowa,shadowb); } if (trend[limit]==-1) { CleanPoint(limit,momDa,momDb); CleanPoint(limit,shadowa,shadowb); } for(int i=limit; i>=0; i--) { int y = iBarShift(NULL,TimeFrame,Time[i]); mom[i] = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",MomentumPeriod,AvgPeriod,AvgType,SmoPeriod,ZoneUp,ZoneDown,ColorOn, 5,y); trend[i] = iCustom(ForSymbol,TimeFrame,indicatorFileName,PERIOD_CURRENT,"",MomentumPeriod,AvgPeriod,AvgType,SmoPeriod,ZoneUp,ZoneDown,ColorOn,10,y); momDa[i] = EMPTY_VALUE; momDb[i] = EMPTY_VALUE; momUa[i] = EMPTY_VALUE; momUb[i] = EMPTY_VALUE; levup[i] = ZoneUp; levdn[i] = ZoneDown; levmi[i] = (levup[i]+levdn[i])/2.0; shadowa[i] = EMPTY_VALUE; shadowb[i] = EMPTY_VALUE; if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue; // // // // // int n,j; datetime time = iTime(NULL,TimeFrame,y); for(n = 1; (i+n)<Bars && Time[i+n] >= time; n++) continue; for(j = 1; j<n && (i+n)<Bars && (i+j)<Bars; j++) mom[i+j] = mom[i] + (mom[i+n] - mom[i] )*j/n; } for(int i=limit; i>=0; i--) { if (i<Bars-1 && trend[i] == 1) { PlotPoint(i,momUa,momUb,mom); PlotPoint(i,shadowa,shadowb,mom); } if (i<Bars-1 && trend[i] == -1) { PlotPoint(i,momDa,momDb,mom); PlotPoint(i,shadowa,shadowb,mom); } } return(0); } // // // // // int avgPeriod = AvgPeriod; if (avgPeriod<=0) avgPeriod = MomentumPeriod; int smoPeriod = SmoPeriod; if (smoPeriod<=0) smoPeriod = MomentumPeriod; if (trend[limit]== 1) { CleanPoint(limit,momUa,momUb); CleanPoint(limit,shadowa,shadowb); } if (trend[limit]==-1) { CleanPoint(limit,momDa,momDb); CleanPoint(limit,shadowa,shadowb); } for (int i=limit; i>=0; i--) { if (i>=Bars-MomentumPeriod) { diff[i] = 0; iCustomMa(AvgType,0,avgPeriod,i,0); iCustomMa(AvgType,0,avgPeriod,i,1); continue; } diff[i] = iCustomMa(AvgType,Close[i]-Close[i+MomentumPeriod],smoPeriod,i,0); double u=0,d=0; if (diff[i]>diff[i+1]) u=diff[i]-diff[i+1]; if (diff[i]<diff[i+1]) d=diff[i+1]-diff[i]; // // // // // double avgu = iCustomMa(AvgType,u,avgPeriod,i,1); double avgd = iCustomMa(AvgType,d,avgPeriod,i,2); if (avgd!=0) mom[i] = 100.0-100.0/(1.0+(avgu/avgd)); else mom[i] = 50; // // // // // levup[i] = ZoneUp; levdn[i] = ZoneDown; levmi[i] = (levup[i]+levdn[i])/2.0; momDa[i] = EMPTY_VALUE; momDb[i] = EMPTY_VALUE; momUa[i] = EMPTY_VALUE; momUb[i] = EMPTY_VALUE; trend[i] = 0; switch(ColorOn) { case cc_onLevels: if (mom[i]>levup[i]) trend[i] = 1; if (mom[i]<levdn[i]) trend[i] = -1; break; case cc_onMiddle: if (mom[i]>levmi[i]) trend[i] = 1; if (mom[i]<levmi[i]) trend[i] = -1; break; default : if (i<Bars-1) { if (mom[i]>mom[i+1]) trend[i] = 1; if (mom[i]<mom[i+1]) trend[i] = -1; } } // // // // // shadowa[i] = EMPTY_VALUE; shadowb[i] = EMPTY_VALUE; if (trend[i] == 1) { PlotPoint(i,momUa,momUb,mom); PlotPoint(i,shadowa,shadowb,mom); } if (trend[i] == -1) { PlotPoint(i,momDa,momDb,mom); PlotPoint(i,shadowa,shadowb,mom); } } return(0); } //------------------------------------------------------------------- // //------------------------------------------------------------------- // // // // // string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"}; int iTfTable[] = {1,5,15,30,60,240,1440,10080,43200}; string timeFrameToString(int tf) { for (int i=ArraySize(iTfTable)-1; i>=0; i--) if (tf==iTfTable[i]) return(sTfTable[i]); return(""); } // // // // // void CleanPoint(int i,double& first[],double& second[]) { if (i>=Bars-3) return; if ((second[i] != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE)) second[i+1] = EMPTY_VALUE; else if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE)) first[i+1] = EMPTY_VALUE; } void PlotPoint(int i,double& first[],double& second[],double& from[]) { if (i>=Bars-2) return; if (first[i+1] == EMPTY_VALUE) if (first[i+2] == EMPTY_VALUE) { first[i] = from[i]; first[i+1] = from[i+1]; second[i] = EMPTY_VALUE; } else { second[i] = from[i]; second[i+1] = from[i+1]; first[i] = EMPTY_VALUE; } else { first[i] = from[i]; second[i] = EMPTY_VALUE; } } //------------------------------------------------------------------ // //------------------------------------------------------------------ // // // // // #define _maInstances 3 #define _maWorkBufferx1 1*_maInstances #define _maWorkBufferx2 2*_maInstances double iCustomMa(int mode, double price, double length, int r, int instanceNo=0) { r = Bars-r-1; switch (mode) { case avgSma : return(iSma(price,(int)length,r,instanceNo)); case avgEma : return(iEma(price,length,r,instanceNo)); case avgSmma : return(iSmma(price,(int)length,r,instanceNo)); case avgLwma : return(iLwma(price,(int)length,r,instanceNo)); default : return(price); } } // // // // // double workSma[][_maWorkBufferx2]; double iSma(double price, int period, int r, int instanceNo=0) { if (period<=1) return(price); if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2; int k; // // // // // workSma[r][instanceNo+0] = price; workSma[r][instanceNo+1] = price; for(k=1; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo+0]; workSma[r][instanceNo+1] /= 1.0*k; return(workSma[r][instanceNo+1]); } // // // // // double workEma[][_maWorkBufferx1]; double iEma(double price, double period, int r, int instanceNo=0) { if (period<=1) return(price); if (ArrayRange(workEma,0)!= Bars) ArrayResize(workEma,Bars); // // // // // workEma[r][instanceNo] = price; double alpha = 2.0 / (1.0+period); if (r>0) workEma[r][instanceNo] = workEma[r-1][instanceNo]+alpha*(price-workEma[r-1][instanceNo]); return(workEma[r][instanceNo]); } // // // // // double workSmma[][_maWorkBufferx1]; double iSmma(double price, double period, int r, int instanceNo=0) { if (period<=1) return(price); if (ArrayRange(workSmma,0)!= Bars) ArrayResize(workSmma,Bars); // // // // // if (r<period) workSmma[r][instanceNo] = price; else workSmma[r][instanceNo] = workSmma[r-1][instanceNo]+(price-workSmma[r-1][instanceNo])/period; return(workSmma[r][instanceNo]); } // // // // // double workLwma[][_maWorkBufferx1]; double iLwma(double price, double period, int r, int instanceNo=0) { if (period<=1) return(price); if (ArrayRange(workLwma,0)!= Bars) ArrayResize(workLwma,Bars); // // // // // workLwma[r][instanceNo] = price; double sumw = period; double sum = period*price; for(int k=1; k<period && (r-k)>=0; k++) { double weight = period-k; sumw += weight; sum += weight*workLwma[r-k][instanceNo]; } return(sum/sumw); } le condizioni di entrata per il buy è quando il momentum diventa verde, mentre il sell quando diventa rosso. le condizioni di chiusura del trade sono per il buy quando non è più verde, per il sell quando non è più rosso. impostare lotto da utente
1baf1cc50b62270d69008640574937e5
{ "intermediate": 0.3752024173736572, "beginner": 0.3425244390964508, "expert": 0.28227314352989197 }
43,239
Given a natural number n and a chess board with 2^n squares on each side (the length of the side is 2^n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. For the L-shaped arrangement of three squares consider a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. In the first case a first square is empty i.e. it is a missing square in the upper left corner and the other 3 squares form an L-shaped arrangement. Similarly, in the second case a missing square is there in the upper right corner, in the third case a missing square is there in the lower right corner and in the fourth case a missing square is there in the lower left corner and the other squares are L-shaped arrangement. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. For instance, the coordinate of the missing square in the first case is (0, 1); the coordinate of the missing square in the second case is (1, 1). You will make a function called tromino as below. void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ); /* size of board, which is a power of 2*/ The main program should call tromino( 0, 0, x_missing, y_missing, board_size), which allows the user to input board_size by prompting the line “Please enter size of board as a power of 2 (0 to quit):” first, then to input coordinates of missing square for x_missing and y_missing by prompting the line “Please enter coordinates of missing square (separate by a space):”. If the board size from the user input is not a power of 2, please issue a message “The board size should be a power of 2” and prompt the same user input line “Please enter size of board as a power of 2 (0 to quit):”. For the tromino function below, void tromino /* function to do tiling */ ( int x_board, /* x coordinate of board */ int y_board, /* y coordinate of board */ int x_missing, /* x coordinate of missing square */ int y_missing, /* y coordinate of missing square */ int board_size ) /* size of board, which is a power of 2*/ you will need to set up the base case for board_size = 2. What you need to do in the base case is to decide which L shape to be put in the three squares. Please print “LR” (Lower Right) in all three squares for the L shape in first case, print “LL” (Lower Left) for the L shape in second case, “UL” (Upper Left) for the L shape in third case, “UR” (Upper Right) for the fourth L shape in fourth case. You will do the following four recursive calls for the four half_size (board_size/2) subboards: upper left subboard, upper right subboard, lower left subboard, and lower right subboard. /* tile the four subboards */ tromino( x_board, y_board + half_size, x_upper_left, y_upper_left, half_size ); tromino( x_board + half_size, y_board + half_size, x_upper_right, y_upper_right, half_size ); tromino( x_board, y_board, x_lower_left, y_lower_left, half_size ); tromino( x_board + half_size, y_board, x_lower_right, y_lower_right, half_size ); The main java program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first case), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR
2e748f868e7e1e3adabdd1679fb8f64d
{ "intermediate": 0.3161616623401642, "beginner": 0.441751092672348, "expert": 0.24208728969097137 }
43,240
is there a way to capture the requester ip on a program that uses aspnetboilerplate framework?
ab8cd4946eb713325014b49bbbe0f914
{ "intermediate": 0.5428130626678467, "beginner": 0.11292784661054611, "expert": 0.3442590832710266 }
43,241
what are the Most Commonly Used Periods in Creating Moving Average?
a37ea4a21203bd4ab7e97a23169b1609
{ "intermediate": 0.3421526551246643, "beginner": 0.24751299619674683, "expert": 0.41033434867858887 }
43,242
I need your help to write some Python code. This is what the code should do- I have a text file, titled "dob_pass.txt", the code should parse this file and find the value MATCH or MISMATCH in each of the lines. The code should pull these values, and put them into a column in the csv file "dob_pass.csv", such that the values pulled from the text file appear under a column titled "ai" in the csv file.
acf7db9acb96bcf596fc899edac895ff
{ "intermediate": 0.43654829263687134, "beginner": 0.20525230467319489, "expert": 0.3581993579864502 }
43,243
i want to delete following columns from my csv files: sma_5 sma_10 sma_20 sma_50 sma_100 sma_200 ema_9 ema_12 ema_20 ema_26 ema_50 ema_100 ema_200 wma_9 wma_14 wma_20 wma_50 wma_100 wma_200 rsi_14 rsi_9 rsi_25 rsi_50 rsi_100 rsi_200 give me proper python code
cd9730f695e5f1279eb5c0420c98b98c
{ "intermediate": 0.34226250648498535, "beginner": 0.4215553104877472, "expert": 0.23618216812610626 }
43,244
is there any way i can calculate all of TA-Lib library available indicators and... on my historical(OHLCV) data all at once?
1e7ad38c005698501f09cc9e1b5ca59a
{ "intermediate": 0.7320613861083984, "beginner": 0.09333080798387527, "expert": 0.17460773885250092 }
43,245
how can i implement macd using TA-Lib library python
41c776657b64298f374b5675c34ad2b1
{ "intermediate": 0.5006309747695923, "beginner": 0.08944813907146454, "expert": 0.40992093086242676 }
43,246
I have julia terminal on my computer i have also chrome, i want to open a .jl file (pluto notebook) what i should write on julia terminal please, i have the direction of the file
e21e1d632240e9a9b51ac21878c8b6e9
{ "intermediate": 0.35001885890960693, "beginner": 0.2185118943452835, "expert": 0.43146923184394836 }
43,247
Complete the below task with help of complete code: 1.Datset is 1000SATSFDUSD-30m-2024-03-19 from Klines daily data of 30 min from month march, print its statistics 2.You are required to implement DDQN on the dataset. 3. You are requested to implement only the DRL approach with DDQN. (i) Design a Trading Environment. (ii) State the state space and action space (iii) Clearly define the parameters used for training an AI agent. 1. Number of episodes 2. Max capacity of replay memory 3. Batch size 4. Period of Q target network updates 5. Discount factor for future rewards 6. Initial value for epsilon of the e-greedy 7. Final value for epsilon of the e-greedy 8. Learning rate of ADAM optimizer, and etc.. (iv) Define the functions for Buy, Sell and Hold actions. (v) Implement a replay buffer for storing the experiences. (vi) Design the Main Network (vii) Target Network (viii) Plot the graph for agents for buying and selling of the stock. (ix) Conclude your assignment with your analysis consisting of at least 200 words by summarizing your findings of the assignment
b0a286217d4a144b0ce2d88327c58e64
{ "intermediate": 0.15229162573814392, "beginner": 0.1553097814321518, "expert": 0.6923986077308655 }
43,248
I am working on a software project using git, and I used another pc to do a local commit, and then commited with my pc and found out my other pc wasn't configured with my email and now I have two commits with different authors: -2nd commit: Author: myusername <<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>> - 1st commit: Author; myusername <myusername@localhost.localdomain> - previous commits. How can I fix my previous commit to use my correct author?
84fcd9f15daf573c8416d2c45c3d01da
{ "intermediate": 0.40312397480010986, "beginner": 0.37113967537879944, "expert": 0.2257363498210907 }
43,249
make this code better. feel free to rename functions, refactor loop an d so on. context this is a base64 implem unsigned char getChar(const unsigned char* input, int* index, const size_t inputLen, const int initialOffset, int* fourByteCounter) {
a202f24bc69a313c6fa5b31f7a2e17ab
{ "intermediate": 0.2760273218154907, "beginner": 0.6082735657691956, "expert": 0.11569906771183014 }
43,250
c#, dictionary in dictionary vs name_name2
967507b8f901bb970193681b5e7a94ae
{ "intermediate": 0.40270742774009705, "beginner": 0.43055856227874756, "expert": 0.166733980178833 }
43,251
make this code better. feel free to rename functions, refactor loop an d so on. context this is a base64 implem unsigned char getChar(const unsigned char* input, int* index, const size_t inputLen, const int initialOffset, int* fourByteCounter) { unsigned char value=0; int initialByte; if (*index > 0 && (*index / 8 + 1) % 4 == 0) { *index += 8; *fourByteCounter = 0; initialByte = (*index + initialOffset)/8; } else { initialByte = (*index + initialOffset)/8; } for (int currentBit = 0; currentBit < 8 && (*index + currentBit + initialOffset) < inputLen; currentBit += 8) { int currentOffset; if ((*index + currentBit + initialOffset)/8 != initialByte) { currentOffset = 2; } else { currentOffset = initialOffset; } int shift = (*fourByteCounter + currentBit) % (8 - currentOffset); shift += currentOffset; value |= ((input[(*index + currentBut + initialOffset) / 8] >> (7-shift)) & 0b00000001) << (7 - currentBit); } return value; }
269361f4aa55e34b69f581c02bff2eb7
{ "intermediate": 0.22145333886146545, "beginner": 0.6325879693031311, "expert": 0.14595875144004822 }
43,252
Win32Exception: ApplicationName='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/../Converter/pdf2img.exe', CommandLine='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/PDF\AwA.pdf pageRight.png 0', CurrentDirectory='', Native error= Success at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <00000000000000000000000000000000>:0 at System.Diagnostics.Process.Start () [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.CallExternalProcess (System.String processPath, System.String arguments) [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.FindPdfFiles () [0x00000] in <00000000000000000000000000000000>:0 at Infrastructure.EntryPoints.PracticeEntryPoint.Initialize () [0x00000] in <00000000000000000000000000000000>:0 at SceneLoader.SceneLoadService+<LoadingMultipleScenes>d__13.MoveNext () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0
503e48842835e138291a1653e0cd1f21
{ "intermediate": 0.4007689654827118, "beginner": 0.3441985249519348, "expert": 0.2550325095653534 }
43,253
why is momentum before spare update? import torch from torch.optim.optimizer import Optimizer import math class Fusedbun(Optimizer): def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True): “”“ Initializer for the Fusedbun optimizer. Args: params (iterable): An iterable of parameters. lr (float, optional): The learning rate (default: 1e-3). eps (float, optional): A small value for numerical stability (default: 1e-8). beta_decay (float, optional): Rate of decay for the moving average of squared gradients (default: 0.8), inspired by Adalite. Lambda (float, optional): Coefficient for L2 regularization (weight decay), from Adalite’s approach to regularization. momentum_beta (float, optional): Coefficient for the moving average of gradients (momentum), inspired by Adalite. centralize (bool, optional): Flag to centralize gradients to have zero mean, inspired by Adalite for improved training stability. use_rms (bool, optional): Flag to use RMSprop-like denominator normalization, from Adalite’s adaptive learning rate strategy. “”” defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms) super(Fusedbun, self).init(params, defaults) @torch.no_grad() def step(self, closure=None): “”“ Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. Returns: The loss from the closure if it is provided. “”” loss = None if closure is not None: loss = closure() for group in self.param_groups: lr = group[‘lr’] eps = group[‘eps’] Lambda = group[‘Lambda’] momentum_beta = group[‘momentum_beta’] centralize = group[‘centralize’] use_rms = group[‘use_rms’] for p in group[‘params’]: if p.grad is None: continue grad = p.grad.data if centralize and len(p.shape) > 1: # Centralize gradients (Adalite inspiration). grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True) state = self.state[p] # Initialize state variables (inspired by both SM3 for efficiency and Adalite’s approach to state management). if len(state) == 0: state[‘step’] = 0 state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format) if momentum_beta > 0: state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format) exp_avg_sq = state[‘exp_avg_sq’] state[‘step’] += 1 if momentum_beta > 0: momentum_buffer = state[‘momentum_buffer’] momentum_buffer.mul_(momentum_beta).add_(grad) grad = momentum_buffer # Sparse update mechanism inspired by SM3. if p.dim() > 1: mask = grad.abs() > eps grad = grad * mask exp_avg_sq = torch.where(mask, exp_avg_sq*beta_decay + (1-beta_decay)*grad.pow(2), exp_avg_sq) else: exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1-beta_decay) denom = exp_avg_sq.sqrt().add_(eps) grad_normalized = grad / denom if use_rms else grad # Apply direct weight decay (Lambda) - informed by Adalite’s regularization approach. if Lambda != 0: p.data.mul_(1 - lr * Lambda) # Update parameters. p.data.add_(grad_normalized, alpha=-lr) return loss
54f3e6827cd5c4420702ba68f57c4f83
{ "intermediate": 0.4286110997200012, "beginner": 0.38831865787506104, "expert": 0.18307021260261536 }
43,254
Win32Exception: ApplicationName='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/../Converter/pdf2img.exe', CommandLine='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/PDF\AwA.pdf pageRight.png 0', CurrentDirectory='', Native error= Success at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <00000000000000000000000000000000>:0 at System.Diagnostics.Process.Start () [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.CallExternalProcess (System.String processPath, System.String arguments) [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.FindPdfFiles () [0x00000] in <00000000000000000000000000000000>:0 at Infrastructure.EntryPoints.PracticeEntryPoint.Initialize () [0x00000] in <00000000000000000000000000000000>:0 at SceneLoader.SceneLoadService+<LoadingMultipleScenes>d__13.MoveNext () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0 [XR] [17836] [22:32:21.849][Error ] xrRequestExitSession: XR_ERROR_SESSION_NOT_RUNNING [XR] [17836] [22:32:21.849][Info ] ==== Start Unity OpenXR Diagnostic Report ====
2c8e538094e146a77efb48457e96471b
{ "intermediate": 0.45779356360435486, "beginner": 0.3138493597507477, "expert": 0.2283570021390915 }
43,255
convert this to c++ from __future__ import division import numpy as np from const_ion import * def MeasurelogZ(R_Obs,O3O2_Obs,Rmode,tag): logZQ = np.linspace(-2,0,1000) ZQ = 10**logZQ if tag == 'local': T4OIII = -0.32*logZQ**2-1.5*logZQ+0.41 T4OII = -0.22*T4OIII**2+1.2*T4OIII+0.066 T4OII[T4OII<0.5] = 0.5 if tag == 'EoR': T4OIII = 0.81*logZQ**2+ 0.14*logZQ+ 1.1 T4OII = -0.744+T4OIII*(2.338-0.610*T4OIII) T4OII[T4OII<0.5] = 0.5 if tag == 'cosmicNoon': T4OIII = 0.88*logZQ**2+ 0.44*logZQ+ 1.2 T4OII = -0.744+T4OIII*(2.338-0.610*T4OIII) T4OII[T4OII<0.5] = 0.5 idx_sol = [] while len(idx_sol)==0: fO3O2 = 1/(0.75*k03_OIII(T4OIII)*nu32_OIII/(k01_OII(T4OII)*nu10_OII+k02_OII(T4OII)*nu20_OII)) FOIII = fO3O2*O3O2_Obs/(1+fO3O2*O3O2_Obs) FOII = 1-FOIII T4HII = T4OIII*FOIII+T4OII*FOII fR2 = 10**-3.31/nu_Hbeta/alphaB_Hbeta(T4HII)*(k01_OII(T4OII)*nu10_OII+k02_OII(T4OII)*nu20_OII) R2 = fR2*FOII*ZQ fR3 = 0.75*10**-3.31*k03_OIII(T4OIII)*nu32_OIII/nu_Hbeta/alphaB_Hbeta(T4HII) R3 = fR3*FOIII*ZQ fR3p = 0.25*10**-3.31*k03_OIII(T4OIII)*nu31_OIII/nu_Hbeta/alphaB_Hbeta(T4HII) R3p = fR3p*FOIII*ZQ R23 = R2+R3+R3p if Rmode == 'R2': R = R2 if Rmode == 'R3': R = R3 if Rmode == 'R23': R = R23 if np.max(R)>=R_Obs: diff = R-R_Obs diff_prod = diff[1:]*diff[:-1] idx_sol = np.where(diff_prod<=0)[0] if np.max(R)<R_Obs: T4OIII = T4OIII+0.1 T4OII = T4OII+0.1 w1 = (R[idx_sol+1]-R_Obs)/(R[idx_sol+1]-R[idx_sol]) w2 = 1-w1 return w1*logZQ[idx_sol]+w2*logZQ[idx_sol+1] def MeasurelogZ_withN2O2(R_Obs,O3O2_Obs,N2O2,Rmode,tag): logZQ = np.linspace(-2,0,1000) ZQ = 10**logZQ if tag == 'local': T4OIII = -0.32*logZQ**2-1.5*logZQ+0.41 T4OII = -0.22*T4OIII**2+1.2*T4OIII+0.066 T4OII[T4OII<0.5] = 0.5 if tag == 'EoR': T4OIII = 0.81*logZQ**2+ 0.14*logZQ+ 1.1 T4OII = -0.744+T4OIII*(2.338-0.610*T4OIII) T4OII[T4OII<0.5] = 0.5 if tag == 'cosmicNoon': T4OIII = 0.88*logZQ**2+ 0.44*logZQ+ 1.2 T4OII = -0.744+T4OIII*(2.338-0.610*T4OIII) T4OII[T4OII<0.5] = 0.5 idx_sol = [] while len(idx_sol)==0: fO3O2 = 1/(0.75*k03_OIII(T4OIII)*nu32_OIII/(k01_OII(T4OII)*nu10_OII+k02_OII(T4OII)*nu20_OII)) FOIII = fO3O2*O3O2_Obs/(1+fO3O2*O3O2_Obs) FOII = 1-FOIII T4HII = T4OIII*FOIII+T4OII*FOII fR2 = 10**-3.31/nu_Hbeta/alphaB_Hbeta(T4HII)*(k01_OII(T4OII)*nu10_OII+k02_OII(T4OII)*nu20_OII) R2 = fR2*FOII*ZQ fR3 = 0.75*10**-3.31*k03_OIII(T4OIII)*nu32_OIII/nu_Hbeta/alphaB_Hbeta(T4HII) R3 = fR3*FOIII*ZQ fR3p = 0.25*10**-3.31*k03_OIII(T4OIII)*nu31_OIII/nu_Hbeta/alphaB_Hbeta(T4HII) R3p = fR3p*FOIII*ZQ R23 = R2+R3+R3p if Rmode == 'R2': R = R2 if Rmode == 'R3': R = R3 if Rmode == 'R23': R = R23 if np.max(R)>=R_Obs: diff = R-R_Obs diff_prod = diff[1:]*diff[:-1] idx_sol = np.where(diff_prod<=0)[0] if np.max(R)<R_Obs: T4OIII = T4OIII+0.1 T4OII = T4OII+0.1 w1 = (R[idx_sol+1]-R_Obs)/(R[idx_sol+1]-R[idx_sol]) w2 = 1-w1 T4OII_sol = w1*T4OII[idx_sol]+w2*T4OII[idx_sol+1] T4OIII_sol = w1*T4OIII[idx_sol]+w2*T4OIII[idx_sol+1] N2O2_model = 0.0738*k03_NII(T4OII_sol)/(k01_OII(T4OII_sol)+k02_OII(T4OII_sol)) idx_true = np.where(np.abs(N2O2_model-N2O2)==np.min(np.abs(N2O2_model-N2O2)))[0] return w1[idx_true]*logZQ[idx_sol][idx_true]+w2[idx_true]*logZQ[idx_sol+1][idx_true]
e1d6cefc9200fa4c064933aa1b98a4c9
{ "intermediate": 0.34062108397483826, "beginner": 0.41437026858329773, "expert": 0.24500861763954163 }
43,256
What is the tailwind class that applies a class to all children of an element?
df6c641bd79c99d34c3158a5c5ba8c61
{ "intermediate": 0.32399511337280273, "beginner": 0.40699321031570435, "expert": 0.2690116763114929 }
43,257
у меня вышла такая ошибка в билде но в эдиторе unity такого не было Win32Exception: ApplicationName='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/Converter/pdf2img.exe', CommandLine='D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/PDF\AwA.pdf pageRight.png 0', CurrentDirectory='', Native error= Success at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <00000000000000000000000000000000>:0 at System.Diagnostics.Process.Start () [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.CallExternalProcess (System.String processPath, System.String arguments) [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.FindPdfFiles () [0x00000] in <00000000000000000000000000000000>:0 at Infrastructure.EntryPoints.PracticeEntryPoint.Initialize () [0x00000] in <00000000000000000000000000000000>:0 at SceneLoader.SceneLoadService+<LoadingMultipleScenes>d__13.MoveNext () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0
62f2d0533553919a1a387a9e2df86758
{ "intermediate": 0.5065404176712036, "beginner": 0.31560149788856506, "expert": 0.17785805463790894 }
43,258
InvalidOperationException: StandardOut has not been redirected or the process hasn't started yet. System.Diagnostics.Process.get_StandardOutput () (at <b33672c2670a41d3b6cd2c30c98a2bed>:0) (wrapper remoting-invoke-with-check) System.Diagnostics.Process.get_StandardOutput() UI.PdfFilesUI.CallExternalProcess (System.String processPath, System.String arguments) (at Assets/Scripst/PdfFilesUI.cs:142) UI.PdfFilesUI.FindPdfFiles () (at Assets/Scripst/PdfFilesUI.cs:65) UI.PdfFilesUI.Initialize () (at Assets/Scripst/PdfFilesUI.cs:39) Infrastructure.EntryPoints.PracticeEntryPoint.Initialize () (at Assets/Scripst/Infrastructure/EntryPoints/PracticeEntryPoint.cs:49) Infrastructure.StateMachine.States.ApplicationStates.SessionState.OnSceneLoaded () (at Assets/Scripst/Infrastructure/StateMachine/States/ApplicationStates/SessionState.cs:38) SceneLoader.SceneLoadService+<LoadingMultipleScenes>d__13.MoveNext () (at Assets/Scripst/Services/SceneLoading/SceneLoader.cs:101) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <685c48cf8f0b48abb797275c046dda6a>:0)
c551bd9a04e9af6c595de857b3c95454
{ "intermediate": 0.4645055830478668, "beginner": 0.36697661876678467, "expert": 0.16851778328418732 }
43,259
import java.util.Scanner; public class TrominoTiling { private static String[][] board; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter size of board (need to be 2^n and 0 to quit): "); int boardSize = scanner.nextInt(); if (boardSize == 0) { scanner.close(); return; } System.out.print("Please enter coordinates of missing square (separated by a space): "); int xMissing = scanner.nextInt(); int yMissing = scanner.nextInt(); // Initialize the board initializeBoard(boardSize); // Mark the initially missing square board[yMissing][xMissing] = "MS"; // Fill the board with trominoes fillBoard(0, 0, boardSize, xMissing, yMissing); // Print the result for (int y = boardSize - 1; y >= 0; y--) { // Start from the top for display for (int x = 0; x < boardSize; x++) { System.out.print(board[y][x] + "\t"); } System.out.println(); } scanner.close(); } private static void initializeBoard(int boardSize) { board = new String[boardSize][boardSize]; for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { board[i][j] = " "; // Initialize with spaces } } } private static void fillBoard(int x, int y, int size, int xMissing, int yMissing) { if (size == 1) { return; } int halfSize = size / 2; int xCenter = x + halfSize; int yCenter = y + halfSize; // Identify the quadrant with the missing square int missingQuadrant = (xMissing < xCenter ? 0 : 1) + (yMissing < yCenter ? 0 : 2); // Based on the missing quadrant, decide the central tromino placement for (int quadrant = 0; quadrant < 4; quadrant++) { if (quadrant == missingQuadrant) { // Recursively fill the quadrant with the actual missing square fillBoard( x + (quadrant % 2) * halfSize, y + (quadrant / 2) * halfSize, halfSize, xMissing, yMissing); } else { // Place a temporary missing square for tromino placement int tmpXMissing = x + (quadrant % 2) * (halfSize - 1); int tmpYMissing = y + (quadrant / 2) * (halfSize - 1); board[tmpYMissing][tmpXMissing] = "MS"; fillBoard(x + (quadrant % 2) * halfSize, y + (quadrant / 2) * halfSize, halfSize, tmpXMissing, tmpYMissing); } } board[yCenter - 1][xCenter] = board[yCenter][xCenter - 1] = board[yCenter][xCenter] = " "; if (missingQuadrant == 0) { // Lower left board[yCenter][xCenter - 1] = "UR"; board[yCenter][xCenter] = "UL"; board[yCenter - 1][xCenter] = "LL"; } else if (missingQuadrant == 1) { // Lower right board[yCenter][xCenter - 1] = "UR"; board[yCenter - 1][xCenter] = "LL"; board[yCenter][xCenter] = "LR"; } else if (missingQuadrant == 2) { // Upper left board[yCenter][xCenter - 1] = "UR"; board[yCenter][xCenter] = "UL"; board[yCenter - 1][xCenter] = "LL"; } else if (missingQuadrant == 3) { // Upper right board[yCenter][xCenter - 1] = "UL"; board[yCenter - 1][xCenter] = "LL"; board[yCenter][xCenter] = "LR"; } // Reset the temporary missing square marker (‘MS’) for necessary quadrant if (size == 2) { // Base case size, directly mark ‘MS’ location board[yMissing][xMissing] = "MS"; } } } The output that I got after running the code is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (separated by a space): 0 0 UR UL MS LL which is incorrect. The missing square is placed at the correct location but the other notations are wrong. According to the L-shaped arrangement that I had explained the correct output is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR where MS is the missing square and UR is the notation for the Upper right L-shaped arrangement as it has a corner in the upper right of board in the L-shaped arrangement. Similarly consider the expected output for Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR where MS is the missing square at the 1 3 position considering (0, 0) as the origin at the lower left corner. The LL notation stands for the Lower left L-shaped arrangement as it has corner at the lower left in the board, UR is the notation for the Upper right L-shaped arrangement as it has corner at the Upper right in the board and LR is the notation for the Lower right L-shaped arrangement as it has corner at the Lower right in the board. There should be only one missing square in the board at the position specified in the input coordinates and the other squares around the missing square MS should be filled with LL,LR,UL,UR according to the L-shaped arrangement. Take the reference for your better understanding. Consider in the first case there is a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. The first square is empty i.e. it is a missing square in the upper left corner, so the L-shaped arrangement for this case will be LR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower right. Similarly, In the second case a missing square is there in the upper right corner so the L-shaped arrangement for this case will be LL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower left, in the third case a missing square is there in the lower right corner so the L-shaped arrangement for this case will be UL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper left and in the fourth case a missing square is there in the lower left corner so the L-shaped arrangement for this case will be UR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper right. Your program should use x coordinate and y coordinate to record the location of the missing square. The origin (0, 0) as the lower left corner of the board. After recording the missing square (MS) the program should fill the remaining squares with Lower Left(LL), Lower right(LR), Upper left(UL) and Upper right(UR) considering the L-shaped arrangement as I had explained in the above expected output.
49cbff2da082a533804f1f39197339b0
{ "intermediate": 0.30143213272094727, "beginner": 0.5481030941009521, "expert": 0.1504647135734558 }
43,260
return only json format as in { "event_name": name, "date":dd-mm-yyyy, "location":city, country} event is: النكسة return location as tuple (city, country) in English event_name is same as event in Arabic Do not return anything else
a7ffe8125cc39f2ea994661e5b9c6c80
{ "intermediate": 0.44823533296585083, "beginner": 0.2375667840242386, "expert": 0.3141978979110718 }
43,261
return only json format as in { “event_name”: name, “date”:dd-mm-yyyy, “location”:city, country} event is: النكسة return location as tuple (city, country) in English if more than one country return then as list of tuples event_name is same as event in Arabic Do not return anything else
8e8deffc0b7638b3d08ca973f767919b
{ "intermediate": 0.37236279249191284, "beginner": 0.27266088128089905, "expert": 0.3549763560295105 }
43,262
example of small java program that uses enum
bd9fda929fd1c583ff87acd3dad0167d
{ "intermediate": 0.37811756134033203, "beginner": 0.33107879757881165, "expert": 0.2908036708831787 }
43,263
In the first case there is a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. The first square is empty i.e. it is a missing square in the upper left corner, so the L-shaped arrangement for this case will be LR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower right. Similarly, In the second case a missing square is there in the upper right corner so the L-shaped arrangement for this case will be LL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower left, in the third case a missing square is there in the lower right corner so the L-shaped arrangement for this case will be UL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper left and in the fourth case a missing square is there in the lower left corner so the L-shaped arrangement for this case will be UR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper right We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. import java.util.Scanner; public class TrominoTiling { private static String[][] board; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter size of board (need to be 2^n and 0 to quit): "); int boardSize = scanner.nextInt(); if (boardSize == 0) { scanner.close(); return; } System.out.print("Please enter coordinates of missing square (separated by a space): "); int xMissing = scanner.nextInt(); int yMissing = scanner.nextInt(); // Initialize the board initializeBoard(boardSize); // Mark the initially missing square board[yMissing][xMissing] = “MS”; // Fill the board with trominoes fillBoard(0, 0, boardSize, xMissing, yMissing); // Print the result for (int y = boardSize - 1; y >= 0; y–) { // Start from the top for display for (int x = 0; x < boardSize; x++) { System.out.print(board[y][x] + “\t”); } System.out.println(); } scanner.close(); } private static void initializeBoard(int boardSize) { board = new String[boardSize][boardSize]; for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { board[i][j] = " "; // Initialize with spaces } } } private static void fillBoard(int x, int y, int size, int xMissing, int yMissing) { // Base condition: If the board size reaches 2x2, place a tromino around the missing square if (size == 2) { // Mark the current batch of trominoes with a unique identifier or simple labels based on the spec String trominoMarker = “UR”; // Default placement, can vary based on conditions below for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (x + i != xMissing || y + j != yMissing) { // Here, adjust the marker based on the quadrant of the missing tile if (xMissing == x && yMissing == y) trominoMarker = “UR”; // Lower Left else if (xMissing == x + 1 && yMissing == y) trominoMarker = “UL”; // Lower Right else if (xMissing == x && yMissing == y + 1) trominoMarker = “LR”; // Upper Left else if (xMissing == x + 1 && yMissing == y + 1) trominoMarker = “LL”; // Upper Right board[y + j][x + i] = trominoMarker; } } } return; } int halfSize = size / 2; // Determine the quadrant of the missing square relative to the current board section // Recursively fill each quadrant // Adjust xMissing and yMissing for each recursive call to be within the new quadrant bounds int newXMissing = xMissing < x + halfSize ? xMissing : x + halfSize - 1; int newYMissing = yMissing < y + halfSize ? yMissing : y + halfSize - 1; // Quadrant 1 - Lower Left fillBoard(x, y, halfSize, xMissing, yMissing); // Quadrant 2 - Lower Right fillBoard(x + halfSize, y, halfSize, xMissing >= x + halfSize ? xMissing : newXMissing, yMissing); // Quadrant 3 - Upper Left fillBoard(x, y + halfSize, halfSize, xMissing, yMissing >= y + halfSize ? yMissing : newYMissing); // Quadrant 4 - Upper Right fillBoard(x + halfSize, y + halfSize, halfSize, xMissing >= x + halfSize ? xMissing : newXMissing, yMissing >= y + halfSize ? yMissing : newYMissing); } } Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (separated by a space): 1 3 LL MS UR UR LL LL UR UR UR UR UR UR UR UR UR UR the above code is giving this output which is incorrect. The MS is placed at the correct position but the other positions are incorrect. The program must fill the other squares with the L-shaped arrangement that I have already specified. What you need to do is to decide which L shape to be put in the remaining squares after the missing square is placed correctly at its position. The correct and expected output when the similar input is given should be Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR where the other positions except MS are filled with LL,LR,UL,UR according to the L-shaped arrangement that I had specified earlier. The remaining squares should be filled with these values. The chess board (with a missing square) should be covered by an arrangement of trominoes (an L-shaped arrangement of three squares; refer to the four cases that I had specified earlier) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another.
0ff15ff0bcd07c2cabfdeb2454860914
{ "intermediate": 0.32235652208328247, "beginner": 0.42075982689857483, "expert": 0.2568836808204651 }
43,264
привет у меня проблема при попытке запустить внешний процесс на Unity-приложения Win32Exception: ApplicationName=‘D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/Converter/pdf2img.exe’, CommandLine=‘D:/Build/VRElectricMotorAssembly/VRElectricMotorAssembly_Data/StreamingAssets/PDF\AwA.pdf pageRight.png 0’, CurrentDirectory=‘’, Native error= Success at System.Diagnostics.Process.StartWithCreateProcess (System.Diagnostics.ProcessStartInfo startInfo) [0x00000] in <00000000000000000000000000000000>:0 at System.Diagnostics.Process.Start () [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.CallExternalProcess (System.String processPath, System.String arguments) [0x00000] in <00000000000000000000000000000000>:0 at UI.PdfFilesUI.FindPdfFiles () [0x00000] in <00000000000000000000000000000000>:0 at Infrastructure.EntryPoints.PracticeEntryPoint.Initialize () [0x00000] in <00000000000000000000000000000000>:0 at SceneLoader.SceneLoadService+<LoadingMultipleScenes>d__13.MoveNext () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0
2bcfd1abb95a53b37fc6e1497e1ee067
{ "intermediate": 0.5384824275970459, "beginner": 0.2828378975391388, "expert": 0.1786797046661377 }
43,265
Given a natural number n and a chess board with 2^n squares on each side (the length of the side is 2^n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. The L-shaped trominoes are LL, LR, UL, UR. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. The main program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR
d7353aec57b30c791eceeb9ffd5c6bd4
{ "intermediate": 0.14581814408302307, "beginner": 0.06782884150743484, "expert": 0.7863529920578003 }
43,266
Given a natural number n and a chess board with 2^n squares on each side (the length of the side is 2^n, called the board size) with a missing square in any location, you will use the divide and conquer approach to design and implement an algorithm to cover the chess board (with a missing square) by an arrangement of trominoes (an L-shaped arrangement of three squares) such that all trominoes are confined to the boundaries of the chess board, and no tromino overlaps another. The L-shaped trominoes are LL, LR, UL, UR. We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. The main java program should output the arrangement of trominoes at each coordinate location. For example, when board_size =2, x_missing = 0, and y_missing = 1 (the first figure above), the output should be as follows (please use “MS” to stand for the missing square). MS LR LR LR Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR
8ef7d3e126591ef83abaa76e0d44b278
{ "intermediate": 0.17149390280246735, "beginner": 0.07244490832090378, "expert": 0.7560611963272095 }
43,267
import java.util.Scanner; public class TrominoTiling { private static String[][] board; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter size of board (need to be 2^n and 0 to quit): "); int boardSize = scanner.nextInt(); if (boardSize == 0) { scanner.close(); return; } System.out.print("Please enter coordinates of missing square (separated by a space): "); int xMissing = scanner.nextInt(); int yMissing = scanner.nextInt(); // Initialize the board initializeBoard(boardSize); // Mark the initially missing square board[yMissing][xMissing] = "MS"; // Fill the board with trominoes fillBoard(0, 0, boardSize, xMissing, yMissing); // Print the result for (int y = boardSize - 1; y >= 0; y--) { // Start from the top for display for (int x = 0; x < boardSize; x++) { System.out.print(board[y][x] + "\t"); } System.out.println(); } scanner.close(); } private static void initializeBoard(int boardSize) { board = new String[boardSize][boardSize]; for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { board[i][j] = " "; // Initialize with spaces } } } private static void fillBoard(int x, int y, int size, int xMissing, int yMissing) { if (size == 2) { // Place the trominoes around the missing square. String trominoMarker = "UR"; // Default placement, adjust based on actual position of the missing tile. for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (x + i != xMissing || y + j != yMissing) { if (xMissing == x && yMissing == y) trominoMarker = "LR"; // Lower Left else if (xMissing == x + 1 && yMissing == y) trominoMarker = "LL"; // Lower Right else if (xMissing == x && yMissing == y + 1) trominoMarker = "UR"; // Upper Left else if (xMissing == x + 1 && yMissing == y + 1) trominoMarker = "UL"; // Upper Right board[y + j][x + i] = trominoMarker; } } } return; } int halfSize = size / 2; // Identify center for placing the tromino if the missing square is not in this quadrant. int centerX = x + halfSize - 1; int centerY = y + halfSize - 1; // Determine in which quadrant the missing square resides. boolean missingInLowerLeft = xMissing < x + halfSize && yMissing < y + halfSize; boolean missingInLowerRight = xMissing >= x + halfSize && yMissing < y + halfSize; boolean missingInUpperLeft = xMissing < x + halfSize && yMissing >= y + halfSize; boolean missingInUpperRight = xMissing >= x + halfSize && yMissing >= y + halfSize; // Place the center tromino based on the quadrant of the missing square. if (!missingInLowerLeft) board[centerY][centerX] = "MS"; // Bottom-Left if (!missingInLowerRight) board[centerY][centerX + 1] = "MS"; // Bottom-Right if (!missingInUpperLeft) board[centerY + 1][centerX] = "MS"; // Top-Left if (!missingInUpperRight) board[centerY + 1][centerX + 1] = "MS"; // Top-Right // Recursively solve for each quadrant. fillBoard(x, y, halfSize, missingInLowerLeft ? xMissing : centerX, missingInLowerLeft ? yMissing : centerY); fillBoard(x + halfSize, y, halfSize, missingInLowerRight ? xMissing : centerX + 1, missingInLowerRight ? yMissing : centerY); fillBoard(x, y + halfSize, halfSize, missingInUpperLeft ? xMissing : centerX, missingInUpperLeft ? yMissing : centerY + 1); fillBoard(x + halfSize, y + halfSize, halfSize, missingInUpperRight ? xMissing : centerX + 1, missingInUpperRight ? yMissing : centerY + 1); // Replace the "MS" used for simulations with correct tromino markers. if (!missingInLowerLeft) board[centerY][centerX] = "LR"; // Center tromino facing Lower Right if (!missingInLowerRight) board[centerY][centerX + 1] = "LL"; // Center tromino facing Lower Left if (!missingInUpperLeft) board[centerY + 1][centerX] = "UR"; // Center tromino facing Upper Right if (!missingInUpperRight) board[centerY + 1][centerX + 1] = "UL"; // Center tromino facing Upper Left } } the output of this program is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (separated by a space): 0 0 LR LR MS LR which is incorrect. The expected output is Please enter size of board (need to be 2^n and 0 to quit): 2 Please enter coordinates of missing square (seperated by a space): 0 0 UR UR MS UR In the first case there is a board with dimensions 2*2 with 4 squares inside it of 1*1 dimension. The first square is empty i.e. it is a missing square in the upper left corner, so the L-shaped arrangement for this case will be LR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower right. Similarly, In the second case a missing square is there in the upper right corner so the L-shaped arrangement for this case will be LL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the lower left, in the third case a missing square is there in the lower right corner so the L-shaped arrangement for this case will be UL and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper left and in the fourth case a missing square is there in the lower left corner so the L-shaped arrangement for this case will be UR and it will be filled at the remaining coordinates as it has the corner for the L-shaped arrangement at the upper right We will use x coordinate and y coordinate to record the location of the missing square. It is convenient to treat the origin (0, 0) as the lower left corner of the board. Similarly the output Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (separated by a space): 1 3 UL MS LR LR UL UL UL LR UL LR LL UR UL UL UR UR is incorrect. The correct output is Please enter size of board (need to be 2^n and 0 to quit): 4 Please enter coordinates of missing square (seperated by a space): 1 3 LL MS UR UR LL LL LR UR LL LR LR LR LL LL LR LR
364ac1ff7c01b4901e387ca007a05707
{ "intermediate": 0.292568564414978, "beginner": 0.5872095227241516, "expert": 0.1202218309044838 }
43,268
How do i format a cell in Excel so that if cell A1 has a value in it and is not empty then Cell c1 fill is red
5e0162c8b837d11c9a8e509128dcc397
{ "intermediate": 0.42028844356536865, "beginner": 0.2614085078239441, "expert": 0.31830301880836487 }
43,269
what are race conditions
a536c0879afc15a11c731123aa838bad
{ "intermediate": 0.3703192472457886, "beginner": 0.32802021503448486, "expert": 0.30166053771972656 }
43,270
Tell me in Golang, how can I have a static variable is a function. For example, I want it to keep its value between calls.
486a1ed96b500e81153c5f2364c0b2a1
{ "intermediate": 0.35997578501701355, "beginner": 0.412169486284256, "expert": 0.22785471379756927 }
43,271
привет добавить обработку исключений вокруг process.Start() public void CallExternalProcess(string processPath, string arguments) { UnityEngine.Debug.Log($"Попытка запуска внешнего процесса: { processPath} с аргументами: { arguments}"); var myProcess = new Process(); myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; myProcess.StartInfo.CreateNoWindow = true; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.FileName = processPath; myProcess.StartInfo.Arguments = arguments; myProcess.EnableRaisingEvents = true; myProcess.Start(); myProcess.WaitForExit(); var ExitCode = myProcess.ExitCode; }
6929bbdcb1ba11e442ba23357db0078b
{ "intermediate": 0.38057613372802734, "beginner": 0.3938008248806, "expert": 0.22562307119369507 }