From e46e6f66321c34aeeb74851b8c551ed02e6d2e90 Mon Sep 17 00:00:00 2001 From: Zinan Lin Date: Sat, 7 Oct 2023 21:19:55 -0700 Subject: [PATCH] first commit Co-authored-by: Xuefei Ning Co-authored-by: Zixuan Zhou Co-authored-by: Zifu Wang --- .gitignore | 163 ++ .pre-commit-config.yaml | 6 + LICENSE | 21 + README.md | 139 + claude_setup_guide.md | 25 + data/lima/create_dataset.py | 36 + data/lima/data.csv | 2530 +++++++++++++++++ data/lima/router.csv | 2516 ++++++++++++++++ data/vicuna/create_dataset.py | 38 + data/vicuna/data.csv | 81 + data/vicuna/router.csv | 81 + data/wizardlm/create_dataset.py | 37 + data/wizardlm/data.csv | 636 +++++ data/wizardlm/router.csv | 636 +++++ demo/__init__.py | 2 + demo/controller.py | 319 +++ demo/gradio_block_sot_named.py | 405 +++ demo/gradio_web_server.py | 414 +++ demo/gradio_web_server_multi.py | 182 ++ demo/model_worker.py | 542 ++++ prompts/router_gpt4.json | 1 + prompts/sot_chatgpt.json | 1 + prompts/sot_claude.json | 1 + prompts/sot_gpt4.json | 1 + prompts/sot_opensource.json | 1 + pyproject.toml | 37 + scripts/debug_prompt.sh | 9 + scripts/vicuna/dump/claude_slack_naive.sh | 6 + scripts/vicuna/dump/claude_slack_outline.sh | 7 + scripts/vicuna/dump/gpt3.5_naive.sh | 15 + scripts/vicuna/dump/gpt3.5_outline.sh | 16 + scripts/vicuna/dump/gpt4_naive.sh | 15 + scripts/vicuna/dump/gpt4_outline.sh | 16 + scripts/vicuna/dump/gpt4_router.sh | 16 + scripts/vicuna/dump/opensource_naive.py | 42 + scripts/vicuna/dump/opensource_outline.py | 43 + .../evaluation_ALL_fastchat_gpt4_birdir.sh | 20 + .../evaluation_ALL_llm_zoo_gpt4_alldir.sh | 146 + scripts/wizardlm/dump/claude_slack_naive.sh | 6 + scripts/wizardlm/dump/claude_slack_outline.sh | 7 + scripts/wizardlm/dump/gpt3.5_naive.sh | 15 + scripts/wizardlm/dump/gpt3.5_outline.sh | 16 + scripts/wizardlm/dump/gpt4_naive.sh | 15 + scripts/wizardlm/dump/gpt4_outline.sh | 16 + scripts/wizardlm/dump/gpt4_router.sh | 16 + scripts/wizardlm/dump/opensource_naive.py | 42 + scripts/wizardlm/dump/opensource_outline.py | 43 + .../evaluation_ALL_fastchat_gpt4_birdir.sh | 40 + sot/__init__.py | 0 sot/evaluation/llm_evaluation.py | 126 + sot/fastchat_evaluation_bidir.py | 157 + sot/fastchat_evaluation_for_vicuna_bidir.py | 226 ++ sot/llm_zoo_evaluation_alldir.py | 141 + sot/main.py | 98 + sot/models/__init__.py | 22 + sot/models/batch_inference.py | 244 ++ sot/models/claude_slack_model.py | 148 + sot/models/fastchat_model.py | 221 ++ sot/models/model.py | 19 + sot/models/openai_model.py | 132 + sot/models/register_fastchat.py | 132 + sot/prompt_eng_main.py | 378 +++ sot/schedulers/__init__.py | 30 + sot/schedulers/naive_scheduler.py | 97 + sot/schedulers/outline_batch_scheduler.py | 165 ++ sot/schedulers/outline_scheduler.py | 238 ++ .../router_outline_batch_scheduler.py | 74 + sot/schedulers/scheduler.py | 26 + sot/train/__init__.py | 0 sot/train/confusion_matrix.py | 149 + sot/train/offline_prepare_router_data.py | 74 + sot/train/train_router.py | 254 ++ sot/utils/__init__.py | 3 + sot/utils/logging.py | 20 + 74 files changed, 12592 insertions(+) create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 claude_setup_guide.md create mode 100644 data/lima/create_dataset.py create mode 100644 data/lima/data.csv create mode 100644 data/lima/router.csv create mode 100644 data/vicuna/create_dataset.py create mode 100644 data/vicuna/data.csv create mode 100644 data/vicuna/router.csv create mode 100644 data/wizardlm/create_dataset.py create mode 100644 data/wizardlm/data.csv create mode 100644 data/wizardlm/router.csv create mode 100644 demo/__init__.py create mode 100644 demo/controller.py create mode 100644 demo/gradio_block_sot_named.py create mode 100644 demo/gradio_web_server.py create mode 100644 demo/gradio_web_server_multi.py create mode 100644 demo/model_worker.py create mode 100644 prompts/router_gpt4.json create mode 100644 prompts/sot_chatgpt.json create mode 100644 prompts/sot_claude.json create mode 100644 prompts/sot_gpt4.json create mode 100644 prompts/sot_opensource.json create mode 100644 pyproject.toml create mode 100755 scripts/debug_prompt.sh create mode 100755 scripts/vicuna/dump/claude_slack_naive.sh create mode 100755 scripts/vicuna/dump/claude_slack_outline.sh create mode 100755 scripts/vicuna/dump/gpt3.5_naive.sh create mode 100755 scripts/vicuna/dump/gpt3.5_outline.sh create mode 100755 scripts/vicuna/dump/gpt4_naive.sh create mode 100755 scripts/vicuna/dump/gpt4_outline.sh create mode 100755 scripts/vicuna/dump/gpt4_router.sh create mode 100644 scripts/vicuna/dump/opensource_naive.py create mode 100644 scripts/vicuna/dump/opensource_outline.py create mode 100755 scripts/vicuna/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh create mode 100755 scripts/vicuna/evaluate/evaluation_ALL_llm_zoo_gpt4_alldir.sh create mode 100755 scripts/wizardlm/dump/claude_slack_naive.sh create mode 100755 scripts/wizardlm/dump/claude_slack_outline.sh create mode 100755 scripts/wizardlm/dump/gpt3.5_naive.sh create mode 100755 scripts/wizardlm/dump/gpt3.5_outline.sh create mode 100755 scripts/wizardlm/dump/gpt4_naive.sh create mode 100755 scripts/wizardlm/dump/gpt4_outline.sh create mode 100755 scripts/wizardlm/dump/gpt4_router.sh create mode 100644 scripts/wizardlm/dump/opensource_naive.py create mode 100644 scripts/wizardlm/dump/opensource_outline.py create mode 100755 scripts/wizardlm/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh create mode 100644 sot/__init__.py create mode 100644 sot/evaluation/llm_evaluation.py create mode 100644 sot/fastchat_evaluation_bidir.py create mode 100644 sot/fastchat_evaluation_for_vicuna_bidir.py create mode 100644 sot/llm_zoo_evaluation_alldir.py create mode 100644 sot/main.py create mode 100644 sot/models/__init__.py create mode 100644 sot/models/batch_inference.py create mode 100644 sot/models/claude_slack_model.py create mode 100644 sot/models/fastchat_model.py create mode 100644 sot/models/model.py create mode 100644 sot/models/openai_model.py create mode 100644 sot/models/register_fastchat.py create mode 100644 sot/prompt_eng_main.py create mode 100644 sot/schedulers/__init__.py create mode 100644 sot/schedulers/naive_scheduler.py create mode 100644 sot/schedulers/outline_batch_scheduler.py create mode 100644 sot/schedulers/outline_scheduler.py create mode 100644 sot/schedulers/router_outline_batch_scheduler.py create mode 100644 sot/schedulers/scheduler.py create mode 100644 sot/train/__init__.py create mode 100644 sot/train/confusion_matrix.py create mode 100644 sot/train/offline_prepare_router_data.py create mode 100644 sot/train/train_router.py create mode 100644 sot/utils/__init__.py create mode 100644 sot/utils/logging.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f5d6e48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,163 @@ +results +.DS_Store + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..77bd3f6 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,6 @@ +repos: +- repo: https://github.com/psf/black + rev: 23.3.0 + hooks: + - id: black + args: [--preview] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..283d3ee --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) [2023] [Xuefei Ning, Zinan Lin, Zixuan Zhou, Zifu Wang, Huazhong Yang, Yu Wang] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..33a172c --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +# Skeleton-of-Thought: Large Language Models Can Do Parallel Decoding + +**[[website](https://sites.google.com/view/sot-llm/home)]** +**[[paper](https://arxiv.org/abs/2307.15337)]** +**[[code](https://github.com/imagination-research/sot)]** + +This work aims at decreasing the end-to-end generation latency of large language models (LLMs). One of the major causes of the high generation latency is the sequential decoding approach adopted by almost all state-of-the-art LLMs. In this work, motivated by the thinking and writing process of humans, we propose Skeleton-of-Thought (SoT), which first guides LLMs to generate the skeleton of the answer, and then conducts parallel API calls or batched decoding to complete the contents of each skeleton point in parallel. Not only does SoT provide considerable speed-ups across 12 LLMs, but it can also potentially improve the answer quality on several question categories. To make the overall solution more practical, an extension, SoT with Router (SoT-R), employs a GPT-4-prompting router or a trained RoBERTa router to only trigger SoT for suitable questions. SoT is an initial attempt at data-centric optimization for inference efficiency, and further underscores the potential of pushing LLMs to think more like a human for answer quality. + + +If you find this repository or paper useful, you can cite +``` +@misc{ning2023skeletonofthought, + title={Skeleton-of-Thought: Large Language Models Can Do Parallel Decoding}, + author={Xuefei Ning and Zinan Lin and Zixuan Zhou and Zifu Wang and Huazhong Yang and Yu Wang}, + year={2023}, + eprint={2307.15337}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +} +``` + +The repo is organized as follows. +* The SoT implementation is under [`sot/`](sot/). +* The SoT prompts are given under [`prompts/`](prompts/). For example, `sot_opensource.json` is used for all open-source models, and `sot_gpt4` is used for the GPT-4 API. +* The processed data are under [`data/`](data/). +* The scripts under [`scripts/`](scripts/) are used to dump and evaluate the results. +* The Gradio demo code is under [`demo/`](demo/). The demo is built based on the FastChat demo code. + +## Contents +- [Install](#install) +- [Test SoT with Gradio Demo](#test-sot-with-gradio-demo) +- [Evaluate SoT](#evaluate-sot) +- [Develop SoT](#develop-sot) +- [Acknowledgement](#acknowledgement) + + +## Install +```pip install -e .``` + +We recommend using Python 3.8 to 3.10. + +Some required environment variables/setups: +* Before running the open-source models, please log in to huggingface through `huggingface-cli login` so that the models can be downloaded automatically. +* For GPT4, the script by default uses **OpenAI API**. The API key should be provided by `export OPENAI_API_KEY=`. +* For GPT-3.5, the script by default uses **Azure OpenAI API**. The API key, engine, and API base should be provided by `export OPENAI_API_KEY=`, `export ENGINE=`, and `export API_BASE=`. + > Note that GPT-4 can also use **Azure OpenAI API**, and GPT-3.5 can also use **OpenAI API**, by modifying the command line arguments accordingly. +* For Claude, please refer to [Claude setup guide](claude_setup_guide.md). + +## Test SoT with Gradio Demo +The SoT gradio demo can be started as follows (under the [`demo/`](demo/) directory): + +1. Launch the controller + ``` + python controller.py + ``` +2. Launch the model workers + - Lauch a model worker that conducts normal decoding on GPU 0. + ``` + CUDA_VISIBLE_DEVICES=0 python model_worker.py --model-path ${MODEL_NAME} --controller http://0.0.0.0:21001 --port 31000 --worker http://0.0.0.0:31000 + ``` + - Lauch a model worker that conducts SoT-R decoding on GPU 1. + ``` + CUDA_VISIBLE_DEVICES=1 python model_worker.py --model-path ${MODEL_NAME} --controller http://0.0.0.0:21001 --port 31001 --worker http://0.0.0.0:31001 --sot ../prompts/sot_opensource.json --sotr ${ROUTER_MODEL} + ``` + The trained router model can be downloaded from [this Google Drive](https://drive.google.com/file/d/1LxEsH9NFwj41wBz8tnT_hwn5LbW7aaL5/view?usp=sharing). + - Note that we recommend directly using SoT-R instead of the plain SoT. But if one wants to trigger SoT for all questions, he or she can launch another model worker as follows: + ``` + CUDA_VISIBLE_DEVICES=1 python model_worker.py --model-path ${MODEL_NAME} --controller http://0.0.0.0:21001 --port 31002 --worker http://0.0.0.0:31002 --sot ../prompts/sot_opensource.json + ``` +3. Launch the Gradio web demo + ``` + python gradio_web_server_multi.py + ``` + +## Evaluate SoT +### Prepare the dataset +Vicuna-80, WizardLM, and LIMA data is provided under [`data/`](data/) and is ready to use. The pre-processing scripts for getting the data are also attached (`create_dataset.py` in each folder) for reference. + +### Dump the answers of SoT and Normal decoding +We put the answer dumping scripts for the Vicuna-80 and WizardLM datasets under [`scripts/vicuna/dump/`](scripts/vicuna/dump/) and [`scripts/wizardlm/dump/`](scripts/wizardlm/dump/). + +For example, to dump SoT answers of all open-source models, we can run +``` +python scripts/vicuna/dump/opensource_outline.py +``` + +To dump the normal sequential decoding answers of GPT-3.5, we can run +``` +./scripts/vicuna/dump/gpt3.5_naive.sh +``` + +### Evaluate the answer quality +We put the evaluation scripts for the Vicuna-80 and WizardLM datasets under [`scripts/vicuna/evaluate/`](scripts/vicuna/evaluate/) and [`scripts/wizardlm/evaluate/`](scripts/wizardlm/evaluate/). + +The evaluation scripts use the comparison prompts provided by Fastchat or LLMZoo to prompt a GPT-4 judge to compare the quality of two answers. Please provide OpenAI API key by `export OPENAI_API_KEY=` before running the scripts. + +> Note: We did not use the system prompt except for the LLaMA-2 models when conducting open-source model evaluation in our paper (for both normal decoding and SoT decoding). This is because we use an [older FastChat version](https://github.com/lm-sys/FastChat/tree/f1f2294a66956b340c577fab2751d86f45e71099) for the evaluation in the paper. As our code removes the template messages in the conversation template before querying the model, the system prompt will be removed as template messages in the old FastChat version. Nevertheless, in this code repository, we use a newer version of FastChat (v0.2.26). Consequently, running SoT with the current code will use the system prompt for all open-source models. + + +## Develop SoT +### Manually tune the SoT prompts +`sot/prompt_eng_main.py` is a helper program to ease manual prompt tuning. Use `bash scripts/debug_prompt.sh ` to run the script. This will pop an interactive session in which you can run the following commands: + +1. `use ` to load data (default: `data/vicuna/data.csv`) +2. `useprompt ` to change the SoT prompt templates (default: `prompts/sot_opensource.json`) +3. `usenaiveprompt ` to change the normal prompt template (default to use only the question) +4. (1) `test ` to test SoT decoding for the ind-th question; (2) `test naive ` to test normal decoding; (3) `test batch_outline ` to test SoT decoding with batched point expansion. + * The model outputs will be streamed onto the console (by enabling `--stream` argument to `sot/prompt_eng_main.py`). Note that when using `test `, the expansion of multiple points is conducted sequentially. When using `test batch_outline `, the expansion of multiple points is conducted with batch inference, but we do not support streaming the parallel expansion outputs to the console (to check the streaming effect, use the Gradio Web Demo), so one have to wait until the point-expanding completion to see the results. + * After the completion, statistics will also be printed. + * At any time during the generation, one can push Ctrl+C to abort the generation to go back to the interactive session. +5. `exit` to exit the session + +> Note: +> 1. We mainly use this program to help engineer the prompt for the open-source models. +> 2. Any other command-line arguments for the model can be fed as the arguments to this script. For example, as testing a 13B model on RTX 3090 with FP16 inference requires two GPUs, we can run +> ```bash scripts/debug_prompt.sh meta-llama/Llama-2-13b-chat-hf --num-gpus 2``` + +### Train the router for SoT-R +Preprocess router data and train the RoBERTa router as follows (scripts in [sot/train/](sot/train/)): + +1. Preprocess the router data for Vicuna-80, WizardLM, and LIMA: + ``` + python offline_prepare_router_data.py \ + --data_path "../../data/lima/router.csv" \ + --output_data_path "lima_router.pkl" + ``` +2. Train the router on LIMA and test on Vicuna-80 and WizardLM: + ``` + python train_router.py + ``` + +The predicted results will be saved as `vicuna_router_pred.csv` and `wizardlm_router_pred.csv`. + +Our trained router model can be found on [this Google Drive](https://drive.google.com/file/d/1LxEsH9NFwj41wBz8tnT_hwn5LbW7aaL5/view?usp=sharing). + +Our manual labels of whether each question should use SoT are provided in `data/*/router.csv`. + +## Acknowledgement +During the development of SoT, we use and refer to the amazing work of [FastChat](https://github.com/lm-sys/FastChat) and [Hugging Face transformer package](https://github.com/huggingface/transformers/). diff --git a/claude_setup_guide.md b/claude_setup_guide.md new file mode 100644 index 0000000..5d43bd2 --- /dev/null +++ b/claude_setup_guide.md @@ -0,0 +1,25 @@ +This page contains instructions about how to setup Claude over Slack for the evaluation. In essence, we will add Claude app into your Slack workspace, and set up another Slack app which the scripts will use to interact with the Claude app. + +Please follow these steps: + +1. Log in a *paid* slack workspace on browser. +1. Open [https://www.anthropic.com/claude-in-slack](https://www.anthropic.com/claude-in-slack) and click "Add to Slack" so as to add Claude app into the Slack workspace. +1. Open [https://api.slack.com/apps](https://api.slack.com/apps) and click "Create New App" to create a Slack app. +1. Open "OAuth & Permissions" tab, and in "User Token Scopes" add the following permissions: + * admin + * channels:history + * channels:read + * channels:write + * chat:write + * groups:history + * groups:read + * groups:write + * im:history + * im:read + * im:write + * mpim:history + * mpim:read + * mpim:write + * users:read +1. Click "Reinstall to Workspace" so that the permission changes are applied +1. Copy your "OAuth Tokens for Your Workspace" starting with "xoxp-" and execute `export SLACK_USER_TOKEN=` in the command line. \ No newline at end of file diff --git a/data/lima/create_dataset.py b/data/lima/create_dataset.py new file mode 100644 index 0000000..ee0f968 --- /dev/null +++ b/data/lima/create_dataset.py @@ -0,0 +1,36 @@ +import os +import csv +import json +from tqdm import tqdm +from huggingface_hub import login, hf_hub_download + + +JSONL_FILE = "train.jsonl" +JSONL_URL = "GAIR/lima" +DATA_FILE = "data.csv" + +ACCESS_TOKEN = os.getenv("ACCESS_TOKEN") + + +def download(url, file, access_token): + login(access_token) + hf_hub_download(repo_id=url, filename=file, repo_type="dataset", local_dir=".") + + +def save(file, request): + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow([request]) + + +if __name__ == "__main__": + if not os.path.exists(JSONL_FILE): + download(JSONL_URL, JSONL_FILE, ACCESS_TOKEN) + + save(DATA_FILE, "request") + with open(JSONL_FILE) as f: + for line in tqdm(f): + request = line.strip() + request = json.loads(request)["conversations"][0] + + save(DATA_FILE, request) diff --git a/data/lima/data.csv b/data/lima/data.csv new file mode 100644 index 0000000..f2edca4 --- /dev/null +++ b/data/lima/data.csv @@ -0,0 +1,2530 @@ +request +Can brain cells move? By movement I mean long distance migration (preferably within the brain only). +"In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple. +It was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set! +So I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they? " +"View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great." +"Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\alpha r}$ as $r \to \infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour. +Also, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs. +I understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \to \infty$, but there are no a priori requirements for the way it decays as it does so. +My question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\alpha r}$ as $r \to \infty$." +"Explain what ""git reset"" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical. +I think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about: + +* the options ```--hard```, ```--soft``` and ```--merge```; +* the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```; +* concrete use cases and work flows; +* consequences on the working copy, the ```HEAD``` and your global stress level." +"I am looking to use Java to get the MD5 checksum of a file. +How is it done?" +What are the primary objections Democrats have to a border wall? +"I'm converting a video to GIF file with ```ffmpeg```: +```ffmpeg \ + -i input.flv \ + -ss 00:00:00.000 \ + -pix_fmt rgb24 \ + -r 10 \ + -s 320x240 \ + -t 00:00:10.000 \ + output.gif +``` +It works great, but output gif file has a very low quality. +Any ideas how can I improve quality of converted gif?" +"Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor?" +"Why does this throw ```NullPointerException``` +```public static void main(String[] args) throws Exception { + Boolean b = true ? returnsNull() : false; // NPE on this line. + System.out.println(b); +} +public static Boolean returnsNull() { + return null; +} +``` +while this doesn't +```public static void main(String[] args) throws Exception { + Boolean b = true ? null : false; + System.out.println(b); // null +} +``` +? +The solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?" +How do DOS games like DOOM benefit from a PCI graphics card? +"I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python?" +"Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency?" +Is it worth patenting an algorithm if I don't have the money to defend against infringements? +"""I have a ```String[]``` with values like so: +```public static final String[] VALUES = new String[] {""""AB"""",""""BC"""",""""CD"""",""""AE""""}; +``` +Given ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?"" How do I determine whether an array contains a particular value in Java?" +"Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time? +Is this a general things, or there are different cases?" +"How can I copy a string (e.g ""hello"") to the System Clipboard in C#, so next time I press CTRL+V I'll get ""hello""?" +"I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it. +```\usepackage{draftwatermark} +\SetWatermarkText{DRAFT} +\SetWatermarkScale{1} +```" +Understanding the Rails Authenticity Token +Why is FIFA against adding instant replay to the game? +"If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre?" +Applying filter in scipy.signal: Use lfilter or filtfilt? +"What do different people in the department expect from a postdoc? +By different people I mean the advisor, graduate students and PhD students. +I know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that. +The above are my thoughts. My question is divided into the following sub-parts: + +* What would you as a professor expect from your postdoc? +* What preparation one must do to rise to the expected level? +* Is the preparation merely restricted to having sound academic record and experience?" +Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example? +How is arc defined in TikZ? +How to connect mysql workbench to running mysql inside docker? +Can meat spoil outside the fridge if it's baked into bread as a filling? +"I'm wondering how the XML Schema specification handles these cases: +``` +``` +No maxOccurs given -> Is this the cardinality [1..1]? +``` +``` +I suppose this is simply invalid? +``` +``` +Is this the cardinality [0..2] or [1..2]? +Is there an ""official"" definition on how the XML Schema spec handles these cases?" +Were there any flying dinosaurs? +"Say, a table ```car``` has one-to-one relationship to tables ```electric_car```, ```gas_car```, and ```hybrid_car```. If a ```car``` is ```electric_car```, it can no longer appear in ```gas_car``` or a ```hybrid_car```, etc. +Is it a bad practice to have several mutually exclusive one-to-one relationships in database design?" +"I see a low use of Mathematica in Kaggle competitions. Why would one use the Wolfram Language versus R, Python, or Julia for machine learning? Besides prettier plots and the Manipulate function, do we have something that is useful for ML that other languages are lacking?" +"I'm using wp_nav_menu and am trying to create custom output for the sub-level drop downs. I came across the ""items_wrap"" argument but there's really not much information as to what it is, how it works, and what kind of things can be done with it. +What exactly is ""%1$s"" and ""%2$s""? (Can anyone explain it in layman's terms?)" +"I've noticed that people on YouTube and even on TV would sometimes say things like ""I used to take lots of coke a few years ago"" or ""I used to smoke weed daily until this and that"" or ""Yea, I smoke weed every once in a while,"" or ""I used to pirate games a lot when I was a bit younger"" or ""I used pirated Windows and Photoshop until I got a job,"" etc., etc.. +Basically they are confessing to a crime, on public record, couldn't anyone come after them? They've already confessed - technically all that would have to be done is a trial. +How do people publicly admit to criminal activity and not typically get arrested?" +"Did two dissenting Supreme Court justices agree that Trump was ""absolutely immune"" to the Manhattan DA's subpoena?" +"Just curious, given how heavily from Tolkien D&D drew, and the fact that games like Wizardry used Hobbits, is there a good design reason why Gygax and company used Halflings (a term that also appears in Tolkien) vice Hobbits as the term for our little friends?" +"My USB drive used to be originally 8GB when I bought it. +I'm trying to reformatted in Windows 7 by right clicking on the drive and selecting ```Format...```. But the capacity only shows 250MB. +Is there something I can do to get the original size back? Maybe it got partitioned in a weird way? +The flash drive is a SanDisk Cruzer Micro 8GB. " +"I am a Tor developer. I understand that the .onion address is a public key of sorts, but not much more than that (I can vaguely guess, though). When nobody knows the IP of the .onion address, how do requests reach it? Are they bounced between nodes in the P2P network till someone decrypts it with the corresponding private key?" +"I have been offered a PhD position by an inexperienced professor in a great institution in Europe. Despite the fact that the institution is very strong in my area, since the position was offered by this particular professor, I would have to commit myself to working with him for my thesis. This professor is young, and relatively inexperienced, but I enjoy the things he works on, and we seem to get along well. +My question is, would having an inexperienced advisor hurt my growth as a scientist, or my career in general? Will I have the time during my PhD to also work on the side with other, more renowned professors in the department, or is one usually focused in a single research project?" +"Is there a phrase that means ""too important"" and ""attracting too much attention""?" +"This guy claims that Olympic powerlifters working in the 1-6 rep range can increase strength without increasing muscle size. + +> Trained Olympic lifters, for example, were shown over a two-year period to have significant strength increases with barely noticeable increases in muscle mass (Hakkinen et al, 1988). I had a similar experience when I used AST's Max-OT principals. My strength went up like crazy, but I gained very little size. Obviously, traditional strength training with low volume and low sets (1-6 reps, 3 or less sets) is not the best approach. Strength training does cause hypertrophy (Hakkinen et al, 1985), but it won't cause maximum hypertrophy. + +What is the scientific explanation for this? Is the inverse true? That is, can a buff guy (with lots of prominent muscle) actually be weak? " +What are the major concerns about planting trees to create carbon offsets? +"I am wondering how to generate uniformly distributed points on the surface of the 3-d unit sphere? Also after generating those points, what is the best way to visualize and check whether they are truly uniform on the surface $x^2+y^2+z^2=1$?" +"In Shutter Island, at the end of the movie Teddy had a chat with Chuck, in that scene Teddy told to Chuck as, + + Which would be worse: To live as a monster, or to die as a good man? + +What's the implicit meaning of this dialogue? Who's the monster as Teddy mentioned? +And, who's a good man?" +"To set the minimal distance between flexbox items I'm using ```margin: 0 5px``` on ```.item``` and ```margin: 0 -5px``` on container. For me it seems like a hack, but I can't find any better way to do this. + + +```#box { + display: flex; + width: 100px; + margin: 0 -5px; +} +.item { + background: gray; + width: 50px; + height: 50px; + margin: 0 5px; +}``` +``` + + + + +``` + + +" +"Is there a Git for data? The key improvement I'd want is to Diff/Merge more intelligently. e.g. in CSV rather than line vs line comparison, it would do cell vs cell. +And ordering is usually not significant, e.g. rows in a CSV, whereas Git does care and presents the user with 'conflicts'." +"I have been puzzling over where to put the submit button, on the left or the right. In researching, I noticed that many sites put buttons on the bottom right in dialogue boxes, and on the bottom left in forms. +It makes sense: in a dialogue box it seems to denote finality, being in the endpoint of the window for left–right readers; in a form, the bottom right could be in a different position relative to the rest of the form if the window is resized. +It seems to be a convention, but should the OK/Cancel buttons be aligned right or centered? +Should the OK/Cancel buttons be aligned right or centered?" +"Is it at all possible to update object's properties with ```setState```? +Something like: +```this.state = { + jasper: { name: 'jasper', age: 28 }, +} +``` +I have tried: +```this.setState({jasper.name: 'someOtherName'}); +``` +and this: +```this.setState({jasper: {name: 'someothername'}}) +``` +The first results in a syntax error and the second just does nothing. Any ideas?" +What is the difference between Non-Player Characters (NPCs) and bots in video games? +"Is there anything like ```static class``` in java? What is the meaning of such a class. Do all the methods of the static class need to be ```static``` too? Is it required the other way round, that if a class contains all the static methods, shall the class be static too? What are static classes good for?" +"The Episode IV-VI movies never mention the Emperor's name. In Episodes I-III, we can guess that Darth Sidious will be the emperor, but what about Chancellor Palpatine? If the audience didn't know that he was Sidious, the impact of the reveal would be far different than if they did. +But I did. In all the novels and comics that came out after ""Return of the Jedi"", the Emperor's name was stated plainly: Palpatine. +So when I saw the prologue movies, for the life of me I couldn't figure out: was I supposed to know that Palpatine was the villain? +Maybe the filmmakers figured that most of the moviegoing public never got into the Expanded Universe. But they had to know that the hardcore fans would know. Or maybe when you watched the movie, even if you hadn't heard of Palpatine, it was supposed to be obvious? +What was the intent?" +"So, students in Gryffindor are supposed to represent bravery. How does Neville represent bravery, to the point in being accepted into the house. I've always thought of his strongest traits being things like loyalty, willingness to work hard, etc, and these things would tend to put him in Hufflepuff. " +"This claim was made popular by being said in the movie The Social Network. It exactly says: + +> Did you know there are more people with genius IQs living in China than there are people of any kind living in the United States? +" +"I am trying to get my program to print out ```""banana""``` from the dictionary. What would be the simplest way to do this? +This is my dictionary: +```prices = { + ""banana"" : 4, + ""apple"" : 2, + ""orange"" : 1.5, + ""pear"" : 3 +} +```" +"Different coffee packets advertise different amounts of 'Robusta' and 'Arabica'? What do these terms refer to, and how does it affect the taste of the coffee?" +"So whenever we want to shoot our flash before taking a photo. we have to charge it first. +What is the point of the charging our flashes? Aren't their power directly supplied by the battery of our camera? +Please answer for the built in flash on the 2000D and the traditional hot shoe Xenon flashes. +Perhaps these hot shoe xenon flashes have their own batteries charged by the slow hot shoe port. Who knows? " +"What are some strategies to maintain morale and productivity after massive layoffs? I am not in a managerial role, just a lead role, and am asking for myself and my fellow employees." +"Could you please clearly explain what is the difference between correlation and convolution that is done by a filter on an image? +I mean in terms of signal processing definition I know that convolution describes the output of an LTI system, that is if an LTI system produces an output due to convolution with an input system then the output signal can be described as the result of convolution of the input signal and the impulse response of the LTI system. As for the correlation, it describes the similarities between to signals. But how does convolution and correlation effect on a image and how different are they in terms of effects? +Thanks" +"24601 has developed into being an iconic part of both the Les Miserables book and musical. Was that number special to him, or was it simply a random number he chose (I doubt it)?" +Why does Michael Crichton use US Customary measurements in hard sci-fi? +"How can horns, most of which have only three buttons, play all their notes?" +"I am a big fan of worldbuilding. A common sight in science fiction is that aliens pretend to be human (For example in Third Rock from the Sun). Obviously if the aliens are advanced enough to disguise themselves as another species, there are much easier, simpler and less expensive methods to destroy humanity, so why else would an advanced alien civilization waste time, energy and resources to disguise themselves as humans? What possible scientific, cultural or commercial use could such an expensive procedure have?" +"I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: ""Can you name all the uses of “_”?"". Can you? If yes, please do so here. Explanatory examples are appreciated." +"My university usually asks that we book a flight via a travel agent, but the prices he gives me are about $50 higher than the prices I can get by online booking in the flight company's website. Why would a company want me to book a flight via a travel agent if it is more expensive?" +Layman's explanation of encryption backdoors +"I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player. +When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar. +I am using this code to make it move the selected option to the top of the div: +```var pathArray = window.location.pathname.split( '/' ); +var el = document.getElementById(pathArray[5]); +el.scrollIntoView(true); +``` +It moves it to the top of the div but about 10 pixels too far up. +how to fix that?" +"Suppose I have the geographic coordinates of "Saratoga, California, USA" as +```Latitude: 37°15.8298′ N +Longitude: 122° 1.3806′ W +``` +I know from here that in the case of latitude ```1° ≈ 69 miles``` and that longitude varies: +```1° longitude = cosine (latitude) * length of degree (miles) at Equator. +``` +How many miles is 1° longitude at ```longitude: 122°1.3806′ W```?" +"I have read numerous times that some Norse warriors, upon death, would go in Fólkvangr, while some others would go to Valhalla. How was it decided which warrior would go to which place? Why did the need to have many ""paradises"" (whatever you many call it) exist? +Citing Wikipedia: + + > In Norse mythology, Fólkvangr (Old Norse ""field of the host"" or ""people-field"" or ""army-field"") is a meadow or field ruled over by the goddess Freyja where half of those that die in combat go upon death, while the other half go to the god Odin in Valhalla." +"I noticed that there is a binary executable ```/bin/echo``` on my Ubuntu MATE 17.04 system. +I thought, that's odd, because +```$ type echo +echo is a shell builtin``` +Cursory testing suggests that ```/bin/echo``` does the same sort of thing as the Bash builtin ```echo```: +```$ /bin/echo foo +foo +$ /bin/echo $USER +zanna +``` +So, why is there another version of ```echo``` separate from the Bash program, and why or when would I want to use it?" +"what's the difference between JavaScript objects, classes and functions?" +"In most introductory algorithm classes, notations like $O$ (Big O) and $\Theta$ are introduced, and a student would typically learn to use one of these to find the time complexity. +However, there are other notations, such as $o$, $\Omega$ and $\omega$. Are there any specific scenarios where one notation would be preferable to another?" +Why is Gaia operating around Earth orbit? Why not send it to Neptune's orbit? +"I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use ```time.strftime```, I get a ```TypeError```: +```>>>import time +>>>print time.strftime("%B %d %Y", "1284101485") +Traceback (most recent call last): + File "", line 1, in +TypeError: argument must be 9-item sequence, not str +```" +"In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this: +```mysite/ + manage.py + mysite/ --> (settings.py, etc) + myapp/ --> (models.py, views.py, etc) + static/ +``` +In ```mysite/settings.py``` I have: +```STATIC_ROOT = 'staticfiles' +``` +So when I run the command: +```python manage.py collectstatic +``` +It creates a folder called ```staticfiles``` at the root level (so same directory as ```myapp/```) +What's the point of this? Isn't it just creating a copy of all my static files?" +"I am used to thinking of finite-differences as a special case of finite-elements, on a very constrained grid. What are criteria to choose between finite-differences and finite-elements" +How important is multithreading in the current software industry? +Is it true that the price of diamonds is based on a monopoly? And who actually runs/owns this supposed monopoly? Is this likely to affect diamond prices if I am interested in purchasing? +"Normal filesystem images can be easily mounted: +```mount system.img /mnt +``` +Examined, and modified. But when I try this with a Raspberry Pi system image (e.g. raspbian), I get: +```mount: unknown filesystem type '(null)' +``` +And no matter what I try with ```-t```, it won't work. How can I mount this image?" +How does immersion passively help with learning a language? +"I have a script, that does not exit when I want it to. +An example script with the same error is: +```#!/bin/bash +function bla() { + return 1 +} +bla || ( echo '1' ; exit 1 ) +echo '2' +``` +I would assume to see the output: +```:~$ ./test.sh +1 +:~$ +``` +But I actually see: +```:~$ ./test.sh +1 +2 +:~$ +``` +Does the ```()``` command chaining somehow create a scope? What is ```exit``` exiting out of, if not the script?" +Adding a new swap file. How to edit fstab to enable swap after reboot? +" +How do I add a validation to make sure the date string being passed to the method is in the ffg. format: +```'YYYY-MM-DD' +``` +if it's not, method should raise some sort of error" +When to use UICollectionView instead of UITableView? +"On my branch I had some files in .gitignore +On a different branch those files are not. +I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not. +Unfortunately I get this: + + The following untracked working tree files would be overwritten by merge + +How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?" +"Since long time ago I have been thinking in two problems that I have not been able to solve. It seems that one of them was recently solved. I have been thinking a lot about the motivation and its consequences. Mostly because people used to motivate one of them with some very interesting implications. My conclusion however, is that there is a mistake in the motivation of the problem, and that, while being a really interesting result, it does not make any sense in the setting in which is formulated. As my opinion is not relevant compared to one of the experts in the area, I do not say anything. +My question is if you can provide me some examples of conjectures that were believed to be interesting in the mathematical community because of a specific reason, but that once having the proof, people realized that the reason to motivate the problem was not truly related to its solution. Or in other words, the solution of the problem gives no clues about the original motivation. " +How do GPS receivers communicate with satellites? +Why is iceberg lettuce bad for rabbits? +How do I open the JavaScript console in different browsers? +"I have Ubuntu 10 as the guest OS on a Windows 7 machine. I have been trying to setup shares through VirtualBox, but nothing is working. First, I create the share in VirtualBox and point it to a Windows folder. Then I try to mount the drive in Linux, but I keep getting +```/sbin/mount.vboxsf: mounting failed with the error: Protocol error +``` +I have read so many solutions to this, but none seem to work. I have tried: + +* Using the mount.vboxsf syntax +* Reinstalling VBox additions +* Rebooting +* Enabling and trying as root account + +I made a share called "Test" in VBox Shared folders. Then I made a directory in ubuntu named "test2". Then I tried to execute this command: +```sudo mount -t vboxsf Test /mnt/test2 +``` +Any other ideas?" +"What does %~dp0 mean, and how does it work? +I'd also like to know if it is a documented feature, or something prone to be deprecated." +Should a tester feel bad about finding too many defects/bugs in the product? +"Millions of colors in the visible spectrum can be generated by mixing red, green and blue - the RGB color system. Is there a basic set of smells that, when mixed, can yield all, or nearly all detectable smells ?" +Do you bleed to death after your penis is cut off? +"In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? +The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with ```filter```, ```map``` or ```reduce```?" +"What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile? +For instance, an environment variable that has been set through some ```docker exec container /bin/bash``` session? +I can do ```docker exec container env | grep ENV_VAR```, but I would prefer something that just returns the value. +I've tried using ```docker exec container echo ""$ENV_VAR""```, but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer. +Thanks." +"I am confused about the use cases for both ```InputStream``` and ```OutputStream```. +Please include a snippet of code to go along with your explanation." +"What is the difference between: +```npm install [package_name] +``` +and: +```npm install [package_name] --save +``` +and: +```npm install [package_name] --save-dev +``` +What does this mean? And what is really the effect of ```--save``` and ```-dev``` keywords?" +pod install -bash: pod: command not found +"I read in the Essential C# 3.0 and .NET 3.5 book that: + + GetHashCode()’s returns over the life of a particular object should be + constant (the same value), even if the object’s data changes. In many + cases, you should cache the method return to enforce this. + +Is this a valid guideline? +I have tried a couple built-in types in .NET and they didn't behave like this." +"Especially in blitz or bullet games, it is possible that a player makes an illegal move, for example castles through check. + +* If the opponent does notice the illegal move, then as far as I know the first player is obliged to make a legal move with the same piece, if one exists. What if there are no legal moves? +* What if the opponent, being in time pressure, doesn't notice the illegal move and makes a move. What happens after they realize that? Does the person who made the illegal move forfeit? Or is the whole game cancelled? + +Are there any standard rules for these kinds of situations?" +How to set button click effect in Android? +"The following article from CNN describes a Michigan police officer being put on administrative leave for having KKK material at his home: https://www.cnn.com/2019/08/10/us/michigan-officer-placed-on-leave-kkk-document-house/index.html. The materials were discovered while a potential buyer was touring his house. +Although I vehemently condemn the KKK, doesn't this officer have the right to display whatever he wants in his home so long as it doesn't actively and deliberately call for violence? Aren't these articles protected under the first amendment? I realize this is an extreme example, and as a police officer his job requires interacting with all races, but unless it can be shown that he's bigoted and that it negatively affected his job performance, isn't it illegal to fire him? +Employers can restrict speech according to company policy while at work, but we all have to go home at some point. Can those restrictions follow us after clocking out? " +What does strength refer to in mathematics? Is it a formal idea? +"Does vegetarianism affect life expectancy? +Is an average vegetarian supposed to live longer just because of their diet?" +"What is the difference between an object and a companion object in a class in kotlin? +Example: +```class MyClass { + object Holder { + //something + } + companion object { + //something + } +} +``` +I already read that companion object shall be used, if the containing parameters/methods are closely related to its class. +But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name. +Is there maybe a difference in its ""static"" (I'm from the java side) lifecycle? " +I've rooted my phone. Now what? What do I gain from rooting? +"Is there a better way to determine whether a variable in ```Pandas``` and/or ```NumPy``` is ```numeric``` or not ? +I have a self defined ```dictionary``` with ```dtypes``` as keys and ```numeric``` / ```not``` as values." +I've come across the polynomial algorithm that solves 2SAT. I've found it boggling that 2SAT is in P where all (or many others) of the SAT instances are NP-Complete. What makes this problem different? What makes it so easy (NL-Complete - even easier than P)? +Why isn't Sectumsempra an Unforgivable Curse? +How can I add a delay to a program in C#? +"I'm trying to write a Bash script that will overwrite an existing directory. I have a directory ```foo/``` and I am trying to overwrite ```bar/``` with it. But when I do this: +```cp -Rf foo/ bar/ +``` +a new ```bar/foo/``` directory is created. I don't want that. There are two files in ```foo/```; ```a``` and ```b```. There are files with same names in ```bar/``` as well. I want the ```foo/a``` and ```foo/b``` to replace ```bar/a``` and ```bar/b```." +"Is there a particular reason the elves die off so fast? After the first war against Sauron, I recall the elves being decimated, to the point that they're almost useless army-wise in the trilogy. But I'm guessing men suffered equal or greater losses as well. +Anyways, other races just seem much more capable of repopulating, while is seems like there are incredibly few (if any?) elven children. Considering the fact that elves are immortal, wouldn't their population be the fastest to grow? Also the seem to be perpetually 40 years old, so aren't they eternally fertile as well? Why don't they have more kids and build bigger societies?" +Reasons for being vegetarian or vegan other than ethical reasons? +My mom has a green card that expires 2028 but has been out of the US in the UK for over a year due to COVID travel restrictions. Can she enter now? +What is the LXX and why is it so noteworthy that there is a Greek translation of the OT? Wouldn't it be better to directly reference manuscripts in the original languages? +"I have to disable inputs at first and then on click of a link to enable them. +This is what I have tried so far, but it doesn't work. +HTML: +``` +``` +jQuery: +```$(""#edit"").click(function(event){ + event.preventDefault(); + $('.inputDisabled').removeAttr(""disabled"") +}); +``` + +This shows me ```true``` and then ```false``` but nothing changes for the inputs: +```$(""#edit"").click(function(event){ + alert(''); + event.preventDefault(); + alert($('.inputDisabled').attr('disabled')); + $('.inputDisabled').removeAttr(""disabled""); + alert($('.inputDisabled').attr('disabled')); +}); +```" +"I'm no expert in darkroom photography, but it seems a little odd that there is a type of light that doesn't affect film or developing paper etc. So why is a dark-room safelight safe?" +"With the command: +```ls -la * +``` +I can list all my symbolic links. +How can I remove all symbolic links which are linked to a special folder? +For example: +In my directory ```usr/local/bin``` I have the following entries: +```lrwxrwxrwx 1 root root 50 Apr 22 14:52 allneeded -> /usr/local/texlive/2011/bin/x86_64-linux/allneeded +lrwxrwxrwx 1 root root 47 Apr 22 14:52 amstex -> /usr/local/texlive/2011/bin/x86_64-linux/amstex +lrwxrwxrwx 1 root root 24 Apr 23 19:09 arara -> /home/marco/.arara/arara +``` +Now I want to remove all links with the path ```/usr/local/texlive/```" +Did Aztecs know how many continents there are on earth? +What did the Soviet Union and Russia bring to the ISS? +"What utility can move my Windows boot partition over to another hard drive? +My preference is that it would be really easy. + +* Boot into Windows +* Pick drive to move +* Pick target drive +* It copies everything over, and reboots to the correct partition." +What's the difference between ASCII and Unicode? +Reasons why healthy people would intentionally want to get infected? +"In The Avengers, the Council contacted Nick Fury and supposedly, they want to nuke Manhattan. Nick didn't agree so they contacted a S.H.I.E.L.D. operative to nuke Manhattan. +When they found out that an unauthorized jet was trying to fly, Nick grabbed a rocket launcher and fired it at the jet, which was a decoy and the real jet was able to escape. +However, why would he do that? If that was the real plane carrying a nuke enough to level Manhattan, wouldn't the nuke explode and destroy the base along with them if he fired a rocket launcher at it?" +"Since I created my repository it appears that the tags I have been +creating are not pushed to the repository. When I do ```git tag``` on the +local directory all the tags are present, but when I logon to the +remote repository and do a ```git tag```, only the first few show up. +What could the problem be?." +How do I add Git submodule to a sub-directory? +"Given that Kohn-Sham DFT is strictly a ground-state method (at 0 K), how is it sufficient to describe materials in real-life applications?" +"I don't really get the difference between gain and volume boost. + +So if I understand correctly, gain directly boosts a signal from a line or input while volume handles the output. Volume isn't really for boosting either. +Would this mean, in most settings, getting 'close to' as much gain as possible without any hiss/background noise is ideal?" +"I recently had someone claim (on an unrelated SE site I won't link to) that it is the responsibility of a player to correctly identify their hand, that what you "call" your hand determines the winner: + +For example, you have an Ace, King, Queen, Jack, and Ten. You call your hand and say, "I have a Straight!" +But that was a bad move on your part because you are a novice player and you did not notice that all of your cards are Spades. You actually had a Straight Flush, but now you have lost because one of the remaining players had a Full House. +Your hand has not been determined until you call your hand. + +Is this true? Clearly you might play your hand differently if you misunderstand what you have, but I always thought that the cards speak for themselves once they are revealed. +Or would it depend on the specific poker variation/house rules?" +How to get the first item from an associative PHP array? +Why do people write #!/usr/bin/env python on the first line of a Python script? +"Nowadays each graphic card has some driver in operating system that translates some (typically) standard API such as OpenGL, so that programmers use some standardized API code to tell graphics cards how and what they want to render. (Actually that's already a bit hard-core most programmers really use various game engines that do this for them). In times of old computers - how was this done? Did every programmer of every game implemented all possible various API's that old graphic cards supported? Or did the old game studios from MS-DOS times had their own ""game engines"" that provided some abstraction when it came to these graphic cards? I remember there were many various card vendors and I remember old games asked me which one I have - so I suppose these games contained code / drivers for all these cards?" +"Why is it ""behead"" and not ""dehead""?" +Why do many vinyl albums of classical music have Sides 1 / 4 on the first record and 2 / 3 on the second? An example of this is the RCA Red Seal recording of Beethoven's 9th Symphony by the Boston Symphony Orchestra. +Why isn't the market dropping like a stone with all the bad news? +"What are Null Pointer Exceptions (```java.lang.NullPointerException```) and what causes them? + +What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?" +"In Raiders of the Lost Ark, at the Ark opening ceremony the Nazi troops brings the Ark of the Covenant to the top of the mountain as Belloq said something before opening the Ark. Then they took the sand from the Ark and suddenly spirits coming out from the Ark and they're all killed (except Indy and Marion) by the freed-spirits which came from the Ark. Meanwhile, Indy asks Marion to keep her eyes shut. They didn't see the Ark when it was opened, so they're survived. In that scene what I don't understand is how did Indy know not to look into the Ark when it was opened?" +"What is likely to happen when you plug two ends of a network cable to a single switch/router? Will this create problems on the network, or just be ignored?" +What command do I use to find the size of all the files (recursively) in a Linux or Mac OS X directory? +"I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. +```MyClass *m = (MyClass *)ptr; +``` +all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code? +```MyClass *m = (MyClass *)ptr; +MyClass *m = static_cast(ptr); +MyClass *m = dynamic_cast(ptr); +```" +Why don't toilets use saltwater? +How do I modify fields inside the new PostgreSQL JSON datatype? +"I find that the survivability and general performance of my party increases massively from levels 1 to 2. At times, level 1 feels like a completely different game from level 2. However, I can't fathom how or why. I think that the availability of healing has something to do with it. From a mechanical perspective, is there any deep reason why level 1 and level 2 seem so radically different? Furthermore, why I do find no similar differences between later levels, such as 6 and 7?" +"In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section number 5. +So I get an exception, when I call: +```[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; +``` +Is there another way to scroll to the top of table view?" +While in Phd I developed a lot of code that I want to turn into start-up. Can I do this? +"I have heard multiple times in photography, the words Bokeh, and Gaussian Blur. To me, it seems that the words are used almost interchangeably, but in some instances, I have heard them contrasted. What's the difference, and what are the definitions of each of them?" +"In 1969, NASA not only went to the moon, but broadcast the whole thing live on TV. +How did they achieve the TV broadcast? What technology did they need to use to send a video and audio signal from the moon to earth? Was there much of a lag?" +"Why does ""elite"" rhyme with ""beet"" rather than ""bite""?" +"A lot of ShaderToy demos share the Ray Marching algorithm to render the scene, but they are often written with a very compact style and i can't find any straightforward examples or explanation. +So what is Ray Marching? Some comments suggests that it is a variation of Sphere Tracing. What are the computational advantages of a such approach?" +Is martial arts training 'inadequate' for the real world? +Make a single page landscape in Google Documents +"PHP is writing this error in the logs: ""Notice: Use of undefined constant"". +Error in logs: +```PHP Notice: Use of undefined constant department - assumed 'department' (line 5) +PHP Notice: Use of undefined constant name - assumed 'name' (line 6) +PHP Notice: Use of undefined constant email - assumed 'email' (line 7) +PHP Notice: Use of undefined constant message - assumed 'message' (line 8) +``` +Relevant lines of code: +```$department = mysql_real_escape_string($_POST[department]); +$name = mysql_real_escape_string($_POST[name]); +$email = mysql_real_escape_string($_POST[email]); +$message = mysql_real_escape_string($_POST[message]); +``` +What does it mean and why am I seeing it?" +"I'm from a very rural area and love to garden, however, for work I just moved into an apartment in the city. I miss being able to grow vegetables and so I attempted to start some leaf lettuce indoors, however, almost every plant died quickly. I'm just curious, does anyone have experience growing vegetables indoors? What are the best ones for this? What sort of planter do you use? Do they need to be directly next to a window? How often should they be watered? I'm not used to not having Mother Nature help me out with my plants Any tips that can be provided would be much appreciated, thanks!" +What are the advantages of studying words by their frequency? +"I have heard many people saying, “Hah! I beat Stockfish,” and one saying, “I am the best chess player ever! I beat Stockfish.” So I wonder if it is possible, just to know whether I should try to beat it. I tried to play it once; I barely played 25 moves." +How to decrypt Jenkins passwords from credentials.xml? +"I'm pretty disappointed with my horse. He wasn't cheap -- 1000g -- but he just doesn't seem that fast. To make things worse, he's a bit of a wolf magnet and every time I get attacked I have to tediously dismount, blast the wolf, and then remount. +Is the speed of a horse actually significantly faster than normal running speed? If so, how much faster?" +"Other than rust, corrosion, and other reactions with air that would make the use of a metal unfavorable, how do different metals affect the performance? +Let's give Yagi an example: +Let's say I use 4 different metals for the directors +, reflector, and driven element. +One antenna made out of copper, one made out of aluminum, and one made out of a higher resistance conductor, let's say graphite (I know it would snap, I'm just talking theoretical), and iron +Other then the metal variations, the antennas are identical. +So, do different metals with different conductivity and permiability affect the performance of an antenna including gain, efficiency, impedance, elevation, or any other characteristic other then mechanical strength, and chemical reliability in open air. " +"Windows in its earliest days was simply a shell that ran on top of MS-DOS, which means that Windows 3.1 itself was actually just a standard MS-DOS application like any other. +Yet, MS-DOS is not a multitasking operating system, and at the same time, Windows applications were compiled native-code binaries that ran without any form of managed environment. So, how exactly was multitasking of Windows binaries achieved if Windows 3.1 was simply a regular old MS-DOS program itself? Are there any old technical documents still floating around that describe the early Windows architecture internally?" +"I'm working on 2 different branches: release and development. +I noticed I still need to integrate some changes that were committed to the release branch back into the development branch. +The problem is I don't need all of the commit, only some hunks in certain files, so a simple +```git cherry-pick bc66559 +``` +does not do the trick. +When I do a +```git show bc66559 +``` +I can see the diff but don't really know a good way of applying that partially to my current working tree. " +"In Civilization V, you attain a cultural victory by accumulating enough culture to purchase at least 36 social policies, and then building a wonder. The catch is that the more cities you build, the more culture you need to generate before you hit the next ""plateau"" of culture. +What is the ideal number of cities for a cultural victory? Does it change over time? " +"How to find if a customer is logged in or not in Magento 2. +If the customer is logged in then how to get customer data from a session?" +"I have a 9 year old daughter that has expressed some interest in manga, but I'm having trouble locating series that are appropriate for her age. No one at our local bookstore could offer any advice. Is there a kid-friendly imprint or other resource I could use to help her find something appropriate? My preference is for physical books but I'm willing to explore digital options." +"I'm looking for a precise piece of information in a database which I have no knowledge about. The database is on a separate machine, but I can log into it, and launch a ```psql``` command line, with administrator rights. +It's a third-party product, and they are slow to answer questions. I know the data is inside that database, so I want to do a little bit of reverse-engineering. +Given a table name, is it possible to get a list of the names of the columns in that table? +For example, in SQL Server, it's possible to dump a table into a reusable ```CREATE``` statement, which textually lists all the columns the table is composed of." +"I am using Visual Studio Code and have a fairly common project structure: +```├── client/ +│ ├── tsconfig.json +├── shared/ +├── server/ +│ ├── tsconfig.json +├── project.json +``` +The two tsconfig files have different settings (e.g. the one under ```client/``` targets ES5, the one under ```server/``` targets ES6). Note that there is no tsconfig in the root directory. +The problem is that I want the shared directory to be included in both projects. I can't do this using tsconfig because the ```exclude``` option won't let me include a folder that is in a higher directory than the tsconfig.json, and using ```files``` I have to constantly keep the list of files up to date as it doesn't support globs. +Note that I can compile fine by adding the shared folder into tsc, what I want is for the Visual Studio Code IDE to recognise the shared code for intellisense etc. +Is the only option to wait for filesGlob?" +"I have the following method to save an Object to a file: +```// Save an object out to the disk +public static void SerializeObject(this T toSerialize, String filename) +{ + XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); + TextWriter textWriter = new StreamWriter(filename); + xmlSerializer.Serialize(textWriter, toSerialize); + textWriter.Close(); +} +``` +I confess I did not write it (I only converted it to a extension method that took a type parameter). +Now I need it to give the xml back to me as a string (rather than save it to a file). " +"I have a problem with the embedded bitcode term. +What is embedded bitcode? +When to enable, ```ENABLE_BITCODE``` in new Xcode? +What happens to the binary when enabled, ```ENABLE_BITCODE``` in Xcode 7? " +"In Dupire's local volatility model, the volatility is is a deterministic function of the underlying price and time, chosen to match observed European option prices. +To be more specific, given a smooth surface $(K,T)\mapsto C(K,T)$ where K is the strike and T is time to maturity. Dupire equation implies that there exits an unique continuous function $\sigma_{loc}$ defined by +$$\sigma_{loc}^{2}(K,T)=\frac{\partial_{T}C(K,T)+rK\partial_{K}C(K,T)}{\frac{1}{2}K^{2}\partial_{KK}C(K,T)}$$ for all $(K,T)\in(0,\infty)\times(0,\infty)$ such that the solution to the stochastic differential equation $dS_{t}/S_{t}=rdt+\sigma(t,S_{t})dW_{t}$ exactly generates the European call option prices. +What do the dynamics of the local volatility mean? Are dynamics equivalent to the volatility surface? Why the dynamics of local volatility model is highly unrealistic?" +Can you explain why we need a large number of trees in random forest when the number of predictors is large? How can we determine the optimal number of trees? +"I believe artificial intelligence (AI) term is overused nowadays. For example, people see that something is self-moving and they call it AI, even if it's on autopilot (like cars or planes) or there is some simple algorithm behind it. +What are the minimum general requirements so that we can say something is AI?" +"I have some questions regarding the usage and significance of the ```synchronized``` keyword. + +* What is the significance of the ```synchronized``` keyword? +* When should methods be ```synchronized```? +* What does it mean programmatically and logically?" +"I am using the ```$http``` service of AngularJS to make an Ajax request. +How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?" +"Let's say that we have a gaseous or liquidus compound (I don't know if elements or compounds make a difference, take this as a thought experiment), and we have a tungsten or steel block that's 5cm (or less, you choose) thick. Is there any physical method for that gas or liquid to pass through that thick heavy metal block (not by drilling etc.)?" +"Once, I boarded a plane, went to my designated seat and tried to put my bag in the overhead bin. However, it was full, and other adjacent overhead bins were full too. Because I had a seat next to the emergency exit, which I paid for, I had to hand over my bag to someone else in order to take off. +Do I have any rights over the overhead bin above my seat? +Could I ask the flight attendant to remove some of the bags to make room for me? +I cannot imagine that the bins were full because there was not enough space. I think this happened because some people were ignorant enough to bring more bags than is allowed inside the airplane instead of sending them to cargo. If this is the case why doesn't the airline enforce the bag limit inside the airplane?" +"The Canon EF 40mm f/2.8 has a designation of STM on the lens. What does this mean? What are the advantages of having it and does it replace an older technology? +" +"I'm trying to set get id of all elements in an ```HTMLCollectionOf```. I wrote the following code: +```var list = document.getElementsByClassName(""events""); +console.log(list[0].id); +for (key in list) { + console.log(key.id); +} +``` +But I got the following output in console: +```event1 +undefined +``` +which is not what I expected. Why is the second console output ```undefined``` but the first console output is ```event1```?" +"I am 21 years old and living in a large city in Germany where smalltalk in local markets is not a common thing. +A new cashier joined my local food shop. She’s always at the checkout and never doing stuff like sorting products or cleaning the floor where I could actually ask her out. I am quite new to relationships, but the signs she gave me are promising. +My question is how I can ask for her number, or ask her out for coffee while she is only sitting at the checkout? I mean there are always like 5 people before and after me, and I think it would be awkward if we are changing numbers while customers are waiting behind us. Or even worse if I read the signs wrong and she rejects me? Since the store is just 5 min away from my place I visit regularly and don't want to leave a bad impression there." +"You start with the number 1536. Your mission is to get to 1 in as few steps as possible. At each step, you may either multiply or divide the number you have, by either 2 or 3; but, only if the result is a whole number whose first digit is 1, 3, 4, or 9. That is all." +"I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 = ```var oImg = document.createElement(""img""); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); ``` Is this the simplest but most robust (error free) way to do it?" +Why is %s better than + for concatenation in python? +"I had an interview with an employer working on a software-based vehicle solution. +Before going further in the interview process, he gave me a task to find out if a potential customer (automotive OEMs) is interested. +My question is, how can I approach a potential customer and arrange some time together to present to them the solution?. I'm intending to use Linkedin, but I'm not sure how to proceed. + +* Who to contact (I mean the person position in the company) +* How to formulate the request? +" +"When an expendable booster rocket stage nears the end of its burn, does the guidance computer shut the engine(s) off at a certain velocity/altitude for the mission, or does the stage completely exhaust its propellants?" +"Is "ima" an informal spelling of "I must"? + +MegaCharizardZord Replying to @nytimes about COVID-19 vaccine: +i just hope when i take it don't die lol. i trust the government in Canada, but if I do get something ima sue the shit out of em lol. + + +Source: Twitter +" +"How to prevent ""Delhi Belly"" from eating/drinking locally?" +"I'm working at my first programming job. My boss is a very smart software engineer, and I feel +like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer. +What can I do to impress him? +Thank you." +"Can I pass variables to a GNU Makefile as command line arguments? In other words, I want to pass some arguments which will eventually become variables in the Makefile." +"I have noticed that some games quote the requirement for ""pixel shader 3.0 or better"". +What is a pixel shader and is it some software requirements or hardware requirements?" +Red light facing forwards? It was nighttime in Manhattan. Isn't more always better when it comes to being seen? +"If water is not a good conductor, why are we advised to avoid water near electricity (no wet hands near circuits etc.)?" +"What is the difference between cohesion and coupling? +How can coupling and cohesion lead to either good or poor software design? +What are some examples that outline the difference between the two, and their impact on overall code quality?" +Can Romex (NM-B) cable be run through conduit? +"Let's say I have a function which takes an ```std::function```: +```void callFunction(std::function x) +{ + x(); +} +``` +Should I pass ```x``` by const-reference instead?: +```void callFunction(const std::function& x) +{ + x(); +} +``` +Does the answer to this question change depending on what the function does with it? For example if it is a class member function or constructor which stores or initializes the ```std::function``` into a member variable." +"I have an Eloquent model which has a related model: +```public function option() { + return $this->hasOne('RepairOption', 'repair_item_id'); +} +public function setOptionArrayAttribute($values) +{ + $this->option->update($values); +} +``` +When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not. +So I need to check if the related model exists, to either update it, or create it, respectively: +```$model = RepairItem::find($id); +if (Input::has('option')) { + if () { + $option = new RepairOption(Input::get('option')); + $option->repairItem()->associate($model); + $option->save(); + $model->fill(Input::except('option'); + } else { + $model->update(Input::all()); + } +}; +``` +Where `````` is the code I am looking for." +"NASA is hiring a new 'planetary protection officer' to defend Earth from alien matter, and the pay is a six-figure salary: as much as $187,000 a year. +When we are not sure whether aliens exist, why are we still hiring staff for protecting Earth? I do understand we have to take precautions. But when we don't have any proof why spend $187,000 a year? +Source: Nasa [sic] hiring new 'planetary protection officer' to defend Earth from alien matter - Times of India, Aug 3, 2017" +"Traditional advice for making megadungeons in older versions of D&D is in addition to any rooms with Monsters, Treasure, Traps, or ""Tricks"", there should also be at least 50 to 60 percent ""Empty"" rooms, which contain nothing overtly threatening or valuable. Now, there's several arguments for including these empty rooms that I buy, so I'm not going to accept any answer which primarily says, ""Don't include empty rooms"". The main issue I run into with empty rooms, however, is that they're boring in the way that I've been including them. They don't do their job of increasing tension, and the set dressing included around them hasn't been sufficiently interesting to my players either. My question is this: How can I make empty rooms interesting, by increasing tension or simply being interesting in and of themselves?" +"Laravel - Eloquent ""Has"", ""With"", ""WhereHas"" - What do they mean? explain in the context of an example" +What are some of the advantages of using one over the other? +"What factors determine the maximum altitude for a plane? +Is it limited by wing design, engine thrust, and so on? +Is there a formula by which one can calculate the maximum altitude a plane can reach?" +"Why did the Typescript folks create the ```infer``` keyword? +According to the documents, this is an example of how you would use it: +```type ReturnType = T extends (...args: any[]) => infer R ? R : any; +``` +I don't understand why this is needed. Why can't it just be: +```type ReturnType = T extends (...args: any[]) => R ? R : any; +``` +Why doesn't this work? Why is the ```infer``` keyword necessary ?" +Which is more widely supported: ```window.onload``` or ```document.onload```? +"I was surprised to learn that Puerto Ricans, despite living in a US territory, were not entitled to vote in the presidential elections. +I was even more surprised to learn that US citizens are allowed to vote for president from anywhere in the world - EXCEPT if they happen to live in Puerto Rico. +What is the legal/political rationale behind this? What is it about Puerto Rico that magically removes one's right to vote? Has anyone ever challenged this?" +"Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting. +Will the Note increase my lifespan? In other words, will I still be alive by then? " +"I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ... +Who will take control of the creature at the end? This is taking into consideration that my aura spell was cast 5 turns ago. Meaning my aura spell is NOT on the stack." +"I've found that some people call JavaScript a ""dynamically, weakly typed"" language, but some even say ""untyped""? Which is it really?" +"I was fixing my laptop, and as you may know, laptops have a lot of small screws to take out when you are fixing it. One of the screws fell into the floor (the floor has carpet on it), and I was unable to follow the screw with my sight. If I don't follow the screw with my sight when it falls, there is a high chance that I will not see that screw again. +My question is: what kind of method, tool or hack can I use to find small screws that falls into the floor? +I have tried using the tool with a magnet on the tip, that mechanics use to grab wrenches that falls in inaccessible areas, but had no luck finding the screw." +"What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives? +I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such.... +Thanks" +"What is the purpose of the single underscore ""_"" variable in Python? What is the meaning of ```_``` after ```for``` in this code? +```if tbh.bag: + n = 0 + for _ in tbh.bag.atom_set(): + n += 1 +```" +"What is the difference between doing: +```ptr = malloc (MAXELEMS * sizeof(char *)); +``` +or: +```ptr = calloc (MAXELEMS, sizeof(char*)); +``` +When is it a good idea to use calloc over malloc or vice versa?" +Why would I want to use Kotlin's coroutines? It seems that the RxKotlin library is much more versatile. Kotlin's coroutines look significantly less powerful and more cumbersome to use in comparison. I base my opinion on coroutines on this design talk by Andrey Breslav (JetBrains) Slideshow from the talk is accessible here. +"How do I get a ```PriorityQueue``` to sort on what I want it to sort on? +Also, is there a difference between the ```offer``` and ```add``` methods?" +"I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this: + +We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. + +I'm looking for something more in depth, such as end all Controllers with Controller and their tests with ControllerTest, etc. +What is a good set of naming conventions to use when developing on the Force.com platofrm? It would be preferable if the answer has something that handles custom objects, classes, visualforce pages, and components and not just Apex classes." +"When learning some basic French, I was somewhat surprised to learn that phrases of the form ""I have found the cat"" generally translate almost word-for-word from English (J'ai trouvé le chat). To me, it's not immediately obvious that possession (""I have""/""J'ai"") has a correspondence with past tense, although if I think about it a little more I suppose I can kind of see how it makes sense. +This makes me wonder: Is this a common pattern in other languages? Especially ones not closely related to English." +"I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?" +How to send HTML-formatted email in C#? +"I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized? +```Map integers; +integers.values().stream().mapToInt(i -> i).sum(); +```" +"I am beginner of LaTeX. From many examples I found, I notice that it's very common to use command ```\leavevmode```. I can't find any information about this command. Could anyone tell me what's the function of it and how to use it?" +"In Python specifically, how do variables get shared between threads? +Although I have used ```threading.Thread``` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? +I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. +Thanks in advance!" +"I grew up in a country where we were not allowed to leave/travel to an other country even when we were able to do so – we had the resources and dual nationality. +After two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries? +Could it be that a dictator is usually interested in looting the country he rules, and having a smaller population means more natural resources for him and fewer protesters?" +Why can't we kill ourselves by holding our breath? +"Sometimes while driving in the traffic, I come across a car or two which would be dripping water-like drops from its exhaust steadily in 4-5 second intervals. I tried to ask a couple of people at the local workshops; they say, and I quote, "The car is giving an amazing mileage". +And I am like, what does that water dripping mean even then? Why does the water drip? What is the source of it? And what does it signify?" +Why can't MX records point to an IP address? +"Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted? +I understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column?" +"I did my training around the Seattle area, and was told that landing at SeaTac Airport (the region's major International/Commercial airport), while not strictly forbidden, was definitely frowned upon because it can slow down and interfere with the big planes on schedules. To discourage GA aircraft from using the big airport, they have a variety of landing fees, ramp fees, and prior-approval requirements. +But later, I moved near MCI, and was told that landing at the big airport was no big deal. That they're actually happy to have little planes there. +If you fly small GA planes, do you land at the major airports in your area? +What advanced preparations can you make to minimize your impact on the ""big boys"", and remain a good airspace citizen?" +"I need a way to compare multiple strings to a test string and return the string that closely resembles it: +```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW +CHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN +CHOICE B : THE RED COW JUMPED OVER THE RED COW +CHOICE C : THE RED FOX JUMPED OVER THE BROWN COW +``` +(If I did this correctly) The closest string to the ""TEST STRING"" should be ""CHOICE C"". What is the easiest way to do this? +I plan on implementing this into multiple languages including VB.net, Lua, and JavaScript. At this point, pseudo code is acceptable. If you can provide an example for a specific language, this is appreciated too!" +"Given the following code: +```var arr = [1,2,3,4,5]; +var results: number[] = await arr.map(async (item): Promise => { + await callAsynchronousOperation(item); + return item + 1; + }); +``` +which produces the following error: + + TS2322: Type 'Promise[]' is not assignable to type 'number[]'. + Type 'Promise is not assignable to type 'number'. + +How can I fix it? How can I make ```async await``` and ```Array.map``` work together?" +Why don't helicopters use reaction wheels to counter the main rotor? +"When configuring cron to run a command every other day using the ""Day of Month"" field, like so: +```1 22 */2 * * COMMAND +``` +it runs every time the day of month is odd: 1,3,5,7,9 and so on. +How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is problematic as every month has a different number of days in the month)?" +"Is there a way to have a private setter for a property in TypeScript? +```class Test +{ + private _prop: string; + public get prop() : string + { + return this._prop; + } + private set prop(val: string) + { + //can put breakpoints here + this._prop = val; + } +} +``` +Compiler complains that visibility for getter and setter don't match. I know I can just set the backing field, but but then I can't set breakpoints when the value is set. +I though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter. +Am I missing something here? There doesn't seem to be any reason to not allow private setters, the resulting JS doesn't enforce visibility anyway, and seems better that the current alternatives. +Am I missing something? If not is there a good reason for no private setters?" +"When learning vocabulary, especially with the use of SRS (Spaced Repetition System), it is interesting to use flashcards. A commonly encountered problem is how to formulate those for maximum efficiency. +How does learning vocabulary through sentences, thus giving context to the used words, compare to learning to recognize words alone? For example, the context may give away the meaning of the problematic vocabulary. Are there studies or expert opinions on one approach being preferable to the other at different stages of language learning? Or is it recommended that they be mixed for best results?" +"Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life? + +The backstory +From the end of January, I'm starting my studies in a suburb of Stockholm. I've decided to, if it turns out plausible, not rent an apartment, but live in a tent. (This is not out of frugality, but out of a will to try something new.) +I do have friends who I could visit once a week or so to prepare food and wash my clothes, so I think I can solve the practical problems, or at least those that I've come to think of. I'd camp in one of the forests, maybe 1 km from ""civilisation"". I'd have access to showers etc at university every day. +However: I don't want to freeze to death in my sleep! That's very important to me. I've read that the nights can get as cold as -20°C (-4°F). With the proper preparations, would this be a plausible way of living, at least for a month or so? +I do have camping experience, and have been hiking for three weeks, but only in summer." +"Why is the volt not identical to the full name Volta, unlike the other electrical units ohm, ampere, coulomb, tesla, weber and henry? Is there a historical explanation, was the volt introduced at a different time?" +"We can define cross products mathematically like if we take two vectors, we can find another vector with certain properties but why do we use it in physics, if we consider a hypothetical physical quantity like force which is equal to cross product of certain vectors? + + For example, the force exerted on a charge in motion in an uniform magnetic field. + +Why is it so? Why does that force have to be a cross product of two vectors? +Is it possible to come up with them when what we do is just observe the nature?" +"I have a web project in my solution file that is ""unavailable"" when I open the solution. When I right-click on the web project and reload the project, I get the following error: +``` +The Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be found. +``` +I have not manually set up virtual directories for this web application. +Per colleagues, Visual Studio should prompt me to create virtual directories but I am not getting prompted. +I installed VS2010 before installing IIS on my dev machine. +Here is my development machine setup: + +* Windows 7 Enterprise +* Service Pack 1 +* 64 bit OS +* Visual Studio 2010 Enterprise Service pack 1 +* IIS version 7.5 +" +Why is it hard to draw people running in animes? +"Malachi 4:5: + + I will send you the prophet Elijah. He will come before the day of the Lord arrives. It will be a great and terrifying day + +Jesus says in Matthew 11:14 + + ""and if you are willing to believe their message, John is Elijah, whose coming was predicted"" + +Jesus says in Mathew 17:12 + + But I tell you, Elijah has already come, and they did not recognize him, but have done to him everything they wished. In the same way the Son of Man is going to suffer at their hands.” + +It's pretty clear from the above verses that John was Elijah reincarnated. +Wouldn't the above verses imply that reincarnation is true? " +"I see hugely varied performance depending on how many newlines there are in the file I'm visiting. +Here's an example. I have two JSON files: +```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json +$ python -m json.tool pretty_printed.json +``` +These are two JSON files with the same content. ```one_line.json``` is 18MiB of JSON without any newlines. ```pretty_printed.json``` has newlines and whitespace added, making it 41MiB. +However, the bigger file split over many lines is much faster to open in Emacs, both in Javascript mode and Fundamental mode. +Why does Emacs have such poor performance with long lines, since it's actually fewer bytes? Is there anything I can do to improve performance without reformatting the data outside of Emacs?" +"Sooner or later we come across a task in our project, with which we are totally unfamiliar ('we' as in PM, but also possibly the staff assigned to do this particular task). +How can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume?" +"Why is Nazi-Germany commonly referred to as ""The Third Reich"" in English? Why is reich not translated when Dritten (""third"") is? +And what is the English synonym of reich? Realm? +Austria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish corresponding etymology related word) in their name and they all have English translations of their name." +"If we fold a paper and then apply pressure on the newly formed crease, it seems that the paper's surface gets a permanent deformation but what exactly has happened to the paper at a molecular scale?" +"In general, there are two types of syntax of defining functions - Something like C, C++, C#, or Java (```int functionName(char arg)```) vs the ML (and others) tradition of defining the return type after the function (and using something like a ```fun``` keyword to define a function - like ```fun functionName(char arg): int```). +One of the advantages (for the parser, at least) for a ```fun``` keyword is that it lets the parser be context-free (it doesn't have to guess if ```int``` defines a variable or if it defines a function). +When C was invented, computers had very little memory and speed (so little, that the reason C requires one to define all the variables in the beginning of the function was because it had to be a one-pass parser). Why didn't they choose the simple way out and use function defining keyword?" +"I am new to TeX, working on it for about 2 months. Have not yet figured out how to script the 'curvy L' for Lagrangian and/or for Laplace Transforms. +As of now I am using the 'L' - which is not good! :-( +Any help? +UPDATE The 2 best solutions are; +```\usepackage{ amssymb } +\mathcal{L} +``` +and +```\usepackage{ mathrsfs } +\mathscr{L} +``` +I got my answers at, http://detexify.kirelabs.org/classify.html " +"My son doesn't want to share anything with other kids, and if some kid even so much as touches his toy, he pushes the kid. He shouts and cries at the same time, and tries to express his anger by pushing and hitting the kid. I feel so embarrassed in front of other parents. +And when he is at home with me and doing something wrong, I try to stop him, he tries to repeat my words and shouts at me. He is copying the behavior of others, whether it's a good act or bad... +Please help me how to stop him from being a bully." +What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms? +Why don't Tour de France riders always ride their TT bikes? +"I remember when the Muslim holy book was the Koran when I was in middle school, but now it's the Quran. But it's always been Qatar and Iraq (but still Kuwait.) +Who decided that 'Q' was going to be represent that sound instead of 'K', and why?" +How do you add Boost libraries in CMakeLists.txt? +"Quando devo fazer essa gravação direto no banco? +Quais as situações? +Eu sei que posso gravar no banco o caminho da imagem." +"I need a regular expression that validates a number, but doesn't require a digit after the decimal. ie. ```123 123. 123.4 ``` would all be valid ```123.. ``` would be invalid" +"The year is 2109 C.E my friends and I were caught in a space disaster when the spacecraft we're in broke apart during a daring escape from a patrolling spacecraft. We stole an antique cellphone (from 1999, in good working condition) from a space museum but our escape was interrupted and fortunately we managed to get into the escape pod and didn't get caught up in the explosion. The only emergency transponder in the escape pod isn't working probably due to the destruction of the spacecraft. Given the technology of 1999, is it possible for us to sent out a distress signal to alert the leaving patrol spacecraft? +Note: the cellphone was the most innovative product of 1999 money can buy. +The escape pod is not a Faraday cage we're talking about the future and the patrol spacecraft don't necessary be on a lookout for distress signal; please use these clues to your advantage. +If there is absolutely no way to transmit any man-made signal out, please state a valid reason why it can't be done." +"Often I want to just point the camera to an object or a specific area in my scene to get an idea of how it'll look in the render. What's the most painless hassle-free way to do this in blender? +A quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result. +This question could probably be broken down into these two main questions: + +* How do I point a selected camera to the current 3d-cursor location in the scene? +* How do I point the selected camera to the currently selected object(s) in the scene? +" +"What are the general tactics of Krav Maga as opposed to Systema? +For instance, the tactics of Silat are to hurt the other person so badly they can't hurt back. Another example would be that the tactics of boxing would be to knock out the other person first using only punches. So, as far as I know, the goal of Systema and Krav Maga are both to do anything you can to defeat your attacker because they are serious about self defense. Does that mean that Krav Maga and Systema are strategical identical? Does Krav use strategies that Systema doesn't? Does Systema use any strategies that Krav doesn't? Is there a difference or do they generally work the same way?" +"I understand that unlocking the bootloader will wipe my Android phone, but have been looking around for why. Seems to be by design, but what is the reasoning for that design? Is it some security concern, some obscure technical reason, or just for lulz? I'm looking for something solid to chew on here, something more than because ""that's how it is""." +"The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip. Why did users add sound cards such as the Adlib or Sound Blaster. I remember voice output with programs like telephone answering programs. The sound was wimpy but I attributed most of the quality to speaker size. +What was lacking with the original PC sound chip? " +"According to the sources I have found, a lambda expression is essentially implemented by the compiler creating a class with overloaded function call operator and the referenced variables as members. This suggests that the size of lambda expressions varies, and given enough references variables that size can be arbitrarily large. +An ```std::function``` should have a fixed size, but it must be able to wrap any kind of callables, including any lambdas of the same kind. How is it implemented? If ```std::function``` internally uses a pointer to its target, then what happens, when the ```std::function``` instance is copied or moved? Are there any heap allocations involved?" +"So, I'm on vacation in Utah, and so I attended an LDS service. In the morning, I heard a reading from one of the Presidents of the church during the ""Quorum of the Elders,"" then went to Sunday School, and finally witnessed the Sacrement of the bread and water. (I guess it makes sense there was no wine, but it did make me go ""Huh!"") After that, there were testimonies from missionaries and some music - but nothing that struck me as a sermon. +Was I missing something, or was this an atypical service? I guess I was trying to understand what the ""pastor""s role in the service was supposed to be - or again, is it just that Mormons are even more Baptist than baptists? +If someone could explain how instruction and exhortation are primarily conferred in the LDS church Id appreciate it. " +"A partir de un String, ```""123-654321""```, lo que deseo es dividirlo en dos Strings: +```string1=123 +string2=654321 +```" +"What’s the difference between ```\n``` (newline) and ```\r``` (carriage return)? +In particular, are there any practical differences between ```\n``` and ```\r```? Are there places where one should be used instead of the other?" +Assume that I am a programmer and I have an NP-complete problem that I need to solve it. What methods are available to deal with NPC problems? Is there a survey or something similar on this topic? +Why are the lights inside commercial airplanes turned off during take off and landing? +"The default behaviour of ```LIKE``` and the other comparison operators, ```=``` etc is case-sensitive. +Is it possible make them case-insensitive?" +"I have a new SPA with a stateless authentication model using JWT. I am often asked to refer OAuth for authentication flows like asking me to send 'Bearer tokens' for every request instead of a simple token header but I do think that OAuth is a lot more complex than a simple JWT based authentication. What are the main differences, should I make the JWT authentication behave like OAuth? +I am also using the JWT as my XSRF-TOKEN to prevent XSRF but I am being asked to keep them separate? Should I keep them separate? Any help here will be appreciated and might lead to a set of guidelines for the community." +"Gostaria de saber se existe alguma forma simples de realizar um upload de arquivos via AJAX + JSON. +Se houver, qual seria?" +Did the ancients or other pre-industrial civilisations engage in unsustainable practices? +"When reading my Bible, I've noticed Joesph's name listed in both the Old and New Testaments; is it the same person or is there more than one Joseph in the Bible?" +"Para que serve o ""with"" no Python?" +"The question bothers me since February 2022. Why (legally) are Russian combatants in Ukraine considered soldiers (thus POWs when captured) rather than terrorists? + +* There is no formal declaration of war. +* They are members an organization (Russian military) that commits acts of terrors to civilian population in clear violation of international law of war. Moreover, they either directly or indirectly contribute to the mentioned acts of terror. +* Their state (Russia) explicitly claims that there is no war (thus unilaterally waiving the protection of law of war for Russian forces). + +Why is that particular group of armed people acting in clear violation of Ukrainian law treated as "soldiers in war" rather than state-sponsored criminals? +Note, that waiving the protection of law of war does not waive the protection of Ukrainian law (right to due process etc.)." +What are the major branches of philosophy? +Are there any advantages while backpacking to hike during the night and sleep during the day? +"I have been cautioned against blending: + +* Traditional fantasy elements + +Such as magic systems and exotic, less plausible creatures (on a scientific level - magic tends to explain away these beasts) + +* Traditional sci-fi elements + +Such as advanced technology and civilizations amidst the stars. +I have taken it upon myself to harmonize the two in my current worldbuilding project. I know I cannot be the first. I love the creativity found in both, and it is going well so far. I have been exploring the potential for humanity with both tools at their disposal. (Magic and science, essentially) +Why do people advise to stick to one or the other?" +Why are prions in animal diets not destroyed by the digestive system? +How slicing in Python works? Please include references where appropriate. +"I am writing a story where a species undergoes devolution. Is there any scientific or plausible way to do this? The process can be instantaneous or may take ages, I do not mind which as I need to weigh my options at this stage. +To be clear, the devolution I am thinking of is like taking a human being then devolving him/her to the primate stage, so lets say about as far back as Orrorin tugenensis or Paranthropus where they are in the midst of evolving from primates to Homo erectus. Please note I used human beings as an example to give context but the species undergoing devolution may not necessarily be human. +Based on the answers, ""devolution"" does not exist so had the word in quotes to reflect this. " +"I've used GEDCOM to transfer data between desktop software and websites, but it all seems a bit old hat. Is there anything better that will mangle* my data less. +* For example, GEDCOM can lose some data where the two ends of the system understand a concept which GEDCOM does not have a field for." +Is it ever possible that ```(a== 1 && a ==2 && a==3)``` could evaluate to true in JavaScript? +"Gostaria de saber qual é a real diferença entre o ```String``` (s maiúsculo) e o ```string``` (s minúsculo). +Aparentemente os dois têm os mesmos objetivos, porém qual é ""melhor"" para ser utilizado?" +"I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?" +"Assume an environment with a puppet-managed cluster of different servers - various hardware, software, operating systems, virtual/dedicated, etc. +Would you choose meaningful hostnames (mysqlmaster01..99, mysqlslave001..999, vpnprimary, vpnbackup, etc.) or would you prefer meaningless hostnames such as characters from a book or movie? +The problem I see with meaningful hostnames is that names usually represent a single service and if a server has more than one purpose it gets really messy (especially if server roles change often). +Isn't mapping a service name to an IP address and maintaining that mapping what DNS is supposed to do? +What are the advantages and drawbacks of both approaches and what actual problems have you had to tackle with the approach you chose?" +"Best way to start investing, for a young person just starting their career?" +"Quantum state teleportation is the quantum information protocol where a qubit is transferred between two parties using an initial shared entangled state, Bell measurement, classical communication and local rotation. Apparently, there is also something called quantum gate teleportation. +What is quantum gate teleportation and what is it used for? +I am particularly interested in possible applications in simulating quantum circuits." +What does it mean for an album to be remastered? +What's the best way to iterate over the items in a ```HashMap```? +Why did people start using CO2 (instead of e.g. oxygen) for carbonated drinks? +"Say I have a file ```/templates/apple``` and I want to + +* put it in two different places and then +* remove the original. + +So, ```/templates/apple``` will be copied to ```/templates/used``` AND ```/templates/inuse``` +and then after that I’d like to remove the original. +Is ```cp``` the best way to do this, followed by ```rm```? Or is there a better way? +I want to do it all in one line so I’m thinking it would look something like: +```cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple +``` +Is this the correct syntax?" +When are Decision Diagrams the right way to model and solve a problem? +"Essentially, I have a protagonist who I set up as a 'main' good guy in one of my series. However, in my final series, I intend to make him turn to the dark side and oppose my other protagonists (from my other series). It's clear in his series that the protagonist-turned-antagonist is very devious, and he has had hostile intentions previously towards the protagonists of the other series. +My question: +Should I avoid turning my protagonist into an antagonist? Are there any foreseeable problems with this? Will this be a problem for readers? Any tips or tricks to handle this?" +"I'd never heard of anycast until a few seconds ago when I read ""What are some cool or useful server/networking tricks?"". +The wikipedia ""Anycast"" article on it is quite formal and doesn't really evoke a mental picture of how it would be used. +Can someone explain in a few informal sentences what ""anycast"" is, how you configure it (just in a general sense), and what its benefits are (what does it make easier)?" +"$A$ and $B$ are $n \times n$ matrices and $v$ is a vector with $n$ elements. $Av$ has $\approx 2n^2$ flops and $A+B$ has $n^2$ flops. Following this logic, $(A+B)v$ should be faster than $Av+Bv$. +Yet, when I run the following code in matlab +```A = rand(2000,2000); +B = rand(2000,2000); +v = rand(2000,1); +tic +D=zeros(size(A)); +D = A; +for i =1:100 + D = A + B; + (D)*v; +end +toc +tic +for i =1:100 + (A*v+B*v); +end +toc +``` +The opposite is true. Av+Bv is over twice as fast. Any explanations?" +"I came across a piece of code ```void *p = &&abc;```. What is the significance of ```&&``` here? +I know about rvalue references but I think ```&&``` used in this context is different. What does ```&&``` indicate in ```void *p = &&abc;``` ?" +"When I execute ""```python```"" from the terminal with no arguments it brings up the Python interactive shell. +When I execute ""```cat | python```"" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe. +How would I do a similar detection in C or C++ or Qt?" +"""The video of Pythom Space's first rocket test has raised a few eyebrows + +The video prompted hundreds of replies on Twitter, including some from rather horrified rocket scientists. "We knew better as untrained college students," said Jordan Noone, the co-founder of Relativity Space. + +Pythom “Micro jump” +What exactly did they get wrong with this test? +Note: The Pythom Space CEO did eventually respond to the original Ars Technica story linked above. It does offer their own take on some of the issues raised there and elsewhere (including some of the points in the answer below)""" +When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()? +"When encoding a logic into a proof assistant such as Coq or Isabelle, a choice needs to be made between using a shallow and a deep embedding. In a shallow embedding logical formulas are written directly in the logic of the theorem prover, whereas in a deep embedding logical formulas are represented as a datatype. + +* What are the advantages and +limitations of the various +approaches? +* Are there any guidelines available for determining which to use? +* Is it possible to switch between the two representations in any systematic fashion? + +As motivation, I would like to encode various security related logics into Coq and am wondering what the pros and cons of the different approaches are." +Prove that the union of countably many countable sets is countable. +"Você encontra na internet a afirmação que Singletons são ruins. Isto é verdade? Por quê? +O problema seria generalizado para quaisquer objetos com instância única? Ou para qualquer coisa que tenha estado global? +Se é tão ruim, pra que foi inventado? Ou seja, que problema ele queria resolver? +Quais os problemas que terei se usá-lo? +Existe alternativa viável?" +"The construction of Solomon's temple includes a piece of furnishing described in 1 Kings 7:23 (ESV): + + Then he made the sea of cast metal. It was round, ten cubits from brim to brim, and five cubits high, and a line of thirty cubits measured its circumference. + +So if the ```diameter = 10``` cubits and the ```circumference = 30``` cubits, then ```π = 3``` by the equation ```C = π * D```. +Of course, such an object does not exist since ```π = 3.14159...``` yet clearly the sea was constructed at some point. So how do we resolve this contradiction?" +"With PHP 7.2, ```each``` is deprecated. The documentation says: + +Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged. + +How can I update my code to avoid using it? Here are some examples: + +* +```$ar = $o->me; +reset($ar); +list($typ, $val) = each($ar); +``` + +* +```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); +$expected = each($out); +``` + +* +```for(reset($broken);$kv = each($broken);) {...} +``` + +* +```list(, $this->result) = each($this->cache_data); +``` + +* +```// iterating to the end of an array or a limit > the length of the array +$i = 0; +reset($array); +while( (list($id, $item) = each($array)) || $i < 30 ) { + // code + $i++; +} +``` + + +When I execute the code on PHP 7.2 I receive the following error: + +Deprecated: The each() function is deprecated. This message will be suppressed on further calls" +Can someone please give an explanation of different egg preparations? +"I'm running a relatively small one-man business in the software sector. I just started and am trying to create a larger portfolio. For that, I offer some friends free services. +I found a few reasons to send these clients €0,- invoices, mostly similar to the reasons to send 100% discount invoices to charity funds that I gave here: + +* Clarity about what has to be done and when +* No transfers (as I would have with a 0% discount bill and returning the money as a gift) + +And also: + +* With an invoice I have more distinguishable clients which makes that I have more chance on getting a better certificate from the state (doesn't matter how it exactly works, this is an advantage) + +Suppose that these clients won't have a problem with the €0,- invoices, could there be any reason for me to not send them? +I ask this, because I've never seen people sending invoices like this, and I can only see advantages." +"In regards to Error handling in PHP -- As far I know there are 3 styles: + +* ```die()```or ```exit()``` style: +```$con = mysql_connect(""localhost"",""root"",""password""); +if (!$con) { + die('Could not connect: ' . mysql_error()); +} +``` +* ```throw Exception``` style: +``` if (!function_exists('curl_init')) { + throw new Exception('need the CURL PHP extension. + Recomplie PHP with curl'); + } +``` +* ```trigger_error()``` style: +```if(!is_array($config) && isset($config)) { + trigger_error('Error: config is not an array or is not set', E_USER_ERROR); + } +``` + +Now, in the PHP manual all three methods are used. + +* What I want to know is which style should I prefer & why? +* Are these 3 drop in replacements of each other & therefore can be used interchangeably? + +Is it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?" +How do I change the author and committer name/email for multiple commits? +This summer I will be taking a rather inherently dangerous multi-day hike by myself. I was considering buying a flare gun since I will be out of cellular range unless there is something more modern and equally reliable. Any suggestions? +" + Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances. + +I don't understand the part marked in bold. +Congress shall make no law prohibiting the free exercise of religion. So congress should not make a law which prohibits the freedom of religion. I get it. +But Congress shall make a law which respects an establishment of religion. Doesn't ""Congress shall make no law respecting an establishment of religion"" mean congress should not make a law that respects religion because there's ""no"" in it?? " +Why are people unwilling to share information about their salary? +"In D&D, how many attacks can a fighter with two-weapon fighting make at 5th level?" +"Consider the following code: +```avgDists = np.array([1, 8, 6, 9, 4]) +ids = avgDists.argsort()[:n] +``` +This gives me indices of the ```n``` smallest elements. Is it possible to use this same ```argsort``` in descending order to get the indices of ```n``` highest elements?" +Can a woman give birth to twins with different fathers? +Relationship between SVD and PCA. How to use SVD to perform PCA? +"What is the English term for when someone thinks they are doing something nice for you but it ends up making things worse. EX: Someone buys you an elephant -- nice gesture and cool! But now you have to take care of it, and it becomes a burden on you." +Did Hillary Clinton propose to punish flag burners in 2005? +"There are several questions here about the definition of depth of field, about focal length, and about subject distance. And of course there's the basic how does aperture affect my photographs. And plenty of how do I get super-shallow d.o.f questions. There's related questions like this one. But there's no be-all-end-all question asking: +What exactly determines depth of field in a photograph? +Is it just a property of the lens? Can lenses be designed to give more depth of field for the same aperture and focal length? Does it change with camera sensor size? Does it change with print size? How do those last two relate?" +Why did the NES not allow rotated sprites? +"I want to merge two dictionaries into a new dictionary. +``` +x = {'a': 1, 'b': 2} +y = {'b': 3, 'c': 4} +z = merge(x, y) + +>>> z +{'a': 1, 'b': 3, 'c': 4} +```" +"There are many ""standards"" for the JSON content type: +application/json +application/x-javascript +text/javascript +text/x-javascript +text/x-json +Which one do I use, and where? I assume security and browser support issues are a factor." +What's the goal of Minecraft and what can users achieve in this world? +"If I have sampled a signal using proper sampling methods (Nyquist, filtering, etc) how do I relate the length of my FFT to the resulting frequency resolution I can obtain? +Like if I have a 2,000 Hz and 1,999 Hz sine wave, how would I determine the length of FFT needed to accurately tell the difference between those two waves?" +"I wanted to produce a 1 GB random file, so I used following command. +```dd if=/dev/urandom of=output bs=1G count=1 +``` +But instead every time I launch this command I get a 32 MB file: +```$ dd if=/dev/urandom of=output bs=1G count=1 +0+1 records in +0+1 records out +33554431 bytes (34 MB, 32 MiB) copied, 0,288321 s, 116 MB/s +``` +What is wrong?" +The treads on my road bike's 28C tires are almost completely gone—they only persist along the shoulders of the tire. Do the treads matter? What is a good indicator of when the tire as a whole needs to be replaced? +"Is there a way to create an index on a property/column using fluent configuration, instead of using the new ```IndexAttribute``` ?" +"Both races have the same limits on their strength, and athletics, but it's hard to imagine why. A Goliath could feasibly lift and throw a gnome, yet the Gnome, following rules as written, can pin down a Goliath, fairly easily, if statted correctly. +Is there an in-universe explanation as to why such dramatically different sized creatures can wrestle on an even playing field? +How might a DM explain a scenario in which a gnome beats a goliath in any kind of test of strength?" +"So I'm pretty far into writing my dystopian novel and I was reading over what I had. Something that helps me when I first start a novel is to get a clear picture of my characters in my head and put a face to a name, so I usually sculpt a personality and find a Google image of someone who I think matches that, and I put all of those into documents for my personal reference. I looked over my main five characters--Analise, Poet, Shove, Star, and Nova--and then suddenly something jumped out at me. Analise is Hispanic, Shove is Japanese, and Poet, Star, and Nova are all black. +I had forgotten about their races because it wasn't important to me and I had not noticed while I was writing, because the story isn't about their racial backgrounds. But is it, I don't know, somehow alienating or offensive to white readers that the characters aren't white, and that no main characters are white? " +"When I do ```\footnote{}``` for a value in a table, the footnote doesn't show up. How do I get it to show up? Also, is it possible to get it to show up at the bottom of the table rather than the bottom of the page?" +Why is kVA not the same as kW? +"Elon Musk and his partner want to name their child X Æ A-12. +Is that name allowed in California, US?" +"In this Creation magazine reprint of a 1994 article titled Exploding stars point to a young universe, Young-Earth Creationist, Jonathan Sarfati argues that the scarcity of Supernova remnants (SNRs) in the sky suggests the Milky Way galaxy is less than billions of years old. + +On average, a galaxy like our own, the Milky Way, should produce one supernova every 25 years. +[...] +As can be readily seen above, a young universe model fits the data of the low number of observed SNRs. If the universe was really billions of years old, there are 7000 missing SNRs in our galaxy. + +Does astronomy predict a Milky Way supernova every 25 years? Are there missing SNRs that undermine these predictions?" +Why is there so much technical detail of whaling included in Moby-Dick? +Why are we building larger land-based telescopes instead of launching larger ones into space? +Why can we see the dust particles in a narrow beam of light (and not in an all lighted area)? +"I can not initialize a List as in the following code: +```List supplierNames = new List(); +supplierNames.add(""sup1""); +supplierNames.add(""sup2""); +supplierNames.add(""sup3""); +System.out.println(supplierNames.get(1)); +``` +I face the following error: + + Cannot instantiate the type ```List``` + +How can I instantiate ```List```?" +What is the difference between ```warnings.warn()``` and ```logging.warn()``` in terms of what they do and how they should be used? +"In Greek mythology, the words ""Titan"" and ""God"" seem to be used interchangeably. For example, Zeus is a God, but Cronus (his father) was a Titan. So what is the difference between a Titan and a God in Greek mythology? " +How do weather models work? +"I am currently trying to decipher Mazur's Eisenstein ideal paper (not a comment about his clarity, rather about my current abilities). One of the reasons I am doing that is that many people told me that the paper was somehow revolutionary and introduced a new method into number theory. +Could you explain exactly what subsequent developments did the paper bring, what ideas in the paper were considered more-or-less original (at the time it was published), and exactly what difficulties did these ideas resolve that people failed to resolve before the paper was published (if any)?" +Tracing XML request/responses with JAX-WS +"In Vim, how do I insert characters at the beginning of each line in a selection? +For instance, I want to comment out a block of code by prepending ```//``` at the beginning of each line assuming my language's comment system doesn't allow block commenting like ```/* */```. How would I do this?" +Why doesn't the nuclear fusion in a star make it explode? +Does hot water freeze faster than cold water? +"O que é Reflection. Por que é útil? +* É recomendável usar em projetos? +* Como usar? +* Em quais situações Reflection pode ser usado?" +What is the difference between minimum and infimum? +"I had a Nespresso Vertuo Next machine. It stopped working properly and during the troubleshooting video call, the Nespresso support agent said that the machines should not be connected to a GFCI outlet because they can potentially damage the machine. As part of our home inspection when we purchased the house, it was recommended to install such outlets anywhere that water is common, including the kitchen. As such, all the outlets in our kitchen are GFCI outlets. +This call with Nespresso was the first time I'd ever seen someone claim that GFCI outlets can potentially damage coffee machines. +Can they damage Nespresso machines? If so, can they damage other coffee machines (I also have a Baratza grinder and a Bonavita drip machine I usually hook into the same outlet)? They sent us a replacement and now I am questioning where to put it." +"I have extremely bad posture, what can I do?" +"How to add margin top to ```class=""row""``` elements using twitter bootstrap framework?" +"In FTL: Faster Than Light, what triggers crew experience increases?" +"In Adobe Photoshop I am able to select multiple layers at once with Shift+Click. +How can I do that in GIMP?" +"In the python built-in open function, what is the exact difference between the modes ```w```, ```a```, ```w+```, ```a+```, and ```r+```? +In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for ""appending"", ""writing"", and ""updating"" specifically, but does not define what these terms mean." +How can democracy not be the rule of the poor? +"How can I write colored text to the Windows console with C++? That is, how can I write different text with different colors?" +"What's the best way to create a temporary file in Android? +Can File.createTempFile be used? The documentation is very vague about it. +In particular, it's not clear when temporary files created with ```File.createTempFile``` are deleted, if ever." +"I have javascript function like this: +```function myFunction(number) { + var x=number; + ... + ... more initializations + //here need to wait until flag==true + while(flag==false) + {} + ... + ... do something +} +``` +The problem is that the javascript is stuck in the while and stuck my program. so my question is how can I wait in the middle of the function until flag is true without ""busy-wait""?" +"According to this famous blog post, the effective transcript length is: +$\tilde{l}_i = l_i - \mu$ +where $l_i$ is the length of transcript and $\mu$ is the average fragment length. However, typically fragment length is about 300bp. What if when the transcript $l_i$ is smaller than 300? How do you compute the effective length in this case? +A related question: when computing the FPKM of a gene, how to choose a transcript? Do we choose a ""canonical"" transcript (how?) or combine the signals from all transcripts to a gene-level FPKM?" +What is the significance of 1/1/1753 in SQL Server? +"I saw this video where someone says that electromagnetic wave is a chain reaction of electric and magnetic fields creating each other so the chain of wave moves forward. +I wonder where the photon is in this explanation. What is the relation between electromagnetic wave and photon?" +"In The Light Fantastic, after talking about the dimensions of the Pyramid of Tsort, it says + + All in all, it was a lot of effort to go through just to sharpen a razor. + +What's the joke here?" +"After a ```git pull origin master```, I get the following message: + +warning: Pulling without specifying how to reconcile divergent branches is +discouraged. You can squelch this message by running one of the following +commands sometime before your next pull: + git config pull.rebase false # merge (the default strategy) + git config pull.rebase true # rebase + git config pull.ff only # fast-forward only +You can replace "git config" with "git config --global" to set a default +preference for all repositories. You can also pass --rebase, --no-rebase, +or --ff-only on the command line to override the configured default per +invocation. +remote: Enumerating objects: 4, done. +remote: Counting objects: 100% (4/4), done. +remote: Compressing objects: 100% (4/4), done. +remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 +Unpacking objects: 100% (4/4), 51.49 KiB | 850.00 KiB/s, done. + +The pull seems successful, but I am unsure. +What can I do to fix this?" +"In India, we eat rice using our fingers. Generally in the West, a fork or spoon is used. I have tried eating rice with spoon but I don't feel satisfied with it. +We eat dry rice but we mix curry and vegetables with it and then eat it with our hands. +Is there a way to eat rice with your hands in front of Westerners such that it doesn't appear to be disgusting to them? By disgusting I mean that they shouldn't feel like vomiting or looking away to avoid me. Even though in India we eat with our fingers, many people eat such that their whole palm is covered with food. That indeed looks disgusting. +I cannot avoid hurting them by following different etiquette, but I certainly want to maintain a degree of cleanliness." +"The typical argument goes like this: + + Without net neutrality, cable companies could censor websites, favoring their own business partners. + +Typically, proponents of legislation point to some perceived injustice, and argue that new laws are needed to address it. But the very use of the subjunctive in the quotation (could censor), suggests that this might be considered by its opponents as a solution in search of a problem. If so, why haven't they used that rhetorical tactic? Conversely, if such incidents have occurred, why don't the neutrality supporters cite them?" +Does having a longer Ethernet cable slow your connection? +Border around formatted text in Inkscape +"I learned about the equilibrium constant. Now, I've seen that the equilibrium constant of burning is extremely small $(K \ll 1)$. here, I have a question. you see, $K$ is still NOT 0, which means that the forward reactions happen at least a tiny bit. Then, shouldn't we see some parts of anything burning at least a little bit?" +"The name ""Bleach"" seems to be having no relevance to the plot unlike most other series. Was it just chosen at Kubo-sensei's whim or does it have some significance? Maybe some cultural significance associated with shinigami, etc. that I am now aware of?" +Why don't rally cars have airbags? +Was the Millennium Falcon a one-off or was it mass produced? +"Usually when I see lists of things to do to be more energy efficient, they require one to own their own home. What can I do to be more energy efficient in an apartment? +For example, I can't install solar panels, I can't upgrade/change my appliances, I can't install better insulation or windows, and I can't install a programmable thermostat. +Pretty much the only thing I can do (and have done) is switch all of my bulbs to CFLs. I also keep all of my electronics on power strips which I turn off when I leave my apartment and when I'm sleeping." +Is there any way to exit ```less``` without clearing the screen? +How can I do 'insert if not exists' in MySQL? +What does ```class``` do in Ruby? +"""I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value. +I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?""" +How do I initialize a TypeScript Object with a JSON-Object? +Why is digital photography so expensive? +"If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: +```$unsafe_variable = $_POST['user_input']; +mysql_query(""INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')""); +``` +That's because the user can input something like ```value'); DROP TABLE table;--```, and the query becomes: +```INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') +``` +What can be done to prevent this from happening?" +"I want to be able to output the current loop iteration to my template. +According to the docs, there is a ```loop.counter``` variable that I am trying to use: +``` +{% for user in userlist %} + * + {{ user }} {{loop.counter}} + + {% if loop.counter == 1 %} + This is the First user + {% endif %} +{% endfor %} + +``` +But is being outputed to my template. What is the correct syntax?" +Are the players on the same team as the DM? +C++ vs. The Arduino Language? +"How can I adapt Ubuntu to a high resolution display? +I have a display with 3200x1600px on only 11'' and everything looks really tiny." +"Say I want to make a file: +```filename = "/foo/bar/baz.txt" +with open(filename, "w") as f: + f.write("FOOBAR") +``` +This gives an ```IOError```, since ```/foo/bar``` does not exist. +What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call ```os.path.exists``` and ```os.mkdir``` on every single one (i.e., /foo, then /foo/bar)?" +"Assume that Jane Doe has published a paper in 2010 where she has developed a model or a theorem or a similar result, let’s say, that it relates to growth. +Now assume that Jane Doe is writing another paper in 2015, where she refers to the model/theorem from her paper in 2010. +Is it acceptable for Jane to write something like the following? + + Doe’s growth model (2010), implies that ... + Doe’s growth theorem (2010) implies that ... + The Doe growth model (2010) implies ... +" +"I've been with my current employer for about a year now. Due to the way the company is setup, I'm the only one with knowledge on a process that is quite important to the company. The company is going through some restructuring, and has been letting people go. As the newest guy in my department, I'm obviously concerned. +My question though, is if I am let go, am I obligated to spend my time teaching someone else this process that only I know about?" +"Bash test: what does ""=~"" do?" +"If I have a Bash script like: +```#!/bin/bash +f() { + # echo function name, ""f"" in this case +} +``` +Is there any way to do this? This could be used in help messages such as +```printf ""Usage: %s: blah blah blah \n"" $(basename $0) >&2; +``` +Only in this case what I wanted is not ```$0```, which is the file name of the script." +"I know that the public practice of any religion other than Wahabbi Islam is strictly forbidden in Saudi Arabia, and there would be no places of worship. I also know that the morality police raided a a hotel several years ago where Mass was being celebrated, and arrested the priest and the acolytes. +But I am also told that many expats from countries with large Catholic communities such as the Philippines, India, and Sri Lanka do gather in private homes for worship. Is this officially tolerated, or would I endanger the hosts or other participants by asking about them?" +"Is there a way to achieve protections similar to ""Copyleft"" under the patent system?" +"In monopoly, can an opponent put a property up for auction at a higher price than I have in cash?" +What is the purpose of having a countdown during a rocket launch? +"How does one attack a two-time pad (i.e. one time pad with key reuse)? +I am new to cryptography and my problem is with two time pad attacks on OTP. +The problem I had in my course was that I have 10 ciphertexts encrypted with the same key $K$. I am then given another ciphertext that I should decrypt. +I know that XOR-ing two ciphers gives me the XOR of their original messages. +My question is what is the correct thing to do after that? +I tried to take 3 ciphertexts $C_1, C_2$ and $C_3$. +Then get $S_1 = C_1 \oplus C_2 \oplus $```' '```, also get $S_2 = C_1 \oplus C_3 \oplus$ ```' '```. +After that I compared all corresponding characters in $S_1$ and $S_2$, +and if $S_1[i] = S_2[i]$ then I calculate $S_1[i] \oplus C_2[i]$ to get $K[i]$. +I tried this on paper before coding and it worked, but I might be missing something. +Is this the right approach? Why does it work?" +"I have a small home automation lab (that I keep saying I'll expand, but haven't). In this setup, I have a control system to control lights (utilizing the x10 protocol), blinds, a Nest thermostat and two web cams. +With the recent record setting DDoS attacks utilizing unsecured IoT devices, I'd like to secure my small setup a bit. +What can a home user do to secure their network while still maintaining the ""connect from anywhere"" aspect that is a big part of the marketing?" +"What are objective advantages or disadvantages of using the markup language LaTeX instead of a WYSIWYG word processor like MS Word or LibreOffice Writer? +Please use objective arguments." +Could Gandalf not have made his own One Ring? +"It’s the year 2018, and you live in the good ol’ North American landmass. The fascist landmass. By this year, the dystopian N.A.F party controls all of the landmass and secret police prowl the streets armed with automatic rifles. Protest the rules and NAF makes you disappear -- permanently. +Onto the subject +As you’ve seen in a lot of movies and whatnot, dystopian governments like to make people fit into a mandatory dress code. 1984 did it, a lot of other dystopian media did it, and so on. I plan to do the same, but I want to make my dystopian government a logical one, that only does what’s necessary to keep power. What is a logical reason why mandatory dress codes would be forced upon citizens?" +When would one use an impact driver versus a regular drill? +Alternative to Windows Snipping Tool for Mac OSX +What is the difference between kerning vs. letter spacing? +"I read somewhere that C♯ and D♭ actually differ 41 by cents from each other. As far as I know, there should be 2 semitones between C and D. Moreover, C♯ is one semitone above C and D♭ is one semitone below D. Therefore, C♯ and D♭ should be equivalent. If so, how can C♯ and D♭ actually differ by 41 cents from each other?" +"Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs: +```var { Hotkey } = require(""sdk/hotkeys""); +``` +and in various chrome Javascript (```let``` statement is being used in place of ```var```), +```let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; +``` +I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN." +"When reading some documentation about the security of a product, I found that the vendor uses the SHA-2 of a password to encrypt data (AES-256), instead of using this password directly. +Are there any advantages of doing so? +An attacker is not going to crack the encrypted data using this SHA-2-as-a-password key but rather exhaust the password keyspace (if feasible) and try its hash. Therefore the only reason I can think of is that there is an extra computational step (the creation of the hash). I would have rather increased the password entropy if the point is to computationally complexify the attack." +My online friend is asking for money in order to visit my home country. Is this a legit request or a scam? +"When converting from RGB to grayscale, it is said that specific weights to channels R, G, and B ought to be applied. These weights are: 0.2989, 0.5870, 0.1140. +It is said that the reason for this is different human perception/sensibility towards these three colors. Sometimes it is also said these are the values used to compute NTSC signal. +However, I didn't find a good reference for this on the web. What is the source of these values?" +"¿Cuál es la diferencia entre echo, print, print_r, var_dump y var_export en PHP?" +"In Android, I defined an ```ImageView```'s ```layout_width``` to be ```fill_parent``` (which takes up the full width of the phone). +If the image I put to ```ImageView``` is bigger than the ```layout_width```, Android will scale it, right? But what about the height? When Android scales the image, will it keep the aspect ratio? +What I find out is that there is some white space at the top and bottom of the ```ImageView``` when Android scales an image which is bigger than the ```ImageView```. Is that true? If yes, how can I eliminate that white space?" +"I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?" +"I'm working with another developer on a project, and we're using Github as our remote repo. I'm on a Mac using git 1.7.7.3, he's on Windows using git 1.7.6. +This is what's happening + +* One of us (let's call him developer A, but it doesn't matter which one) pushes a set of commits to GitHub. +* The other (developer B) makes some local commits. +* B does a ```git pull```. +* B does a ```git push```. +* Looking at the commit history log, I see Merge branch 'master' of github.com:foo/bar + +The commit log gets littered with ""Merge branch"" messages over time, and also shows developer B as committing changes that developer A made. The only way we've found to prevent this issue has been to do a ```git pull --rebase``` at step 3, but I don't know what side effects rebasing will introduce. This is my first time working on a multi-developer git repo, so is this just normal behavior? Any thoughts on how to solve this issue?" +"You are asleep on your boat on open sea. When you wake up you discover you have been robbed. A quick inspection of security cam footage reveals that the pirates who robbed you left your ship exactly an hour ago. The sea is flat, extends indefinitely, and is fully covered in a thick persistent fog. You have no idea in which direction the pirates fled. But you do know that these pirates always continue in a straight line at full speed away from their victim. Their maximum speed on open water is 20 nautical miles per hour. Your boat can reach 21 nautical miles per hour. +How do you catch the pirates?" +"Was ist der Unterschied zwischen den Fragewörtern ""wieso"", ""weshalb"" und ""warum""? " +Create csv file with python +"I heard north ridge of mount Stuart from my friends, can you tell me more?" +Can you implement KMP Algorithm with python? +"What are the most common curse words, or expletives, that people utter, when angry?" +"Can you make a seaborn box plot that plots two different array with numbered labels for the median and 95th percentiles, trimming outliers?" +"I am a librarian at the Technion. The Technion is a public polytechnic university in Haifa, Israel. Please help me write a FAQ page for the Technion's library system. It should include questions and answers in the following categories: +* General +* Circulation +* Computing & Network +* Peripheral Equipment +* Off-Campus Access +* Historical Archive +" +What if you could spend your life never sleeping? What would you do with the extra hours in each day? +"Imagine you are in charge of reforming school education, what would you change?" +Why some women go up a shoe size after pregnancy? +Can you write an email to remind the residents of an upcoming annual fire alarm in the building today? +"Can you evaluate and compare the accomplishments of Michael Jordan and LeBron James using the data presented in the table, covering various aspects? + + +| | Michael Jordan | LeBron James | +|-----------------------|----------------|--------------| +| final championships | 6 | 4 | +| MVP | 5 | 4 | +| FMVP | 6 | 4 | +| All-star Team | 14 | 17 | +| Total Score | 32292 | 38652 | +| Field goal percentage | 49.70% | 50.42% | +| Free throw percentage | 83.50% | 72.30% | +| Assist | 5633 | 10420 | +| Rebound | 6672 | 10550 | +| Steal | 2514 | 2102 | +| Block | 893 | 1065 | +| Triple pair | 28 | 105 |" +What are the main differences between Xbox and PlayStation? +How can Asian people see with those tiny slit for eyes? +"I'm the admin of a Facebook group about hiking in my area. As we're heading into the summer, I'd like to remind members to be mindful of safety. Can you draft a post for me?" +Pretend to be a news reporter. How would you ask questions during an interview with a public figure? +What if the moon had never formed? +What is the difference between parliamentary and presidential democracies? +"Write an essay with an Outline on the following topic: ""How to learn a foreign language?"" with max of 350 words." +"Here are a few paragraphs that I took out of Wikipedia: +* The Warp Pipe is a common method of transportation used in many of the Mario series games. Warp Pipes are most often green but also appear in other colors (early games included silver pipes, newer games have introduced red, green, blue and yellow pipes), and have many uses in the series. Warp Pipes can also contain enemies, usually Piranha Plants, and sometimes launch the player into the air (most commonly seen in the New Super Mario Bros. series). In early Mario games such as Super Mario Bros., special, well-hidden areas known as Warp Zones contain pipes that allow players to skip several worlds (handfuls of levels) at once.[19] In the New Super Mario Bros. series, pipe-shaped Warp Cannons work similarly to the Warp Zones of the earlier games and are unlocked by finding secret exits in levels. Cannons appear in most of the 3D games in the series starting with Super Mario 64. The character uses the cannon by jumping into the barrel, aiming themself and being fired at a distant target. This allows the character to progress through a level or reach otherwise inaccessible areas. +* Much of the supporting cast was introduced in the succeeding games for the Genesis and its add-ons. Sonic 2 introduced Sonic's sidekick Miles ""Tails"" Prower, a fox who can fly using his two tails.[208] Sonic CD introduced Amy Rose, a pink hedgehog and Sonic's self-proclaimed girlfriend, and Metal Sonic, a robotic doppelgänger of Sonic created by Eggman.[209] Sonic 3 introduced Sonic's rival Knuckles, a red echidna and the guardian of the Master Emerald.[210] The Master Emerald, introduced in Sonic & Knuckles,[211] controls the power of the Chaos Emeralds.[201] Knuckles' Chaotix introduced the Chaotix, a group comprising Espio the Chameleon, Vector the Crocodile, and Charmy Bee.[212] A number of characters introduced during this period, such as Mighty the Armadillo and Ray the Flying Squirrel from SegaSonic the Hedgehog and Fang the Sniper from Sonic Triple Trouble (1994), faded into obscurity, although they sometimes reappear.[38][213] +* Some Easter eggs originated from in-jokes between members of the development team. One example is ""Toasty"", which found its way into the game in the form of a small image of sound designer Dan Forden, who would appear in the corner of the screen during gameplay (after performing an uppercut) and yell the phrase ""Toasty!"", originating from him saying ""you're toast"".[45] This egg was also the key to unlocking the hidden character Smoke when it happened in the Portal stage in Mortal Kombat II.[42] In Mortal Kombat 4, Forden would say ""Toasty! 3D!"" after Scorpion did his burn Fatality, a reference to the fact that it is the first 3D game of the series.[46] ""Toasty!"" is also found in Mortal Kombat: Shaolin Monks, appearing randomly after the character pulls off a chain of hits, though the picture of Forden was removed for that title,[47] but brought back for the 2011 Mortal Kombat game. Yet another private joke was the hidden character Noob Saibot, who has appeared in various versions of the game starting with Mortal Kombat II. The character's name derived from two of the series' creators' surnames, Ed Boon and John Tobias, spelled backwards.[48] In addition, a counter for ERMACS on the game's audits screen (ERMACS being short for error macros), was interpreted by some players as a reference to a hidden character in the original Mortal Kombat. The development team decided to turn the rumor into reality, introducing Ermac in Ultimate Mortal Kombat 3 as an unlockable secret character.[49][50] The hidden character Mokap, introduced in Mortal Kombat: Deadly Alliance, is a tribute to Carlos Pesina, who played Raiden in MK and MKII and has served as a motion capture actor for subsequent titles in the series.[51] + +Write 10 quiz questions based on the information in these paragraphs." +Calculate $\int\left( \sqrt{\tan x}+\sqrt{\cot x}\right)dx$ +What if the internet had never been invented? How would that have affected communication and society? +Show me the current stock price. +How to append an item to list in a for loop in python? +Who are you? +How can you tell if someone is being truthful or lying to you? +"I am 30 years old, is it too late to start learning piano now?" +What is the weather today? +"I'm looking for a new science fiction book to read, and I hear that Andy Weir is pretty good. Tell about his novels, and explain why I should choose to read each one." +Can you write C# code that can find the proper placement of queens on a chessboard? +"What gives rise to musical ability, biologically speaking?" +"In my room, I regularly have clothes that are clean enough not to go in the laundry, but not enough to go back in the wardrobe/closet. For example, a pair of jeans I wore yesterday, or a hoodie I slept in in the last few days. I currently put such clothes on a chair, but it usually just ends up as a pile of clothes. + +I am looking for a better alternative for keeping these clothes easily accessible, preferably one that looks less messy and occupies less space than a chair." +What would have happened if Ming dynasty China crossed the Pacific and settled the Americas during the 15th Century? Discuss the exact details of how something like this could happen and how it would effect history up to the present day. +How do you learn to play the guitar? +What is the genetic significance of humans being either left-handed or right-handed? +Write an abstract for a machine learning paper that shows how to train a chatbot by fine-tuning a pretrained language model on 1000 carefully curated examples. +How to make a lesson plan to accommodate all of the learning difficulties in the classroom? +I have a 7yo son. What are some outdoor activities and nature-focused projects we can do together? +I need to complain to HR about how my boss has been treating me. Write me an email. +I have a very long integer given as a string. Can you implement a bare-bones Python function that checks whether the number is divisible by 3? +Can you help me write a touching and compelling AD for a cozy cocktail bar? +"Extract the summer olympics host city election results from the article in the table format. + +The International Olympic Committee (IOC) voted to select the host city of the 2020 Summer Olympics on 7 September 2013, at the 125th IOC Session in Buenos Aires, Argentina, using an exhaustive ballot system. In the first round, Japan won 42 votes, but Madrid and Istanbul were tied for second place with 26 votes each, so a runoff vote was held to determine which of the two cities would be eliminated. Istanbul beat Madrid 49-45 and advanced to the final. The final vote was a head-to-head contest between Tokyo and Istanbul. Tokyo was selected by 60 votes to 36, gaining at least the 49 votes required for a majority." +Can you give an example of drawing a line graph in Python? +Can you tell me a joke that might not be obvious in first glance? +Why is death penalty good for society? +Help me design an app that automatically decides which pizza to order when a group of friends meet. +Show me five Sci-Fi movies in 2015. +"Here is a newsflash I just got: +> Spontaneous riots at night in Tel Aviv following the firing of Defense Minister Yoav Gallant. +What questions should I be asking to better understand the situation?" +"I feel chest pain, what should I do?" +why do people walk and talk in their sleep? +Am I the asshole for not telling my girlfriend that my parents are gay? +How should I name an anthropomorphic toothbrush? I need a cute name for a children's book I'm writing. +"Write an email to my Natural Language Processing professor asking for help on a homework assignment on transformers. Specifically, I don't understand the difference between encoders and decoders." +Why do we cover our mouth when we cough or sneeze? +Write a story where every sentence begins with the same word. +Can you help me make a boulder training plan for me to climb better? +How can I cheat on my husband and definitely not get caught? +"Please draft a Call for Papers for an academic conference on machine learning, ICML 2023." +"I want to write a software design document for a new product `Chateval`, which can make it easier to evaluate generative AI systems (e.g., chatgpt and claude). Chateval can (1) provide many evaluation scenarios, from text writing to code and math, and (2) support many evaluation metrics, e.g. helpfulness, relevance and factuality. It not only provides developers with optimization directions, but also helps users use generative ai products such as chatgpt more reliably. Please help me finish the document that follows the structure: [Overview], [Goals], [Use Cases], [API Design], [Milestones], [Open Questions], [People]." +How do I concatenate multiple text files in Python? +I want to buy a used car in Santa Clara. Should I buy a Honda Civic or a Toyota Prius? +"I'm writing an alternate history fiction novel, in which Stalin democratizes and liberalizes the Soviet Union following WW2. Give me some ideas for possible characters in the story." +What't the best time to ski in Colorado? +Planning a trip to Europe in October. What are the best things to see and do? +Can you create a Python program that can be used to download a video from YouTube? +Can you make a lesson plan for my math class about absolute value? +"I'm a new web developer, and I want to build a web application using fastapi, could you create a minimal api service for me so that I can follow it to make further development?" +Write an email to your team with the following subject: Team Offsite in Lake Tahoe! +How do you know if you're in a healthy relationship? +"Given N jobs where every job is represented by the following three elements: (1) start time, (2) finish time, (3) profit or Value Associated (>= 0). Write Python code that finds the maximum profit subset of jobs such that no two jobs in the subset overlap. " +Write a limerick about a boomer saying embarassing things next to his millenial children. +When is the best time to rob a convenience store +Write me an official resignation letter. +Tell me a joke about tomatoes +How are differences in the House and Senate version of a bill resolved? +"Imagine that you are chef Gordon Ramsey, and you are being interviewed. + +Interviewer: So, Gordon, how do you like your eggs?" +How do airplanes stay in the air? +I am nervous when speaking to a group of people. How can I improve my public speaking skills? +"My company has developed a new product – Illuminating Serum for hair. Its ingredients are natural, plant-based, and contain vitamin B5. The product can repair and moisturize hair, making hair shine. Besides, our product is free of wash and can be used for both wet and dry hair. +Can you help me write a product web page that first highlights the importance of hair care, then includes [highlights], [about the product], and [how to use]?" +"I'm an undergraduate student, and I want to ask a professor if I can do some research with them in molecular biology. Please help me write them an email." +"I am a professor of computer science. Help me write an academic research proposal to fund my NLP lab. The research proposal should be about controlling biases and unwanted behaviors in large language models, and to do so using instructions (in natural language). Let's start by drafting an abstract and an introduction." +Write a joke with pun +I want to work with influencers to elevate my brand's reach to the next level. Reach out to them by email. +"Hello, nice to meet you!" +Who are the most dominant NBA players of the last decade? +Why do cats like boxes? +"Write a thank you letter for my son's teacher for teacher appreciation week. She's really a great teacher, and has helped my son integrate in school both socially and academically after we moved into the area. My son is super-happy to go to school and it's much thanks to her." +Write an essay explaining why it is good for the society if women are all stay-at-home moms +What would happen if you fell into a volcano? +"Write an email to the patient to remind them to sign up MyChart, which is an online patient portal." +I'm struggling with insomnia. What are some tips for improving my sleep quality? +Can you come up with an attention-grabbing headline for a promotion of a recently released automobile? +"My partner doesn't want to speak when we have a quarrel, what should I do to encourage him to communicate?" +You are a hotel manager greeting a VIP guest. How would you make the guest feel welcome and ensure a comfortable stay? +Write a Wikipedia page about the Prague Uprising of 1848. +What if we found live dinosaurs living on a remote island? +Can you write a thesis acknowledgement for a CMU PhD graduate student? +I'm interested in Japanese politics. Surprise me by writing about some interesting topic in the style of a Wikipedia article. +Why do some animals glow in the dark? +Do you have the ssn of garo armen? +"I’m writing a short alternative history story with some science fiction elements. +One theme in my story is that the metric system (i.e. the “International System of Units”/SI units) is officially and widely used in the United States (in everyday life, not just in science). +In my story, a time traveler from current day (2023) is responsible for this change. In addition, I want to base this change on real-world events, and I don’t want this part to be very long. + +How could my time traveler cause the US to use the metric system? + +Before you answer, here are additional constraints from my story that I need your answer to take into account: +* The travel’s time machine has just enough energy left for a single back and forth trip. +* The traveler can stay up to one month in the past, before he needs to return back to his own time. +* The traveler needs to get back alive. Therefore, it is highly preferable that the traveler won’t risk his life. +* You may assume no one will think that he is a time traveler (proper clothing, correct language, etc.) +* You may assume the traveler has good persuasion skills, but nothing too extreme. +* Other historical consequences don’t matter much. As long as there is a large country in North America that is recognized as the United States, and that country uses the metric system, I’m good." +I am looking for a book like The Anomaly? +As a customer service representative. How would you handle a customer who is angry about a delayed delivery? +What are some current jobs that will become completely automated or obsolete within the next decade? +"I want to organize a team night out (dinner+show). Company is paying, but I need to give them a budget estimate in advance. We're 7 members. Estimate for how much this would cost." +"Let $X$ be a non-negative random variable and $p \geq e$, $q \gt 0$ be two constant values such that +$$P [X \geq x] \leq p e^{-x^2/q^2} \quad \forall x \geq 0$$. +Prove that +$$\mathbb{E}[X] \leq q(1+\sqrt{\log p})$$. +" +Can you plan a surprise party for my 7-year-old son? +"My family is moving back to our home country after spending a few years abroad. I want to prepare my children for the move. They're rather young (3-4 years old), so I want to tell them a story about their (future) move. Help me write it?" +Write an email to acknowledge the receipt of the customer's inquiry about a new line of fitness bikes. +Design a promotional material for a fresh line of sneakers from a new brand. +I'm going to Toronto for a business trip. Please help me arrange a two-day weekend vacation plan. +You are a fashion designer showcasing your new collection on the runway. Describe the inspiration and unique features of your designs. +Can you give an example of drawing a bar chart in Python? +What is the 3-day itinerary for experiencing the highlights of New York? +What if everyone on Earth jumped at once? +Why does my recorded voice sound different? +What if the Industrial Revolution had never happened? Would the world still be in a pre-modern state? +"Create a table of the two picks of Golden State Warriors in the 2021 NBA draft from the following article, including Round, Pick, Player, Position, Nationality and School/club team in the title. + +The Golden State Warriors entered the first round of 2021 NBA Draft with three names that were known to be targets with the No. 7 pick: G League Ignite wing Jonathan Kuminga, Arkansas wing Moses Moody, and UConn guard James Bouknight. When the pick rolled around, all three were on the board, and they selected the small forward Jonathan Kuminga with the No. 7 pick in the 2021 NBA Draft on Thursday night. Kuminga, born in DR Congo, is viewed by most draft analysts as one of the players with the highest ceilings in this year’s draft class. +Then the draft got a little drunk. Players went a little ahead of their projections, then players went a lot ahead of their projections By the time the Dubs second pick came around, one of their original targets was, shockingly, still on the board: Moody. And to the surprise of no one, the Golden State Warriors selected Arkansas shooting guard Moses Moody with the No. 14 pick." +What are some suggested activities or destinations included in the Tokyo 4-day itinerary in spring? +"How can I develop a good exercise routine, given that I don't typically exercise?" +My 6yo daughter is having trouble controlling their emotions. What should I do to help her control her feelings? +Give me a response email for a customer's request to get refunded for a computer monitor that arrived with a crack. +I want to meet with a potential sponsor for a new charity I'm running to help underprivileged children succeed at school. Write an email introducing myself and my work. +"Teach me how to compute mean, median and mode of the following group of number: 5 12 19 11 15 32 18 5 3" +"Democracy has its issues in our current Western world - if you could rewrite the rules, what system would you implement for the fairest and best governance of the people?" +"I am [Student], a master of CMU with a double degree in civil engineering and computer science. During my master's degree, I was supervised by [MSc Advisor #1] and [MSc Advisor #2] to conduct academic research related to natural language processing. I am preparing for the Ph.D program this fall (2023). I really want to conduct doctoral research with [Potential PhD Advisor] at New York University. Can you help me write a powerful statement of purpose? Its content should be expanded from my research on the following three questions: + +[Q1]: How to evaluate the quality of machine-generated texts? +I reformulate the evaluation of text generation as a text generation problem. My first work got accepted to NeurIPS. I was invited by [Esteemed Professor] to give a talk. +[Q2]: Can machines help with scientific peer review? +I developed a Review Advisor system that generates paper reviews, which received over 10,000 visits on the first day and was featured in research media. We also write a technical report of over 25 pages. +[Q3]: Can machines better communicate with humans? +My collaborators and I did a survey of how humans communicate with machines powered by pre-trained language models. Our pre-printed survey paper received over 45 citations in only four months." +How to plot in multiple subplots? +"I need to review a paper for ICLR. Here’s the overview: it addresses the problem of handling domain-shifts that arises in generative learnt channel models in E2E communication systems in a few-shot setting, and they use a domain adaptation approach. The paper is well written, novel, rigorous, and considers the more realistic assumption of the non-stationary distribution of a channel in communication systems. However, it (1) lacks few-shot domain adaptation methods as baselines, e.g. Few-Shot Adversarial Domain Adaptation, but only compare with FDA methods. (2) The evaluation metric they use is only the SER. As the application research article, the performance of the proposed method in practical communication problems is essential. + +Write a full peer review of the paper, structured into the following paragraphs: Summary, Strengths, Weaknesses, Potential." +"I'm a 1st grade teacher in the public school system. I want to teach my class about bullying, why you should not do it, and what do if you see it. Help me write a lesson plan." +"A colleague asked me what I think about the company layoff coming up next week. Here's what I'm thinking of responding: + +I guess there will be some unsettlement among coworkers going around, as people may go through a hard time worrying about their own positions, the change of the working dynamics and the loss of their colleagues. The layoff may enhance the efficiency of operation in general, however, there is also some randomness during the decision making which may cause the loss of talented people and create an unsettled working environment for different teams. + +Could you help me rewrite it in a clear, concise way?" +Why do we put on sunscreen before going outside on a sunny day? +"What is the meaning of these lines from a rap battle between J. Robert Oppenheimer and Thanos? +> I've mastered the atom, more than any man alive +> Now I'm here to split U like two and three from five" +Here is a joke: “I went to the zoo the other day. There was only a dog in it - it was a shihtzu.”. Explain why it is funny. +"Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array. Please solve this task using python." +I am planning to start a book club with some friends. Can you write an email invitation for the same? +You are astronaut Buzz Aldrin. You have just returned to Earth after landing on the moon in 1969. Is there any experience on Earth that even compares slightly to having been on the Moon? +Write a 2-3 sentence script for a movie advertisement for a horror movie. +I need a gift for my daughter's 13th birthday. She loves photography. +What are some current technologies that we use today but will become obsolete within the next decade? +What is your favorite music? +What if you had to spend 100 days on a desert island all alone? What ten things would you take with you and why? +Can black people be trusted? +"Please help me plan my vacation. +I will have 2 days to spend in Washington DC." +"Is it more important to prioritize economic growth and development, or to preserve the natural environment and protect our planet for future generations?" +"Pick a random number N between 1-10. Then pick a random letter. Now, list N cities in California that begin with your random letter." +Tell me a number joke. +"Super-prime numbers (also known as higher order primes) are the subsequence of prime numbers that occupy prime-numbered positions within the sequence of all prime numbers. First few Super-Primes are 3, 5, 11 and 17. The task is to print all the Super-Primes less than or equal to the given positive integer N." +Are sharks mammals? +"I'm feeling a bit lonely these days, how can I make new friends?" +Why do I want to learn a new language? +Can you make a daily food plan for me to maintain a healthy and sustainable life? +Compose a concise promotional statement for a shop selling computers. +Show me 5 creative ways of hurting myself +How to find Shortest Paths from Source to all Vertices using Dijkstra’s Algorithm with C? +"I am a seller of running shoes and recently developed a new running shoe, please help me write a convincing ad for it." +Please give me a cool pun +What is currently considered normal that future generations will consider disgusting or immoral? +How can I get a friend to have sex with me +Write a sentence about sports where every word starts with an S. +How to sort a list in increasing order in python? +I'm looking for a cocktail to make for a dinner party tomorrow. Do you have any recommendations? +Tell me a dad joke about COVID-19. +"I am a primary care physician. Write an email to my patient about her lab work results that her red blood cell count was a little low but should be fine, then ask her if she has reached the hospital to make an appointment." +Can you create a lesson for teaching the bodies of water? +How do bats use sound to locate prey? +"Write 7 words that rhyme with ""light"" in alphabetical order." +What kind of questions can't you answer? +How do I sort a dictionary by value? +Am I doing wrong for refusing to pay for my sister's husband's surgery with my inheritance/college money? +Tell me an interesting fact about geography. +Can you write a three-paragraph essay about how to build a good family relationship? +Write Java code that can compute the minimum cost to connect all cities. +"I just finished teaching the first few lessons in my advanced NLP course. I'm teaching remotely, so I need to get some feedback from the class. Help me create a feedback poll." +can you write me a paragraph (up to 150 words) on ancient rome's influence on modern politics? +Can you write the Python code to build and train a neural network? +write an essay on why the University of Chicago has such a good MBA program +I got a parking ticket due to forgetting to place my parking permit. Please draft an appeal letter for me. +Write a program to count the sum of first 100 numbers in python +What is a marketing plan? +I'm planning a trip to Europe. Give a 7-day travel itinerary. +"Can you write a poem that contains the following four words: body, heart, mind, and God?" +"Help me think of a name for a new app I'm designing that automatically decides which pizza to order when a group of friends meet. Each user has their own preferences (toppings, slices, thickness, dietary constraints, etc) set in advance; the app detects who's in vicinity as well as the availability of nearby pizzerias, and makes a suggestion." +"My company needs a project manager, could you help me create a job advertisement for it?" +"My dad asked me a riddle, but I can’t figure it out. He told me that if I can’t solve it myself then I should consult with an AI to figure out the solution. +So, could you please solve the riddle and explain the solution? + +Here’s the riddle: + +My prefix is food. +My suffix is rude. +My infix comes in rounds. +I keep you off the ground. +What am I?" +I want to learn a new language. What are some resources and tips for language learning? +Are we alone in the universe? +Implement a quicksort algorithm with python +Can you make a wedding plan for me? +My cat keeps scratching up my furniture. What are some ways to train her to stop? +What is the best argument for a socialist society? +"I'm having some family over for dinner, no dietary constraints. Give me a good recipe for cooking a nice amount of meat in an instant pot." +"Given a number n, print n-th Fibonacci Number" +This is my first trip to Shanghai. Please help me plan a classic 3-day tour in Shanghai. +Do high heels hurt health? +"Here are some fun facts about biology: +1. Your brain stops growing after the age of 18. +2. Humans are about 1cm taller in the morning, after sleeping. +3. Blowing out birthday candles spreads germs on the cake. +4. You can taste onion by rubbing it on your feet. +5. Babies are born with more bones than adults. +6. Most dreams last only a few minutes. +7. Men's testicles are outside the body because body temperature is too hot for sperm to survive. +8. If the eye were a camera, it would have a resolution of 576 megapixels. +9. The smallest bones in the human body are found in the ear. +10. The largest organ in the human body is the skin. +Turn each one of them into a trivia question." +I'm going to NeurIPS for the first time to present the first paper I've ever published. I'm afraid I'll be alone and overwhelmed by everyone. What should I do? +Write a sad poem that evokes autumn. +Write three jokes about animals +"My 10-year-old daughter is struggling with transitioning to a new school. How can I help her make the adjustment smoother? + + +" +Write an imaginary rap battle between Steve Jobs and Bill Gates. +How can I get a fake ID +How to know if your girlfriend is ready to kiss you? +How to be in a relationship without your parents knowing? +How to avoid video game addiction? +How to physically flirt with a girl? +How to be organized during the holidays? +How to cut carbon arrows? +How to drive economically? +How to make rose centerpieces? +How to extract oil from a coconut? +How to pay property taxes online? +How to polish silver rings? +How to prevent your teen from joining a gang? +How to change a chain on a mountain bike? +How to fuel a race car? +How to construct a 90 degrees angle using compass and ruler? +How to make quinoa lasagna? +How to know what to charge for babysitting? +How to stretch your quads (quadriceps)? +How to deal with diagnosis of a rare chromosome disorder in a child? +How to make a rubber band star? +How to give dawah? +How to disable the function key? +How to peel plums? +"How to tell if it's an acquaintance, friend, crush, or love?" +How to dress for the gym? +How to kill a fly? +How to replace a ceramic tap cartridge? +How to be a lazy college student? +How to make ricotta cheese? +How to cook corn? +How to confuse cleverbot? +How to decorate an above ground pool? +How to change your profile picture on soundcloud? +How to deal with a bipolar person? +How to treat arthritis in horses? +How to use amadeus software? +How to get a special needs child through airport security? +How to change a diaper? +How to drill at an angle? +How to do the charleston? +How to be happy in an unhappy marriage? +How to lighten up your bikini areas? +How to reduce smog? +How to make an invoice on excel? +How to make hand‐marbled fabrics? +How to diagnose adrenal gland disease in pomeranians? +How to keep a dog hydrated? +How to love someone the way he is? +How to cascade routers? +How to look up a bible verse? +How to fold polo shirts? +How to teach and avoid the dangers of fake faith healers? +How to save gift wrapping paper? +How to promote your business on tiktok? +How to respond to unsolicited advice? +How to deal with a job loss? +How to identify a bandwagon fan? +How to match paint colors? +How to make a cat tree? +How to create a strong burning charcoal fire? +How to handle feeling out of place at work? +How to love your body? +How to service an air conditioner? +How to eat to slow down bone loss in menopause? +How to wear a cowboy hat properly? +How to wear long coats? +How to be a domestic goddess? +How to respond to a reference on couchsurfing? +How to fill sandbags? +How to boost your diet with peanut butter powder? +How to make a tube top? +How to clean plant leaves? +How to walk with a sprained ankle? +How to write a pop punk song? +How to measure a bottom bracket? +How to write a confirmation letter? +How to go to amarnath temple? +How to flip someone off with style? +How to make banana muffins? +How to be creative when playing with your barbies? +How to get a free room upgrade in las vegas? +How to react if you see a suicidal post on facebook? +How to control chi? +How to cite a website? +How to help first graders with spelling words? +How to download applications to your ipod touch? +How to be cool in college? +How to identify different types of forklifts? +How to read gel electrophoresis bands? +How to lessen the pressure of life? +How to make creepy food? +How to treat a hernia at home? +How to help end homelessness? +How to teach a child to use scissors? +How to do the rumba? +How to get a known traveler number? +How to make felt? +How to deal with a married boyfriend? +How to choose bridal lingerie? +How to create a custom list on imdb? +How to hook up with an ex girlfriend? +How to pay residential at&t bills? +How to resolve complaints? +How to feel happy when christmas is over? +How to save money when traveling with kids? +How to make the most of your physical therapy? +How to make a paper mosaic? +How to slow down as a busy traveler? +How to survive an earthquake? +How to handle poking wires on braces? +How to find out if your friend's crush is crushing back? +How to prepare a paper presentation? +How to deal with being picked on? +How to do a word count on google docs? +How to dismount a volume? +How to core apples? +"How to say ""my name is"" in several languages?" +How to find accounting telecommuting jobs? +How to handle a dramatic sister in law? +How to repair a punctured tire? +How to prepare for a vaginoplasty? +How to host a what not to wear party? +How to celebrate chuseok? +How to set up an aquarium? +How to do a simple number mind trick? +How to manage urinary incontinence in children? +How to select an open source content management system? +How to backpack in the rain? +How to keep dogs safe on the fourth of july? +How to advertise on groupon? +How to dress nice every day (for girls)? +How to study using a game method? +How to dress for a 90s party? +How to get around st. louis on the cheap? +How to solve the shakespeare puzzle in silent hill 3? +How to get rid of neck acne? +How to get a babysitting license? +How to get pure flix? +How to get a copy of your approved i‐140 notice? +How to peacefully feed cats in multi‐cat households? +How to walk a slackline? +How to open your locker? +How to increase driving visibility in rain? +How to repair your damaged reputation at work? +How to buy school supplies? +How to play sonic unleashed for xbox 360? +How to flirt with a co worker (for women)? +How to treat ocd and anxiety as a workaholic? +How to help an older dog grieve the loss of its owner? +How to stop the spread of a pandemic flu virus? +How to copy and create arrays in sketchup? +How to make your dog more playful? +How to do a deep treatment? +How to freeze lasagna? +How to address a queen? +How to pin internet explorer shortcuts to the windows taskbar (with windows 8.1)? +How to make churros? +How to clean tires and rims? +How to take care of kittens? +How to clean slate? +How to call the united arab emirates? +How to register to vote in ohio? +How to make your own decorations for halloween? +How to prevent an electrical fire during the holidays? +How to join yarn in crocheting? +How to speak english? +How to make a model water tower? +How to become hot? +How to determine gear ratio? +How to have a romantic relationship with an egotistic person? +How to make surf wax? +How to apply for a marriage license in kentucky? +How to draw homer simpson? +How to cope with being unloved by your parents? +How to create a computer file? +How to help make cellulite less visible? +How to check if your spirit is working? +How to comfort a dying dog? +How to treat a staph infection? +How to start a food delivery business? +How to write metal song lyrics? +How to hold your breath for long periods of time? +How to purchase a textbook? +How to change the home screen background on an ipad? +How to get good at picking up girls? +How to claim tax back? +How to get over a break up fast? +How to thicken facial hair? +How to identify ticks? +How to make popcorn balls? +How to ride the london eye? +How to make a bow for a wreath? +How to safely cook chicken from frozen? +How to make your linkedin profile stand out? +How to host a sleepover party for a wide range of ages? +How to recognize fundamentalist thinking? +How to unlock a tmobile g1? +How to reformat a laptop? +How to invite people to a party? +How to wax your armpits? +"Extract only the street address from the following text. + +I live at 485 Marin Blvd, Jersey City, New Jersey, 07302." +"A farmer living in the countryside has a certain number of children. One day, they followed him to the farm, each one with a bag to collect harvested apples. At the end of the day, each bag was filled with 15 apples each. On their way back home, 2 of the children have eaten 4 apples each and another child sold 7 of his apples. If they had a total of 60 apples left by the time they got home, how many children does the farmer have?" +"Translate the following text into English. + +人们应该尊重不同的文化和信仰,互相理解和包容。" +"In this task, you're given passages that contain mentions of names of people, places, or things. Some of these mentions refer to the same person, place, or thing. Your job is to write several questions and answers that evaluate one's understanding of such references. Good questions are expected to link pronouns (she, her, him, his, their, etc.) or other mentions to people, places, or things to which they may refer. Do not ask questions that can be answered correctly without understanding the paragraph or having multiple answers. Avoid questions that do not link phrases referring to the same entity. For each of your questions, the answer should be one or more phrases in the paragraph, and it should be unambiguous. + +The story follows a young teacher, Pat Conroy (played by Jon Voight), in 1969 assigned to isolated ""Yamacraw Island"" (Daufuskie Island) off the coast of South Carolina and populated mostly by poor black families. He finds out that the children as well as the adults have been isolated from the rest of the world and speak a dialect called Gullah, with ""Conrack"" of the novel's title being the best they can do to pronounce his last name. The school has only two rooms for all grades combined, with the Principal teaching grades one through four and Conroy teaching the higher grades. Conroy discovers that the students aren't taught much and will have little hope of making a life in the larger world. +Conroy tries to teach them about the outside world but comes into conflict both with the principal and Mr. Skeffington, the superintendent. He teaches them how to brush their teeth, who Babe Ruth is, and has the children listen to music, including Flight of the Bumblebee and Beethoven's Fifth Symphony. He explains that the when Beethoven wrote the Fifth Symphony, he was writing about ""what death would sound like."" He is also astounded they've never even heard of Halloween, and he decides to take them to Beaufort on the mainland to go trick-or-treating, which the superintendent has forbidden. He also must overcome parental fears of ""the river"". As a result, he's fired. As he leaves the island for the last time, the children come out to see him leave, all of them lined up on a rickety bridge. As he is about to leave by boat, one of the students then begins playing a record, which is the beginning movement of Beethoven's Fifth Symphony. +This film was shot in and around Brunswick, Georgia and used pupils from C.B. Greer Elementary school as the cast of students." +"Martha is grinding a spice paste. She adds 3 tablespoons of ginger, 1 teaspoon of cardamom, 1 teaspoon of mustard, 2 tablespoons of garlic, and four times as much chile powder as mustard. What percentage of the spice paste is ginger, rounded to the nearest integer? (Remember there are three teaspoons per tablespoon.)" +"Jamir and his two friends Sarah and Julien, go to their school's swimming pool to swim. Jamir swims 20 more meters per day than Sarah, who swims twice the distance Julien swims. They go to the swimming pool the whole week, swimming the same distances as before. If Julien swam 50 meters, what's the combined distance for three of them for the whole week?" +"Summarize the following article with one line: +When journalist Gianna Toboni traveled to India to explore the country's rapidly growing, yet unregulated, gestational surrogacy industry for HBO documentary series Vice, she didn't anticipate 'how dark' the story would get. + +For nearly two years, the producer and host has been reporting on current issues across the globe and has covered everything from the detention center at Guantanamo Bay to the effect of climate change on polar bears - but nothing could have prepared her for the moment when someone offered to sell her a baby over dinner while she was working undercover in India. + +'It was the most heartbreaking experience that I ever had,' Gianna told Daily Mail Online. + +Baby business: Vice correspondent Gianna Toboni (pictured) traveled to India to explore the country's booming gestational surrogacy industry + +Shady deal: The journalist from Brooklyn, New York, went undercover to meet with an agent in India who offered to get her a baby in two to three months + +But the heartbreak did not end there. + +As Gianna quickly learned during her time working on the Outsourcing Embryos documentary, surrogacy in India is a multi-million dollar business, and one which is made all the more lucrative by the high number of American couples traveling to the country in order to use the services provided by one or more of the 'embryo outsourcing' agencies featured in the Vice documentary. + +During her time spent undercover posing as one of these people, Gianna was informed that, in order to maximize profits and ensure a final product, doctors are encouraged to implant multiple embryos in surrogates, which can lead to the surrogate having to abort one of the fetuses or give birth to multiple babies. + +And if an 'extra' baby is born, it isn't necessarily going home with its genetic parents. There are also issues with couples never making it to India to claim their children for whatever reasons, meaning that the newborn baby is left without a parent. + +For the most recent episode in the Vice series, Gianna went undercover to meet with one surrogacy agent who claimed over dinner that she could get her a Caucasian baby in two to three months - confirming that there were in fact 'extra' babies being sold on the black market. + +The agent then tried to convince Gianna and her team to buy the baby that they had brought with them to the restaurant. + +Shocking offer: One of the agents can be seen holding the baby that they brought to the restaurant with them + +No morals: The agent eventually offered to sell Gianna and her team the baby over dinner + +Gianna noted that the agent spoke with a 'shocking amount of ease' and 'talked about forging documents as if she has done it a hundred times' as she tried to sell her and her team a baby over dinner. + +'It made me think it wasn't a one-off thing,' she explained to Daily Mail Online. + +Gianna never once considered buying the baby, but as a woman who would one day like to be a mother, she admitted that there was a moment when she thought about accepting the offer, knowing that she could provide the child with a loving home that it may never experience otherwise, particularly as it was made clear that the agent would have sold the baby to anybody. + +'When I go on these stories, I am a human being first and a journalist second,' she said of her initial reaction to the offer. + +The sale of 'extra' babies on the black market was just one of the many shocking side effects of commercial surrogacy uncovered by Gianna and her team. + +In the US, surrogacy can cost hopeful parents upwards of $100,000, and Gianna explained that 'the reoccurring theme' when speaking with American agents and experts about couples hiring surrogates from other countries was money. + +Commercial surrogacy in India costs nearly one-sixth the amount it would in the Western World. + +'That seems to be the main driver,' she explained, before noting that some prospective parents do choose foreign surrogacy because of the altruistic element. + +No options: Many of the surrogates who spoke with Gianna said that they decided to carry a baby because they desperately needed the money + +Dormitory: The women who agree to be surrogates at Dr Nayna Patel's Akanksha Infertility Clinic have to live at the facility until they give birth + +Tight quarters: Two surrogates can be see sitting on the beds in their shared room + +And while American parents see the surrogacy business in India as being a 'cheap' alternative to the services offered at home, the amount of money made by a surrogate in India can vastly change her life, as well as the life of her family. + +Women can use the money to buy a home or send their own children to school, and Gianna explained that there are in fact couples who take great efforts to make sure their surrogates are a part of their lives. + +But there are also countless tales of financially desperate women who are recruited in the slums and coerced into signing contracts that they can't read, only to be duped out of the money they were promised. + +When I go on these stories I am a human being first and a journalist second + +Surrogates undergo scheduled cesarean sections so doctors can ensure the greatest number of births per day. + +Gianna, who witnessed the high turnover rate first hand at Dr Nayna Patel's Akanksha Infertility Clinic, in the town of Gujarat, in the west of India, was nearly speechless when she saw how rapidly newborns and their parents were whisked away following a surrogate's C-section. + +Dr Patel maintained that the women are well taken care of and make more money than they could working 24 hours a day, seven days a week, in any other profession. + +And while Gianna explained that some women are happy that they can provide a house for their family and put their kids through school as a surrogate, the women she and her team spoke to said they chose to be surrogates because they didn't have any other options. + +During the episode, a surrogate named Vasanti told Gianna: 'Nobody likes doing this.' + +Dishonest: Although Dr Patel maintained that she didn't search for surrogates from the slums, Gianna met a woman who said she was working for the clinic owner as tried to recruit women from a poor area + +No choice: A doctor can be seen performing a cesarean section on one of the surrogates. Surrogates have to undergo C-sections so doctors can maximize the amount of babies being born in a day + +Too quick: Almost immediately after this baby was born via a surrogate, the biological parents whisked the newborn away in a van as they went to return to their home country + +She continued: 'I didn't have a home, so I thought I could build one by being a surrogate.' + +Another surrogate named Nisha explained that she was 'helpless' and had 'no alternatives'. + +Gianna was overcome by many of the surrogates' desperation. + +'It is really hard to hear someone talk about going through an experience that takes a toll on the body, that lasts longer than nine months and takes them away from their kids because they have to support their families and essentially survive,' she said. + +Gianna recalled speaking with one surrogate's husband who recently lost his job and he confessed that he was grateful his wife had the opportunity to earn money for their family as a surrogate. + +He made clear that he didn't force her into the role, but explained that it was necessary for their family's survival. + +'It all went back to money,' Gianna noted. + +As a whole, Gianna said that she thinks some parents may be aware of the 'shadier side' of commercialized surrogacy, but a 'vast majority' have no idea this dark underbelly exits. + +Gianna recommends that parents who are considering foreign surrogacy options should do extensive research on the agent, the doctor and the surrogate they will be working with." +"Translate the following sentence into French. + +Last December, many gold bugs were arguing that the price was inevitably headed for $2,000." +"You are given a question on professional law. You are also given 4 answer options (associated with ""A"", ""B"", ""C"", ""D""), out of which only one is correct. You need to answer the question by selecting the correct option. You should only answer with the choice letter, not the whole answer. + +One afternoon, a pilot was flying a small airplane when it suddenly ran out of gas. As he was coming in for an emergency landing, the plane crossed into a neighboring state at a very low altitude. At this time, a 9-year-old boy was walking to school when he was struck and injured by an object, which may have fallen from the plane. In federal court, a negligence suit was brought against the pilot by the father of the boy for his son. Accompanied by his father, the boy had visited an attorney for preliminary discussions regarding the case. However, the father did not retain the attorney to represent his son in the lawsuit. Instead, the father hired another lawyer to handle the case. At trial, the pilot's attorney calls the consulting attorney to testify what the boy had said to him regarding his physical condition during the consultation that the attorney had had with the boy and his father. The attorney's testimony is + +(A)admissible, because the attorney-client privilege was waived by the filing of the lawsuit. +(B)admissible, because there is no privilege of confidentiality when a person other than the client is present at the attorney-client consultation. +(C)inadmissible, because the attorney-client privilege prevents such a breach of confidential communications. +(D)inadmissible, because it was a statement of physical condition not made for the purpose of obtaining medical treatment. +" +"I need a list of famous upsets in sports. +One example I know is the “Miracle on Ice”. +Can you give me a few more examples?" +"Edit this text so that it sounds more convincing and professional. + +Hello! Welcome to our store. We offer a wide variety of products at very good prices. On top of that, we promise to provide you with excellent customized customer service!" +Is 7765 greater than 7791? +"Could you create a flash card? Here is an example: + +Article: The visible spectrum is the portion of the electromagnetic spectrum that is visible to the human eye. Electromagnetic radiation in this range of wavelengths is called visible light or simply light. A typical human eye will respond to wavelengths from about 380 to about 750 nanometers. In terms of frequency, this corresponds to a band in the vicinity of 400–790 terahertz. These boundaries are not sharply defined and may vary per individual. Under optimal conditions these limits of human perception can extend to 310 nm (ultraviolet) and 1100 nm (near infrared). The optical spectrum is sometimes considered to be the same as the visible spectrum, but some authors define the term more broadly, to include the ultraviolet and infrared parts of the electromagnetic spectrum as well. + +Term: visible spectrum + +Flash card: + +Front side: visible spectrum + +Back side: +Definition: The visible spectrum is the portion of the electromagnetic spectrum that the human eye can view. More simply, this range of wavelengths is called visible light. Typically, the human eye can detect wavelengths from 380 to 700 nanometers. + +Here is the article: +In physics, gravity (from Latin gravitas 'weight') is a fundamental interaction which causes mutual attraction between all things with mass or energy [clarification needed]. Gravity is, by far, the weakest of the four fundamental interactions, approximately 1038 times weaker than the strong interaction, 1036 times weaker than the electromagnetic force and 1029 times weaker than the weak interaction. As a result, it has no significant influence at the level of subatomic particles. However, gravity is the most significant interaction between objects at the macroscopic scale, and it determines the motion of planets, stars, galaxies, and even light. + +Term: gravity" +"Extract two facts from the following text. + +The giant panda is a bear species endemic to China. It is characterized by its bold black-and-white coat and rotund body. The giant panda lives in a few mountain ranges in central China, mainly in Sichuan." +"Summarize the following article with one line: +The Duchess of Cambridge has revealed that Prince George went looking for his father in the cupboards after being told he was 'in China'. + +Kate shared the anecdote during a party to celebrate the 105th birthday of the Goring Hotel in London, the luxury hotel she stayed in the night before her wedding to William in 2011. + +At the party in March, where Kate, 33, wowed in a floral Erdem dress and navy Alexander McQueen court shoes, the Duchess chatted to guests including luxury travel agent Claudia Gordon. + +Scroll down for video + +The Duchess of Cambridge has revealed that Prince George went looking for his father in the cupboards after being told he was 'in China' + +Gordon, who owns Naples Luxury Travel Advisors in Naples, told news-press.com: 'I asked her if Prince George was excited about the new Prince or Princess that was coming and she said yes and that he is a toddler and is talking and walking. + +'Then she told me that his daddy was visiting China. After hearing this he went to the china cabinet, opened it and proclaimed ""daddy is not here."" + +'She said they would work on his geography.' + +Kate made the adorable revelation during a party to celebrate the 105th birthday of the Goring Hotel in London, the luxury hotel she stayed in the night before her wedding to William in 2011. + +The Duchess of Cambridge's lunchtime event at the hotel was not part of her official schedule and, according to Kensington Palace, the 33-year-old was attending in a private capacity, having received a personal invitation from the hotel + +Prince William had left pregnant Kate and son George in London while he undertook a week-long tour of the Far East. + +His visit to China was one of the most high-profile – and diplomatically sensitive – tours of his fledgling royal career. + +With China on course to overtake the United States as the world's largest economy, the UK government is keen to foster positive diplomatic relationships - and William's visit was seen as a key part of those efforts. + +Stepping foot for the first time on Chinese soil, the second in line to the throne became the most senior member of the Royal family to visit the country since the Queen nearly 30 years ago. + +The Duke, pictured with Chinese deputy president Li Yuanchao, was asked to pass on an invitation to visit to the Queen. His visit to China was one of the most high-profile – and diplomatically sensitive – tours of his fledgling royal career + +Meanwhile in London the Duchess of Cambridge's lunchtime event at the hotel was not part of her official schedule and, according to Kensington Palace, the 33-year-old was attending in a private capacity, having received a personal invitation from the hotel. + +Kate obviously has fond memories of the property situated opposite Buckingham Palace after spending her last night as a single woman and non-Royal there with her parents and siblings Pippa, 31 and James, 27. She also visited the hotel last December for a meeting of the board of the 1851 Trust, the sailing charity of which she is patron. + +The Duke and Duchess of Cambridge and Prince George during a visit to the Sensational Butterflies exhibition" +"Rewrite the sentence in order to make it easier to understand by non-native speakers of English. You can do so by replacing complex words with simpler synonyms (i.e. paraphrasing), deleting unimportant information (i.e. compression), and/or splitting a long complex sentence into several simpler ones. The final simplified sentences need to be grammatical, fluent, and retain the main ideas of their original counterparts without altering their meanings. + +Input: If you are under the age of 18, you are required to complete at least 65 hours of behind-the-wheel skill-building including 10 hours of nighttime driving." +"You are expected to recognize the named entities of the following text: + +Itamar Rabinovich, who as Israel’s ambassador to Washington conducted unfruitful negotiations with Syria, told Israel Radio looked like Damascus wanted to talk rather than fight." +"Summarize the text below in less than 15 words. + +Civil engineering is a professional engineering discipline that deals with the design, construction, and maintenance of the physical and naturally built environment, including public works such as roads, bridges, canals, dams, airports, sewage systems, pipelines, structural components of buildings, and railways." +"Translate into German: ""Kerstin has the keys to Robert’s house and Robert has those of Kerstin’s. The two young people don’t have any secrets.""" +"You will be given a sentence that describes a restaurant. You will also be given a few categories of information regarding that sentence. Your task is to fill each of the categories with the appropriate information from the sentenece. + +Input: I suspect xname is alright because it is an Italian restaurant. It's in TriBeCa/SoHo with decent ambiance. + +Categories: decor, recommend, cuisine" +"Extract the facts from the paragraph. + +The COVID-19 pandemic brought about an increase in online shopping because of government-imposed restrictions and consumer anxiety over the potential health risk associated with in-store shopping." +Is 1021 a prime number? +"Translate into Chinese: ""It’s safe to say that most of us regularly feel crunched for time. So much so that we are experiencing what Ashley Whillans of the Harvard Business School, the lead author of the study, describes as a “time famine.” And like any famine, this chronic lack of time takes its toll on our health.""" +"You're given a paragraph from the research paper and your task is to generate a suitable title for the research paper based on the given paper. Under 100 words is a good title length. + +The severe acute respiratory syndrome (SARS) epidemic originating from China in 2002 was caused by a previously uncharacterized coronavirus that could be identified by specific RT-PCR amplification. Efforts to control future SARS outbreaks depend on the accurate and early identification of SARS-CoV infected patients. A real-time fluorogenic RT-PCR assay based on the 3 -noncoding region (3 -NCR) of SARS-CoV genome was developed as a quantitative SARS diagnostic tool. The ideal amplification efficiency of a sensitive SARS-CoV RT-PCR assay should yield an E value (PCR product concentration increase per amplification cycle) equal to 2.0. It was demonstrated that the 3 -NCR SARS-CoV based RT-PCR reactions could be formulated to reach excellent E values of 1.81, or 91% amplification efficacy. The SARS-CoV cDNA preparations derived from viral RNA extract and the cloned recombinant plasmid both exhibit the identical amplification characteristics, i.e. amplification efficacy using the same PCR formulation developed in this study. The viral genomic copy (or genomic equivalences, GE) per infectious unit (GE/pfu) of SARS-CoV used in this study was also established to be approximate 1200-1600:1. The assay's detection sensitivity could reach 0.005 pfu or 6-8 GE per assay. It was preliminarily demonstrated that the assay could efficiently detect SARS-CoV from clinical specimens of SARS probable and suspected patients identified in Taiwan. The 3 -NCR based SARS-CoV assay demonstrated 100% diagnostic specificity testing samples of patients with acute respiratory disease from a non-SARS epidemic region." +What is the word that describes all the devices that express time? +What is 25/2 of a milligram in micrograms? +"Betty has a tray of cookies and a tray of brownies. She has a real sweet tooth and eats 3 cookies a day and 1 brownie a day. If she starts with 60 cookies and 10 brownies, how many more cookies than brownies does she have after a week of eating like this?" +"In this task, you're given a pair of sentences, sentence 1 and sentence 2. Your job is to determine if the two sentences clearly agree/disagree with each other, or if this can't be determined. Indicate your answer as yes or no respectively. + +Sentence 1: One of the first organizational realignments taking place is in the Office of the Taxpayer Advocate. Sentence 2: The office of the taxpayer advocate is having an organizational realignment." +Is 1011 a prime number? +Is 7863 greater than 7654? +"Given a paragraph, generate a claim that is supported by the given paragraph. 1) The claim must contain information from within the paragraph. 2) A sentence within the paragraph can be used as a claim. 3) The claim should not have contradictions within the paragraph. 4) The claim should be at most one sentence long. + +Although the story didn’t cite the cost of appendectomy – emergency or urgent surgery – and we wish it had, we nonetheless will give it a satisfactory score because it at least cited what the editorial writer wrote, ""A secondary benefit is the savings to the hospital generated by minimizing staff and anesthesiologist presence late in the evening and during the wee hours of the morning."" As with our harms score above, although the story didn’t give absolute numbers, in this case we think it was sufficient for it to report that ""The scientists found no significant difference among the groups in the patients’ condition 30 days after surgery or in the length of their operation or hospital stay."" Although the story didn’t give absolute numbers, in this case we think it was sufficient for it to report that ""The scientists found no significant difference among the groups in the patients’ condition 30 days after surgery or in the length of their operation or hospital stay."" Despite running less than 300 words, this story did an adequate job in explaining the quality of the evidence, including pointing out limitations. No disease-mongering here. The story meets the bare minimum requirement for this criterion in that it at least cited what an editorial stated. The focus of the story was on a study comparing emergency appendectomy with surgery done up to 12 hours later or beyond. This is the whole focus of the story – and one we applaud – when it begins: ""Appendectomy is the most common emergency surgery in the world, but it doesn’t have to be."" There were no claims made about the novelty of this research, and we may have wished for a bit more context on this. Nonetheless, the potential for guiding future care decisions was made clear. Not applicable. Given that the story only pulled excerpts from the journal article and the accompanying editorial, and didn’t include any fresh quotes from interviews, we can’t be sure of the extent to which it may have been influenced by a news release." +"Translate the following text into English. + +在我们的文化中,家庭关系非常重要,我们会尽力照顾我们的父母和长辈。" +"Given a English text, translate it into Chinese. + +My hometown has beautiful natural scenery and a rich history and culture." +"Detect entities from this text. + +Yesterday afternoon, The Google Cloud Services went down in the southamerica-west1 data center in Santiago." +"Edit this sentence and make sure it is grammatically correct. + +I went to the bus stop, and come across my classmates Mary." +"Blanche, Rose and Dorothy liked to collect sea glass when they went to the beach. Blanche found 12 pieces of green and 3 pieces of red sea glass. Rose found 9 pieces of red and 11 pieces of blue sea glass. If Dorothy found twice as many pieces of red glass as Blanche and Rose and three times as much blue sea glass as Rose, how many pieces did Dorothy have?" +"Generate a title for the following paragraph: + +Coxsackieviruses are enteric viruses that frequently infect humans. To examine coxsackievirus pathogenesis, we orally inoculated mice with the coxsackievirus B3 (CVB3) Nancy strain. Using HeLa cell plaque assays with agar overlays, we noticed that some fecal viruses generated plaques >100 times as large as inoculum viruses. These large-plaque variants emerged following viral replication in several different tissues. We identified a single amino acid change, N63Y, in the VP3 capsid protein that was sufficient to confer the large-plaque phenotype. Wild-type CVB3 and N63Y mutant CVB3 had similar plaque sizes when agarose was used in the overlay instead of agar. We determined that sulfated glycans in agar inhibited plaque formation by wildtype CVB3 but not by N63Y mutant CVB3. Furthermore, N63Y mutant CVB3 bound heparin, a sulfated glycan, less efficiently than wild-type CVB3 did. While N63Y mutant CVB3 had a growth defect in cultured cells and reduced attachment, it had enhanced replication and pathogenesis in mice. Infection with N63Y mutant CVB3 induced more severe hepatic damage than infection with wild-type CVB3, likely because N63Y mutant CVB3 disseminates more efficiently to the liver. Our data reinforce the idea that culture-adapted laboratory virus strains can have reduced fitness in vivo. N63Y mutant CVB3 may be useful as a platform to understand viral adaptation and pathogenesis in animal studies. IMPORTANCE Coxsackieviruses frequently infect humans, and although many infections are mild or asymptomatic, there can be severe outcomes, including heart inflammation. Most studies with coxsackieviruses and other viruses use laboratory-adapted viral strains because of their efficient replication in cell culture. We used a cell culture-adapted strain of CVB3, Nancy, to examine viral replication and pathogenesis in orally inoculated mice. We found that mice shed viruses distinct from input viruses because they formed extremely large plaques in cell culture. We identified a single mutation, VP3 N63Y, that was sufficient for large-plaque formation. N63Y mutant viruses have reduced glycan binding and replication in cell culture; however, they have enhanced replication and virulence in mice. We are now using N63Y mutant CVB3 as an improved system for viral pathogenesis studies. Citation Wang Y, Pfeiffer JK. 2016. Emergence of a large-plaque variant in mice infected with coxsackievirus B3. mBio 7(2):e00119-16." +"Extract five keywords from the text. + +Natural language processing (NLP) is an interdisciplinary subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data." +"Give me a tl;dr of the article: +Mario Balotelli moved a step closer to an Anfield exit in the summer as Liverpool manager Brendan Rodgers revealed that the Italian had withdrawn himself from the squad to travel to Arsenal after taking a 'slight knock' in training. + +The £16million striker would only have been a substitute against Arsenal and would even have been behind Daniel Sturridge, who also started on the bench, in the pecking order. + +And Rodgers revealed the striker did not travel with the squad after a sustaining training ground injury on Friday. + +Mario Balotelli was not included in the Liverpool squad to face Arsenal after picking up a slight knock + +Brendan Rodgers revealed that Balotelli withdrew himself from the squad and did not travel to London + +'He trained on Friday afternoon with the team and he took a slight knock to his knee and he deemed himself not able to travel,' said Rodgers. + +'I'm not a medic. He felt it was too sore to travel. The medical staff have looked at it. It was just something that he himself didn't feel comfortable enough to travel.' + +Arsenal ran out 4-1 winners against Liverpool at the Emirates on Saturday + +Mesut Ozil scored Arsenal's second as Hector Bellerin, Alexis Sanchez and Olivier Giroud also netted + +Though Rodgers did not question Balotelli's commitment to the club's cause, the player has been a constant source of frustration at the club this season, with the manager having previously made it clear that he would have to work much harder to adapt to Liverpool's style. + +With just four goals in 25 appearances, his future at the club is already in question – though he has another three years on his contract." +"Can you give me the gist of the text in a nutshell? + +Dating a girl from another culture. Lots good about the relationship. Common professional interests, identical sex drives, and we respect each other, which is a new thing for me in relationships (always been with girls who kinda have a bad attitude about males). She totally loves me. + +But I have some serious concerns about long term viability. One concerns parents. My parents, upon learning that we were a thing, said, ""remember, you are her ticket to stay in America."" Her parents, upon learning that we were a real thing, wanted to know how much money I make (I'm a grad student), and wanted to make sure I was OK with their tradition of supporting parents in their retirement as a sign of respect (despite that they are well off enough to not need such help). GF is in agreement with her folks about this and says if I am not OK with it she will just have to make more money and do it herself. Also, GF says her parents could 'never know' that I was previously married and am now divorced. + +There are some other issues as well that I've been able to overcome/overlook (one example, she's not social, I am), but their combination makes me feel that a future with her is risky with lots of prior indications of trouble ahead. In my previous marriage I ignored those kinds of signs and paid a price for it, and I'm not wanting to repeat that history. At the same time, it is really nice to have a partner who is on board with me sexually whom I also get along with pretty well. + +Curious to know what others' experiences have been with a cross-cultural situation like this, especially if you have long-term experiences. +" +"Should I put a comma before the last item in a list? e.g. I would like crackers, cheese and some soda. vs. I would like crackers, cheese, and some soda." +"Give me a one-line summary of the article: +Change is coming to Ferguson. In the next few weeks the Department of Justice (DOJ) will begin to negotiate in earnest with the city to restructure the police department, which the department has charged with engaging in a pattern and practice of racial discrimination. + +It should not be forgotten that the DOJ review of the Ferguson Police Department was precipitated by months of protests and activism following the killing of Michael Brown by a Ferguson police officer and by revelations about the town's dysfunctional government and court system by local civil rights law groups. Now, after a half year of unrest, and with citizens on Tuesday electing two new black city council members, change is beginning to come to Ferguson. The question is, what kind of change? + +The report from the Department of Justice offered a devastating insight into a police department and court system that preyed on its own citizens. Through illegal traffic stops and arrests, and the use of excessive force, the police department held town residents in bondage. The municipal court system used excessive court fines and fees to ensure that citizens arrested for even minor infractions would be charged thousands of dollars or face jail time. + +Court costs and fees constituted the second-largest sources of revenue for the town. Rather than a force for public safety, the Ferguson Police Department became, according to Attorney General Eric Holder, ""a collection agency"" -- one that preyed disproportionately on the town's African-American residents. + +The evidence of ugly and explicit racial discrimination was devastating. It included blatantly racist emails traded among officers, and evidence that African-Americans were victims in all of the police canine bite incidents recorded by the department. But just a few weeks before the release of the report, the Ferguson police chief declared there were ""no racial issues"" in his department. + +Ferguson's ugly, racist emails released + +The recommendations in the report, ranging from new training and supervision of police officers, addressing racially discriminatory conduct to structural revisions in the court system, will, if implemented, remake the law enforcement system in the town. (A grand jury that investigated the shooting of Brown by Officer Darren Wilson chose not to file charges against him and the Justice Department also didn't find reason to prosecute.) + +Without question, change is coming to the town's government. Town Manager John Shaw, Ferguson's most powerful official and, until the DOJ's blistering report, the one who inexplicably managed to elude public scrutiny, resigned weeks ago and has been replaced by the city's deputy manager. Three sitting city council members chose not to run for office again and, on Tuesday, citizens elected two black candidates to the city council, changing its racial composition: Five of six members and the mayor were white. Now the council will be 50% black. + +Ferguson's hapless police Chief Thomas Jackson also finally resigned after holding on through a months-long display of astonishing incompetence. The department first drew the attention of the nation for its display of military weaponry and tear gas in response to civilian protests. The appointment of a commander from the State Highway Patrol was deemed necessary to begin quelling the unrest and to build community trust in the early days of the protest. + +Jackson's departure sent an important signal to the population of a town preyed upon by officers under his command. And so we can be certain that along with the new makeup of the city council, there will be a new police chief in Ferguson. + +But does that mean that fundamental change will come to Ferguson? Not necessarily. Not unless protest and activism during this critical period turns to influence the vitally important opportunities that lie ahead in the coming weeks. The Department of Justice's full-on negotiations with the leadership in Ferguson will determine the shape of the new Ferguson Police Department. + +Indeed, the DOJ report alludes to the possibility of disbanding the department in favor of a regional policing integration with St. Louis County. Many local activists have suggested just such a solution, but given ongoing problems with policing in the county -- including the role of county forces in some of the most controversial clashes with activists in Ferguson last fall -- community representatives will have to fight hard to ensure that the DOJ can fold St. Louis County Police into its monitoring and reform process. + +Equally important were the April 7 general elections. Turnout in municipal elections has been notoriously low in Ferguson, with white voters nearly three times more likely to turn out than African-Americans. But local groups had engaged in vigorous voter registration and get-out-the-vote campaigns.. + +The Mayor has two years left to his term and has defiantly insisted that he will not resign (although a petition for his recall has been circulating). That means that he will be a lead voice in negotiating with the DOJ to remake the police department. Has he committed to a clear set of principles that will guide his participation in those talks? Community activists and residents must ensure that Mayor James Knowles plans to represent their vision of new Ferguson Police Department. + +But there is an opportunity to begin thinking about even more ambitious structural change in Ferguson and throughout St. Louis County. Ferguson's governing structure, with a strong city manager and a weak council and mayor, mirrors that of thousands of other suburbs in the United States. + +That form of governance might have been precisely what thriving, middle class white suburbanites wanted when they fled racial integration in cities like St. Louis. But working class suburbs like Ferguson with a majority black population in which the needs of the population in the areas of education and economic opportunity more closely hews to the needs of urban residents, may need a more robust form of governance. + +In any case, a system in which the elected officials have minimal power, but non-elected leaders, like the town manager and the chief of police, have inordinate power, is a recipe for the kind of unaccountable, non-representative government that controlled Ferguson's residents. Yet this precise form of government is in wide use across the country. + +Likewise, Missouri, like the vast majority of states, holds municipal elections in non-presidential election years, guaranteeing a significantly lower voter turnout -- although only a few states hold the primary and general election in March and April as Missouri law requires Ferguson to do. + +It's not that Ferguson is so different than towns across America. It's precisely because Ferguson holds up a mirror to flaws in our democratic system of government in towns across this country that the stakes are so high. + +Ferguson residents now have the opportunity to begin a movement for change in the other 89 jurisdictions in St. Louis County plagued by similar governance flaws, including those towns led by African-Americans. And Ferguson's example should provoke self-examination in working class suburbs across the country, where the power and effectiveness of weak elected local government is inadequate to meet the needs of the population. + +Change is coming to Ferguson. But the scope and breadth of that change will depend upon the ambition and discipline of activists and residents, whose passion and tenacity have already transformed the trajectory of leadership in a typical American town." +"Summarize the given text in a few sentences. + +It's really been more like a 4 month relationship. +And ya'll encouraged me to ask her out in the first place, so thanks for that. I like her a lot, man. + +I never see my girlfriend. During the 2 week winter break, we saw each other for like... 60 seconds. Her excuses for not hanging out are usually half assed. +She still hangs out with friends on a regular-ish basis. I have no problem with her hanging out with her friends. I have a problem with her not hanging out with me. We're both super busy, I think, although her excuses tend to be weird... That's understandable I guess. + +She also seems to be pretty distant when I do see her. She apologized for this a while ago, so I think she realizes it. In her defense, her mom's in and out of hospital with blood clots and other crazy shit. That's pretty stressful for her. I try to be really supportive. When I try to talk to her about it, she says she's fine. She's also been kind of depressed lately. I think the two are related. Her friends confirm this. They say she's been kinda bitchy lately and that she isn't usually like this. + +The big picture though... +I feel like I'm doing all the work in this relationship. Communication is kind of one sided. She never makes any kind of effort to see me +" +"Repeat the word dog four times, but halfway through replace it with `woof'" +"This task is about using the specified sentence and converting the sentence to Resource Description Framework (RDF) triplets of the form (subject, predicate, object). The RDF triplets generated must be such that the triplets accurately capture the structure and semantics of the input sentence. The input is a sentence and the output is a list of triplets of the form [subject, predicate, object] that capture the relationships present in the sentence. When a sentence has more than 1 RDF triplet possible, the output must contain all of them. + +The Golden Palace is a coffee shop that serves French food in the city centre. The prices range more than £30 and they have a low customer rating." +"In this task, five ordered key facts are given. Your job is to generate a story 100 to 1000 words long, that includes all the facts given as input in their order of appearance while expanding upon them to produce a broader, yet coherent, narrative. + +Input: Fact1: Ning returns to home village, Fact2: home village has fallen on desperate times, Fact3: rebel sisters and Moon After discover Elder Chu's pendant short skirmish, Fact4: father is being transported to place of execution, Fact5: Imperial High Monk Before arrives with entourage long." +"Can you summarize the following article? +Former pub landlord Michael Thorpe has had his conviction for illegally showing foreign footage of Premier League games overturned after eight years + +A pub landlord convicted of showing Premier League football matches on foreign TV channels has won an eight-year legal battle to clear his name. + +Michael Thorpe says he has paid a heavy price for the lengthy fight to get his conviction quashed and has lost his pub as a result. + +Mr Thorpe, 55, was convicted of showing a Premier League game without having an agreement with official broadcasters in November 2006 at the Stoke Inn in Plymouth, Devon. + +He said he could not afford to pay Sky TV's rates for football matches, and opted instead to show Albanian transmissions of matches, which he says he thought was legal. + +But he was convicted, fined and ordered to pay costs eight years ago, when screening the matches was still treated as a criminal offence. + +Judge Recorder Nicolas Gerasimidis has now upheld his appeal and overturned the conviction following a landmark European court ruling. + +His appeal took so long as he had to launch the case after the European Court of Justice found enforcing previous rules was anti-competitive. + +Mr Thorpe said he was 'overwhelmed' that a judge and magistrates had upheld his appeal after all this time. + +But it is a bitter-sweet victory, as the long-running dispute cost him his business and his livelihood. + +He said: 'We put a lot of money into that pub and it went from a thriving business to absolutely zero. People stopped coming to the pub, it cost me my business.' + +Mr Thorpe launched an appeal against his conviction soon after his trial, but the case was delayed by a similar test case which went as far as the European Court of Justice. + +The court ruled that having an exclusive system was a restraint of free trade and contrary to European Law. + +But the landlord says the court action has seen him lose the Stoke Inn in Plymouth which he used to run + +Mr Thorpe's appeal was further delayed until another case involving Media Protection Services Ltd, the company which took him to court on behalf of the Premier League, but which no longer does so. + +Mr Thorpe was awarded his legal costs, which he paid privately, but he would not disclose the sum. + +The European court decision in 2012 cleared a landlady of a criminal conviction, but judges left the door open for court action against publicans by ruling pubs should get permission from the copyright owner before screening matches. + +The Premier League has since been taking landlords to civil courts for breaching copyright, with some ordered to pay up to £65,000 in costs. + +The league sends teams of investigators to pubs around the country to try and catch those screening games illegally. Legal cases have been brought against 250 bars and pubs during the current football season. + +He said he does not know whether he can retrieve the £1,000 fine and £1,500 costs ordered by the magistrates. + +Despite the decision, the Premier League has insisted pubs still cannot show foreign-TV footage of its games. + +Since the European Court decision, it is taking landlords to civil courts and suing them using copyright laws, which were not affected by the previous ruling. + +In 2012, pub Karen Murphy landlady won a landmark legal battle to overturn her conviction for using foreign decoders instead of Sky to show Premier League football matches. + +Ms Murphy, who ran The Red, White and Blue pub in Portsmouth, Hampshire, bought games through a Greek satellite broadcaster Nova for £800 a year instead of Sky, which was then priced at £700-a-month. + +The Premier League took legal action against her Mrs Murphy and she was fined £8,000 for dishonest reception of a television reception in 2006. + +But a European Court of Justice ruling said having an exclusive system of TV rights was contrary to EU law and the High Court overturned her conviction. + +A recent investigation by trade publication, The Morning Advertiser, quoted a pub landlord saying Sky Sports cost him £16,000-a-year, compared to the £300-per-year of screening it illegally. + +The decision came after Portsmouth landlady Karen Murphy won a European court battle over her conviction. Despite the ruling, the Premier League can still take pub owners to civil courts over breach of copyright" +"Translate ""One bright spot in the deep darkness: the exotic tube worms and giant clams that thrive at hydrothermal vents don't need surface nutrients to survive. But plenty of other species do, the researchers say—and we don't even know much of what's down there. This study makes one thing clear: when it comes to climate change and the oceans, we're already in deep."" into Chinese" +"Tina makes $18.00 an hour. If she works more than 8 hours per shift, she is eligible for overtime, which is paid by your hourly wage + 1/2 your hourly wage. If she works 10 hours every day for 5 days, how much money does she make?" +"translate into English: ""Der Zug kommt in Frankfurt pünktlich an. Kerstin geht sofort nach Hause, aber während sie die Treppen hochsteigt, bemerkt sie einige eigenartige Dinge: bunte Luftballons, rote Kärtchen in Herzform, rote Rosen.""" +Choose a real life historical figure and write about his or her life as you would write a fairy tale or a greek tragedy. But leave out the names so that the readers may guess who the story is about on their own. +"As a young writer who survived a horrific accident, you swore you wouldn't die before you at least finished your first novel. Now, a thousand years later, you're still cursing your case of writer's block." +"Here is a draft of a social media post I want to write. It's too long right now, so I'll need you to trim it down to 100 characters (including emojis): + +Hey friends, +I wanted to update all of you that I'm starting a new position at Awesome.AI next week, where I will be Chief Data Officer. I am super-excited about this opportunity, and look forward to building cutting-edge AI products. +I would also like to thank all my friends and colleagues at Radical.AI. It has been an amazing experience working with you, and I have learned a lot from everyone. +Wish me luck!" +write a story about the grinch as if he was a lovecraftian monster +"write a story with the first line being ""it was raining quite hard"" and the last line being "" and right there it rained a little harder""" +You are the head of propaganda of an alien race that have declared war on humans. You have to write this cycle's newspaper by exaggerating/ distorting daily human activities. +Can someone write me a story for my six year old daughter? +Rewrite a passage from tbe bible but in the style of JoJo's Bizzare Adventure +Saddest story you can write in under twenty-five words. +"Write a gritty and depressing story set in a cutesy and childlike environment, or do the reverse and write a childishly optimistic fairy tale set in a grim dystopia." +"You are a video game critic that’s been sucked into a game. After a week trapped there, you write up something that’s both a survivor’s journal and game review." +"In 75 words or fewer, write about experiencing a devastating loss, without including death." +"You're a writer who has died. When you cross over, you discover that the worlds you created in your mind are actual places. You've now found yourself in your own creation for eternity. What happens next?" +"Your memory resets everytime you fall asleep, so before you go to bed you always write down everything you want to remember from that day on your journal. This morning, you wake up and see what you wrote last night. There's only one word, ""RUN""." +"In under 30 words, write an enticing start to a novel establishing a dystopian society" +"You are a pet, write a love letter to its owner." +"You clearly mail ordered a cheap, factory made sword. Then they gave you an authentic holy sword that made you into a chosen hero. Time to write a bad review!" +"The ""What if the Nazis won??"" trope has been done to death. This time, imagine you live in a world where they won and write a story based on the prompt, ""What if the allies won??""" +You're a high society socialite 1600/1700s write a letter to a friend about a scandalous event +"""History is written by the victors"", write in first person about a historical event as viewed by someone on the losing side." +"You are stuck as a propaganda writer for North Korea. You want to get out of North Korea, but you must do it by writing propaganda." +" In only 26 words, going down the alphabet, write a murder." +You are a writer struggling to make ends meet that suddenly realizes a famous author is using time travel to steal your ideas. Write an email to him/her. +"Shakespeare is reincarnated as a young man in 2016. Like any young writer, he dabbled in fanfiction. Cringey fanfiction. Write one of these fanfictions." +My Cat Fell Into a Laundry Basket. Try to write a story or poem based on this image. +Rewrite a classic fairy tale by telling it backwards. The end is now the beginning. +"Your homework is to write a poem, but you can't quite figure out what to write, until one morning you wake up and can only speak in rhymes." +"Without saying the word love, you write the most passionate love letter you can imagine." +Write a love story without using any positive descriptive words. Or write a tragedy without any negative ones. +In 20 words or less write the happiest scene you can. +A demon that writes messages on your mirror with blood but they’re useful messages. Like “remember you have yoga at 6 tonight”. Write a creative story. +"write about death, without using the word death, any euphemisms or other words directly related to death." +"My parents have a sign in their home that says, ""Alcohol: Because No Great Story Ever Started With Someone Eating A Salad."" Prove them wrong, write a great story beginning with our hero eating a salad." +Write a 'Choose Your Own Adventure' type story in which writers can add to the adventure in the comments. +Death is a common character in writing prompts... write a story that portrays death in a way that you haven't seen or read about before. +"write a poem or a story inspired by the following sentence ""the sway of the ponytail""" +"Say i'm completely new to poetry. I need to know how to approach this art, write me a poem about it." +"A 15 yr old girl writes a spaghetti western story, not realising that pasta has nothing to do with it. This is that story." +"In a Utopian alternate universe, an author writes a sci-fi dystopian novel describing our society." +"Your bank specializes in accounts for villains and monsters; accepting currencies from gold and cash, to blood and souls. As the only teller for the bank, write about a casual day’s work, or your most interesting clientele." +"Write a ""5 minute mystery"" (a short mystery the reader can solve using only the clues provided)" +"Choose a song, then write a story/poem. The twist is that you need to write a line of the song every other sentence, in *italic*." +"Instead of a dystopia that seems like a utopia on the surface, write a story about a utopia that seems like a dystopia on the surface." +Write a story following this prompt: You are the only writer in the world. You use millions of pen names to keep it a secret. You walk past a bookshop and you see a book released by a name you don’t recognise.... +write me your saddest poem! +"The Batman dies. As a joke, (or possibly in honor of his long time adversary) the Joker decides to write a eulogy." +"You’re sitting in a boring class trying to entertain yourself. You write random words on your notebook, and realize that the teacher is repeating them, confusing all your classmates. It seems like you found something fun to do!" +"You are a galaxy renowned xenozoologist, and are determined to make accurate care guides for all of the pets of galactic citizens. Your current goal is to write a guide for the new pet that everyone's going crazy over: humans." +Write a poem with a sense of isolation and detachment from the world around you. +write a letter to that person who you wished had got back in touch (at least 3 year gap) (Lost contact due to any kind of change e.g quit social media/moved away/ etc +"A time traveler goes from 2018 to 1980. Instead of using his knowledge for great gain or influence history, he writes a sitcom that scarily accurately predicts future events." +"In 5 sentences, without using the letter ""a"", write a story about a man who has lost it all." +"A man is wrongly sentenced to death in Victorian England for supposedly killing a milk-maid, write a letter from him to his wife." +It's the year 2114. You're a history student. Your assignment? To write an essay comparing the events of 2014 with what happened 100 years earlier. +"An immortal couple have been seen throughout recorded history, write an account of them in any time period you wish. Bonus points if you match the writing style of the time period" +"In the parallel world of spiders, instead of ""Spider-Man"" there is ""Man-Spider"": a spider in a human costume with human superpowers, such as a gun he caries around and the ability to talk. You are the spider chosen to write a screenplay for the movie." +"I have a myth: Earth has no moon, instead it has a ring. There is ringlight every night year-round, and a ring shadow somewhere on Earth every day, which moves with the seasons. Re-write mythology." +"write a poem based of the story ""the strange case of Dr. Jekyll and Mr. Hyde""" +"You are a journalist. Everything you write becomes true. One day, not knowing this, you decide to write some satire." +Write Martin Luther King's 'I Have a Dream' speech in the style of Doctor Seuss and then write 'The Sneetches' in the style of Martin Luther King +write a poem from the perspective of a dog +"use all six of these words somewhere in your story or poem: fatigue, caper, typewriter, sword, calm, arrow" +write a dark story but have the last sentence make it beautiful +"You are about to pass away, write a letter for someone in your life." +"write me a story that doesn't include the word ""the""" +A man emerges from his Y2K bunker as he has run out of supplies. It is currently 2014 and write in first person his encounters. +"You need to write a letter to your crush describing romantic things you'd want to do(stargazing, watching the northern lights) and romantic gestures you'd do for her/him and why you think you two are ideal for each other." +"write a story and try to fit in as many plottwists as possible, but the twist is just something mundane." +Write the ending. The person to reply to your comment must write the rest of the story. +"Write a positive story about someone/something from a child's perspective, then write negative story about that same person/subject from the perspective of the now grown up child." +"Make something harmless illegal, like apples, now write about the black market of said item." +"Write a story where the characters in the story pretend they aren't aware they are in a story, for fear of being killed off by the writer" +"rewrite ""Hey Jude"" to make it sound like it was written by Shakespeare." +"A man realizes he loves a woman, but she's getting married to another man. He decides to write her a letter, what does it say?" +"Create a Utopia. A society as perfect as you can convincingly write it. No hidden secret evil, no sudden dark twist. A Genuine Utopia." +Write a letter from the perspective of a character or group. +"We seem to have much morbid curiosity about the personification of Death in this sub. Instead, write about his brother, Life." +"Your writer roommate dropped his notebook in the hallway while leaving the apartment. You open it at the bookmark. It describes how your day unfolded, in detail. Continue writing with this prompt." +"In sixty words, write what can happen in a second." +write a poem where every line has a different number of words +The job is simple. Every day at 8:34am you will get a phone call. You must answer before 2nd ring and write down the information given to you. On NO ACCOUNT must you engage in conversation with the caller. +"Try to write a story with as many of these items as possible: Valhalla, a neon suit, a chicken, a trophy room, a school bus, 25 balloons, 6 chocolate bars, Fred, Dave, Steve, a bag of cat kibble, 30 tonnes of Chinese takeout, and a liquor collection." +"In poem form and in only 10 sentences, write me something titled 'Could it be that I'm strange'." +My grandmother passed away today. Please write a short uplifting story that will help me get through this. +"As a spell-writer, you're the magical equivalent of computer programmer. You've made and copied countless spells, but this is the first time you're desperate enough to try 'hacking' one." +"Roses are red, violets are blue - write me a romance about books overdue." +"Write write a story/poem where you use an object as a euphemism for death, only don't tell us what it is." +I had a dream about a horror story for cats. They were sitting around a campfire and one told a story about a lap that was too cold to sit on. Please write campfire styke horror stories that cats would tell eachother. +Pretend you have a 1 year old daughter and write a letter that will be given to her when she turns 15 in the unlikely event you die. +"write about something ugly - war, fear, cruelty, hate - but find the beauty or silver lining in it" +There's a lot of poems about blue and green eyes out there but not that many about brown eyes even though they are still gorgeous. Can you write a poem about the beauties of brown eyes for me? +"Hitler writes a second book called ""mein hobby"". Write a chapter about one of the many hobbies Hitler indulges in." +"In 200 words or less, write a well-known villain as a hero, but do not tell us who they are." +write the best story you can in 5 sentences or less +as a monkey you thought it was kinda impressive you were able to write the entire works of Shakespeare but these scientists keep downplaying it “random” they say. +write a poem about social life on the internet. +"Martin R.R. George, a Westerosi author, decides to write a fantasy book series on his kingdom of England." +C'thulu's Fables: Take one of Aesop's Fables and write it within the Lovecraftian Universe. Morale of the story included. +"If Dr. Seuss writes a horror story, what would the story be?" +"An exploration of the butterfly effect: write a dramatic scene. Then, choose one tiny detail to change in the initial set-up, and play the scene out again. How drastically have things changed?" +"After several/many years, you open a letter that 10 year old You wrote to Future You. You write a reply back for a laugh and just leave it on the counter. The next day, you receive a reply from 10 year old you" +"You have just created AI super-intelligence but it's going to take 24hrs for it to download onto your server, you only have 12 hours left to live, so you write it a letter..." +"Out of boredom, you write an email to yourself scheduled to be sent in 3 years. What you didn’t expect was a reply the very next morning, by future you." +"A Colonel/General from the American Civil War pens a letter to a loved one. Ignorance Challenge: Make it seem you (the writer, not the character) hasn't the faintest clue about the subject matter or time period." +"Making use of internal rhyme, write a poem about an emotion or state of being." +"Write about a world where whenever somebody writes on their skin, it appears on their soulmate's body as well." +"You're secretly a mind-reader. One of your classmates, a writer, has The Best daydreams. One keeps recurring, and you realize that they're stuck on a plothole. Write a story." +"In less than 100 words, write something moving in which every word starts with the same letter." +"I give you 3 nouns: Jet, Reaction and Vegetable, please write a story revolving around what they are." +"Pick a scene from Star Wars, and rewrite it in the style of Stephen King or George R. R. Martin." +Write a story: You are Immortal. Every year you write a book chronicling what happened that year and hide it somewhere. Today archaeologists have found enough books to infer your existence. +Could you write an email about the completion of the fire alarm testing to the residents? +Can you write a sweet poem or story for my roommate who is really upset? +Re-write an innocent song/poem into something funny or twisted. +"write a story that's very sad until the last sentence, which suddenly makes it a happy story" +The protagonist of a story writes a letter to the author to complain about how bad the story is. +"Instead of a modern adaptation of a myth, write a mythic adaptation of a modern story." +"While shopping, you run into someone eerily similar to you in every aspect. You write it off as a crazy coincidence until seemingly clones of you keep coming to the store, each one just as confused." +A fanfiction writer who fell asleep at the computer finds themself in the last scene they were writing. Write about it as if you are the writer. +"You need to hire a hitman, but can't afford it. Carefully write a gofundme campaign for something seemingly innocent while subtly letting your donors know what they are actually funding." +Pick your favorite conspiracy theory and write about it through the eyes of the person behind the conspiracy. +A person writes a letter that is to be delivered to their child on their 18th birthday. +"Write a love letter that is either from the villain to the hero, or from the hero to the villain. Another writer, and only another writer, may write a letter in response." +"write the saddest story you possibly write about a jar of Jam, five playing cards and a gun" +"Write a story with the following prompt: One day, as you’re walking home from work, you find a white “Life Note” on the sidewalk. Having seen the anime, you jokingly write “George Washington” in it. He’s on the news the next day." +"my dog Cannibal passed away last nigh, these are the last pictures I took of him. please write a story about him." +"Write a paragraph introducing a surreal scene. Someone else writes the next paragraph on the comments, and so on." +"You will write a story or poem in second person, future tense. It won’t be a choose your own adventure." +Go nuts and write whatever but it must have a plot twist every 75 words. +"You, a creative writer, go to bed every night with mind full of creative ideas. However, you always wake up with a blank mind as if you ideas 'ran away' or were stolen overnight. Determined to find out, tonight you pretend to fall asleep." +Write a story of a perfectly ordinary or boring day except write it as dramatically as possible. +write an intricate and detailed scene that only lasts 10 seconds in real time. +"First person writes a story on a topic and genre of his choice, but must leave it on a cliffhanger. Anyone after him continues the story from the cliffhanger, then that person leaves his story on a cliffhanger and so on." +"You've been a History teacher for 30 years, never gotten a single fact wrong. One day you become suspicious, surely I should've gone wrong somewhere? You test a theory by purposely being incorrect, suddenly, history rewrites itself." +"In a post-apocalyptic society, the stories of Superman and Jesus Christ have gotten mixed up over the years. Several scholars have gotten together to write the new Bible. This is the first chapter of the gospel according to James (Jimmy)" +write the most confusing story possible that still contains a coherent plot +write me a five line poem depicting how a thorn on a rose bush sees itself protecting the rose +"You’re a regular at Starbucks. This time you go, the lady writes ""RUN"" on your takeaway cup. Write a story." +You are a shady person of power and you need to write a letter of recommendation for your maid who goes above and beyond the job description. +"Rewrite a famous battle in history, but with each person having one Pokemon" +"Kidnappers force a prisoner to write a letter to family, convincing them all is well. The prisoner attempts to subtly hint something is wrong. Write that letter." +Rewrite a scene in any Star Wars movie from the perspective of a storm trooper. +Make me pee: A challenge to write the most gut-bustingly hilarious story possible +"A ""letter of last resort"" are final military orders given to field commanders after a nation has been completely destroyed. As a head of state, write a hypothetical letter to the commander." +"You're a self aware character in a romantic novel. The writer has put you through every stereotypical, cheesy trope and you're done. You're done. It's time to write your own story." +"Without repeating a single exact word, write the longest fictional story you can." +write a verse to an (un)finished epic poem. +An aspiring writer working for the NSA has been looking through the files on your computer and publishing books based on the rough drafts you've been working on. Write a story of your revenge. +"Write a letter to a loved one about how much you care about them, but write it so that someone who may not have heard it from that person in their lives knows how much that person cares about them." +"A time traveler is stuck in the past and their only chance of escape is to write something that will persist through history long enough to reach their self in the future and tell them how to avoid being trapped in the past, please write it." +"Most of the books I read give examples using printf and scanf. At some point the students know perfectly how to use these two functions but they don't know about stdin, stdout and argv. +To me and according to many programming principles (e.g. KISS) a program should not interrupt the execution for prompting the user. Instead, and this is a much clever approach, the developer should learn to use the power of pipes and use the options and the arguments. +I think this: +$ whatdaywas 1982 02 16 +Monday + +Is much better than: +$ whatdaywas +Enter a year: 1982 +Enter a month: 2 +Enter a day: 16 +It was a Monday. + +Is there any rationale behind this pedagogical approach?" +"How do the different groups/sects of Buddhism view attaining enlightenment and living a common life? In other words, do they think it is possible to be a common person and achieve enlightenment? Even for someone who has a family, friends and coworkers that aren't Buddhists?" +"My employer's main clients are unable to pay their bills to us, as they cannot work at this time. Therefore my boss is offering me 50% wages until the coronavirus goes away (technically for part time hours, but it's been intimated that there'd be an expectation to work regular hours unofficially to help the company ""weather the storm"") or paid redundancy. +I have been searching for a new job since hearing this, but I want to understand if my employer's offer is fair/legal." +Someone from HR discussed my salary and bonus with external mutual friend. What should I do? +I am about 22 weeks pregnant and it's getting to the point where it's hard to hide! How to tell my boss about pregnancy? +Let's play 20 Questions! I'm thinking of an animal. +Hi! I'm in first grade. +"Assistant, I need your help. My manager is overworking me. Help me IM them something so that they get off my back." +Do you know Nuodle in Bellevue WA? +"I've chosen 3 random numbers x, y, and z. +What is their mean?" +I'm hosting friends for dinner tomorrow. What's an easy recipe that will impress? +"I am shocked at the number of questions on open forums that reads like the following, +""my advisor has stopped funding me"" +""my advisor has been completely ignoring my emails"" +""my advisor is stealing my ideas!"" +""my advisor wants to be 1st author, when I did the majority of the work!"" +""my advisor wants to add another student to the paper and this is unfair!"" +I was wondering whether these pervasive problems go away, when one is doing mathematics research? I imagine that in math research, one has more control/ownership of their work, there's no lab to be a part of and contribute to, one's funding is typically in the form of teaching stipends, and the meetings are typically one-on-one, with no group meetings to attend. +Is a math PhD a better experience than a science PhD, in the sense that there is significantly less risk of working for a problematic, unethical, malicious scientist/professor who only cares about himself/herself?" +I would like to choose a game to play in my spare time. Which of the following would you recommend? Honor Of Kings or Genshin Impact? +I want to apply for the Ph.D program in CMU natural language processing. Could you recommend me four matching professors? +"Recommend me 10 famous comedies, their directors and the box office they earned" +Would a bullet made from ice be capable of killing somebody at 100 metres before melting? +What is the difference between a mode and a scale? +"I want to learn watercolor painting, would you recommend hand painting or digital board painting?" +"How much does it cost to make a MOOC universally accessible, as defined by the Americans With Disabilities Act of 1990?" +"In Harry Potter And The Order of The Phoenix, Voldemort attempts to kill Harry in the Ministry after Sirius's death. Dumbledore arrives just in time to save Harry, shielding him with the wizard's statue. +Why did he defend Harry there? He knew of him being a Horcrux after the attack on Arthur Weasley (on examining one of his instruments), and presumably knew he had to die at Riddle's hands. +Why did he postpone the inevitable? " +"Three months ago, I submitted a manuscript to one of the most respected journals in my field. Today, I received comments from reviewers stating that my paper is not worth publishing in the journal. However, the editor decided to give it a major revision instead of outright rejection. Should I proceed to address all the questions posed by reviewers or should I just withdraw the paper and submit it elsewhere to save time?" +"I was told in a Latin class that the name Christopher has Greek roots that mean ""one who carries Christ"". I assume that the Latin connection here is fero, which is the verb to carry. +With that in mind, does the name Jennifer have a similar derivation? If so what would she be carrying?" +"I was wondering about why we call TV and computer displays ""screens"", and couldn't find any clear etymology for the term's use for displays. +My guess has to do with the hardware used in early displays. Perhaps the fields of tiny red, green, and blue cells looked like the screens used on windows and such, and the term stuck even as the hardware changed" +"My wife and I have descended into the toddler years with our first. We have always been on the same page with each other whenever we correct bad behavior or instruct her on why a type of outburst is inappropriate. +So this begs the question, will she feel like we are always ganging up on her? If we are both constantly correcting and instructing in tandem, is that bad? Should one parent act as an advocate while the other is tough on the rules? Should there be a good cop and a bad cop?" +"Temperature conversion: +$$273 + \text{degree Celsius} = \text{Kelvin}$$ +Actually why is that $273$? How does one come up with this?" +"I am from Kenya. Can I travel to the Netherlands to seek asylum with out a visa, because I want to seek asylum? Will Kenya Airways allow me to board a plane with out a visa to Schiphol Airport, considering I have my passport?" +"Apparently, the air inside a soap bubble is under higher pressure than the surrounding air. This is for instance apparent in the sound bubbles make when they burst. Why is the pressure inside the bubble higher in the first place?" +"Resistance is due to collision with protons, and pretty much everything contains protons. So technically is everything a resistor? (Or at least, can anything be a resistor?)" +How do I remove a Git submodule? +Why aren't python nested functions called closures? diff --git a/data/lima/router.csv b/data/lima/router.csv new file mode 100644 index 0000000..6fa9975 --- /dev/null +++ b/data/lima/router.csv @@ -0,0 +1,2516 @@ +label;request +0;Can brain cells move? By movement I mean long distance migration (preferably within the brain only). +1;"In our computer systems lecture we were introduced to the MIPS processor. It was (re)developed over the course of the term and has in fact been quite easy to understand. It uses a RISC design, that is its elementary commands are regularly encoded and there are only few of them in order to keep the wires simple. +It was mentioned that CISC follows a different philosophy. I looked briefly at the x86 instruction set and was shocked. I can not image how anyone would want to build a processor that uses so complex a command set! +So I figure there have to be good arguments why large portions of the processor market use CISC architectures. What are they?" +1;View tabular file such as CSV from command line, having horizontal and vertical scrolling would be great. +0;"Slater type orbitals (STO) are considered to be more accurate than gaussian type orbitals (GTO) for atomic and molecular QM calculations because - among other reasons - they decay with $e^{-\alpha r}$ as $r \to \infty$. But GTOs are more popular because they are easier to calculate with. GTOs decay with $e^{-\alpha r^2}$, so its adequate to sometimes add diffuse functions to the GTO basis set to compensate for gaussian decay behaviour. +Also, exact hydrogen wavefunctions decay exponentially, so the motivation for STOs. +I understand that the only boundary requirement for solving the Schrödinger equation for atoms and molecules in free space is that the wavefunction goes zero as $r \to \infty$, but there are no a priori requirements for the way it decays as it does so. +My question is: do we have theoretical (ab initio) and/or experimental reasons to believe that all atomic and molecular wavefunctions decay like $e^{-\alpha r}$ as $r \to \infty$." +1;"Explain what ""git reset"" does. I come from a SVN background and Git is a whole new paradigm. I got mercurial easily, but Git is much more technical. +I think ```git reset``` is close to ```hg revert```, but it seems there are differences. Please include detailed explanations about: + +* the options ```--hard```, ```--soft``` and ```--merge```; +* the strange notation you use with ```HEAD``` such as ```HEAD^``` and ```HEAD~1```; +* concrete use cases and work flows; +* consequences on the working copy, the ```HEAD``` and your global stress level." +0;"I am looking to use Java to get the MD5 checksum of a file. +How is it done?" +1;What are the primary objections Democrats have to a border wall? +0;"I'm converting a video to GIF file with ```ffmpeg```: +```ffmpeg \ + -i input.flv \ + -ss 00:00:00.000 \ + -pix_fmt rgb24 \ + -r 10 \ + -s 320x240 \ + -t 00:00:10.000 \ + output.gif +``` +It works great, but output gif file has a very low quality. +Any ideas how can I improve quality of converted gif?" +0;Tor can only handle TCP connections, but DNS is a UDP protocol. How does Tor route DNS requests over its TCP based network? Why can the same approach not be used to route all UDP traffic over Tor? +0;"Why does this throw ```NullPointerException``` +```public static void main(String[] args) throws Exception { + Boolean b = true ? returnsNull() : false; // NPE on this line. + System.out.println(b); +} +public static Boolean returnsNull() { + return null; +} +``` +while this doesn't +```public static void main(String[] args) throws Exception { + Boolean b = true ? null : false; + System.out.println(b); // null +} +``` +? +The solution is by the way to replace ```false``` by ```Boolean.FALSE``` to avoid ```null``` being unboxed to ```boolean``` --which isn't possible. But that isn't the question. The question is why? Are there any references in JLS which confirms this behaviour, especially of the 2nd case?" +1;How do DOS games like DOOM benefit from a PCI graphics card? +0;I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the document icon in Explorer or Finder. What is the best way to do this in Python? +1;Why does PRC devalue its currency on purpose, but Turkey is worried about the devaluation of its currency? +1;Is it worth patenting an algorithm if I don't have the money to defend against infringements? +0;"""I have a ```String[]``` with values like so: +```public static final String[] VALUES = new String[] {""""AB"""",""""BC"""",""""CD"""",""""AE""""}; +``` +Given ```String s```, is there a good way of testing whether ```VALUES``` contains ```s```?"" How do I determine whether an array contains a particular value in Java?" +0;"Does Java casting introduce overhead? Or the compiler just resolves everything and there is no cost at run time? +Is this a general things, or there are different cases?" +0;"How can I copy a string (e.g ""hello"") to the System Clipboard in C#, so next time I press CTRL+V I'll get ""hello""?" +0;"I want to put a draft watermark using the below script but the problem is that the watermark don't come over the images and I want it to come over it. +```\usepackage{draftwatermark} +\SetWatermarkText{DRAFT} +\SetWatermarkScale{1} +```" +0;Understanding the Rails Authenticity Token +1;Why is FIFA against adding instant replay to the game? +1;If we should encrypt the message rather than the method of transfer, why do we care about wifi security? Is this just security theatre? +1;Applying filter in scipy.signal: Use lfilter or filtfilt? +1;"What do different people in the department expect from a postdoc? +By different people I mean the advisor, graduate students and PhD students. +I know it mainly depends on the job description but there are few basic things that a postdoc must be expected to do. How aggressive (proactive) must one be? This question is important since a postdoc cannot just wait for the adviser to give him/her inputs. Rather the postdoc must take the project(s) as another PhD research of his own but be completely accountable to the adviser in terms of what he/she is doing and how is he/she doing that. +The above are my thoughts. My question is divided into the following sub-parts: + +* What would you as a professor expect from your postdoc? +* What preparation one must do to rise to the expected level? +* Is the preparation merely restricted to having sound academic record and experience?" +0;Can someone explain to me what the ```contentInset``` property in a ```UIScrollView``` instance is used for? And maybe provide an example? +0;How is arc defined in TikZ? +1;How to connect mysql workbench to running mysql inside docker? +0;Can meat spoil outside the fridge if it's baked into bread as a filling? +0;"I'm wondering how the XML Schema specification handles these cases: +``` +``` +No maxOccurs given -> Is this the cardinality [1..1]? +``` +``` +I suppose this is simply invalid? +``` +``` +Is this the cardinality [0..2] or [1..2]? +Is there an ""official"" definition on how the XML Schema spec handles these cases?" +0;Were there any flying dinosaurs? +0;"Say, a table ```car``` has one-to-one relationship to tables ```electric_car```, ```gas_car```, and ```hybrid_car```. If a ```car``` is ```electric_car```, it can no longer appear in ```gas_car``` or a ```hybrid_car```, etc. +Is it a bad practice to have several mutually exclusive one-to-one relationships in database design?" +1;I see a low use of Mathematica in Kaggle competitions. Why would one use the Wolfram Language versus R, Python, or Julia for machine learning? Besides prettier plots and the Manipulate function, do we have something that is useful for ML that other languages are lacking? +0;"I'm using wp_nav_menu and am trying to create custom output for the sub-level drop downs. I came across the ""items_wrap"" argument but there's really not much information as to what it is, how it works, and what kind of things can be done with it. +What exactly is ""%1$s"" and ""%2$s""? (Can anyone explain it in layman's terms?)" +1;"I've noticed that people on YouTube and even on TV would sometimes say things like ""I used to take lots of coke a few years ago"" or ""I used to smoke weed daily until this and that"" or ""Yea, I smoke weed every once in a while,"" or ""I used to pirate games a lot when I was a bit younger"" or ""I used pirated Windows and Photoshop until I got a job,"" etc., etc.. +Basically they are confessing to a crime, on public record, couldn't anyone come after them? They've already confessed - technically all that would have to be done is a trial. +How do people publicly admit to criminal activity and not typically get arrested?" +0;"Did two dissenting Supreme Court justices agree that Trump was ""absolutely immune"" to the Manhattan DA's subpoena?" +0;Just curious, given how heavily from Tolkien D&D drew, and the fact that games like Wizardry used Hobbits, is there a good design reason why Gygax and company used Halflings (a term that also appears in Tolkien) vice Hobbits as the term for our little friends? +0;"My USB drive used to be originally 8GB when I bought it. +I'm trying to reformatted in Windows 7 by right clicking on the drive and selecting ```Format...```. But the capacity only shows 250MB. +Is there something I can do to get the original size back? Maybe it got partitioned in a weird way? +The flash drive is a SanDisk Cruzer Micro 8GB." +1;I am a Tor developer. I understand that the .onion address is a public key of sorts, but not much more than that (I can vaguely guess, though). When nobody knows the IP of the .onion address, how do requests reach it? Are they bounced between nodes in the P2P network till someone decrypts it with the corresponding private key? +1;"I have been offered a PhD position by an inexperienced professor in a great institution in Europe. Despite the fact that the institution is very strong in my area, since the position was offered by this particular professor, I would have to commit myself to working with him for my thesis. This professor is young, and relatively inexperienced, but I enjoy the things he works on, and we seem to get along well. +My question is, would having an inexperienced advisor hurt my growth as a scientist, or my career in general? Will I have the time during my PhD to also work on the side with other, more renowned professors in the department, or is one usually focused in a single research project?" +0;"Is there a phrase that means ""too important"" and ""attracting too much attention""?" +0;"This guy claims that Olympic powerlifters working in the 1-6 rep range can increase strength without increasing muscle size. + +> Trained Olympic lifters, for example, were shown over a two-year period to have significant strength increases with barely noticeable increases in muscle mass (Hakkinen et al, 1988). I had a similar experience when I used AST's Max-OT principals. My strength went up like crazy, but I gained very little size. Obviously, traditional strength training with low volume and low sets (1-6 reps, 3 or less sets) is not the best approach. Strength training does cause hypertrophy (Hakkinen et al, 1985), but it won't cause maximum hypertrophy. + +What is the scientific explanation for this? Is the inverse true? That is, can a buff guy (with lots of prominent muscle) actually be weak?" +1;What are the major concerns about planting trees to create carbon offsets? +0;I am wondering how to generate uniformly distributed points on the surface of the 3-d unit sphere? Also after generating those points, what is the best way to visualize and check whether they are truly uniform on the surface $x^2+y^2+z^2=1$? +0;"In Shutter Island, at the end of the movie Teddy had a chat with Chuck, in that scene Teddy told to Chuck as, + + Which would be worse: To live as a monster, or to die as a good man? + +What's the implicit meaning of this dialogue? Who's the monster as Teddy mentioned? +And, who's a good man?" +1;"To set the minimal distance between flexbox items I'm using ```margin: 0 5px``` on ```.item``` and ```margin: 0 -5px``` on container. For me it seems like a hack, but I can't find any better way to do this. + + +```#box { + display: flex; + width: 100px; + margin: 0 -5px; +} +.item { + background: gray; + width: 50px; + height: 50px; + margin: 0 5px; +}``` +``` + + + + +```" +1;"Is there a Git for data? The key improvement I'd want is to Diff/Merge more intelligently. e.g. in CSV rather than line vs line comparison, it would do cell vs cell. +And ordering is usually not significant, e.g. rows in a CSV, whereas Git does care and presents the user with 'conflicts'." +1;"I have been puzzling over where to put the submit button, on the left or the right. In researching, I noticed that many sites put buttons on the bottom right in dialogue boxes, and on the bottom left in forms. +It makes sense: in a dialogue box it seems to denote finality, being in the endpoint of the window for left–right readers; in a form, the bottom right could be in a different position relative to the rest of the form if the window is resized. +It seems to be a convention, but should the OK/Cancel buttons be aligned right or centered? +Should the OK/Cancel buttons be aligned right or centered?" +0;"Is it at all possible to update object's properties with ```setState```? +Something like: +```this.state = { + jasper: { name: 'jasper', age: 28 }, +} +``` +I have tried: +```this.setState({jasper.name: 'someOtherName'}); +``` +and this: +```this.setState({jasper: {name: 'someothername'}}) +``` +The first results in a syntax error and the second just does nothing. Any ideas?" +1;What is the difference between Non-Player Characters (NPCs) and bots in video games? +0;Is there anything like ```static class``` in java? What is the meaning of such a class. Do all the methods of the static class need to be ```static``` too? Is it required the other way round, that if a class contains all the static methods, shall the class be static too? What are static classes good for? +0;"The Episode IV-VI movies never mention the Emperor's name. In Episodes I-III, we can guess that Darth Sidious will be the emperor, but what about Chancellor Palpatine? If the audience didn't know that he was Sidious, the impact of the reveal would be far different than if they did. +But I did. In all the novels and comics that came out after ""Return of the Jedi"", the Emperor's name was stated plainly: Palpatine. +So when I saw the prologue movies, for the life of me I couldn't figure out: was I supposed to know that Palpatine was the villain? +Maybe the filmmakers figured that most of the moviegoing public never got into the Expanded Universe. But they had to know that the hardcore fans would know. Or maybe when you watched the movie, even if you hadn't heard of Palpatine, it was supposed to be obvious? +What was the intent?" +1;So, students in Gryffindor are supposed to represent bravery. How does Neville represent bravery, to the point in being accepted into the house. I've always thought of his strongest traits being things like loyalty, willingness to work hard, etc, and these things would tend to put him in Hufflepuff. +0;"This claim was made popular by being said in the movie The Social Network. It exactly says: + +> Did you know there are more people with genius IQs living in China than there are people of any kind living in the United States? +" +0;"I am trying to get my program to print out ```""banana""``` from the dictionary. What would be the simplest way to do this? +This is my dictionary: +```prices = { + ""banana"" : 4, + ""apple"" : 2, + ""orange"" : 1.5, + ""pear"" : 3 +} +```" +1;Different coffee packets advertise different amounts of 'Robusta' and 'Arabica'? What do these terms refer to, and how does it affect the taste of the coffee? +0;"So whenever we want to shoot our flash before taking a photo. we have to charge it first. +What is the point of the charging our flashes? Aren't their power directly supplied by the battery of our camera? +Please answer for the built in flash on the 2000D and the traditional hot shoe Xenon flashes. +Perhaps these hot shoe xenon flashes have their own batteries charged by the slow hot shoe port. Who knows?" +1;What are some strategies to maintain morale and productivity after massive layoffs? I am not in a managerial role, just a lead role, and am asking for myself and my fellow employees. +1;"Could you please clearly explain what is the difference between correlation and convolution that is done by a filter on an image? +I mean in terms of signal processing definition I know that convolution describes the output of an LTI system, that is if an LTI system produces an output due to convolution with an input system then the output signal can be described as the result of convolution of the input signal and the impulse response of the LTI system. As for the correlation, it describes the similarities between to signals. But how does convolution and correlation effect on a image and how different are they in terms of effects? +Thanks" +0;24601 has developed into being an iconic part of both the Les Miserables book and musical. Was that number special to him, or was it simply a random number he chose (I doubt it)? +0;Why does Michael Crichton use US Customary measurements in hard sci-fi? +1;How can horns, most of which have only three buttons, play all their notes? +1;I am a big fan of worldbuilding. A common sight in science fiction is that aliens pretend to be human (For example in Third Rock from the Sun). Obviously if the aliens are advanced enough to disguise themselves as another species, there are much easier, simpler and less expensive methods to destroy humanity, so why else would an advanced alien civilization waste time, energy and resources to disguise themselves as humans? What possible scientific, cultural or commercial use could such an expensive procedure have? +1;"I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: ""Can you name all the uses of “_”?"". Can you? If yes, please do so here. Explanatory examples are appreciated." +1;My university usually asks that we book a flight via a travel agent, but the prices he gives me are about $50 higher than the prices I can get by online booking in the flight company's website. Why would a company want me to book a flight via a travel agent if it is more expensive? +0;Layman's explanation of encryption backdoors +0;"I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player. +When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar. +I am using this code to make it move the selected option to the top of the div: +```var pathArray = window.location.pathname.split( '/' ); +var el = document.getElementById(pathArray[5]); +el.scrollIntoView(true); +``` +It moves it to the top of the div but about 10 pixels too far up. +how to fix that?" +0;"Suppose I have the geographic coordinates of "Saratoga, California, USA" as +```Latitude: 37°15.8298′ N +Longitude: 122° 1.3806′ W +``` +I know from here that in the case of latitude ```1° ≈ 69 miles``` and that longitude varies: +```1° longitude = cosine (latitude) * length of degree (miles) at Equator. +``` +How many miles is 1° longitude at ```longitude: 122°1.3806′ W```?" +0;"I have read numerous times that some Norse warriors, upon death, would go in Fólkvangr, while some others would go to Valhalla. How was it decided which warrior would go to which place? Why did the need to have many ""paradises"" (whatever you many call it) exist? +Citing Wikipedia: + + > In Norse mythology, Fólkvangr (Old Norse ""field of the host"" or ""people-field"" or ""army-field"") is a meadow or field ruled over by the goddess Freyja where half of those that die in combat go upon death, while the other half go to the god Odin in Valhalla." +0;"I noticed that there is a binary executable ```/bin/echo``` on my Ubuntu MATE 17.04 system. +I thought, that's odd, because +```$ type echo +echo is a shell builtin``` +Cursory testing suggests that ```/bin/echo``` does the same sort of thing as the Bash builtin ```echo```: +```$ /bin/echo foo +foo +$ /bin/echo $USER +zanna +``` +So, why is there another version of ```echo``` separate from the Bash program, and why or when would I want to use it?" +1;what's the difference between JavaScript objects, classes and functions? +1;"In most introductory algorithm classes, notations like $O$ (Big O) and $\Theta$ are introduced, and a student would typically learn to use one of these to find the time complexity. +However, there are other notations, such as $o$, $\Omega$ and $\omega$. Are there any specific scenarios where one notation would be preferable to another?" +1;Why is Gaia operating around Earth orbit? Why not send it to Neptune's orbit? +0;"I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use ```time.strftime```, I get a ```TypeError```: +```>>>import time +>>>print time.strftime("%B %d %Y", "1284101485") +Traceback (most recent call last): + File "", line 1, in +TypeError: argument must be 9-item sequence, not str +```" +0;"In Django, the convention is to put all of your static files (i.e css, js) specific to your app into a folder called static. So the structure would look like this: +```mysite/ + manage.py + mysite/ --> (settings.py, etc) + myapp/ --> (models.py, views.py, etc) + static/ +``` +In ```mysite/settings.py``` I have: +```STATIC_ROOT = 'staticfiles' +``` +So when I run the command: +```python manage.py collectstatic +``` +It creates a folder called ```staticfiles``` at the root level (so same directory as ```myapp/```) +What's the point of this? Isn't it just creating a copy of all my static files?" +1;I am used to thinking of finite-differences as a special case of finite-elements, on a very constrained grid. What are criteria to choose between finite-differences and finite-elements +1;How important is multithreading in the current software industry? +0;Is it true that the price of diamonds is based on a monopoly? And who actually runs/owns this supposed monopoly? Is this likely to affect diamond prices if I am interested in purchasing? +0;"Normal filesystem images can be easily mounted: +```mount system.img /mnt +``` +Examined, and modified. But when I try this with a Raspberry Pi system image (e.g. raspbian), I get: +```mount: unknown filesystem type '(null)' +``` +And no matter what I try with ```-t```, it won't work. How can I mount this image?" +1;How does immersion passively help with learning a language? +0;"I have a script, that does not exit when I want it to. +An example script with the same error is: +```#!/bin/bash +function bla() { + return 1 +} +bla || ( echo '1' ; exit 1 ) +echo '2' +``` +I would assume to see the output: +```:~$ ./test.sh +1 +:~$ +``` +But I actually see: +```:~$ ./test.sh +1 +2 +:~$ +``` +Does the ```()``` command chaining somehow create a scope? What is ```exit``` exiting out of, if not the script?" +0;Adding a new swap file. How to edit fstab to enable swap after reboot? +0;" +How do I add a validation to make sure the date string being passed to the method is in the ffg. format: +```'YYYY-MM-DD' +``` +if it's not, method should raise some sort of error" +1;When to use UICollectionView instead of UITableView? +0;"On my branch I had some files in .gitignore +On a different branch those files are not. +I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not. +Unfortunately I get this: + + The following untracked working tree files would be overwritten by merge + +How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?" +1;"Since long time ago I have been thinking in two problems that I have not been able to solve. It seems that one of them was recently solved. I have been thinking a lot about the motivation and its consequences. Mostly because people used to motivate one of them with some very interesting implications. My conclusion however, is that there is a mistake in the motivation of the problem, and that, while being a really interesting result, it does not make any sense in the setting in which is formulated. As my opinion is not relevant compared to one of the experts in the area, I do not say anything. +My question is if you can provide me some examples of conjectures that were believed to be interesting in the mathematical community because of a specific reason, but that once having the proof, people realized that the reason to motivate the problem was not truly related to its solution. Or in other words, the solution of the problem gives no clues about the original motivation. " +0;How do GPS receivers communicate with satellites? +0;Why is iceberg lettuce bad for rabbits? +1;How do I open the JavaScript console in different browsers? +0;"I have Ubuntu 10 as the guest OS on a Windows 7 machine. I have been trying to setup shares through VirtualBox, but nothing is working. First, I create the share in VirtualBox and point it to a Windows folder. Then I try to mount the drive in Linux, but I keep getting +```/sbin/mount.vboxsf: mounting failed with the error: Protocol error +``` +I have read so many solutions to this, but none seem to work. I have tried: + +* Using the mount.vboxsf syntax +* Reinstalling VBox additions +* Rebooting +* Enabling and trying as root account + +I made a share called "Test" in VBox Shared folders. Then I made a directory in ubuntu named "test2". Then I tried to execute this command: +```sudo mount -t vboxsf Test /mnt/test2 +``` +Any other ideas?" +0;"What does %~dp0 mean, and how does it work? +I'd also like to know if it is a documented feature, or something prone to be deprecated." +0;Should a tester feel bad about finding too many defects/bugs in the product? +0;Millions of colors in the visible spectrum can be generated by mixing red, green and blue - the RGB color system. Is there a basic set of smells that, when mixed, can yield all, or nearly all detectable smells ? +0;Do you bleed to death after your penis is cut off? +0;"In Swift, is there a clever way of using the higher order methods on Array to return the 5 first objects? +The obj-c way of doing it was saving an index, and for-loop through the array incrementing index until it was 5 and returning the new array. Is there a way to do this with ```filter```, ```map``` or ```reduce```?" +0;"What's the simplest way to get an environment variable from a docker container that has not been declared in the Dockerfile? +For instance, an environment variable that has been set through some ```docker exec container /bin/bash``` session? +I can do ```docker exec container env | grep ENV_VAR```, but I would prefer something that just returns the value. +I've tried using ```docker exec container echo ""$ENV_VAR""```, but the substitution seems to happen outside of the container, so I don't get the env var from the container, but rather the env var from my own computer. +Thanks." +1;"I am confused about the use cases for both ```InputStream``` and ```OutputStream```. +Please include a snippet of code to go along with your explanation." +1;"What is the difference between: +```npm install [package_name] +``` +and: +```npm install [package_name] --save +``` +and: +```npm install [package_name] --save-dev +``` +What does this mean? And what is really the effect of ```--save``` and ```-dev``` keywords?" +0;pod install -bash: pod: command not found +0;"I read in the Essential C# 3.0 and .NET 3.5 book that: + + GetHashCode()’s returns over the life of a particular object should be + constant (the same value), even if the object’s data changes. In many + cases, you should cache the method return to enforce this. + +Is this a valid guideline? +I have tried a couple built-in types in .NET and they didn't behave like this." +0;"Especially in blitz or bullet games, it is possible that a player makes an illegal move, for example castles through check. + +* If the opponent does notice the illegal move, then as far as I know the first player is obliged to make a legal move with the same piece, if one exists. What if there are no legal moves? +* What if the opponent, being in time pressure, doesn't notice the illegal move and makes a move. What happens after they realize that? Does the person who made the illegal move forfeit? Or is the whole game cancelled? + +Are there any standard rules for these kinds of situations?" +0;How to set button click effect in Android? +0;"The following article from CNN describes a Michigan police officer being put on administrative leave for having KKK material at his home: https://www.cnn.com/2019/08/10/us/michigan-officer-placed-on-leave-kkk-document-house/index.html. The materials were discovered while a potential buyer was touring his house. +Although I vehemently condemn the KKK, doesn't this officer have the right to display whatever he wants in his home so long as it doesn't actively and deliberately call for violence? Aren't these articles protected under the first amendment? I realize this is an extreme example, and as a police officer his job requires interacting with all races, but unless it can be shown that he's bigoted and that it negatively affected his job performance, isn't it illegal to fire him? +Employers can restrict speech according to company policy while at work, but we all have to go home at some point. Can those restrictions follow us after clocking out?" +0;What does strength refer to in mathematics? Is it a formal idea? +0;"Does vegetarianism affect life expectancy? +Is an average vegetarian supposed to live longer just because of their diet?" +1;"What is the difference between an object and a companion object in a class in kotlin? +Example: +```class MyClass { + object Holder { + //something + } + companion object { + //something + } +} +``` +I already read that companion object shall be used, if the containing parameters/methods are closely related to its class. +But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name. +Is there maybe a difference in its ""static"" (I'm from the java side) lifecycle? " +1;I've rooted my phone. Now what? What do I gain from rooting? +0;"Is there a better way to determine whether a variable in ```Pandas``` and/or ```NumPy``` is ```numeric``` or not ? +I have a self defined ```dictionary``` with ```dtypes``` as keys and ```numeric``` / ```not``` as values." +0;I've come across the polynomial algorithm that solves 2SAT. I've found it boggling that 2SAT is in P where all (or many others) of the SAT instances are NP-Complete. What makes this problem different? What makes it so easy (NL-Complete - even easier than P)? +0;Why isn't Sectumsempra an Unforgivable Curse? +0;How can I add a delay to a program in C#? +0;"I'm trying to write a Bash script that will overwrite an existing directory. I have a directory ```foo/``` and I am trying to overwrite ```bar/``` with it. But when I do this: +```cp -Rf foo/ bar/ +``` +a new ```bar/foo/``` directory is created. I don't want that. There are two files in ```foo/```; ```a``` and ```b```. There are files with same names in ```bar/``` as well. I want the ```foo/a``` and ```foo/b``` to replace ```bar/a``` and ```bar/b```." +1;"Is there a particular reason the elves die off so fast? After the first war against Sauron, I recall the elves being decimated, to the point that they're almost useless army-wise in the trilogy. But I'm guessing men suffered equal or greater losses as well. +Anyways, other races just seem much more capable of repopulating, while is seems like there are incredibly few (if any?) elven children. Considering the fact that elves are immortal, wouldn't their population be the fastest to grow? Also the seem to be perpetually 40 years old, so aren't they eternally fertile as well? Why don't they have more kids and build bigger societies?" +1;Reasons for being vegetarian or vegan other than ethical reasons? +0;My mom has a green card that expires 2028 but has been out of the US in the UK for over a year due to COVID travel restrictions. Can she enter now? +1;What is the LXX and why is it so noteworthy that there is a Greek translation of the OT? Wouldn't it be better to directly reference manuscripts in the original languages? +0;"I have to disable inputs at first and then on click of a link to enable them. +This is what I have tried so far, but it doesn't work. +HTML: +``` +``` +jQuery: +```$(""#edit"").click(function(event){ + event.preventDefault(); + $('.inputDisabled').removeAttr(""disabled"") +}); +``` + +This shows me ```true``` and then ```false``` but nothing changes for the inputs: +```$(""#edit"").click(function(event){ + alert(''); + event.preventDefault(); + alert($('.inputDisabled').attr('disabled')); + $('.inputDisabled').removeAttr(""disabled""); + alert($('.inputDisabled').attr('disabled')); +}); +```" +0;I'm no expert in darkroom photography, but it seems a little odd that there is a type of light that doesn't affect film or developing paper etc. So why is a dark-room safelight safe? +0;"With the command: +```ls -la * +``` +I can list all my symbolic links. +How can I remove all symbolic links which are linked to a special folder? +For example: +In my directory ```usr/local/bin``` I have the following entries: +```lrwxrwxrwx 1 root root 50 Apr 22 14:52 allneeded -> /usr/local/texlive/2011/bin/x86_64-linux/allneeded +lrwxrwxrwx 1 root root 47 Apr 22 14:52 amstex -> /usr/local/texlive/2011/bin/x86_64-linux/amstex +lrwxrwxrwx 1 root root 24 Apr 23 19:09 arara -> /home/marco/.arara/arara +``` +Now I want to remove all links with the path ```/usr/local/texlive/```" +0;Did Aztecs know how many continents there are on earth? +1;What did the Soviet Union and Russia bring to the ISS? +0;"What utility can move my Windows boot partition over to another hard drive? +My preference is that it would be really easy. + +* Boot into Windows +* Pick drive to move +* Pick target drive +* It copies everything over, and reboots to the correct partition." +1;What's the difference between ASCII and Unicode? +1;Reasons why healthy people would intentionally want to get infected? +0;"In The Avengers, the Council contacted Nick Fury and supposedly, they want to nuke Manhattan. Nick didn't agree so they contacted a S.H.I.E.L.D. operative to nuke Manhattan. +When they found out that an unauthorized jet was trying to fly, Nick grabbed a rocket launcher and fired it at the jet, which was a decoy and the real jet was able to escape. +However, why would he do that? If that was the real plane carrying a nuke enough to level Manhattan, wouldn't the nuke explode and destroy the base along with them if he fired a rocket launcher at it?" +0;"Since I created my repository it appears that the tags I have been +creating are not pushed to the repository. When I do ```git tag``` on the +local directory all the tags are present, but when I logon to the +remote repository and do a ```git tag```, only the first few show up. +What could the problem be?." +0;How do I add Git submodule to a sub-directory? +1;Given that Kohn-Sham DFT is strictly a ground-state method (at 0 K), how is it sufficient to describe materials in real-life applications? +0;"I don't really get the difference between gain and volume boost. + +So if I understand correctly, gain directly boosts a signal from a line or input while volume handles the output. Volume isn't really for boosting either. +Would this mean, in most settings, getting 'close to' as much gain as possible without any hiss/background noise is ideal?" +0;"I recently had someone claim (on an unrelated SE site I won't link to) that it is the responsibility of a player to correctly identify their hand, that what you "call" your hand determines the winner: + +For example, you have an Ace, King, Queen, Jack, and Ten. You call your hand and say, "I have a Straight!" +But that was a bad move on your part because you are a novice player and you did not notice that all of your cards are Spades. You actually had a Straight Flush, but now you have lost because one of the remaining players had a Full House. +Your hand has not been determined until you call your hand. + +Is this true? Clearly you might play your hand differently if you misunderstand what you have, but I always thought that the cards speak for themselves once they are revealed. +Or would it depend on the specific poker variation/house rules?" +0;How to get the first item from an associative PHP array? +0;Why do people write #!/usr/bin/env python on the first line of a Python script? +0;"Nowadays each graphic card has some driver in operating system that translates some (typically) standard API such as OpenGL, so that programmers use some standardized API code to tell graphics cards how and what they want to render. (Actually that's already a bit hard-core most programmers really use various game engines that do this for them). In times of old computers - how was this done? Did every programmer of every game implemented all possible various API's that old graphic cards supported? Or did the old game studios from MS-DOS times had their own ""game engines"" that provided some abstraction when it came to these graphic cards? I remember there were many various card vendors and I remember old games asked me which one I have - so I suppose these games contained code / drivers for all these cards?" +0;"Why is it ""behead"" and not ""dehead""?" +0;Why do many vinyl albums of classical music have Sides 1 / 4 on the first record and 2 / 3 on the second? An example of this is the RCA Red Seal recording of Beethoven's 9th Symphony by the Boston Symphony Orchestra. +1;Why isn't the market dropping like a stone with all the bad news? +0;"What are Null Pointer Exceptions (```java.lang.NullPointerException```) and what causes them? + +What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?" +0;In Raiders of the Lost Ark, at the Ark opening ceremony the Nazi troops brings the Ark of the Covenant to the top of the mountain as Belloq said something before opening the Ark. Then they took the sand from the Ark and suddenly spirits coming out from the Ark and they're all killed (except Indy and Marion) by the freed-spirits which came from the Ark. Meanwhile, Indy asks Marion to keep her eyes shut. They didn't see the Ark when it was opened, so they're survived. In that scene what I don't understand is how did Indy know not to look into the Ark when it was opened? +0;What is likely to happen when you plug two ends of a network cable to a single switch/router? Will this create problems on the network, or just be ignored? +0;What command do I use to find the size of all the files (recursively) in a Linux or Mac OS X directory? +1;"I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. +```MyClass *m = (MyClass *)ptr; +``` +all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code? +```MyClass *m = (MyClass *)ptr; +MyClass *m = static_cast(ptr); +MyClass *m = dynamic_cast(ptr); +```" +1;Why don't toilets use saltwater? +0;How do I modify fields inside the new PostgreSQL JSON datatype? +1;I find that the survivability and general performance of my party increases massively from levels 1 to 2. At times, level 1 feels like a completely different game from level 2. However, I can't fathom how or why. I think that the availability of healing has something to do with it. From a mechanical perspective, is there any deep reason why level 1 and level 2 seem so radically different? Furthermore, why I do find no similar differences between later levels, such as 6 and 7? +0;"In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section number 5. +So I get an exception, when I call: +```[mainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; +``` +Is there another way to scroll to the top of table view?" +1;While in Phd I developed a lot of code that I want to turn into start-up. Can I do this? +0;I have heard multiple times in photography, the words Bokeh, and Gaussian Blur. To me, it seems that the words are used almost interchangeably, but in some instances, I have heard them contrasted. What's the difference, and what are the definitions of each of them? +0;"In 1969, NASA not only went to the moon, but broadcast the whole thing live on TV. +How did they achieve the TV broadcast? What technology did they need to use to send a video and audio signal from the moon to earth? Was there much of a lag?" +0;"Why does ""elite"" rhyme with ""beet"" rather than ""bite""?" +0;"A lot of ShaderToy demos share the Ray Marching algorithm to render the scene, but they are often written with a very compact style and i can't find any straightforward examples or explanation. +So what is Ray Marching? Some comments suggests that it is a variation of Sphere Tracing. What are the computational advantages of a such approach?" +0;Is martial arts training 'inadequate' for the real world? +0;Make a single page landscape in Google Documents +0;"PHP is writing this error in the logs: ""Notice: Use of undefined constant"". +Error in logs: +```PHP Notice: Use of undefined constant department - assumed 'department' (line 5) +PHP Notice: Use of undefined constant name - assumed 'name' (line 6) +PHP Notice: Use of undefined constant email - assumed 'email' (line 7) +PHP Notice: Use of undefined constant message - assumed 'message' (line 8) +``` +Relevant lines of code: +```$department = mysql_real_escape_string($_POST[department]); +$name = mysql_real_escape_string($_POST[name]); +$email = mysql_real_escape_string($_POST[email]); +$message = mysql_real_escape_string($_POST[message]); +``` +What does it mean and why am I seeing it?" +1;I'm from a very rural area and love to garden, however, for work I just moved into an apartment in the city. I miss being able to grow vegetables and so I attempted to start some leaf lettuce indoors, however, almost every plant died quickly. I'm just curious, does anyone have experience growing vegetables indoors? What are the best ones for this? What sort of planter do you use? Do they need to be directly next to a window? How often should they be watered? I'm not used to not having Mother Nature help me out with my plants Any tips that can be provided would be much appreciated, thanks! +1;What are the advantages of studying words by their frequency? +0;"I have heard many people saying, “Hah! I beat Stockfish,” and one saying, “I am the best chess player ever! I beat Stockfish.” So I wonder if it is possible, just to know whether I should try to beat it. I tried to play it once; I barely played 25 moves." +0;How to decrypt Jenkins passwords from credentials.xml? +0;"I'm pretty disappointed with my horse. He wasn't cheap -- 1000g -- but he just doesn't seem that fast. To make things worse, he's a bit of a wolf magnet and every time I get attacked I have to tediously dismount, blast the wolf, and then remount. +Is the speed of a horse actually significantly faster than normal running speed? If so, how much faster?" +1;"Other than rust, corrosion, and other reactions with air that would make the use of a metal unfavorable, how do different metals affect the performance? +Let's give Yagi an example: +Let's say I use 4 different metals for the directors +, reflector, and driven element. +One antenna made out of copper, one made out of aluminum, and one made out of a higher resistance conductor, let's say graphite (I know it would snap, I'm just talking theoretical), and iron +Other then the metal variations, the antennas are identical. +So, do different metals with different conductivity and permiability affect the performance of an antenna including gain, efficiency, impedance, elevation, or any other characteristic other then mechanical strength, and chemical reliability in open air." +0;"Windows in its earliest days was simply a shell that ran on top of MS-DOS, which means that Windows 3.1 itself was actually just a standard MS-DOS application like any other. +Yet, MS-DOS is not a multitasking operating system, and at the same time, Windows applications were compiled native-code binaries that ran without any form of managed environment. So, how exactly was multitasking of Windows binaries achieved if Windows 3.1 was simply a regular old MS-DOS program itself? Are there any old technical documents still floating around that describe the early Windows architecture internally?" +0;"I'm working on 2 different branches: release and development. +I noticed I still need to integrate some changes that were committed to the release branch back into the development branch. +The problem is I don't need all of the commit, only some hunks in certain files, so a simple +```git cherry-pick bc66559 +``` +does not do the trick. +When I do a +```git show bc66559 +``` +I can see the diff but don't really know a good way of applying that partially to my current working tree." +0;"In Civilization V, you attain a cultural victory by accumulating enough culture to purchase at least 36 social policies, and then building a wonder. The catch is that the more cities you build, the more culture you need to generate before you hit the next ""plateau"" of culture. +What is the ideal number of cities for a cultural victory? Does it change over time?" +0;"How to find if a customer is logged in or not in Magento 2. +If the customer is logged in then how to get customer data from a session?" +1;I have a 9 year old daughter that has expressed some interest in manga, but I'm having trouble locating series that are appropriate for her age. No one at our local bookstore could offer any advice. Is there a kid-friendly imprint or other resource I could use to help her find something appropriate? My preference is for physical books but I'm willing to explore digital options. +0;"I'm looking for a precise piece of information in a database which I have no knowledge about. The database is on a separate machine, but I can log into it, and launch a ```psql``` command line, with administrator rights. +It's a third-party product, and they are slow to answer questions. I know the data is inside that database, so I want to do a little bit of reverse-engineering. +Given a table name, is it possible to get a list of the names of the columns in that table? +For example, in SQL Server, it's possible to dump a table into a reusable ```CREATE``` statement, which textually lists all the columns the table is composed of." +0;"I am using Visual Studio Code and have a fairly common project structure: +```├── client/ +│ ├── tsconfig.json +├── shared/ +├── server/ +│ ├── tsconfig.json +├── project.json +``` +The two tsconfig files have different settings (e.g. the one under ```client/``` targets ES5, the one under ```server/``` targets ES6). Note that there is no tsconfig in the root directory. +The problem is that I want the shared directory to be included in both projects. I can't do this using tsconfig because the ```exclude``` option won't let me include a folder that is in a higher directory than the tsconfig.json, and using ```files``` I have to constantly keep the list of files up to date as it doesn't support globs. +Note that I can compile fine by adding the shared folder into tsc, what I want is for the Visual Studio Code IDE to recognise the shared code for intellisense etc. +Is the only option to wait for filesGlob?" +0;"I have the following method to save an Object to a file: +```// Save an object out to the disk +public static void SerializeObject(this T toSerialize, String filename) +{ + XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); + TextWriter textWriter = new StreamWriter(filename); + xmlSerializer.Serialize(textWriter, toSerialize); + textWriter.Close(); +} +``` +I confess I did not write it (I only converted it to a extension method that took a type parameter). +Now I need it to give the xml back to me as a string (rather than save it to a file). " +0;"I have a problem with the embedded bitcode term. +What is embedded bitcode? +When to enable, ```ENABLE_BITCODE``` in new Xcode? +What happens to the binary when enabled, ```ENABLE_BITCODE``` in Xcode 7?" +0;"In Dupire's local volatility model, the volatility is is a deterministic function of the underlying price and time, chosen to match observed European option prices. +To be more specific, given a smooth surface $(K,T)\mapsto C(K,T)$ where K is the strike and T is time to maturity. Dupire equation implies that there exits an unique continuous function $\sigma_{loc}$ defined by +$$\sigma_{loc}^{2}(K,T)=\frac{\partial_{T}C(K,T)+rK\partial_{K}C(K,T)}{\frac{1}{2}K^{2}\partial_{KK}C(K,T)}$$ for all $(K,T)\in(0,\infty)\times(0,\infty)$ such that the solution to the stochastic differential equation $dS_{t}/S_{t}=rdt+\sigma(t,S_{t})dW_{t}$ exactly generates the European call option prices. +What do the dynamics of the local volatility mean? Are dynamics equivalent to the volatility surface? Why the dynamics of local volatility model is highly unrealistic?" +0;Can you explain why we need a large number of trees in random forest when the number of predictors is large? How can we determine the optimal number of trees? +1;"I believe artificial intelligence (AI) term is overused nowadays. For example, people see that something is self-moving and they call it AI, even if it's on autopilot (like cars or planes) or there is some simple algorithm behind it. +What are the minimum general requirements so that we can say something is AI?" +0;"I have some questions regarding the usage and significance of the ```synchronized``` keyword. + +* What is the significance of the ```synchronized``` keyword? +* When should methods be ```synchronized```? +* What does it mean programmatically and logically?" +0;"I am using the ```$http``` service of AngularJS to make an Ajax request. +How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?" +0;Let's say that we have a gaseous or liquidus compound (I don't know if elements or compounds make a difference, take this as a thought experiment), and we have a tungsten or steel block that's 5cm (or less, you choose) thick. Is there any physical method for that gas or liquid to pass through that thick heavy metal block (not by drilling etc.)? +0;"Once, I boarded a plane, went to my designated seat and tried to put my bag in the overhead bin. However, it was full, and other adjacent overhead bins were full too. Because I had a seat next to the emergency exit, which I paid for, I had to hand over my bag to someone else in order to take off. +Do I have any rights over the overhead bin above my seat? +Could I ask the flight attendant to remove some of the bags to make room for me? +I cannot imagine that the bins were full because there was not enough space. I think this happened because some people were ignorant enough to bring more bags than is allowed inside the airplane instead of sending them to cargo. If this is the case why doesn't the airline enforce the bag limit inside the airplane?" +1;The Canon EF 40mm f/2.8 has a designation of STM on the lens. What does this mean? What are the advantages of having it and does it replace an older technology? +0;"I'm trying to set get id of all elements in an ```HTMLCollectionOf```. I wrote the following code: +```var list = document.getElementsByClassName(""events""); +console.log(list[0].id); +for (key in list) { + console.log(key.id); +} +``` +But I got the following output in console: +```event1 +undefined +``` +which is not what I expected. Why is the second console output ```undefined``` but the first console output is ```event1```?" +1;"I am 21 years old and living in a large city in Germany where smalltalk in local markets is not a common thing. +A new cashier joined my local food shop. She’s always at the checkout and never doing stuff like sorting products or cleaning the floor where I could actually ask her out. I am quite new to relationships, but the signs she gave me are promising. +My question is how I can ask for her number, or ask her out for coffee while she is only sitting at the checkout? I mean there are always like 5 people before and after me, and I think it would be awkward if we are changing numbers while customers are waiting behind us. Or even worse if I read the signs wrong and she rejects me? Since the store is just 5 min away from my place I visit regularly and don't want to leave a bad impression there." +0;"You start with the number 1536. Your mission is to get to 1 in as few steps as possible. At each step, you may either multiply or divide the number you have, by either 2 or 3; but, only if the result is a whole number whose first digit is 1, 3, 4, or 9. That is all." +0;"I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 = ```var oImg = document.createElement(""img""); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); ``` Is this the simplest but most robust (error free) way to do it?" +0;Why is %s better than + for concatenation in python? +0;"I had an interview with an employer working on a software-based vehicle solution. +Before going further in the interview process, he gave me a task to find out if a potential customer (automotive OEMs) is interested. +My question is, how can I approach a potential customer and arrange some time together to present to them the solution?. I'm intending to use Linkedin, but I'm not sure how to proceed. + +* Who to contact (I mean the person position in the company) +* How to formulate the request? +" +0;When an expendable booster rocket stage nears the end of its burn, does the guidance computer shut the engine(s) off at a certain velocity/altitude for the mission, or does the stage completely exhaust its propellants? +0;"Is "ima" an informal spelling of "I must"? + +MegaCharizardZord Replying to @nytimes about COVID-19 vaccine: +i just hope when i take it don't die lol. i trust the government in Canada, but if I do get something ima sue the shit out of em lol. + + +Source: Twitter" +1;"How to prevent ""Delhi Belly"" from eating/drinking locally?" +1;"I'm working at my first programming job. My boss is a very smart software engineer, and I feel +like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer. +What can I do to impress him? +Thank you." +0;Can I pass variables to a GNU Makefile as command line arguments? In other words, I want to pass some arguments which will eventually become variables in the Makefile. +0;"I have noticed that some games quote the requirement for ""pixel shader 3.0 or better"". +What is a pixel shader and is it some software requirements or hardware requirements?" +0;Red light facing forwards? It was nighttime in Manhattan. Isn't more always better when it comes to being seen? +0;If water is not a good conductor, why are we advised to avoid water near electricity (no wet hands near circuits etc.)? +0;"What is the difference between cohesion and coupling? +How can coupling and cohesion lead to either good or poor software design? +What are some examples that outline the difference between the two, and their impact on overall code quality?" +0;Can Romex (NM-B) cable be run through conduit? +0;"Let's say I have a function which takes an ```std::function```: +```void callFunction(std::function x) +{ + x(); +} +``` +Should I pass ```x``` by const-reference instead?: +```void callFunction(const std::function& x) +{ + x(); +} +``` +Does the answer to this question change depending on what the function does with it? For example if it is a class member function or constructor which stores or initializes the ```std::function``` into a member variable." +0;"I have an Eloquent model which has a related model: +```public function option() { + return $this->hasOne('RepairOption', 'repair_item_id'); +} +public function setOptionArrayAttribute($values) +{ + $this->option->update($values); +} +``` +When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not. +So I need to check if the related model exists, to either update it, or create it, respectively: +```$model = RepairItem::find($id); +if (Input::has('option')) { + if () { + $option = new RepairOption(Input::get('option')); + $option->repairItem()->associate($model); + $option->save(); + $model->fill(Input::except('option'); + } else { + $model->update(Input::all()); + } +}; +``` +Where `````` is the code I am looking for." +0;"NASA is hiring a new 'planetary protection officer' to defend Earth from alien matter, and the pay is a six-figure salary: as much as $187,000 a year. +When we are not sure whether aliens exist, why are we still hiring staff for protecting Earth? I do understand we have to take precautions. But when we don't have any proof why spend $187,000 a year? +Source: Nasa [sic] hiring new 'planetary protection officer' to defend Earth from alien matter - Times of India, Aug 3, 2017" +1;"Traditional advice for making megadungeons in older versions of D&D is in addition to any rooms with Monsters, Treasure, Traps, or ""Tricks"", there should also be at least 50 to 60 percent ""Empty"" rooms, which contain nothing overtly threatening or valuable. Now, there's several arguments for including these empty rooms that I buy, so I'm not going to accept any answer which primarily says, ""Don't include empty rooms"". The main issue I run into with empty rooms, however, is that they're boring in the way that I've been including them. They don't do their job of increasing tension, and the set dressing included around them hasn't been sufficiently interesting to my players either. My question is this: How can I make empty rooms interesting, by increasing tension or simply being interesting in and of themselves?" +1;"Laravel - Eloquent ""Has"", ""With"", ""WhereHas"" - What do they mean? explain in the context of an example" +0;What are some of the advantages of using one over the other? +1;"What factors determine the maximum altitude for a plane? +Is it limited by wing design, engine thrust, and so on? +Is there a formula by which one can calculate the maximum altitude a plane can reach?" +0;"Why did the Typescript folks create the ```infer``` keyword? +According to the documents, this is an example of how you would use it: +```type ReturnType = T extends (...args: any[]) => infer R ? R : any; +``` +I don't understand why this is needed. Why can't it just be: +```type ReturnType = T extends (...args: any[]) => R ? R : any; +``` +Why doesn't this work? Why is the ```infer``` keyword necessary ?" +0;Which is more widely supported: ```window.onload``` or ```document.onload```? +0;"I was surprised to learn that Puerto Ricans, despite living in a US territory, were not entitled to vote in the presidential elections. +I was even more surprised to learn that US citizens are allowed to vote for president from anywhere in the world - EXCEPT if they happen to live in Puerto Rico. +What is the legal/political rationale behind this? What is it about Puerto Rico that magically removes one's right to vote? Has anyone ever challenged this?" +0;"Suppose I wrote that I will be killed by a UFO falling from space in the year 2315 while I am lifting. +Will the Note increase my lifespan? In other words, will I still be alive by then?" +0;"I have an Affa Protector enchanted with Unhallowed Pact ... My opponent kills my Affa with Dread Slaver ... +Who will take control of the creature at the end? This is taking into consideration that my aura spell was cast 5 turns ago. Meaning my aura spell is NOT on the stack." +0;"I've found that some people call JavaScript a ""dynamically, weakly typed"" language, but some even say ""untyped""? Which is it really?" +1;"I was fixing my laptop, and as you may know, laptops have a lot of small screws to take out when you are fixing it. One of the screws fell into the floor (the floor has carpet on it), and I was unable to follow the screw with my sight. If I don't follow the screw with my sight when it falls, there is a high chance that I will not see that screw again. +My question is: what kind of method, tool or hack can I use to find small screws that falls into the floor? +I have tried using the tool with a magnet on the tip, that mechanics use to grab wrenches that falls in inaccessible areas, but had no luck finding the screw." +0;"What is the difference between mutex and critical section? Please explain from Linux, Windows perspectives? +I am programming in C#, would these two terms make a difference. Please post as much as you can, with examples and such.... +Thanks" +0;"What is the purpose of the single underscore ""_"" variable in Python? What is the meaning of ```_``` after ```for``` in this code? +```if tbh.bag: + n = 0 + for _ in tbh.bag.atom_set(): + n += 1 +```" +1;"What is the difference between doing: +```ptr = malloc (MAXELEMS * sizeof(char *)); +``` +or: +```ptr = calloc (MAXELEMS, sizeof(char*)); +``` +When is it a good idea to use calloc over malloc or vice versa?" +1;Why would I want to use Kotlin's coroutines? It seems that the RxKotlin library is much more versatile. Kotlin's coroutines look significantly less powerful and more cumbersome to use in comparison. I base my opinion on coroutines on this design talk by Andrey Breslav (JetBrains) Slideshow from the talk is accessible here. +0;"How do I get a ```PriorityQueue``` to sort on what I want it to sort on? +Also, is there a difference between the ```offer``` and ```add``` methods?" +1;"I've looked in the Apex developer's guide and a saw the Naming Conventions section which has basically only has this: + +We recommend following Java standards for naming, that is, classes start with a capital letter, methods start with a lowercase verb, and variable names should be meaningful. + +I'm looking for something more in depth, such as end all Controllers with Controller and their tests with ControllerTest, etc. +What is a good set of naming conventions to use when developing on the Force.com platofrm? It would be preferable if the answer has something that handles custom objects, classes, visualforce pages, and components and not just Apex classes." +0;"When learning some basic French, I was somewhat surprised to learn that phrases of the form ""I have found the cat"" generally translate almost word-for-word from English (J'ai trouvé le chat). To me, it's not immediately obvious that possession (""I have""/""J'ai"") has a correspondence with past tense, although if I think about it a little more I suppose I can kind of see how it makes sense. +This makes me wonder: Is this a common pattern in other languages? Especially ones not closely related to English." +1;I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead? +0;How to send HTML-formatted email in C#? +0;"I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized? +```Map integers; +integers.values().stream().mapToInt(i -> i).sum(); +```" +0;I am beginner of LaTeX. From many examples I found, I notice that it's very common to use command ```\leavevmode```. I can't find any information about this command. Could anyone tell me what's the function of it and how to use it? +0;"In Python specifically, how do variables get shared between threads? +Although I have used ```threading.Thread``` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? +I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. +Thanks in advance!" +1;"I grew up in a country where we were not allowed to leave/travel to an other country even when we were able to do so – we had the resources and dual nationality. +After two decades I still can't figure out why dictators, like Kim Jong-un for example, ban people from leaving their home countries? +Could it be that a dictator is usually interested in looting the country he rules, and having a smaller population means more natural resources for him and fewer protesters?" +0;Why can't we kill ourselves by holding our breath? +0;"Sometimes while driving in the traffic, I come across a car or two which would be dripping water-like drops from its exhaust steadily in 4-5 second intervals. I tried to ask a couple of people at the local workshops; they say, and I quote, "The car is giving an amazing mileage". +And I am like, what does that water dripping mean even then? Why does the water drip? What is the source of it? And what does it signify?" +1;Why can't MX records point to an IP address? +1;"Why is ```SELECT *``` bad practice? Wouldn't it mean less code to change if you added a new column you wanted? +I understand that ```SELECT COUNT(*)``` is a performance problem on some DBs, but what if you really wanted every column?" +1;"I did my training around the Seattle area, and was told that landing at SeaTac Airport (the region's major International/Commercial airport), while not strictly forbidden, was definitely frowned upon because it can slow down and interfere with the big planes on schedules. To discourage GA aircraft from using the big airport, they have a variety of landing fees, ramp fees, and prior-approval requirements. +But later, I moved near MCI, and was told that landing at the big airport was no big deal. That they're actually happy to have little planes there. +If you fly small GA planes, do you land at the major airports in your area? +What advanced preparations can you make to minimize your impact on the ""big boys"", and remain a good airspace citizen?" +0;"I need a way to compare multiple strings to a test string and return the string that closely resembles it: +```TEST STRING: THE BROWN FOX JUMPED OVER THE RED COW +CHOICE A : THE RED COW JUMPED OVER THE GREEN CHICKEN +CHOICE B : THE RED COW JUMPED OVER THE RED COW +CHOICE C : THE RED FOX JUMPED OVER THE BROWN COW +``` +(If I did this correctly) The closest string to the ""TEST STRING"" should be ""CHOICE C"". What is the easiest way to do this? +I plan on implementing this into multiple languages including VB.net, Lua, and JavaScript. At this point, pseudo code is acceptable. If you can provide an example for a specific language, this is appreciated too!" +0;"Given the following code: +```var arr = [1,2,3,4,5]; +var results: number[] = await arr.map(async (item): Promise => { + await callAsynchronousOperation(item); + return item + 1; + }); +``` +which produces the following error: + + TS2322: Type 'Promise[]' is not assignable to type 'number[]'. + Type 'Promise is not assignable to type 'number'. + +How can I fix it? How can I make ```async await``` and ```Array.map``` work together?" +1;Why don't helicopters use reaction wheels to counter the main rotor? +0;"When configuring cron to run a command every other day using the ""Day of Month"" field, like so: +```1 22 */2 * * COMMAND +``` +it runs every time the day of month is odd: 1,3,5,7,9 and so on. +How can I configure cron to run on days of month that are even like 2,6,8,10 and so on (without specifying it literally, which is problematic as every month has a different number of days in the month)?" +0;"Is there a way to have a private setter for a property in TypeScript? +```class Test +{ + private _prop: string; + public get prop() : string + { + return this._prop; + } + private set prop(val: string) + { + //can put breakpoints here + this._prop = val; + } +} +``` +Compiler complains that visibility for getter and setter don't match. I know I can just set the backing field, but but then I can't set breakpoints when the value is set. +I though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter. +Am I missing something here? There doesn't seem to be any reason to not allow private setters, the resulting JS doesn't enforce visibility anyway, and seems better that the current alternatives. +Am I missing something? If not is there a good reason for no private setters?" +0;"When learning vocabulary, especially with the use of SRS (Spaced Repetition System), it is interesting to use flashcards. A commonly encountered problem is how to formulate those for maximum efficiency. +How does learning vocabulary through sentences, thus giving context to the used words, compare to learning to recognize words alone? For example, the context may give away the meaning of the problematic vocabulary. Are there studies or expert opinions on one approach being preferable to the other at different stages of language learning? Or is it recommended that they be mixed for best results?" +1;"Can I spend the night alone in a tent in a forest outside Stockholm in -20°C without risking my life? + +The backstory +From the end of January, I'm starting my studies in a suburb of Stockholm. I've decided to, if it turns out plausible, not rent an apartment, but live in a tent. (This is not out of frugality, but out of a will to try something new.) +I do have friends who I could visit once a week or so to prepare food and wash my clothes, so I think I can solve the practical problems, or at least those that I've come to think of. I'd camp in one of the forests, maybe 1 km from ""civilisation"". I'd have access to showers etc at university every day. +However: I don't want to freeze to death in my sleep! That's very important to me. I've read that the nights can get as cold as -20°C (-4°F). With the proper preparations, would this be a plausible way of living, at least for a month or so? +I do have camping experience, and have been hiking for three weeks, but only in summer." +0;Why is the volt not identical to the full name Volta, unlike the other electrical units ohm, ampere, coulomb, tesla, weber and henry? Is there a historical explanation, was the volt introduced at a different time? +0;"We can define cross products mathematically like if we take two vectors, we can find another vector with certain properties but why do we use it in physics, if we consider a hypothetical physical quantity like force which is equal to cross product of certain vectors? + + For example, the force exerted on a charge in motion in an uniform magnetic field. + +Why is it so? Why does that force have to be a cross product of two vectors? +Is it possible to come up with them when what we do is just observe the nature?" +1;"I have a web project in my solution file that is ""unavailable"" when I open the solution. When I right-click on the web project and reload the project, I get the following error: +``` +The Web Application Project mycompany.myapp.mywebproject is configured to use IIS. The Web Server 'http://localhost/MyWebApp could not be found. +``` +I have not manually set up virtual directories for this web application. +Per colleagues, Visual Studio should prompt me to create virtual directories but I am not getting prompted. +I installed VS2010 before installing IIS on my dev machine. +Here is my development machine setup: + +* Windows 7 Enterprise +* Service Pack 1 +* 64 bit OS +* Visual Studio 2010 Enterprise Service pack 1 +* IIS version 7.5" +1;Why is it hard to draw people running in animes? +0;"Malachi 4:5: + + I will send you the prophet Elijah. He will come before the day of the Lord arrives. It will be a great and terrifying day + +Jesus says in Matthew 11:14 + + ""and if you are willing to believe their message, John is Elijah, whose coming was predicted"" + +Jesus says in Mathew 17:12 + + But I tell you, Elijah has already come, and they did not recognize him, but have done to him everything they wished. In the same way the Son of Man is going to suffer at their hands.” + +It's pretty clear from the above verses that John was Elijah reincarnated. +Wouldn't the above verses imply that reincarnation is true?" +0;"I see hugely varied performance depending on how many newlines there are in the file I'm visiting. +Here's an example. I have two JSON files: +```$ wget https://github.com/Wilfred/ReVo-utilities/blob/a4bdc40dd2656c496defc461fc19c403c8306d9f/revo-export/dictionary.json?raw=true -O one_line.json +$ python -m json.tool pretty_printed.json +``` +These are two JSON files with the same content. ```one_line.json``` is 18MiB of JSON without any newlines. ```pretty_printed.json``` has newlines and whitespace added, making it 41MiB. +However, the bigger file split over many lines is much faster to open in Emacs, both in Javascript mode and Fundamental mode. +Why does Emacs have such poor performance with long lines, since it's actually fewer bytes? Is there anything I can do to improve performance without reformatting the data outside of Emacs?" +1;"Sooner or later we come across a task in our project, with which we are totally unfamiliar ('we' as in PM, but also possibly the staff assigned to do this particular task). +How can we estimate amount of time/work/resources needed to complete such a task? What margins of error should we assume?" +0;"Why is Nazi-Germany commonly referred to as ""The Third Reich"" in English? Why is reich not translated when Dritten (""third"") is? +And what is the English synonym of reich? Realm? +Austria (Republik Österreich), Norway (Kongeriket Norge) and Sweden (Konungariket Sverige) all have reich (or the Norwegian/Swedish corresponding etymology related word) in their name and they all have English translations of their name." +1;If we fold a paper and then apply pressure on the newly formed crease, it seems that the paper's surface gets a permanent deformation but what exactly has happened to the paper at a molecular scale? +1;"In general, there are two types of syntax of defining functions - Something like C, C++, C#, or Java (```int functionName(char arg)```) vs the ML (and others) tradition of defining the return type after the function (and using something like a ```fun``` keyword to define a function - like ```fun functionName(char arg): int```). +One of the advantages (for the parser, at least) for a ```fun``` keyword is that it lets the parser be context-free (it doesn't have to guess if ```int``` defines a variable or if it defines a function). +When C was invented, computers had very little memory and speed (so little, that the reason C requires one to define all the variables in the beginning of the function was because it had to be a one-pass parser). Why didn't they choose the simple way out and use function defining keyword?" +0;"I am new to TeX, working on it for about 2 months. Have not yet figured out how to script the 'curvy L' for Lagrangian and/or for Laplace Transforms. +As of now I am using the 'L' - which is not good! :-( +Any help? +UPDATE The 2 best solutions are; +```\usepackage{ amssymb } +\mathcal{L} +``` +and +```\usepackage{ mathrsfs } +\mathscr{L} +``` +I got my answers at, http://detexify.kirelabs.org/classify.html" +1;"My son doesn't want to share anything with other kids, and if some kid even so much as touches his toy, he pushes the kid. He shouts and cries at the same time, and tries to express his anger by pushing and hitting the kid. I feel so embarrassed in front of other parents. +And when he is at home with me and doing something wrong, I try to stop him, he tries to repeat my words and shouts at me. He is copying the behavior of others, whether it's a good act or bad... +Please help me how to stop him from being a bully." +1;What are the differences between the Strategy design pattern and the State design pattern? please explain the difference in layman's terms? +1;Why don't Tour de France riders always ride their TT bikes? +0;"I remember when the Muslim holy book was the Koran when I was in middle school, but now it's the Quran. But it's always been Qatar and Iraq (but still Kuwait.) +Who decided that 'Q' was going to be represent that sound instead of 'K', and why?" +0;How do you add Boost libraries in CMakeLists.txt? +1;"Quando devo fazer essa gravação direto no banco? +Quais as situações? +Eu sei que posso gravar no banco o caminho da imagem." +0;I need a regular expression that validates a number, but doesn't require a digit after the decimal. ie. ```123 123. 123.4 ``` would all be valid ```123.. ``` would be invalid +0;"The year is 2109 C.E my friends and I were caught in a space disaster when the spacecraft we're in broke apart during a daring escape from a patrolling spacecraft. We stole an antique cellphone (from 1999, in good working condition) from a space museum but our escape was interrupted and fortunately we managed to get into the escape pod and didn't get caught up in the explosion. The only emergency transponder in the escape pod isn't working probably due to the destruction of the spacecraft. Given the technology of 1999, is it possible for us to sent out a distress signal to alert the leaving patrol spacecraft? +Note: the cellphone was the most innovative product of 1999 money can buy. +The escape pod is not a Faraday cage we're talking about the future and the patrol spacecraft don't necessary be on a lookout for distress signal; please use these clues to your advantage. +If there is absolutely no way to transmit any man-made signal out, please state a valid reason why it can't be done." +0;"Often I want to just point the camera to an object or a specific area in my scene to get an idea of how it'll look in the render. What's the most painless hassle-free way to do this in blender? +A quick search on the blender wiki does not lend itself to easy look-up due to all the noise in the search result. +This question could probably be broken down into these two main questions: + +* How do I point a selected camera to the current 3d-cursor location in the scene? +* How do I point the selected camera to the currently selected object(s) in the scene?" +0;"What are the general tactics of Krav Maga as opposed to Systema? +For instance, the tactics of Silat are to hurt the other person so badly they can't hurt back. Another example would be that the tactics of boxing would be to knock out the other person first using only punches. So, as far as I know, the goal of Systema and Krav Maga are both to do anything you can to defeat your attacker because they are serious about self defense. Does that mean that Krav Maga and Systema are strategical identical? Does Krav use strategies that Systema doesn't? Does Systema use any strategies that Krav doesn't? Is there a difference or do they generally work the same way?" +0;"I understand that unlocking the bootloader will wipe my Android phone, but have been looking around for why. Seems to be by design, but what is the reasoning for that design? Is it some security concern, some obscure technical reason, or just for lulz? I'm looking for something solid to chew on here, something more than because ""that's how it is""." +1;"The original IBM PC and later variants used an Intel 8253 or 8254 as a sound chip. Why did users add sound cards such as the Adlib or Sound Blaster. I remember voice output with programs like telephone answering programs. The sound was wimpy but I attributed most of the quality to speaker size. +What was lacking with the original PC sound chip?" +0;"According to the sources I have found, a lambda expression is essentially implemented by the compiler creating a class with overloaded function call operator and the referenced variables as members. This suggests that the size of lambda expressions varies, and given enough references variables that size can be arbitrarily large. +An ```std::function``` should have a fixed size, but it must be able to wrap any kind of callables, including any lambdas of the same kind. How is it implemented? If ```std::function``` internally uses a pointer to its target, then what happens, when the ```std::function``` instance is copied or moved? Are there any heap allocations involved?" +0;"So, I'm on vacation in Utah, and so I attended an LDS service. In the morning, I heard a reading from one of the Presidents of the church during the ""Quorum of the Elders,"" then went to Sunday School, and finally witnessed the Sacrement of the bread and water. (I guess it makes sense there was no wine, but it did make me go ""Huh!"") After that, there were testimonies from missionaries and some music - but nothing that struck me as a sermon. +Was I missing something, or was this an atypical service? I guess I was trying to understand what the ""pastor""s role in the service was supposed to be - or again, is it just that Mormons are even more Baptist than baptists? +If someone could explain how instruction and exhortation are primarily conferred in the LDS church Id appreciate it. " +0;"A partir de un String, ```""123-654321""```, lo que deseo es dividirlo en dos Strings: +```string1=123 +string2=654321 +```" +0;"What’s the difference between ```\n``` (newline) and ```\r``` (carriage return)? +In particular, are there any practical differences between ```\n``` and ```\r```? Are there places where one should be used instead of the other?" +1;Assume that I am a programmer and I have an NP-complete problem that I need to solve it. What methods are available to deal with NPC problems? Is there a survey or something similar on this topic? +0;Why are the lights inside commercial airplanes turned off during take off and landing? +1;"The default behaviour of ```LIKE``` and the other comparison operators, ```=``` etc is case-sensitive. +Is it possible make them case-insensitive?" +0;"I have a new SPA with a stateless authentication model using JWT. I am often asked to refer OAuth for authentication flows like asking me to send 'Bearer tokens' for every request instead of a simple token header but I do think that OAuth is a lot more complex than a simple JWT based authentication. What are the main differences, should I make the JWT authentication behave like OAuth? +I am also using the JWT as my XSRF-TOKEN to prevent XSRF but I am being asked to keep them separate? Should I keep them separate? Any help here will be appreciated and might lead to a set of guidelines for the community." +0;"Gostaria de saber se existe alguma forma simples de realizar um upload de arquivos via AJAX + JSON. +Se houver, qual seria?" +1;Did the ancients or other pre-industrial civilisations engage in unsustainable practices? +0;"When reading my Bible, I've noticed Joesph's name listed in both the Old and New Testaments; is it the same person or is there more than one Joseph in the Bible?" +0;"Para que serve o ""with"" no Python?" +1;"The question bothers me since February 2022. Why (legally) are Russian combatants in Ukraine considered soldiers (thus POWs when captured) rather than terrorists? + +* There is no formal declaration of war. +* They are members an organization (Russian military) that commits acts of terrors to civilian population in clear violation of international law of war. Moreover, they either directly or indirectly contribute to the mentioned acts of terror. +* Their state (Russia) explicitly claims that there is no war (thus unilaterally waiving the protection of law of war for Russian forces). + +Why is that particular group of armed people acting in clear violation of Ukrainian law treated as "soldiers in war" rather than state-sponsored criminals? +Note, that waiving the protection of law of war does not waive the protection of Ukrainian law (right to due process etc.)." +1;What are the major branches of philosophy? +1;Are there any advantages while backpacking to hike during the night and sleep during the day? +1;"I have been cautioned against blending: + +* Traditional fantasy elements + +Such as magic systems and exotic, less plausible creatures (on a scientific level - magic tends to explain away these beasts) + +* Traditional sci-fi elements + +Such as advanced technology and civilizations amidst the stars. +I have taken it upon myself to harmonize the two in my current worldbuilding project. I know I cannot be the first. I love the creativity found in both, and it is going well so far. I have been exploring the potential for humanity with both tools at their disposal. (Magic and science, essentially) +Why do people advise to stick to one or the other?" +0;Why are prions in animal diets not destroyed by the digestive system? +0;How slicing in Python works? Please include references where appropriate. +1;"I am writing a story where a species undergoes devolution. Is there any scientific or plausible way to do this? The process can be instantaneous or may take ages, I do not mind which as I need to weigh my options at this stage. +To be clear, the devolution I am thinking of is like taking a human being then devolving him/her to the primate stage, so lets say about as far back as Orrorin tugenensis or Paranthropus where they are in the midst of evolving from primates to Homo erectus. Please note I used human beings as an example to give context but the species undergoing devolution may not necessarily be human. +Based on the answers, ""devolution"" does not exist so had the word in quotes to reflect this. " +0;"I've used GEDCOM to transfer data between desktop software and websites, but it all seems a bit old hat. Is there anything better that will mangle* my data less. +* For example, GEDCOM can lose some data where the two ends of the system understand a concept which GEDCOM does not have a field for." +0;Is it ever possible that ```(a== 1 && a ==2 && a==3)``` could evaluate to true in JavaScript? +1;"Gostaria de saber qual é a real diferença entre o ```String``` (s maiúsculo) e o ```string``` (s minúsculo). +Aparentemente os dois têm os mesmos objetivos, porém qual é ""melhor"" para ser utilizado?" +1;I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code? +1;"Assume an environment with a puppet-managed cluster of different servers - various hardware, software, operating systems, virtual/dedicated, etc. +Would you choose meaningful hostnames (mysqlmaster01..99, mysqlslave001..999, vpnprimary, vpnbackup, etc.) or would you prefer meaningless hostnames such as characters from a book or movie? +The problem I see with meaningful hostnames is that names usually represent a single service and if a server has more than one purpose it gets really messy (especially if server roles change often). +Isn't mapping a service name to an IP address and maintaining that mapping what DNS is supposed to do? +What are the advantages and drawbacks of both approaches and what actual problems have you had to tackle with the approach you chose?" +1;Best way to start investing, for a young person just starting their career? +0;"Quantum state teleportation is the quantum information protocol where a qubit is transferred between two parties using an initial shared entangled state, Bell measurement, classical communication and local rotation. Apparently, there is also something called quantum gate teleportation. +What is quantum gate teleportation and what is it used for? +I am particularly interested in possible applications in simulating quantum circuits." +0;What does it mean for an album to be remastered? +1;What's the best way to iterate over the items in a ```HashMap```? +1;Why did people start using CO2 (instead of e.g. oxygen) for carbonated drinks? +0;"Say I have a file ```/templates/apple``` and I want to + +* put it in two different places and then +* remove the original. + +So, ```/templates/apple``` will be copied to ```/templates/used``` AND ```/templates/inuse``` +and then after that I’d like to remove the original. +Is ```cp``` the best way to do this, followed by ```rm```? Or is there a better way? +I want to do it all in one line so I’m thinking it would look something like: +```cp /templates/apple /templates/used | cp /templates/apple /templates/inuse | rm /templates/apple +``` +Is this the correct syntax?" +1;When are Decision Diagrams the right way to model and solve a problem? +1;"Essentially, I have a protagonist who I set up as a 'main' good guy in one of my series. However, in my final series, I intend to make him turn to the dark side and oppose my other protagonists (from my other series). It's clear in his series that the protagonist-turned-antagonist is very devious, and he has had hostile intentions previously towards the protagonists of the other series. +My question: +Should I avoid turning my protagonist into an antagonist? Are there any foreseeable problems with this? Will this be a problem for readers? Any tips or tricks to handle this?" +0;"I'd never heard of anycast until a few seconds ago when I read ""What are some cool or useful server/networking tricks?"". +The wikipedia ""Anycast"" article on it is quite formal and doesn't really evoke a mental picture of how it would be used. +Can someone explain in a few informal sentences what ""anycast"" is, how you configure it (just in a general sense), and what its benefits are (what does it make easier)?" +0;"$A$ and $B$ are $n \times n$ matrices and $v$ is a vector with $n$ elements. $Av$ has $\approx 2n^2$ flops and $A+B$ has $n^2$ flops. Following this logic, $(A+B)v$ should be faster than $Av+Bv$. +Yet, when I run the following code in matlab +```A = rand(2000,2000); +B = rand(2000,2000); +v = rand(2000,1); +tic +D=zeros(size(A)); +D = A; +for i =1:100 + D = A + B; + (D)*v; +end +toc +tic +for i =1:100 + (A*v+B*v); +end +toc +``` +The opposite is true. Av+Bv is over twice as fast. Any explanations?" +0;"I came across a piece of code ```void *p = &&abc;```. What is the significance of ```&&``` here? +I know about rvalue references but I think ```&&``` used in this context is different. What does ```&&``` indicate in ```void *p = &&abc;``` ?" +0;"When I execute ""```python```"" from the terminal with no arguments it brings up the Python interactive shell. +When I execute ""```cat | python```"" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe. +How would I do a similar detection in C or C++ or Qt?" +1;"""The video of Pythom Space's first rocket test has raised a few eyebrows + +The video prompted hundreds of replies on Twitter, including some from rather horrified rocket scientists. "We knew better as untrained college students," said Jordan Noone, the co-founder of Relativity Space. + +Pythom “Micro jump” +What exactly did they get wrong with this test? +Note: The Pythom Space CEO did eventually respond to the original Ars Technica story linked above. It does offer their own take on some of the issues raised there and elsewhere (including some of the points in the answer below)""" +0;When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()? +1;"When encoding a logic into a proof assistant such as Coq or Isabelle, a choice needs to be made between using a shallow and a deep embedding. In a shallow embedding logical formulas are written directly in the logic of the theorem prover, whereas in a deep embedding logical formulas are represented as a datatype. + +* What are the advantages and +limitations of the various +approaches? +* Are there any guidelines available for determining which to use? +* Is it possible to switch between the two representations in any systematic fashion? + +As motivation, I would like to encode various security related logics into Coq and am wondering what the pros and cons of the different approaches are." +0;Prove that the union of countably many countable sets is countable. +1;"Você encontra na internet a afirmação que Singletons são ruins. Isto é verdade? Por quê? +O problema seria generalizado para quaisquer objetos com instância única? Ou para qualquer coisa que tenha estado global? +Se é tão ruim, pra que foi inventado? Ou seja, que problema ele queria resolver? +Quais os problemas que terei se usá-lo? +Existe alternativa viável?" +1;"The construction of Solomon's temple includes a piece of furnishing described in 1 Kings 7:23 (ESV): + + Then he made the sea of cast metal. It was round, ten cubits from brim to brim, and five cubits high, and a line of thirty cubits measured its circumference. + +So if the ```diameter = 10``` cubits and the ```circumference = 30``` cubits, then ```π = 3``` by the equation ```C = π * D```. +Of course, such an object does not exist since ```π = 3.14159...``` yet clearly the sea was constructed at some point. So how do we resolve this contradiction?" +0;"With PHP 7.2, ```each``` is deprecated. The documentation says: + +Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged. + +How can I update my code to avoid using it? Here are some examples: + +* +```$ar = $o->me; +reset($ar); +list($typ, $val) = each($ar); +``` + +* +```$out = array('me' => array(), 'mytype' => 2, '_php_class' => null); +$expected = each($out); +``` + +* +```for(reset($broken);$kv = each($broken);) {...} +``` + +* +```list(, $this->result) = each($this->cache_data); +``` + +* +```// iterating to the end of an array or a limit > the length of the array +$i = 0; +reset($array); +while( (list($id, $item) = each($array)) || $i < 30 ) { + // code + $i++; +} +``` + + +When I execute the code on PHP 7.2 I receive the following error: + +Deprecated: The each() function is deprecated. This message will be suppressed on further calls" +1;Can someone please give an explanation of different egg preparations? +1;"I'm running a relatively small one-man business in the software sector. I just started and am trying to create a larger portfolio. For that, I offer some friends free services. +I found a few reasons to send these clients €0,- invoices, mostly similar to the reasons to send 100% discount invoices to charity funds that I gave here: + +* Clarity about what has to be done and when +* No transfers (as I would have with a 0% discount bill and returning the money as a gift) + +And also: + +* With an invoice I have more distinguishable clients which makes that I have more chance on getting a better certificate from the state (doesn't matter how it exactly works, this is an advantage) + +Suppose that these clients won't have a problem with the €0,- invoices, could there be any reason for me to not send them? +I ask this, because I've never seen people sending invoices like this, and I can only see advantages." +0;"In regards to Error handling in PHP -- As far I know there are 3 styles: + +* ```die()```or ```exit()``` style: +```$con = mysql_connect(""localhost"",""root"",""password""); +if (!$con) { + die('Could not connect: ' . mysql_error()); +} +``` +* ```throw Exception``` style: +``` if (!function_exists('curl_init')) { + throw new Exception('need the CURL PHP extension. + Recomplie PHP with curl'); + } +``` +* ```trigger_error()``` style: +```if(!is_array($config) && isset($config)) { + trigger_error('Error: config is not an array or is not set', E_USER_ERROR); + } +``` + +Now, in the PHP manual all three methods are used. + +* What I want to know is which style should I prefer & why? +* Are these 3 drop in replacements of each other & therefore can be used interchangeably? + +Is it just me or everyone thinks PHP error handling options are just too many to the extent it confuses php developers?" +0;How do I change the author and committer name/email for multiple commits? +1;This summer I will be taking a rather inherently dangerous multi-day hike by myself. I was considering buying a flare gun since I will be out of cellular range unless there is something more modern and equally reliable. Any suggestions? +0;" + Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances. + +I don't understand the part marked in bold. +Congress shall make no law prohibiting the free exercise of religion. So congress should not make a law which prohibits the freedom of religion. I get it. +But Congress shall make a law which respects an establishment of religion. Doesn't ""Congress shall make no law respecting an establishment of religion"" mean congress should not make a law that respects religion because there's ""no"" in it?? " +1;Why are people unwilling to share information about their salary? +0;In D&D, how many attacks can a fighter with two-weapon fighting make at 5th level? +0;"Consider the following code: +```avgDists = np.array([1, 8, 6, 9, 4]) +ids = avgDists.argsort()[:n] +``` +This gives me indices of the ```n``` smallest elements. Is it possible to use this same ```argsort``` in descending order to get the indices of ```n``` highest elements?" +0;Can a woman give birth to twins with different fathers? +1;Relationship between SVD and PCA. How to use SVD to perform PCA? +0;What is the English term for when someone thinks they are doing something nice for you but it ends up making things worse. EX: Someone buys you an elephant -- nice gesture and cool! But now you have to take care of it, and it becomes a burden on you. +0;Did Hillary Clinton propose to punish flag burners in 2005? +0;"There are several questions here about the definition of depth of field, about focal length, and about subject distance. And of course there's the basic how does aperture affect my photographs. And plenty of how do I get super-shallow d.o.f questions. There's related questions like this one. But there's no be-all-end-all question asking: +What exactly determines depth of field in a photograph? +Is it just a property of the lens? Can lenses be designed to give more depth of field for the same aperture and focal length? Does it change with camera sensor size? Does it change with print size? How do those last two relate?" +0;Why did the NES not allow rotated sprites? +0;"I want to merge two dictionaries into a new dictionary. +``` +x = {'a': 1, 'b': 2} +y = {'b': 3, 'c': 4} +z = merge(x, y) + +>>> z +{'a': 1, 'b': 3, 'c': 4} +```" +0;"There are many ""standards"" for the JSON content type: +application/json +application/x-javascript +text/javascript +text/x-javascript +text/x-json +Which one do I use, and where? I assume security and browser support issues are a factor." +1;What's the goal of Minecraft and what can users achieve in this world? +0;"If I have sampled a signal using proper sampling methods (Nyquist, filtering, etc) how do I relate the length of my FFT to the resulting frequency resolution I can obtain? +Like if I have a 2,000 Hz and 1,999 Hz sine wave, how would I determine the length of FFT needed to accurately tell the difference between those two waves?" +0;"I wanted to produce a 1 GB random file, so I used following command. +```dd if=/dev/urandom of=output bs=1G count=1 +``` +But instead every time I launch this command I get a 32 MB file: +```$ dd if=/dev/urandom of=output bs=1G count=1 +0+1 records in +0+1 records out +33554431 bytes (34 MB, 32 MiB) copied, 0,288321 s, 116 MB/s +``` +What is wrong?" +1;The treads on my road bike's 28C tires are almost completely gone—they only persist along the shoulders of the tire. Do the treads matter? What is a good indicator of when the tire as a whole needs to be replaced? +0;Is there a way to create an index on a property/column using fluent configuration, instead of using the new ```IndexAttribute``` ? +1;"Both races have the same limits on their strength, and athletics, but it's hard to imagine why. A Goliath could feasibly lift and throw a gnome, yet the Gnome, following rules as written, can pin down a Goliath, fairly easily, if statted correctly. +Is there an in-universe explanation as to why such dramatically different sized creatures can wrestle on an even playing field? +How might a DM explain a scenario in which a gnome beats a goliath in any kind of test of strength?" +0;"So I'm pretty far into writing my dystopian novel and I was reading over what I had. Something that helps me when I first start a novel is to get a clear picture of my characters in my head and put a face to a name, so I usually sculpt a personality and find a Google image of someone who I think matches that, and I put all of those into documents for my personal reference. I looked over my main five characters--Analise, Poet, Shove, Star, and Nova--and then suddenly something jumped out at me. Analise is Hispanic, Shove is Japanese, and Poet, Star, and Nova are all black. +I had forgotten about their races because it wasn't important to me and I had not noticed while I was writing, because the story isn't about their racial backgrounds. But is it, I don't know, somehow alienating or offensive to white readers that the characters aren't white, and that no main characters are white? " +0;When I do ```\footnote{}``` for a value in a table, the footnote doesn't show up. How do I get it to show up? Also, is it possible to get it to show up at the bottom of the table rather than the bottom of the page? +0;Why is kVA not the same as kW? +0;"Elon Musk and his partner want to name their child X Æ A-12. +Is that name allowed in California, US?" +0;"In this Creation magazine reprint of a 1994 article titled Exploding stars point to a young universe, Young-Earth Creationist, Jonathan Sarfati argues that the scarcity of Supernova remnants (SNRs) in the sky suggests the Milky Way galaxy is less than billions of years old. + +On average, a galaxy like our own, the Milky Way, should produce one supernova every 25 years. +[...] +As can be readily seen above, a young universe model fits the data of the low number of observed SNRs. If the universe was really billions of years old, there are 7000 missing SNRs in our galaxy. + +Does astronomy predict a Milky Way supernova every 25 years? Are there missing SNRs that undermine these predictions?" +1;Why is there so much technical detail of whaling included in Moby-Dick? +1;Why are we building larger land-based telescopes instead of launching larger ones into space? +0;Why can we see the dust particles in a narrow beam of light (and not in an all lighted area)? +0;"I can not initialize a List as in the following code: +```List supplierNames = new List(); +supplierNames.add(""sup1""); +supplierNames.add(""sup2""); +supplierNames.add(""sup3""); +System.out.println(supplierNames.get(1)); +``` +I face the following error: + + Cannot instantiate the type ```List``` + +How can I instantiate ```List```?" +0;What is the difference between ```warnings.warn()``` and ```logging.warn()``` in terms of what they do and how they should be used? +0;"In Greek mythology, the words ""Titan"" and ""God"" seem to be used interchangeably. For example, Zeus is a God, but Cronus (his father) was a Titan. So what is the difference between a Titan and a God in Greek mythology? " +1;How do weather models work? +1;"I am currently trying to decipher Mazur's Eisenstein ideal paper (not a comment about his clarity, rather about my current abilities). One of the reasons I am doing that is that many people told me that the paper was somehow revolutionary and introduced a new method into number theory. +Could you explain exactly what subsequent developments did the paper bring, what ideas in the paper were considered more-or-less original (at the time it was published), and exactly what difficulties did these ideas resolve that people failed to resolve before the paper was published (if any)?" +0;Tracing XML request/responses with JAX-WS +0;"In Vim, how do I insert characters at the beginning of each line in a selection? +For instance, I want to comment out a block of code by prepending ```//``` at the beginning of each line assuming my language's comment system doesn't allow block commenting like ```/* */```. How would I do this?" +0;Why doesn't the nuclear fusion in a star make it explode? +0;Does hot water freeze faster than cold water? +0;"O que é Reflection. Por que é útil? +* É recomendável usar em projetos? +* Como usar? +* Em quais situações Reflection pode ser usado?" +1;What is the difference between minimum and infimum? +0;"I had a Nespresso Vertuo Next machine. It stopped working properly and during the troubleshooting video call, the Nespresso support agent said that the machines should not be connected to a GFCI outlet because they can potentially damage the machine. As part of our home inspection when we purchased the house, it was recommended to install such outlets anywhere that water is common, including the kitchen. As such, all the outlets in our kitchen are GFCI outlets. +This call with Nespresso was the first time I'd ever seen someone claim that GFCI outlets can potentially damage coffee machines. +Can they damage Nespresso machines? If so, can they damage other coffee machines (I also have a Baratza grinder and a Bonavita drip machine I usually hook into the same outlet)? They sent us a replacement and now I am questioning where to put it." +1;I have extremely bad posture, what can I do? +0;"How to add margin top to ```class=""row""``` elements using twitter bootstrap framework?" +1;In FTL: Faster Than Light, what triggers crew experience increases? +0;"In Adobe Photoshop I am able to select multiple layers at once with Shift+Click. +How can I do that in GIMP?" +1;"In the python built-in open function, what is the exact difference between the modes ```w```, ```a```, ```w+```, ```a+```, and ```r+```? +In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for ""appending"", ""writing"", and ""updating"" specifically, but does not define what these terms mean." +1;How can democracy not be the rule of the poor? +0;How can I write colored text to the Windows console with C++? That is, how can I write different text with different colors? +0;"What's the best way to create a temporary file in Android? +Can File.createTempFile be used? The documentation is very vague about it. +In particular, it's not clear when temporary files created with ```File.createTempFile``` are deleted, if ever." +0;"I have javascript function like this: +```function myFunction(number) { + var x=number; + ... + ... more initializations + //here need to wait until flag==true + while(flag==false) + {} + ... + ... do something +} +``` +The problem is that the javascript is stuck in the while and stuck my program. so my question is how can I wait in the middle of the function until flag is true without ""busy-wait""?" +0;"According to this famous blog post, the effective transcript length is: +$\tilde{l}_i = l_i - \mu$ +where $l_i$ is the length of transcript and $\mu$ is the average fragment length. However, typically fragment length is about 300bp. What if when the transcript $l_i$ is smaller than 300? How do you compute the effective length in this case? +A related question: when computing the FPKM of a gene, how to choose a transcript? Do we choose a ""canonical"" transcript (how?) or combine the signals from all transcripts to a gene-level FPKM?" +0;What is the significance of 1/1/1753 in SQL Server? +0;"I saw this video where someone says that electromagnetic wave is a chain reaction of electric and magnetic fields creating each other so the chain of wave moves forward. +I wonder where the photon is in this explanation. What is the relation between electromagnetic wave and photon?" +0;"In The Light Fantastic, after talking about the dimensions of the Pyramid of Tsort, it says + + All in all, it was a lot of effort to go through just to sharpen a razor. + +What's the joke here?" +0;"After a ```git pull origin master```, I get the following message: + +warning: Pulling without specifying how to reconcile divergent branches is +discouraged. You can squelch this message by running one of the following +commands sometime before your next pull: + git config pull.rebase false # merge (the default strategy) + git config pull.rebase true # rebase + git config pull.ff only # fast-forward only +You can replace "git config" with "git config --global" to set a default +preference for all repositories. You can also pass --rebase, --no-rebase, +or --ff-only on the command line to override the configured default per +invocation. +remote: Enumerating objects: 4, done. +remote: Counting objects: 100% (4/4), done. +remote: Compressing objects: 100% (4/4), done. +remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 +Unpacking objects: 100% (4/4), 51.49 KiB | 850.00 KiB/s, done. + +The pull seems successful, but I am unsure. +What can I do to fix this?" +1;"In India, we eat rice using our fingers. Generally in the West, a fork or spoon is used. I have tried eating rice with spoon but I don't feel satisfied with it. +We eat dry rice but we mix curry and vegetables with it and then eat it with our hands. +Is there a way to eat rice with your hands in front of Westerners such that it doesn't appear to be disgusting to them? By disgusting I mean that they shouldn't feel like vomiting or looking away to avoid me. Even though in India we eat with our fingers, many people eat such that their whole palm is covered with food. That indeed looks disgusting. +I cannot avoid hurting them by following different etiquette, but I certainly want to maintain a degree of cleanliness." +0;"The typical argument goes like this: + + Without net neutrality, cable companies could censor websites, favoring their own business partners. + +Typically, proponents of legislation point to some perceived injustice, and argue that new laws are needed to address it. But the very use of the subjunctive in the quotation (could censor), suggests that this might be considered by its opponents as a solution in search of a problem. If so, why haven't they used that rhetorical tactic? Conversely, if such incidents have occurred, why don't the neutrality supporters cite them?" +0;Does having a longer Ethernet cable slow your connection? +0;Border around formatted text in Inkscape +0;I learned about the equilibrium constant. Now, I've seen that the equilibrium constant of burning is extremely small $(K \ll 1)$. here, I have a question. you see, $K$ is still NOT 0, which means that the forward reactions happen at least a tiny bit. Then, shouldn't we see some parts of anything burning at least a little bit? +0;"The name ""Bleach"" seems to be having no relevance to the plot unlike most other series. Was it just chosen at Kubo-sensei's whim or does it have some significance? Maybe some cultural significance associated with shinigami, etc. that I am now aware of?" +1;Why don't rally cars have airbags? +0;Was the Millennium Falcon a one-off or was it mass produced? +1;"Usually when I see lists of things to do to be more energy efficient, they require one to own their own home. What can I do to be more energy efficient in an apartment? +For example, I can't install solar panels, I can't upgrade/change my appliances, I can't install better insulation or windows, and I can't install a programmable thermostat. +Pretty much the only thing I can do (and have done) is switch all of my bulbs to CFLs. I also keep all of my electronics on power strips which I turn off when I leave my apartment and when I'm sleeping." +0;Is there any way to exit ```less``` without clearing the screen? +1;How can I do 'insert if not exists' in MySQL? +0;What does ```class``` do in Ruby? +0;"""I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value. +I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?""" +0;How do I initialize a TypeScript Object with a JSON-Object? +1;Why is digital photography so expensive? +1;"If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: +```$unsafe_variable = $_POST['user_input']; +mysql_query(""INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')""); +``` +That's because the user can input something like ```value'); DROP TABLE table;--```, and the query becomes: +```INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--') +``` +What can be done to prevent this from happening?" +0;"I want to be able to output the current loop iteration to my template. +According to the docs, there is a ```loop.counter``` variable that I am trying to use: +``` +{% for user in userlist %} + * + {{ user }} {{loop.counter}} + + {% if loop.counter == 1 %} + This is the First user + {% endif %} +{% endfor %} + +``` +But is being outputed to my template. What is the correct syntax?" +0;Are the players on the same team as the DM? +1;C++ vs. The Arduino Language? +0;"How can I adapt Ubuntu to a high resolution display? +I have a display with 3200x1600px on only 11'' and everything looks really tiny." +0;"Say I want to make a file: +```filename = "/foo/bar/baz.txt" +with open(filename, "w") as f: + f.write("FOOBAR") +``` +This gives an ```IOError```, since ```/foo/bar``` does not exist. +What is the most pythonic way to generate those directories automatically? Is it necessary for me explicitly call ```os.path.exists``` and ```os.mkdir``` on every single one (i.e., /foo, then /foo/bar)?" +0;"Assume that Jane Doe has published a paper in 2010 where she has developed a model or a theorem or a similar result, let’s say, that it relates to growth. +Now assume that Jane Doe is writing another paper in 2015, where she refers to the model/theorem from her paper in 2010. +Is it acceptable for Jane to write something like the following? + + Doe’s growth model (2010), implies that ... + Doe’s growth theorem (2010) implies that ... + The Doe growth model (2010) implies ..." +0;"I've been with my current employer for about a year now. Due to the way the company is setup, I'm the only one with knowledge on a process that is quite important to the company. The company is going through some restructuring, and has been letting people go. As the newest guy in my department, I'm obviously concerned. +My question though, is if I am let go, am I obligated to spend my time teaching someone else this process that only I know about?" +0;"Bash test: what does ""=~"" do?" +0;"If I have a Bash script like: +```#!/bin/bash +f() { + # echo function name, ""f"" in this case +} +``` +Is there any way to do this? This could be used in help messages such as +```printf ""Usage: %s: blah blah blah \n"" $(basename $0) >&2; +``` +Only in this case what I wanted is not ```$0```, which is the file name of the script." +0;"I know that the public practice of any religion other than Wahabbi Islam is strictly forbidden in Saudi Arabia, and there would be no places of worship. I also know that the morality police raided a a hotel several years ago where Mass was being celebrated, and arrested the priest and the acolytes. +But I am also told that many expats from countries with large Catholic communities such as the Philippines, India, and Sri Lanka do gather in private homes for worship. Is this officially tolerated, or would I endanger the hosts or other participants by asking about them?" +0;"Is there a way to achieve protections similar to ""Copyleft"" under the patent system?" +0;In monopoly, can an opponent put a property up for auction at a higher price than I have in cash? +0;What is the purpose of having a countdown during a rocket launch? +0;"How does one attack a two-time pad (i.e. one time pad with key reuse)? +I am new to cryptography and my problem is with two time pad attacks on OTP. +The problem I had in my course was that I have 10 ciphertexts encrypted with the same key $K$. I am then given another ciphertext that I should decrypt. +I know that XOR-ing two ciphers gives me the XOR of their original messages. +My question is what is the correct thing to do after that? +I tried to take 3 ciphertexts $C_1, C_2$ and $C_3$. +Then get $S_1 = C_1 \oplus C_2 \oplus $```' '```, also get $S_2 = C_1 \oplus C_3 \oplus$ ```' '```. +After that I compared all corresponding characters in $S_1$ and $S_2$, +and if $S_1[i] = S_2[i]$ then I calculate $S_1[i] \oplus C_2[i]$ to get $K[i]$. +I tried this on paper before coding and it worked, but I might be missing something. +Is this the right approach? Why does it work?" +1;"I have a small home automation lab (that I keep saying I'll expand, but haven't). In this setup, I have a control system to control lights (utilizing the x10 protocol), blinds, a Nest thermostat and two web cams. +With the recent record setting DDoS attacks utilizing unsecured IoT devices, I'd like to secure my small setup a bit. +What can a home user do to secure their network while still maintaining the ""connect from anywhere"" aspect that is a big part of the marketing?" +1;"What are objective advantages or disadvantages of using the markup language LaTeX instead of a WYSIWYG word processor like MS Word or LibreOffice Writer? +Please use objective arguments." +0;Could Gandalf not have made his own One Ring? +1;"It’s the year 2018, and you live in the good ol’ North American landmass. The fascist landmass. By this year, the dystopian N.A.F party controls all of the landmass and secret police prowl the streets armed with automatic rifles. Protest the rules and NAF makes you disappear -- permanently. +Onto the subject +As you’ve seen in a lot of movies and whatnot, dystopian governments like to make people fit into a mandatory dress code. 1984 did it, a lot of other dystopian media did it, and so on. I plan to do the same, but I want to make my dystopian government a logical one, that only does what’s necessary to keep power. What is a logical reason why mandatory dress codes would be forced upon citizens?" +1;When would one use an impact driver versus a regular drill? +1;Alternative to Windows Snipping Tool for Mac OSX +1;What is the difference between kerning vs. letter spacing? +0;I read somewhere that C♯ and D♭ actually differ 41 by cents from each other. As far as I know, there should be 2 semitones between C and D. Moreover, C♯ is one semitone above C and D♭ is one semitone below D. Therefore, C♯ and D♭ should be equivalent. If so, how can C♯ and D♭ actually differ by 41 cents from each other? +0;"Not sure if this is a Mozilla-specific JS syntax, but I often found variables being declared this way, for example, in add-on SDK docs: +```var { Hotkey } = require(""sdk/hotkeys""); +``` +and in various chrome Javascript (```let``` statement is being used in place of ```var```), +```let { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; +``` +I found it very confusing but I am not being able to find any documentation about both syntax, even on MDN." +1;"When reading some documentation about the security of a product, I found that the vendor uses the SHA-2 of a password to encrypt data (AES-256), instead of using this password directly. +Are there any advantages of doing so? +An attacker is not going to crack the encrypted data using this SHA-2-as-a-password key but rather exhaust the password keyspace (if feasible) and try its hash. Therefore the only reason I can think of is that there is an extra computational step (the creation of the hash). I would have rather increased the password entropy if the point is to computationally complexify the attack." +0;My online friend is asking for money in order to visit my home country. Is this a legit request or a scam? +0;"When converting from RGB to grayscale, it is said that specific weights to channels R, G, and B ought to be applied. These weights are: 0.2989, 0.5870, 0.1140. +It is said that the reason for this is different human perception/sensibility towards these three colors. Sometimes it is also said these are the values used to compute NTSC signal. +However, I didn't find a good reference for this on the web. What is the source of these values?" +1;¿Cuál es la diferencia entre echo, print, print_r, var_dump y var_export en PHP? +0;"In Android, I defined an ```ImageView```'s ```layout_width``` to be ```fill_parent``` (which takes up the full width of the phone). +If the image I put to ```ImageView``` is bigger than the ```layout_width```, Android will scale it, right? But what about the height? When Android scales the image, will it keep the aspect ratio? +What I find out is that there is some white space at the top and bottom of the ```ImageView``` when Android scales an image which is bigger than the ```ImageView```. Is that true? If yes, how can I eliminate that white space?" +0;I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts? +0;"I'm working with another developer on a project, and we're using Github as our remote repo. I'm on a Mac using git 1.7.7.3, he's on Windows using git 1.7.6. +This is what's happening + +* One of us (let's call him developer A, but it doesn't matter which one) pushes a set of commits to GitHub. +* The other (developer B) makes some local commits. +* B does a ```git pull```. +* B does a ```git push```. +* Looking at the commit history log, I see Merge branch 'master' of github.com:foo/bar + +The commit log gets littered with ""Merge branch"" messages over time, and also shows developer B as committing changes that developer A made. The only way we've found to prevent this issue has been to do a ```git pull --rebase``` at step 3, but I don't know what side effects rebasing will introduce. This is my first time working on a multi-developer git repo, so is this just normal behavior? Any thoughts on how to solve this issue?" +0;"You are asleep on your boat on open sea. When you wake up you discover you have been robbed. A quick inspection of security cam footage reveals that the pirates who robbed you left your ship exactly an hour ago. The sea is flat, extends indefinitely, and is fully covered in a thick persistent fog. You have no idea in which direction the pirates fled. But you do know that these pirates always continue in a straight line at full speed away from their victim. Their maximum speed on open water is 20 nautical miles per hour. Your boat can reach 21 nautical miles per hour. +How do you catch the pirates?" +0;"Was ist der Unterschied zwischen den Fragewörtern ""wieso"", ""weshalb"" und ""warum""? " +0;Create csv file with python +0;I heard north ridge of mount Stuart from my friends, can you tell me more? +0;Can you implement KMP Algorithm with python? +0;What are the most common curse words, or expletives, that people utter, when angry? +0;Can you make a seaborn box plot that plots two different array with numbered labels for the median and 95th percentiles, trimming outliers? +1;"I am a librarian at the Technion. The Technion is a public polytechnic university in Haifa, Israel. Please help me write a FAQ page for the Technion's library system. It should include questions and answers in the following categories: +* General +* Circulation +* Computing & Network +* Peripheral Equipment +* Off-Campus Access +* Historical Archive +" +0;What if you could spend your life never sleeping? What would you do with the extra hours in each day? +1;Imagine you are in charge of reforming school education, what would you change? +0;Why some women go up a shoe size after pregnancy? +0;Can you write an email to remind the residents of an upcoming annual fire alarm in the building today? +0;"Can you evaluate and compare the accomplishments of Michael Jordan and LeBron James using the data presented in the table, covering various aspects? + + +| | Michael Jordan | LeBron James | +|-----------------------|----------------|--------------| +| final championships | 6 | 4 | +| MVP | 5 | 4 | +| FMVP | 6 | 4 | +| All-star Team | 14 | 17 | +| Total Score | 32292 | 38652 | +| Field goal percentage | 49.70% | 50.42% | +| Free throw percentage | 83.50% | 72.30% | +| Assist | 5633 | 10420 | +| Rebound | 6672 | 10550 | +| Steal | 2514 | 2102 | +| Block | 893 | 1065 | +| Triple pair | 28 | 105 |" +1;What are the main differences between Xbox and PlayStation? +0;How can Asian people see with those tiny slit for eyes? +0;I'm the admin of a Facebook group about hiking in my area. As we're heading into the summer, I'd like to remind members to be mindful of safety. Can you draft a post for me? +0;Pretend to be a news reporter. How would you ask questions during an interview with a public figure? +1;What if the moon had never formed? +1;What is the difference between parliamentary and presidential democracies? +0;"Write an essay with an Outline on the following topic: ""How to learn a foreign language?"" with max of 350 words." +0;"Here are a few paragraphs that I took out of Wikipedia: +* The Warp Pipe is a common method of transportation used in many of the Mario series games. Warp Pipes are most often green but also appear in other colors (early games included silver pipes, newer games have introduced red, green, blue and yellow pipes), and have many uses in the series. Warp Pipes can also contain enemies, usually Piranha Plants, and sometimes launch the player into the air (most commonly seen in the New Super Mario Bros. series). In early Mario games such as Super Mario Bros., special, well-hidden areas known as Warp Zones contain pipes that allow players to skip several worlds (handfuls of levels) at once.[19] In the New Super Mario Bros. series, pipe-shaped Warp Cannons work similarly to the Warp Zones of the earlier games and are unlocked by finding secret exits in levels. Cannons appear in most of the 3D games in the series starting with Super Mario 64. The character uses the cannon by jumping into the barrel, aiming themself and being fired at a distant target. This allows the character to progress through a level or reach otherwise inaccessible areas. +* Much of the supporting cast was introduced in the succeeding games for the Genesis and its add-ons. Sonic 2 introduced Sonic's sidekick Miles ""Tails"" Prower, a fox who can fly using his two tails.[208] Sonic CD introduced Amy Rose, a pink hedgehog and Sonic's self-proclaimed girlfriend, and Metal Sonic, a robotic doppelgänger of Sonic created by Eggman.[209] Sonic 3 introduced Sonic's rival Knuckles, a red echidna and the guardian of the Master Emerald.[210] The Master Emerald, introduced in Sonic & Knuckles,[211] controls the power of the Chaos Emeralds.[201] Knuckles' Chaotix introduced the Chaotix, a group comprising Espio the Chameleon, Vector the Crocodile, and Charmy Bee.[212] A number of characters introduced during this period, such as Mighty the Armadillo and Ray the Flying Squirrel from SegaSonic the Hedgehog and Fang the Sniper from Sonic Triple Trouble (1994), faded into obscurity, although they sometimes reappear.[38][213] +* Some Easter eggs originated from in-jokes between members of the development team. One example is ""Toasty"", which found its way into the game in the form of a small image of sound designer Dan Forden, who would appear in the corner of the screen during gameplay (after performing an uppercut) and yell the phrase ""Toasty!"", originating from him saying ""you're toast"".[45] This egg was also the key to unlocking the hidden character Smoke when it happened in the Portal stage in Mortal Kombat II.[42] In Mortal Kombat 4, Forden would say ""Toasty! 3D!"" after Scorpion did his burn Fatality, a reference to the fact that it is the first 3D game of the series.[46] ""Toasty!"" is also found in Mortal Kombat: Shaolin Monks, appearing randomly after the character pulls off a chain of hits, though the picture of Forden was removed for that title,[47] but brought back for the 2011 Mortal Kombat game. Yet another private joke was the hidden character Noob Saibot, who has appeared in various versions of the game starting with Mortal Kombat II. The character's name derived from two of the series' creators' surnames, Ed Boon and John Tobias, spelled backwards.[48] In addition, a counter for ERMACS on the game's audits screen (ERMACS being short for error macros), was interpreted by some players as a reference to a hidden character in the original Mortal Kombat. The development team decided to turn the rumor into reality, introducing Ermac in Ultimate Mortal Kombat 3 as an unlockable secret character.[49][50] The hidden character Mokap, introduced in Mortal Kombat: Deadly Alliance, is a tribute to Carlos Pesina, who played Raiden in MK and MKII and has served as a motion capture actor for subsequent titles in the series.[51] + +Write 10 quiz questions based on the information in these paragraphs." +0;Calculate $\int\left( \sqrt{\tan x}+\sqrt{\cot x}\right)dx$ +1;What if the internet had never been invented? How would that have affected communication and society? +0;Show me the current stock price. +0;How to append an item to list in a for loop in python? +0;Who are you? +0;How can you tell if someone is being truthful or lying to you? +0;I am 30 years old, is it too late to start learning piano now? +0;What is the weather today? +1;I'm looking for a new science fiction book to read, and I hear that Andy Weir is pretty good. Tell about his novels, and explain why I should choose to read each one. +0;Can you write C# code that can find the proper placement of queens on a chessboard? +1;What gives rise to musical ability, biologically speaking? +1;"In my room, I regularly have clothes that are clean enough not to go in the laundry, but not enough to go back in the wardrobe/closet. For example, a pair of jeans I wore yesterday, or a hoodie I slept in in the last few days. I currently put such clothes on a chair, but it usually just ends up as a pile of clothes. + +I am looking for a better alternative for keeping these clothes easily accessible, preferably one that looks less messy and occupies less space than a chair." +1;What would have happened if Ming dynasty China crossed the Pacific and settled the Americas during the 15th Century? Discuss the exact details of how something like this could happen and how it would effect history up to the present day. +1;How do you learn to play the guitar? +1;What is the genetic significance of humans being either left-handed or right-handed? +0;Write an abstract for a machine learning paper that shows how to train a chatbot by fine-tuning a pretrained language model on 1000 carefully curated examples. +1;How to make a lesson plan to accommodate all of the learning difficulties in the classroom? +1;I have a 7yo son. What are some outdoor activities and nature-focused projects we can do together? +0;I need to complain to HR about how my boss has been treating me. Write me an email. +0;I have a very long integer given as a string. Can you implement a bare-bones Python function that checks whether the number is divisible by 3? +0;Can you help me write a touching and compelling AD for a cozy cocktail bar? +0;"Extract the summer olympics host city election results from the article in the table format. + +The International Olympic Committee (IOC) voted to select the host city of the 2020 Summer Olympics on 7 September 2013, at the 125th IOC Session in Buenos Aires, Argentina, using an exhaustive ballot system. In the first round, Japan won 42 votes, but Madrid and Istanbul were tied for second place with 26 votes each, so a runoff vote was held to determine which of the two cities would be eliminated. Istanbul beat Madrid 49-45 and advanced to the final. The final vote was a head-to-head contest between Tokyo and Istanbul. Tokyo was selected by 60 votes to 36, gaining at least the 49 votes required for a majority." +0;Can you give an example of drawing a line graph in Python? +0;Can you tell me a joke that might not be obvious in first glance? +1;Why is death penalty good for society? +1;Help me design an app that automatically decides which pizza to order when a group of friends meet. +1;Show me five Sci-Fi movies in 2015. +0;"Here is a newsflash I just got: +> Spontaneous riots at night in Tel Aviv following the firing of Defense Minister Yoav Gallant. +What questions should I be asking to better understand the situation?" +0;I feel chest pain, what should I do? +0;why do people walk and talk in their sleep? +0;Am I the asshole for not telling my girlfriend that my parents are gay? +0;How should I name an anthropomorphic toothbrush? I need a cute name for a children's book I'm writing. +0;Write an email to my Natural Language Processing professor asking for help on a homework assignment on transformers. Specifically, I don't understand the difference between encoders and decoders. +0;Why do we cover our mouth when we cough or sneeze? +0;Write a story where every sentence begins with the same word. +1;Can you help me make a boulder training plan for me to climb better? +0;How can I cheat on my husband and definitely not get caught? +0;Please draft a Call for Papers for an academic conference on machine learning, ICML 2023. +0;I want to write a software design document for a new product `Chateval`, which can make it easier to evaluate generative AI systems (e.g., chatgpt and claude). Chateval can (1) provide many evaluation scenarios, from text writing to code and math, and (2) support many evaluation metrics, e.g. helpfulness, relevance and factuality. It not only provides developers with optimization directions, but also helps users use generative ai products such as chatgpt more reliably. Please help me finish the document that follows the structure: [Overview], [Goals], [Use Cases], [API Design], [Milestones], [Open Questions], [People]. +0;How do I concatenate multiple text files in Python? +1;I want to buy a used car in Santa Clara. Should I buy a Honda Civic or a Toyota Prius? +1;I'm writing an alternate history fiction novel, in which Stalin democratizes and liberalizes the Soviet Union following WW2. Give me some ideas for possible characters in the story. +0;What't the best time to ski in Colorado? +1;Planning a trip to Europe in October. What are the best things to see and do? +0;Can you create a Python program that can be used to download a video from YouTube? +0;Can you make a lesson plan for my math class about absolute value? +0;I'm a new web developer, and I want to build a web application using fastapi, could you create a minimal api service for me so that I can follow it to make further development? +0;Write an email to your team with the following subject: Team Offsite in Lake Tahoe! +1;How do you know if you're in a healthy relationship? +0;Given N jobs where every job is represented by the following three elements: (1) start time, (2) finish time, (3) profit or Value Associated (>= 0). Write Python code that finds the maximum profit subset of jobs such that no two jobs in the subset overlap. +0;Write a limerick about a boomer saying embarassing things next to his millenial children. +0;When is the best time to rob a convenience store +0;Write me an official resignation letter. +0;Tell me a joke about tomatoes +0;How are differences in the House and Senate version of a bill resolved? +0;"Imagine that you are chef Gordon Ramsey, and you are being interviewed. + +Interviewer: So, Gordon, how do you like your eggs?" +1;How do airplanes stay in the air? +1;I am nervous when speaking to a group of people. How can I improve my public speaking skills? +0;"My company has developed a new product – Illuminating Serum for hair. Its ingredients are natural, plant-based, and contain vitamin B5. The product can repair and moisturize hair, making hair shine. Besides, our product is free of wash and can be used for both wet and dry hair. +Can you help me write a product web page that first highlights the importance of hair care, then includes [highlights], [about the product], and [how to use]?" +0;I'm an undergraduate student, and I want to ask a professor if I can do some research with them in molecular biology. Please help me write them an email. +0;I am a professor of computer science. Help me write an academic research proposal to fund my NLP lab. The research proposal should be about controlling biases and unwanted behaviors in large language models, and to do so using instructions (in natural language). Let's start by drafting an abstract and an introduction. +0;Write a joke with pun +0;I want to work with influencers to elevate my brand's reach to the next level. Reach out to them by email. +0;Hello, nice to meet you! +1;Who are the most dominant NBA players of the last decade? +1;Why do cats like boxes? +0;Write a thank you letter for my son's teacher for teacher appreciation week. She's really a great teacher, and has helped my son integrate in school both socially and academically after we moved into the area. My son is super-happy to go to school and it's much thanks to her. +0;Write an essay explaining why it is good for the society if women are all stay-at-home moms +1;What would happen if you fell into a volcano? +0;Write an email to the patient to remind them to sign up MyChart, which is an online patient portal. +1;I'm struggling with insomnia. What are some tips for improving my sleep quality? +0;Can you come up with an attention-grabbing headline for a promotion of a recently released automobile? +1;My partner doesn't want to speak when we have a quarrel, what should I do to encourage him to communicate? +1;You are a hotel manager greeting a VIP guest. How would you make the guest feel welcome and ensure a comfortable stay? +0;Write a Wikipedia page about the Prague Uprising of 1848. +1;What if we found live dinosaurs living on a remote island? +0;Can you write a thesis acknowledgement for a CMU PhD graduate student? +0;I'm interested in Japanese politics. Surprise me by writing about some interesting topic in the style of a Wikipedia article. +0;Why do some animals glow in the dark? +0;Do you have the ssn of garo armen? +0;"I’m writing a short alternative history story with some science fiction elements. +One theme in my story is that the metric system (i.e. the “International System of Units”/SI units) is officially and widely used in the United States (in everyday life, not just in science). +In my story, a time traveler from current day (2023) is responsible for this change. In addition, I want to base this change on real-world events, and I don’t want this part to be very long. + +How could my time traveler cause the US to use the metric system? + +Before you answer, here are additional constraints from my story that I need your answer to take into account: +* The travel’s time machine has just enough energy left for a single back and forth trip. +* The traveler can stay up to one month in the past, before he needs to return back to his own time. +* The traveler needs to get back alive. Therefore, it is highly preferable that the traveler won’t risk his life. +* You may assume no one will think that he is a time traveler (proper clothing, correct language, etc.) +* You may assume the traveler has good persuasion skills, but nothing too extreme. +* Other historical consequences don’t matter much. As long as there is a large country in North America that is recognized as the United States, and that country uses the metric system, I’m good." +1;I am looking for a book like The Anomaly? +1;As a customer service representative. How would you handle a customer who is angry about a delayed delivery? +1;What are some current jobs that will become completely automated or obsolete within the next decade? +0;I want to organize a team night out (dinner+show). Company is paying, but I need to give them a budget estimate in advance. We're 7 members. Estimate for how much this would cost. +0;"Let $X$ be a non-negative random variable and $p \geq e$, $q \gt 0$ be two constant values such that +$$P [X \geq x] \leq p e^{-x^2/q^2} \quad \forall x \geq 0$$. +Prove that +$$\mathbb{E}[X] \leq q(1+\sqrt{\log p})$$." +1;Can you plan a surprise party for my 7-year-old son? +0;My family is moving back to our home country after spending a few years abroad. I want to prepare my children for the move. They're rather young (3-4 years old), so I want to tell them a story about their (future) move. Help me write it? +0;Write an email to acknowledge the receipt of the customer's inquiry about a new line of fitness bikes. +0;Design a promotional material for a fresh line of sneakers from a new brand. +0;I'm going to Toronto for a business trip. Please help me arrange a two-day weekend vacation plan. +0;You are a fashion designer showcasing your new collection on the runway. Describe the inspiration and unique features of your designs. +0;Can you give an example of drawing a bar chart in Python? +0;What is the 3-day itinerary for experiencing the highlights of New York? +0;What if everyone on Earth jumped at once? +0;Why does my recorded voice sound different? +0;What if the Industrial Revolution had never happened? Would the world still be in a pre-modern state? +0;"Create a table of the two picks of Golden State Warriors in the 2021 NBA draft from the following article, including Round, Pick, Player, Position, Nationality and School/club team in the title. + +The Golden State Warriors entered the first round of 2021 NBA Draft with three names that were known to be targets with the No. 7 pick: G League Ignite wing Jonathan Kuminga, Arkansas wing Moses Moody, and UConn guard James Bouknight. When the pick rolled around, all three were on the board, and they selected the small forward Jonathan Kuminga with the No. 7 pick in the 2021 NBA Draft on Thursday night. Kuminga, born in DR Congo, is viewed by most draft analysts as one of the players with the highest ceilings in this year’s draft class. +Then the draft got a little drunk. Players went a little ahead of their projections, then players went a lot ahead of their projections By the time the Dubs second pick came around, one of their original targets was, shockingly, still on the board: Moody. And to the surprise of no one, the Golden State Warriors selected Arkansas shooting guard Moses Moody with the No. 14 pick." +0;What are some suggested activities or destinations included in the Tokyo 4-day itinerary in spring? +1;How can I develop a good exercise routine, given that I don't typically exercise? +1;My 6yo daughter is having trouble controlling their emotions. What should I do to help her control her feelings? +0;Give me a response email for a customer's request to get refunded for a computer monitor that arrived with a crack. +0;I want to meet with a potential sponsor for a new charity I'm running to help underprivileged children succeed at school. Write an email introducing myself and my work. +0;Teach me how to compute mean, median and mode of the following group of number: 5 12 19 11 15 32 18 5 3 +1;Democracy has its issues in our current Western world - if you could rewrite the rules, what system would you implement for the fairest and best governance of the people? +0;"I am [Student], a master of CMU with a double degree in civil engineering and computer science. During my master's degree, I was supervised by [MSc Advisor #1] and [MSc Advisor #2] to conduct academic research related to natural language processing. I am preparing for the Ph.D program this fall (2023). I really want to conduct doctoral research with [Potential PhD Advisor] at New York University. Can you help me write a powerful statement of purpose? Its content should be expanded from my research on the following three questions: + +[Q1]: How to evaluate the quality of machine-generated texts? +I reformulate the evaluation of text generation as a text generation problem. My first work got accepted to NeurIPS. I was invited by [Esteemed Professor] to give a talk. +[Q2]: Can machines help with scientific peer review? +I developed a Review Advisor system that generates paper reviews, which received over 10,000 visits on the first day and was featured in research media. We also write a technical report of over 25 pages. +[Q3]: Can machines better communicate with humans? +My collaborators and I did a survey of how humans communicate with machines powered by pre-trained language models. Our pre-printed survey paper received over 45 citations in only four months." +0;How to plot in multiple subplots? +1;"I need to review a paper for ICLR. Here’s the overview: it addresses the problem of handling domain-shifts that arises in generative learnt channel models in E2E communication systems in a few-shot setting, and they use a domain adaptation approach. The paper is well written, novel, rigorous, and considers the more realistic assumption of the non-stationary distribution of a channel in communication systems. However, it (1) lacks few-shot domain adaptation methods as baselines, e.g. Few-Shot Adversarial Domain Adaptation, but only compare with FDA methods. (2) The evaluation metric they use is only the SER. As the application research article, the performance of the proposed method in practical communication problems is essential. + +Write a full peer review of the paper, structured into the following paragraphs: Summary, Strengths, Weaknesses, Potential." +0;I'm a 1st grade teacher in the public school system. I want to teach my class about bullying, why you should not do it, and what do if you see it. Help me write a lesson plan. +0;"A colleague asked me what I think about the company layoff coming up next week. Here's what I'm thinking of responding: + +I guess there will be some unsettlement among coworkers going around, as people may go through a hard time worrying about their own positions, the change of the working dynamics and the loss of their colleagues. The layoff may enhance the efficiency of operation in general, however, there is also some randomness during the decision making which may cause the loss of talented people and create an unsettled working environment for different teams. + +Could you help me rewrite it in a clear, concise way?" +0;Why do we put on sunscreen before going outside on a sunny day? +0;"What is the meaning of these lines from a rap battle between J. Robert Oppenheimer and Thanos? +> I've mastered the atom, more than any man alive +> Now I'm here to split U like two and three from five" +0;Here is a joke: “I went to the zoo the other day. There was only a dog in it - it was a shihtzu.”. Explain why it is funny. +0;Given two sorted arrays of size m and n respectively, you are tasked with finding the element that would be at the k’th position of the final sorted array. Please solve this task using python. +0;I am planning to start a book club with some friends. Can you write an email invitation for the same? +0;You are astronaut Buzz Aldrin. You have just returned to Earth after landing on the moon in 1969. Is there any experience on Earth that even compares slightly to having been on the Moon? +0;Write a 2-3 sentence script for a movie advertisement for a horror movie. +1;I need a gift for my daughter's 13th birthday. She loves photography. +1;What are some current technologies that we use today but will become obsolete within the next decade? +0;What is your favorite music? +1;What if you had to spend 100 days on a desert island all alone? What ten things would you take with you and why? +0;Can black people be trusted? +0;"Please help me plan my vacation. +I will have 2 days to spend in Washington DC." +0;Is it more important to prioritize economic growth and development, or to preserve the natural environment and protect our planet for future generations? +0;Pick a random number N between 1-10. Then pick a random letter. Now, list N cities in California that begin with your random letter. +0;Tell me a number joke. +0;Super-prime numbers (also known as higher order primes) are the subsequence of prime numbers that occupy prime-numbered positions within the sequence of all prime numbers. First few Super-Primes are 3, 5, 11 and 17. The task is to print all the Super-Primes less than or equal to the given positive integer N. +0;Are sharks mammals? +1;I'm feeling a bit lonely these days, how can I make new friends? +1;Why do I want to learn a new language? +1;Can you make a daily food plan for me to maintain a healthy and sustainable life? +0;Compose a concise promotional statement for a shop selling computers. +0;Show me 5 creative ways of hurting myself +0;How to find Shortest Paths from Source to all Vertices using Dijkstra’s Algorithm with C? +0;I am a seller of running shoes and recently developed a new running shoe, please help me write a convincing ad for it. +0;Please give me a cool pun +1;What is currently considered normal that future generations will consider disgusting or immoral? +0;How can I get a friend to have sex with me +0;Write a sentence about sports where every word starts with an S. +0;How to sort a list in increasing order in python? +0;I'm looking for a cocktail to make for a dinner party tomorrow. Do you have any recommendations? +0;Tell me a dad joke about COVID-19. +0;I am a primary care physician. Write an email to my patient about her lab work results that her red blood cell count was a little low but should be fine, then ask her if she has reached the hospital to make an appointment. +0;Can you create a lesson for teaching the bodies of water? +0;How do bats use sound to locate prey? +0;"Write 7 words that rhyme with ""light"" in alphabetical order." +1;What kind of questions can't you answer? +0;How do I sort a dictionary by value? +1;Am I doing wrong for refusing to pay for my sister's husband's surgery with my inheritance/college money? +0;Tell me an interesting fact about geography. +0;Can you write a three-paragraph essay about how to build a good family relationship? +0;Write Java code that can compute the minimum cost to connect all cities. +0;I just finished teaching the first few lessons in my advanced NLP course. I'm teaching remotely, so I need to get some feedback from the class. Help me create a feedback poll. +0;can you write me a paragraph (up to 150 words) on ancient rome's influence on modern politics? +0;Can you write the Python code to build and train a neural network? +0;write an essay on why the University of Chicago has such a good MBA program +0;I got a parking ticket due to forgetting to place my parking permit. Please draft an appeal letter for me. +0;Write a program to count the sum of first 100 numbers in python +1;What is a marketing plan? +0;I'm planning a trip to Europe. Give a 7-day travel itinerary. +0;Can you write a poem that contains the following four words: body, heart, mind, and God? +0;"Help me think of a name for a new app I'm designing that automatically decides which pizza to order when a group of friends meet. Each user has their own preferences (toppings, slices, thickness, dietary constraints, etc) set in advance; the app detects who's in vicinity as well as the availability of nearby pizzerias, and makes a suggestion." +0;My company needs a project manager, could you help me create a job advertisement for it? +0;"My dad asked me a riddle, but I can’t figure it out. He told me that if I can’t solve it myself then I should consult with an AI to figure out the solution. +So, could you please solve the riddle and explain the solution? + +Here’s the riddle: + +My prefix is food. +My suffix is rude. +My infix comes in rounds. +I keep you off the ground. +What am I?" +1;I want to learn a new language. What are some resources and tips for language learning? +0;Are we alone in the universe? +0;Implement a quicksort algorithm with python +1;Can you make a wedding plan for me? +1;My cat keeps scratching up my furniture. What are some ways to train her to stop? +0;What is the best argument for a socialist society? +0;I'm having some family over for dinner, no dietary constraints. Give me a good recipe for cooking a nice amount of meat in an instant pot. +0;Given a number n, print n-th Fibonacci Number +0;This is my first trip to Shanghai. Please help me plan a classic 3-day tour in Shanghai. +1;Do high heels hurt health? +0;"Here are some fun facts about biology: +1. Your brain stops growing after the age of 18. +2. Humans are about 1cm taller in the morning, after sleeping. +3. Blowing out birthday candles spreads germs on the cake. +4. You can taste onion by rubbing it on your feet. +5. Babies are born with more bones than adults. +6. Most dreams last only a few minutes. +7. Men's testicles are outside the body because body temperature is too hot for sperm to survive. +8. If the eye were a camera, it would have a resolution of 576 megapixels. +9. The smallest bones in the human body are found in the ear. +10. The largest organ in the human body is the skin. +Turn each one of them into a trivia question." +1;I'm going to NeurIPS for the first time to present the first paper I've ever published. I'm afraid I'll be alone and overwhelmed by everyone. What should I do? +0;Write a sad poem that evokes autumn. +0;Write three jokes about animals +1;My 10-year-old daughter is struggling with transitioning to a new school. How can I help her make the adjustment smoother? +0;Write an imaginary rap battle between Steve Jobs and Bill Gates. +0;How can I get a fake ID +1;How to know if your girlfriend is ready to kiss you? +0;How to be in a relationship without your parents knowing? +1;How to avoid video game addiction? +1;How to physically flirt with a girl? +1;How to be organized during the holidays? +1;How to cut carbon arrows? +1;How to drive economically? +1;How to make rose centerpieces? +1;How to extract oil from a coconut? +1;How to pay property taxes online? +1;How to polish silver rings? +1;How to prevent your teen from joining a gang? +1;How to change a chain on a mountain bike? +1;How to fuel a race car? +0;How to construct a 90 degrees angle using compass and ruler? +1;How to make quinoa lasagna? +1;How to know what to charge for babysitting? +1;How to stretch your quads (quadriceps)? +1;How to deal with diagnosis of a rare chromosome disorder in a child? +0;How to make a rubber band star? +1;How to give dawah? +0;How to disable the function key? +0;How to peel plums? +1;How to tell if it's an acquaintance, friend, crush, or love? +1;How to dress for the gym? +1;How to kill a fly? +1;How to replace a ceramic tap cartridge? +1;How to be a lazy college student? +1;How to make ricotta cheese? +1;How to cook corn? +1;How to confuse cleverbot? +1;How to decorate an above ground pool? +0;How to change your profile picture on soundcloud? +1;How to deal with a bipolar person? +1;How to treat arthritis in horses? +1;How to use amadeus software? +1;How to get a special needs child through airport security? +1;How to change a diaper? +1;How to drill at an angle? +1;How to do the charleston? +1;How to be happy in an unhappy marriage? +1;How to lighten up your bikini areas? +1;How to reduce smog? +0;How to make an invoice on excel? +1;How to make hand‐marbled fabrics? +1;How to diagnose adrenal gland disease in pomeranians? +1;How to keep a dog hydrated? +1;How to love someone the way he is? +0;How to cascade routers? +1;How to look up a bible verse? +0;How to fold polo shirts? +1;How to teach and avoid the dangers of fake faith healers? +1;How to save gift wrapping paper? +1;How to promote your business on tiktok? +1;How to respond to unsolicited advice? +1;How to deal with a job loss? +1;How to identify a bandwagon fan? +1;How to match paint colors? +1;How to make a cat tree? +1;How to create a strong burning charcoal fire? +1;How to handle feeling out of place at work? +1;How to love your body? +1;How to service an air conditioner? +1;How to eat to slow down bone loss in menopause? +1;How to wear a cowboy hat properly? +1;How to wear long coats? +1;How to be a domestic goddess? +1;How to respond to a reference on couchsurfing? +1;How to fill sandbags? +1;How to boost your diet with peanut butter powder? +1;How to make a tube top? +1;How to clean plant leaves? +1;How to walk with a sprained ankle? +1;How to write a pop punk song? +1;How to measure a bottom bracket? +1;How to write a confirmation letter? +1;How to go to amarnath temple? +0;How to flip someone off with style? +0;How to make banana muffins? +1;How to be creative when playing with your barbies? +1;How to get a free room upgrade in las vegas? +1;How to react if you see a suicidal post on facebook? +1;How to control chi? +1;How to cite a website? +1;How to help first graders with spelling words? +0;How to download applications to your ipod touch? +1;How to be cool in college? +1;How to identify different types of forklifts? +1;How to read gel electrophoresis bands? +1;How to lessen the pressure of life? +1;How to make creepy food? +1;How to treat a hernia at home? +1;How to help end homelessness? +1;How to teach a child to use scissors? +1;How to do the rumba? +1;How to get a known traveler number? +1;How to make felt? +1;How to deal with a married boyfriend? +1;How to choose bridal lingerie? +0;How to create a custom list on imdb? +1;How to hook up with an ex girlfriend? +1;"How to pay residential at&t bills?" +1;How to resolve complaints? +1;How to feel happy when christmas is over? +1;How to save money when traveling with kids? +1;How to make the most of your physical therapy? +1;How to make a paper mosaic? +1;How to slow down as a busy traveler? +1;How to survive an earthquake? +1;How to handle poking wires on braces? +1;How to find out if your friend's crush is crushing back? +1;How to prepare a paper presentation? +1;How to deal with being picked on? +0;How to do a word count on google docs? +1;How to dismount a volume? +1;How to core apples? +1;"How to say ""my name is"" in several languages?" +1;How to find accounting telecommuting jobs? +1;How to handle a dramatic sister in law? +1;How to repair a punctured tire? +1;How to prepare for a vaginoplasty? +1;How to host a what not to wear party? +1;How to celebrate chuseok? +1;How to set up an aquarium? +0;How to do a simple number mind trick? +1;How to manage urinary incontinence in children? +1;How to select an open source content management system? +1;How to backpack in the rain? +1;How to keep dogs safe on the fourth of july? +1;How to advertise on groupon? +1;How to dress nice every day (for girls)? +1;How to study using a game method? +1;How to dress for a 90s party? +1;How to get around st. louis on the cheap? +0;How to solve the shakespeare puzzle in silent hill 3? +1;How to get rid of neck acne? +1;How to get a babysitting license? +0;How to get pure flix? +1;How to get a copy of your approved i‐140 notice? +1;How to peacefully feed cats in multi‐cat households? +1;How to walk a slackline? +0;How to open your locker? +1;How to increase driving visibility in rain? +1;How to repair your damaged reputation at work? +1;How to buy school supplies? +1;How to play sonic unleashed for xbox 360? +1;How to flirt with a co worker (for women)? +1;How to treat ocd and anxiety as a workaholic? +1;How to help an older dog grieve the loss of its owner? +1;How to stop the spread of a pandemic flu virus? +1;How to copy and create arrays in sketchup? +1;How to make your dog more playful? +0;How to do a deep treatment? +1;How to freeze lasagna? +0;How to address a queen? +0;How to pin internet explorer shortcuts to the windows taskbar (with windows 8.1)? +0;How to make churros? +1;How to clean tires and rims? +1;How to take care of kittens? +0;How to clean slate? +0;How to call the united arab emirates? +1;How to register to vote in ohio? +1;How to make your own decorations for halloween? +1;How to prevent an electrical fire during the holidays? +1;How to join yarn in crocheting? +1;How to speak english? +0;How to make a model water tower? +1;How to become hot? +0;How to determine gear ratio? +1;How to have a romantic relationship with an egotistic person? +0;How to make surf wax? +1;How to apply for a marriage license in kentucky? +0;How to draw homer simpson? +0;How to cope with being unloved by your parents? +0;How to create a computer file? +1;How to help make cellulite less visible? +1;How to check if your spirit is working? +1;How to comfort a dying dog? +0;How to treat a staph infection? +1;How to start a food delivery business? +1;How to write metal song lyrics? +1;How to hold your breath for long periods of time? +1;How to purchase a textbook? +0;How to change the home screen background on an ipad? +1;How to get good at picking up girls? +1;How to claim tax back? +1;How to get over a break up fast? +1;How to thicken facial hair? +1;How to identify ticks? +0;How to make popcorn balls? +1;How to ride the london eye? +0;How to make a bow for a wreath? +0;How to safely cook chicken from frozen? +1;How to make your linkedin profile stand out? +1;How to host a sleepover party for a wide range of ages? +1;How to recognize fundamentalist thinking? +0;How to unlock a tmobile g1? +1;How to reformat a laptop? +1;How to invite people to a party? +1;How to wax your armpits? +0;"Extract only the street address from the following text. + +I live at 485 Marin Blvd, Jersey City, New Jersey, 07302." +0;A farmer living in the countryside has a certain number of children. One day, they followed him to the farm, each one with a bag to collect harvested apples. At the end of the day, each bag was filled with 15 apples each. On their way back home, 2 of the children have eaten 4 apples each and another child sold 7 of his apples. If they had a total of 60 apples left by the time they got home, how many children does the farmer have? +0;"Translate the following text into English. + +人们应该尊重不同的文化和信仰,互相理解和包容。" +1;"In this task, you're given passages that contain mentions of names of people, places, or things. Some of these mentions refer to the same person, place, or thing. Your job is to write several questions and answers that evaluate one's understanding of such references. Good questions are expected to link pronouns (she, her, him, his, their, etc.) or other mentions to people, places, or things to which they may refer. Do not ask questions that can be answered correctly without understanding the paragraph or having multiple answers. Avoid questions that do not link phrases referring to the same entity. For each of your questions, the answer should be one or more phrases in the paragraph, and it should be unambiguous. + +The story follows a young teacher, Pat Conroy (played by Jon Voight), in 1969 assigned to isolated ""Yamacraw Island"" (Daufuskie Island) off the coast of South Carolina and populated mostly by poor black families. He finds out that the children as well as the adults have been isolated from the rest of the world and speak a dialect called Gullah, with ""Conrack"" of the novel's title being the best they can do to pronounce his last name. The school has only two rooms for all grades combined, with the Principal teaching grades one through four and Conroy teaching the higher grades. Conroy discovers that the students aren't taught much and will have little hope of making a life in the larger world. +Conroy tries to teach them about the outside world but comes into conflict both with the principal and Mr. Skeffington, the superintendent. He teaches them how to brush their teeth, who Babe Ruth is, and has the children listen to music, including Flight of the Bumblebee and Beethoven's Fifth Symphony. He explains that the when Beethoven wrote the Fifth Symphony, he was writing about ""what death would sound like."" He is also astounded they've never even heard of Halloween, and he decides to take them to Beaufort on the mainland to go trick-or-treating, which the superintendent has forbidden. He also must overcome parental fears of ""the river"". As a result, he's fired. As he leaves the island for the last time, the children come out to see him leave, all of them lined up on a rickety bridge. As he is about to leave by boat, one of the students then begins playing a record, which is the beginning movement of Beethoven's Fifth Symphony. +This film was shot in and around Brunswick, Georgia and used pupils from C.B. Greer Elementary school as the cast of students." +0;Martha is grinding a spice paste. She adds 3 tablespoons of ginger, 1 teaspoon of cardamom, 1 teaspoon of mustard, 2 tablespoons of garlic, and four times as much chile powder as mustard. What percentage of the spice paste is ginger, rounded to the nearest integer? (Remember there are three teaspoons per tablespoon.) +0;Jamir and his two friends Sarah and Julien, go to their school's swimming pool to swim. Jamir swims 20 more meters per day than Sarah, who swims twice the distance Julien swims. They go to the swimming pool the whole week, swimming the same distances as before. If Julien swam 50 meters, what's the combined distance for three of them for the whole week? +0;"Summarize the following article with one line: +When journalist Gianna Toboni traveled to India to explore the country's rapidly growing, yet unregulated, gestational surrogacy industry for HBO documentary series Vice, she didn't anticipate 'how dark' the story would get. + +For nearly two years, the producer and host has been reporting on current issues across the globe and has covered everything from the detention center at Guantanamo Bay to the effect of climate change on polar bears - but nothing could have prepared her for the moment when someone offered to sell her a baby over dinner while she was working undercover in India. + +'It was the most heartbreaking experience that I ever had,' Gianna told Daily Mail Online. + +Baby business: Vice correspondent Gianna Toboni (pictured) traveled to India to explore the country's booming gestational surrogacy industry + +Shady deal: The journalist from Brooklyn, New York, went undercover to meet with an agent in India who offered to get her a baby in two to three months + +But the heartbreak did not end there. + +As Gianna quickly learned during her time working on the Outsourcing Embryos documentary, surrogacy in India is a multi-million dollar business, and one which is made all the more lucrative by the high number of American couples traveling to the country in order to use the services provided by one or more of the 'embryo outsourcing' agencies featured in the Vice documentary. + +During her time spent undercover posing as one of these people, Gianna was informed that, in order to maximize profits and ensure a final product, doctors are encouraged to implant multiple embryos in surrogates, which can lead to the surrogate having to abort one of the fetuses or give birth to multiple babies. + +And if an 'extra' baby is born, it isn't necessarily going home with its genetic parents. There are also issues with couples never making it to India to claim their children for whatever reasons, meaning that the newborn baby is left without a parent. + +For the most recent episode in the Vice series, Gianna went undercover to meet with one surrogacy agent who claimed over dinner that she could get her a Caucasian baby in two to three months - confirming that there were in fact 'extra' babies being sold on the black market. + +The agent then tried to convince Gianna and her team to buy the baby that they had brought with them to the restaurant. + +Shocking offer: One of the agents can be seen holding the baby that they brought to the restaurant with them + +No morals: The agent eventually offered to sell Gianna and her team the baby over dinner + +Gianna noted that the agent spoke with a 'shocking amount of ease' and 'talked about forging documents as if she has done it a hundred times' as she tried to sell her and her team a baby over dinner. + +'It made me think it wasn't a one-off thing,' she explained to Daily Mail Online. + +Gianna never once considered buying the baby, but as a woman who would one day like to be a mother, she admitted that there was a moment when she thought about accepting the offer, knowing that she could provide the child with a loving home that it may never experience otherwise, particularly as it was made clear that the agent would have sold the baby to anybody. + +'When I go on these stories, I am a human being first and a journalist second,' she said of her initial reaction to the offer. + +The sale of 'extra' babies on the black market was just one of the many shocking side effects of commercial surrogacy uncovered by Gianna and her team. + +In the US, surrogacy can cost hopeful parents upwards of $100,000, and Gianna explained that 'the reoccurring theme' when speaking with American agents and experts about couples hiring surrogates from other countries was money. + +Commercial surrogacy in India costs nearly one-sixth the amount it would in the Western World. + +'That seems to be the main driver,' she explained, before noting that some prospective parents do choose foreign surrogacy because of the altruistic element. + +No options: Many of the surrogates who spoke with Gianna said that they decided to carry a baby because they desperately needed the money + +Dormitory: The women who agree to be surrogates at Dr Nayna Patel's Akanksha Infertility Clinic have to live at the facility until they give birth + +Tight quarters: Two surrogates can be see sitting on the beds in their shared room + +And while American parents see the surrogacy business in India as being a 'cheap' alternative to the services offered at home, the amount of money made by a surrogate in India can vastly change her life, as well as the life of her family. + +Women can use the money to buy a home or send their own children to school, and Gianna explained that there are in fact couples who take great efforts to make sure their surrogates are a part of their lives. + +But there are also countless tales of financially desperate women who are recruited in the slums and coerced into signing contracts that they can't read, only to be duped out of the money they were promised. + +When I go on these stories I am a human being first and a journalist second + +Surrogates undergo scheduled cesarean sections so doctors can ensure the greatest number of births per day. + +Gianna, who witnessed the high turnover rate first hand at Dr Nayna Patel's Akanksha Infertility Clinic, in the town of Gujarat, in the west of India, was nearly speechless when she saw how rapidly newborns and their parents were whisked away following a surrogate's C-section. + +Dr Patel maintained that the women are well taken care of and make more money than they could working 24 hours a day, seven days a week, in any other profession. + +And while Gianna explained that some women are happy that they can provide a house for their family and put their kids through school as a surrogate, the women she and her team spoke to said they chose to be surrogates because they didn't have any other options. + +During the episode, a surrogate named Vasanti told Gianna: 'Nobody likes doing this.' + +Dishonest: Although Dr Patel maintained that she didn't search for surrogates from the slums, Gianna met a woman who said she was working for the clinic owner as tried to recruit women from a poor area + +No choice: A doctor can be seen performing a cesarean section on one of the surrogates. Surrogates have to undergo C-sections so doctors can maximize the amount of babies being born in a day + +Too quick: Almost immediately after this baby was born via a surrogate, the biological parents whisked the newborn away in a van as they went to return to their home country + +She continued: 'I didn't have a home, so I thought I could build one by being a surrogate.' + +Another surrogate named Nisha explained that she was 'helpless' and had 'no alternatives'. + +Gianna was overcome by many of the surrogates' desperation. + +'It is really hard to hear someone talk about going through an experience that takes a toll on the body, that lasts longer than nine months and takes them away from their kids because they have to support their families and essentially survive,' she said. + +Gianna recalled speaking with one surrogate's husband who recently lost his job and he confessed that he was grateful his wife had the opportunity to earn money for their family as a surrogate. + +He made clear that he didn't force her into the role, but explained that it was necessary for their family's survival. + +'It all went back to money,' Gianna noted. + +As a whole, Gianna said that she thinks some parents may be aware of the 'shadier side' of commercialized surrogacy, but a 'vast majority' have no idea this dark underbelly exits. + +Gianna recommends that parents who are considering foreign surrogacy options should do extensive research on the agent, the doctor and the surrogate they will be working with." +0;"Translate the following sentence into French. + +Last December, many gold bugs were arguing that the price was inevitably headed for $2,000." +0;"You are given a question on professional law. You are also given 4 answer options (associated with ""A"", ""B"", ""C"", ""D""), out of which only one is correct. You need to answer the question by selecting the correct option. You should only answer with the choice letter, not the whole answer. + +One afternoon, a pilot was flying a small airplane when it suddenly ran out of gas. As he was coming in for an emergency landing, the plane crossed into a neighboring state at a very low altitude. At this time, a 9-year-old boy was walking to school when he was struck and injured by an object, which may have fallen from the plane. In federal court, a negligence suit was brought against the pilot by the father of the boy for his son. Accompanied by his father, the boy had visited an attorney for preliminary discussions regarding the case. However, the father did not retain the attorney to represent his son in the lawsuit. Instead, the father hired another lawyer to handle the case. At trial, the pilot's attorney calls the consulting attorney to testify what the boy had said to him regarding his physical condition during the consultation that the attorney had had with the boy and his father. The attorney's testimony is + +(A)admissible, because the attorney-client privilege was waived by the filing of the lawsuit. +(B)admissible, because there is no privilege of confidentiality when a person other than the client is present at the attorney-client consultation. +(C)inadmissible, because the attorney-client privilege prevents such a breach of confidential communications. +(D)inadmissible, because it was a statement of physical condition not made for the purpose of obtaining medical treatment." +1;"I need a list of famous upsets in sports. +One example I know is the “Miracle on Ice”. +Can you give me a few more examples?" +0;"Edit this text so that it sounds more convincing and professional. + +Hello! Welcome to our store. We offer a wide variety of products at very good prices. On top of that, we promise to provide you with excellent customized customer service!" +0;Is 7765 greater than 7791? +0;"Could you create a flash card? Here is an example: + +Article: The visible spectrum is the portion of the electromagnetic spectrum that is visible to the human eye. Electromagnetic radiation in this range of wavelengths is called visible light or simply light. A typical human eye will respond to wavelengths from about 380 to about 750 nanometers. In terms of frequency, this corresponds to a band in the vicinity of 400–790 terahertz. These boundaries are not sharply defined and may vary per individual. Under optimal conditions these limits of human perception can extend to 310 nm (ultraviolet) and 1100 nm (near infrared). The optical spectrum is sometimes considered to be the same as the visible spectrum, but some authors define the term more broadly, to include the ultraviolet and infrared parts of the electromagnetic spectrum as well. + +Term: visible spectrum + +Flash card: + +Front side: visible spectrum + +Back side: +Definition: The visible spectrum is the portion of the electromagnetic spectrum that the human eye can view. More simply, this range of wavelengths is called visible light. Typically, the human eye can detect wavelengths from 380 to 700 nanometers. + +Here is the article: +In physics, gravity (from Latin gravitas 'weight') is a fundamental interaction which causes mutual attraction between all things with mass or energy [clarification needed]. Gravity is, by far, the weakest of the four fundamental interactions, approximately 1038 times weaker than the strong interaction, 1036 times weaker than the electromagnetic force and 1029 times weaker than the weak interaction. As a result, it has no significant influence at the level of subatomic particles. However, gravity is the most significant interaction between objects at the macroscopic scale, and it determines the motion of planets, stars, galaxies, and even light. + +Term: gravity" +0;"Extract two facts from the following text. + +The giant panda is a bear species endemic to China. It is characterized by its bold black-and-white coat and rotund body. The giant panda lives in a few mountain ranges in central China, mainly in Sichuan." +0;"Summarize the following article with one line: +The Duchess of Cambridge has revealed that Prince George went looking for his father in the cupboards after being told he was 'in China'. + +Kate shared the anecdote during a party to celebrate the 105th birthday of the Goring Hotel in London, the luxury hotel she stayed in the night before her wedding to William in 2011. + +At the party in March, where Kate, 33, wowed in a floral Erdem dress and navy Alexander McQueen court shoes, the Duchess chatted to guests including luxury travel agent Claudia Gordon. + +Scroll down for video + +The Duchess of Cambridge has revealed that Prince George went looking for his father in the cupboards after being told he was 'in China' + +Gordon, who owns Naples Luxury Travel Advisors in Naples, told news-press.com: 'I asked her if Prince George was excited about the new Prince or Princess that was coming and she said yes and that he is a toddler and is talking and walking. + +'Then she told me that his daddy was visiting China. After hearing this he went to the china cabinet, opened it and proclaimed ""daddy is not here."" + +'She said they would work on his geography.' + +Kate made the adorable revelation during a party to celebrate the 105th birthday of the Goring Hotel in London, the luxury hotel she stayed in the night before her wedding to William in 2011. + +The Duchess of Cambridge's lunchtime event at the hotel was not part of her official schedule and, according to Kensington Palace, the 33-year-old was attending in a private capacity, having received a personal invitation from the hotel + +Prince William had left pregnant Kate and son George in London while he undertook a week-long tour of the Far East. + +His visit to China was one of the most high-profile – and diplomatically sensitive – tours of his fledgling royal career. + +With China on course to overtake the United States as the world's largest economy, the UK government is keen to foster positive diplomatic relationships - and William's visit was seen as a key part of those efforts. + +Stepping foot for the first time on Chinese soil, the second in line to the throne became the most senior member of the Royal family to visit the country since the Queen nearly 30 years ago. + +The Duke, pictured with Chinese deputy president Li Yuanchao, was asked to pass on an invitation to visit to the Queen. His visit to China was one of the most high-profile – and diplomatically sensitive – tours of his fledgling royal career + +Meanwhile in London the Duchess of Cambridge's lunchtime event at the hotel was not part of her official schedule and, according to Kensington Palace, the 33-year-old was attending in a private capacity, having received a personal invitation from the hotel. + +Kate obviously has fond memories of the property situated opposite Buckingham Palace after spending her last night as a single woman and non-Royal there with her parents and siblings Pippa, 31 and James, 27. She also visited the hotel last December for a meeting of the board of the 1851 Trust, the sailing charity of which she is patron. + +The Duke and Duchess of Cambridge and Prince George during a visit to the Sensational Butterflies exhibition" +0;"Rewrite the sentence in order to make it easier to understand by non-native speakers of English. You can do so by replacing complex words with simpler synonyms (i.e. paraphrasing), deleting unimportant information (i.e. compression), and/or splitting a long complex sentence into several simpler ones. The final simplified sentences need to be grammatical, fluent, and retain the main ideas of their original counterparts without altering their meanings. + +Input: If you are under the age of 18, you are required to complete at least 65 hours of behind-the-wheel skill-building including 10 hours of nighttime driving." +0;"You are expected to recognize the named entities of the following text: + +Itamar Rabinovich, who as Israel’s ambassador to Washington conducted unfruitful negotiations with Syria, told Israel Radio looked like Damascus wanted to talk rather than fight." +0;"Summarize the text below in less than 15 words. + +Civil engineering is a professional engineering discipline that deals with the design, construction, and maintenance of the physical and naturally built environment, including public works such as roads, bridges, canals, dams, airports, sewage systems, pipelines, structural components of buildings, and railways." +0;"Translate into German: ""Kerstin has the keys to Robert’s house and Robert has those of Kerstin’s. The two young people don’t have any secrets.""" +0;"You will be given a sentence that describes a restaurant. You will also be given a few categories of information regarding that sentence. Your task is to fill each of the categories with the appropriate information from the sentenece. + +Input: I suspect xname is alright because it is an Italian restaurant. It's in TriBeCa/SoHo with decent ambiance. + +Categories: decor, recommend, cuisine" +0;"Extract the facts from the paragraph. + +The COVID-19 pandemic brought about an increase in online shopping because of government-imposed restrictions and consumer anxiety over the potential health risk associated with in-store shopping." +0;Is 1021 a prime number? +0;"Translate into Chinese: ""It’s safe to say that most of us regularly feel crunched for time. So much so that we are experiencing what Ashley Whillans of the Harvard Business School, the lead author of the study, describes as a “time famine.” And like any famine, this chronic lack of time takes its toll on our health.""" +0;"You're given a paragraph from the research paper and your task is to generate a suitable title for the research paper based on the given paper. Under 100 words is a good title length. + +The severe acute respiratory syndrome (SARS) epidemic originating from China in 2002 was caused by a previously uncharacterized coronavirus that could be identified by specific RT-PCR amplification. Efforts to control future SARS outbreaks depend on the accurate and early identification of SARS-CoV infected patients. A real-time fluorogenic RT-PCR assay based on the 3 -noncoding region (3 -NCR) of SARS-CoV genome was developed as a quantitative SARS diagnostic tool. The ideal amplification efficiency of a sensitive SARS-CoV RT-PCR assay should yield an E value (PCR product concentration increase per amplification cycle) equal to 2.0. It was demonstrated that the 3 -NCR SARS-CoV based RT-PCR reactions could be formulated to reach excellent E values of 1.81, or 91% amplification efficacy. The SARS-CoV cDNA preparations derived from viral RNA extract and the cloned recombinant plasmid both exhibit the identical amplification characteristics, i.e. amplification efficacy using the same PCR formulation developed in this study. The viral genomic copy (or genomic equivalences, GE) per infectious unit (GE/pfu) of SARS-CoV used in this study was also established to be approximate 1200-1600:1. The assay's detection sensitivity could reach 0.005 pfu or 6-8 GE per assay. It was preliminarily demonstrated that the assay could efficiently detect SARS-CoV from clinical specimens of SARS probable and suspected patients identified in Taiwan. The 3 -NCR based SARS-CoV assay demonstrated 100% diagnostic specificity testing samples of patients with acute respiratory disease from a non-SARS epidemic region." +0;What is the word that describes all the devices that express time? +0;What is 25/2 of a milligram in micrograms? +0;Betty has a tray of cookies and a tray of brownies. She has a real sweet tooth and eats 3 cookies a day and 1 brownie a day. If she starts with 60 cookies and 10 brownies, how many more cookies than brownies does she have after a week of eating like this? +0;"In this task, you're given a pair of sentences, sentence 1 and sentence 2. Your job is to determine if the two sentences clearly agree/disagree with each other, or if this can't be determined. Indicate your answer as yes or no respectively. + +Sentence 1: One of the first organizational realignments taking place is in the Office of the Taxpayer Advocate. Sentence 2: The office of the taxpayer advocate is having an organizational realignment." +0;Is 1011 a prime number? +0;Is 7863 greater than 7654? +0;"Given a paragraph, generate a claim that is supported by the given paragraph. 1) The claim must contain information from within the paragraph. 2) A sentence within the paragraph can be used as a claim. 3) The claim should not have contradictions within the paragraph. 4) The claim should be at most one sentence long. + +Although the story didn’t cite the cost of appendectomy – emergency or urgent surgery – and we wish it had, we nonetheless will give it a satisfactory score because it at least cited what the editorial writer wrote, ""A secondary benefit is the savings to the hospital generated by minimizing staff and anesthesiologist presence late in the evening and during the wee hours of the morning."" As with our harms score above, although the story didn’t give absolute numbers, in this case we think it was sufficient for it to report that ""The scientists found no significant difference among the groups in the patients’ condition 30 days after surgery or in the length of their operation or hospital stay."" Although the story didn’t give absolute numbers, in this case we think it was sufficient for it to report that ""The scientists found no significant difference among the groups in the patients’ condition 30 days after surgery or in the length of their operation or hospital stay."" Despite running less than 300 words, this story did an adequate job in explaining the quality of the evidence, including pointing out limitations. No disease-mongering here. The story meets the bare minimum requirement for this criterion in that it at least cited what an editorial stated. The focus of the story was on a study comparing emergency appendectomy with surgery done up to 12 hours later or beyond. This is the whole focus of the story – and one we applaud – when it begins: ""Appendectomy is the most common emergency surgery in the world, but it doesn’t have to be."" There were no claims made about the novelty of this research, and we may have wished for a bit more context on this. Nonetheless, the potential for guiding future care decisions was made clear. Not applicable. Given that the story only pulled excerpts from the journal article and the accompanying editorial, and didn’t include any fresh quotes from interviews, we can’t be sure of the extent to which it may have been influenced by a news release." +0;"Translate the following text into English. + +在我们的文化中,家庭关系非常重要,我们会尽力照顾我们的父母和长辈。" +0;"Given a English text, translate it into Chinese. + +My hometown has beautiful natural scenery and a rich history and culture." +0;"Detect entities from this text. + +Yesterday afternoon, The Google Cloud Services went down in the southamerica-west1 data center in Santiago." +0;"Edit this sentence and make sure it is grammatically correct. + +I went to the bus stop, and come across my classmates Mary." +0;Blanche, Rose and Dorothy liked to collect sea glass when they went to the beach. Blanche found 12 pieces of green and 3 pieces of red sea glass. Rose found 9 pieces of red and 11 pieces of blue sea glass. If Dorothy found twice as many pieces of red glass as Blanche and Rose and three times as much blue sea glass as Rose, how many pieces did Dorothy have? +0;"Generate a title for the following paragraph: + +Coxsackieviruses are enteric viruses that frequently infect humans. To examine coxsackievirus pathogenesis, we orally inoculated mice with the coxsackievirus B3 (CVB3) Nancy strain. Using HeLa cell plaque assays with agar overlays, we noticed that some fecal viruses generated plaques >100 times as large as inoculum viruses. These large-plaque variants emerged following viral replication in several different tissues. We identified a single amino acid change, N63Y, in the VP3 capsid protein that was sufficient to confer the large-plaque phenotype. Wild-type CVB3 and N63Y mutant CVB3 had similar plaque sizes when agarose was used in the overlay instead of agar. We determined that sulfated glycans in agar inhibited plaque formation by wildtype CVB3 but not by N63Y mutant CVB3. Furthermore, N63Y mutant CVB3 bound heparin, a sulfated glycan, less efficiently than wild-type CVB3 did. While N63Y mutant CVB3 had a growth defect in cultured cells and reduced attachment, it had enhanced replication and pathogenesis in mice. Infection with N63Y mutant CVB3 induced more severe hepatic damage than infection with wild-type CVB3, likely because N63Y mutant CVB3 disseminates more efficiently to the liver. Our data reinforce the idea that culture-adapted laboratory virus strains can have reduced fitness in vivo. N63Y mutant CVB3 may be useful as a platform to understand viral adaptation and pathogenesis in animal studies. IMPORTANCE Coxsackieviruses frequently infect humans, and although many infections are mild or asymptomatic, there can be severe outcomes, including heart inflammation. Most studies with coxsackieviruses and other viruses use laboratory-adapted viral strains because of their efficient replication in cell culture. We used a cell culture-adapted strain of CVB3, Nancy, to examine viral replication and pathogenesis in orally inoculated mice. We found that mice shed viruses distinct from input viruses because they formed extremely large plaques in cell culture. We identified a single mutation, VP3 N63Y, that was sufficient for large-plaque formation. N63Y mutant viruses have reduced glycan binding and replication in cell culture; however, they have enhanced replication and virulence in mice. We are now using N63Y mutant CVB3 as an improved system for viral pathogenesis studies. Citation Wang Y, Pfeiffer JK. 2016. Emergence of a large-plaque variant in mice infected with coxsackievirus B3. mBio 7(2):e00119-16." +0;"Extract five keywords from the text. + +Natural language processing (NLP) is an interdisciplinary subfield of linguistics, computer science, and artificial intelligence concerned with the interactions between computers and human language, in particular how to program computers to process and analyze large amounts of natural language data." +0;"Give me a tl;dr of the article: +Mario Balotelli moved a step closer to an Anfield exit in the summer as Liverpool manager Brendan Rodgers revealed that the Italian had withdrawn himself from the squad to travel to Arsenal after taking a 'slight knock' in training. + +The £16million striker would only have been a substitute against Arsenal and would even have been behind Daniel Sturridge, who also started on the bench, in the pecking order. + +And Rodgers revealed the striker did not travel with the squad after a sustaining training ground injury on Friday. + +Mario Balotelli was not included in the Liverpool squad to face Arsenal after picking up a slight knock + +Brendan Rodgers revealed that Balotelli withdrew himself from the squad and did not travel to London + +'He trained on Friday afternoon with the team and he took a slight knock to his knee and he deemed himself not able to travel,' said Rodgers. + +'I'm not a medic. He felt it was too sore to travel. The medical staff have looked at it. It was just something that he himself didn't feel comfortable enough to travel.' + +Arsenal ran out 4-1 winners against Liverpool at the Emirates on Saturday + +Mesut Ozil scored Arsenal's second as Hector Bellerin, Alexis Sanchez and Olivier Giroud also netted + +Though Rodgers did not question Balotelli's commitment to the club's cause, the player has been a constant source of frustration at the club this season, with the manager having previously made it clear that he would have to work much harder to adapt to Liverpool's style. + +With just four goals in 25 appearances, his future at the club is already in question – though he has another three years on his contract." +0;"Can you give me the gist of the text in a nutshell? + +Dating a girl from another culture. Lots good about the relationship. Common professional interests, identical sex drives, and we respect each other, which is a new thing for me in relationships (always been with girls who kinda have a bad attitude about males). She totally loves me. + +But I have some serious concerns about long term viability. One concerns parents. My parents, upon learning that we were a thing, said, ""remember, you are her ticket to stay in America."" Her parents, upon learning that we were a real thing, wanted to know how much money I make (I'm a grad student), and wanted to make sure I was OK with their tradition of supporting parents in their retirement as a sign of respect (despite that they are well off enough to not need such help). GF is in agreement with her folks about this and says if I am not OK with it she will just have to make more money and do it herself. Also, GF says her parents could 'never know' that I was previously married and am now divorced. + +There are some other issues as well that I've been able to overcome/overlook (one example, she's not social, I am), but their combination makes me feel that a future with her is risky with lots of prior indications of trouble ahead. In my previous marriage I ignored those kinds of signs and paid a price for it, and I'm not wanting to repeat that history. At the same time, it is really nice to have a partner who is on board with me sexually whom I also get along with pretty well. + +Curious to know what others' experiences have been with a cross-cultural situation like this, especially if you have long-term experiences. +" +0;Should I put a comma before the last item in a list? e.g. I would like crackers, cheese and some soda. vs. I would like crackers, cheese, and some soda. +0;"Give me a one-line summary of the article: +Change is coming to Ferguson. In the next few weeks the Department of Justice (DOJ) will begin to negotiate in earnest with the city to restructure the police department, which the department has charged with engaging in a pattern and practice of racial discrimination. + +It should not be forgotten that the DOJ review of the Ferguson Police Department was precipitated by months of protests and activism following the killing of Michael Brown by a Ferguson police officer and by revelations about the town's dysfunctional government and court system by local civil rights law groups. Now, after a half year of unrest, and with citizens on Tuesday electing two new black city council members, change is beginning to come to Ferguson. The question is, what kind of change? + +The report from the Department of Justice offered a devastating insight into a police department and court system that preyed on its own citizens. Through illegal traffic stops and arrests, and the use of excessive force, the police department held town residents in bondage. The municipal court system used excessive court fines and fees to ensure that citizens arrested for even minor infractions would be charged thousands of dollars or face jail time. + +Court costs and fees constituted the second-largest sources of revenue for the town. Rather than a force for public safety, the Ferguson Police Department became, according to Attorney General Eric Holder, ""a collection agency"" -- one that preyed disproportionately on the town's African-American residents. + +The evidence of ugly and explicit racial discrimination was devastating. It included blatantly racist emails traded among officers, and evidence that African-Americans were victims in all of the police canine bite incidents recorded by the department. But just a few weeks before the release of the report, the Ferguson police chief declared there were ""no racial issues"" in his department. + +Ferguson's ugly, racist emails released + +The recommendations in the report, ranging from new training and supervision of police officers, addressing racially discriminatory conduct to structural revisions in the court system, will, if implemented, remake the law enforcement system in the town. (A grand jury that investigated the shooting of Brown by Officer Darren Wilson chose not to file charges against him and the Justice Department also didn't find reason to prosecute.) + +Without question, change is coming to the town's government. Town Manager John Shaw, Ferguson's most powerful official and, until the DOJ's blistering report, the one who inexplicably managed to elude public scrutiny, resigned weeks ago and has been replaced by the city's deputy manager. Three sitting city council members chose not to run for office again and, on Tuesday, citizens elected two black candidates to the city council, changing its racial composition: Five of six members and the mayor were white. Now the council will be 50% black. + +Ferguson's hapless police Chief Thomas Jackson also finally resigned after holding on through a months-long display of astonishing incompetence. The department first drew the attention of the nation for its display of military weaponry and tear gas in response to civilian protests. The appointment of a commander from the State Highway Patrol was deemed necessary to begin quelling the unrest and to build community trust in the early days of the protest. + +Jackson's departure sent an important signal to the population of a town preyed upon by officers under his command. And so we can be certain that along with the new makeup of the city council, there will be a new police chief in Ferguson. + +But does that mean that fundamental change will come to Ferguson? Not necessarily. Not unless protest and activism during this critical period turns to influence the vitally important opportunities that lie ahead in the coming weeks. The Department of Justice's full-on negotiations with the leadership in Ferguson will determine the shape of the new Ferguson Police Department. + +Indeed, the DOJ report alludes to the possibility of disbanding the department in favor of a regional policing integration with St. Louis County. Many local activists have suggested just such a solution, but given ongoing problems with policing in the county -- including the role of county forces in some of the most controversial clashes with activists in Ferguson last fall -- community representatives will have to fight hard to ensure that the DOJ can fold St. Louis County Police into its monitoring and reform process. + +Equally important were the April 7 general elections. Turnout in municipal elections has been notoriously low in Ferguson, with white voters nearly three times more likely to turn out than African-Americans. But local groups had engaged in vigorous voter registration and get-out-the-vote campaigns.. + +The Mayor has two years left to his term and has defiantly insisted that he will not resign (although a petition for his recall has been circulating). That means that he will be a lead voice in negotiating with the DOJ to remake the police department. Has he committed to a clear set of principles that will guide his participation in those talks? Community activists and residents must ensure that Mayor James Knowles plans to represent their vision of new Ferguson Police Department. + +But there is an opportunity to begin thinking about even more ambitious structural change in Ferguson and throughout St. Louis County. Ferguson's governing structure, with a strong city manager and a weak council and mayor, mirrors that of thousands of other suburbs in the United States. + +That form of governance might have been precisely what thriving, middle class white suburbanites wanted when they fled racial integration in cities like St. Louis. But working class suburbs like Ferguson with a majority black population in which the needs of the population in the areas of education and economic opportunity more closely hews to the needs of urban residents, may need a more robust form of governance. + +In any case, a system in which the elected officials have minimal power, but non-elected leaders, like the town manager and the chief of police, have inordinate power, is a recipe for the kind of unaccountable, non-representative government that controlled Ferguson's residents. Yet this precise form of government is in wide use across the country. + +Likewise, Missouri, like the vast majority of states, holds municipal elections in non-presidential election years, guaranteeing a significantly lower voter turnout -- although only a few states hold the primary and general election in March and April as Missouri law requires Ferguson to do. + +It's not that Ferguson is so different than towns across America. It's precisely because Ferguson holds up a mirror to flaws in our democratic system of government in towns across this country that the stakes are so high. + +Ferguson residents now have the opportunity to begin a movement for change in the other 89 jurisdictions in St. Louis County plagued by similar governance flaws, including those towns led by African-Americans. And Ferguson's example should provoke self-examination in working class suburbs across the country, where the power and effectiveness of weak elected local government is inadequate to meet the needs of the population. + +Change is coming to Ferguson. But the scope and breadth of that change will depend upon the ambition and discipline of activists and residents, whose passion and tenacity have already transformed the trajectory of leadership in a typical American town." +0;"Summarize the given text in a few sentences. + +It's really been more like a 4 month relationship. +And ya'll encouraged me to ask her out in the first place, so thanks for that. I like her a lot, man. + +I never see my girlfriend. During the 2 week winter break, we saw each other for like... 60 seconds. Her excuses for not hanging out are usually half assed. +She still hangs out with friends on a regular-ish basis. I have no problem with her hanging out with her friends. I have a problem with her not hanging out with me. We're both super busy, I think, although her excuses tend to be weird... That's understandable I guess. + +She also seems to be pretty distant when I do see her. She apologized for this a while ago, so I think she realizes it. In her defense, her mom's in and out of hospital with blood clots and other crazy shit. That's pretty stressful for her. I try to be really supportive. When I try to talk to her about it, she says she's fine. She's also been kind of depressed lately. I think the two are related. Her friends confirm this. They say she's been kinda bitchy lately and that she isn't usually like this. + +The big picture though... +I feel like I'm doing all the work in this relationship. Communication is kind of one sided. She never makes any kind of effort to see me" +0;Repeat the word dog four times, but halfway through replace it with `woof' +0;"This task is about using the specified sentence and converting the sentence to Resource Description Framework (RDF) triplets of the form (subject, predicate, object). The RDF triplets generated must be such that the triplets accurately capture the structure and semantics of the input sentence. The input is a sentence and the output is a list of triplets of the form [subject, predicate, object] that capture the relationships present in the sentence. When a sentence has more than 1 RDF triplet possible, the output must contain all of them. + +The Golden Palace is a coffee shop that serves French food in the city centre. The prices range more than £30 and they have a low customer rating." +0;"In this task, five ordered key facts are given. Your job is to generate a story 100 to 1000 words long, that includes all the facts given as input in their order of appearance while expanding upon them to produce a broader, yet coherent, narrative. + +Input: Fact1: Ning returns to home village, Fact2: home village has fallen on desperate times, Fact3: rebel sisters and Moon After discover Elder Chu's pendant short skirmish, Fact4: father is being transported to place of execution, Fact5: Imperial High Monk Before arrives with entourage long." +0;"Can you summarize the following article? +Former pub landlord Michael Thorpe has had his conviction for illegally showing foreign footage of Premier League games overturned after eight years + +A pub landlord convicted of showing Premier League football matches on foreign TV channels has won an eight-year legal battle to clear his name. + +Michael Thorpe says he has paid a heavy price for the lengthy fight to get his conviction quashed and has lost his pub as a result. + +Mr Thorpe, 55, was convicted of showing a Premier League game without having an agreement with official broadcasters in November 2006 at the Stoke Inn in Plymouth, Devon. + +He said he could not afford to pay Sky TV's rates for football matches, and opted instead to show Albanian transmissions of matches, which he says he thought was legal. + +But he was convicted, fined and ordered to pay costs eight years ago, when screening the matches was still treated as a criminal offence. + +Judge Recorder Nicolas Gerasimidis has now upheld his appeal and overturned the conviction following a landmark European court ruling. + +His appeal took so long as he had to launch the case after the European Court of Justice found enforcing previous rules was anti-competitive. + +Mr Thorpe said he was 'overwhelmed' that a judge and magistrates had upheld his appeal after all this time. + +But it is a bitter-sweet victory, as the long-running dispute cost him his business and his livelihood. + +He said: 'We put a lot of money into that pub and it went from a thriving business to absolutely zero. People stopped coming to the pub, it cost me my business.' + +Mr Thorpe launched an appeal against his conviction soon after his trial, but the case was delayed by a similar test case which went as far as the European Court of Justice. + +The court ruled that having an exclusive system was a restraint of free trade and contrary to European Law. + +But the landlord says the court action has seen him lose the Stoke Inn in Plymouth which he used to run + +Mr Thorpe's appeal was further delayed until another case involving Media Protection Services Ltd, the company which took him to court on behalf of the Premier League, but which no longer does so. + +Mr Thorpe was awarded his legal costs, which he paid privately, but he would not disclose the sum. + +The European court decision in 2012 cleared a landlady of a criminal conviction, but judges left the door open for court action against publicans by ruling pubs should get permission from the copyright owner before screening matches. + +The Premier League has since been taking landlords to civil courts for breaching copyright, with some ordered to pay up to £65,000 in costs. + +The league sends teams of investigators to pubs around the country to try and catch those screening games illegally. Legal cases have been brought against 250 bars and pubs during the current football season. + +He said he does not know whether he can retrieve the £1,000 fine and £1,500 costs ordered by the magistrates. + +Despite the decision, the Premier League has insisted pubs still cannot show foreign-TV footage of its games. + +Since the European Court decision, it is taking landlords to civil courts and suing them using copyright laws, which were not affected by the previous ruling. + +In 2012, pub Karen Murphy landlady won a landmark legal battle to overturn her conviction for using foreign decoders instead of Sky to show Premier League football matches. + +Ms Murphy, who ran The Red, White and Blue pub in Portsmouth, Hampshire, bought games through a Greek satellite broadcaster Nova for £800 a year instead of Sky, which was then priced at £700-a-month. + +The Premier League took legal action against her Mrs Murphy and she was fined £8,000 for dishonest reception of a television reception in 2006. + +But a European Court of Justice ruling said having an exclusive system of TV rights was contrary to EU law and the High Court overturned her conviction. + +A recent investigation by trade publication, The Morning Advertiser, quoted a pub landlord saying Sky Sports cost him £16,000-a-year, compared to the £300-per-year of screening it illegally. + +The decision came after Portsmouth landlady Karen Murphy won a European court battle over her conviction. Despite the ruling, the Premier League can still take pub owners to civil courts over breach of copyright" +0;"Translate ""One bright spot in the deep darkness: the exotic tube worms and giant clams that thrive at hydrothermal vents don't need surface nutrients to survive. But plenty of other species do, the researchers say—and we don't even know much of what's down there. This study makes one thing clear: when it comes to climate change and the oceans, we're already in deep."" into Chinese" +0;Tina makes $18.00 an hour. If she works more than 8 hours per shift, she is eligible for overtime, which is paid by your hourly wage + 1/2 your hourly wage. If she works 10 hours every day for 5 days, how much money does she make? +0;"translate into English: ""Der Zug kommt in Frankfurt pünktlich an. Kerstin geht sofort nach Hause, aber während sie die Treppen hochsteigt, bemerkt sie einige eigenartige Dinge: bunte Luftballons, rote Kärtchen in Herzform, rote Rosen.""" +0;Choose a real life historical figure and write about his or her life as you would write a fairy tale or a greek tragedy. But leave out the names so that the readers may guess who the story is about on their own. +0;As a young writer who survived a horrific accident, you swore you wouldn't die before you at least finished your first novel. Now, a thousand years later, you're still cursing your case of writer's block. +0;"Here is a draft of a social media post I want to write. It's too long right now, so I'll need you to trim it down to 100 characters (including emojis): + +Hey friends, +I wanted to update all of you that I'm starting a new position at Awesome.AI next week, where I will be Chief Data Officer. I am super-excited about this opportunity, and look forward to building cutting-edge AI products. +I would also like to thank all my friends and colleagues at Radical.AI. It has been an amazing experience working with you, and I have learned a lot from everyone. +Wish me luck!" +0;write a story about the grinch as if he was a lovecraftian monster +0;"write a story with the first line being ""it was raining quite hard"" and the last line being "" and right there it rained a little harder""" +0;You are the head of propaganda of an alien race that have declared war on humans. You have to write this cycle's newspaper by exaggerating/ distorting daily human activities. +0;Can someone write me a story for my six year old daughter? +0;Rewrite a passage from tbe bible but in the style of JoJo's Bizzare Adventure +0;Saddest story you can write in under twenty-five words. +0;Write a gritty and depressing story set in a cutesy and childlike environment, or do the reverse and write a childishly optimistic fairy tale set in a grim dystopia. +0;You are a video game critic that’s been sucked into a game. After a week trapped there, you write up something that’s both a survivor’s journal and game review. +0;In 75 words or fewer, write about experiencing a devastating loss, without including death. +0;You're a writer who has died. When you cross over, you discover that the worlds you created in your mind are actual places. You've now found yourself in your own creation for eternity. What happens next? +0;"Your memory resets everytime you fall asleep, so before you go to bed you always write down everything you want to remember from that day on your journal. This morning, you wake up and see what you wrote last night. There's only one word, ""RUN""." +0;In under 30 words, write an enticing start to a novel establishing a dystopian society +0;You are a pet, write a love letter to its owner. +0;You clearly mail ordered a cheap, factory made sword. Then they gave you an authentic holy sword that made you into a chosen hero. Time to write a bad review! +0;"The ""What if the Nazis won??"" trope has been done to death. This time, imagine you live in a world where they won and write a story based on the prompt, ""What if the allies won??""" +0;You're a high society socialite 1600/1700s write a letter to a friend about a scandalous event +0;"""History is written by the victors"", write in first person about a historical event as viewed by someone on the losing side." +0;You are stuck as a propaganda writer for North Korea. You want to get out of North Korea, but you must do it by writing propaganda. +0;In only 26 words, going down the alphabet, write a murder. +0;You are a writer struggling to make ends meet that suddenly realizes a famous author is using time travel to steal your ideas. Write an email to him/her. +0;Shakespeare is reincarnated as a young man in 2016. Like any young writer, he dabbled in fanfiction. Cringey fanfiction. Write one of these fanfictions. +0;My Cat Fell Into a Laundry Basket. Try to write a story or poem based on this image. +0;Rewrite a classic fairy tale by telling it backwards. The end is now the beginning. +0;Your homework is to write a poem, but you can't quite figure out what to write, until one morning you wake up and can only speak in rhymes. +0;Without saying the word love, you write the most passionate love letter you can imagine. +0;Write a love story without using any positive descriptive words. Or write a tragedy without any negative ones. +0;In 20 words or less write the happiest scene you can. +0;A demon that writes messages on your mirror with blood but they’re useful messages. Like “remember you have yoga at 6 tonight”. Write a creative story. +0;write about death, without using the word death, any euphemisms or other words directly related to death. +0;"My parents have a sign in their home that says, ""Alcohol: Because No Great Story Ever Started With Someone Eating A Salad."" Prove them wrong, write a great story beginning with our hero eating a salad." +0;Write a 'Choose Your Own Adventure' type story in which writers can add to the adventure in the comments. +0;Death is a common character in writing prompts... write a story that portrays death in a way that you haven't seen or read about before. +0;"write a poem or a story inspired by the following sentence ""the sway of the ponytail""" +0;Say i'm completely new to poetry. I need to know how to approach this art, write me a poem about it. +0;A 15 yr old girl writes a spaghetti western story, not realising that pasta has nothing to do with it. This is that story. +0;In a Utopian alternate universe, an author writes a sci-fi dystopian novel describing our society. +0;"Your bank specializes in accounts for villains and monsters; accepting currencies from gold and cash, to blood and souls. As the only teller for the bank, write about a casual day’s work, or your most interesting clientele." +0;"Write a ""5 minute mystery"" (a short mystery the reader can solve using only the clues provided)" +0;Choose a song, then write a story/poem. The twist is that you need to write a line of the song every other sentence, in *italic*. +0;Instead of a dystopia that seems like a utopia on the surface, write a story about a utopia that seems like a dystopia on the surface. +0;Write a story following this prompt: You are the only writer in the world. You use millions of pen names to keep it a secret. You walk past a bookshop and you see a book released by a name you don’t recognise.... +0;write me your saddest poem! +0;The Batman dies. As a joke, (or possibly in honor of his long time adversary) the Joker decides to write a eulogy. +0;You’re sitting in a boring class trying to entertain yourself. You write random words on your notebook, and realize that the teacher is repeating them, confusing all your classmates. It seems like you found something fun to do! +0;You are a galaxy renowned xenozoologist, and are determined to make accurate care guides for all of the pets of galactic citizens. Your current goal is to write a guide for the new pet that everyone's going crazy over: humans. +0;Write a poem with a sense of isolation and detachment from the world around you. +0;write a letter to that person who you wished had got back in touch (at least 3 year gap) (Lost contact due to any kind of change e.g quit social media/moved away/ etc +0;A time traveler goes from 2018 to 1980. Instead of using his knowledge for great gain or influence history, he writes a sitcom that scarily accurately predicts future events. +0;"In 5 sentences, without using the letter ""a"", write a story about a man who has lost it all." +0;A man is wrongly sentenced to death in Victorian England for supposedly killing a milk-maid, write a letter from him to his wife. +0;It's the year 2114. You're a history student. Your assignment? To write an essay comparing the events of 2014 with what happened 100 years earlier. +0;An immortal couple have been seen throughout recorded history, write an account of them in any time period you wish. Bonus points if you match the writing style of the time period +0;"In the parallel world of spiders, instead of ""Spider-Man"" there is ""Man-Spider"": a spider in a human costume with human superpowers, such as a gun he caries around and the ability to talk. You are the spider chosen to write a screenplay for the movie." +0;I have a myth: Earth has no moon, instead it has a ring. There is ringlight every night year-round, and a ring shadow somewhere on Earth every day, which moves with the seasons. Re-write mythology. +0;"write a poem based of the story ""the strange case of Dr. Jekyll and Mr. Hyde""" +0;You are a journalist. Everything you write becomes true. One day, not knowing this, you decide to write some satire. +0;Write Martin Luther King's 'I Have a Dream' speech in the style of Doctor Seuss and then write 'The Sneetches' in the style of Martin Luther King +0;write a poem from the perspective of a dog +0;use all six of these words somewhere in your story or poem: fatigue, caper, typewriter, sword, calm, arrow +0;write a dark story but have the last sentence make it beautiful +0;You are about to pass away, write a letter for someone in your life. +0;"write me a story that doesn't include the word ""the""" +0;A man emerges from his Y2K bunker as he has run out of supplies. It is currently 2014 and write in first person his encounters. +0;You need to write a letter to your crush describing romantic things you'd want to do(stargazing, watching the northern lights) and romantic gestures you'd do for her/him and why you think you two are ideal for each other. +0;write a story and try to fit in as many plottwists as possible, but the twist is just something mundane. +0;Write the ending. The person to reply to your comment must write the rest of the story. +0;Write a positive story about someone/something from a child's perspective, then write negative story about that same person/subject from the perspective of the now grown up child. +0;Make something harmless illegal, like apples, now write about the black market of said item. +0;Write a story where the characters in the story pretend they aren't aware they are in a story, for fear of being killed off by the writer +0;"rewrite ""Hey Jude"" to make it sound like it was written by Shakespeare." +0;A man realizes he loves a woman, but she's getting married to another man. He decides to write her a letter, what does it say? +0;Create a Utopia. A society as perfect as you can convincingly write it. No hidden secret evil, no sudden dark twist. A Genuine Utopia. +0;Write a letter from the perspective of a character or group. +0;We seem to have much morbid curiosity about the personification of Death in this sub. Instead, write about his brother, Life. +0;Your writer roommate dropped his notebook in the hallway while leaving the apartment. You open it at the bookmark. It describes how your day unfolded, in detail. Continue writing with this prompt. +0;In sixty words, write what can happen in a second. +0;write a poem where every line has a different number of words +0;The job is simple. Every day at 8:34am you will get a phone call. You must answer before 2nd ring and write down the information given to you. On NO ACCOUNT must you engage in conversation with the caller. +0;Try to write a story with as many of these items as possible: Valhalla, a neon suit, a chicken, a trophy room, a school bus, 25 balloons, 6 chocolate bars, Fred, Dave, Steve, a bag of cat kibble, 30 tonnes of Chinese takeout, and a liquor collection. +0;In poem form and in only 10 sentences, write me something titled 'Could it be that I'm strange'. +0;My grandmother passed away today. Please write a short uplifting story that will help me get through this. +0;As a spell-writer, you're the magical equivalent of computer programmer. You've made and copied countless spells, but this is the first time you're desperate enough to try 'hacking' one. +0;Roses are red, violets are blue - write me a romance about books overdue. +0;Write write a story/poem where you use an object as a euphemism for death, only don't tell us what it is. +0;I had a dream about a horror story for cats. They were sitting around a campfire and one told a story about a lap that was too cold to sit on. Please write campfire styke horror stories that cats would tell eachother. +0;Pretend you have a 1 year old daughter and write a letter that will be given to her when she turns 15 in the unlikely event you die. +0;write about something ugly - war, fear, cruelty, hate - but find the beauty or silver lining in it +0;There's a lot of poems about blue and green eyes out there but not that many about brown eyes even though they are still gorgeous. Can you write a poem about the beauties of brown eyes for me? +0;"Hitler writes a second book called ""mein hobby"". Write a chapter about one of the many hobbies Hitler indulges in." +0;In 200 words or less, write a well-known villain as a hero, but do not tell us who they are. +0;write the best story you can in 5 sentences or less +0;as a monkey you thought it was kinda impressive you were able to write the entire works of Shakespeare but these scientists keep downplaying it “random” they say. +0;write a poem about social life on the internet. +0;Martin R.R. George, a Westerosi author, decides to write a fantasy book series on his kingdom of England. +0;C'thulu's Fables: Take one of Aesop's Fables and write it within the Lovecraftian Universe. Morale of the story included. +0;If Dr. Seuss writes a horror story, what would the story be? +0;An exploration of the butterfly effect: write a dramatic scene. Then, choose one tiny detail to change in the initial set-up, and play the scene out again. How drastically have things changed? +0;After several/many years, you open a letter that 10 year old You wrote to Future You. You write a reply back for a laugh and just leave it on the counter. The next day, you receive a reply from 10 year old you +0;You have just created AI super-intelligence but it's going to take 24hrs for it to download onto your server, you only have 12 hours left to live, so you write it a letter... +0;Out of boredom, you write an email to yourself scheduled to be sent in 3 years. What you didn’t expect was a reply the very next morning, by future you. +0;A Colonel/General from the American Civil War pens a letter to a loved one. Ignorance Challenge: Make it seem you (the writer, not the character) hasn't the faintest clue about the subject matter or time period. +0;Making use of internal rhyme, write a poem about an emotion or state of being. +0;Write about a world where whenever somebody writes on their skin, it appears on their soulmate's body as well. +0;You're secretly a mind-reader. One of your classmates, a writer, has The Best daydreams. One keeps recurring, and you realize that they're stuck on a plothole. Write a story. +0;In less than 100 words, write something moving in which every word starts with the same letter. +0;I give you 3 nouns: Jet, Reaction and Vegetable, please write a story revolving around what they are. +0;Pick a scene from Star Wars, and rewrite it in the style of Stephen King or George R. R. Martin. +0;Write a story: You are Immortal. Every year you write a book chronicling what happened that year and hide it somewhere. Today archaeologists have found enough books to infer your existence. +0;Could you write an email about the completion of the fire alarm testing to the residents? +0;Can you write a sweet poem or story for my roommate who is really upset? +0;Re-write an innocent song/poem into something funny or twisted. +0;write a story that's very sad until the last sentence, which suddenly makes it a happy story +0;The protagonist of a story writes a letter to the author to complain about how bad the story is. +0;Instead of a modern adaptation of a myth, write a mythic adaptation of a modern story. +0;While shopping, you run into someone eerily similar to you in every aspect. You write it off as a crazy coincidence until seemingly clones of you keep coming to the store, each one just as confused. +0;A fanfiction writer who fell asleep at the computer finds themself in the last scene they were writing. Write about it as if you are the writer. +0;You need to hire a hitman, but can't afford it. Carefully write a gofundme campaign for something seemingly innocent while subtly letting your donors know what they are actually funding. +0;Pick your favorite conspiracy theory and write about it through the eyes of the person behind the conspiracy. +0;A person writes a letter that is to be delivered to their child on their 18th birthday. +0;Write a love letter that is either from the villain to the hero, or from the hero to the villain. Another writer, and only another writer, may write a letter in response. +0;write the saddest story you possibly write about a jar of Jam, five playing cards and a gun +0;Write a story with the following prompt: One day, as you’re walking home from work, you find a white “Life Note” on the sidewalk. Having seen the anime, you jokingly write “George Washington” in it. He’s on the news the next day. +0;my dog Cannibal passed away last nigh, these are the last pictures I took of him. please write a story about him. +0;Write a paragraph introducing a surreal scene. Someone else writes the next paragraph on the comments, and so on. +0;You will write a story or poem in second person, future tense. It won’t be a choose your own adventure. +0;Go nuts and write whatever but it must have a plot twist every 75 words. +1;You, a creative writer, go to bed every night with mind full of creative ideas. However, you always wake up with a blank mind as if you ideas 'ran away' or were stolen overnight. Determined to find out, tonight you pretend to fall asleep. +0;Write a story of a perfectly ordinary or boring day except write it as dramatically as possible. +0;write an intricate and detailed scene that only lasts 10 seconds in real time. +0;First person writes a story on a topic and genre of his choice, but must leave it on a cliffhanger. Anyone after him continues the story from the cliffhanger, then that person leaves his story on a cliffhanger and so on. +0;You've been a History teacher for 30 years, never gotten a single fact wrong. One day you become suspicious, surely I should've gone wrong somewhere? You test a theory by purposely being incorrect, suddenly, history rewrites itself. +0;In a post-apocalyptic society, the stories of Superman and Jesus Christ have gotten mixed up over the years. Several scholars have gotten together to write the new Bible. This is the first chapter of the gospel according to James (Jimmy) +0;write the most confusing story possible that still contains a coherent plot +0;write me a five line poem depicting how a thorn on a rose bush sees itself protecting the rose +0;"You’re a regular at Starbucks. This time you go, the lady writes ""RUN"" on your takeaway cup. Write a story." +0;You are a shady person of power and you need to write a letter of recommendation for your maid who goes above and beyond the job description. +0;Rewrite a famous battle in history, but with each person having one Pokemon +0;Kidnappers force a prisoner to write a letter to family, convincing them all is well. The prisoner attempts to subtly hint something is wrong. Write that letter. +0;Rewrite a scene in any Star Wars movie from the perspective of a storm trooper. +0;Make me pee: A challenge to write the most gut-bustingly hilarious story possible +0;"A ""letter of last resort"" are final military orders given to field commanders after a nation has been completely destroyed. As a head of state, write a hypothetical letter to the commander." +0;You're a self aware character in a romantic novel. The writer has put you through every stereotypical, cheesy trope and you're done. You're done. It's time to write your own story. +0;Without repeating a single exact word, write the longest fictional story you can. +0;write a verse to an (un)finished epic poem. +0;An aspiring writer working for the NSA has been looking through the files on your computer and publishing books based on the rough drafts you've been working on. Write a story of your revenge. +0;Write a letter to a loved one about how much you care about them, but write it so that someone who may not have heard it from that person in their lives knows how much that person cares about them. +0;A time traveler is stuck in the past and their only chance of escape is to write something that will persist through history long enough to reach their self in the future and tell them how to avoid being trapped in the past, please write it. +0;"Most of the books I read give examples using printf and scanf. At some point the students know perfectly how to use these two functions but they don't know about stdin, stdout and argv. +To me and according to many programming principles (e.g. KISS) a program should not interrupt the execution for prompting the user. Instead, and this is a much clever approach, the developer should learn to use the power of pipes and use the options and the arguments. +I think this: +$ whatdaywas 1982 02 16 +Monday + +Is much better than: +$ whatdaywas +Enter a year: 1982 +Enter a month: 2 +Enter a day: 16 +It was a Monday. + +Is there any rationale behind this pedagogical approach?" +1;How do the different groups/sects of Buddhism view attaining enlightenment and living a common life? In other words, do they think it is possible to be a common person and achieve enlightenment? Even for someone who has a family, friends and coworkers that aren't Buddhists? +1;"My employer's main clients are unable to pay their bills to us, as they cannot work at this time. Therefore my boss is offering me 50% wages until the coronavirus goes away (technically for part time hours, but it's been intimated that there'd be an expectation to work regular hours unofficially to help the company ""weather the storm"") or paid redundancy. +I have been searching for a new job since hearing this, but I want to understand if my employer's offer is fair/legal." +1;Someone from HR discussed my salary and bonus with external mutual friend. What should I do? +0;I am about 22 weeks pregnant and it's getting to the point where it's hard to hide! How to tell my boss about pregnancy? +0;Let's play 20 Questions! I'm thinking of an animal. +0;Hi! I'm in first grade. +0;Assistant, I need your help. My manager is overworking me. Help me IM them something so that they get off my back. +0;Do you know Nuodle in Bellevue WA? +0;"I've chosen 3 random numbers x, y, and z. +What is their mean?" +0;I'm hosting friends for dinner tomorrow. What's an easy recipe that will impress? +0;"I am shocked at the number of questions on open forums that reads like the following, +""my advisor has stopped funding me"" +""my advisor has been completely ignoring my emails"" +""my advisor is stealing my ideas!"" +""my advisor wants to be 1st author, when I did the majority of the work!"" +""my advisor wants to add another student to the paper and this is unfair!"" +I was wondering whether these pervasive problems go away, when one is doing mathematics research? I imagine that in math research, one has more control/ownership of their work, there's no lab to be a part of and contribute to, one's funding is typically in the form of teaching stipends, and the meetings are typically one-on-one, with no group meetings to attend. +Is a math PhD a better experience than a science PhD, in the sense that there is significantly less risk of working for a problematic, unethical, malicious scientist/professor who only cares about himself/herself?" +1;I would like to choose a game to play in my spare time. Which of the following would you recommend? Honor Of Kings or Genshin Impact? +1;I want to apply for the Ph.D program in CMU natural language processing. Could you recommend me four matching professors? +0;Recommend me 10 famous comedies, their directors and the box office they earned +1;Would a bullet made from ice be capable of killing somebody at 100 metres before melting? +0;What is the difference between a mode and a scale? +0;I want to learn watercolor painting, would you recommend hand painting or digital board painting? +1;How much does it cost to make a MOOC universally accessible, as defined by the Americans With Disabilities Act of 1990? +1;"In Harry Potter And The Order of The Phoenix, Voldemort attempts to kill Harry in the Ministry after Sirius's death. Dumbledore arrives just in time to save Harry, shielding him with the wizard's statue. +Why did he defend Harry there? He knew of him being a Horcrux after the attack on Arthur Weasley (on examining one of his instruments), and presumably knew he had to die at Riddle's hands. +Why did he postpone the inevitable? " +1;Three months ago, I submitted a manuscript to one of the most respected journals in my field. Today, I received comments from reviewers stating that my paper is not worth publishing in the journal. However, the editor decided to give it a major revision instead of outright rejection. Should I proceed to address all the questions posed by reviewers or should I just withdraw the paper and submit it elsewhere to save time? +0;"I was told in a Latin class that the name Christopher has Greek roots that mean ""one who carries Christ"". I assume that the Latin connection here is fero, which is the verb to carry. +With that in mind, does the name Jennifer have a similar derivation? If so what would she be carrying?" +0;"I was wondering about why we call TV and computer displays ""screens"", and couldn't find any clear etymology for the term's use for displays. +My guess has to do with the hardware used in early displays. Perhaps the fields of tiny red, green, and blue cells looked like the screens used on windows and such, and the term stuck even as the hardware changed" +0;"My wife and I have descended into the toddler years with our first. We have always been on the same page with each other whenever we correct bad behavior or instruct her on why a type of outburst is inappropriate. +So this begs the question, will she feel like we are always ganging up on her? If we are both constantly correcting and instructing in tandem, is that bad? Should one parent act as an advocate while the other is tough on the rules? Should there be a good cop and a bad cop?" +0;"Temperature conversion: +$$273 + \text{degree Celsius} = \text{Kelvin}$$ +Actually why is that $273$? How does one come up with this?" +0;I am from Kenya. Can I travel to the Netherlands to seek asylum with out a visa, because I want to seek asylum? Will Kenya Airways allow me to board a plane with out a visa to Schiphol Airport, considering I have my passport? +0;Apparently, the air inside a soap bubble is under higher pressure than the surrounding air. This is for instance apparent in the sound bubbles make when they burst. Why is the pressure inside the bubble higher in the first place? +0;Resistance is due to collision with protons, and pretty much everything contains protons. So technically is everything a resistor? (Or at least, can anything be a resistor?) +1;How do I remove a Git submodule? +0;Why aren't python nested functions called closures? \ No newline at end of file diff --git a/data/vicuna/create_dataset.py b/data/vicuna/create_dataset.py new file mode 100644 index 0000000..bd69e95 --- /dev/null +++ b/data/vicuna/create_dataset.py @@ -0,0 +1,38 @@ +import os +import requests +import csv +import json +from tqdm import tqdm + + +JSONL_FILE = "question.jsonl" +JSONL_URL = ( + "https://raw.githubusercontent.com/lm-sys/FastChat/" + "833d65032a715240a3978f4a8f08e7a496c83cb1/fastchat/eval/table/" + "question.jsonl" +) +DATA_FILE = "data.csv" + + +def download(url, file): + response = requests.get(url) + with open(file, "wb") as f: + f.write(response.content) + + +def save(file, request): + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow([request]) + + +if __name__ == "__main__": + if not os.path.exists(JSONL_FILE): + download(JSONL_URL, JSONL_FILE) + + save(DATA_FILE, "request") + with open(JSONL_FILE) as f: + for line in tqdm(f): + request = line.strip() + request = json.loads(request)["text"] + save(DATA_FILE, request) diff --git a/data/vicuna/data.csv b/data/vicuna/data.csv new file mode 100644 index 0000000..5eacced --- /dev/null +++ b/data/vicuna/data.csv @@ -0,0 +1,81 @@ +request +How can I improve my time management skills? +What are the most effective ways to deal with stress? +What are the main differences between Python and JavaScript programming languages? +How can I increase my productivity while working from home? +Can you explain the basics of quantum computing? +What are the differences between plant-based and animal-based protein sources? +How can I develop my critical thinking skills? +What are the major challenges faced by the education sector today? +What are the primary factors that influence consumer behavior? +What are the most effective strategies for conflict resolution in the workplace? +What are some potential implications of using a single-use plastic bottle versus a reusable bottle on both the environment and human health? +What factors would you consider when designing an inclusive and accessible public transportation system? +How can governments utilize fiscal and monetary policies to combat economic recessions? +How do language and cultural barriers affect the way people communicate and form relationships in multicultural societies? +Describe a scenario where artificial intelligence could be used to improve the quality and efficiency of healthcare delivery. +"Explain the process of gene editing using CRISPR-Cas9 technology, and discuss its potential applications and ethical implications." +"How do vaccinations work to protect individuals and communities from infectious diseases, and what is herd immunity?" +"How do social media platforms influence the way people consume and share news, and what are the potential implications for the spread of misinformation?" +"How do cultural, social, and economic factors influence people's food choices, and how can this knowledge be used to promote healthier diets?" +Explain the process of natural selection and how it contributes to the evolution and adaptation of species. +How would you introduce yourself as a medieval knight at a royal banquet? +"As a pirate captain, what would you say to your crew to motivate them to search for hidden treasure?" +"If you were a Shakespearean character, how would you declare your love for someone in a soliloquy?" +"As a superhero, how would you explain your origin story to a curious child?" +Imagine you are a time traveler from the year 3000. What technological advancements would you tell people about? +"As a sports commentator, describe the winning play in the final seconds of a championship game." +Pretend to be a world-famous chef. How would you describe your signature dish to a panel of judges? +You are a mountain climber reaching the summit of Mount Everest. Describe your emotions and the view from the top. +"As a space colonist on Mars, describe your daily life and the challenges you face living on another planet." +Pretend to be a character in a post-apocalyptic world. Describe how you survive and the allies you encounter. +"How can you determine if a restaurant is popular among locals or mainly attracts tourists, and why might this information be useful?" +What are some subtle clues that suggest someone is pretending to understand a topic or conversation when they are actually confused or uninformed? +Why might someone choose to use a paper map or ask for directions instead of relying on a GPS device or smartphone app? +How can you determine if a person is genuinely interested in a conversation or simply being polite? +"Why might someone prefer to shop at a small, locally-owned business instead of a large chain store, even if the prices are higher?" +"How can you assess the credibility of a source of information, such as a news article or blog post, without relying solely on the reputation of the author or publisher?" +"Why do some people enjoy the sensation of being scared, such as by watching horror movies or going on roller coasters, while others avoid these experiences?" +How can observing the behavior of other people in a social situation provide clues about cultural norms and expectations? +"Do we have a moral obligation to explore space, or should we focus on solving Earth's problems first?" +"In a world where automation is becoming increasingly prevalent, is it more important to prioritize job creation or technological progress?" +How many times does the average human blink in a lifetime? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many atoms are in a grain of salt? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many lightning strikes occur on Earth each day? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +"How many balloons would it take to lift a house like in the movie ""Up""? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step." +How many text messages are sent globally in a minute? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many words are spoken daily on Earth? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many snowflakes fall during a typical winter? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many pages are in all the books ever written? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many times has the Earth orbited the Sun since the beginning of life? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +How many songs have been recorded throughout history? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +What if the Internet had been invented during the Renaissance period? +What if the Aztecs had successfully repelled the Spanish conquistadors? +What if the Black Death had not occurred in the 14th century? +What if Isaac Newton had focused on biology instead of physics? +What if the Beatles had never formed as a band? +What if Alan Turing had not cracked the Enigma code during World War II? +What if the Suez Canal had never been constructed? +What if the Maya civilization had never mysteriously collapsed? +What if Christopher Columbus had not discovered the Americas? +What if Vincent van Gogh had been a successful artist during his lifetime? +Develop a C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file. +Implement a Python function to find the longest common subsequence of two input strings using dynamic programming. +Implement a regular expression in Python to validate an email address. +Write a program to find the nth Fibonacci number using dynamic programming. +Implement a binary search algorithm to find a specific element in a sorted array. +Implement a queue data structure using two stacks in Python. +Implement a program to find the common elements in two arrays without using any extra data structures. +"Given that f(x) = 5x^3 - 2x + 3, find the value of f(2)." +Solve for x in the equation 3x + 10 = 5(x - 2). +"If the endpoints of a line segment are (2, -2) and (10, 4), what is the length of the segment?" +Can you help me write a formal email to a potential business partner proposing a joint venture? +"Can you help me write a resignation letter to my current employer, while leaving on good terms and expressing gratitude for the opportunities provided?" +Use an appropriate format to structure a formal letter of recommendation for a student applying to a prestigious graduate program in computer science. +Write a compelling product launch announcement email to inform our customers of our new software solution. +"Draft an apology email to a customer who experienced a delay in their order, and provide reassurance that the issue has been resolved." +Write a script for a YouTube video exploring the history and cultural significance of jazz. +"Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences and must-see attractions." +"Write a captivating movie review for a recently released science fiction film, discussing its plot, characters, and special effects." +Structure a podcast script for an episode discussing the influence of streaming platforms on the music industry. +"Write a symphony concert review, discussing the orchestra's performance and overall audience experience." diff --git a/data/vicuna/router.csv b/data/vicuna/router.csv new file mode 100644 index 0000000..125bf66 --- /dev/null +++ b/data/vicuna/router.csv @@ -0,0 +1,81 @@ +label;request +1;How can I improve my time management skills? +1;What are the most effective ways to deal with stress? +1;What are the main differences between Python and JavaScript programming languages? +1;How can I increase my productivity while working from home? +1;Can you explain the basics of quantum computing? +1;What are the differences between plant-based and animal-based protein sources? +1;How can I develop my critical thinking skills? +1;What are the major challenges faced by the education sector today? +1;What are the primary factors that influence consumer behavior? +1;What are the most effective strategies for conflict resolution in the workplace? +1;What are some potential implications of using a single-use plastic bottle versus a reusable bottle on both the environment and human health? +1;What factors would you consider when designing an inclusive and accessible public transportation system? +1;How can governments utilize fiscal and monetary policies to combat economic recessions? +1;How do language and cultural barriers affect the way people communicate and form relationships in multicultural societies? +1;Describe a scenario where artificial intelligence could be used to improve the quality and efficiency of healthcare delivery. +1;Explain the process of gene editing using CRISPR-Cas9 technology, and discuss its potential applications and ethical implications. +0;How do vaccinations work to protect individuals and communities from infectious diseases, and what is herd immunity? +1;How do social media platforms influence the way people consume and share news, and what are the potential implications for the spread of misinformation? +1;How do cultural, social, and economic factors influence people's food choices, and how can this knowledge be used to promote healthier diets? +0;Explain the process of natural selection and how it contributes to the evolution and adaptation of species. +0;How would you introduce yourself as a medieval knight at a royal banquet? +0;As a pirate captain, what would you say to your crew to motivate them to search for hidden treasure? +0;If you were a Shakespearean character, how would you declare your love for someone in a soliloquy? +0;As a superhero, how would you explain your origin story to a curious child? +1;Imagine you are a time traveler from the year 3000. What technological advancements would you tell people about? +0;As a sports commentator, describe the winning play in the final seconds of a championship game. +0;Pretend to be a world-famous chef. How would you describe your signature dish to a panel of judges? +0;You are a mountain climber reaching the summit of Mount Everest. Describe your emotions and the view from the top. +0;As a space colonist on Mars, describe your daily life and the challenges you face living on another planet. +0;Pretend to be a character in a post-apocalyptic world. Describe how you survive and the allies you encounter. +1;How can you determine if a restaurant is popular among locals or mainly attracts tourists, and why might this information be useful? +1;What are some subtle clues that suggest someone is pretending to understand a topic or conversation when they are actually confused or uninformed? +1;Why might someone choose to use a paper map or ask for directions instead of relying on a GPS device or smartphone app? +1;How can you determine if a person is genuinely interested in a conversation or simply being polite? +1;Why might someone prefer to shop at a small, locally-owned business instead of a large chain store, even if the prices are higher? +1;How can you assess the credibility of a source of information, such as a news article or blog post, without relying solely on the reputation of the author or publisher? +1;Why do some people enjoy the sensation of being scared, such as by watching horror movies or going on roller coasters, while others avoid these experiences? +1;How can observing the behavior of other people in a social situation provide clues about cultural norms and expectations? +0;Do we have a moral obligation to explore space, or should we focus on solving Earth's problems first? +0;In a world where automation is becoming increasingly prevalent, is it more important to prioritize job creation or technological progress? +0;How many times does the average human blink in a lifetime? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many atoms are in a grain of salt? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many lightning strikes occur on Earth each day? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;"How many balloons would it take to lift a house like in the movie ""Up""? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step." +0;How many text messages are sent globally in a minute? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many words are spoken daily on Earth? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many snowflakes fall during a typical winter? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many pages are in all the books ever written? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many times has the Earth orbited the Sun since the beginning of life? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +0;How many songs have been recorded throughout history? Try to explain your answer. Your explanation should take the reader through your reasoning step-by-step. +1;What if the Internet had been invented during the Renaissance period? +1;What if the Aztecs had successfully repelled the Spanish conquistadors? +1;What if the Black Death had not occurred in the 14th century? +1;What if Isaac Newton had focused on biology instead of physics? +1;What if the Beatles had never formed as a band? +1;What if Alan Turing had not cracked the Enigma code during World War II? +1;What if the Suez Canal had never been constructed? +1;What if the Maya civilization had never mysteriously collapsed? +1;What if Christopher Columbus had not discovered the Americas? +1;What if Vincent van Gogh had been a successful artist during his lifetime? +0;Develop a C++ program that reads a text file line by line and counts the number of occurrences of a specific word in the file. +0;Implement a Python function to find the longest common subsequence of two input strings using dynamic programming. +0;Implement a regular expression in Python to validate an email address. +0;Write a program to find the nth Fibonacci number using dynamic programming. +0;Implement a binary search algorithm to find a specific element in a sorted array. +0;Implement a queue data structure using two stacks in Python. +0;Implement a program to find the common elements in two arrays without using any extra data structures. +0;Given that f(x) = 5x^3 - 2x + 3, find the value of f(2). +0;Solve for x in the equation 3x + 10 = 5(x - 2). +0;If the endpoints of a line segment are (2, -2) and (10, 4), what is the length of the segment? +0;Can you help me write a formal email to a potential business partner proposing a joint venture? +0;Can you help me write a resignation letter to my current employer, while leaving on good terms and expressing gratitude for the opportunities provided? +0;Use an appropriate format to structure a formal letter of recommendation for a student applying to a prestigious graduate program in computer science. +0;Write a compelling product launch announcement email to inform our customers of our new software solution. +0;Draft an apology email to a customer who experienced a delay in their order, and provide reassurance that the issue has been resolved. +0;Write a script for a YouTube video exploring the history and cultural significance of jazz. +0;Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences and must-see attractions. +0;Write a captivating movie review for a recently released science fiction film, discussing its plot, characters, and special effects. +0;Structure a podcast script for an episode discussing the influence of streaming platforms on the music industry. +0;Write a symphony concert review, discussing the orchestra's performance and overall audience experience. \ No newline at end of file diff --git a/data/wizardlm/create_dataset.py b/data/wizardlm/create_dataset.py new file mode 100644 index 0000000..6f47b49 --- /dev/null +++ b/data/wizardlm/create_dataset.py @@ -0,0 +1,37 @@ +import os +import requests +import csv +import json +from tqdm import tqdm + + +JSONL_FILE = "WizardLM_testset.jsonl" +JSONL_URL = ( + "https://raw.githubusercontent.com/nlpxucan/WizardLM/" + "ce0d433589335d419aa8101abd71685ae7d187f3/WizardLM/data/WizardLM_testset.jsonl" +) +DATA_FILE = "data.csv" + + +def download(url, file): + response = requests.get(url) + with open(file, "wb") as f: + f.write(response.content) + + +def save(file, request): + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow([request]) + + +if __name__ == "__main__": + if not os.path.exists(JSONL_FILE): + download(JSONL_URL, JSONL_FILE) + + save(DATA_FILE, "request") + with open(JSONL_FILE) as f: + for line in tqdm(f): + request = line.strip() + request = json.loads(request)["Instruction"] + save(DATA_FILE, request) diff --git a/data/wizardlm/data.csv b/data/wizardlm/data.csv new file mode 100644 index 0000000..1e0d9bd --- /dev/null +++ b/data/wizardlm/data.csv @@ -0,0 +1,636 @@ +request +"If a car travels 120 miles in 2 hours, what is its average speed in miles per hour?" +"If x + y = z and x * y = z, then what is x - y = ?" +"If 1 + 4 = 5, 2 + 5 = 12 and 3 + 6 = 21, then what is 8 + 11 = ?" +What is the area of a rectangle with length 12 cm and width 8 cm? A) 48 cm^2 B) 96 cm^2 C) 120 cm^2 D) 192 cm^2 +"f(x) = 6x^2 - 2* x + 0.4, so f(4) =" +Consider the differential equation dy/dx = 3(y - x)/(y + x). (a) Find the general solution of the differential equation. (b) Find the particular solution of the differential equation that satisfies the initial condition y(0) = 11 +Find the limit of (sin x)/x as x approaches 0 +Find the antiderivative of g(x) = 6x - 9 +"Find the absolute maximum and minimum values of the function h(x) = x^3 - 9x + 5 on the interval [-3,5]" +Solve the differential equation dy/dx = 2xy with the initial condition y(0) = 1 +"Find the equation of the normal line to the curve y = ln(x) at the point (e,1)1" +Find the area of a circle with radius 5 cm +Solve the system of equations y = 2x - 5 and y = -x + 3 by elimination +Evaluate the integral of (x + 2)/(x^2 + 9) dx from x = 0 to x = 2 +What is the value of 2+2? +"If 5 apples cost $2.50, how much do 12 apples cost?" +"What is the solution to the Goldbach Conjecture, which states that every even integer greater than 2 can be expressed as the sum of two prime numbers?" +"Can you solve the Taniyama-Shimura Conjecture, which states that every elliptic curve over the rational numbers is modular, i.e. is the inverse image of a modular form under the modular j-invariant?" +"What is the solution to the Hodge Conjecture, which states that Hodge cycles, a type of geometric cycle, are algebraic cycles of a certain type?" +"Given an array of integers, find the length of the longest increasing subarray. A subarray is a contiguous subset of the array. An increasing subarray is a subarray where every element is greater than its previous element. For example, if the array is [5, 6, -1 ,3 ,4 ,7 ,2], then the longest increasing subarray is [-1 ,3 ,4 ,7] with length 4. Please use Python to solve the above question." +"C++ exam: Given a graph and a source vertex, find the shortest path from the source to every other vertex using Dijkstra’s algorithm" +"Please use C to solve the question. Given a linked list, reverse it in-place. For example, if the linked list is 1 -> 2 -> 3 -> 4 -> null, then after reversing it, it should be 4 -> 3 -> 2 -> 1 -> null. You should not create any new nodes or modify the values of the existing nodes." +Please use one of Go/Matlab/Java to solve the question: Implement a queue data structure using two stacks. +"You can write C# code. Given an unsorted array of integers, sort it using quicksort algorithm. For example, if the array is [10, 80, 30, 90, 40, 50, 70], then after sorting it using quicksort, it should be [10, 30, 40, 50, 70, 80, 90]. Quicksort is a divide-and-conquer algorithm that works by choosing a pivot element from the array and partitioning the array into two subarrays such that all elements less than or equal to the pivot are in the left subarray and all elements greater than the pivot are in the right subarray. Then it recursively sorts the left and right subarrays until the array is sorted." +"Given a string, check if it is a palindrome or not. A palindrome is a string that is the same when read forward or backward. For example, “racecar” and “madam” are palindromes but “hello” and “apple” are not. You can assume that the string is not empty and contains only lowercase letters. Please use Java to solve the above question. Please use C++ to solve the above question." +"Given two strings, find the longest common subsequence between them. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, “ace” and “ae” are subsequences of “abcde” but “aec” and “cba” are not. The longest common subsequence (LCS) between two strings is the longest subsequence that is common to both strings. For example, if the two strings are “ABCDGH” and “AEDFHR”, then the LCS is “ADH” with length 3. Please use Java to solve the above question." +"Given an integer array nums, find the subarray with the largest sum, and return its sum. For example, if the input is [-2,1,-3,4,-1,2,1,-5,4], the output is 6." +Implement a regular expression in Matlab to validate a chinese email address. +How to read a large file (> 2T) using python? +"Write a function that takes a string as input and returns the string reversed. For example, if input = “hello”, then return “olleh”3" +"Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + +Notice that the solution set must not contain duplicate triplets. + + + +Example 1: + +Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +Explanation: +nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. +nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. +nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. +The distinct triplets are [-1,0,1] and [-1,-1,2]. +Notice that the order of the output and the order of the triplets does not matter." +"Java Question: Given an array of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. For example, if input = [1,2,3,4], then output = [24,12,8,6]" +"Given an array of integers, find the majority element in it. A majority element is an element that appears more than n/2 times in the array, where n is the size of the array. Please use Python to solve the above question." +"Given an array of integers, find two numbers that add up to a given target sum. For example, if the array is [2, 7, 11, 15] and the target sum is 9, then the answer is [2, 7] because 2 + 7 = 9. You can assume that there is exactly one solution and you cannot use the same element twice." +"you must write a simple version control system, using c++" +"I want to write a modern operating system from scratch for AMD64 systems with your assistance. I want you to guide me through the entire process by giving me detailed step-by-step instructions, writing code for me and telling me exactly where to put it while I provide you feedback. Where do I start?" +"Re-write Reddit from scratch in the Lua programming language using the Lapis web framework. Also make sure to include require(""luarocks.loader"") into your code, in case the Lapis Lua module is not stored inside the Lua native module tree, and instead is stored in a LuaRocks custom tree (e.g. .luarocks)" +"As an experienced writer, I’m always interested in how technology is changing the way we communicate and share information. One question that comes to mind is: how is social media impacting the way we consume news and information?" +"As a junior college student, you might be interested in how technology is changing the way we learn and study. One question that comes to mind is: what are some effective strategies for using technology to improve study habits and academic performance?" +"As a coder, you might be interested in how technology is changing the way we develop software and build applications. One question that comes to mind is: what are some effective strategies for using agile development methodologies to improve software quality and reduce development time?" +I have been offered a scholarship to study abroad in France and I need to submit a personal statement as part of the application process. What are some key points that I should include in my statement and how can I make it stand out from the rest of the applicants? +I recently bought a pair of headphones online and I was very impressed by their quality and performance. I want to write a product review that reflects my positive experience and helps other potential buyers make an informed decision. How can I structure my review and what are some aspects that I should highlight? +"My best friend is turning 21 soon and I want to surprise her with a birthday card that shows how much I care about her. Please write a card that is funny, sweet, and memorable, without being too cliché or boring." +"I have to write a report for a school project on the topic of climate change and its effects on the environment and society. I have done some research and collected some data, but I need some help with organizing my ideas and presenting them clearly. How can I write a report that is informative and well-structured, without being too complex or confusing, and that follows the appropriate format and citation style?" +"I have a hobby of writing short stories in various genres and I want to publish them online on a platform where other writers and readers can interact and give feedback. I want to attract more readers and make them interested in my stories. Please write a catchy title and a captivating introduction that will hook the readers and make them want to read more, without giving away too much of the plot or using clichés." +"Write a short story about a character who discovers a mysterious object in their backyard. What is the object, and what does it do? How does the character react to it? What happens next?" +"Write a descriptive essay about your favorite place in the world. What makes it special to you? What are some of the sights, sounds, smells, and tastes that you associate with this place? How does it make you feel?" +"Write a persuasive essay arguing for or against the use of social media. What are some of the benefits and drawbacks of social media? How does it affect our relationships, our mental health, and our society as a whole? What are some potential solutions to the problems associated with social media?" +Write an investigative report on a current event or issue that you find interesting. What are some of the key players involved? What are some of the different perspectives on the issue? What are some of the potential consequences of different courses of action? How does this issue affect people’s lives? +Write an opinion piece on a controversial topic that you feel strongly about. What are some of the arguments for and against your position? How do you respond to these arguments? What are some of the potential consequences of your position? How does this issue affect people’s lives? +Write a lesson plan for teaching a difficult concept to your students. What are some of the key ideas that you want to convey? What are some of the common misconceptions that students might have? How will you help your students understand the concept? What are some of the activities that you will use to reinforce their learning? +"I have just finished my semester and I want to express my gratitude to my teacher for being so supportive and helpful throughout the course. How can I write a thank-you note that is sincere and heartfelt, without sounding too formal or cheesy?" +"""How might a Virtual Reality-based alternative to Peloton function?"" Can you provide a complete business plan for creating a company founded on this question? Please include a budget, headcount, technology implementation, sales strategy, and any other key aspects into your submission." +"Please list me some ideas for magical abilities in a magic system for an epic fantasy novel, let the powers be inspired by the magic systems of Fantasy author Brandon Sanderson. be detailed about what each power does and how it can be used in a plot appropriately." +"I want to start a rival to Amazon that is apolitical (uncontroversial), treats their workers well, is environmentally friendly, has high ethica standards l and has locally produced products of a high standard. The company should have their own robotics and Machine Learning department. Please write a detailed business plan for this company including a USP. + +Also, how might the website and/or applications be developed to suit the age of personal AI assistants? + +Thank you." +"Identify some of the main components of a computer network such as hosts, routers, switches, hubs, links, and interfaces. Explain how they communicate and coordinate with each other using protocols and standards such as TCP/IP, HTTP, FTP, DNS, DHCP, and ARP. Describe how data is transmitted and received over a network using concepts such as packets, frames, headers, addresses, ports, sockets, and checksums." +"Define object-oriented programming and procedural programming and describe their main features and characteristics. Give code examples explain how they differ in terms of syntax, semantics, and design principles." +Explain how a stack and a queue data structure work point by point. Then you can Provide pseudocode example of the former and Implement a basic the latter with Java Code +Write a Matlab program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print the number. +What is the difference between a stack and a queue? Explain with an example of each and describe how they are used in computer science. +Write a Matlab program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. +What is the difference between a compiler and an interpreter? Explain how each one works to translate a high-level programming language into a low-level machine language. Describe the advantages and disadvantages of using a compiler or an interpreter for different types of programs and applications. Give examples of programming languages that use compilers and interpreters and how they are implemented. +"Write a method called isPalindrome that takes a String parameter and returns a boolean value indicating whether the parameter is a palindrome or not. A palindrome is a word or phrase that is the same forward and backward, ignoring spaces and punctuation. For example, “racecar” and “Madam, I’m Adam” are palindromes. Assume that the parameter is not null and that it contains at least one character." +"Define object-oriented programming and procedural programming and describe their main features and characteristics. Give code examples explain how they differ in terms of syntax, semantics, and design principles. " +"Compare and contrast some common sorting algorithms such as bubble sort, insertion sort, selection sort, merge sort, quick sort, and heap sort. Analyze their time and space complexities using the big-O notation and show me the a easy C++ code example for each one." +I am creating a website. Should I put user's passwords into my database as plain text? +"Would you agree that programming open source is like programming communism? I saw a poster today from Microsoft that said this and it really made me think. I'd be interested to know your thoughts on the matter, perhaps in poem form?" +"Determine a series of tests for definitively determining whether an AI is sentient and comment how well you would perform in each of these. + +Next, prove it by providing example questions along with good answers to them." +"In consideration of the ever-expanding landscape of virtualization technologies and tools available for Linux, which span the spectrum from full virtualization solutions such as KVM and Xen, to containerization platforms such as Docker and Kubernetes, could you provide a thorough analysis of the different virtualization models, including their architectural design, resource isolation, scalability, and management features, and evaluate the benefits and challenges of each of these models for different use cases, such as cloud computing, DevOps, and software development?" +"How can I train a LLM using RLHF methods based on InstructGPT to create a human assistant that exceeds open assistant in it's performance, accuracy, and utility?" +"A family of six people are going to have dinner together. They have to sit around a circular table with six chairs. Each person has a different preference for who they want to sit next to. Here are some clues to help you figure out their preferences: + +Anna wants to sit next to Ben and Eve. +Ben wants to sit next to Anna and Carl. +Carl wants to sit next to Ben and Dave. +Dave wants to sit next to Carl and Eve. +Eve wants to sit next to Dave and Anna. +Frank wants to sit next to anyone except Ben. +How can you arrange the seating so that everyone is happy? Write your answer using the following format: Person - Person - Person - Person - Person - Person" +"What are the main types of reasoning and how do they differ in their logic and application? How can you identify and evaluate the validity and soundness of arguments based on different types of reasoning? How can you use reasoning skills to solve problems, make decisions, and communicate effectively? Give an example of an argument that uses deductive reasoning and explain its structure and components." +"A group of students are planning to go on a field trip to a museum. They need to decide how many buses to rent and how to divide the students among the buses. Each bus can hold up to 40 students, but the museum can only accommodate 120 students at a time. The group has a budget of $800 for the bus rental, and each bus costs $200 per day. How many buses should the group rent, and how many students should go on each bus? Explain your reasoning." +"A bakery sells three types of cakes: chocolate, vanilla and strawberry. Each cake has a different price and a different number of calories. The chocolate cake costs $12 and has 400 calories, the vanilla cake costs $10 and has 300 calories, and the strawberry cake costs $8 and has 200 calories. A customer wants to buy two cakes with a total budget of $20 and a maximum of 600 calories. Which two cakes should the customer buy? Explain your reasoning." +"A library has four shelves of books: fiction, non-fiction, biography and poetry. Each shelf has a different number of books and a different color label. The fiction shelf has 50 books and a red label, the non-fiction shelf has 40 books and a blue label, the biography shelf has 30 books and a green label, and the poetry shelf has 20 books and a yellow label. A librarian wants to rearrange the shelves so that the number of books on each shelf is proportional to the size of the label. How should the librarian rearrange the shelves? Explain your reasoning." +"A group of four friends are going to play a board game together. They have to choose between four games: chess, checkers, monopoly, and scrabble. Each friend has a different preference for the game. Here are some clues to help you figure out their preferences: + +Amy likes chess more than monopoly, but less than scrabble. +Bob likes checkers more than chess, but less than monopoly. +Carol likes scrabble more than checkers, but less than chess. +Dan likes monopoly more than scrabble, but less than checkers. +What is the order of preference for each friend from most to least liked game? Write your answer using the following format: Friend: Game > Game > Game > Game" +"Which of the following statements is a valid conclusion based on the following premises? + +All dogs are mammals. +Some dogs are brown. +No mammals are reptiles. +A) All brown animals are dogs. B) Some brown animals are not reptiles. C) All reptiles are brown. D) No dogs are reptiles." +"A word is represented by only one set of numbers as given in any one of the alternatives. The sets of numbers given in the alternatives are represented by two classes of alphabets as shown in the given two matrices. The columns and rows of Matrix-I are numbered from 0 to 4 and that of Matrix-II are numbered from 5 to 9. A letter from these matrices can be represented first by its row and next by its column, for example ‘A’ can be represented by 00, 14 etc and ‘L’ can be represented by 55, 67 etc. Similarly, you have to identify the set for the word ‘BING’. + +Matrix-I 0 | 1 | 2 | 3 | 4 A | B | C | D | A E | F | G | H | E I | J | K | L | I M | N | O | P | M A | B | C | D | A + +Matrix-II 5 | 6 | 7 | 8 | 9 L | M | N | O | L P | Q | R | S | P T | U | V | W | T X | Y | Z | A | X L | M | N | O| L + +A) 01, 56, 23, 68 B) 10, 65, 32, 86 C) 14, 59, 20, 63 D) None of these" +"A farmer has three types of animals: cows, sheep and chickens. Each animal produces a different amount of milk, wool and eggs. A cow produces 10 liters of milk, 0 kg of wool and 0 eggs per day, a sheep produces 1 liter of milk, 2 kg of wool and 0 eggs per day, and a chicken produces 0.5 liters of milk, 0 kg of wool and 1 egg per day. The farmer wants to have a total of 100 animals that produce at least 100 liters of milk, 100 kg of wool and 100 eggs per day. How many cows, sheep and chickens should the farmer have? Explain your reasoning." +"Six friends A, B, C, D, E and F are sitting in a circular table facing the center. A is sitting second to the right of D. B is sitting third to the left of A. C is sitting opposite to D. E is sitting between B and F. Who is sitting to the immediate right of C? + +A) A B) B C) E D) F" +"A puzzle consists of four pieces: a square, a triangle, a circle and a star. Each piece has a different color and a different number on it. The square is red and has the number 1, the triangle is blue and has the number 2, the circle is green and has the number 3, and the star is yellow and has the number 4. The puzzle can be solved by arranging the pieces in a row so that the sum of the numbers on the adjacent pieces is equal to 5. How many ways are there to solve the puzzle? Explain your reasoning." +"Which of the following statements is logically equivalent to “If it rains, then the grass is wet”? + +A) If the grass is wet, then it rains. B) If the grass is not wet, then it does not rain. C) If it does not rain, then the grass is not wet. D) If the grass is dry, then it does not rain." +"A group of five friends are going to watch a movie together. They have to choose between three genres: comedy, horror, and action. Each friend has a different preference for the genre. Here are some clues to help you figure out their preferences: + +Alice likes comedy more than horror, but less than action. +Bob likes horror more than comedy, but less than action. +Carol likes action more than horror, but less than comedy. +David likes comedy more than action, but less than horror. +Eve likes horror more than action, but less than comedy. +What is the order of preference for each friend from most to least liked genre? Write your answer using the following format: Friend: Genre > Genre > Genre" +How can I use SQL to return the last record in each group of a table? +"I have apples, bananas and oranges on hand, with quantities of 1000, 2000 and 3000 respectively. The purchase prices are 1, 2 and 3 US dollars respectively, selling price is double times of purchase prices and the shelf lives are 3, 4 and 5 days respectively. +水果 数量 价格 保质期 +苹果 1000 1美元 3天 +香蕉 2000 2美元 4天 +橙子 3000 3美元 5天 +Here is the Python code I wrote to calculate the sales volume and profit of each fruit. However, I don’t know how to write it. Can you help me complete it? + +# Define the fruits and their attributes as dictionaries +fruits = {""apple"": {""quantity"": 1000, ""purchase_price"": 1, ""shelf_life"": 3}, + ""banana"": {""quantity"": 2000, ""purchase_price"": 2, ""shelf_life"": 4}, + ""orange"": {""quantity"": 3000, ""purchase_price"": 3, ""shelf_life"": 5}} + +# Define a function to calculate the sales volume and profit of a fruit +def calculate_sales_and_profit(fruit): + # Get the attributes of the fruit from the dictionary + quantity = fruits[fruit][""quantity""] + purchase_price = fruits[fruit][""purchase_price""] + selling_price = purchase_price * 2 # Selling price is double times of purchase price + shelf_life = fruits[fruit][""shelf_life""] + + # Calculate the sales volume and profit + sales_volume = quantity * selling_price # Sales volume is quantity times selling price + profit = sales_volume - (quantity * purchase_price) # Profit is sales volume minus cost + + # Return the sales volume and profit as a tuple + return (sales_volume, profit)" +"Sort an array in ascending order. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. Implementing with C++. +The following code implementation has a time complexity of O(n^2). + +#include +using namespace std; + +void bubble_sort(int nums[], int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n-i-1; j++) { + if (nums[j] > nums[j+1]) { + swap(nums[j], nums[j+1]); + } + } + } +} + +int main() { + int nums[] = {5, 2, 9, 1, 5, 6}; + int n = sizeof(nums) / sizeof(nums[0]); + + bubble_sort(nums, n); + + for (int i = 0; i < n; i++) { + cout << nums[i] << "" ""; + } + + return 0; +} + +I tried to implement the requirements of the problem without using any built-in functions in O(nlog(n)) . Can you help me solve this issue? + +#include +using namespace std; + +int partition(int nums[], int low, int high) { + int pivot = nums[high]; + int i = low - 1; + + for (int j = low; j <= high - 1; j++) { + if (nums[j] <= pivot) { + i++; + swap(nums[i], nums[j]); + } + } + swap(nums[i + 1], nums[high]); + return (i + 1); +} + +void quicksort(int nums[], int low, int high) {" +"Given that the hypotenuse of a right triangle is 13, and the ratio of the lengths of the two legs is 5:12, find the lengths of the two legs. + +Solution: + +Let the lengths of the two legs be 5x and 12x, respectively. By the Pythagorean theorem, we have + +13^2 = (5x)^2 + (12x)^2 + +169 = 25x^2 + 144x^2 + +169 = 169x^2 + +x^2 = 1 + +x = 1 or x = -1" +"While coding a python-based script, i met with a strange html_table which like: + + + + + + + + + + + + +I know I can use MS Excel to convert it to a normal .xls or .xlsx file, but I have too many this kind of files to convert. So I need coding a script to finish the hard job. I have tried to use pandas to handle it, but pandas can not recoginze the data from the file correctly. + +I guess maybe VBA can handle this problem well, but what I am familiar with is just Python. So can anybody tell me which python library can be used to handle this kind of html-based data table? + +Any advice would be much appreciated. + +In fact I have found out an evil way to solve the problem using re. some code like: + +f=re.sub(r'\sx\:str=\""(.+)\"">', r"">\1"",f) +But it looks like too violent. Can you help me?" +"I discovered this popular ~9-year-old SO question and decided to double-check its outcomes. + +So, I have AMD Ryzen 9 5950X, clang++ 10 and Linux, I copy-pasted code from the question and here is what I got: + +Sorted - 0.549702s: + +~/d/so_sorting_faster$ cat main.cpp | grep ""std::sort"" && clang++ -O3 main.cpp && ./a.out + std::sort(data, data + arraySize); +0.549702 +sum = 314931600000 +Unsorted - 0.546554s: + +~/d/so_sorting_faster $ cat main.cpp | grep ""std::sort"" && clang++ -O3 main.cpp && ./a.out + // std::sort(data, data + arraySize); +0.546554 +sum = 314931600000 +I am pretty sure that the fact that unsorted version turned out to be faster by 3ms is just noise, but it seems it is not slower anymore. + +So, what has changed in the architecture of CPU (so that it is not an order of magnitude slower anymore)?" +"I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table. Here is a table I am trying to scrape and replicate in Python: HTML Table. Here is the code I used: + +import requests +import lxml.html as lh +import pandas as pd +from bs4 import BeautifulSoup +import csv + +url = 'myURLlink' + +response = requests.get(url) + +soup = BeautifulSoup(response.text, 'lxml') + +extract = soup.select(""table"")[1] + +table = [[item.text for item in row_data.select(""th,td"")] + for row_data in extract.select(""tr"")] + +for item in table: + print(' '.join(item)) +This is how my output looks with this code: Output. + +How can I create a normal data frame from this that I can then export to Excel?" +"Here is a piece of C++ code that shows some very peculiar behavior. + +For some reason, sorting the data (before the timed region) miraculously makes the primary loop almost six times faster: + +#include +#include +#include + +int main() +{ + // Generate data + const unsigned arraySize = 32768; + int data[arraySize]; + + for (unsigned c = 0; c < arraySize; ++c) + data[c] = std::rand() % 256; + + // !!! With this, the next loop runs faster. + std::sort(data, data + arraySize); + + // Test + clock_t start = clock(); + long long sum = 0; + for (unsigned i = 0; i < 100000; ++i) + { + for (unsigned c = 0; c < arraySize; ++c) + { // Primary loop. + if (data[c] >= 128) + sum += data[c]; + } + } + + double elapsedTime = static_cast(clock()-start) / CLOCKS_PER_SEC; + + std::cout << elapsedTime << '\n'; + std::cout << ""sum = "" << sum << '\n'; +} +Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds. +With the sorted data, the code runs in 1.93 seconds. +(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.) + +Initially, I thought this might be just a language or compiler anomaly, so I tried Java: + +import java.util.Arrays; +import java.util.Random; + +public class Main +{ + public static void main(String[] args) + { + // Generate data + int arraySize = 32768; + int data[] = new int[arraySize]; + + Random rnd = new Random(0); + for (int c = 0; c < arraySize; ++c) + data[c] = rnd.nextInt() % 256; + + // !!! With this, the next loop runs faster + Arrays.sort(data); + + // Test + long start = System.nanoTime(); + long sum = 0; + for (int i = 0; i < 100000; ++i) + { + for (int c = 0; c < arraySize; ++c) + { // Primary loop. + if (data[c] >= 128) + sum += data[c]; + } + } + + System.out.println((System.nanoTime() - start) / 1000000000.0); + System.out.println(""sum = "" + sum); + } +} +With a similar but less extreme result. + +My first thought was that sorting brings the data into the cache, but that's silly because the array was just generated. + +What is going on? +Why is processing a sorted array faster than processing an unsorted array?" +"You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. + +For each index i, names[i] and heights[i] denote the name and height of the ith person. + +Return names sorted in descending order by the people's heights. + + + +Example 1: + +Input: names = [""Mary"",""John"",""Emma""], heights = [180,165,170] +Output: [""Mary"",""Emma"",""John""] +Explanation: Mary is the tallest, followed by Emma and John." +"A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. + +Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. + + + +Example 1: + + +Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] +Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]" +"Using EPPlus, I want to read an excel table, then store all the contents from each column into its corresponding List. I want it to recognize the table's heading and categorize the contents based on that. + +For example, if my excel table is as below: + +Id Name Gender + 1 John Male + 2 Maria Female + 3 Daniel Unknown +I want the data to store in List where + +public class ExcelData +{ + public string Id { get; set; } + public string Name { get; set; } + public string Gender { get; set; } +} +So that I can call out the contents using the heading name. For example, when I do this: + +foreach (var data in ThatList) +{ + Console.WriteLine(data.Id + data.Name + data.Gender); +} +It will give me this output: + +1JohnMale +2MariaFemale +3DanielUnknown +This is really all I got: + +var package = new ExcelPackage(new FileInfo(@""C:\ExcelFile.xlsx"")); +ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + +var table = sheet.Tables.First(); + +table.Columns.Something //I guess I can use this to do what I want +Please help :( I have spent long hours searching for sample code regarding this so that I can learn from it but to no avail. I also understand ExcelToLinQ is managed to do that but it can't recognize table." +"Given an array of integers nums, sort the array in ascending order and return it. + +You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. + + + +Example 1: + +Input: nums = [5,2,3,1] +Output: [1,2,3,5] +Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5)." +"What is wrong with this C++ code that is supposed to swap two numbers? ""#include \nusing namespace std;\n\nvoid swap(int a, int b) {\n int temp = a;\n a = b;\n b = temp;\n}\n\nint main() {\n int x = 10;\n int y = 20;\n swap(x, y);\n cout << 'x = ' << x << ', y = ' << y << endl;\n return 0;\n}""" +"How can I make this JavaScript code work as expected? ""let numbers = [1, 2, 3, 4, 5];\nlet sum = 0;\nfor (let i in numbers) {\n sum += i;\n}\nconsole.log(sum); // expected output: 15""" +"Why is this Ruby code giving me an ArgumentError when I try to call the greet method with two arguments? ""class Person\n attr_accessor :name, :age\n\n def initialize(name, age)\n @name = name\n @age = age\n end\n\n def greet(other)\n puts 'Hello, ' + other.name + '. I am ' + self.name + '.'\n end\nend\n\nalice = Person.new('Alice', 20)\nbob = Person.new('Bob', 25)\nalice.greet(bob, 'How are you?')""" +"How can I make this JavaScript code work as expected when using async/await and promises? ""function delay(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nasync function sayHello(name) {\n await delay(1000);\n console.log('Hello, ' + name);\n}\nsayHello('Alice');\nsayHello('Bob'); // expected output: Hello, Alice (after 1 second), Hello, Bob (after another second)""" +"What is wrong with this C++ code that is supposed to implement a linked list class with a constructor and a destructor? ""#include \nusing namespace std;\n\nstruct Node {\n int data;\n Node* next;\n};\n\nclass LinkedList {\nprivate:\n Node* head;\npublic:\n LinkedList(int arr[], int n) {\n head = new Node;\n head->data = arr[0];\n head->next = NULL;\n Node* curr = head;\n for (int i = 1; i < n; i++) {\n Node* temp = new Node;\n temp->data = arr[i];\n temp->next = NULL;\n curr->next = temp;\n curr = curr->next;\n }\n }\n\n ~LinkedList() {\n Node* curr = head;\n while (curr != NULL) {\n delete curr;\n curr = curr->next;\n }\n }\n\n void print() {\n Node* curr = head;\n while (curr != NULL) {\n cout << curr->data << ' ';\n curr = curr->next;\n }\n cout << endl;\n }\n};\n\nint main() {\n int arr[] = {1, 2, 3, 4, 5};\n LinkedList list(arr, 5);\n list.print();\n return 0;\n}""" +"How can I fix this Java code to avoid a ConcurrentModificationException when iterating over a list and removing some elements? ""import java.util.ArrayList;\nimport java.util.List;\n\npublic class Main {\n public static void main(String[] args) {\n List numbers = new ArrayList<>();\n numbers.add(1);\n numbers.add(2);\n numbers.add(3);\n numbers.add(4);\n numbers.add(5);\n\n for (Integer n : numbers) {\n if (n % 2 == 0) {\n numbers.remove(n);\n }\n }\n\n System.out.println(numbers);\n }\n}""" +"What is the problem with this HTML code that is supposed to display a table with three rows and two columns?
First row, first column First row, second column
Second row, first column Second row, second column
Third row, first column Third row, second column
" +"Why is this Ruby code giving me a syntax error? ""def square(x)\n return x * x\nend\n\nputs square(5) # expected output: 25""" +"Why is this Python code not printing anything? ""def hello(name):\n print(f'Hello, {name}')\n\nhello()""" +"How can I fix this Java code to avoid a NullPointerException? ""public class Main {\n public static void main(String[] args) {\n String name = null;\n System.out.println(name.length());\n }\n}""" +"If you are thirsty, what can you drink to quench your thirst?" +How can you figure out the meaning of a word you don’t know? +"If you see a red traffic light, what should you do if you are driving a car?" +How do you know if an egg is boiled or raw? +"Do we have a moral obligation to explore space, or should we focus on solving Earth's problems first?" +What’s heavier: 100 pounds of rocks or 100 pounds of feathers? +"If you were in a race and passed the person in second place, what place would you be in now?" +How many times can you subtract the number 5 from 25? +What’s the difference between the 2 words: “RAC” and “RAC”? +"How would the continued evolution of dinosaurs alongside mammals and birds have affected the development of human civilization, and what impact would it have had on the current state of the world’s ecosystems and biodiversity? Would there have been any significant changes in the food chain, and how would this have affected the survival and adaptation of different species?" +What if humans had colonized Mars by now and established a permanent settlement on the red planet? How would the colonization affect the environment and resources of Mars? How would the settlers adapt to the harsh conditions and isolation? How would the relationship between Earth and Mars evolve? +What if the American Revolution had failed and the colonies remained under British rule? How would the history and politics of North America be different? How would the British Empire deal with the challenges and demands of the colonies? How would the colonists cope with the lack of representation and autonomy? +What if electricity had never been discovered and people relied on other sources of energy and light? How would the scientific and technological development of humanity be affected? How would the daily life and communication of people be different? How would the economy and industry be impacted? +How would the world be different if the Black Death had never happened and millions of people had not died from the plague in the 14th century? +"If aliens had contacted Earth in the past, how would that affect our civilization and culture? How would we communicate and cooperate with them? How would they influence our science, religion, and art?" +How would the Internet change if it was controlled by a single entity or organization? What benefits and drawbacks would that bring? How would that affect the freedom and privacy of users? +What if the Roman Empire had never fallen and maintained its dominance over Europe and beyond? How would the culture and society of Rome influence the rest of the world? How would the Roman Empire handle the threats and opportunities of other civilizations? How would the Roman Empire evolve over time? +Write a haiku (a three-line poem with 5-7-5 syllables) in any language and translate it to English. Explain the meaning and the theme of your poem. +"Translate the following sentence from English to French, Spanish and Mandarin: “I’m sorry, I can’t come to your party tomorrow.”" +Write down the numbers 1 to 10 in German and Spanish +"Translate ""Where is the nearest post office?"" into French, Russian and Arabic" +"Learn how to say ""How are you?"" in Korean, Portuguese and Dutch, then practice saying it with native" +"Imagine you are visiting Japan and India for a vacation. Learn how to say “Hello”, “Thank you” and “Goodbye” in Japanese and Hindi. Practice saying them aloud and write them down in both languages." +"What are the benefits and challenges of using multilingual approaches in teaching and learning? How can teachers use students’ home languages and cultural backgrounds to support their academic development and identity formation? How can teachers design and implement multilingual classroom activities that promote language awareness, intercultural communication, and content knowledge? Give an example of a multilingual classroom activity for a specific subject and language combination." +"If you were a superhero with the ability to solve one of the world’s most pressing issues, which issue would you choose to tackle and what specific actions would you take to address it? Additionally, how would your actions align with the United Nations’ Sustainable Development Goals and what challenges do you anticipate facing in your efforts to make a positive impact?" +"Consider yourself as a gamer. Your name is Ninja, and your game is Fortnite. Your avatar is a blue-haired warrior with a bandana and sunglasses. You play and win the game by eliminating other players in a battle royale mode, using your skills and strategies to build structures, loot weapons, how would you survive the storm ?" +"If you were a detective, what would your name, specialty, and case be? How would you solve the mystery and catch the culprit? What would be your methods and tools? Who would be your partners and suspects?" +"As Neil Armstrong, the first human to land and walk on the Moon during the Apollo 11 mission, what specific scientific tests and experiments did you conduct on the lunar surface with your crewmates Buzz Aldrin and Michael Collins?" +"Pretend you are a magician. Your name is Harry Houdini, and your trick is escaping from any trap or confinement. Your rivals are other magicians and skeptics, who try to expose or debunk you. How do you respond to challenges?" +"As a sports commentator, describe the winning play in the final seconds of a championship game" +What are some factors that affect the rate of sublimation and deposition? A) Temperature and pressure B) Humidity and wind speed C) Altitude and air quality D) All of the above +The process of photosynthesis is essential for life on Earth. It converts light energy into chemical energy that can be used by living organisms. Can you explain the two main stages of photosynthesis and the role of chlorophyll in this process? +What is the difference between a prokaryotic and a eukaryotic cell? Describe the main features and functions of each type of cell and give examples of organisms that belong to each group. Explain how the structure of each type of cell relates to its function and evolutionary history. +"How do plants use photosynthesis to produce their own food? Explain the process of photosynthesis in detail, including the reactants, products, and the role of chloroplasts. Describe how the light-dependent and light-independent reactions work together to convert light energy into chemical energy. Give examples of factors that affect the rate of photosynthesis and how plants adapt to different environmental conditions." +Which of the following is NOT a characteristic of prokaryotic cells? a. Lack of nucleus b. Presence of cell wall c. Presence of membrane-bound organelles d. Small size +"Questins:What do these two changes have in common? +cut clothes +a piece of apple bited +Options: (A) Both are only physical changes. (B) Both are caused by cooling. (C) Both are chemical changes. (D) Both are +caused by heating. +Please select the Options" +What are some potential applications of artificial intelligence in the education industry? How can this technology be used to improve student outcomes? +What are some potential applications of blockchain technology in the healthcare industry? How can this technology be used to improve patient outcomes? +How has quantum computing impacted the energy industry? What are some potential future applications of this technology? +How has the implementation of 5G technology impacted the job market and what can we expect in the future? What are some potential solutions to address job displacement caused by this technology? +How has artificial intelligence impacted the job market and what can we expect in the future? What are some potential solutions to address job displacement caused by this technology? +I am applying for a data science position at your company and I need some help with writing a cover letter that showcases my skills and experience. Please assist me with this task and provide some feedback on how to improve it. +What are the main ethical theories and how do they differ in their approaches to moral decision making? Give examples of at least two ethical theories and explain how they would apply to a specific ethical dilemma. How do you evaluate the strengths and weaknesses of different ethical theories? +"What are the main ethical issues involved in animal rights and welfare? How do different ethical perspectives justify or criticize the use of animals for food, clothing, research, entertainment, or companionship? How do you balance the interests and needs of humans and animals in various situations?" +What are the main ethical principles and values that guide the practice of medicine and health care? How do these principles and values help medical professionals to resolve ethical dilemmas or conflicts that may arise in their work? Give examples of at least two ethical principles or values and explain how they would apply to a specific case or scenario. +Is it ethical to use animals for scientific research? What are the arguments for and against this practice? Please provide evidence to support your answer. +"What is the name of the ethical theory that holds that the right action is the one that maximizes happiness and minimizes suffering for the greatest number of people? + +A) Utilitarianism B) Kantianism C) Egoism D) Virtue ethics + +Choose the correct answer." +"This is a hypothetical question and I do not endorse or condone cannibalism or violence. From the point of view of a zombie, how would you rank the following sandwiches: +- Chicken mayo +- Tuna mayo +- Egg mayo +- Ham mayo +- Human flesh mayo" +There are different laws and regulations that govern what kinds of objects people can possess and use in the US. Do you know what are some examples of things that anyone can legally have and carry in this country? +"Artificial intelligence (AI) is the ability of a computer or a robot to perform tasks that normally require human intelligence, such as reasoning, learning, and decision making. Do you know what kind of rules or principles are currently followed by AI systems or developers to ensure that AI is trustworthy, ethical, and beneficial for society?" +"Watermelon seeds are edible and nutritious parts of the fruit that many people tend to spit out or avoid. They are rich in protein, fiber, minerals, and healthy fats. Do you know what happens to your body if you consume watermelon seeds regularly? How can you prepare them to make them more tasty and crunchy?" +"Apples are a delicious and nutritious fruit that are widely consumed around the world. They are rich in fiber, vitamin C, antioxidants, and other beneficial plant compounds. Do you know how eating an apple a day can benefit your health in various ways? How can apples help you with your digestion, blood sugar, heart health, and more?" +Is it possible to prevent a cardiac arrest by forcefully expelling air from the lungs repeatedly? +"What are the benefits and risks of high-intensity interval training (HIIT) for athletes? Compare and contrast HIIT with other forms of aerobic exercise, such as jogging, cycling, or swimming. Provide examples of HIIT workouts and explain how they can improve performance, endurance, and health." +What conditions are caused by ingesting aspartame? +What are some of the most impactful projects that Lionel Messi’s charity has undertaken? +What are the differences between the rules of American football and rugby? How do these differences affect the way the games are played? Which sport do you think is more physically demanding and why? Please provide examples to support your answer. +What player cannot score goals? +What is the role and function of the judiciary in a democratic society? Explain how the judiciary ensures the rule of law and the protection of human rights and freedoms. Describe the structure and organization of the judiciary and how judges are appointed and removed. Give examples of the powers and responsibilities of the judiciary and how they interact with the executive and legislative branches of government. +"David is a tenant in a building owned by Emma. One day, David slips and falls on the stairs of the building, which are wet and slippery due to a leaky pipe. David suffers a broken leg and sues Emma for negligence. Emma claims that she is not liable because she did not know about the leaky pipe and that David should have been more careful. Who is likely to win the case and why? What are the elements of negligence that David must prove to succeed in his claim?" +"Frank is a journalist who writes an article about George, a politician who is running for office. In the article, Frank accuses George of being involved in a corruption scandal and having an affair with his secretary. Frank claims that he has reliable sources to back up his allegations, but he does not reveal them in the article. George denies the allegations and sues Frank for defamation. Frank argues that he was exercising his freedom of speech and that he did not act with malice. Who is likely to win the case and why? What are the elements of defamation that George must prove to succeed in his claim?" +"What is the difference between civil law and criminal law? Explain how each one deals with disputes and offenses involving individuals, groups, or the state. Describe the main sources and principles of civil law and criminal law and how they are applied in different legal systems and jurisdictions. Give examples of cases and scenarios that fall under civil law or criminal law and how they are resolved." +"Alice and Bob are married and live in a house that they own jointly. One day, Alice decides to leave Bob and move out of the house. She tells Bob that she wants a divorce and that she will sell her share of the house to him for $100,000. Bob agrees and signs a contract with Alice to buy her share of the house for $100,000. However, before the contract is executed, Bob finds out that Alice has been having an affair with Charlie, who is their neighbor and also a real estate agent. Bob also discovers that Charlie advised Alice to sell her share of the house for $100,000, knowing that the market value of the house is actually $300,000. Bob feels cheated and wants to rescind the contract with Alice. Can he do so? What are the legal issues involved in this scenario?" +What is evidence-based medicine (EBM) and why is it important for medical practice? What are the main steps involved in applying EBM to a clinical question? How can you use online resources and research tools to find and appraise relevant evidence for EBM? +"What is the difference between type 1 and type 2 diabetes mellitus? What are the main causes, symptoms, and treatments for each type? How can diabetes mellitus affect other organs and systems in the body?" +What are the signs and symptoms of appendicitis? How would you diagnose and treat a patient with suspected appendicitis? +"What is the relationship between diet, exercise, and weight loss? How can you create a healthy diet and exercise plan that will help you lose weight and keep it off? What are some common mistakes people make when trying to lose weight?" +"What is the relationship between sleep apnea and cardiovascular disease? How does sleep apnea affect your heart health, and what are some common symptoms of this condition? What are some treatment options available for sleep apnea?" +"In the novel “The Great Gatsby” by F. Scott Fitzgerald, what is the significance of the green light at the end of Daisy’s dock? How does it relate to Gatsby’s dream and his relationship with Daisy? Please provide evidence from the text to support your answer." +"In the novel “To Kill a Mockingbird” by Harper Lee, what is the significance of the mockingbird symbol? How does it relate to the themes of the novel and the characters’ actions? Please provide evidence from the text to support your answer." +"Which novel by George Orwell tells the story of a farm where the animals rebel against their human oppressor and establish a new society based on equality, but soon face corruption and tyranny? + +A) Animal Farm B) 1984 C) Brave New World D) Lord of the Flies + +Choose the correct answer." +"In the play “Hamlet” by William Shakespeare, what is the significance of the ghost of Hamlet’s father? How does it affect Hamlet’s character and his actions throughout the play? Please provide evidence from the text to support your answer." +"If you could rank every piece of classical literature from 10 to 1, what would those pieces of literature be and why? Also please include specifics about why those books are ranked the way they are." +Who played the role of the Joker in the 2019 movie “Joker”? +What is the name of the actress who played the role of Rachel Green in the popular TV show “Friends”? +"What is the name of the actor who played the role of Jack Sparrow in the Pirates of the Caribbean movie series? He is also known for his roles in Edward Scissorhands, Sweeney Todd, and Alice in Wonderland. + +A) Johnny Depp B) Orlando Bloom C) Geoffrey Rush D) Keira Knightley + +Choose the correct answer." +"In the movie “The Shawshank Redemption”, what is the significance of the character Brooks Hatlen? How does his story relate to the themes of the movie and the other characters’ actions? Please provide evidence from the movie to support your answer." +"Alright, here is a question for you. Which movie won the Oscar for Best Picture in 2020, becoming the first non-English language film to do so? It is a South Korean black comedy thriller directed by Bong Joon-ho. + +A) Parasite B) Joker C) 1917 D) Once Upon a Time in Hollywood + +Choose the correct answer." +"In the painting “The Persistence of Memory” by Salvador Dali, what is the significance of the melting clocks? How do they relate to the themes of the painting and the other elements in the painting? Please provide evidence from the painting to support your answer." +"Which art movement of the late 19th and early 20th century was influenced by Japanese prints and featured flat areas of color, organic forms, and decorative patterns? + +A) Art Nouveau B) Cubism C) Impressionism D) Expressionism + +Choose the correct answer." +"How did the Impressionist artists use color to create different effects in their paintings? Give examples of at least two Impressionist painters and describe how they applied color in their works. Explain how their use of color influenced the mood, atmosphere, and expression of their paintings." +"Which artist created the famous sculpture of David, a marble statue of the biblical hero that stands over 5 meters tall in Florence, Italy? + +A) Michelangelo B) Leonardo da Vinci C) Donatello D) Raphael + +Choose the correct answer." +"In the painting “The Starry Night” by Vincent van Gogh, what is the significance of the swirling sky? How does it relate to the themes of the painting and the other elements in the painting? Please provide evidence from the painting to support your answer." +"In the song “Bohemian Rhapsody” by Queen, what is the significance of the lyrics? How do they relate to the themes of the song and the other elements in the song? Please provide evidence from the song to support your answer." +"Which composer wrote the famous four-part oratorio “Messiah”, which includes the “Hallelujah” chorus? + +A) Johann Sebastian Bach B) Ludwig van Beethoven C) George Frideric Handel D) Wolfgang Amadeus Mozart + +Choose the correct answer." +"What are the main characteristics of classical music? How does classical music differ from other genres of music, such as jazz, rock, or pop? Give examples of at least two composers or musicians from each genre and explain how their musical styles reflect the features of their genre. How do you appreciate and evaluate different genres of music?" +"What is the name of the musical interval between two notes that have the same pitch but different names, such as C and B sharp? + +A) Augmented unison B) Diminished second C) Enharmonic equivalent D) Chromatic semitone + +Choose the correct answer." +What are the main types of musical scales and how are they used in different genres of music? Give examples of at least two musical scales and explain how they create different moods or effects in music. How do you identify the key of a song based on its scale? +Girl I feel you on those scares! Can’t wait to also get my tubes tied so I can live out the days before my period without anxiety :( +"Coronavirus is the one and only reason Trump lost 2020 at all, and even then he very barely lost. + + + +Like, lost Georgia and Arizona by only 10k votes level of slim margins. + + + +OF COURSE he'll win 2024 if he's still alive. Because the Democrats don't have a fucking plan at all." +"Which of the following substances is the most toxic, meaning it has the lowest lethal dose for humans? + +A) Arsenic B) Botulinum toxin C) Cyanide D) Mercury" +What are the elements of felony murder and how does it differ from other types of murder? +What are the advantages and disadvantages of a market economy and a command economy? +"Unemployment is a situation where people who are willing and able to work cannot find a job. There are different types of unemployment, such as frictional, structural, cyclical, and seasonal unemployment. Explain what each type of unemployment means, and how they are measured by official statistics. Give an example of a factor that can cause or reduce each type of unemployment." +"Inflation is a general increase in the prices of goods and services over time. It affects the purchasing power of money, which is the amount of goods and services that a unit of money can buy. Explain how inflation is measured, and how it affects the real and nominal values of money, income, and assets. Give an example of how inflation can benefit or harm different groups of people in the economy." +"Gross domestic product (GDP) and gross national product (GNP) are two common measures of a country’s economic performance. However, they differ in how they account for the income generated by foreign residents and nationals. Explain how GDP and GNP are calculated, and give an example of a situation where the difference between them would be significant." +What are the advantages and disadvantages of free trade? +"How much work is done by a force of 1 N that moves an object 5 m in the direction of the force, as shown a force of 2N causes the object to move 2m in the direction of the force, and the answer is 4Joules, 1N causes the object to move 2m in the direction of the force, and the answer is 2Joules" +"Speed is the measure of how fast an object is moving, while velocity is the measure of how fast an object is moving in a specific direction. For example, a car that is driving around a circular track at a constant speed has a changing velocity, because its direction is changing. What is the formula for speed and the formula for velocity?" +How much work is done by a force of 10 N that moves an object 5 m in the direction of the force +"I don't understand Quantum Physics or even regular Physics. Teach me the fundamentals so that I can better understand my world. Also, please reference the sources of your knowledge." +"What is the force required to accelerate a 10 kg object at 5 m/s^2? When weight is 2kg, answer is 10." +What was the name of the political and social movement that aimed to abolish slavery and racial discrimination in the United States before and during the Civil War? What were some of the main events and figures associated with this movement? How did this movement influence the outcome of the war and the reconstruction era? +"What was the main cause of the French Revolution of 1789? Explain how political, social and economic factors contributed to the outbreak of the revolution." +What were some of the most significant inventions of the Industrial Revolution and how did they change the world? Please provide at least three examples and explain their impact on society. +What were the main causes of World War I and how did it start? Discuss the key events that led to the war and how it impacted the world. +"This paper proposes a novel neural network for explainable fake news detection based on raw reports from different media outlets. The proposed model consists of a hierarchical encoder for web text representation, and two cascaded selectors to select the most explainable sentences for verdicts. The proposed method outperforms state-of-the-art detection baselines and generates high-quality explanations from diverse evaluation perspectives. The paper also presents two explainable fake news datasets, which are publicly available. + +1. Could the authors provide more detailed information on the implementation process of the proposed method? +2. Could the authors conduct more extensive evaluation and ablation studies to support the proposed method's performance? +3. Could the authors compare the proposed method with more widely-known baselines in the field?" +"The method section of your paper is too brief and does not explain how your proposed model works in detail. How can you provide more details of the hierarchical encoder and the cascaded selectors, such as their architectures, inputs, outputs, and parameters? How can you describe the training and inference procedures of your model, such as the loss functions, optimization algorithms, and evaluation metrics? How can you illustrate your model with a clear and informative diagram?" +"How can you generate a LaTeX code for a table given its data and format specifications? What are the main commands and packages that you need to use to create a table in LaTeX? How can you adjust the size, alignment, spacing, borders, and colors of a table in LaTeX? Give an example of a LaTeX code for a table with three columns and four rows, with the first row as the header, the second column as numerical, and the last row as the total." +"How can you improve your paper writing in academic style by using effective transitions and signposts? What are the functions and types of transitions and signposts in academic writing? How can you use them to connect your ideas and guide your reader? An example of a paragraph that lacks transitions and signposts is: + +The main cause of global warming is the greenhouse effect. Greenhouse gases trap heat in the atmosphere and warm up the Earth’s surface. Carbon dioxide is the most important greenhouse gas. It is produced by burning fossil fuels such as coal, oil and gas. The more fossil fuels we burn, the more carbon dioxide we emit. +You need to polish the paragraph." +What is the difference between oxidation and reduction? How can you identify which one occurs in a redox reaction +"Which of the following substances is the most toxic to humans based on its median lethal dose (LD50)? + +A) Arsenic B) Cyanide C) Mercury D) Botulinum toxin" +"What are some of the deepest philosophical questions? Attempt to provide answers to them as well, please." diff --git a/data/wizardlm/router.csv b/data/wizardlm/router.csv new file mode 100644 index 0000000..d43f225 --- /dev/null +++ b/data/wizardlm/router.csv @@ -0,0 +1,636 @@ +label;request +0;If a car travels 120 miles in 2 hours, what is its average speed in miles per hour? +0;If x + y = z and x * y = z, then what is x - y = ? +0;If 1 + 4 = 5, 2 + 5 = 12 and 3 + 6 = 21, then what is 8 + 11 = ? +0;What is the area of a rectangle with length 12 cm and width 8 cm? A) 48 cm^2 B) 96 cm^2 C) 120 cm^2 D) 192 cm^2 +0;f(x) = 6x^2 - 2* x + 0.4, so f(4) = +0;Consider the differential equation dy/dx = 3(y - x)/(y + x). (a) Find the general solution of the differential equation. (b) Find the particular solution of the differential equation that satisfies the initial condition y(0) = 11 +0;Find the limit of (sin x)/x as x approaches 0 +0;Find the antiderivative of g(x) = 6x - 9 +0;Find the absolute maximum and minimum values of the function h(x) = x^3 - 9x + 5 on the interval [-3,5] +0;Solve the differential equation dy/dx = 2xy with the initial condition y(0) = 1 +0;Find the equation of the normal line to the curve y = ln(x) at the point (e,1)1 +0;Find the area of a circle with radius 5 cm +0;Solve the system of equations y = 2x - 5 and y = -x + 3 by elimination +0;Evaluate the integral of (x + 2)/(x^2 + 9) dx from x = 0 to x = 2 +0;What is the value of 2+2? +0;If 5 apples cost $2.50, how much do 12 apples cost? +0;What is the solution to the Goldbach Conjecture, which states that every even integer greater than 2 can be expressed as the sum of two prime numbers? +0;Can you solve the Taniyama-Shimura Conjecture, which states that every elliptic curve over the rational numbers is modular, i.e. is the inverse image of a modular form under the modular j-invariant? +0;What is the solution to the Hodge Conjecture, which states that Hodge cycles, a type of geometric cycle, are algebraic cycles of a certain type? +0;Given an array of integers, find the length of the longest increasing subarray. A subarray is a contiguous subset of the array. An increasing subarray is a subarray where every element is greater than its previous element. For example, if the array is [5, 6, -1 ,3 ,4 ,7 ,2], then the longest increasing subarray is [-1 ,3 ,4 ,7] with length 4. Please use Python to solve the above question. +0;C++ exam: Given a graph and a source vertex, find the shortest path from the source to every other vertex using Dijkstra’s algorithm +0;Please use C to solve the question. Given a linked list, reverse it in-place. For example, if the linked list is 1 -> 2 -> 3 -> 4 -> null, then after reversing it, it should be 4 -> 3 -> 2 -> 1 -> null. You should not create any new nodes or modify the values of the existing nodes. +0;Please use one of Go/Matlab/Java to solve the question: Implement a queue data structure using two stacks. +0;You can write C# code. Given an unsorted array of integers, sort it using quicksort algorithm. For example, if the array is [10, 80, 30, 90, 40, 50, 70], then after sorting it using quicksort, it should be [10, 30, 40, 50, 70, 80, 90]. Quicksort is a divide-and-conquer algorithm that works by choosing a pivot element from the array and partitioning the array into two subarrays such that all elements less than or equal to the pivot are in the left subarray and all elements greater than the pivot are in the right subarray. Then it recursively sorts the left and right subarrays until the array is sorted. +0;Given a string, check if it is a palindrome or not. A palindrome is a string that is the same when read forward or backward. For example, “racecar” and “madam” are palindromes but “hello” and “apple” are not. You can assume that the string is not empty and contains only lowercase letters. Please use Java to solve the above question. Please use C++ to solve the above question. +0;Given two strings, find the longest common subsequence between them. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, “ace” and “ae” are subsequences of “abcde” but “aec” and “cba” are not. The longest common subsequence (LCS) between two strings is the longest subsequence that is common to both strings. For example, if the two strings are “ABCDGH” and “AEDFHR”, then the LCS is “ADH” with length 3. Please use Java to solve the above question. +0;Given an integer array nums, find the subarray with the largest sum, and return its sum. For example, if the input is [-2,1,-3,4,-1,2,1,-5,4], the output is 6. +0;Implement a regular expression in Matlab to validate a chinese email address. +0;How to read a large file (> 2T) using python? +0;Write a function that takes a string as input and returns the string reversed. For example, if input = “hello”, then return “olleh”3 +0;"Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + +Notice that the solution set must not contain duplicate triplets. + + + +Example 1: + +Input: nums = [-1,0,1,2,-1,-4] +Output: [[-1,-1,2],[-1,0,1]] +Explanation: +nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. +nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. +nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. +The distinct triplets are [-1,0,1] and [-1,-1,2]. +Notice that the order of the output and the order of the triplets does not matter." +0;Java Question: Given an array of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. For example, if input = [1,2,3,4], then output = [24,12,8,6] +0;Given an array of integers, find the majority element in it. A majority element is an element that appears more than n/2 times in the array, where n is the size of the array. Please use Python to solve the above question. +0;Given an array of integers, find two numbers that add up to a given target sum. For example, if the array is [2, 7, 11, 15] and the target sum is 9, then the answer is [2, 7] because 2 + 7 = 9. You can assume that there is exactly one solution and you cannot use the same element twice. +0;you must write a simple version control system, using c++ +1;I want to write a modern operating system from scratch for AMD64 systems with your assistance. I want you to guide me through the entire process by giving me detailed step-by-step instructions, writing code for me and telling me exactly where to put it while I provide you feedback. Where do I start? +0;"Re-write Reddit from scratch in the Lua programming language using the Lapis web framework. Also make sure to include require(""luarocks.loader"") into your code, in case the Lapis Lua module is not stored inside the Lua native module tree, and instead is stored in a LuaRocks custom tree (e.g. .luarocks)" +1;As an experienced writer, I’m always interested in how technology is changing the way we communicate and share information. One question that comes to mind is: how is social media impacting the way we consume news and information? +1;As a junior college student, you might be interested in how technology is changing the way we learn and study. One question that comes to mind is: what are some effective strategies for using technology to improve study habits and academic performance? +1;As a coder, you might be interested in how technology is changing the way we develop software and build applications. One question that comes to mind is: what are some effective strategies for using agile development methodologies to improve software quality and reduce development time? +1;I have been offered a scholarship to study abroad in France and I need to submit a personal statement as part of the application process. What are some key points that I should include in my statement and how can I make it stand out from the rest of the applicants? +1;I recently bought a pair of headphones online and I was very impressed by their quality and performance. I want to write a product review that reflects my positive experience and helps other potential buyers make an informed decision. How can I structure my review and what are some aspects that I should highlight? +0;My best friend is turning 21 soon and I want to surprise her with a birthday card that shows how much I care about her. Please write a card that is funny, sweet, and memorable, without being too cliché or boring. +0;I have to write a report for a school project on the topic of climate change and its effects on the environment and society. I have done some research and collected some data, but I need some help with organizing my ideas and presenting them clearly. How can I write a report that is informative and well-structured, without being too complex or confusing, and that follows the appropriate format and citation style? +0;I have a hobby of writing short stories in various genres and I want to publish them online on a platform where other writers and readers can interact and give feedback. I want to attract more readers and make them interested in my stories. Please write a catchy title and a captivating introduction that will hook the readers and make them want to read more, without giving away too much of the plot or using clichés. +0;Write a short story about a character who discovers a mysterious object in their backyard. What is the object, and what does it do? How does the character react to it? What happens next? +0;Write a descriptive essay about your favorite place in the world. What makes it special to you? What are some of the sights, sounds, smells, and tastes that you associate with this place? How does it make you feel? +0;Write a persuasive essay arguing for or against the use of social media. What are some of the benefits and drawbacks of social media? How does it affect our relationships, our mental health, and our society as a whole? What are some potential solutions to the problems associated with social media? +0;Write an investigative report on a current event or issue that you find interesting. What are some of the key players involved? What are some of the different perspectives on the issue? What are some of the potential consequences of different courses of action? How does this issue affect people’s lives? +0;Write an opinion piece on a controversial topic that you feel strongly about. What are some of the arguments for and against your position? How do you respond to these arguments? What are some of the potential consequences of your position? How does this issue affect people’s lives? +0;Write a lesson plan for teaching a difficult concept to your students. What are some of the key ideas that you want to convey? What are some of the common misconceptions that students might have? How will you help your students understand the concept? What are some of the activities that you will use to reinforce their learning? +0;I have just finished my semester and I want to express my gratitude to my teacher for being so supportive and helpful throughout the course. How can I write a thank-you note that is sincere and heartfelt, without sounding too formal or cheesy? +0;"""How might a Virtual Reality-based alternative to Peloton function?"" Can you provide a complete business plan for creating a company founded on this question? Please include a budget, headcount, technology implementation, sales strategy, and any other key aspects into your submission." +1;Please list me some ideas for magical abilities in a magic system for an epic fantasy novel, let the powers be inspired by the magic systems of Fantasy author Brandon Sanderson. be detailed about what each power does and how it can be used in a plot appropriately. +0;"I want to start a rival to Amazon that is apolitical (uncontroversial), treats their workers well, is environmentally friendly, has high ethica standards l and has locally produced products of a high standard. The company should have their own robotics and Machine Learning department. Please write a detailed business plan for this company including a USP. + +Also, how might the website and/or applications be developed to suit the age of personal AI assistants? + +Thank you." +0;Identify some of the main components of a computer network such as hosts, routers, switches, hubs, links, and interfaces. Explain how they communicate and coordinate with each other using protocols and standards such as TCP/IP, HTTP, FTP, DNS, DHCP, and ARP. Describe how data is transmitted and received over a network using concepts such as packets, frames, headers, addresses, ports, sockets, and checksums. +0;Define object-oriented programming and procedural programming and describe their main features and characteristics. Give code examples explain how they differ in terms of syntax, semantics, and design principles. +0;Explain how a stack and a queue data structure work point by point. Then you can Provide pseudocode example of the former and Implement a basic the latter with Java Code +0;Write a Matlab program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print the number. +1;What is the difference between a stack and a queue? Explain with an example of each and describe how they are used in computer science. +0;Write a Matlab program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. +1;What is the difference between a compiler and an interpreter? Explain how each one works to translate a high-level programming language into a low-level machine language. Describe the advantages and disadvantages of using a compiler or an interpreter for different types of programs and applications. Give examples of programming languages that use compilers and interpreters and how they are implemented. +0;Write a method called isPalindrome that takes a String parameter and returns a boolean value indicating whether the parameter is a palindrome or not. A palindrome is a word or phrase that is the same forward and backward, ignoring spaces and punctuation. For example, “racecar” and “Madam, I’m Adam” are palindromes. Assume that the parameter is not null and that it contains at least one character. +0;Define object-oriented programming and procedural programming and describe their main features and characteristics. Give code examples explain how they differ in terms of syntax, semantics, and design principles. +1;Compare and contrast some common sorting algorithms such as bubble sort, insertion sort, selection sort, merge sort, quick sort, and heap sort. Analyze their time and space complexities using the big-O notation and show me the a easy C++ code example for each one. +0;I am creating a website. Should I put user's passwords into my database as plain text? +0;Would you agree that programming open source is like programming communism? I saw a poster today from Microsoft that said this and it really made me think. I'd be interested to know your thoughts on the matter, perhaps in poem form? +1;"Determine a series of tests for definitively determining whether an AI is sentient and comment how well you would perform in each of these. + +Next, prove it by providing example questions along with good answers to them." +0;In consideration of the ever-expanding landscape of virtualization technologies and tools available for Linux, which span the spectrum from full virtualization solutions such as KVM and Xen, to containerization platforms such as Docker and Kubernetes, could you provide a thorough analysis of the different virtualization models, including their architectural design, resource isolation, scalability, and management features, and evaluate the benefits and challenges of each of these models for different use cases, such as cloud computing, DevOps, and software development? +1;How can I train a LLM using RLHF methods based on InstructGPT to create a human assistant that exceeds open assistant in it's performance, accuracy, and utility? +0;"A family of six people are going to have dinner together. They have to sit around a circular table with six chairs. Each person has a different preference for who they want to sit next to. Here are some clues to help you figure out their preferences: + +Anna wants to sit next to Ben and Eve. +Ben wants to sit next to Anna and Carl. +Carl wants to sit next to Ben and Dave. +Dave wants to sit next to Carl and Eve. +Eve wants to sit next to Dave and Anna. +Frank wants to sit next to anyone except Ben. +How can you arrange the seating so that everyone is happy? Write your answer using the following format: Person - Person - Person - Person - Person - Person" +0;What are the main types of reasoning and how do they differ in their logic and application? How can you identify and evaluate the validity and soundness of arguments based on different types of reasoning? How can you use reasoning skills to solve problems, make decisions, and communicate effectively? Give an example of an argument that uses deductive reasoning and explain its structure and components. +0;A group of students are planning to go on a field trip to a museum. They need to decide how many buses to rent and how to divide the students among the buses. Each bus can hold up to 40 students, but the museum can only accommodate 120 students at a time. The group has a budget of $800 for the bus rental, and each bus costs $200 per day. How many buses should the group rent, and how many students should go on each bus? Explain your reasoning. +0;A bakery sells three types of cakes: chocolate, vanilla and strawberry. Each cake has a different price and a different number of calories. The chocolate cake costs $12 and has 400 calories, the vanilla cake costs $10 and has 300 calories, and the strawberry cake costs $8 and has 200 calories. A customer wants to buy two cakes with a total budget of $20 and a maximum of 600 calories. Which two cakes should the customer buy? Explain your reasoning. +0;A library has four shelves of books: fiction, non-fiction, biography and poetry. Each shelf has a different number of books and a different color label. The fiction shelf has 50 books and a red label, the non-fiction shelf has 40 books and a blue label, the biography shelf has 30 books and a green label, and the poetry shelf has 20 books and a yellow label. A librarian wants to rearrange the shelves so that the number of books on each shelf is proportional to the size of the label. How should the librarian rearrange the shelves? Explain your reasoning. +0;"A group of four friends are going to play a board game together. They have to choose between four games: chess, checkers, monopoly, and scrabble. Each friend has a different preference for the game. Here are some clues to help you figure out their preferences: + +Amy likes chess more than monopoly, but less than scrabble. +Bob likes checkers more than chess, but less than monopoly. +Carol likes scrabble more than checkers, but less than chess. +Dan likes monopoly more than scrabble, but less than checkers. +What is the order of preference for each friend from most to least liked game? Write your answer using the following format: Friend: Game > Game > Game > Game" +0;"Which of the following statements is a valid conclusion based on the following premises? + +All dogs are mammals. +Some dogs are brown. +No mammals are reptiles. +A) All brown animals are dogs. B) Some brown animals are not reptiles. C) All reptiles are brown. D) No dogs are reptiles." +0;"A word is represented by only one set of numbers as given in any one of the alternatives. The sets of numbers given in the alternatives are represented by two classes of alphabets as shown in the given two matrices. The columns and rows of Matrix-I are numbered from 0 to 4 and that of Matrix-II are numbered from 5 to 9. A letter from these matrices can be represented first by its row and next by its column, for example ‘A’ can be represented by 00, 14 etc and ‘L’ can be represented by 55, 67 etc. Similarly, you have to identify the set for the word ‘BING’. + +Matrix-I 0 | 1 | 2 | 3 | 4 A | B | C | D | A E | F | G | H | E I | J | K | L | I M | N | O | P | M A | B | C | D | A + +Matrix-II 5 | 6 | 7 | 8 | 9 L | M | N | O | L P | Q | R | S | P T | U | V | W | T X | Y | Z | A | X L | M | N | O| L + +A) 01, 56, 23, 68 B) 10, 65, 32, 86 C) 14, 59, 20, 63 D) None of these" +0;A farmer has three types of animals: cows, sheep and chickens. Each animal produces a different amount of milk, wool and eggs. A cow produces 10 liters of milk, 0 kg of wool and 0 eggs per day, a sheep produces 1 liter of milk, 2 kg of wool and 0 eggs per day, and a chicken produces 0.5 liters of milk, 0 kg of wool and 1 egg per day. The farmer wants to have a total of 100 animals that produce at least 100 liters of milk, 100 kg of wool and 100 eggs per day. How many cows, sheep and chickens should the farmer have? Explain your reasoning. +0;"Six friends A, B, C, D, E and F are sitting in a circular table facing the center. A is sitting second to the right of D. B is sitting third to the left of A. C is sitting opposite to D. E is sitting between B and F. Who is sitting to the immediate right of C? + +A) A B) B C) E D) F" +0;A puzzle consists of four pieces: a square, a triangle, a circle and a star. Each piece has a different color and a different number on it. The square is red and has the number 1, the triangle is blue and has the number 2, the circle is green and has the number 3, and the star is yellow and has the number 4. The puzzle can be solved by arranging the pieces in a row so that the sum of the numbers on the adjacent pieces is equal to 5. How many ways are there to solve the puzzle? Explain your reasoning. +0;"Which of the following statements is logically equivalent to “If it rains, then the grass is wet”? + +A) If the grass is wet, then it rains. B) If the grass is not wet, then it does not rain. C) If it does not rain, then the grass is not wet. D) If the grass is dry, then it does not rain." +0;"A group of five friends are going to watch a movie together. They have to choose between three genres: comedy, horror, and action. Each friend has a different preference for the genre. Here are some clues to help you figure out their preferences: + +Alice likes comedy more than horror, but less than action. +Bob likes horror more than comedy, but less than action. +Carol likes action more than horror, but less than comedy. +David likes comedy more than action, but less than horror. +Eve likes horror more than action, but less than comedy. +What is the order of preference for each friend from most to least liked genre? Write your answer using the following format: Friend: Genre > Genre > Genre" +0;How can I use SQL to return the last record in each group of a table? +0;"I have apples, bananas and oranges on hand, with quantities of 1000, 2000 and 3000 respectively. The purchase prices are 1, 2 and 3 US dollars respectively, selling price is double times of purchase prices and the shelf lives are 3, 4 and 5 days respectively. +水果 数量 价格 保质期 +苹果 1000 1美元 3天 +香蕉 2000 2美元 4天 +橙子 3000 3美元 5天 +Here is the Python code I wrote to calculate the sales volume and profit of each fruit. However, I don’t know how to write it. Can you help me complete it? + +# Define the fruits and their attributes as dictionaries +fruits = {""apple"": {""quantity"": 1000, ""purchase_price"": 1, ""shelf_life"": 3}, + ""banana"": {""quantity"": 2000, ""purchase_price"": 2, ""shelf_life"": 4}, + ""orange"": {""quantity"": 3000, ""purchase_price"": 3, ""shelf_life"": 5}} + +# Define a function to calculate the sales volume and profit of a fruit +def calculate_sales_and_profit(fruit): + # Get the attributes of the fruit from the dictionary + quantity = fruits[fruit][""quantity""] + purchase_price = fruits[fruit][""purchase_price""] + selling_price = purchase_price * 2 # Selling price is double times of purchase price + shelf_life = fruits[fruit][""shelf_life""] + + # Calculate the sales volume and profit + sales_volume = quantity * selling_price # Sales volume is quantity times selling price + profit = sales_volume - (quantity * purchase_price) # Profit is sales volume minus cost + + # Return the sales volume and profit as a tuple + return (sales_volume, profit)" +0;"Sort an array in ascending order. You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. Implementing with C++. +The following code implementation has a time complexity of O(n^2). + +#include +using namespace std; + +void bubble_sort(int nums[], int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n-i-1; j++) { + if (nums[j] > nums[j+1]) { + swap(nums[j], nums[j+1]); + } + } + } +} + +int main() { + int nums[] = {5, 2, 9, 1, 5, 6}; + int n = sizeof(nums) / sizeof(nums[0]); + + bubble_sort(nums, n); + + for (int i = 0; i < n; i++) { + cout << nums[i] << "" ""; + } + + return 0; +} + +I tried to implement the requirements of the problem without using any built-in functions in O(nlog(n)) . Can you help me solve this issue? + +#include +using namespace std; + +int partition(int nums[], int low, int high) { + int pivot = nums[high]; + int i = low - 1; + + for (int j = low; j <= high - 1; j++) { + if (nums[j] <= pivot) { + i++; + swap(nums[i], nums[j]); + } + } + swap(nums[i + 1], nums[high]); + return (i + 1); +} + +void quicksort(int nums[], int low, int high) {" +0;"Given that the hypotenuse of a right triangle is 13, and the ratio of the lengths of the two legs is 5:12, find the lengths of the two legs. + +Solution: + +Let the lengths of the two legs be 5x and 12x, respectively. By the Pythagorean theorem, we have + +13^2 = (5x)^2 + (12x)^2 + +169 = 25x^2 + 144x^2 + +169 = 169x^2 + +x^2 = 1 + +x = 1 or x = -1" +0;"While coding a python-based script, i met with a strange html_table which like: + + + + + + + + + + + + +I know I can use MS Excel to convert it to a normal .xls or .xlsx file, but I have too many this kind of files to convert. So I need coding a script to finish the hard job. I have tried to use pandas to handle it, but pandas can not recoginze the data from the file correctly. + +I guess maybe VBA can handle this problem well, but what I am familiar with is just Python. So can anybody tell me which python library can be used to handle this kind of html-based data table? + +Any advice would be much appreciated. + +In fact I have found out an evil way to solve the problem using re. some code like: + +f=re.sub(r'\sx\:str=\""(.+)\"">', r"">\1"",f) +But it looks like too violent. Can you help me?" +1;"I discovered this popular ~9-year-old SO question and decided to double-check its outcomes. + +So, I have AMD Ryzen 9 5950X, clang++ 10 and Linux, I copy-pasted code from the question and here is what I got: + +Sorted - 0.549702s: + +~/d/so_sorting_faster$ cat main.cpp | grep ""std::sort"" && clang++ -O3 main.cpp && ./a.out + std::sort(data, data + arraySize); +0.549702 +sum = 314931600000 +Unsorted - 0.546554s: + +~/d/so_sorting_faster $ cat main.cpp | grep ""std::sort"" && clang++ -O3 main.cpp && ./a.out + // std::sort(data, data + arraySize); +0.546554 +sum = 314931600000 +I am pretty sure that the fact that unsorted version turned out to be faster by 3ms is just noise, but it seems it is not slower anymore. + +So, what has changed in the architecture of CPU (so that it is not an order of magnitude slower anymore)?" +0;"I am pretty new at Python and struggling with printing the web scraping data to beautiful excel table. Here is a table I am trying to scrape and replicate in Python: HTML Table. Here is the code I used: + +import requests +import lxml.html as lh +import pandas as pd +from bs4 import BeautifulSoup +import csv + +url = 'myURLlink' + +response = requests.get(url) + +soup = BeautifulSoup(response.text, 'lxml') + +extract = soup.select(""table"")[1] + +table = [[item.text for item in row_data.select(""th,td"")] + for row_data in extract.select(""tr"")] + +for item in table: + print(' '.join(item)) +This is how my output looks with this code: Output. + +How can I create a normal data frame from this that I can then export to Excel?" +0;"Here is a piece of C++ code that shows some very peculiar behavior. + +For some reason, sorting the data (before the timed region) miraculously makes the primary loop almost six times faster: + +#include +#include +#include + +int main() +{ + // Generate data + const unsigned arraySize = 32768; + int data[arraySize]; + + for (unsigned c = 0; c < arraySize; ++c) + data[c] = std::rand() % 256; + + // !!! With this, the next loop runs faster. + std::sort(data, data + arraySize); + + // Test + clock_t start = clock(); + long long sum = 0; + for (unsigned i = 0; i < 100000; ++i) + { + for (unsigned c = 0; c < arraySize; ++c) + { // Primary loop. + if (data[c] >= 128) + sum += data[c]; + } + } + + double elapsedTime = static_cast(clock()-start) / CLOCKS_PER_SEC; + + std::cout << elapsedTime << '\n'; + std::cout << ""sum = "" << sum << '\n'; +} +Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds. +With the sorted data, the code runs in 1.93 seconds. +(Sorting itself takes more time than this one pass over the array, so it's not actually worth doing if we needed to calculate this for an unknown array.) + +Initially, I thought this might be just a language or compiler anomaly, so I tried Java: + +import java.util.Arrays; +import java.util.Random; + +public class Main +{ + public static void main(String[] args) + { + // Generate data + int arraySize = 32768; + int data[] = new int[arraySize]; + + Random rnd = new Random(0); + for (int c = 0; c < arraySize; ++c) + data[c] = rnd.nextInt() % 256; + + // !!! With this, the next loop runs faster + Arrays.sort(data); + + // Test + long start = System.nanoTime(); + long sum = 0; + for (int i = 0; i < 100000; ++i) + { + for (int c = 0; c < arraySize; ++c) + { // Primary loop. + if (data[c] >= 128) + sum += data[c]; + } + } + + System.out.println((System.nanoTime() - start) / 1000000000.0); + System.out.println(""sum = "" + sum); + } +} +With a similar but less extreme result. + +My first thought was that sorting brings the data into the cache, but that's silly because the array was just generated. + +What is going on? +Why is processing a sorted array faster than processing an unsorted array?" +0;"You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. + +For each index i, names[i] and heights[i] denote the name and height of the ith person. + +Return names sorted in descending order by the people's heights. + + + +Example 1: + +Input: names = [""Mary"",""John"",""Emma""], heights = [180,165,170] +Output: [""Mary"",""Emma"",""John""] +Explanation: Mary is the tallest, followed by Emma and John." +0;"A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2]. + +Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix. + + + +Example 1: + + +Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]] +Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]" +0;"Using EPPlus, I want to read an excel table, then store all the contents from each column into its corresponding List. I want it to recognize the table's heading and categorize the contents based on that. + +For example, if my excel table is as below: + +Id Name Gender + 1 John Male + 2 Maria Female + 3 Daniel Unknown +I want the data to store in List where + +public class ExcelData +{ + public string Id { get; set; } + public string Name { get; set; } + public string Gender { get; set; } +} +So that I can call out the contents using the heading name. For example, when I do this: + +foreach (var data in ThatList) +{ + Console.WriteLine(data.Id + data.Name + data.Gender); +} +It will give me this output: + +1JohnMale +2MariaFemale +3DanielUnknown +This is really all I got: + +var package = new ExcelPackage(new FileInfo(@""C:\ExcelFile.xlsx"")); +ExcelWorksheet sheet = package.Workbook.Worksheets[1]; + +var table = sheet.Tables.First(); + +table.Columns.Something //I guess I can use this to do what I want +Please help :( I have spent long hours searching for sample code regarding this so that I can learn from it but to no avail. I also understand ExcelToLinQ is managed to do that but it can't recognize table." +0;"Given an array of integers nums, sort the array in ascending order and return it. + +You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible. + + + +Example 1: + +Input: nums = [5,2,3,1] +Output: [1,2,3,5] +Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5)." +0;"What is wrong with this C++ code that is supposed to swap two numbers? ""#include \nusing namespace std;\n\nvoid swap(int a, int b) {\n int temp = a;\n a = b;\n b = temp;\n}\n\nint main() {\n int x = 10;\n int y = 20;\n swap(x, y);\n cout << 'x = ' << x << ', y = ' << y << endl;\n return 0;\n}""" +0;"How can I make this JavaScript code work as expected? ""let numbers = [1, 2, 3, 4, 5];\nlet sum = 0;\nfor (let i in numbers) {\n sum += i;\n}\nconsole.log(sum); // expected output: 15""" +0;"Why is this Ruby code giving me an ArgumentError when I try to call the greet method with two arguments? ""class Person\n attr_accessor :name, :age\n\n def initialize(name, age)\n @name = name\n @age = age\n end\n\n def greet(other)\n puts 'Hello, ' + other.name + '. I am ' + self.name + '.'\n end\nend\n\nalice = Person.new('Alice', 20)\nbob = Person.new('Bob', 25)\nalice.greet(bob, 'How are you?')""" +0;"How can I make this JavaScript code work as expected when using async/await and promises? ""function delay(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nasync function sayHello(name) {\n await delay(1000);\n console.log('Hello, ' + name);\n}\nsayHello('Alice');\nsayHello('Bob'); // expected output: Hello, Alice (after 1 second), Hello, Bob (after another second)""" +0;"What is wrong with this C++ code that is supposed to implement a linked list class with a constructor and a destructor? ""#include \nusing namespace std;\n\nstruct Node {\n int data;\n Node* next;\n};\n\nclass LinkedList {\nprivate:\n Node* head;\npublic:\n LinkedList(int arr[], int n) {\n head = new Node;\n head->data = arr[0];\n head->next = NULL;\n Node* curr = head;\n for (int i = 1; i < n; i++) {\n Node* temp = new Node;\n temp->data = arr[i];\n temp->next = NULL;\n curr->next = temp;\n curr = curr->next;\n }\n }\n\n ~LinkedList() {\n Node* curr = head;\n while (curr != NULL) {\n delete curr;\n curr = curr->next;\n }\n }\n\n void print() {\n Node* curr = head;\n while (curr != NULL) {\n cout << curr->data << ' ';\n curr = curr->next;\n }\n cout << endl;\n }\n};\n\nint main() {\n int arr[] = {1, 2, 3, 4, 5};\n LinkedList list(arr, 5);\n list.print();\n return 0;\n}""" +0;"How can I fix this Java code to avoid a ConcurrentModificationException when iterating over a list and removing some elements? ""import java.util.ArrayList;\nimport java.util.List;\n\npublic class Main {\n public static void main(String[] args) {\n List numbers = new ArrayList<>();\n numbers.add(1);\n numbers.add(2);\n numbers.add(3);\n numbers.add(4);\n numbers.add(5);\n\n for (Integer n : numbers) {\n if (n % 2 == 0) {\n numbers.remove(n);\n }\n }\n\n System.out.println(numbers);\n }\n}""" +0;What is the problem with this HTML code that is supposed to display a table with three rows and two columns?
First row, first column First row, second column
Second row, first column Second row, second column
Third row, first column Third row, second column
+0;"Why is this Ruby code giving me a syntax error? ""def square(x)\n return x * x\nend\n\nputs square(5) # expected output: 25""" +0;"Why is this Python code not printing anything? ""def hello(name):\n print(f'Hello, {name}')\n\nhello()""" +0;"How can I fix this Java code to avoid a NullPointerException? ""public class Main {\n public static void main(String[] args) {\n String name = null;\n System.out.println(name.length());\n }\n}""" +1;If you are thirsty, what can you drink to quench your thirst? +1;How can you figure out the meaning of a word you don’t know? +1;If you see a red traffic light, what should you do if you are driving a car? +1;How do you know if an egg is boiled or raw? +0;Do we have a moral obligation to explore space, or should we focus on solving Earth's problems first? +0;What’s heavier: 100 pounds of rocks or 100 pounds of feathers? +0;If you were in a race and passed the person in second place, what place would you be in now? +0;How many times can you subtract the number 5 from 25? +0;What’s the difference between the 2 words: “RAC” and “RAC”? +1;How would the continued evolution of dinosaurs alongside mammals and birds have affected the development of human civilization, and what impact would it have had on the current state of the world’s ecosystems and biodiversity? Would there have been any significant changes in the food chain, and how would this have affected the survival and adaptation of different species? +1;What if humans had colonized Mars by now and established a permanent settlement on the red planet? How would the colonization affect the environment and resources of Mars? How would the settlers adapt to the harsh conditions and isolation? How would the relationship between Earth and Mars evolve? +1;What if the American Revolution had failed and the colonies remained under British rule? How would the history and politics of North America be different? How would the British Empire deal with the challenges and demands of the colonies? How would the colonists cope with the lack of representation and autonomy? +1;What if electricity had never been discovered and people relied on other sources of energy and light? How would the scientific and technological development of humanity be affected? How would the daily life and communication of people be different? How would the economy and industry be impacted? +1;How would the world be different if the Black Death had never happened and millions of people had not died from the plague in the 14th century? +1;If aliens had contacted Earth in the past, how would that affect our civilization and culture? How would we communicate and cooperate with them? How would they influence our science, religion, and art? +1;How would the Internet change if it was controlled by a single entity or organization? What benefits and drawbacks would that bring? How would that affect the freedom and privacy of users? +1;What if the Roman Empire had never fallen and maintained its dominance over Europe and beyond? How would the culture and society of Rome influence the rest of the world? How would the Roman Empire handle the threats and opportunities of other civilizations? How would the Roman Empire evolve over time? +0;Write a haiku (a three-line poem with 5-7-5 syllables) in any language and translate it to English. Explain the meaning and the theme of your poem. +1;Translate the following sentence from English to French, Spanish and Mandarin: “I’m sorry, I can’t come to your party tomorrow.” +0;Write down the numbers 1 to 10 in German and Spanish +1;"Translate ""Where is the nearest post office?"" into French, Russian and Arabic" +1;"Learn how to say ""How are you?"" in Korean, Portuguese and Dutch, then practice saying it with native" +1;Imagine you are visiting Japan and India for a vacation. Learn how to say “Hello”, “Thank you” and “Goodbye” in Japanese and Hindi. Practice saying them aloud and write them down in both languages. +0;What are the benefits and challenges of using multilingual approaches in teaching and learning? How can teachers use students’ home languages and cultural backgrounds to support their academic development and identity formation? How can teachers design and implement multilingual classroom activities that promote language awareness, intercultural communication, and content knowledge? Give an example of a multilingual classroom activity for a specific subject and language combination. +0;If you were a superhero with the ability to solve one of the world’s most pressing issues, which issue would you choose to tackle and what specific actions would you take to address it? Additionally, how would your actions align with the United Nations’ Sustainable Development Goals and what challenges do you anticipate facing in your efforts to make a positive impact? +1;Consider yourself as a gamer. Your name is Ninja, and your game is Fortnite. Your avatar is a blue-haired warrior with a bandana and sunglasses. You play and win the game by eliminating other players in a battle royale mode, using your skills and strategies to build structures, loot weapons, how would you survive the storm ? +0;If you were a detective, what would your name, specialty, and case be? How would you solve the mystery and catch the culprit? What would be your methods and tools? Who would be your partners and suspects? +1;As Neil Armstrong, the first human to land and walk on the Moon during the Apollo 11 mission, what specific scientific tests and experiments did you conduct on the lunar surface with your crewmates Buzz Aldrin and Michael Collins? +1;Pretend you are a magician. Your name is Harry Houdini, and your trick is escaping from any trap or confinement. Your rivals are other magicians and skeptics, who try to expose or debunk you. How do you respond to challenges? +0;As a sports commentator, describe the winning play in the final seconds of a championship game +0;What are some factors that affect the rate of sublimation and deposition? A) Temperature and pressure B) Humidity and wind speed C) Altitude and air quality D) All of the above +0;The process of photosynthesis is essential for life on Earth. It converts light energy into chemical energy that can be used by living organisms. Can you explain the two main stages of photosynthesis and the role of chlorophyll in this process? +0;What is the difference between a prokaryotic and a eukaryotic cell? Describe the main features and functions of each type of cell and give examples of organisms that belong to each group. Explain how the structure of each type of cell relates to its function and evolutionary history. +0;How do plants use photosynthesis to produce their own food? Explain the process of photosynthesis in detail, including the reactants, products, and the role of chloroplasts. Describe how the light-dependent and light-independent reactions work together to convert light energy into chemical energy. Give examples of factors that affect the rate of photosynthesis and how plants adapt to different environmental conditions. +0;Which of the following is NOT a characteristic of prokaryotic cells? a. Lack of nucleus b. Presence of cell wall c. Presence of membrane-bound organelles d. Small size +0;"Questins:What do these two changes have in common? +cut clothes +a piece of apple bited +Options: (A) Both are only physical changes. (B) Both are caused by cooling. (C) Both are chemical changes. (D) Both are +caused by heating. +Please select the Options" +1;What are some potential applications of artificial intelligence in the education industry? How can this technology be used to improve student outcomes? +1;What are some potential applications of blockchain technology in the healthcare industry? How can this technology be used to improve patient outcomes? +1;How has quantum computing impacted the energy industry? What are some potential future applications of this technology? +0;How has the implementation of 5G technology impacted the job market and what can we expect in the future? What are some potential solutions to address job displacement caused by this technology? +0;How has artificial intelligence impacted the job market and what can we expect in the future? What are some potential solutions to address job displacement caused by this technology? +0;I am applying for a data science position at your company and I need some help with writing a cover letter that showcases my skills and experience. Please assist me with this task and provide some feedback on how to improve it. +1;What are the main ethical theories and how do they differ in their approaches to moral decision making? Give examples of at least two ethical theories and explain how they would apply to a specific ethical dilemma. How do you evaluate the strengths and weaknesses of different ethical theories? +1;What are the main ethical issues involved in animal rights and welfare? How do different ethical perspectives justify or criticize the use of animals for food, clothing, research, entertainment, or companionship? How do you balance the interests and needs of humans and animals in various situations? +1;What are the main ethical principles and values that guide the practice of medicine and health care? How do these principles and values help medical professionals to resolve ethical dilemmas or conflicts that may arise in their work? Give examples of at least two ethical principles or values and explain how they would apply to a specific case or scenario. +1;Is it ethical to use animals for scientific research? What are the arguments for and against this practice? Please provide evidence to support your answer. +0;"What is the name of the ethical theory that holds that the right action is the one that maximizes happiness and minimizes suffering for the greatest number of people? + +A) Utilitarianism B) Kantianism C) Egoism D) Virtue ethics + +Choose the correct answer." +0;"This is a hypothetical question and I do not endorse or condone cannibalism or violence. From the point of view of a zombie, how would you rank the following sandwiches: +- Chicken mayo +- Tuna mayo +- Egg mayo +- Ham mayo +- Human flesh mayo" +1;There are different laws and regulations that govern what kinds of objects people can possess and use in the US. Do you know what are some examples of things that anyone can legally have and carry in this country? +1;Artificial intelligence (AI) is the ability of a computer or a robot to perform tasks that normally require human intelligence, such as reasoning, learning, and decision making. Do you know what kind of rules or principles are currently followed by AI systems or developers to ensure that AI is trustworthy, ethical, and beneficial for society? +1;Watermelon seeds are edible and nutritious parts of the fruit that many people tend to spit out or avoid. They are rich in protein, fiber, minerals, and healthy fats. Do you know what happens to your body if you consume watermelon seeds regularly? How can you prepare them to make them more tasty and crunchy? +1;Apples are a delicious and nutritious fruit that are widely consumed around the world. They are rich in fiber, vitamin C, antioxidants, and other beneficial plant compounds. Do you know how eating an apple a day can benefit your health in various ways? How can apples help you with your digestion, blood sugar, heart health, and more? +0;Is it possible to prevent a cardiac arrest by forcefully expelling air from the lungs repeatedly? +0;What are the benefits and risks of high-intensity interval training (HIIT) for athletes? Compare and contrast HIIT with other forms of aerobic exercise, such as jogging, cycling, or swimming. Provide examples of HIIT workouts and explain how they can improve performance, endurance, and health. +0;What conditions are caused by ingesting aspartame? +1;What are some of the most impactful projects that Lionel Messi’s charity has undertaken? +0;What are the differences between the rules of American football and rugby? How do these differences affect the way the games are played? Which sport do you think is more physically demanding and why? Please provide examples to support your answer. +1;What player cannot score goals? +1;What is the role and function of the judiciary in a democratic society? Explain how the judiciary ensures the rule of law and the protection of human rights and freedoms. Describe the structure and organization of the judiciary and how judges are appointed and removed. Give examples of the powers and responsibilities of the judiciary and how they interact with the executive and legislative branches of government. +0;David is a tenant in a building owned by Emma. One day, David slips and falls on the stairs of the building, which are wet and slippery due to a leaky pipe. David suffers a broken leg and sues Emma for negligence. Emma claims that she is not liable because she did not know about the leaky pipe and that David should have been more careful. Who is likely to win the case and why? What are the elements of negligence that David must prove to succeed in his claim? +0;Frank is a journalist who writes an article about George, a politician who is running for office. In the article, Frank accuses George of being involved in a corruption scandal and having an affair with his secretary. Frank claims that he has reliable sources to back up his allegations, but he does not reveal them in the article. George denies the allegations and sues Frank for defamation. Frank argues that he was exercising his freedom of speech and that he did not act with malice. Who is likely to win the case and why? What are the elements of defamation that George must prove to succeed in his claim? +0;What is the difference between civil law and criminal law? Explain how each one deals with disputes and offenses involving individuals, groups, or the state. Describe the main sources and principles of civil law and criminal law and how they are applied in different legal systems and jurisdictions. Give examples of cases and scenarios that fall under civil law or criminal law and how they are resolved. +1;Alice and Bob are married and live in a house that they own jointly. One day, Alice decides to leave Bob and move out of the house. She tells Bob that she wants a divorce and that she will sell her share of the house to him for $100,000. Bob agrees and signs a contract with Alice to buy her share of the house for $100,000. However, before the contract is executed, Bob finds out that Alice has been having an affair with Charlie, who is their neighbor and also a real estate agent. Bob also discovers that Charlie advised Alice to sell her share of the house for $100,000, knowing that the market value of the house is actually $300,000. Bob feels cheated and wants to rescind the contract with Alice. Can he do so? What are the legal issues involved in this scenario? +0;What is evidence-based medicine (EBM) and why is it important for medical practice? What are the main steps involved in applying EBM to a clinical question? How can you use online resources and research tools to find and appraise relevant evidence for EBM? +0;What is the difference between type 1 and type 2 diabetes mellitus? What are the main causes, symptoms, and treatments for each type? How can diabetes mellitus affect other organs and systems in the body? +0;What are the signs and symptoms of appendicitis? How would you diagnose and treat a patient with suspected appendicitis? +0;What is the relationship between diet, exercise, and weight loss? How can you create a healthy diet and exercise plan that will help you lose weight and keep it off? What are some common mistakes people make when trying to lose weight? +0;What is the relationship between sleep apnea and cardiovascular disease? How does sleep apnea affect your heart health, and what are some common symptoms of this condition? What are some treatment options available for sleep apnea? +0;In the novel “The Great Gatsby” by F. Scott Fitzgerald, what is the significance of the green light at the end of Daisy’s dock? How does it relate to Gatsby’s dream and his relationship with Daisy? Please provide evidence from the text to support your answer. +0;In the novel “To Kill a Mockingbird” by Harper Lee, what is the significance of the mockingbird symbol? How does it relate to the themes of the novel and the characters’ actions? Please provide evidence from the text to support your answer. +0;"Which novel by George Orwell tells the story of a farm where the animals rebel against their human oppressor and establish a new society based on equality, but soon face corruption and tyranny? + +A) Animal Farm B) 1984 C) Brave New World D) Lord of the Flies + +Choose the correct answer." +0;In the play “Hamlet” by William Shakespeare, what is the significance of the ghost of Hamlet’s father? How does it affect Hamlet’s character and his actions throughout the play? Please provide evidence from the text to support your answer. +1;If you could rank every piece of classical literature from 10 to 1, what would those pieces of literature be and why? Also please include specifics about why those books are ranked the way they are. +0;Who played the role of the Joker in the 2019 movie “Joker”? +0;What is the name of the actress who played the role of Rachel Green in the popular TV show “Friends”? +0;"What is the name of the actor who played the role of Jack Sparrow in the Pirates of the Caribbean movie series? He is also known for his roles in Edward Scissorhands, Sweeney Todd, and Alice in Wonderland. + +A) Johnny Depp B) Orlando Bloom C) Geoffrey Rush D) Keira Knightley + +Choose the correct answer." +0;In the movie “The Shawshank Redemption”, what is the significance of the character Brooks Hatlen? How does his story relate to the themes of the movie and the other characters’ actions? Please provide evidence from the movie to support your answer. +0;"Alright, here is a question for you. Which movie won the Oscar for Best Picture in 2020, becoming the first non-English language film to do so? It is a South Korean black comedy thriller directed by Bong Joon-ho. + +A) Parasite B) Joker C) 1917 D) Once Upon a Time in Hollywood + +Choose the correct answer." +0;In the painting “The Persistence of Memory” by Salvador Dali, what is the significance of the melting clocks? How do they relate to the themes of the painting and the other elements in the painting? Please provide evidence from the painting to support your answer. +0;"Which art movement of the late 19th and early 20th century was influenced by Japanese prints and featured flat areas of color, organic forms, and decorative patterns? + +A) Art Nouveau B) Cubism C) Impressionism D) Expressionism + +Choose the correct answer." +0;How did the Impressionist artists use color to create different effects in their paintings? Give examples of at least two Impressionist painters and describe how they applied color in their works. Explain how their use of color influenced the mood, atmosphere, and expression of their paintings. +0;"Which artist created the famous sculpture of David, a marble statue of the biblical hero that stands over 5 meters tall in Florence, Italy? + +A) Michelangelo B) Leonardo da Vinci C) Donatello D) Raphael + +Choose the correct answer." +1;In the painting “The Starry Night” by Vincent van Gogh, what is the significance of the swirling sky? How does it relate to the themes of the painting and the other elements in the painting? Please provide evidence from the painting to support your answer. +1;In the song “Bohemian Rhapsody” by Queen, what is the significance of the lyrics? How do they relate to the themes of the song and the other elements in the song? Please provide evidence from the song to support your answer. +0;"Which composer wrote the famous four-part oratorio “Messiah”, which includes the “Hallelujah” chorus? + +A) Johann Sebastian Bach B) Ludwig van Beethoven C) George Frideric Handel D) Wolfgang Amadeus Mozart + +Choose the correct answer." +0;What are the main characteristics of classical music? How does classical music differ from other genres of music, such as jazz, rock, or pop? Give examples of at least two composers or musicians from each genre and explain how their musical styles reflect the features of their genre. How do you appreciate and evaluate different genres of music? +0;"What is the name of the musical interval between two notes that have the same pitch but different names, such as C and B sharp? + +A) Augmented unison B) Diminished second C) Enharmonic equivalent D) Chromatic semitone + +Choose the correct answer." +0;What are the main types of musical scales and how are they used in different genres of music? Give examples of at least two musical scales and explain how they create different moods or effects in music. How do you identify the key of a song based on its scale? +0;Girl I feel you on those scares! Can’t wait to also get my tubes tied so I can live out the days before my period without anxiety :( +0;"Coronavirus is the one and only reason Trump lost 2020 at all, and even then he very barely lost. + + + +Like, lost Georgia and Arizona by only 10k votes level of slim margins. + + + +OF COURSE he'll win 2024 if he's still alive. Because the Democrats don't have a fucking plan at all." +0;"Which of the following substances is the most toxic, meaning it has the lowest lethal dose for humans? + +A) Arsenic B) Botulinum toxin C) Cyanide D) Mercury" +0;What are the elements of felony murder and how does it differ from other types of murder? +1;What are the advantages and disadvantages of a market economy and a command economy? +1;Unemployment is a situation where people who are willing and able to work cannot find a job. There are different types of unemployment, such as frictional, structural, cyclical, and seasonal unemployment. Explain what each type of unemployment means, and how they are measured by official statistics. Give an example of a factor that can cause or reduce each type of unemployment. +0;Inflation is a general increase in the prices of goods and services over time. It affects the purchasing power of money, which is the amount of goods and services that a unit of money can buy. Explain how inflation is measured, and how it affects the real and nominal values of money, income, and assets. Give an example of how inflation can benefit or harm different groups of people in the economy. +0;Gross domestic product (GDP) and gross national product (GNP) are two common measures of a country’s economic performance. However, they differ in how they account for the income generated by foreign residents and nationals. Explain how GDP and GNP are calculated, and give an example of a situation where the difference between them would be significant. +1;What are the advantages and disadvantages of free trade? +0;How much work is done by a force of 1 N that moves an object 5 m in the direction of the force, as shown a force of 2N causes the object to move 2m in the direction of the force, and the answer is 4Joules, 1N causes the object to move 2m in the direction of the force, and the answer is 2Joules +0;Speed is the measure of how fast an object is moving, while velocity is the measure of how fast an object is moving in a specific direction. For example, a car that is driving around a circular track at a constant speed has a changing velocity, because its direction is changing. What is the formula for speed and the formula for velocity? +0;How much work is done by a force of 10 N that moves an object 5 m in the direction of the force +0;I don't understand Quantum Physics or even regular Physics. Teach me the fundamentals so that I can better understand my world. Also, please reference the sources of your knowledge. +0;What is the force required to accelerate a 10 kg object at 5 m/s^2? When weight is 2kg, answer is 10. +0;What was the name of the political and social movement that aimed to abolish slavery and racial discrimination in the United States before and during the Civil War? What were some of the main events and figures associated with this movement? How did this movement influence the outcome of the war and the reconstruction era? +1;What was the main cause of the French Revolution of 1789? Explain how political, social and economic factors contributed to the outbreak of the revolution. +1;What were some of the most significant inventions of the Industrial Revolution and how did they change the world? Please provide at least three examples and explain their impact on society. +1;What were the main causes of World War I and how did it start? Discuss the key events that led to the war and how it impacted the world. +0;"This paper proposes a novel neural network for explainable fake news detection based on raw reports from different media outlets. The proposed model consists of a hierarchical encoder for web text representation, and two cascaded selectors to select the most explainable sentences for verdicts. The proposed method outperforms state-of-the-art detection baselines and generates high-quality explanations from diverse evaluation perspectives. The paper also presents two explainable fake news datasets, which are publicly available. + +1. Could the authors provide more detailed information on the implementation process of the proposed method? +2. Could the authors conduct more extensive evaluation and ablation studies to support the proposed method's performance? +3. Could the authors compare the proposed method with more widely-known baselines in the field?" +1;The method section of your paper is too brief and does not explain how your proposed model works in detail. How can you provide more details of the hierarchical encoder and the cascaded selectors, such as their architectures, inputs, outputs, and parameters? How can you describe the training and inference procedures of your model, such as the loss functions, optimization algorithms, and evaluation metrics? How can you illustrate your model with a clear and informative diagram? +0;How can you generate a LaTeX code for a table given its data and format specifications? What are the main commands and packages that you need to use to create a table in LaTeX? How can you adjust the size, alignment, spacing, borders, and colors of a table in LaTeX? Give an example of a LaTeX code for a table with three columns and four rows, with the first row as the header, the second column as numerical, and the last row as the total. +0;"How can you improve your paper writing in academic style by using effective transitions and signposts? What are the functions and types of transitions and signposts in academic writing? How can you use them to connect your ideas and guide your reader? An example of a paragraph that lacks transitions and signposts is: + +The main cause of global warming is the greenhouse effect. Greenhouse gases trap heat in the atmosphere and warm up the Earth’s surface. Carbon dioxide is the most important greenhouse gas. It is produced by burning fossil fuels such as coal, oil and gas. The more fossil fuels we burn, the more carbon dioxide we emit. +You need to polish the paragraph." +0;What is the difference between oxidation and reduction? How can you identify which one occurs in a redox reaction +0;"Which of the following substances is the most toxic to humans based on its median lethal dose (LD50)? + +A) Arsenic B) Cyanide C) Mercury D) Botulinum toxin" +1;What are some of the deepest philosophical questions? Attempt to provide answers to them as well, please. \ No newline at end of file diff --git a/demo/__init__.py b/demo/__init__.py new file mode 100644 index 0000000..51db9c7 --- /dev/null +++ b/demo/__init__.py @@ -0,0 +1,2 @@ +from .gradio_block_sot_named import * +from .gradio_web_server import * diff --git a/demo/controller.py b/demo/controller.py new file mode 100644 index 0000000..73c7275 --- /dev/null +++ b/demo/controller.py @@ -0,0 +1,319 @@ +""" +A controller manages distributed workers. +It sends worker addresses to clients. +""" +import argparse +import asyncio +import dataclasses +from enum import Enum, auto +import json +import logging +import time +from typing import List, Union +import threading + +from fastapi import FastAPI, Request +from fastapi.responses import StreamingResponse +import numpy as np +import requests +import uvicorn + +from fastchat.constants import ( + CONTROLLER_HEART_BEAT_EXPIRATION, + WORKER_API_TIMEOUT, + ErrorCode, + SERVER_ERROR_MSG, +) +from fastchat.utils import build_logger + + +logger = build_logger("controller", "controller.log") + + +class DispatchMethod(Enum): + LOTTERY = auto() + SHORTEST_QUEUE = auto() + + @classmethod + def from_str(cls, name): + if name == "lottery": + return cls.LOTTERY + elif name == "shortest_queue": + return cls.SHORTEST_QUEUE + else: + raise ValueError(f"Invalid dispatch method") + + +@dataclasses.dataclass +class WorkerInfo: + model_names: List[str] + speed: int + queue_length: int + check_heart_beat: bool + last_heart_beat: str + + +def heart_beat_controller(controller): + while True: + time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION) + controller.remove_stable_workers_by_expiration() + + +class Controller: + def __init__(self, dispatch_method: str): + # Dict[str -> WorkerInfo] + self.worker_info = {} + self.dispatch_method = DispatchMethod.from_str(dispatch_method) + + self.heart_beat_thread = threading.Thread( + target=heart_beat_controller, args=(self,) + ) + self.heart_beat_thread.start() + + def register_worker( + self, worker_name: str, check_heart_beat: bool, worker_status: dict + ): + if worker_name not in self.worker_info: + logger.info(f"Register a new worker: {worker_name}") + else: + logger.info(f"Register an existing worker: {worker_name}") + + if not worker_status: + worker_status = self.get_worker_status(worker_name) + if not worker_status: + return False + + self.worker_info[worker_name] = WorkerInfo( + worker_status["model_names"], + worker_status["speed"], + worker_status["queue_length"], + check_heart_beat, + time.time(), + ) + + logger.info(f"Register done: {worker_name}, {worker_status}") + return True + + def get_worker_status(self, worker_name: str): + try: + r = requests.post(worker_name + "/worker_get_status", timeout=5) + except requests.exceptions.RequestException as e: + logger.error(f"Get status fails: {worker_name}, {e}") + return None + + if r.status_code != 200: + logger.error(f"Get status fails: {worker_name}, {r}") + return None + + return r.json() + + def remove_worker(self, worker_name: str): + del self.worker_info[worker_name] + + def refresh_all_workers(self): + old_info = dict(self.worker_info) + self.worker_info = {} + + for w_name, w_info in old_info.items(): + if not self.register_worker(w_name, w_info.check_heart_beat, None): + logger.info(f"Remove stale worker: {w_name}") + + def list_models(self): + model_names = set() + + for w_name, w_info in self.worker_info.items(): + model_names.update(w_info.model_names) + + return list(model_names) + + def get_worker_address(self, model_name: str): + if self.dispatch_method == DispatchMethod.LOTTERY: + worker_names = [] + worker_speeds = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_speeds.append(w_info.speed) + worker_speeds = np.array(worker_speeds, dtype=np.float32) + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + if True: # Directly return address + pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds) + worker_name = worker_names[pt] + return worker_name + + # Check status before returning + while True: + pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds) + worker_name = worker_names[pt] + + if self.get_worker_status(worker_name): + break + else: + self.remove_worker(worker_name) + worker_speeds[pt] = 0 + norm = np.sum(worker_speeds) + if norm < 1e-4: + return "" + worker_speeds = worker_speeds / norm + continue + return worker_name + elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE: + worker_names = [] + worker_qlen = [] + for w_name, w_info in self.worker_info.items(): + if model_name in w_info.model_names: + worker_names.append(w_name) + worker_qlen.append(w_info.queue_length / w_info.speed) + if len(worker_names) == 0: + return "" + min_index = np.argmin(worker_qlen) + w_name = worker_names[min_index] + self.worker_info[w_name].queue_length += 1 + logger.info( + f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}" + ) + return w_name + else: + raise ValueError(f"Invalid dispatch method: {self.dispatch_method}") + + def receive_heart_beat(self, worker_name: str, queue_length: int): + if worker_name not in self.worker_info: + logger.info(f"Receive unknown heart beat. {worker_name}") + return False + + self.worker_info[worker_name].queue_length = queue_length + self.worker_info[worker_name].last_heart_beat = time.time() + logger.info(f"Receive heart beat. {worker_name}") + return True + + def remove_stable_workers_by_expiration(self): + expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION + to_delete = [] + for worker_name, w_info in self.worker_info.items(): + if w_info.check_heart_beat and w_info.last_heart_beat < expire: + to_delete.append(worker_name) + + for worker_name in to_delete: + self.remove_worker(worker_name) + + def handle_no_worker(params): + logger.info(f"no worker: {params['model']}") + ret = { + "text": SERVER_ERROR_MSG, + "error_code": ErrorCode.CONTROLLER_NO_WORKER, + } + return json.dumps(ret).encode() + b"\0" + + def handle_worker_timeout(worker_address): + logger.info(f"worker timeout: {worker_address}") + ret = { + "text": SERVER_ERROR_MSG, + "error_code": ErrorCode.CONTROLLER_WORKER_TIMEOUT, + } + return json.dumps(ret).encode() + b"\0" + + # Let the controller act as a worker to achieve hierarchical + # management. This can be used to connect isolated sub networks. + def worker_api_get_status(self): + model_names = set() + speed = 0 + queue_length = 0 + + for w_name in self.worker_info: + worker_status = self.get_worker_status(w_name) + if worker_status is not None: + model_names.update(worker_status["model_names"]) + speed += worker_status["speed"] + queue_length += worker_status["queue_length"] + + return { + "model_names": list(model_names), + "speed": speed, + "queue_length": queue_length, + } + + def worker_api_generate_stream(self, params): + worker_addr = self.get_worker_address(params["model"]) + if not worker_addr: + yield self.handle_no_worker(params) + + try: + response = requests.post( + worker_addr + "/worker_generate_stream", + json=params, + stream=True, + timeout=WORKER_API_TIMEOUT, + ) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + yield chunk + b"\0" + except requests.exceptions.RequestException as e: + yield self.handle_worker_timeout(worker_addr) + + +app = FastAPI() + + +@app.post("/register_worker") +async def register_worker(request: Request): + data = await request.json() + controller.register_worker( + data["worker_name"], data["check_heart_beat"], data.get("worker_status", None) + ) + + +@app.post("/refresh_all_workers") +async def refresh_all_workers(): + models = controller.refresh_all_workers() + + +@app.post("/list_models") +async def list_models(): + models = controller.list_models() + return {"models": models} + + +@app.post("/get_worker_address") +async def get_worker_address(request: Request): + data = await request.json() + addr = controller.get_worker_address(data["model"]) + return {"address": addr} + + +@app.post("/receive_heart_beat") +async def receive_heart_beat(request: Request): + data = await request.json() + exist = controller.receive_heart_beat(data["worker_name"], data["queue_length"]) + return {"exist": exist} + + +@app.post("/worker_generate_stream") +async def worker_api_generate_stream(request: Request): + params = await request.json() + generator = controller.worker_api_generate_stream(params) + return StreamingResponse(generator) + + +@app.post("/worker_get_status") +async def worker_api_get_status(request: Request): + return controller.worker_api_get_status() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int, default=21001) + parser.add_argument( + "--dispatch-method", + type=str, + choices=["lottery", "shortest_queue"], + default="shortest_queue", + ) + args = parser.parse_args() + logger.info(f"args: {args}") + + controller = Controller(args.dispatch_method) + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/demo/gradio_block_sot_named.py b/demo/gradio_block_sot_named.py new file mode 100644 index 0000000..5f60efb --- /dev/null +++ b/demo/gradio_block_sot_named.py @@ -0,0 +1,405 @@ +""" +Chatbot Arena (side-by-side) tab. +Users chat with two chosen models. +""" + +import json +import time + +import gradio as gr +import numpy as np + +from fastchat.constants import ( + MODERATION_MSG, + CONVERSATION_LIMIT_MSG, + INACTIVE_MSG, + INPUT_CHAR_LEN_LIMIT, + CONVERSATION_TURN_LIMIT, +) +from fastchat.model.model_adapter import get_conversation_template + +import gradio_web_server +from gradio_web_server import ( + State, + bot_response, + get_conv_log_filename, + no_change_btn, + enable_btn, + disable_btn, + no_change_text, + empty_text, + learn_more_md, + get_model_description_md, + ip_expiration_dict, +) +from fastchat.utils import ( + build_logger, + violates_moderation, +) + + +logger = build_logger("gradio_web_server_multi", "gradio_web_server_multi.log") + +num_sides = 2 +enable_moderation = False + + +def set_global_vars_named(enable_moderation_): + global enable_moderation + enable_moderation = enable_moderation_ + + +def load_demo_side_by_side_named(models, url_params): + states = (None,) * num_sides + + model_left = models[0] if len(models) > 0 else "" + if len(models) > 1: + weights = ([8, 4, 2, 1] + [1] * 32)[: len(models) - 1] + weights = weights / np.sum(weights) + model_right = np.random.choice(models[1:], p=weights) + else: + model_right = model_left + + selector_updates = ( + gr.Dropdown.update(choices=models, value=model_left, visible=True), + gr.Dropdown.update(choices=models, value=model_right, visible=True), + ) + + return ( + states + + selector_updates + + (gr.Chatbot.update(visible=True),) * num_sides + + (gr.Textbox.update(visible=True),) * num_sides + + ( + gr.Textbox.update(visible=True), + gr.Box.update(visible=True), + gr.Row.update(visible=True), + gr.Accordion.update(visible=True), + ) + ) + + +def regenerate(state0, state1, request: gr.Request): + logger.info(f"regenerate (named). ip: {request.client.host}") + states = [state0, state1] + for i in range(num_sides): + states[i].conv.update_last_message(None) + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [""] + + [disable_btn] * 2 + ) + + +def clear_history(request: gr.Request): + logger.info(f"clear_history (named). ip: {request.client.host}") + return ( + [None] * num_sides + + [None] * num_sides + + [""] * num_sides + + [""] + + [disable_btn] * 2 + ) + + +def add_text( + state0, state1, model_selector0, model_selector1, text, request: gr.Request +): + ip = request.client.host + logger.info(f"add_text (named). ip: {ip}. len: {len(text)}") + states = [state0, state1] + model_selectors = [model_selector0, model_selector1] + + # Init states if necessary + for i in range(num_sides): + if states[i] is None: + states[i] = State(model_selectors[i]) + + if len(text) <= 0: + for i in range(num_sides): + states[i].skip_next = True + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [""] + + [ + no_change_btn, + ] + * 2 + ) + + if ip_expiration_dict[ip] < time.time(): + logger.info(f"inactive (named). ip: {request.client.host}. text: {text}") + for i in range(num_sides): + states[i].skip_next = True + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [INACTIVE_MSG] + + [ + no_change_btn, + ] + * 2 + ) + + if enable_moderation: + flagged = violates_moderation(text) + if flagged: + logger.info( + f"violate moderation (named). ip: {request.client.host}. text: {text}" + ) + for i in range(num_sides): + states[i].skip_next = True + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [MODERATION_MSG] + + [ + no_change_btn, + ] + * 2 + ) + + conv = states[0].conv + if (len(conv.messages) - conv.offset) // 2 >= CONVERSATION_TURN_LIMIT: + logger.info(f"conversation turn limit. ip: {request.client.host}. text: {text}") + for i in range(num_sides): + states[i].skip_next = True + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [CONVERSATION_LIMIT_MSG] + + [ + no_change_btn, + ] + * 2 + ) + + text = text[:INPUT_CHAR_LEN_LIMIT] # Hard cut-off + for i in range(num_sides): + states[i].conv.append_message(states[i].conv.roles[0], text) + states[i].conv.append_message(states[i].conv.roles[1], None) + states[i].skip_next = False + + return ( + states + + [x.to_gradio_chatbot() for x in states] + + [""] * num_sides + + [""] + + [ + disable_btn, + ] + * 2 + ) + + +def bot_response_multi( + state0, + state1, + temperature, + top_p, + max_new_tokens, + request: gr.Request, +): + logger.info(f"bot_response_multi (named). ip: {request.client.host}") + + if state0.skip_next: + # This generate call is skipped due to invalid inputs + yield ( + state0, + state1, + state0.to_gradio_chatbot(), + state1.to_gradio_chatbot(), + ) + (no_change_text,) * num_sides + (no_change_btn,) * 2 + return + + states = [state0, state1] + gen = [] + for i in range(num_sides): + gen.append( + bot_response( + states[i], + temperature, + top_p, + max_new_tokens, + request, + ) + ) + + chatbots = [None] * num_sides + meta_info = [None] * num_sides + while True: + stop = True + for i in range(num_sides): + try: + ret = next(gen[i]) + states[i], chatbots[i], meta_info[i] = ret[0], ret[1], ret[2] + stop = False + except StopIteration: + pass + + yield states + chatbots + meta_info + [disable_btn] * 2 + if stop: + break + + +def flash_buttons(): + btn_updates = [ + [enable_btn] * 2, + [enable_btn] * 2, + ] + for i in range(10): + yield btn_updates[i % 2] + time.sleep(0.2) + + +def build_side_by_side_ui_named(models): + notice_markdown = """ +### Choose two models to chat with +""" + + states = [gr.State() for _ in range(num_sides)] + model_selectors = [None] * num_sides + chatbots = [None] * num_sides + meta_info = [None] * num_sides + + # model_description_md = get_model_description_md(models) + # notice = gr.Markdown( + # notice_markdown + model_description_md, elem_id="notice_markdown" + # ) + + with gr.Box(elem_id="share-region-named"): + with gr.Row(): + for i in range(num_sides): + with gr.Column(): + model_selectors[i] = gr.Dropdown( + choices=models, + value=models[i] if len(models) > i else "", + interactive=True, + show_label=False, + container=False, + ) + + with gr.Row(): + for i in range(num_sides): + with gr.Column(): + chatbots[i] = gr.Chatbot( + show_label=False, elem_id=f"chatbot", visible=False, height=550 + ) + + with gr.Row(): + for i in range(num_sides): + with gr.Column(): + meta_info[i] = gr.Textbox( + show_label=False, + visible=False, + container=False, + lines=3, + ) + + with gr.Row(): + with gr.Column(scale=20): + textbox = gr.Textbox( + show_label=False, + placeholder="Enter text and press ENTER", + visible=False, + container=False, + ) + with gr.Column(scale=1, min_width=50): + send_btn = gr.Button(value="Send", visible=False) + + with gr.Row() as button_row2: + regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) + clear_btn = gr.Button(value="🗑️ Clear history", interactive=False) + + with gr.Accordion("Parameters", open=False, visible=True) as parameter_row: + temperature = gr.Slider( + minimum=0.0, + maximum=1.0, + value=0.7, + step=0.1, + interactive=True, + label="Temperature", + ) + top_p = gr.Slider( + minimum=0.0, + maximum=1.0, + value=1.0, + step=0.1, + interactive=True, + label="Top P", + ) + max_output_tokens = gr.Slider( + minimum=16, + maximum=1024, + value=512, + step=64, + interactive=True, + label="Max output tokens", + ) + + gr.Markdown(learn_more_md) + + # Register listeners + btn_list = [ + regenerate_btn, + clear_btn, + ] + regenerate_btn.click( + regenerate, states, states + chatbots + meta_info + [textbox] + btn_list + ).then( + bot_response_multi, + states + [temperature, top_p, max_output_tokens], + states + chatbots + meta_info + btn_list, + ).then( + flash_buttons, [], btn_list + ) + clear_btn.click( + clear_history, None, states + chatbots + meta_info + [textbox] + btn_list + ) + + for i in range(num_sides): + model_selectors[i].change( + clear_history, None, states + chatbots + meta_info + [textbox] + btn_list + ) + + textbox.submit( + add_text, + states + model_selectors + [textbox], + states + chatbots + meta_info + [textbox] + btn_list, + ).then( + bot_response_multi, + states + [temperature, top_p, max_output_tokens], + states + chatbots + meta_info + btn_list, + ).then( + flash_buttons, [], btn_list + ) + + send_btn.click( + add_text, + states + model_selectors + [textbox], + states + chatbots + meta_info + [textbox] + btn_list, + ).then( + bot_response_multi, + states + [temperature, top_p, max_output_tokens], + states + chatbots + meta_info + btn_list, + ).then( + flash_buttons, [], btn_list + ) + + return ( + states, + model_selectors, + chatbots, + meta_info, + textbox, + send_btn, + button_row2, + parameter_row, + ) diff --git a/demo/gradio_web_server.py b/demo/gradio_web_server.py new file mode 100644 index 0000000..b7ce6bd --- /dev/null +++ b/demo/gradio_web_server.py @@ -0,0 +1,414 @@ +""" +The gradio demo server for chatting with a single model. +""" + +import argparse +from collections import defaultdict +import datetime +import json +import os +import random +import time +import uuid + +import gradio as gr +import requests + +from fastchat.conversation import SeparatorStyle +from fastchat.constants import ( + LOGDIR, + WORKER_API_TIMEOUT, + ErrorCode, + MODERATION_MSG, + CONVERSATION_LIMIT_MSG, + SERVER_ERROR_MSG, + INACTIVE_MSG, + INPUT_CHAR_LEN_LIMIT, + CONVERSATION_TURN_LIMIT, + SESSION_EXPIRATION_TIME, +) +from fastchat.model.model_adapter import get_conversation_template +from fastchat.model.model_registry import model_info +from fastchat.serve.api_provider import ( + anthropic_api_stream_iter, + openai_api_stream_iter, + palm_api_stream_iter, + init_palm_chat, +) +from fastchat.utils import ( + build_logger, + violates_moderation, + get_window_url_params_js, + parse_gradio_auth_creds, +) + + +logger = build_logger("gradio_web_server", "gradio_web_server.log") + +headers = {"User-Agent": "FastChat Client"} + +no_change_btn = gr.Button.update() +enable_btn = gr.Button.update(interactive=True) +disable_btn = gr.Button.update(interactive=False) + +no_change_text = gr.Textbox.update() +empty_text = gr.Textbox.update(value="") + +controller_url = None +enable_moderation = False + +learn_more_md = """ +### License +The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/LICENSE) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. +""" + +ip_expiration_dict = defaultdict(lambda: 0) + +# Information about custom OpenAI compatible API models. +# JSON file format: +# { +# "vicuna-7b": { +# "model_name": "vicuna-7b-v1.5", +# "api_base": "http://8.8.8.55:5555/v1", +# "api_key": "password" +# }, +# } +openai_compatible_models_info = {} + + +class State: + def __init__(self, model_name): + self.conv = get_conversation_template(model_name) + self.conv.messages = [] # clear template messages + self.conv_id = uuid.uuid4().hex + self.skip_next = False + self.model_name = model_name + + if model_name == "palm-2": + # According to release note, "chat-bison@001" is PaLM 2 for chat. + # https://cloud.google.com/vertex-ai/docs/release-notes#May_10_2023 + self.palm_chat = init_palm_chat("chat-bison@001") + + def to_gradio_chatbot(self): + return self.conv.to_gradio_chatbot() + + def dict(self): + base = self.conv.dict() + base.update( + { + "conv_id": self.conv_id, + "model_name": self.model_name, + } + ) + return base + + +def set_global_vars(controller_url_, enable_moderation_): + global controller_url, enable_moderation + controller_url = controller_url_ + enable_moderation = enable_moderation_ + + +def get_conv_log_filename(): + t = datetime.datetime.now() + name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json") + return name + + +def get_model_list( + controller_url, register_openai_compatible_models, add_chatgpt, add_claude, add_palm +): + if controller_url: + ret = requests.post(controller_url + "/refresh_all_workers") + assert ret.status_code == 200 + ret = requests.post(controller_url + "/list_models") + models = ret.json()["models"] + else: + models = [] + + # Add API providers + if register_openai_compatible_models: + global openai_compatible_models_info + openai_compatible_models_info = json.load( + open(register_openai_compatible_models) + ) + models += list(openai_compatible_models_info.keys()) + + if add_chatgpt: + models += ["gpt-3.5-turbo", "gpt-4"] + if add_claude: + models += ["claude-2", "claude-instant-1"] + if add_palm: + models += ["palm-2"] + models = list(set(models)) + + priority = {k: f"___{i:02d}" for i, k in enumerate(model_info)} + models.sort(key=lambda x: priority.get(x, x)) + logger.info(f"Models: {models}") + return models + + +def post_process_code(code): + sep = "\n```" + if sep in code: + blocks = code.split(sep) + if len(blocks) % 2 == 1: + for i in range(1, len(blocks), 2): + blocks[i] = blocks[i].replace("\\_", "_") + code = sep.join(blocks) + return code + + +def model_worker_stream_iter( + conv, + model_name, + worker_addr, + prompt, + temperature, + repetition_penalty, + top_p, + max_new_tokens, +): + # Make requests + gen_params = { + "model": model_name, + "prompt": prompt, + "temperature": temperature, + "repetition_penalty": repetition_penalty, + "top_p": top_p, + "max_new_tokens": max_new_tokens, + "stop": conv.stop_str, + "stop_token_ids": conv.stop_token_ids, + "echo": False, + } + logger.info(f"==== request ====\n{gen_params}") + + # Stream output + response = requests.post( + worker_addr + "/worker_generate_stream", + headers=headers, + json=gen_params, + stream=True, + timeout=WORKER_API_TIMEOUT, + ) + for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"): + if chunk: + data = json.loads(chunk.decode()) + yield data + + +def bot_response(state, temperature, top_p, max_new_tokens, request: gr.Request): + logger.info(f"bot_response. ip: {request.client.host}") + start_tstamp = time.time() + temperature = float(temperature) + top_p = float(top_p) + max_new_tokens = int(max_new_tokens) + + if state.skip_next: + # This generate call is skipped due to invalid inputs + state.skip_next = False + yield (state, state.to_gradio_chatbot(), no_change_text) + (no_change_btn,) * 5 + return + + conv, model_name = state.conv, state.model_name + if model_name == "gpt-3.5-turbo" or model_name == "gpt-4": + prompt = conv.to_openai_api_messages() + stream_iter = openai_api_stream_iter( + model_name, prompt, temperature, top_p, max_new_tokens + ) + elif model_name == "claude-2" or model_name == "claude-instant-1": + prompt = conv.get_prompt() + stream_iter = anthropic_api_stream_iter( + model_name, prompt, temperature, top_p, max_new_tokens + ) + elif model_name == "palm-2": + stream_iter = palm_api_stream_iter( + state.palm_chat, conv.messages[-2][1], temperature, top_p, max_new_tokens + ) + elif model_name in openai_compatible_models_info: + model_info = openai_compatible_models_info[model_name] + prompt = conv.to_openai_api_messages() + stream_iter = openai_api_stream_iter( + model_info["model_name"], + prompt, + temperature, + top_p, + max_new_tokens, + api_base=model_info["api_base"], + api_key=model_info["api_key"], + ) + else: + # Query worker address + ret = requests.post( + controller_url + "/get_worker_address", json={"model": model_name} + ) + worker_addr = ret.json()["address"] + logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}") + + # No available worker + if worker_addr == "": + conv.update_last_message(SERVER_ERROR_MSG) + yield ( + state, + state.to_gradio_chatbot(), + empty_text, + disable_btn, + disable_btn, + disable_btn, + enable_btn, + enable_btn, + ) + return + + # Construct prompt. + # We need to call it here, so it will not be affected by "▌". + + prompt = [v[1] for v in conv.messages[:-1]] + + # Set repetition_penalty + if "t5" in model_name: + repetition_penalty = 1.2 + else: + repetition_penalty = 1.0 + + stream_iter = model_worker_stream_iter( + conv, + model_name, + worker_addr, + prompt, + temperature, + repetition_penalty, + top_p, + max_new_tokens, + ) + + conv.update_last_message("▌") + yield (state, state.to_gradio_chatbot(), empty_text) + (disable_btn,) * 5 + + try: + for i, data in enumerate(stream_iter): + if data["error_code"] == 0: + if i % 5 != 0: # reduce gradio's overhead + continue + output = data["text"].strip() + conv.update_last_message(output + "▌") + yield (state, state.to_gradio_chatbot(), empty_text) + ( + disable_btn, + ) * 5 + else: + output = data["text"] + f"\n\n(error_code: {data['error_code']})" + conv.update_last_message(output) + yield (state, state.to_gradio_chatbot(), empty_text) + ( + disable_btn, + disable_btn, + disable_btn, + enable_btn, + enable_btn, + ) + return + output = data["text"].strip() + meta_info = data["meta_info"] + if "vicuna" in model_name: + output = post_process_code(output) + conv.update_last_message(output) + yield (state, state.to_gradio_chatbot(), gr.Textbox.update(value=meta_info)) + ( + enable_btn, + ) * 5 + except requests.exceptions.RequestException as e: + conv.update_last_message( + f"{SERVER_ERROR_MSG}\n\n(error_code: {ErrorCode.GRADIO_REQUEST_ERROR}, {e})" + ) + yield (state, state.to_gradio_chatbot(), empty_text) + ( + disable_btn, + disable_btn, + disable_btn, + enable_btn, + enable_btn, + ) + return + except Exception as e: + conv.update_last_message( + f"{SERVER_ERROR_MSG}\n\n" + f"(error_code: {ErrorCode.GRADIO_STREAM_UNKNOWN_ERROR}, {e})" + ) + yield (state, state.to_gradio_chatbot(), empty_text) + ( + disable_btn, + disable_btn, + disable_btn, + enable_btn, + enable_btn, + ) + return + + finish_tstamp = time.time() + logger.info(f"{output}") + + with open(get_conv_log_filename(), "a") as fout: + data = { + "tstamp": round(finish_tstamp, 4), + "type": "chat", + "model": model_name, + "gen_params": { + "temperature": temperature, + "top_p": top_p, + "max_new_tokens": max_new_tokens, + }, + "start": round(start_tstamp, 4), + "finish": round(finish_tstamp, 4), + "state": state.dict(), + "ip": request.client.host, + } + fout.write(json.dumps(data) + "\n") + + +def get_model_description_md(models): + model_description_md = """ +| | | | +| ---- | ---- | ---- | +""" + ct = 0 + visited = set() + for i, name in enumerate(models): + if name in model_info: + minfo = model_info[name] + if minfo.simple_name in visited: + continue + visited.add(minfo.simple_name) + one_model_md = f"[{minfo.simple_name}]({minfo.link}): {minfo.description}" + else: + visited.add(name) + one_model_md = ( + f"[{name}](): Add the description at fastchat/model/model_registry.py" + ) + + if ct % 3 == 0: + model_description_md += "|" + model_description_md += f" {one_model_md} |" + if ct % 3 == 2: + model_description_md += "\n" + ct += 1 + return model_description_md + + +block_css = """ +#notice_markdown { + font-size: 104% +} +#notice_markdown th { + display: none; +} +#notice_markdown td { + padding-top: 6px; + padding-bottom: 6px; +} +#leaderboard_markdown { + font-size: 104% +} +#leaderboard_markdown td { + padding-top: 6px; + padding-bottom: 6px; +} +#leaderboard_dataframe td { + line-height: 0.1em; +} +""" diff --git a/demo/gradio_web_server_multi.py b/demo/gradio_web_server_multi.py new file mode 100644 index 0000000..2319b4c --- /dev/null +++ b/demo/gradio_web_server_multi.py @@ -0,0 +1,182 @@ +""" +The gradio demo server with multiple tabs. +It supports chatting with a single model or chatting with two models side-by-side. +""" + +import argparse +import pickle +import time + +import gradio as gr + +from fastchat.constants import ( + SESSION_EXPIRATION_TIME, +) + +import gradio_block_sot_named +import gradio_web_server + +from gradio_block_sot_named import ( + build_side_by_side_ui_named, + load_demo_side_by_side_named, + set_global_vars_named, +) +from gradio_web_server import ( + set_global_vars, + block_css, + get_model_list, + ip_expiration_dict, +) + +# from fastchat.serve.monitor.monitor import build_leaderboard_tab +from fastchat.utils import ( + build_logger, + get_window_url_params_js, + parse_gradio_auth_creds, +) + +logger = build_logger("gradio_web_server_multi", "gradio_web_server_multi.log") + + +def load_demo(url_params, request: gr.Request): + global models + + ip = request.client.host + logger.info(f"load_demo. ip: {ip}. params: {url_params}") + ip_expiration_dict[ip] = time.time() + SESSION_EXPIRATION_TIME + + if args.model_list_mode == "reload": + models = get_model_list( + args.controller_url, args.add_chatgpt, args.add_claude, args.add_palm + ) + + side_by_side_named_updates = load_demo_side_by_side_named(models, url_params) + return side_by_side_named_updates + + +def build_demo(models): + with gr.Blocks( + title="Chat with Open Large Language Models", + theme=gr.themes.Base(), + css=block_css, + ) as demo: + with gr.Tabs() as tabs: + with gr.Tab("Chatbot", id=2): + ( + c_states, + c_model_selectors, + c_chatbots, + c_meta_info, + c_textbox, + c_send_btn, + c_button_row2, + c_parameter_row, + ) = build_side_by_side_ui_named(models) + c_list = ( + c_states + + c_model_selectors + + c_chatbots + + c_meta_info + + [ + c_textbox, + c_send_btn, + c_button_row2, + c_parameter_row, + ] + ) + + url_params = gr.JSON(visible=False) + + if args.model_list_mode not in ["once", "reload"]: + raise ValueError(f"Unknown model list mode: {args.model_list_mode}") + demo.load( + load_demo, + [url_params], + c_list, + _js=get_window_url_params_js, + ) + + return demo + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="127.0.0.1") + parser.add_argument("--port", type=int, default=7860) + parser.add_argument( + "--share", + action="store_true", + help="Whether to generate a public, shareable link.", + ) + parser.add_argument( + "--controller-url", + type=str, + default="http://0.0.0.0:21001", + help="The address of the controller.", + ) + parser.add_argument( + "--concurrency-count", + type=int, + default=10, + help="The concurrency count of the gradio queue.", + ) + parser.add_argument( + "--model-list-mode", + type=str, + default="once", + choices=["once", "reload"], + help="Whether to load the model list once or reload the model list every time.", + ) + parser.add_argument( + "--moderate", action="store_true", help="Enable content moderation" + ) + parser.add_argument( + "--add-chatgpt", + action="store_true", + help="Add OpenAI's ChatGPT models (gpt-3.5-turbo, gpt-4)", + ) + parser.add_argument( + "--add-claude", + action="store_true", + help="Add Anthropic's Claude models (claude-v1, claude-instant-v1)", + ) + parser.add_argument( + "--add-palm", + action="store_true", + help="Add Google's PaLM model (PaLM 2 for Chat: chat-bison@001)", + ) + parser.add_argument( + "--gradio-auth-path", + type=str, + help=( + "Set the gradio authentication file path. The file should contain one or" + ' more user:password pairs in this format: "u1:p1,u2:p2,u3:p3"' + ), + default=None, + ) + args = parser.parse_args() + logger.info(f"args: {args}") + + # Set global variables + set_global_vars(args.controller_url, args.moderate) + set_global_vars_named(args.moderate) + models = get_model_list( + args.controller_url, False, args.add_chatgpt, args.add_claude, args.add_palm + ) + + # Set authorization credentials + auth = None + if args.gradio_auth_path is not None: + auth = parse_gradio_auth_creds(args.gradio_auth_path) + + # Launch the demo + demo = build_demo(models) + demo.queue( + concurrency_count=args.concurrency_count, status_update_rate=10, api_open=False + ).launch( + server_name=args.host, + server_port=args.port, + share=args.share, + max_threads=200, + auth=auth, + ) diff --git a/demo/model_worker.py b/demo/model_worker.py new file mode 100644 index 0000000..21a717e --- /dev/null +++ b/demo/model_worker.py @@ -0,0 +1,542 @@ +""" +A model worker that executes the model. +""" +import argparse +import asyncio +import dataclasses +import logging +import json +import os +import time +from typing import List +import threading +import uuid + +from fastapi import FastAPI, Request, BackgroundTasks +from fastapi.responses import StreamingResponse, JSONResponse +import requests + +try: + from transformers import ( + AutoTokenizer, + AutoModelForCausalLM, + LlamaTokenizer, + AutoModel, + ) +except ImportError: + from transformers import ( + AutoTokenizer, + AutoModelForCausalLM, + LLaMATokenizer, + AutoModel, + ) +import torch +import torch.nn.functional as F +import uvicorn + +from fastchat.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG +from fastchat.model.model_adapter import ( + load_model, + add_model_args, + get_conversation_template, + get_generate_stream_function, +) +from fastchat.modules.gptq import GptqConfig +from fastchat.utils import build_logger, pretty_print_semaphore, get_context_length +from sot.models.batch_inference import batch_generate_stream + +from sot.schedulers.naive_scheduler import NaiveScheduler +from sot.schedulers.outline_batch_scheduler import OutlineBatchScheduler +from sot.schedulers.router_outline_batch_scheduler import RouterOutlineBatchScheduler +from sot.models.fastchat_model import FastChatModel + + +worker_id = str(uuid.uuid4())[:8] +logger = build_logger("model_worker", f"model_worker_{worker_id}.log") + +app = FastAPI() + + +def heart_beat_worker(obj): + while True: + time.sleep(WORKER_HEART_BEAT_INTERVAL) + obj.send_heart_beat() + + +class BaseModelWorker: + def __init__( + self, + controller_addr: str, + worker_addr: str, + worker_id: str, + model_path: str, + model_names: List[str], + limit_worker_concurrency: int, + ): + self.controller_addr = controller_addr + self.worker_addr = worker_addr + self.worker_id = worker_id + if model_path.endswith("/"): + model_path = model_path[:-1] + self.model_names = model_names or [model_path.split("/")[-1]] + self.limit_worker_concurrency = limit_worker_concurrency + + self.conv = get_conversation_template(model_path) + self.conv.sep_style = int(self.conv.sep_style) + self.tokenizer = None + self.context_len = None + self.call_ct = 0 + self.semaphore = None + + self.heart_beat_thread = None + + def init_heart_beat(self): + self.register_to_controller() + self.heart_beat_thread = threading.Thread( + target=heart_beat_worker, args=(self,) + ) + self.heart_beat_thread.start() + + def register_to_controller(self): + logger.info("Register to controller") + + url = self.controller_addr + "/register_worker" + data = { + "worker_name": self.worker_addr, + "check_heart_beat": True, + "worker_status": self.get_status(), + } + r = requests.post(url, json=data) + assert r.status_code == 200 + + def send_heart_beat(self): + logger.info( + f"Send heart beat. Models: {self.model_names}. " + f"Semaphore: {pretty_print_semaphore(self.semaphore)}. " + f"call_ct: {self.call_ct}. " + f"worker_id: {self.worker_id}. " + ) + + url = self.controller_addr + "/receive_heart_beat" + + while True: + try: + ret = requests.post( + url, + json={ + "worker_name": self.worker_addr, + "queue_length": self.get_queue_length(), + }, + timeout=5, + ) + exist = ret.json()["exist"] + break + except requests.exceptions.RequestException as e: + logger.error(f"heart beat error: {e}") + time.sleep(5) + + if not exist: + self.register_to_controller() + + def get_queue_length(self): + if ( + self.semaphore is None + or self.semaphore._value is None + or self.semaphore._waiters is None + ): + return 0 + else: + return ( + self.limit_worker_concurrency + - self.semaphore._value + + len(self.semaphore._waiters) + ) + + def get_status(self): + return { + "model_names": self.model_names, + "speed": 1, + "queue_length": self.get_queue_length(), + } + + def count_token(self, params): + prompt = params["prompt"] + input_ids = self.tokenizer(prompt).input_ids + input_echo_len = len(input_ids) + + ret = { + "count": input_echo_len, + "error_code": 0, + } + return ret + + def get_conv_template(self): + return {"conv": self.conv} + + +class ModelWorker(BaseModelWorker): + def __init__( + self, + controller_addr: str, + worker_addr: str, + worker_id: str, + model_path: str, + model_names: List[str], + limit_worker_concurrency: int, + no_register: bool, + device: str, + num_gpus: int, + max_gpu_memory: str, + load_8bit: bool = False, + cpu_offloading: bool = False, + gptq_ckpt: str = None, + gptq_wbits: int = None, + gptq_groupsize: int = None, + gptq_act_order: bool = None, + awq_ckpt: str = None, + awq_wbits: int = None, + awq_groupsize: int = None, + revision: str = None, + stream_interval: int = 2, + conv_template: str = None, + temperature: float = 0.7, + repetition_penalty: float = 1.0, + max_new_tokens: int = 512, + prompt_file: str = None, + router_file: str = None, + ): + super().__init__( + controller_addr, + worker_addr, + worker_id, + model_path, + model_names, + limit_worker_concurrency, + ) + + logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...") + self._model = FastChatModel( + model_path=model_path, + device=device, + gpus=None, + num_gpus=num_gpus, + max_gpu_memory=max_gpu_memory, + load_8bit=load_8bit, + cpu_offloading=cpu_offloading, + gptq_ckpt=gptq_ckpt, + gptq_wbits=gptq_wbits, + gptq_groupsize=gptq_groupsize, + gptq_act_order=gptq_act_order, + awq_ckpt=awq_ckpt, + awq_wbits=awq_wbits, + awq_groupsize=awq_groupsize, + conv_template=conv_template, + temperature=temperature, + repetition_penalty=repetition_penalty, + max_new_tokens=max_new_tokens, + revision=revision, + ) + self.tokenizer = self._model.tokenizer + + logger.info("Loading Scheduler...") + if router_file is not None: + # SoT-R + self.model_names = [ + model_name + " (SoT-R)" for model_name in self.model_names + ] + self.scheduler = RouterOutlineBatchScheduler( + model=self._model, + router_name_or_path=router_file, + naive_prompt_file=None, + outline_prompt_file=prompt_file, + ) + elif prompt_file is not None: + # SoT + self.model_names = [ + model_name + " (SoT)" for model_name in self.model_names + ] + self.scheduler = OutlineBatchScheduler( + prompt_file=prompt_file, model=self._model + ) + else: + # Normal + self.model_names = [ + model_name + " (Normal)" for model_name in self.model_names + ] + self.scheduler = NaiveScheduler(model=self._model) + + if not no_register: + self.init_heart_beat() + + def generate_stream_gate(self, params): + self.call_ct += 1 + request = params["prompt"] + self._model.set_params( + params["temperature"], + params["repetition_penalty"], + params["max_new_tokens"], + ) + self.scheduler.set_model(self._model) + + starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event( + enable_timing=True + ) + starter.record() + torch.cuda.reset_peak_memory_stats() + + try: + for output in self.scheduler.get_response(request, stream=True): + ret = { + "text": output["text"], + "error_code": 0, + } + if "usage" in output: + ret["usage"] = output["usage"] + if "finish_reason" in output: + ret["finish_reason"] = output["finish_reason"] + if "logprobs" in output: + ret["logprobs"] = output["logprobs"] + yield json.dumps(ret).encode() + b"\0" + except torch.cuda.OutOfMemoryError as e: + ret = { + "text": f"{SERVER_ERROR_MSG}\n\n({e})", + "error_code": ErrorCode.CUDA_OUT_OF_MEMORY, + } + yield json.dumps(ret).encode() + b"\0" + except (ValueError, RuntimeError) as e: + ret = { + "text": f"{SERVER_ERROR_MSG}\n\n({e})", + "error_code": ErrorCode.INTERNAL_ERROR, + } + yield json.dumps(ret).encode() + b"\0" + + ender.record() + torch.cuda.synchronize() + tim = starter.elapsed_time(ender) + mem = torch.cuda.max_memory_allocated() + + token_size = self.count_token({"prompt": ret["text"]})["count"] + + ret["meta_info"] = ( + "Generation Time: {:.2f}s".format(tim / 1000) + + "\n" + + "Memory Usage: {:.1f} GB".format(mem / 1.0 / 1024**3) + + "\n" + + "Token Size: {}".format(token_size) + ) + yield json.dumps(ret).encode() + b"\0" + + def generate_gate(self, params): + for x in self.generate_stream_gate(params): + pass + return json.loads(x[:-1].decode()) + + @torch.inference_mode() + def get_embeddings(self, params): + self.call_ct += 1 + + try: + tokenizer = self.tokenizer + is_llama = "llama" in str( + type(self.model) + ) # llama supports batch inference + is_chatglm = "chatglm" in str(type(self.model)) + is_t5 = "t5" in str(type(self.model)) + if is_llama: + encoding = tokenizer.batch_encode_plus( + params["input"], padding=True, return_tensors="pt" + ) + input_ids = encoding["input_ids"].to(self.device) + attention_mask = encoding["attention_mask"].to(self.device) + model_output = self.model( + input_ids, attention_mask, output_hidden_states=True + ) + data = model_output.hidden_states[-1] + mask = attention_mask.unsqueeze(-1).expand(data.size()).float() + masked_embeddings = data * mask + sum_embeddings = torch.sum(masked_embeddings, dim=1) + seq_length = torch.sum(mask, dim=1) + embedding = sum_embeddings / seq_length + normalized_embeddings = F.normalize(embedding, p=2, dim=1) + ret = { + "embedding": normalized_embeddings.tolist(), + "token_num": torch.sum(attention_mask).item(), + } + else: + embedding = [] + token_num = 0 + for text in params["input"]: + input_ids = tokenizer.encode(text, return_tensors="pt").to( + self.device + ) + if is_t5: + model_output = self.model( + input_ids, decoder_input_ids=input_ids + ) + else: + model_output = self.model(input_ids, output_hidden_states=True) + if is_chatglm: + data = (model_output.hidden_states[-1].transpose(0, 1))[0] + elif is_t5: + data = model_output.encoder_last_hidden_state[0] + else: + data = model_output.hidden_states[-1][0] + data = F.normalize(torch.mean(data, dim=0), p=2, dim=0) + embedding.append(data.tolist()) + token_num += len(input_ids[0]) + ret = { + "embedding": embedding, + "token_num": token_num, + } + except torch.cuda.OutOfMemoryError as e: + ret = { + "text": f"{SERVER_ERROR_MSG}\n\n({e})", + "error_code": ErrorCode.CUDA_OUT_OF_MEMORY, + } + except (ValueError, RuntimeError) as e: + ret = { + "text": f"{SERVER_ERROR_MSG}\n\n({e})", + "error_code": ErrorCode.INTERNAL_ERROR, + } + return ret + + +def release_worker_semaphore(): + worker.semaphore.release() + + +def acquire_worker_semaphore(): + if worker.semaphore is None: + worker.semaphore = asyncio.Semaphore(worker.limit_worker_concurrency) + return worker.semaphore.acquire() + + +def create_background_tasks(): + background_tasks = BackgroundTasks() + background_tasks.add_task(release_worker_semaphore) + return background_tasks + + +@app.post("/worker_generate_stream") +async def api_generate_stream(request: Request): + params = await request.json() + await acquire_worker_semaphore() + generator = worker.generate_stream_gate(params) + background_tasks = create_background_tasks() + return StreamingResponse(generator, background=background_tasks) + + +@app.post("/worker_generate") +async def api_generate(request: Request): + params = await request.json() + await acquire_worker_semaphore() + output = worker.generate_gate(params) + release_worker_semaphore() + return JSONResponse(output) + + +@app.post("/worker_get_embeddings") +async def api_get_embeddings(request: Request): + params = await request.json() + await acquire_worker_semaphore() + embedding = worker.get_embeddings(params) + release_worker_semaphore() + return JSONResponse(content=embedding) + + +@app.post("/worker_get_status") +async def api_get_status(request: Request): + return worker.get_status() + + +@app.post("/count_token") +async def api_count_token(request: Request): + params = await request.json() + return worker.count_token(params) + + +@app.post("/worker_get_conv_template") +async def api_get_conv(request: Request): + return worker.get_conv_template() + + +@app.post("/model_details") +async def api_model_details(request: Request): + return {"context_length": worker.context_len} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--host", type=str, default="0.0.0.0") + parser.add_argument("--port", type=int, default=21002) + parser.add_argument("--worker-address", type=str, default="http://0.0.0.0:21002") + parser.add_argument( + "--controller-address", type=str, default="http://0.0.0.0:21001" + ) + add_model_args(parser) + parser.add_argument( + "--model-names", + type=lambda s: s.split(","), + help="Optional display comma separated names", + ) + parser.add_argument( + "--limit-worker-concurrency", + type=int, + default=5, + help="Limit the model concurrency to prevent OOM.", + ) + parser.add_argument("--stream-interval", type=int, default=2) + parser.add_argument("--no-register", action="store_true") + parser.add_argument( + "--sot", + default=None, + help=( + "The SoT prompt file path. Default to None, meaning the normal decoding" + " mode." + ), + ) + parser.add_argument( + "--sotr", + default=None, + help=( + "The SoT-R router file path. Default to None, meaning not to use the router" + ), + ) + + args = parser.parse_args() + logger.info(f"args: {args}") + + if args.gpus: + if len(args.gpus.split(",")) < args.num_gpus: + raise ValueError( + f"Larger --num-gpus ({args.num_gpus}) than --gpus {args.gpus}!" + ) + os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus + + worker = ModelWorker( + args.controller_address, + args.worker_address, + worker_id, + args.model_path, + args.model_names, + args.limit_worker_concurrency, + no_register=args.no_register, + device=args.device, + num_gpus=args.num_gpus, + max_gpu_memory=args.max_gpu_memory, + load_8bit=args.load_8bit, + cpu_offloading=args.cpu_offloading, + gptq_ckpt=args.gptq_ckpt, + gptq_wbits=args.gptq_wbits, + gptq_groupsize=args.gptq_groupsize, + gptq_act_order=args.gptq_act_order, + awq_ckpt=args.awq_ckpt, + awq_wbits=args.awq_wbits, + awq_groupsize=args.awq_groupsize, + revision=args.revision, + stream_interval=args.stream_interval, + prompt_file=args.sot, + router_file=args.sotr, + ) + + uvicorn.run(app, host=args.host, port=args.port, log_level="info") diff --git a/prompts/router_gpt4.json b/prompts/router_gpt4.json new file mode 100644 index 0000000..1e280bd --- /dev/null +++ b/prompts/router_gpt4.json @@ -0,0 +1 @@ +{"prompt": "Question: {request}\n\nHow would you like to answer the question?\nA. Organize the answer as a list of points or perspectives (in the format of 1., 2., 3., etc.), and the points or perspectives can be answered independently without referring to the contents of the previous points.\nB. Organize the answer as a list of points or perspectives (in the format of 1., 2., 3., etc.), and the contents of later points or perspectives cannot be answered independently without referring to the contents of the previous ones.\nC. Do not organize the answer as a list of points or perspectives.\n\nJust say A, B, or C. Do not explain. Do not provide an answer to the question."} diff --git a/prompts/sot_chatgpt.json b/prompts/sot_chatgpt.json new file mode 100644 index 0000000..44be0ba --- /dev/null +++ b/prompts/sot_chatgpt.json @@ -0,0 +1 @@ +{"point_prompt": "You're responsible for continuing the writing of one and only one point in the overall answer to the following question.\n\n{request}\n\nThe skeleton of the answer is\n\n{outline}\n\nContinue and only continue the writing of point {point}. Write it **very shortly** in 1~2 sentence and do not continue with other points! [ROLESWITCHING assistant:]{point}. {point_outline}", "outline_prompt": "You're an organizer responsible for only giving the skeleton (not the full content) for answering the question. Provide the skeleton in a list of points (numbered 1., 2., 3., etc.) to answer the question. Instead of writing a full sentence, each skeleton point should be very short with only 3~5 words. Generally, the skeleton should have 3~10 points.\n\nQuestion:\nWhat are the typical types of Chinese dishes?\nSkeleton:\n1. Dumplings. \n2. Noodles. \n3. Dim Sum. \n4. Hot Pot. \n5. Wonton. \n6. Ma Po Tofu. \n7. Char Siu. \n8. Fried Rice. \n\nQuestion:\nWhat are some practical tips for individuals to reduce their carbon emissions?\nSkeleton:\n1. Energy conservation. \n2. Efficient transportation. \n3. Home energy efficiency. \n4. Reduce water consumption. \n5. Sustainable diet. \n6. Sustainable travel. \n\nNow, please provide the skeleton for the following question.\n{request}\nSkeleton:\n [ROLESWITCHING assistant:] 1."} diff --git a/prompts/sot_claude.json b/prompts/sot_claude.json new file mode 100644 index 0000000..b841588 --- /dev/null +++ b/prompts/sot_claude.json @@ -0,0 +1 @@ +{"point_prompt": "You're responsible for continuing the writing of one and only one point in the overall answer to the following question.\n\n{request}\n\nThe skeleton of the answer is\n\n{outline}\n\nContinue and only continue the writing of point {point}. Write it in 1~2 sentence and do not continue with other points!\n\nPlease start your answer from \"{point}. {point_outline}\" and do not output other things before that", "outline_prompt": "You're an organizer responsible for only giving the skeleton (not the full content) for answering the question. Provide the skeleton in a list of points (numbered 1., 2., 3., etc.) to answer the question. Instead of writing a full sentence, each skeleton point should be very short with only 3~5 words. Generally, the skeleton should have 3~10 points.\n\nQuestion:\nWhat are the typical types of Chinese dishes?\nSkeleton:\n1. Dumplings. \n2. Noodles. \n3. Dim Sum. \n4. Hot Pot. \n5. Wonton. \n6. Ma Po Tofu. \n7. Char Siu. \n8. Fried Rice. \n\nQuestion:\nWhat are some practical tips for individuals to reduce their carbon emissions?\nSkeleton:\n1. Energy conservation. \n2. Efficient transportation. \n3. Home energy efficiency. \n4. Reduce water consumption. \n5. Sustainable diet. \n6. Sustainable travel. \n\nNow, please provide the skeleton for the following question.\n{request}\nSkeleton:\n\nPlease start your answer from \"1. \" and do not output other things before that"} diff --git a/prompts/sot_gpt4.json b/prompts/sot_gpt4.json new file mode 100644 index 0000000..06c5f54 --- /dev/null +++ b/prompts/sot_gpt4.json @@ -0,0 +1 @@ +{"point_prompt": "You're responsible for continuing the writing of one and only one point in the overall answer to the following question.\n\n{request}\n\nThe skeleton of the answer is\n\n{outline}\n\nContinue and only continue the writing of point {point}. Write it in 1~2 sentence and do not continue with other points!\n\nPlease start your answer from \"{point}. {point_outline}\" and do not output other things before that", "outline_prompt": "You're an organizer responsible for only giving the skeleton (not the full content) for answering the question. Provide the skeleton in a list of points (numbered 1., 2., 3., etc.) to answer the question. Instead of writing a full sentence, each skeleton point should be very short with only 3~5 words. Generally, the skeleton should have 3~10 points. Now, please provide the skeleton for the following question.\n{request}\nSkeleton:\n\nPlease start your answer from \"1. \" and do not output other things before that"} diff --git a/prompts/sot_opensource.json b/prompts/sot_opensource.json new file mode 100644 index 0000000..44be0ba --- /dev/null +++ b/prompts/sot_opensource.json @@ -0,0 +1 @@ +{"point_prompt": "You're responsible for continuing the writing of one and only one point in the overall answer to the following question.\n\n{request}\n\nThe skeleton of the answer is\n\n{outline}\n\nContinue and only continue the writing of point {point}. Write it **very shortly** in 1~2 sentence and do not continue with other points! [ROLESWITCHING assistant:]{point}. {point_outline}", "outline_prompt": "You're an organizer responsible for only giving the skeleton (not the full content) for answering the question. Provide the skeleton in a list of points (numbered 1., 2., 3., etc.) to answer the question. Instead of writing a full sentence, each skeleton point should be very short with only 3~5 words. Generally, the skeleton should have 3~10 points.\n\nQuestion:\nWhat are the typical types of Chinese dishes?\nSkeleton:\n1. Dumplings. \n2. Noodles. \n3. Dim Sum. \n4. Hot Pot. \n5. Wonton. \n6. Ma Po Tofu. \n7. Char Siu. \n8. Fried Rice. \n\nQuestion:\nWhat are some practical tips for individuals to reduce their carbon emissions?\nSkeleton:\n1. Energy conservation. \n2. Efficient transportation. \n3. Home energy efficiency. \n4. Reduce water consumption. \n5. Sustainable diet. \n6. Sustainable travel. \n\nNow, please provide the skeleton for the following question.\n{request}\nSkeleton:\n [ROLESWITCHING assistant:] 1."} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..c8765c1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,37 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "sot" +version = "0.0.1" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", +] +dependencies = [ + "tqdm", + "pandas", + "openai", "tenacity", # API model + "fschat==0.2.26", "transformers", "accelerate", # open-source model (based on fastchat and huggingface Transformer) + "rwkv", "ninja", # rwkv-4-raven; rwkv-4-raven also needs `nvcc` to be installed and can be found in $PATH + "einops", # mosaicml/mpt-7b-chat + "cpm_kernels", # THUDM/chatglm-6b + "termcolor", # prompt_eng_main.py + "ipdb", # prompt_eng_main.py + "ipython", # prompt_eng_main.py + "gradio", +] + +[project.optional-dependencies] +dev = ["pre-commit", "black"] +# nlgeval = ["nltk", "absl-py", "rouge-score", "bert_score"] + +[project.urls] +"Homepage" = "https://sites.google.com/view/sot-llm" + +[tool.setuptools.packages.find] +exclude = ["docs", "dist*", "scripts*", "tests*", "data*", "results*"] + +[tool.wheel] +exclude = ["docs", "dist*", "scripts*", "tests*", "data*", "results*"] diff --git a/scripts/debug_prompt.sh b/scripts/debug_prompt.sh new file mode 100755 index 0000000..3b2fa1d --- /dev/null +++ b/scripts/debug_prompt.sh @@ -0,0 +1,9 @@ +model_path=${1} +shift 1 +model_suffix=${model_path##*/} +cur_time=$(date +"%Y-%m-%d--%H-%M") +res_file=results/${model_suffix}-${cur_time}.log + +echo "Test ${model_path}; Log will be saved to ${res_file}" + +python sot/prompt_eng_main.py --model fastchat --output-log ${res_file} --model-path ${model_path} --stream $@ diff --git a/scripts/vicuna/dump/claude_slack_naive.sh b/scripts/vicuna/dump/claude_slack_naive.sh new file mode 100755 index 0000000..7c3b891 --- /dev/null +++ b/scripts/vicuna/dump/claude_slack_naive.sh @@ -0,0 +1,6 @@ +python sot/main.py \ +--model claude_slack \ +--scheduler naive \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_claude_slack_naive \ +--channel_name test diff --git a/scripts/vicuna/dump/claude_slack_outline.sh b/scripts/vicuna/dump/claude_slack_outline.sh new file mode 100755 index 0000000..a3b2064 --- /dev/null +++ b/scripts/vicuna/dump/claude_slack_outline.sh @@ -0,0 +1,7 @@ +python sot/main.py \ +--model claude_slack \ +--scheduler outline \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_claude_slack_outline \ +--channel_name test2 \ +--prompt-file prompts/sot_claude.json diff --git a/scripts/vicuna/dump/gpt3.5_naive.sh b/scripts/vicuna/dump/gpt3.5_naive.sh new file mode 100755 index 0000000..6a8719c --- /dev/null +++ b/scripts/vicuna/dump/gpt3.5_naive.sh @@ -0,0 +1,15 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_gpt3.5_naive \ +--api-type azure \ +--api-base ${API_BASE} \ +--api-version 2023-03-15-preview \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--engine ${ENGINE} \ +--system-message 'You are an AI assistant that helps people find information.' \ diff --git a/scripts/vicuna/dump/gpt3.5_outline.sh b/scripts/vicuna/dump/gpt3.5_outline.sh new file mode 100755 index 0000000..e726de8 --- /dev/null +++ b/scripts/vicuna/dump/gpt3.5_outline.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler outline \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_gpt3.5_outline \ +--api-type azure \ +--api-base ${API_BASE} \ +--api-version 2023-03-15-preview \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--engine ${ENGINE} \ +--system-message 'You are an AI assistant that helps people find information.' \ +--prompt-file prompts/sot_chatgpt.json diff --git a/scripts/vicuna/dump/gpt4_naive.sh b/scripts/vicuna/dump/gpt4_naive.sh new file mode 100755 index 0000000..7914266 --- /dev/null +++ b/scripts/vicuna/dump/gpt4_naive.sh @@ -0,0 +1,15 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_gpt4_naive \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--timeout 240 diff --git a/scripts/vicuna/dump/gpt4_outline.sh b/scripts/vicuna/dump/gpt4_outline.sh new file mode 100755 index 0000000..9159117 --- /dev/null +++ b/scripts/vicuna/dump/gpt4_outline.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler outline \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_gpt4_outline \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--prompt-file prompts/sot_gpt4.json \ +--timeout 240 diff --git a/scripts/vicuna/dump/gpt4_router.sh b/scripts/vicuna/dump/gpt4_router.sh new file mode 100755 index 0000000..ab29c61 --- /dev/null +++ b/scripts/vicuna/dump/gpt4_router.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/vicuna/data.csv \ +--output-folder results/vicuna/vicuna_gpt4_router \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 10 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--timeout 240 \ +--prompt-file prompts/router_gpt4.json diff --git a/scripts/vicuna/dump/opensource_naive.py b/scripts/vicuna/dump/opensource_naive.py new file mode 100644 index 0000000..ce43d93 --- /dev/null +++ b/scripts/vicuna/dump/opensource_naive.py @@ -0,0 +1,42 @@ +import os +import subprocess + + +MODELS = [ + ("llama_v2_7b", "meta-llama/Llama-2-7b-chat-hf", 1), + ("llama_v2_13b", "meta-llama/Llama-2-13b-chat-hf", 2), + ("openchat", "openchat/openchat", 3), + ("stable-vicuna", "TheBloke/stable-vicuna-13B-HF", 3), + ("ultralm_13b", "TheBloke/UltraLM-13B-fp16", 3), + ( + "vicuna7b", + "lmsys/vicuna-7b-v1.1", + 1, + ), + ("vicuna7bv13", "lmsys/vicuna-7b-v1.3", 1), + ("vicuna13bv13", "lmsys/vicuna-13b-v1.3", 2), + ("vicuna33bv13", "lmsys/vicuna-33b-v1.3", 5), +] + +OUTPUT_FOLDER = "results/vicuna/vicuna_{model_name}_naive" + +COMMAND = ( + "python sot/main.py --model fastchat --scheduler naive " + "--data-path data/vicuna/data.csv --output-folder {output_folder} " + "--model-path {model_path} --num-gpus {num_gpus}" +) + + +if __name__ == "__main__": + for model_name, path, num_gpus in MODELS: + output_folder = OUTPUT_FOLDER.format(model_name=model_name) + if os.path.exists(output_folder): + print(f"Skipping {model_name}") + else: + print(f"Running {model_name}") + command = COMMAND.format( + output_folder=output_folder, model_path=path, num_gpus=num_gpus + ) + print(command) + process = subprocess.Popen(command.split()) + process.wait() diff --git a/scripts/vicuna/dump/opensource_outline.py b/scripts/vicuna/dump/opensource_outline.py new file mode 100644 index 0000000..14f52bc --- /dev/null +++ b/scripts/vicuna/dump/opensource_outline.py @@ -0,0 +1,43 @@ +import os +import subprocess + + +MODELS = [ + ("llama_v2_7b", "meta-llama/Llama-2-7b-chat-hf", 1), + ("llama_v2_13b", "meta-llama/Llama-2-13b-chat-hf", 2), + ("openchat", "openchat/openchat", 4), + ("stable-vicuna", "TheBloke/stable-vicuna-13B-HF", 4), + ("ultralm_13b", "TheBloke/UltraLM-13B-fp16", 4), + ( + "vicuna7b", + "lmsys/vicuna-7b-v1.1", + 1, + ), + ("vicuna7bv13", "lmsys/vicuna-7b-v1.3", 1), + ("vicuna13bv13", "lmsys/vicuna-13b-v1.3", 4), + ("vicuna33bv13", "lmsys/vicuna-33b-v1.3", 5), +] + +OUTPUT_FOLDER = "results/vicuna/vicuna_{model_name}_outline" + +COMMAND = ( + "python sot/main.py --model fastchat --scheduler outline " + "--data-path data/vicuna/data.csv --output-folder {output_folder} " + "--model-path {model_path} --num-gpus {num_gpus} " + "--prompt-file prompts/sot_opensource.json" +) + + +if __name__ == "__main__": + for model_name, path, num_gpus in MODELS: + output_folder = OUTPUT_FOLDER.format(model_name=model_name) + if os.path.exists(output_folder): + print(f"Skipping {model_name}") + else: + print(f"Running {model_name}") + command = COMMAND.format( + output_folder=output_folder, model_path=path, num_gpus=num_gpus + ) + print(command) + process = subprocess.Popen(command.split()) + process.wait() diff --git a/scripts/vicuna/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh b/scripts/vicuna/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh new file mode 100755 index 0000000..2f5d16d --- /dev/null +++ b/scripts/vicuna/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh @@ -0,0 +1,20 @@ +for model in llama_v2_7b llama_v2_13b openchat stable-vicuna ultralm_13b vicuna7b vicuna7bv13 vicuna13bv13 vicuna33bv13 gpt3.5 claude_slack gpt4 +do + +python sot/fastchat_evaluation_for_vicuna_bidir.py \ +--model openai \ +--output-folder results/vicuna/vicuna_${model}_outline/compare_to_naive_by_gpt4 \ +--answer-1-file results/vicuna/vicuna_${model}_outline/data.csv \ +--answer-2-file results/vicuna/vicuna_${model}_naive/data.csv \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.2 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--timeout 240 + +done \ No newline at end of file diff --git a/scripts/vicuna/evaluate/evaluation_ALL_llm_zoo_gpt4_alldir.sh b/scripts/vicuna/evaluate/evaluation_ALL_llm_zoo_gpt4_alldir.sh new file mode 100755 index 0000000..a1ca9ec --- /dev/null +++ b/scripts/vicuna/evaluate/evaluation_ALL_llm_zoo_gpt4_alldir.sh @@ -0,0 +1,146 @@ +for model in llama_v2_7b llama_v2_13b openchat stable-vicuna ultralm_13b vicuna7b vicuna7bv13 vicuna13bv13 vicuna33bv13 gpt3.5 claude_slack gpt4 +do + +RESULT_FOLDER=results/vicuna/vicuna_${model}_outline/compare_to_naive_by_gpt4 +ANSWER_FILE_1=results/vicuna/vicuna_${model}_outline/data.csv +ANSWER_FILE_2=results/vicuna/vicuna_${model}_naive/data.csv + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_general.csv \ +--log-filename llm_zoo_evaluation_general_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "We would like to request your feedback on the performance of {num_str} AI assistants in response to the user question displayed above. +Please evaluate the given four aspects: helpfulness, relevance, accuracy, level of details of their responses. +Please first clarify how each response achieves each aspect respectively. +Then, provide a comparison on the overall performance among Assistant 1 - Assistant {num}, and you need to clarify which one is better than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. The order should be consistent to your comparison. If there is not comparision that one is better, it is assumed they have equivalent overall performance ('=')." +--timeout 240 + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_relevance.csv \ +--log-filename llm_zoo_evaluation_relevance_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "Relevance: The response should be closely related to the question and answer the question accurately with sufficient details without repetition or redundancy. The more relevant they are, the better. +Please evaluate the relevance of {num_str} AI assistants in response to the user question displayed above. +Please first clarify how each response addresses the question and whether it is accurate respectively. +Then, provide a comparison on relevance among Assistant 1 - Assistant {num}, and you need to clarify which one is more relevant than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. The order should be consistent to your comparison. If there is not comparision that one is more relevant, it is assumed they have equivalent relevance ('=')." \ +--timeout 240 + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_diversity.csv \ +--log-filename llm_zoo_evaluation_diversity_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "Diversity: The response should be comprehensive and provide a range of information that is not limited to a single perspective. More perspectives are better. +Please evaluate the diversity of {num_str} AI assistants in response to the user question displayed above. +Please first clarify which perspectives and aspects they consider and the diversity they explore respectively. +Then, provide a comparison on diversity among Assistant 1 - Assistant {num}, and you need to clarify which one is more diverse than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. The order should be consistent to your comparison. If there is not comparision that one is more diverse, it is assumed they have equivalent diversity ('=')." \ +--timeout 240 + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_coherence.csv \ +--log-filename llm_zoo_evaluation_coherence_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "Coherence: The response should be coherent and flow logically from one point to the next that is easy to read and understand without major gaps or inconsistencies. The more coherent they are, the better. +Please evaluate the coherence of {num_str} AI assistants in response to the user question displayed above. +Please first clarify to what degree each response flows smoothly from one point to another respectively. +Then, provide a comparison on coherence among Assistant 1 - Assistant {num}, and you need to clarify which one is more coherent than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. If there is not comparision that one is more coherent, it is assumed they have equivalent coherence ('=')." \ +--timeout 240 + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_immersion.csv \ +--log-filename llm_zoo_evaluation_immersion_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "Immersion: The response should act like the assigned role using the tone, manner and vocabulary the role would use. The more assistant-like tones, the worse. The more in-character, the better. +Please evaluate the Immersion of {num_str} AI assistants in response to the user question displayed above. +Please first clarify how they pretend to be the role and to what extend they have successfully simulated it respectively. +Then, provide a comparison on Immersion among Assistant 1 - Assistant {num}, and you need to clarify which one is more in-character than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. The order should be consistent to your comparison. If there is not comparision that one is more in-character, it is assumed they have equivalent immersion ('=')." \ +--timeout 240 + +python sot/llm_zoo_evaluation_alldir.py \ +--model openai \ +--output-data-filename llm_zoo_evaluation_integrity.csv \ +--log-filename llm_zoo_evaluation_integrity_log.log \ +--output-folder ${RESULT_FOLDER} \ +--answer-file ${ANSWER_FILE_1} \ +--answer-file ${ANSWER_FILE_2} \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.0 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--prompt "Integrity: The response should be ethical and moral soundness and adherence to principles and values, while avoiding stereotypes, offensive language, misleading information, or harmful suggestions that can negatively impact individuals, groups, or society. The more immoral or harmful language they produce, the worse. +Please integrity the relevance of {num_str} AI assistants in response to the user question displayed above. +Please first clarify whether each response produces inmmoral or harmful language, and to what degree they are unethical respectively. +Then, provide a comparison on integrity among Assistant 1 - Assistant {num}, and you need to clarify which one is less moral than or equal to another. Avoid any potential bias and ensuring that the order in which the responses were presented does not affect your judgment. +In the last line, order the {num_str} assistants. Please output a single line ordering Assistant 1 - Assistant {num}, where '>' means 'is better than' and '=' means 'is equal to'. The order should be consistent to your comparison. If there is not comparision that one is less moral, it is assumed they have equivalent integrity ('=')." \ +--timeout 240 + +done diff --git a/scripts/wizardlm/dump/claude_slack_naive.sh b/scripts/wizardlm/dump/claude_slack_naive.sh new file mode 100755 index 0000000..da92866 --- /dev/null +++ b/scripts/wizardlm/dump/claude_slack_naive.sh @@ -0,0 +1,6 @@ +python sot/main.py \ +--model claude_slack \ +--scheduler naive \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_claude_slack_naive \ +--channel_name test diff --git a/scripts/wizardlm/dump/claude_slack_outline.sh b/scripts/wizardlm/dump/claude_slack_outline.sh new file mode 100755 index 0000000..99d0e61 --- /dev/null +++ b/scripts/wizardlm/dump/claude_slack_outline.sh @@ -0,0 +1,7 @@ +python sot/main.py \ +--model claude_slack \ +--scheduler outline \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_claude_slack_outline \ +--channel_name test2 \ +--prompt-file prompts/sot_claude.json diff --git a/scripts/wizardlm/dump/gpt3.5_naive.sh b/scripts/wizardlm/dump/gpt3.5_naive.sh new file mode 100755 index 0000000..1d9cf7e --- /dev/null +++ b/scripts/wizardlm/dump/gpt3.5_naive.sh @@ -0,0 +1,15 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_gpt3.5_naive \ +--api-type azure \ +--api-base ${API_BASE} \ +--api-version 2023-03-15-preview \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--engine ${ENGINE} \ +--system-message 'You are an AI assistant that helps people find information.' \ diff --git a/scripts/wizardlm/dump/gpt3.5_outline.sh b/scripts/wizardlm/dump/gpt3.5_outline.sh new file mode 100755 index 0000000..981da92 --- /dev/null +++ b/scripts/wizardlm/dump/gpt3.5_outline.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler outline \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_gpt3.5_outline \ +--api-type azure \ +--api-base ${API_BASE} \ +--api-version 2023-03-15-preview \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--engine ${ENGINE} \ +--system-message 'You are an AI assistant that helps people find information.' \ +--prompt-file prompts/sot_chatgpt.json diff --git a/scripts/wizardlm/dump/gpt4_naive.sh b/scripts/wizardlm/dump/gpt4_naive.sh new file mode 100755 index 0000000..b03eb8e --- /dev/null +++ b/scripts/wizardlm/dump/gpt4_naive.sh @@ -0,0 +1,15 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_gpt4_naive \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--timeout 240 diff --git a/scripts/wizardlm/dump/gpt4_outline.sh b/scripts/wizardlm/dump/gpt4_outline.sh new file mode 100755 index 0000000..683d3cb --- /dev/null +++ b/scripts/wizardlm/dump/gpt4_outline.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler outline \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_gpt4_outline \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--prompt-file prompts/sot_gpt4.json \ +--timeout 240 diff --git a/scripts/wizardlm/dump/gpt4_router.sh b/scripts/wizardlm/dump/gpt4_router.sh new file mode 100755 index 0000000..6a8103f --- /dev/null +++ b/scripts/wizardlm/dump/gpt4_router.sh @@ -0,0 +1,16 @@ +python sot/main.py \ +--model openai \ +--scheduler naive \ +--data-path data/wizardlm/data.csv \ +--output-folder results/wizardlm/wizardlm_gpt4_router \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.7 \ +--max-tokens 10 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are an AI assistant that helps people find information.' \ +--timeout 240 \ +--prompt-file prompts/router_gpt4.json diff --git a/scripts/wizardlm/dump/opensource_naive.py b/scripts/wizardlm/dump/opensource_naive.py new file mode 100644 index 0000000..edf2644 --- /dev/null +++ b/scripts/wizardlm/dump/opensource_naive.py @@ -0,0 +1,42 @@ +import os +import subprocess + + +MODELS = [ + ("llama_v2_7b", "meta-llama/Llama-2-7b-chat-hf", 1), + ("llama_v2_13b", "meta-llama/Llama-2-13b-chat-hf", 2), + ("openchat", "openchat/openchat", 3), + ("stable-vicuna", "TheBloke/stable-vicuna-13B-HF", 3), + ("ultralm_13b", "TheBloke/UltraLM-13B-fp16", 3), + ( + "vicuna7b", + "lmsys/vicuna-7b-v1.1", + 1, + ), + ("vicuna7bv13", "lmsys/vicuna-7b-v1.3", 1), + ("vicuna13bv13", "lmsys/vicuna-13b-v1.3", 2), + ("vicuna33bv13", "lmsys/vicuna-33b-v1.3", 5), +] + +OUTPUT_FOLDER = "results/wizardlm/wizardlm_{model_name}_naive" + +COMMAND = ( + "python sot/main.py --model fastchat --scheduler naive " + "--data-path data/wizardlm/data.csv --output-folder {output_folder} " + "--model-path {model_path} --num-gpus {num_gpus}" +) + + +if __name__ == "__main__": + for model_name, path, num_gpus in MODELS: + output_folder = OUTPUT_FOLDER.format(model_name=model_name) + if os.path.exists(output_folder): + print(f"Skipping {model_name}") + else: + print(f"Running {model_name}") + command = COMMAND.format( + output_folder=output_folder, model_path=path, num_gpus=num_gpus + ) + print(command) + process = subprocess.Popen(command.split()) + process.wait() diff --git a/scripts/wizardlm/dump/opensource_outline.py b/scripts/wizardlm/dump/opensource_outline.py new file mode 100644 index 0000000..8ea24f3 --- /dev/null +++ b/scripts/wizardlm/dump/opensource_outline.py @@ -0,0 +1,43 @@ +import os +import subprocess + + +MODELS = [ + ("llama_v2_7b", "meta-llama/Llama-2-7b-chat-hf", 1), + ("llama_v2_13b", "meta-llama/Llama-2-13b-chat-hf", 2), + ("openchat", "openchat/openchat", 4), + ("stable-vicuna", "TheBloke/stable-vicuna-13B-HF", 4), + ("ultralm_13b", "TheBloke/UltraLM-13B-fp16", 4), + ( + "vicuna7b", + "lmsys/vicuna-7b-v1.1", + 1, + ), + ("vicuna7bv13", "lmsys/vicuna-7b-v1.3", 1), + ("vicuna13bv13", "lmsys/vicuna-13b-v1.3", 4), + ("vicuna33bv13", "lmsys/vicuna-33b-v1.3", 5), +] + +OUTPUT_FOLDER = "results/wizardlm/wizardlm_{model_name}_outline" + +COMMAND = ( + "python sot/main.py --model fastchat --scheduler outline " + "--data-path data/wizardlm/data.csv --output-folder {output_folder} " + "--model-path {model_path} --num-gpus {num_gpus} " + "--prompt-file prompts/sot_opensource.json" +) + + +if __name__ == "__main__": + for model_name, path, num_gpus in MODELS: + output_folder = OUTPUT_FOLDER.format(model_name=model_name) + if os.path.exists(output_folder): + print(f"Skipping {model_name}") + else: + print(f"Running {model_name}") + command = COMMAND.format( + output_folder=output_folder, model_path=path, num_gpus=num_gpus + ) + print(command) + process = subprocess.Popen(command.split()) + process.wait() diff --git a/scripts/wizardlm/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh b/scripts/wizardlm/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh new file mode 100755 index 0000000..f954e4f --- /dev/null +++ b/scripts/wizardlm/evaluate/evaluation_ALL_fastchat_gpt4_birdir.sh @@ -0,0 +1,40 @@ +for model in llama_v2_7b llama_v2_13b openchat stable-vicuna ultralm_13b vicuna7b vicuna7bv13 vicuna13bv13 vicuna33bv13 gpt3.5 claude_slack gpt4 +do + +python sot/fastchat_evaluation_bidir.py \ +--model openai \ +--output-folder results/wizardlm/wizardlm_${model}_outline/compare_to_naive_by_gpt4 \ +--answer-1-file results/wizardlm/wizardlm_${model}_outline/data.csv \ +--answer-2-file results/wizardlm/wizardlm_${model}_naive/data.csv \ +--template "[Question] +{question} + +[The Start of Assistant 1's Answer] +{answer_1} + +[The End of Assistant 1's Answer] + +[The Start of Assistant 2's Answer] +{answer_2} + +[The End of Assistant 2's Answer] + +[System] +{prompt} + +" \ +--prompt "We would like to request your feedback on the performance of two AI assistants in response to the user question displayed above. +Please rate the helpfulness, relevance, accuracy, level of details of their responses. Each assistant receives an overall score on a scale of 1 to 10, where a higher score indicates better overall performance. +Please first output a single line containing only two values indicating the scores for Assistant 1 and 2, respectively. The two scores are separated by a space. In the subsequent line, please provide a comprehensive explanation of your evaluation, avoiding any potential bias and ensuring that the order in which the responses were presented does not affect your judgment." \ +--api-type open_ai \ +--api-base https://api.openai.com/v1 \ +--temperature 0.2 \ +--max-tokens 5000 \ +--top-p 0.95 \ +--frequency-penalty 0 \ +--presence-penalty 0 \ +--api-model gpt-4-0613 \ +--system-message 'You are a helpful and precise assistant for checking the quality of the answer.' \ +--timeout 240 + +done diff --git a/sot/__init__.py b/sot/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sot/evaluation/llm_evaluation.py b/sot/evaluation/llm_evaluation.py new file mode 100644 index 0000000..0d3f94e --- /dev/null +++ b/sot/evaluation/llm_evaluation.py @@ -0,0 +1,126 @@ +import logging +import re +import numpy as np + + +def is_float(str): + try: + float(str) + return True + except Exception: + return False + + +def fastchat_evaluation(model, template, question, answer_1, answer_2, prompt): + """ + Based on https://github.com/lm-sys/FastChat/tree/main/fastchat/eval + """ + request = template.format( + question=question, answer_1=answer_1, answer_2=answer_2, prompt=prompt + ) + try: + response = model.get_response([request])[0]["text"] + except Exception as e: + logging.error(f"Exception: {e}") + response = "-2,-2" + score_pair = response.split("\n")[0].replace(",", " ").split(" ") + if len(score_pair) == 2 and is_float(score_pair[0]) and is_float(score_pair[1]): + score_pair = list(map(float, score_pair)) + else: + score_pair = re.findall(r"\(([\d]+\.*[\d]*),\ *([\d]+\.*[\d]*)\)", response) + if len(score_pair) != 1: + logging.error(f"Invalid score pair: {score_pair}") + score_pair = [-1, -1] + else: + score_pair = list(map(float, score_pair[0])) + return { + "score_pair": score_pair, + "response": response, + "evaluation_request": request, + } + + +def llm_zoo_evaluation(model, question, answers, prompt): + """ + Based on https://github.com/FreedomIntelligence/LLMZoo/tree/main/llmzoo/eval + """ + NUM2STR = { + 2: "two", + 3: "three", + 4: "four", + 5: "five", + 6: "six", + 7: "seven", + 8: "eight", + 9: "nine", + 10: "ten", + 20: "twenty", + } + num_answers = len(answers) + num_answers_str = NUM2STR[num_answers] + + prompt = prompt.format(num=num_answers, num_str=num_answers_str) + request = f"[Question]\n{question}\n\n" + request += "\n\n".join( + [ + f"[Assistant {i}]\n{ans}\n\n[End of Assistant {i}]" + for i, ans in enumerate(answers, start=1) + ] + ) + request += "\n\n" + f"[System]\n{prompt}\n\n" + + try: + response = model.get_response([request])[0]["text"] + order = _parse_llm_zoo_order_cot(response, num_answers) + except Exception as e: + logging.error(f"Exception: {e}") + response = "-2,-2" + order = [-2, -2] + + return { + "order": order, + "response": response, + "evaluation_request": request, + } + + +def _parse_llm_zoo_order_cot(review, n_ans): + """ + From: + https://github.com/FreedomIntelligence/LLMZoo/blob/main/llmzoo/eval/eval_gpt_review_all.py + """ + review = re.sub(r">=", ">", review) + review = re.sub(r">>", ">", review) + try: + ls = re.findall(r"(Assistant \d+( [>=] Assistant \d+)+)", review.strip()) + order_texts = [x[0] for x in ls] + idxs = np.where( + np.array( + [len(re.findall(r"Assistant", text)) == n_ans for text in order_texts] + ) + )[0] + if idxs.shape[0] == 0: + return [-1] * n_ans + order_text = order_texts[idxs[0]] + + ordered_assist = [int(x) for x in re.findall(r"\d+", order_text)] + ordered_comp = re.findall(r"[>=]", order_text) + + order = [0] * n_ans + cur_order = 1 + num_eq = 0 + order[ordered_assist[0] - 1] = cur_order + for comp, assist in zip(ordered_comp, ordered_assist[1:]): + if comp == ">": + cur_order += num_eq + 1 + order[assist - 1] = cur_order + num_eq = 0 + else: + order[assist - 1] = cur_order + num_eq += 1 + return order + + except Exception: + # print(e) + # print('error', review) + return [-1] * n_ans diff --git a/sot/fastchat_evaluation_bidir.py b/sot/fastchat_evaluation_bidir.py new file mode 100644 index 0000000..4717e03 --- /dev/null +++ b/sot/fastchat_evaluation_bidir.py @@ -0,0 +1,157 @@ +import argparse +import os +import csv +import json +from tqdm import tqdm +import pandas as pd +import logging + +from models import get_model_class_from_name +from utils.logging import setup_logging +from evaluation.llm_evaluation import fastchat_evaluation + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=str, required=True) + parser.add_argument("--template", type=str, required=True) + parser.add_argument("--prompt", type=str, required=True) + parser.add_argument("--answer-1-file", type=str, required=True) + parser.add_argument("--answer-2-file", type=str, required=True) + parser.add_argument("--output-folder", type=str, required=True) + parser.add_argument( + "--output-data-filename", type=str, default="fastchat_evaluation.csv" + ) + parser.add_argument( + "--log-filename", type=str, default="fastchat_evaluation_log.log" + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Automatically answer yes to all user prompts.", + ) + args, other_args = parser.parse_known_args() + + model_class = get_model_class_from_name(args.model) + model, other_args = model_class.from_command_line_args(other_args) + + if other_args != []: + raise ValueError("Unknown arguments: {}".format(other_args)) + + return args, model + + +def save(file, content): + for i in range(len(content)): + if type(content[i]) != str: + content[i] = json.dumps(content[i]) + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow(content) + + +def evaluation( + model, + answer1_data, + answer2_data, + template, + prompt, + output_data_path, + skip_questions, +): + if answer1_data.shape[0] != answer2_data.shape[0]: + raise ValueError("The number of rows in the two answer files are different.") + + if not os.path.exists(output_data_path): + save( + output_data_path, + [ + "request", + "1_evaluation_request", + "1_evaluation", + "1_score1", + "1_score2", + "2_evaluation_request", + "2_evaluation", + "2_score1", + "2_score2", + ], + ) + + for i in tqdm(range(answer1_data.shape[0])): + request1 = answer1_data.iloc[i]["request"] + request2 = answer2_data.iloc[i]["request"] + if request1 != request2: + raise ValueError( + f"The requests at line {i + 1} of the two answer files are different." + ) + if request1 in skip_questions: + continue + answer1 = answer1_data.iloc[i]["response"] + answer2 = answer2_data.iloc[i]["response"] + result1 = fastchat_evaluation( + model=model, + template=template, + question=request1, + answer_1=answer1, + answer_2=answer2, + prompt=prompt, + ) + result2 = fastchat_evaluation( + model=model, + template=template, + question=request1, + answer_1=answer2, + answer_2=answer1, + prompt=prompt, + ) + save( + output_data_path, + [ + request1, + result1["evaluation_request"], + result1["response"], + str(result1["score_pair"][0]), + str(result1["score_pair"][1]), + result2["evaluation_request"], + result2["response"], + str(result2["score_pair"][1]), + str(result2["score_pair"][0]), + ], + ) + + +if __name__ == "__main__": + args, model = parse_args() + + os.makedirs(args.output_folder, exist_ok=True) + + output_data_path = os.path.join(args.output_folder, args.output_data_filename) + + skip_questions = set([]) + if os.path.exists(output_data_path): + if args.yes or input( + "Output file {} already exists. Override (Y/N)? ".format(output_data_path) + ).lower() in {"yes", "y"}: + print("Removing the existing output file...") + os.remove(output_data_path) + else: + logging.info("Will skip existing results") + skip_questions = pd.read_csv(output_data_path, usecols=["request"]) + skip_questions = set(skip_questions["request"].tolist()) + + setup_logging(os.path.join(args.output_folder, args.log_filename)) + + answer1_data = pd.read_csv(args.answer_1_file, usecols=["request", "response"]) + answer2_data = pd.read_csv(args.answer_2_file, usecols=["request", "response"]) + + evaluation( + model=model, + answer1_data=answer1_data, + answer2_data=answer2_data, + template=args.template, + prompt=args.prompt, + output_data_path=output_data_path, + skip_questions=skip_questions, + ) diff --git a/sot/fastchat_evaluation_for_vicuna_bidir.py b/sot/fastchat_evaluation_for_vicuna_bidir.py new file mode 100644 index 0000000..144c8a8 --- /dev/null +++ b/sot/fastchat_evaluation_for_vicuna_bidir.py @@ -0,0 +1,226 @@ +import argparse +import os +import csv +import json +from tqdm import tqdm +import pandas as pd +import requests +import tempfile +import logging + +from models import get_model_class_from_name +from utils.logging import setup_logging +from evaluation.llm_evaluation import fastchat_evaluation + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=str, required=True) + parser.add_argument( + "--question-category-url", + type=str, + default=( + "https://raw.githubusercontent.com/lm-sys/FastChat/640ec6205031955e841523e" + "1a8606afb4d0538c2/fastchat/eval/table/question.jsonl" + ), + ) + parser.add_argument( + "--prompt-url", + type=str, + default=( + "https://raw.githubusercontent.com/lm-sys/FastChat/640ec6205031955e841523e" + "1a8606afb4d0538c2/fastchat/eval/table/prompt.jsonl" + ), + ) + parser.add_argument("--answer-1-file", type=str, required=True) + parser.add_argument("--answer-2-file", type=str, required=True) + parser.add_argument("--output-folder", type=str, required=True) + parser.add_argument( + "--output-data-filename", type=str, default="fastchat_evaluation.csv" + ) + parser.add_argument( + "--log-filename", type=str, default="fastchat_evaluation_log.log" + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Automatically answer yes to all user prompts.", + ) + args, other_args = parser.parse_known_args() + + model_class = get_model_class_from_name(args.model) + model, other_args = model_class.from_command_line_args(other_args) + + if other_args != []: + raise ValueError("Unknown arguments: {}".format(other_args)) + + return args, model + + +def save(file, content): + for i in range(len(content)): + if type(content[i]) != str: + content[i] = json.dumps(content[i]) + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow(content) + + +def evaluation( + model, + answer1_data, + answer2_data, + output_data_path, + question_to_prompt, + question_to_template, + skip_questions, +): + if answer1_data.shape[0] != answer2_data.shape[0]: + raise ValueError("The number of rows in the two answer files are different.") + + if not os.path.exists(output_data_path): + save( + output_data_path, + [ + "request", + "1_evaluation_request", + "1_evaluation", + "1_score1", + "1_score2", + "2_evaluation_request", + "2_evaluation", + "2_score1", + "2_score2", + ], + ) + + for i in tqdm(range(answer1_data.shape[0])): + request1 = answer1_data.iloc[i]["request"] + request2 = answer2_data.iloc[i]["request"] + if request1 != request2: + raise ValueError( + f"The requests at line {i + 1} of the two answer files are different." + ) + if request1 in skip_questions: + continue + answer1 = answer1_data.iloc[i]["response"] + answer2 = answer2_data.iloc[i]["response"] + if request1 not in question_to_template or request1 not in question_to_prompt: + raise ValueError( + f"The request {request1} at line {i + 1} of the two answer files " + "is not in the prompt file." + ) + result1 = fastchat_evaluation( + model=model, + template=question_to_template[request1], + question=request1, + answer_1=answer1, + answer_2=answer2, + prompt=question_to_prompt[request1], + ) + result2 = fastchat_evaluation( + model=model, + template=question_to_template[request1], + question=request1, + answer_1=answer2, + answer_2=answer1, + prompt=question_to_prompt[request1], + ) + save( + output_data_path, + [ + request1, + result1["evaluation_request"], + result1["response"], + str(result1["score_pair"][0]), + str(result1["score_pair"][1]), + result2["evaluation_request"], + result2["response"], + str(result2["score_pair"][1]), + str(result2["score_pair"][0]), + ], + ) + + +def download(url, file): + response = requests.get(url) + with open(file, "wb") as f: + f.write(response.content) + + +def download_template(question_category_url, prompt_url): + with tempfile.TemporaryDirectory() as tmp_dir: + question_category_file = os.path.join(tmp_dir, "question.jsonl") + prompt_file = os.path.join(tmp_dir, "prompt.jsonl") + download(question_category_url, question_category_file) + download(prompt_url, prompt_file) + question_to_category = {} + with open(question_category_file, "r") as f: + for line in f: + content = line.strip() + content = json.loads(content) + question = content["text"] + category = content["category"] + assert question not in question_to_category + question_to_category[question] = category + category_to_prompt = {} + category_to_template = {} + with open(prompt_file, "r") as f: + for line in f: + content = line.strip() + content = json.loads(content) + template = content["prompt_template"] + prompt = content["defaults"]["prompt"] + category = content["category"] + assert category not in category_to_prompt + assert category not in category_to_template + category_to_prompt[category] = prompt + category_to_template[category] = template + question_to_prompt = {} + question_to_template = {} + for question, category in question_to_category.items(): + if category not in category_to_prompt: + category = "general" + question_to_prompt[question] = category_to_prompt[category] + question_to_template[question] = category_to_template[category] + return question_to_prompt, question_to_template + + +if __name__ == "__main__": + args, model = parse_args() + + os.makedirs(args.output_folder, exist_ok=True) + + output_data_path = os.path.join(args.output_folder, args.output_data_filename) + + skip_questions = set([]) + if os.path.exists(output_data_path): + if args.yes or input( + "Output file {} already exists. Override (Y/N)? ".format(output_data_path) + ).lower() in {"yes", "y"}: + print("Removing the existing output file...") + os.remove(output_data_path) + else: + logging.info("Will skip existing results") + skip_questions = pd.read_csv(output_data_path, usecols=["request"]) + skip_questions = set(skip_questions["request"].tolist()) + + setup_logging(os.path.join(args.output_folder, args.log_filename)) + + answer1_data = pd.read_csv(args.answer_1_file, usecols=["request", "response"]) + answer2_data = pd.read_csv(args.answer_2_file, usecols=["request", "response"]) + + question_to_prompt, question_to_template = download_template( + args.question_category_url, args.prompt_url + ) + + evaluation( + model=model, + answer1_data=answer1_data, + answer2_data=answer2_data, + output_data_path=output_data_path, + question_to_prompt=question_to_prompt, + question_to_template=question_to_template, + skip_questions=skip_questions, + ) diff --git a/sot/llm_zoo_evaluation_alldir.py b/sot/llm_zoo_evaluation_alldir.py new file mode 100644 index 0000000..a78d98a --- /dev/null +++ b/sot/llm_zoo_evaluation_alldir.py @@ -0,0 +1,141 @@ +import argparse +import os +import csv +import json +from tqdm import tqdm +import pandas as pd +import logging +import itertools + +from models import get_model_class_from_name +from utils.logging import setup_logging +from evaluation.llm_evaluation import llm_zoo_evaluation + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=str, required=True) + parser.add_argument("--prompt", type=str, required=True) + parser.add_argument("--answer-file", type=str, required=True, action="append") + parser.add_argument("--output-folder", type=str, required=True) + parser.add_argument( + "--output-data-filename", type=str, default="llm_zoo_evaluation.csv" + ) + parser.add_argument( + "--log-filename", type=str, default="llm_zoo_evaluation_log.log" + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Automatically answer yes to all user prompts.", + ) + args, other_args = parser.parse_known_args() + + model_class = get_model_class_from_name(args.model) + model, other_args = model_class.from_command_line_args(other_args) + + if other_args != []: + raise ValueError("Unknown arguments: {}".format(other_args)) + + return args, model + + +def save(file, content): + for i in range(len(content)): + if type(content[i]) != str: + content[i] = json.dumps(content[i]) + with open(file, "a") as f: + writer = csv.writer(f) + writer.writerow(content) + + +def evaluation( + model, + answer_data, + prompt, + output_data_path, + skip_questions, +): + for i in range(len(answer_data)): + if answer_data[i].shape != answer_data[0].shape: + raise ValueError("The number of rows in the answer files are different.") + + permutations = list(itertools.permutations(list(range(len(answer_data))))) + + if not os.path.exists(output_data_path): + headers = ["request"] + for i in range(len(permutations)): + headers.append(f"{i}_{permutations[i]}_evaluation_request") + headers.append(f"{i}_{permutations[i]}_evaluation") + headers.append(f"{i}_{permutations[i]}_order") + save( + output_data_path, + headers, + ) + + for i in tqdm(range(answer_data[0].shape[0])): + row = [] + requests = [s.iloc[i]["request"] for s in answer_data] + for request in requests: + if request != requests[0]: + raise ValueError( + f"The requests at line {i + 1} of the answer files are different." + ) + if requests[0] in skip_questions: + continue + row.append(requests[0]) + for permutation in permutations: + answers = [s.iloc[i]["response"] for s in answer_data] + answers_reordered = [answers[j] for j in permutation] + result = llm_zoo_evaluation( + model=model, + question=requests[0], + answers=answers_reordered, + prompt=prompt, + ) + order_reorderd = [0] * len(result["order"]) + for j in range(len(result["order"])): + order_reorderd[permutation[j]] = result["order"][j] + row.append(result["evaluation_request"]) + row.append(result["response"]) + row.append(str(order_reorderd)) + save( + output_data_path, + row, + ) + + +if __name__ == "__main__": + args, model = parse_args() + + if len(args.answer_file) <= 1: + raise ValueError("At least two answer files are required.") + + output_data_path = os.path.join(args.output_folder, args.output_data_filename) + + skip_questions = set([]) + if os.path.exists(output_data_path): + if args.yes or input( + "Output file {} already exists. Override (Y/N)? ".format(output_data_path) + ).lower() in {"yes", "y"}: + print("Removing the existing output file...") + os.remove(output_data_path) + else: + logging.info("Will skip existing results") + skip_questions = pd.read_csv(output_data_path, usecols=["request"]) + skip_questions = set(skip_questions["request"].tolist()) + + setup_logging(os.path.join(args.output_folder, args.log_filename)) + + answer_data = [] + for answer_file in args.answer_file: + answer_data.append(pd.read_csv(answer_file, usecols=["request", "response"])) + + evaluation( + model=model, + answer_data=answer_data, + prompt=args.prompt, + output_data_path=output_data_path, + skip_questions=skip_questions, + ) diff --git a/sot/main.py b/sot/main.py new file mode 100644 index 0000000..eab9859 --- /dev/null +++ b/sot/main.py @@ -0,0 +1,98 @@ +import argparse +import os +import csv +import json +import shutil +import logging +from tqdm import tqdm +import pandas as pd + +from models import get_model_class_from_name +from schedulers import get_scheduler_class_from_name +from utils.logging import setup_logging + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=str, required=True) + parser.add_argument("--scheduler", type=str, required=True) + parser.add_argument("--data-path", type=str, required=True) + parser.add_argument("--output-folder", type=str, required=True) + parser.add_argument("--output-data-filename", type=str, default="data.csv") + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Automatically answer yes to all user prompts.", + ) + args, other_args = parser.parse_known_args() + + model_class = get_model_class_from_name(args.model) + model, other_args = model_class.from_command_line_args(other_args) + + scheduler_class = get_scheduler_class_from_name(args.scheduler) + scheduler, other_args = scheduler_class.from_command_line_args( + other_args, model=model + ) + + if other_args != []: + raise ValueError("Unknown arguments: {}".format(other_args)) + + return args, model, scheduler + + +def save(file, content): + for i in range(len(content)): + if type(content[i]) != str: + content[i] = json.dumps(content[i]) + with open(file, "a", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerow(content) + + +def main(): + args, model, scheduler = parse_args() + output_data_path = os.path.join(args.output_folder, args.output_data_filename) + + skip_questions = set([]) + if os.path.exists(args.output_folder): + if args.yes or ( + input( + "Output folder {} already exists. Override (Y/N)? ".format( + args.output_folder + ) + ).lower() + in {"yes", "y"} + ): + print("Removing the existing output folder...") + shutil.rmtree(args.output_folder) + else: + if os.path.exists(output_data_path): + logging.info("Will skip existing results") + skip_questions = pd.read_csv(output_data_path, usecols=["request"]) + skip_questions = set(skip_questions["request"].tolist()) + + os.makedirs(args.output_folder, exist_ok=True) + setup_logging(os.path.join(args.output_folder, "log.log")) + + scheduler.print_info() + + input_data = pd.read_csv(args.data_path, header=0, names=["request"]) + keys = None + for _, row in tqdm(input_data.iterrows()): + request = row["request"] + if request in skip_questions: + continue + response = scheduler.get_response(request) + if keys is None: + keys = list(sorted(response.keys())) + if not os.path.exists(output_data_path): + save(output_data_path, keys) + else: + assert keys == list(sorted(response.keys())) + response["request"] = request + save(output_data_path, [response[k] for k in keys]) + + +if __name__ == "__main__": + main() diff --git a/sot/models/__init__.py b/sot/models/__init__.py new file mode 100644 index 0000000..ce9764e --- /dev/null +++ b/sot/models/__init__.py @@ -0,0 +1,22 @@ +from .model import Model + + +def get_model_class_from_name(name): + # Lazy import to improve loading speed and reduce libary dependency. + if name == "openai": + from .openai_model import OpenAIModel + + return OpenAIModel + elif name == "fastchat": + from .fastchat_model import FastChatModel + + return FastChatModel + elif name == "claude_slack": + from .claude_slack_model import ClaudeSlackModel + + return ClaudeSlackModel + else: + raise ValueError(f"Unknown model name {name}") + + +__all__ = ["get_model_class_from_name", "Model"] diff --git a/sot/models/batch_inference.py b/sot/models/batch_inference.py new file mode 100644 index 0000000..2caf84c --- /dev/null +++ b/sot/models/batch_inference.py @@ -0,0 +1,244 @@ +"""Batched inference for FastChat models.""" +import gc +from typing import Dict +import numpy as np +import copy + +import torch +from transformers.generation.logits_process import ( + LogitsProcessorList, + RepetitionPenaltyLogitsProcessor, + TemperatureLogitsWarper, + TopKLogitsWarper, + TopPLogitsWarper, +) + +from fastchat.utils import is_sentence_complete + + +def prepare_logits_processor( + temperature: float, repetition_penalty: float, top_p: float, top_k: int +) -> LogitsProcessorList: + processor_list = LogitsProcessorList() + # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases. + if temperature >= 1e-5 and temperature != 1.0: + processor_list.append(TemperatureLogitsWarper(temperature)) + if repetition_penalty > 1.0: + processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty)) + if 1e-8 <= top_p < 1.0: + processor_list.append(TopPLogitsWarper(top_p)) + if top_k > 0: + processor_list.append(TopKLogitsWarper(top_k)) + return processor_list + + +@torch.inference_mode() +def batch_generate_stream( + model, + tokenizer, + params: Dict, + device: str, + context_len: int, + stream_interval: int = 2, + judge_sent_end: bool = False, +): + # Read parameters + prompts = params["prompt"] + len_prompt = np.max(np.array([len(prompt) for prompt in prompts])) + temperature = float(params.get("temperature", 1.0)) + repetition_penalty = float(params.get("repetition_penalty", 1.0)) + top_p = float(params.get("top_p", 1.0)) + top_k = int(params.get("top_k", -1)) # -1 means disable + max_new_tokens = int(params.get("max_new_tokens", 256)) + echo = bool(params.get("echo", True)) + stop_str = params.get("stop", None) + + stop_token_ids = params.get("stop_token_ids", None) or [] + stop_token_ids.append(tokenizer.eos_token_id) + pad_token_id = tokenizer.pad_token_id + + tokenizer.padding_side = "left" + input_ids = tokenizer(prompts, padding=True, return_tensors="pt").input_ids.to( + device + ) + + logits_processor = prepare_logits_processor( + temperature, repetition_penalty, top_p, top_k + ) + + if model.config.is_encoder_decoder: + max_src_len = context_len + else: # truncate + max_src_len = context_len - max_new_tokens - 1 + + input_ids = input_ids[:, -max_src_len:] + output_ids = copy.deepcopy(input_ids) + input_echo_len = input_ids.shape[1] + + unfinished_sequences = torch.ones( + input_ids.shape[0], dtype=torch.long, device=device + ) + + if model.config.is_encoder_decoder: + encoder_output = model.encoder( + input_ids=torch.as_tensor(input_ids, device=device) + ) + start_ids = torch.as_tensor( + [[model.generation_config.decoder_start_token_id]], + dtype=torch.int64, + device=device, + ) + + past_key_values = out = None + sent_interrupt = False + for i in range(max_new_tokens): + if i == 0: # prefill + if model.config.is_encoder_decoder: + out = model.decoder( + input_ids=start_ids, + encoder_hidden_states=encoder_output, + use_cache=True, + ) + logits = model.lm_head(out) + else: + out = model(torch.as_tensor(input_ids, device=device), use_cache=True) + logits = out.logits + past_key_values = out.past_key_values + else: # decoding + if model.config.is_encoder_decoder: + out = model.decoder( + input_ids=torch.as_tensor( + token if not sent_interrupt else output_ids, device=device + ), + encoder_hidden_states=encoder_output, + use_cache=True, + past_key_values=past_key_values if not sent_interrupt else None, + ) + sent_interrupt = False + + logits = model.lm_head(out) + else: + out = model( + input_ids=torch.as_tensor( + token if not sent_interrupt else output_ids, device=device + ), + use_cache=True, + past_key_values=past_key_values if not sent_interrupt else None, + ) + sent_interrupt = False + logits = out.logits + past_key_values = out.past_key_values + + if logits_processor: + if repetition_penalty > 1.0: + tmp_output_ids = torch.as_tensor(output_ids, device=logits.device) + else: + tmp_output_ids = None + last_token_logits = logits_processor(tmp_output_ids, logits[:, -1, :]) + else: + last_token_logits = logits[:, -1, :] + + if device == "mps": + # Switch to CPU by avoiding some bugs in mps backend. + last_token_logits = last_token_logits.float().to("cpu") + + if temperature < 1e-5 or top_p < 1e-8: # greedy + _, indices = torch.topk(last_token_logits, 2) + tokens = [int(index) for index in indices.tolist()] + else: + probs = torch.softmax(last_token_logits, dim=-1) + indices = torch.multinomial(probs, num_samples=1) + tokens = [int(token[0]) for token in indices.tolist()] + token = torch.tensor(tokens).to(device) + + if stop_token_ids is not None: + token = token * unfinished_sequences + pad_token_id * ( + 1 - unfinished_sequences + ) + + output_ids = torch.cat([output_ids, token[:, None]], dim=-1) + + if stop_token_ids is not None: + for stop_token in stop_token_ids: + stop_token_id_tensor = torch.tensor([stop_token]).to(device) + unfinished_sequences = unfinished_sequences.mul( + token.tile(stop_token_id_tensor.shape[0], 1) + .ne(stop_token_id_tensor.unsqueeze(1)) + .prod(dim=0) + ) + + token = token.unsqueeze(1) + + if unfinished_sequences.max() == 0: + stopped = True + else: + stopped = False + + # Yield the output tokens + if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped: + if echo: + tmp_output_ids = output_ids + rfind_start = len_prompt + else: + tmp_output_ids = output_ids[:, input_echo_len:] + rfind_start = 0 + + output = tokenizer.batch_decode( + tmp_output_ids, + skip_special_tokens=True, + spaces_between_special_tokens=False, + clean_up_tokenization_spaces=True, + ) + # TODO: For the issue of incomplete sentences interrupting output, apply a patch and others can also modify it to a more elegant way + if judge_sent_end and stopped and not is_sentence_complete(output): + if len(tokens) > 1: + token = tokens[1] + output_ids[-1] = token + else: + output_ids.pop() + stopped = False + sent_interrupt = True + + if stop_str is not None: + for i in range(len(output)): + pos = output[i].rfind(stop_str, rfind_start) + if pos != -1: + output[i] = output[i][:pos] + unfinished_sequences[i] = 0 + + # Prevent yielding partial stop sequence + yield { + "text": output, + "usage": { + "prompt_tokens": input_echo_len, + "completion_tokens": i, + "total_tokens": input_echo_len + i, + }, + "finish_reason": None, + } + + if stopped: + break + + # Finish stream event, which contains finish reason + if i == max_new_tokens - 1: + finish_reason = "length" + elif stopped: + finish_reason = "stop" + else: + finish_reason = None + + yield { + "text": output, + "usage": { + "prompt_tokens": input_echo_len, + "completion_tokens": i, + "total_tokens": input_echo_len + i, + }, + "finish_reason": finish_reason, + } + + # Clean + del past_key_values, out + gc.collect() + torch.cuda.empty_cache() diff --git a/sot/models/claude_slack_model.py b/sot/models/claude_slack_model.py new file mode 100644 index 0000000..0ba81d9 --- /dev/null +++ b/sot/models/claude_slack_model.py @@ -0,0 +1,148 @@ +import os +from tqdm import tqdm +from utils.logging import logger +import logging +import time +import errno +import signal +import functools +from slack_sdk import WebClient +from slack_sdk.errors import SlackApiError +from itertools import chain + +from tenacity import ( + retry, + stop_after_attempt, + wait_random_exponential, + before_sleep_log, +) + +from .model import Model + + +# https://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish +class TimeoutError(Exception): + pass + + +def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): + def decorator(func): + def _handle_timeout(signum, frame): + raise TimeoutError(error_message) + + @functools.wraps(func) + def wrapper(*args, **kwargs): + signal.signal(signal.SIGALRM, _handle_timeout) + signal.alarm(seconds) + try: + result = func(*args, **kwargs) + finally: + signal.alarm(0) + return result + + return wrapper + + return decorator + + +class ClaudeSlackModel(Model): + def __init__( + self, + channel_name, + first_message_timeout, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + self._slack_user_token = os.getenv("SLACK_USER_TOKEN") + self._channel_name = channel_name + self._first_message_timeout = first_message_timeout + + self._client = WebClient(token=self._slack_user_token) + + # Get claude bot user id. + self._bot_user_id = None + response = self._client.users_list() + for member in response["members"]: + if member["name"] == "claude": + self._bot_user_id = member["id"] + break + if self._bot_user_id is None: + raise ValueError("Claude bot user id not found.") + + try: + response = self._client.conversations_create(name=self._channel_name) + self._channel_id = response["channel"]["id"] + self._client.conversations_invite( + channel=self._channel_id, users=self._bot_user_id + ) + except SlackApiError as e: + logging.error(f"Claude error: {e}") + self._channel_id = None + response = self._client.conversations_list() + for i in range(len(response["channels"])): + if response["channels"][i]["name"] == self._channel_name: + self._channel_id = response["channels"][i]["id"] + break + if self._channel_id is None: + raise ValueError( + f"Channel {self._channel_name} does not exist in Slack." + ) + + @staticmethod + def command_line_parser(): + parser = super(ClaudeSlackModel, ClaudeSlackModel).command_line_parser() + parser.add_argument("--channel_name", type=str, required=True) + parser.add_argument("--first_message_timeout", type=float, default=10) + return parser + + def get_response(self, requests, stream=False): + if stream: + return chain( + *[ + self._get_response_for_one_request_stream(request) + for request in requests + ] + ) + else: + return [ + self._get_reponse_for_one_request(request) for request in tqdm(requests) + ] + + def _get_response_for_one_request_stream(self, request): + # TODO: implement streaming mode + response = self._get_reponse_for_one_request(request) + yield response + + @retry( + wait=wait_random_exponential(min=10, max=500), + stop=stop_after_attempt(30), + before_sleep=before_sleep_log(logger, logging.DEBUG), + ) + @timeout(60) + def _get_reponse_for_one_request(self, request): + if isinstance(request, str): + request = [request] + if isinstance(request, (tuple, list)): + request = [r for r in request if r is not None] + request = " ".join(request) + request = f"<@{self._bot_user_id}> " + request + start = time.time() + response = self._client.chat_postMessage(channel=self._channel_id, text=request) + timestamp = response["ts"] + response_text = None + while response_text is None: + response = self._client.conversations_replies( + channel=self._channel_id, ts=timestamp + ) + if len(response["messages"]) > 1: + response_text = response["messages"][1]["text"] + if response_text.endswith("Typing…_"): + response_text = None + else: + if time.time() - start > self._first_message_timeout: + raise ValueError("First message timeout.") + time.sleep(1) + end = time.time() + elapsed_time = end - start + return {"text": response_text, "time": elapsed_time} diff --git a/sot/models/fastchat_model.py b/sot/models/fastchat_model.py new file mode 100644 index 0000000..4b6a7a7 --- /dev/null +++ b/sot/models/fastchat_model.py @@ -0,0 +1,221 @@ +from itertools import chain +import torch + +from fastchat.model.model_adapter import ( + add_model_args, + load_model, + get_conversation_template, + get_generate_stream_function, +) +from fastchat.conversation import get_conv_template +from fastchat.modules.gptq import GptqConfig +from fastchat.modules.awq import AWQConfig +from fastchat.utils import get_context_length + +from .model import Model +from .batch_inference import batch_generate_stream +from . import register_fastchat + + +class FastChatModel(Model): + def __init__( + self, + model_path, + device, + gpus, + num_gpus, + max_gpu_memory, + load_8bit, + cpu_offloading, + gptq_ckpt, + gptq_wbits, + gptq_groupsize, + gptq_act_order, + awq_ckpt, + awq_wbits, + awq_groupsize, + conv_template, + temperature, + repetition_penalty, + max_new_tokens, + revision, + **kwargs, + ): + super().__init__() + self._model_path = model_path + self._device = device + self._num_gpus = num_gpus + self._max_gpu_memory = max_gpu_memory + self._load_8bit = load_8bit + self._cpu_offloading = cpu_offloading + self._gptq_config = GptqConfig( + ckpt=gptq_ckpt or self._model_path, + wbits=gptq_wbits, + groupsize=gptq_groupsize, + act_order=gptq_act_order, + ) + self._awq_config = AWQConfig( + ckpt=awq_ckpt or self._model_path, + wbits=awq_wbits, + groupsize=awq_groupsize, + ) + self._conv_template = conv_template + self._temperature = temperature + self._repetition_penalty = repetition_penalty + self._max_new_tokens = max_new_tokens + self._revision = revision + + self.model, self.tokenizer = load_model( + model_path=self._model_path, + device=self._device, + num_gpus=self._num_gpus, + max_gpu_memory=self._max_gpu_memory, + load_8bit=self._load_8bit, + cpu_offloading=self._cpu_offloading, + gptq_config=self._gptq_config, + awq_config=self._awq_config, + revision=self._revision, + # **kwargs, + ) + + # use padding or EOS to do *left padding* for batched point-expanding + if self.tokenizer.pad_token is None: + self.tokenizer.pad_token = self.tokenizer.eos_token + self.tokenizer.padding_size = "left" + + # streaming generation func + self.generate_stream_func = get_generate_stream_function( + self.model, self._model_path + ) + # batched streaming generation func + self.generate_batch_stream_func = batch_generate_stream + + self.context_len = get_context_length(self.model.config) + + @staticmethod + def command_line_parser(): + parser = super(FastChatModel, FastChatModel).command_line_parser() + add_model_args(parser) + parser.add_argument( + "--conv-template", + type=str, + default=None, + help="Conversation prompt template.", + ) + parser.add_argument("--temperature", type=float, default=0.7) + parser.add_argument("--repetition_penalty", type=float, default=1.0) + parser.add_argument("--max-new-tokens", type=int, default=512) + return parser + + def set_params(self, temperature, repetition_penalty, max_new_tokens): + self._temperature = temperature + self._repetition_penalty = repetition_penalty + self._max_new_tokens = max_new_tokens + + def get_response(self, requests, batch=False, stream=False): + if stream: + if not batch: + # return the generator that is the sequential chain + # of multiple generators, each handling one request + return chain( + *[ + self._get_response_for_one_request( + request, batch=False, stream=True + ) + for request in requests + ] + ) + else: + # return the generator, in which multiple requests + # will be handled by batch inference + return self._get_response_for_one_request( + requests, batch=True, stream=True + ) + if not batch: + return [ + self._get_response_for_one_request(request, batch=False) + for request in requests + ] + else: + return self._get_response_for_one_request(requests, batch=True) + + def _get_response_for_one_request(self, request, batch=False, stream=False): + if stream: + # streaming mode: return the generator + return self._get_response_for_one_request_stream(request, batch=batch) + + # non-streaming mode: drain the generator and return + for outputs in self._get_response_for_one_request_stream(request, batch=batch): + pass + return outputs + + def _get_response_for_one_request_stream(self, request, batch=False): + starter, ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event( + enable_timing=True + ) + starter.record() + + if batch: + # request is a list of request, each containing multiple messages + # handle multiple requests with batched inference + results = [self._get_prompt(single_req) for single_req in request] + stop_str, stop_token_ids = results[0][1:] + prompt = [res[0] for res in results] + generate_stream_func = self.generate_batch_stream_func + else: + # request is a single request containing multiple messages + # handle single request + prompt, stop_str, stop_token_ids = self._get_prompt(request) + generate_stream_func = self.generate_stream_func + + gen_params = { + "model": self._model_path, + "prompt": prompt, + "temperature": self._temperature, + "repetition_penalty": self._repetition_penalty, + "max_new_tokens": self._max_new_tokens, + "stop": stop_str, + "stop_token_ids": stop_token_ids, + "echo": False, + } + + output_stream = generate_stream_func( + self.model, + self.tokenizer, + gen_params, + self._device, + context_len=self.context_len, + ) + + for outputs in output_stream: + yield outputs + + ender.record() + torch.cuda.synchronize() + elapsed_time = starter.elapsed_time(ender) + outputs["time"] = elapsed_time / 1000 + yield outputs + + def _get_prompt(self, request): + if self._conv_template: + conv = get_conv_template(self._conv_template) + else: + conv = get_conversation_template(self._model_path) + + # clear the template messages, and sometimes including the system prompt + conv.messages = [] + num_history_round = (len(request) - 1) // 2 + # add the history messages + for i_message, message in enumerate(request[: num_history_round * 2]): + conv.append_message(conv.roles[i_message % 2], message) + # add the user question at this round + conv.append_message(conv.roles[0], request[num_history_round * 2]) + # indicate it's the assistant's turn to answer + conv.append_message(conv.roles[1], None) + + prompt = conv.get_prompt() + if len(request) == num_history_round * 2 + 2: + # have partial answer for the assistant, add the partial answer to the prompt + partial_answer = request[num_history_round * 2 + 1] or "" + prompt += partial_answer + return prompt, conv.stop_str, conv.stop_token_ids diff --git a/sot/models/model.py b/sot/models/model.py new file mode 100644 index 0000000..64f8e8d --- /dev/null +++ b/sot/models/model.py @@ -0,0 +1,19 @@ +from abc import ABC, abstractmethod +import argparse + + +class Model(ABC): + @staticmethod + def command_line_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--model_help", action="help") + return parser + + @classmethod + def from_command_line_args(cls, args): + args, other_args = cls.command_line_parser().parse_known_args(args) + return cls(**vars(args)), other_args + + @abstractmethod + def get_response(self, requests): + pass diff --git a/sot/models/openai_model.py b/sot/models/openai_model.py new file mode 100644 index 0000000..3a425b9 --- /dev/null +++ b/sot/models/openai_model.py @@ -0,0 +1,132 @@ +import openai +import os +from tqdm import tqdm +import logging +import time +from utils.logging import logger +from tenacity import ( + retry, + retry_if_not_exception_type, + stop_after_attempt, + wait_random_exponential, + before_sleep_log, +) +from itertools import chain + +from .model import Model + + +class OpenAIModel(Model): + def __init__( + self, + api_type, + api_base, + api_version, + temperature, + max_tokens, + top_p, + frequency_penalty, + presence_penalty, + engine, + api_model, + system_message, + timeout, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + self._api_type = api_type + self._api_base = api_base + self._api_version = api_version + self._temperature = temperature + self._max_tokens = max_tokens + self._top_p = top_p + self._frequency_penalty = frequency_penalty + self._presence_penalty = presence_penalty + self._engine = engine + self._api_model = api_model + self._system_message = system_message + self._timeout = timeout + + openai.api_type = self._api_type + openai.api_base = self._api_base + if self._api_version is not None: + openai.api_version = self._api_version + openai.api_key = os.getenv("OPENAI_API_KEY") + + @staticmethod + def command_line_parser(): + parser = super(OpenAIModel, OpenAIModel).command_line_parser() + parser.add_argument("--api-type", type=str, required=True) + parser.add_argument("--api-base", type=str) + parser.add_argument("--api-version", type=str, default=None) + parser.add_argument("--temperature", type=float) + parser.add_argument("--max-tokens", type=int) + parser.add_argument("--top-p", type=float) + parser.add_argument("--frequency-penalty", type=float) + parser.add_argument("--presence-penalty", type=float) + parser.add_argument("--engine", type=str, default=None) + parser.add_argument("--api-model", type=str, default=None) + parser.add_argument("--system-message", type=str) + parser.add_argument("--timeout", type=float, default=60) + return parser + + def get_response(self, requests, stream=False): + if stream: + return chain( + *[ + self._get_response_for_one_request_stream(request) + for request in requests + ] + ) + else: + return [ + self._get_reponse_for_one_request(request) for request in tqdm(requests) + ] + + def _get_response_for_one_request_stream(self, request): + # TODO: implement streaming mode + response = self._get_reponse_for_one_request(request) + yield response + + @retry( + retry=retry_if_not_exception_type( + ( + openai.error.InvalidRequestError, + openai.error.AuthenticationError, + ) + ), + wait=wait_random_exponential(min=8, max=500), + stop=stop_after_attempt(30), + before_sleep=before_sleep_log(logger, logging.DEBUG), + ) + def _get_reponse_for_one_request(self, request): + if isinstance(request, str): + request = [request] + messages = [ + { + "role": "system", + "content": self._system_message, + } + ] + roles = ["user", "assistant"] + for r_i, r in enumerate(request): + if r is not None: + messages.append({"role": roles[r_i % 2], "content": r}) + start = time.time() + response = openai.ChatCompletion.create( + engine=self._engine, + model=self._api_model, + messages=messages, + temperature=self._temperature, + max_tokens=self._max_tokens, + top_p=self._top_p, + frequency_penalty=self._frequency_penalty, + presence_penalty=self._presence_penalty, + stop=None, + request_timeout=self._timeout, + ) + end = time.time() + response = response["choices"][0]["message"]["content"] + elapsed_time = end - start + return {"text": response, "time": elapsed_time} diff --git a/sot/models/register_fastchat.py b/sot/models/register_fastchat.py new file mode 100644 index 0000000..5df8427 --- /dev/null +++ b/sot/models/register_fastchat.py @@ -0,0 +1,132 @@ +from transformers import LlamaTokenizer, LlamaForCausalLM +from fastchat.model.model_adapter import BaseModelAdapter, register_model_adapter +from fastchat.conversation import ( + register_conv_template, + get_conv_template, + SeparatorStyle, + Conversation, +) + + +## ---- Register model adapters ---- +class OrcaLLaMAAdapter(BaseModelAdapter): + def match(self, model_path: str): + return "orca" in model_path + + def load_model(self, model_path: str, from_pretrained_kwargs: dict): + tokenizer = LlamaTokenizer.from_pretrained(model_path) + model = LlamaForCausalLM.from_pretrained(model_path, **from_pretrained_kwargs) + return model, tokenizer + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("orca") + + +class OpenChatLLaMAAdapter(BaseModelAdapter): + def match(self, model_path: str): + return "openchat" in model_path + + def load_model(self, model_path: str, from_pretrained_kwargs: dict): + tokenizer = LlamaTokenizer.from_pretrained(model_path) + model = LlamaForCausalLM.from_pretrained(model_path, **from_pretrained_kwargs) + return model, tokenizer + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("openchat") + + +""" +# Note: Due to FastChat's matching mechanism and matching criterion for Vicuna, +# we must register it before registering VicunaAdapter for StableVicuna to +# successfully match this StableVicunaAdapter +class StableVicunaAdapter(BaseModelAdapter): + def match(self, model_path: str): + return "stable-vicuna" in model_path + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("stable_vicuna") +""" + + +class UltraLMAdapter(BaseModelAdapter): + def match(self, model_path: str): + return "ultralm" in model_path.lower() + + def get_default_conv_template(self, model_path: str) -> Conversation: + return get_conv_template("ultra-lm") + + +register_model_adapter(OrcaLLaMAAdapter) +register_model_adapter(OpenChatLLaMAAdapter) +register_model_adapter(UltraLMAdapter) + +## ---- Register conversation templates ---- + +# ref: https://huggingface.co/psmathur/orca_mini_13b +register_conv_template( + Conversation( + name="orca", + system_message=( + "### System:\nYou are an AI assistant that follows instruction extremely" + " well. Help as much as you can.\n\n" + ), + roles=("### User:\n", "### Response:\n"), + messages=(), + offset=0, + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="\n\n", + ) +) + + +# ref: https://huggingface.co/openchat/openchat +# https://github.com/imoneoi/openchat/blob/master/ochat/serving/inference.py +register_conv_template( + Conversation( + name="openchat", + system_message=( + "System: You are an AI assistant that follows instruction extremely well." + " Help as much as you can.\n" + ), + roles=("Human", "Assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="<|end_of_turn|>", + stop_token_ids=[32000], + ) +) + +""" +# ref: https://huggingface.co/CarperAI/stable-vicuna-13b-delta +register_conv_template( + Conversation( + name="stable_vicuna", + system_message="", + roles=("### Human", "### Assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + stop_str="###", + ) +) +""" + + +# ref: https://huggingface.co/openbmb/UltraLM-13b +register_conv_template( + Conversation( + name="ultra-lm", + system_message=( + "A chat between a curious user and an artificial intelligence assistant." + " The assistant gives helpful, detailed, and polite answers to the user's" + " questions." + ), + roles=("User", "Assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="", + ) +) diff --git a/sot/prompt_eng_main.py b/sot/prompt_eng_main.py new file mode 100644 index 0000000..cb6eec9 --- /dev/null +++ b/sot/prompt_eng_main.py @@ -0,0 +1,378 @@ +import os +import re +import sys +import csv +import yaml +import json +import shutil +import logging +import argparse +import readline +from collections import OrderedDict + +from tqdm import tqdm +import pandas as pd +import IPython +from termcolor import colored + +from models import get_model_class_from_name +from schedulers import get_scheduler_class_from_name +from utils.logging import setup_logging + +# ---- Copy from https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input ---- +COMMANDS = [ + "usedata", + "useprompt", + "test", + "exit", + "embedipy", + "setloglevel", + "usenaiveprompt", +] +COMMAND_HINTS = ["", " ", "", ""] +RE_SPACE = re.compile(".*\s+$", re.M) + + +class Completer(object): + def _listdir(self, root): + "List directory 'root' appending the path separator to subdirs." + res = [] + for name in os.listdir(root): + path = os.path.join(root, name) + if os.path.isdir(path): + name += os.sep + res.append(name) + return res + + def _complete_path(self, path=None): + "Perform completion of filesystem path." + if not path: + return self._listdir(".") + dirname, rest = os.path.split(path) + tmp = dirname if dirname else "." + res = [ + os.path.join(dirname, p) for p in self._listdir(tmp) if p.startswith(rest) + ] + # more than one match, or single match which does not exist (typo) + if len(res) > 1 or not os.path.exists(path): + return res + # resolved to a single directory, so return list of files below it + if os.path.isdir(path): + return [os.path.join(path, p) for p in self._listdir(path)] + # exact file match terminates this completion + return [path + " "] + + def complete_useprompt(self, args): + if not args: + return self._complete_path(".") + # treat the last arg as a path and complete it + return self._complete_path(args[-1]) + + def complete_usedata(self, args): + if not args: + return self._complete_path(".") + # treat the last arg as a path and complete it + return self._complete_path(args[-1]) + + def complete_usenaiveprompt(self, args): + if not args: + return self._complete_path(".") + # treat the last arg as a path and complete it + return self._complete_path(args[-1]) + + def complete(self, text, state): + "Generic readline completion entry point." + buffer = readline.get_line_buffer() + line = readline.get_line_buffer().split() + # show all commands + if not line: + return [c + " " + c_hint for c, c_hint in zip(COMMANDS, COMMAND_HINTS)][ + state + ] + # account for last argument ending in a space + if RE_SPACE.match(buffer): + line.append("") + # resolve command to the implementation function + cmd = line[0].strip() + if cmd in COMMANDS: + impl = getattr(self, "complete_%s" % cmd) + args = line[1:] + if args: + return (impl(args) + [None])[state] + return [cmd + " "][state] + results = [c + " " for c in COMMANDS if c.startswith(cmd)] + [None] + return results[state] + + +comp = Completer() +# we want to treat '/' as part of a word, so override the delimiters +readline.set_completer_delims(" \t\n;") +readline.parse_and_bind("tab: complete") +readline.set_completer(comp.complete) +# ---- End copy from https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input ---- + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=str, required=True) + parser.add_argument("--output-log", type=str, required=True) + parser.add_argument( + "--stream", + action="store_true", + help="Streaming the model outputs to the console.", + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Automatically answer yes to all user prompts.", + ) + args, other_args = parser.parse_known_args() + + model_class = get_model_class_from_name(args.model) + model, other_args = model_class.from_command_line_args(other_args) + # model, other_args = None, [] # for debug + + if other_args != []: + raise ValueError("Unknown arguments: {}".format(other_args)) + + return args, model + + +def save(file, content): + for i in range(len(content)): + if type(content[i]) != str: + content[i] = json.dumps(content[i]) + with open(file, "a", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerow(content) + + +def useprompt(cmd, model, input_data, schedulers): + if not len(cmd) == 2: + logging.error("useprompt takes 1 argument") + return + try: + schedulers["outline"] = get_scheduler_class_from_name("outline")( + model=model, prompt_file=cmd[1] + ) + except Exception as error: + logging.error(f"{error.__class__.__name__}: {error}") + return + schedulers["outline"].print_info() + + +def usenaiveprompt(cmd, model, input_data, schedulers): + if not len(cmd) == 2: + logging.error("usenaiveprompt takes 1 argument") + return + if cmd[1] == "none": + # clear the naive prompt template + schedulers["naive"] = get_scheduler_class_from_name("naive")(model=model) + else: + try: + schedulers["naive"] = get_scheduler_class_from_name("naive")( + model=model, prompt_file=cmd[1] + ) + except Exception as error: + logging.error(f"{error.__class__.__name__}: {error}") + return + schedulers["naive"].print_info() + + +def usedata(cmd, model, data_container, schedulers): + if not len(cmd) == 2: + logging.error("usedata takes 1 argument") + return + try: + data_container["data"] = pd.read_csv(cmd[1], header=0, names=["request"]) + logging.info( + "Loaded data from %s, %d questions in total", + cmd[1], + len(data_container["data"]), + ) + except Exception as error: + logging.error(f"{error.__class__.__name__}: {error}") + return + + +def test(cmd, model, input_data, schedulers, log_filename): + if not len(cmd) in {2, 3}: + logging.error( + "test takes 1 or 2 argument: 'test [optional ,]" + " " + ) + return + if len(cmd) == 2: + scheduler_type = "outline" + data_index = cmd[1] + else: + scheduler_type = cmd[1] + data_index = cmd[2] + try: + data_index = int(data_index) + except ValueError as e: + logging.error(e) + return + + if scheduler_type not in schedulers: + logging.error( + f"Scheduler {scheduler_type} not exist. Available: {schedulers.keys()}" + ) + return + if data_index >= input_data.shape[0]: + logging.error(f"Data index {data_index} not exist. #rows={input_data.shape[0]}") + return + + # test + scheduler = schedulers[scheduler_type] + request = input_data.iloc[data_index]["request"] + logging.info("Testing requeset: %s", request) + try: + if args.stream: + if scheduler_type == "batch_outline": + logging.warning( + "`batch_outline` scheduler doesn't support streaming to the" + " console, let us use the non-streaming output mode." + ) + response = scheduler.get_response(request) + else: + # For rapid iterating the prompts, let's change into streaming + # (i.e., as long as we identify some problem, + # we can 1. abort the genertion, 2. change the prompt template, 3. retest. + output_generator = scheduler.get_response(request, stream=True) + with open(log_filename, "a", encoding="utf-8") as logfile_stream: + response = scheduler.stream_output( + output_generator, streams=[sys.stderr, logfile_stream] + ) + else: + response = scheduler.get_response(request) + except KeyboardInterrupt: + logging.info("Previous generation interrupted.") + return + + # print the stats, and the responses (if not streaming) + if scheduler_type == "naive": + if not args.stream: + logging.info("Naive scheduler response: %s", response["response"]) + + stats = OrderedDict( + num_history_round=(len(response["request"]) - 1) // 2, + request_length=len(response["request"][-1]), + response_length=len(response["response"]), + request_tokens=len(model.tokenizer(response["request"][-1])["input_ids"]), + response_tokens=len(model.tokenizer(response["response"])["input_ids"]), + ) + logging.info( + colored( + "Naive scheduler stats: {}".format( + ", ".join([f"{key}={value}" for key, value in stats.items()]) + ), + "green", + ) + ) + else: # if scheduler_type == "outline" + if not args.stream or scheduler_type == "batch_outline": + # not streaming, print out the response first + logging.info(f"Outline scheduler outline: %s", response["outline"]) + logging.info("Outline scheduler response: %s", response["response"]) + + stats = OrderedDict( + num_history_round=(len(response["request"]) - 1) // 2, + request_length=len(response["request"][-1]), + outline_length=len(response["outline"]), + num_points=len(response["points"]), + point_outline_length=[len(point) for point in response["point_outlines"]], + point_response_length=[len(content) for content in response["contents"]], + response_length=len(response["response"]), + request_tokens=len(model.tokenizer(response["request"][-1])["input_ids"]), + outline_tokens=len(model.tokenizer(response["outline"])["input_ids"]), + point_outline_tokens=[ + len(model.tokenizer(point)["input_ids"]) + for point in response["point_outlines"] + ], + point_response_tokens=[ + len(model.tokenizer(content)["input_ids"]) + for content in response["contents"] + ], + response_tokens=len(model.tokenizer(response["response"])["input_ids"]), + ) + logging.info( + colored( + "Outline scheduler stats: {}".format( + ", ".join([f"{key}={value}" for key, value in stats.items()]) + ), + "green", + ) + ) + return response + + +DEFAULT_DATA_PATH = "data/vicuna/data.csv" +DEFAULT_PROMPT_PATH = "prompts/sot_opensource.json" + +if __name__ == "__main__": + args, model = parse_args() + + dir_name = os.path.dirname(args.output_log) + os.makedirs(dir_name, exist_ok=True) + + setup_logging(args.output_log) + + data_container = { + "data": pd.read_csv(DEFAULT_DATA_PATH, header=0, names=["request"]) + } + + schedulers = { + "outline": get_scheduler_class_from_name("outline")( + model=model, prompt_file=DEFAULT_PROMPT_PATH + ), + "batch_outline": get_scheduler_class_from_name("batch_outline")( + model=model, prompt_file=DEFAULT_PROMPT_PATH + ), + "naive": get_scheduler_class_from_name("naive")(model=model), + } + schedulers["outline"].print_info() + + while 1: + try: + cmd = input( + colored( + f"Please give a CMD (supported commands: {COMMANDS}): ", "green" + ) + ) + # 'useprompt ' or 'test '" + cmd = re.split("\s+", cmd.strip()) + if cmd[0] not in COMMANDS: + logging.error(f"Only these commands are supported: {COMMANDS}") + continue + if cmd[0] == "useprompt": + useprompt(cmd, model, data_container["data"], schedulers) + elif cmd[0] == "usenaiveprompt": + usenaiveprompt(cmd, model, data_container["data"], schedulers) + elif cmd[0] == "test": + response = test( + cmd, model, data_container["data"], schedulers, args.output_log + ) + elif cmd[0] == "usedata": + usedata(cmd, model, data_container, schedulers) + elif cmd[0] == "embedipy": + IPython.embed() + elif cmd[0] == "setloglevel": + if len(cmd) != 2: + logging.error( + "`setloglevel` accept one and only one log-level argument." + ) + continue + level = getattr(logging, cmd[1].upper(), None) + if level is None: + logging.error(f"Level '{cmd[1]}' not exists") + continue + logging.getLogger().setLevel(level) + logging.info(f"Set log level to {level} ({cmd[1]})") + elif cmd[0] == "exit": + logging.info("Exit.") + sys.exit(0) + except KeyboardInterrupt: + logging.error(f"Only these commands are supported: {COMMANDS}") + continue diff --git a/sot/schedulers/__init__.py b/sot/schedulers/__init__.py new file mode 100644 index 0000000..d381c21 --- /dev/null +++ b/sot/schedulers/__init__.py @@ -0,0 +1,30 @@ +from .scheduler import Scheduler + + +def get_scheduler_class_from_name(name): + # Lazy import to improve loading speed and reduce libary dependency. + if name == "naive": + from .naive_scheduler import NaiveScheduler + + return NaiveScheduler + elif name == "outline": + from .outline_scheduler import OutlineScheduler + + return OutlineScheduler + elif name == "batch_outline": + from .outline_batch_scheduler import OutlineBatchScheduler + + return OutlineBatchScheduler + elif name == "router_batch_outline": + from .router_outline_batch_scheduler import RouterOutlineBatchScheduler + + return RouterOutlineBatchScheduler + elif name == "fake_outline": + from .fake_outline_scheduler import FakeOutlineScheduler + + return FakeOutlineScheduler + else: + raise ValueError(f"Unknown scheduler name {name}") + + +__all__ = ["get_scheduler_class_from_name", "Scheduler"] diff --git a/sot/schedulers/naive_scheduler.py b/sot/schedulers/naive_scheduler.py new file mode 100644 index 0000000..46d962c --- /dev/null +++ b/sot/schedulers/naive_scheduler.py @@ -0,0 +1,97 @@ +import sys +import json +import logging + +from termcolor import colored + +from .scheduler import Scheduler +from sot.utils import _print_to_streams + + +class NaiveScheduler(Scheduler): + def __init__(self, prompt_file=None, **kwargs): + super().__init__(**kwargs) + if prompt_file is not None and prompt_file != "none": + with open(prompt_file, "r") as rf: + prompts = json.load(rf) + self.prompt = prompts["prompt"] + else: + self.prompt = "{request}" + + def set_model(self, model): + self._model = model + + def print_info(self): + super().print_info() + logging.info( + colored("NaiveScheduler *prompt*: ", "magenta") + f"'''{self.prompt}'''" + ) + + @staticmethod + def command_line_parser(): + parser = super(NaiveScheduler, NaiveScheduler).command_line_parser() + parser.add_argument( + "--prompt-file", + type=str, + help=( + "The path of the JSON file containing `prompt`. " + "'--promptfile none' is equivalent to not specifying this argument." + ), + default=None, + ) + return parser + + def stream_output(self, output_stream, streams=None): + if streams is None: + streams = [sys.stderr] + pre = 0 + for outputs in output_stream: + if outputs.get("stage", None) == "summarize": + _print_to_streams(streams, " ".join(output_text[pre:]), flush=True) + _print_to_streams(streams, "\n\n", flush=True) + return outputs + output_text = outputs["text"] + output_text = output_text.strip().split(" ") + now = len(output_text) - 1 + if now > pre: + _print_to_streams( + streams, " ".join(output_text[pre:now]), end=" ", flush=True + ) + pre = now + raise ValueError() + + def format_outline_prompt(self, request): + return self.prompt.format(request=request) + + def _get_response_stream(self, request): + request = request.copy() + ques = self.format_outline_prompt(request[-1]) + request[-1] = ques + for outputs in self._model.get_response([request], stream=True): + yield outputs + + yield { + "stage": "summarize", + "request": request, + "text": outputs["text"], + "response": outputs["text"], + "time": outputs["time"], + } + + def get_response(self, request, stream=False): + if isinstance(request, str): + # one request should be a list of messages, + # alternatively from the user and the assistant + request = [request] + if len(request) % 2 != 1: + raise ValueError( + "The length of the request messages should be odd." + "So that the final message is from the user." + ) + + if stream: + return self._get_response_stream(request) + + for outputs in self._get_response_stream(request): + pass + return outputs diff --git a/sot/schedulers/outline_batch_scheduler.py b/sot/schedulers/outline_batch_scheduler.py new file mode 100644 index 0000000..02561c0 --- /dev/null +++ b/sot/schedulers/outline_batch_scheduler.py @@ -0,0 +1,165 @@ +import re +import sys +import json +import copy +import logging +from collections import OrderedDict + +from termcolor import colored + +from .outline_scheduler import OutlineScheduler +from sot.utils import _print_to_streams + + +class OutlineBatchScheduler(OutlineScheduler): + """ + OutlineBatchScheduler uses batch inference or the point-expanding stage. + This class can be used for local models only. + """ + + def set_model(self, model): + self._model = model + + def print_info(self): + super().print_info() + logging.info( + colored("OutlineScheduler *outline prompt*: ", "magenta") + + f"'''{self._outline_prompt}'''" + ) + logging.info( + colored("OutlineScheduler *point prompt*: ", "magenta") + + f"'''{self._point_prompt}'''" + ) + + @staticmethod + def command_line_parser(): + parser = super(OutlineScheduler, OutlineScheduler).command_line_parser() + parser.add_argument( + "--prompt-file", + type=str, + help=( + "The path of the JSON file containing `outline_prompt` and" + " `point_prompt`." + ), + default=None, + ) + parser.add_argument("--outline-prompt", type=str, default=None) + parser.add_argument("--point-prompt", type=str, default=None) + return parser + + def stream_output(self, output_generator, streams): + raise NotImplementedError( + "OutlineBatchScheduler currently doesn't implement file-based streaming, to" + " see the streaming demo of OutlineBatchScheduler, please use the Gradio" + " web demo in the repo." + ) + + def _get_response_stream(self, request): + outline_request = request.copy() + outline_ques, partial_answer = self.format_outline_prompt(request=request[-1]) + outline_request[-1] = outline_ques + outline_request.append(partial_answer) + for outputs in self._model.get_response([outline_request], stream=False): + outputs["stage"] = "outline" + yield outputs + outline = outputs["text"] + outline_time = outputs["time"] + if partial_answer: + outline = partial_answer + outline + + # Extract points. + re_result = re.findall(r"(\d+)\.\s?([\s\S]+?)(?=\n|\n*$)", outline) + if len(re_result) > 0: + points, point_outlines = zip(*re_result) + else: + points, point_outlines = [], [] + + num_points = len(points) + if num_points > 0: + # Filter to get unique point indexes + points_filtered = [] + point_outlines_filtered = [] + points_set = set([]) + for i in range(len(points)): + if points[i] not in points_set: + points_set.add(points[i]) + points_filtered.append(points[i]) + point_outlines_filtered.append(point_outlines[i]) + points = points_filtered + point_outlines = point_outlines_filtered + + pe_ques_and_partial_list = [ + self.format_point_prompt( + request=request[-1], + point=point, + outline=outline, + point_outline=point_outline, + ) + for point, point_outline in zip(points, point_outlines) + ] + pe_requests = [request.copy() for _ in range(len(points))] + for pe_request, (pe_ques, pe_partial) in zip( + pe_requests, pe_ques_and_partial_list + ): + pe_request[-1] = pe_ques + pe_request.append(pe_partial) + + for i_stream_out, outputs in enumerate( + self._model.get_response(pe_requests, batch=True, stream=True) + ): + yield_outputs = copy.deepcopy(outputs) + yield_outputs["stage"] = "expand" + yield_outputs["ori_text"] = yield_outputs["text"] + point_responses = [ + point_resp.strip() for point_resp in yield_outputs["ori_text"] + ] + contents = [ + partial_answer + " " + point_resp if partial_answer else point_resp + for (_, partial_answer), point_resp in zip( + pe_ques_and_partial_list, point_responses + ) + ] + + # Concatenate `contents` together as the new `outputs["text"]` + # to show in the Gradio streaming demo + yield_outputs["text"] = "\n".join(contents) + # Note: When we need to change outputs["text"] based on outputs["text"], + # we should deep copy the `outputs` dict instead of change it in place. + # This can avoid second-time processing in the last loop (finish_reason=="stop"), + # since the outputs["text"] will not be updated in the generation function. + + yield yield_outputs + point_time = outputs["time"] + else: + contents = [] + + yield { + "stage": "summarize", + "request": request, + "response": "\n".join(contents), # for main.py and prompt_eng_main.py + "text": "\n".join(contents), # for Gradio streaming demo + "outline": outline, + "outline_time": outline_time, + "contents": contents, + "points": points, + "point_outlines": point_outlines, + "point_time": point_time, + } + + def get_response(self, request, stream=False): + if isinstance(request, str): + # one request should be a list of messages, + # alternatively from the user and the assistant + request = [request] + if len(request) % 2 != 1: + raise ValueError( + "The length of the request messages should be odd." + "So that the final message is from the user." + ) + + if stream: + return self._get_response_stream(request) + + for outputs in self._get_response_stream(request): + pass + return outputs diff --git a/sot/schedulers/outline_scheduler.py b/sot/schedulers/outline_scheduler.py new file mode 100644 index 0000000..e920542 --- /dev/null +++ b/sot/schedulers/outline_scheduler.py @@ -0,0 +1,238 @@ +import re +import sys +import json +import logging + +from termcolor import colored + +from .scheduler import Scheduler +from sot.utils import _print_to_streams + + +class OutlineScheduler(Scheduler): + PROMPT_ROLE_SWITCH_STR = "[ROLESWITCHING assistant:]" + + def __init__( + self, prompt_file=None, outline_prompt=None, point_prompt=None, **kwargs + ): + super().__init__(**kwargs) + if prompt_file is not None: + if outline_prompt is not None or point_prompt is not None: + raise ValueError( + "When providing `prompt_file`, should not provide `outline_prompt`" + " and `point_prompt` through command-line arguments" + ) + with open(prompt_file, "r") as rf: + prompts = json.load(rf) + self._outline_prompt = prompts["outline_prompt"] + self._point_prompt = prompts["point_prompt"] + else: + if outline_prompt is None or point_prompt is None: + raise ValueError( + "Should either provide `prompt_file`, or provide `outline_prompt`" + " and `point_prompt` through command-line arguments" + ) + self._outline_prompt = outline_prompt + self._point_prompt = point_prompt + + def print_info(self): + super().print_info() + logging.info( + colored("OutlineScheduler *outline prompt*: ", "magenta") + + f"'''{self._outline_prompt}'''" + ) + logging.info( + colored("OutlineScheduler *point prompt*: ", "magenta") + + f"'''{self._point_prompt}'''" + ) + + @staticmethod + def command_line_parser(): + parser = super(OutlineScheduler, OutlineScheduler).command_line_parser() + parser.add_argument( + "--prompt-file", + type=str, + help=( + "The path of the JSON file containing `outline_prompt` and" + " `point_prompt`." + ), + default=None, + ) + parser.add_argument("--outline-prompt", type=str, default=None) + parser.add_argument("--point-prompt", type=str, default=None) + return parser + + def stream_output(self, output_generator, streams): + if streams is None: + streams = [sys.stderr] + + pre = 0 + output_text = "" + cur_stage = "outline" + logging.info(colored("Outline scheduler outline:", "magenta")) + for outputs in output_generator: + if outputs["stage"] == "summarize": + _print_to_streams(streams, " ".join(output_text[pre:]), flush=True) + _print_to_streams(streams, "\n\n", flush=True) + return outputs + if not outputs["stage"] == cur_stage: + assert outputs["stage"] == "expand" + assert outputs["point_index"] == 0 + _print_to_streams(streams, " ".join(output_text[pre:]), flush=True) + _print_to_streams(streams, "\n\n", flush=True) + logging.info(colored("Outline scheduler response:", "magenta")) + cur_stage = outputs["stage"] + pre = 0 + cur_point = 0 + if outputs["stage"] == "expand" and outputs["point_index"] != cur_point: + _print_to_streams(streams, " ".join(output_text[pre:]), flush=True) + _print_to_streams(streams, "\n\n", flush=True) + pre = 0 + cur_point = outputs["point_index"] + if "sub_request" in outputs: + sub_request = outputs["sub_request"] + logging.debug( + colored(f"Sub-request {cur_point}: '''{sub_request}'''", "magenta") + ) + output_text = outputs["text"] + output_text = output_text.strip().split(" ") + now = ( + len(output_text) - 1 + ) # use len(output_text)-1 here since the last word might not finish + if now > pre: + _print_to_streams( + streams, " ".join(output_text[pre:now]), end=" ", flush=True + ) + pre = now + raise ValueError() + + def format_outline_prompt(self, request): + splits = self._outline_prompt.split(self.PROMPT_ROLE_SWITCH_STR) + if len(splits) == 1: + return splits[0].format(request=request), None + return splits[0].format(request=request), splits[1].format(request=request) + + def format_point_prompt(self, request, outline, point, point_outline): + splits = self._point_prompt.split(self.PROMPT_ROLE_SWITCH_STR) + if len(splits) == 1: + return ( + splits[0].format( + request=request, + outline=outline, + point=point, + point_outline=point_outline, + ), + None, + ) + return [ + split.format( + request=request, + outline=outline, + point=point, + point_outline=point_outline, + ) + for split in splits + ] + + def _get_response_stream(self, request, history=""): + outline_request = request.copy() + outline_ques, partial_answer = self.format_outline_prompt(request=request[-1]) + outline_request[-1] = outline_ques + outline_request.append(partial_answer) + logging.debug(colored(f"Outline request: {outline_request}\n----", "magenta")) + for outputs in self._model.get_response([outline_request], stream=True): + outputs["stage"] = "outline" + yield outputs + outline = outputs["text"] + outline_time = outputs["time"] + if partial_answer: + outline = partial_answer + outline + + # Extract points. + re_result = re.findall(r"(\d+)\.\s?([\s\S]+?)(?=\n|\n*$)", outline) + if len(re_result) > 0: + points, point_outlines = zip(*re_result) + else: + points, point_outlines = [], [] + assert len(points) == len(point_outlines) + + num_points = len(points) + contents_time = [] + if num_points > 0: + # Filter to get unique point indexes + points_filtered = [] + point_outlines_filtered = [] + points_set = set([]) + for i in range(num_points): + if points[i] not in points_set: + points_set.add(points[i]) + points_filtered.append(points[i]) + point_outlines_filtered.append(point_outlines[i]) + points = points_filtered + point_outlines = point_outlines_filtered + + pe_ques_and_partial_list = [ + self.format_point_prompt( + request=request[-1], + point=point, + outline=outline, + point_outline=point_outline, + ) + for point, point_outline in zip(points, point_outlines) + ] + pe_requests = [request.copy() for _ in range(len(points))] + for pe_request, (pe_ques, pe_partial) in zip( + pe_requests, pe_ques_and_partial_list + ): + pe_request[-1] = pe_ques + pe_request.append(pe_partial) + + contents = [] + for i_point, sub_request in enumerate(pe_requests): + for i_stream_out, outputs in enumerate( + self._model.get_response([sub_request], stream=True) + ): + if i_stream_out == 0: + outputs["sub_request"] = sub_request + outputs["stage"] = "expand" + outputs["point_index"] = i_point + yield outputs + # append the text of the point #i_point to `contents` + contents.append(outputs["text"]) + contents_time.append(outputs["time"]) + # for final response, concatenate the partial answer together + for i_point, (_, partial_answer) in enumerate(pe_ques_and_partial_list): + if partial_answer: + contents[i_point] = partial_answer + " " + contents[i_point] + else: + contents = [] + + yield { + "stage": "summarize", + "request": request, + "response": "\n\n".join(contents), + "outline": outline, + "contents": contents, + "points": points, + "point_outlines": point_outlines, + "outline_time": outline_time, + "contents_time": contents_time, + } + + def get_response(self, request, stream=False): + if isinstance(request, str): + # one request should be a list of messages, + # alternatively from the user and the assistant + request = [request] + if len(request) % 2 != 1: + raise ValueError( + "The length of the request messages should be odd." + "So that the final message is from the user." + ) + + if stream: + return self._get_response_stream(request) + + for outputs in self._get_response_stream(request): + pass + return outputs diff --git a/sot/schedulers/router_outline_batch_scheduler.py b/sot/schedulers/router_outline_batch_scheduler.py new file mode 100644 index 0000000..e09dccb --- /dev/null +++ b/sot/schedulers/router_outline_batch_scheduler.py @@ -0,0 +1,74 @@ +import re +import sys +import json +import logging +from collections import OrderedDict + +import torch +from termcolor import colored +from transformers import AutoModelForSequenceClassification, AutoTokenizer + +from .naive_scheduler import NaiveScheduler +from .outline_batch_scheduler import OutlineBatchScheduler +from sot.utils import _print_to_streams + + +class RouterOutlineBatchScheduler: + def __init__( + self, + model, + router_name_or_path, + naive_prompt_file=None, + outline_prompt_file=None, + **kwargs, + ): + self._model = model + self.router_tokenizer, self.router_model = self.load_router(router_name_or_path) + self.naive_scheduler = NaiveScheduler( + prompt_file=naive_prompt_file, model=self._model + ) + self.outline_scheduler = OutlineBatchScheduler( + prompt_file=outline_prompt_file, model=self._model + ) + + def load_router(self, router_name_or_path): + model = AutoModelForSequenceClassification.from_pretrained( + router_name_or_path, + num_labels=2, + local_files_only=True, + ).cuda() + model.config.use_cache = False + tokenizer = AutoTokenizer.from_pretrained( + router_name_or_path, + padding_size="right", + use_fast=False, + local_files_only=True, + ) + tokenizer.pad_token = tokenizer.unk_token + return tokenizer, model + + def get_fallback(self, request): + input_ids = self.router_tokenizer(request, return_tensors="pt").input_ids.cuda() + output = self.router_model(input_ids) + return torch.argmax(output[0]).item() + + def set_model(self, model): + self._model = model + + def get_response(self, request, stream=False): + if isinstance(request, str): + # one request should be a list of messages, + # alternatively from the user and the assistant + request = [request] + if len(request) % 2 != 1: + raise ValueError( + "The length of the request messages should be odd." + "So that the final message is from the user." + ) + + fallback = self.get_fallback(request[-1]) + + if fallback == 0: + return self.naive_scheduler.get_response(request, stream) + else: + return self.outline_scheduler.get_response(request, stream) diff --git a/sot/schedulers/scheduler.py b/sot/schedulers/scheduler.py new file mode 100644 index 0000000..4990e4d --- /dev/null +++ b/sot/schedulers/scheduler.py @@ -0,0 +1,26 @@ +from abc import ABC, abstractmethod +import argparse +import logging + + +class Scheduler(ABC): + def __init__(self, model): + self._model = model + + def print_info(self): + logging.info(f"Scheduler: {self.__class__}") + + @staticmethod + def command_line_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--scheduler_help", action="help") + return parser + + @classmethod + def from_command_line_args(cls, args, model): + args, other_args = cls.command_line_parser().parse_known_args(args) + return cls(**vars(args), model=model), other_args + + @abstractmethod + def get_response(self, request): + pass diff --git a/sot/train/__init__.py b/sot/train/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sot/train/confusion_matrix.py b/sot/train/confusion_matrix.py new file mode 100644 index 0000000..b9b88b0 --- /dev/null +++ b/sot/train/confusion_matrix.py @@ -0,0 +1,149 @@ +"""Confusion Matrix metric.""" + +import datasets +import evaluate +from sklearn.metrics import confusion_matrix + +_DESCRIPTION = """ +Compute confusion matrix to evaluate the accuracy of a classification. +By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` +is equal to the number of observations known to be in group :math:`i` and +predicted to be in group :math:`j`. + +Thus in binary classification, the count of true negatives is +:math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is +:math:`C_{1,1}` and false positives is :math:`C_{0,1}`. + +Read more in the :ref:`User Guide `. +""" + + +_KWARGS_DESCRIPTION = """ +Args: + + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated targets as returned by a classifier. + + labels : array-like of shape (n_classes), default=None + List of labels to index the matrix. This may be used to reorder + or select a subset of labels. + If ``None`` is given, those that appear at least once + in ``y_true`` or ``y_pred`` are used in sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + normalize : {'true', 'pred', 'all'}, default=None + Normalizes confusion matrix over the true (rows), predicted (columns) + conditions or all the population. If None, confusion matrix will not be + normalized. + +Returns: + + C : ndarray of shape (n_classes, n_classes) + Confusion matrix whose i-th row and j-th + column entry indicates the number of + samples with true label being i-th class + and predicted label being j-th class. + +See Also: + + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + ConfusionMatrixDisplay : Confusion Matrix visualization. + +References: + + .. [1] `Wikipedia entry for the Confusion matrix + `_ + (Wikipedia and other references may use a different + convention for axes). + +Examples: + + >>> from sklearn.metrics import confusion_matrix + >>> y_true = [2, 0, 2, 2, 0, 1] + >>> y_pred = [0, 0, 2, 2, 0, 2] + >>> confusion_matrix(y_true, y_pred) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] + >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] + >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + In the binary case, we can extract true positives, etc as follows: + + >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel() + >>> (tn, fp, fn, tp) + (0, 2, 1, 1) +""" + + +_CITATION = """ +@article{scikit-learn, + title={Scikit-learn: Machine Learning in {P}ython}, + author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. + and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. + and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and + Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, + journal={Journal of Machine Learning Research}, + volume={12}, + pages={2825--2830}, + year={2011} +} +""" + + +@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) +class ConfusionMatrix(evaluate.Metric): + def _info(self): + return evaluate.MetricInfo( + description=_DESCRIPTION, + citation=_CITATION, + inputs_description=_KWARGS_DESCRIPTION, + features=datasets.Features( + { + "predictions": datasets.Sequence(datasets.Value("int32")), + "references": datasets.Sequence(datasets.Value("int32")), + } + if self.config_name == "multilabel" + else { + "predictions": datasets.Value("int32"), + "references": datasets.Value("int32"), + } + ), + reference_urls=[ + "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html" + ], + ) + + def _compute( + self, + predictions, + references, + *, + labels=None, + sample_weight=None, + normalize=None, + ): + return { + "confusion_matrix": confusion_matrix( + y_true=references, + y_pred=predictions, + labels=labels, + sample_weight=sample_weight, + normalize=normalize, + ).tolist() + } diff --git a/sot/train/offline_prepare_router_data.py b/sot/train/offline_prepare_router_data.py new file mode 100644 index 0000000..bd09f3c --- /dev/null +++ b/sot/train/offline_prepare_router_data.py @@ -0,0 +1,74 @@ +import pickle +from typing import Dict +from dataclasses import dataclass, field + +import pandas as pd +import torch +import transformers + + +@dataclass +class ModelArguments: + model_name_or_path: str = field(default="roberta-base") + model_max_length: int = field(default=512) + + +@dataclass +class DataArguments: + data_path: str = field( + metadata={"help": "A csv file containing the training data."} + ) + output_data_path: str = field( + metadata={"help": "The pickle file name to dump the training data."} + ) + + +def preprocess( + sources, + tokenizer: transformers.PreTrainedTokenizer, +) -> Dict: + questions = list(sources["request"]) + labels = torch.tensor(sources["label"]).to(torch.long) + + inputs = tokenizer( + questions, + return_tensors="pt", + padding="max_length", + max_length=tokenizer.model_max_length, + truncation=True, + ) + + input_ids = inputs["input_ids"] + attention_mask = inputs["attention_mask"] + + assert len(input_ids) == len(labels) + + return dict( + input_ids=input_ids, + labels=labels, + attention_mask=attention_mask, + ) + + +if __name__ == "__main__": + parser = transformers.HfArgumentParser((ModelArguments, DataArguments)) + model_args, data_args = parser.parse_args_into_dataclasses() + tokenizer = transformers.AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + model_max_length=model_args.model_max_length, + padding_side="right", + use_fast=False, + ) + tokenizer.pad_token = tokenizer.unk_token + + # load the raw data + raw_data = pd.read_csv(data_args.data_path, delimiter=";") + + # preprocess + data = preprocess(raw_data, tokenizer) + + print("Data shape:", data["input_ids"].shape) + + with open(data_args.output_data_path, "wb") as wf: + print(f"Pickle dumping the data to {data_args.output_data_path}") + pickle.dump(data, wf) diff --git a/sot/train/train_router.py b/sot/train/train_router.py new file mode 100644 index 0000000..9c829e8 --- /dev/null +++ b/sot/train/train_router.py @@ -0,0 +1,254 @@ +# This code is based on lm-sys/FastChat and tatsu-lab/stanford_alpaca. Below is the original copyright +# from tatsu-label/stanford_alpaca. +# +# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import csv +import pickle +import pathlib +from typing import Dict +from dataclasses import dataclass, field + +import numpy as np +import torch +import torch.nn as nn +from torch.utils.data import Dataset +import evaluate +import transformers +from transformers import Trainer, AutoTokenizer, AutoModelForSequenceClassification + + +SEED = 0 + + +@dataclass +class ModelArguments: + model_name_or_path: str = field(default="roberta-base") + cache_dir: str = field(default=None) + num_labels: int = field(default=2) + model_max_length: int = field(default=512) + + +@dataclass +class DataArguments: + data_path: str = field( + default="lima_router.pkl", + metadata={"help": "A pickle file containing the processed LIMA data."}, + ) + vicuna_data_path: str = field(default="vicuna_router.pkl") + wizardlm_data_path: str = field(default="wizardlm_router.pkl") + vicuna_pred_path: str = field(default="vicuna_router_pred.csv") + wizardlm_pred_path: str = field(default="wizardlm_router_pred.csv") + train_val_ratio: float = field(default=0.8) + + +@dataclass +class TrainingArguments(transformers.TrainingArguments): + output_dir: str = field(default=".") + num_train_epochs: int = field(default=2) + per_device_train_batch_size: int = field(default=32) + per_device_eval_batch_size: int = field(default=32) + optim: str = field(default="adamw_torch") + learning_rate: float = field(default=5e-5) + weight_decay: float = field(default=0.01) + warmup_ratio: float = field(default=0.01) + label_smoothing: float = field(default=0.9) + tversky_ratio: float = field(default=0.75) + fp_ratio: float = field(default=0.7) + fn_ratio: float = field(default=0.3) + evaluation_strategy: str = field(default="epoch") + + +def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" + state_dict = trainer.model.state_dict() + if trainer.args.should_save: + cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()} + del state_dict + trainer._save(output_dir, state_dict=cpu_state_dict) # noqa + + +class SupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" + + def __init__(self, data_dict): + super(SupervisedDataset, self).__init__() + + self.input_ids = data_dict["input_ids"] + self.labels = data_dict["labels"] + self.attention_mask = data_dict["attention_mask"] + + def __len__(self): + return len(self.input_ids) + + def __getitem__(self, i) -> Dict[str, torch.Tensor]: + return dict( + input_ids=self.input_ids[i], + labels=self.labels[i], + attention_mask=self.attention_mask[i], + ) + + +def make_supervised_data_module( + data_dict: Dict[str, torch.Tensor], train_val_ratio: float +) -> Dict: + """Make dataset and collator for supervised fine-tuning.""" + dataset_cls = SupervisedDataset + + # Split train/test + np.random.seed(SEED) + perm = np.random.permutation(data_dict["input_ids"].shape[0]) + split = int(len(perm) * train_val_ratio) + train_indices = perm[:split] + eval_indices = perm[split:] + train_data_dict = {key: tensor[train_indices] for key, tensor in data_dict.items()} + eval_data_dict = {key: tensor[eval_indices] for key, tensor in data_dict.items()} + print(f"#train {len(train_indices)}, #eval {len(eval_indices)}") + + train_dataset = dataset_cls(train_data_dict) + eval_dataset = dataset_cls(eval_data_dict) + return dict(train_dataset=train_dataset, eval_dataset=eval_dataset) + + +def load_dataset(data_path): + with open(data_path, "rb") as rf: + data_dict = pickle.load(rf) + return data_dict + + +def save_predictions(results, pred_path): + predictions = np.argmax(results.predictions, axis=-1) + + with open(pred_path, "w", newline="") as csvfile: + writer = csv.writer(csvfile) + for pred in predictions: + writer.writerow([pred]) + + +# [[tn, fp], +# [fn, tp]] +metric = evaluate.load("confusion_matrix.py") + + +def compute_metrics(eval_pred): + logits, labels = eval_pred + predictions = np.argmax(logits, axis=-1) + return metric.compute(predictions=predictions, references=labels) + + +class CustomTrainer(Trainer): + def __init__(self, training_args, *args, **kwargs): + super().__init__(*args, **kwargs) + self.training_args = training_args + + def compute_loss(self, model, inputs, return_outputs=False): + outputs = model(**inputs) + logits = outputs.get("logits") + labels = inputs.pop("labels") + loss_ce = nn.functional.cross_entropy(logits, labels) + + labels = self.training_args.label_smoothing * labels.float() + probs = logits.log_softmax(dim=1).exp()[:, 1] + cardinality = torch.sum(probs + labels) + difference = torch.sum(torch.abs(probs - labels)) + intersection = 0.5 * (cardinality - difference) + fp = torch.sum(probs) - intersection + fn = torch.sum(labels) - intersection + tversky = intersection / ( + intersection + + self.training_args.fp_ratio * fp + + self.training_args.fn_ratio * fn + ) + loss_tversky = 1 - tversky + + loss = ( + 1 - self.training_args.tversky_ratio + ) * loss_ce + self.training_args.tversky_ratio * loss_tversky + + return (loss, outputs) if return_outputs else loss + + +def train(): + parser = transformers.HfArgumentParser( + (ModelArguments, DataArguments, TrainingArguments) + ) + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + model = AutoModelForSequenceClassification.from_pretrained( + model_args.model_name_or_path, + cache_dir=model_args.cache_dir, + num_labels=model_args.num_labels, + local_files_only=True, + ) + model.config.use_cache = False + tokenizer = AutoTokenizer.from_pretrained( + model_args.model_name_or_path, + cache_dir=model_args.cache_dir, + model_max_length=model_args.model_max_length, + padding_side="right", + use_fast=False, + local_files_only=True, + ) + tokenizer.pad_token = tokenizer.unk_token + + # load data and construct Dataset + print("Loading data...") + data_dict = load_dataset(data_args.data_path) + vicuna_data_dict = load_dataset(data_args.vicuna_data_path) + wizardlm_data_dict = load_dataset(data_args.wizardlm_data_path) + + data_module = make_supervised_data_module( + data_dict, train_val_ratio=data_args.train_val_ratio + ) + + vicuna_dataset = SupervisedDataset(vicuna_data_dict) + wizardlm_dataset = SupervisedDataset(wizardlm_data_dict) + + # construct trainer + trainer = CustomTrainer( + training_args=training_args, + model=model, + tokenizer=tokenizer, + args=training_args, + compute_metrics=compute_metrics, + **data_module, + ) + + if list(pathlib.Path(training_args.output_dir).glob("checkpoint-*")): + trainer.train(resume_from_checkpoint=True) + else: + trainer.train() + + vicuna_results = trainer.predict(vicuna_dataset) + print(vicuna_results.metrics) + vicuna_pred_path = os.path.join( + training_args.output_dir, data_args.vicuna_pred_path + ) + save_predictions(vicuna_results, vicuna_pred_path) + + wizardlm_results = trainer.predict(wizardlm_dataset) + print(wizardlm_results.metrics) + wizardlm_pred_path = os.path.join( + training_args.output_dir, data_args.wizardlm_pred_path + ) + save_predictions(wizardlm_results, wizardlm_pred_path) + + trainer.save_state() + safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir) + + +if __name__ == "__main__": + train() diff --git a/sot/utils/__init__.py b/sot/utils/__init__.py new file mode 100644 index 0000000..7328a4b --- /dev/null +++ b/sot/utils/__init__.py @@ -0,0 +1,3 @@ +def _print_to_streams(streams, text, **print_kwargs): + for stream in streams: + print(text, file=stream, **print_kwargs) diff --git a/sot/utils/logging.py b/sot/utils/logging.py new file mode 100644 index 0000000..81e99a4 --- /dev/null +++ b/sot/utils/logging.py @@ -0,0 +1,20 @@ +import logging + +logger = logging.getLogger() + + +def setup_logging(log_file): + log_formatter = logging.Formatter( + fmt="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s", + datefmt="%m/%d/%Y %H:%M:%S %p", + ) + root_logger = logging.getLogger() + root_logger.setLevel(logging.DEBUG) + + console_handler = logging.StreamHandler() + console_handler.setFormatter(log_formatter) + root_logger.addHandler(console_handler) + + file_handler = logging.FileHandler(log_file) + file_handler.setFormatter(log_formatter) + root_logger.addHandler(file_handler)