title
stringlengths
2
169
diff
stringlengths
235
19.5k
body
stringlengths
0
30.5k
url
stringlengths
48
84
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
diff_len
float64
101
3.99k
repo_name
stringclasses
83 values
__index_level_0__
int64
15
52.7k
poloniex error mapping
diff --git a/js/poloniex.js b/js/poloniex.js index 40b212539ac1..e46db845be54 100644 --- a/js/poloniex.js +++ b/js/poloniex.js @@ -223,7 +223,7 @@ module.exports = class poloniex extends Exchange { }, 'broad': { 'Total must be at least': InvalidOrder, // {"error":"Total must be at least 0.0001."} - 'This account is frozen.': AccountSuspended, + 'This account is frozen': AccountSuspended, // {"error":"This account is frozen for trading."} || {"error":"This account is frozen."} 'This account is locked.': AccountSuspended, // {"error":"This account is locked."} 'Not enough': InsufficientFunds, 'Nonce must be greater': InvalidNonce,
https://api.github.com/repos/ccxt/ccxt/pulls/11935
2022-02-11T19:42:44Z
2022-02-11T20:24:14Z
2022-02-11T20:24:14Z
2022-02-11T20:24:14Z
194
ccxt/ccxt
13,751
livecoin safeSymbol
diff --git a/js/livecoin.js b/js/livecoin.js index a9c7a7d70771..e729b7fcaa2e 100644 --- a/js/livecoin.js +++ b/js/livecoin.js @@ -448,21 +448,8 @@ module.exports = class livecoin extends Exchange { cost = amount * price; } } - let symbol = undefined; const marketId = this.safeString (trade, 'symbol'); - if (marketId !== undefined) { - if (marketId in this.markets_by_id) { - market = this.markets_by_id[marketId]; - } else { - const [ baseId, quoteId ] = marketId.split ('/'); - const base = this.safeCurrencyCode (baseId); - const quote = this.safeCurrencyCode (quoteId); - symbol = base + '/' + quote; - } - } - if ((symbol === undefined) && (market !== undefined)) { - symbol = market['symbol']; - } + const symbol = this.safeSymbol (marketId, market, '/'); return { 'id': id, 'info': trade, @@ -587,14 +574,8 @@ module.exports = class livecoin extends Exchange { // let trades = this.parseTrades (order['trades'], market, since, limit); const trades = undefined; const status = this.parseOrderStatus (this.safeString2 (order, 'status', 'orderStatus')); - let symbol = undefined; - if (market === undefined) { - let marketId = this.safeString (order, 'currencyPair'); - marketId = this.safeString (order, 'symbol', marketId); - if (marketId in this.markets_by_id) { - market = this.markets_by_id[marketId]; - } - } + const marketId = this.safeString2 (order, 'symbol', 'currencyPair'); + const symbol = this.safeSymbol (marketId, market, '/'); let type = this.safeStringLower (order, 'type'); let side = undefined; if (type !== undefined) { @@ -620,9 +601,11 @@ module.exports = class livecoin extends Exchange { if (cost !== undefined && feeRate !== undefined) { feeCost = cost * feeRate; } + if ((market === undefined) && (symbol in this.markets)) { + market = this.markets[symbol]; + } let feeCurrency = undefined; if (market !== undefined) { - symbol = market['symbol']; feeCurrency = market['quote']; } return {
https://api.github.com/repos/ccxt/ccxt/pulls/7679
2020-10-02T17:56:41Z
2020-10-03T00:27:34Z
2020-10-03T00:27:34Z
2020-10-03T00:27:34Z
582
ccxt/ccxt
13,385
Update changing.py
diff --git a/manimlib/mobject/changing.py b/manimlib/mobject/changing.py index 0f10f5e3a0..69e9302ba3 100644 --- a/manimlib/mobject/changing.py +++ b/manimlib/mobject/changing.py @@ -92,7 +92,7 @@ def update_path(self): self.get_points()[-1] = new_point # Second to last point - nppcc = self.n_points_per_cubic_curve + nppcc = self.n_points_per_curve dist = get_norm(new_point - self.get_points()[-nppcc]) if dist >= self.min_distance_to_new_point: self.add_line_to(new_point)
To fix the error of "AttributeError: 'TracedPath' object has no attribute 'n_points_per_cubic_curve'" (because in the CONFIG dictionary of VMobject class, the n_points_per_cubic_curve dose not exist, and now 'n_points_per_curve' is used instead)
https://api.github.com/repos/3b1b/manim/pulls/1386
2021-02-13T13:08:38Z
2021-02-13T13:15:24Z
2021-02-13T13:15:24Z
2021-02-13T13:16:07Z
163
3b1b/manim
18,462
Fix typos (user-facing and non-user-facing
diff --git a/.github/workflows/release-snap.yml b/.github/workflows/release-snap.yml index afb22e841f..c415edd76e 100644 --- a/.github/workflows/release-snap.yml +++ b/.github/workflows/release-snap.yml @@ -15,7 +15,7 @@ jobs: strategy: # If any of the stages fail, then we'll stop the action - # to give release manager time to investigate the underyling + # to give release manager time to investigate the underlying # issue. fail-fast: true matrix: diff --git a/extras/packaging/linux/README.md b/extras/packaging/linux/README.md index a62e4dc58e..2958dfaef4 100644 --- a/extras/packaging/linux/README.md +++ b/extras/packaging/linux/README.md @@ -23,7 +23,7 @@ contains 2 major methods: We use [PyInstaller](https://pyinstaller.readthedocs.io/en/stable/) for the binaries. Normally pyinstaller offers two different modes: -- Single directory (harder to distribute, low redundancy. Library files are shared accross different executables) +- Single directory (harder to distribute, low redundancy. Library files are shared across different executables) - Single binary (easier to distribute, higher redundancy. Same libraries are statically linked to different executables, so higher total size) Since our binary size (in total 20 MiBs) is not that big, we have decided to choose the single binary mode for the sake of easier distribution. diff --git a/extras/profiling/README.md b/extras/profiling/README.md index c2487de4a6..0eef816656 100644 --- a/extras/profiling/README.md +++ b/extras/profiling/README.md @@ -1,7 +1,7 @@ # HTTPie Benchmarking Infrastructure This directory includes the benchmarks we use for testing HTTPie's speed and the -infrastructure to automate this testing accross versions. +infrastructure to automate this testing across versions. ## Usage @@ -35,5 +35,5 @@ You can customize these branches by passing `--local-repo`/`--target-branch`, and customize the repos by passing `--local-repo`/`--target-repo` (can either take a URL or a path). -If you want to run a third enviroment with additional dependencies (such as +If you want to run a third environment with additional dependencies (such as `pyOpenSSL`), you can pass `--complex`. diff --git a/extras/profiling/benchmarks.py b/extras/profiling/benchmarks.py index 5d47a3a125..ede4915f63 100644 --- a/extras/profiling/benchmarks.py +++ b/extras/profiling/benchmarks.py @@ -21,7 +21,7 @@ $ python extras/profiling/benchmarks.py --fast # For verify everything works as expected, pass --debug-single-value. - # It will only run everything once, so the resuls are not realiable. But + # It will only run everything once, so the resuls are not reliable. But # very useful when iterating on a benchmark $ python extras/profiling/benchmarks.py --debug-single-value diff --git a/httpie/context.py b/httpie/context.py index 44aedd421c..da4d19257e 100644 --- a/httpie/context.py +++ b/httpie/context.py @@ -205,7 +205,7 @@ def _make_rich_console( theme=Theme(theme) ) - # Rich recommends separting the actual console (stdout) from + # Rich recommends separating the actual console (stdout) from # the error (stderr) console for better isolation between parts. # https://rich.readthedocs.io/en/stable/console.html#error-console diff --git a/httpie/manager/tasks/plugins.py b/httpie/manager/tasks/plugins.py index a0180537f5..c3c7d540c7 100644 --- a/httpie/manager/tasks/plugins.py +++ b/httpie/manager/tasks/plugins.py @@ -165,7 +165,7 @@ def _uninstall(self, target: str) -> Optional[ExitStatus]: return self.fail('uninstall', target, 'couldn\'t locate the package') # TODO: Consider handling failures here (e.g if it fails, - # just rever the operation and leave the site-packages + # just revert the operation and leave the site-packages # in a proper shape). for file in files: with suppress(FileNotFoundError): diff --git a/httpie/plugins/manager.py b/httpie/plugins/manager.py index 0a25f320e4..27af6eedac 100644 --- a/httpie/plugins/manager.py +++ b/httpie/plugins/manager.py @@ -70,7 +70,7 @@ def load_installed_plugins(self, directory: Optional[Path] = None): plugin = entry_point.load() except BaseException as exc: warnings.warn( - f'While loading "{plugin_name}", an error ocurred: {exc}\n' + f'While loading "{plugin_name}", an error occurred: {exc}\n' f'For uninstallations, please use either "httpie plugins uninstall {plugin_name}" ' f'or "pip uninstall {plugin_name}" (depending on how you installed it in the first ' 'place).' diff --git a/tests/test_cli_utils.py b/tests/test_cli_utils.py index 2ea319d848..8041727b57 100644 --- a/tests/test_cli_utils.py +++ b/tests/test_cli_utils.py @@ -28,7 +28,7 @@ def test_lazy_choices(): cache=False # for test purposes ) - # Parser initalization doesn't call it. + # Parser initialization doesn't call it. getter.assert_not_called() # If we don't use --lazy-option, we don't retrieve it. @@ -69,7 +69,7 @@ def test_lazy_choices_help(): cache=False # for test purposes ) - # Parser initalization doesn't call it. + # Parser initialization doesn't call it. getter.assert_not_called() # If we don't use `--help`, we don't use it. diff --git a/tests/test_plugins_cli.py b/tests/test_plugins_cli.py index 7be110de3b..2805792364 100644 --- a/tests/test_plugins_cli.py +++ b/tests/test_plugins_cli.py @@ -138,7 +138,7 @@ def test_broken_plugins(httpie_plugins, httpie_plugins_success, dummy_plugin, br UserWarning, match=( f'While loading "{broken_plugin.name}", an error' - ' ocurred: broken plugin' + ' occurred: broken plugin' ) ): data = parse_listing(httpie_plugins_success('list')) diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py index 79cafa07cd..8a575aef03 100644 --- a/tests/utils/__init__.py +++ b/tests/utils/__init__.py @@ -83,7 +83,7 @@ class Encoder: def __init__(self): self.substitutions = {} - def subsitute(self, data: bytes) -> str: + def substitute(self, data: bytes) -> str: idx = hash(data) self.substitutions[idx] = data return self.TEMPLATE.format(idx) @@ -110,7 +110,7 @@ def write(self, data): try: self.original_buffer.write(data.decode(UTF8)) except UnicodeDecodeError: - self.original_buffer.write(self.encoder.subsitute(data)) + self.original_buffer.write(self.encoder.substitute(data)) finally: self.original_buffer.flush()
Found via `codespell -q 3 -L datas,medias,warmup`
https://api.github.com/repos/httpie/cli/pulls/1357
2022-04-15T21:57:39Z
2022-04-15T23:06:34Z
2022-04-15T23:06:34Z
2022-04-20T02:16:30Z
1,765
httpie/cli
33,938
[generic] prefer enclosures over following links in rss feeds
diff --git a/youtube_dl/extractor/generic.py b/youtube_dl/extractor/generic.py index e3cb5c5ce51..c548a164907 100644 --- a/youtube_dl/extractor/generic.py +++ b/youtube_dl/extractor/generic.py @@ -190,6 +190,16 @@ class GenericIE(InfoExtractor): 'title': 'pdv_maddow_netcast_m4v-02-27-2015-201624', } }, + # RSS feed with enclosures and unsupported link URLs + { + 'url': 'http://www.hellointernet.fm/podcast?format=rss', + 'info_dict': { + 'id': 'http://www.hellointernet.fm/podcast?format=rss', + 'description': 'CGP Grey and Brady Haran talk about YouTube, life, work, whatever.', + 'title': 'Hello Internet', + }, + 'playlist_mincount': 100, + }, # SMIL from http://videolectures.net/promogram_igor_mekjavic_eng { 'url': 'http://videolectures.net/promogram_igor_mekjavic_eng/video/1/smil.xml', @@ -2009,13 +2019,15 @@ def _extract_rss(self, url, video_id, doc): entries = [] for it in doc.findall('./channel/item'): - next_url = xpath_text(it, 'link', fatal=False) + next_url = None + enclosure_nodes = it.findall('./enclosure') + for e in enclosure_nodes: + next_url = e.attrib.get('url') + if next_url: + break + if not next_url: - enclosure_nodes = it.findall('./enclosure') - for e in enclosure_nodes: - next_url = e.attrib.get('url') - if next_url: - break + next_url = xpath_text(it, 'link', fatal=False) if not next_url: continue
## Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [adding new extractor tutorial](https://github.com/rg3/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/rg3/youtube-dl#youtube-dl-coding-conventions) sections - [x] [Searched](https://github.com/rg3/youtube-dl/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) ### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [ ] Bug fix - [x] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information When downloading from rss feeds, the generic extractor follows the rss links first. This leads to "ERROR: Unsupported URL" messages in a lot of cases. Even though there are enclosures present. ``` $ youtube-dl --playlist-end 1 http://www.hellointernet.fm/podcast?format=rss [generic] podcast?format=rss: Requesting header WARNING: Falling back on generic information extractor. [generic] podcast?format=rss: Downloading webpage [generic] podcast?format=rss: Extracting information [download] Downloading playlist: Hello Internet [generic] playlist Hello Internet: Collected 100 video ids (downloading 1 of them) [download] Downloading video 1 of 1 [generic] onehundred: Requesting header WARNING: Falling back on generic information extractor. [generic] onehundred: Downloading webpage [generic] onehundred: Extracting information ERROR: Unsupported URL: http://www.hellointernet.fm/podcast/onehundred ``` With this pull request downloading enclosures is preferred over following the rss links. ``` $ python -m youtube_dl --playlist-end 1 http://www.hellointernet.fm/podcast?format=rss [generic] podcast?format=rss: Requesting header WARNING: Falling back on generic information extractor. [generic] podcast?format=rss: Downloading webpage [generic] podcast?format=rss: Extracting information [download] Downloading playlist: Hello Internet [generic] playlist Hello Internet: Collected 100 video ids (downloading 1 of them) [download] Downloading video 1 of 1 [generic] Hello_Internet_Episode_One_Hundred: Requesting header [redirect] Following redirect to http://hwcdn.libsyn.com/p/e/5/c/e5ca0f579a9f12b4/Hello_Internet_Episode_One_Hundred.mp3?c_id=20078576&expiration=1523726590&hwt=d00666280d294aea41062d82e934b6f0 [generic] Hello_Internet_Episode_One_Hundred: Requesting header [download] Destination: Hello Internet Episode One Hundred-Hello_Internet_Episode_One_Hundred.mp3 [download] 100% of 96.39MiB in 00:09 [download] Finished downloading playlist: Hello Internet ```
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/16189
2018-04-14T15:39:25Z
2018-04-29T15:14:38Z
2018-04-29T15:14:38Z
2018-04-29T17:21:14Z
451
ytdl-org/youtube-dl
49,817
Updated registration.py
diff --git a/gym/envs/registration.py b/gym/envs/registration.py index 7014939a4c4..fd23b9fce0a 100644 --- a/gym/envs/registration.py +++ b/gym/envs/registration.py @@ -1,7 +1,6 @@ import re import copy import importlib -import warnings from gym import error, logger @@ -104,16 +103,6 @@ def make(self, path, **kwargs): logger.info("Making new env: %s", path) spec = self.spec(path) env = spec.make(**kwargs) - # We used to have people override _reset/_step rather than - # reset/step. Set _gym_disable_underscore_compat = True on - # your environment if you use these methods and don't want - # compatibility code to be invoked. - if ( - hasattr(env, "_reset") - and hasattr(env, "_step") - and not getattr(env, "_gym_disable_underscore_compat", False) - ): - patch_deprecated_methods(env) if env.spec.max_episode_steps is not None: from gym.wrappers.time_limit import TimeLimit @@ -125,11 +114,10 @@ def all(self): def spec(self, path): if ":" in path: - mod_name, _sep, id = path.partition(":") + mod_name, _, id = path.partition(":") try: importlib.import_module(mod_name) - # catch ImportError for python2.7 compatibility - except ImportError: + except ModuleNotFoundError: raise error.Error( "A module ({}) was specified for the environment but was not found, make sure the package is installed with `pip install` before calling `gym.make()`".format( mod_name @@ -182,7 +170,7 @@ def spec(self, path): def register(self, id, **kwargs): if id in self.env_specs: - raise error.Error("Cannot re-register id: {}".format(id)) + logger.warn("Overriding environment {}".format(id)) self.env_specs[id] = EnvSpec(id, **kwargs) @@ -200,32 +188,3 @@ def make(id, **kwargs): def spec(id): return registry.spec(id) - - -warn_once = True - - -def patch_deprecated_methods(env): - """ - Methods renamed from '_method' to 'method', render() no longer has 'close' parameter, close is a separate method. - For backward compatibility, this makes it possible to work with unmodified environments. - """ - global warn_once - if warn_once: - logger.warn( - "Environment '%s' has deprecated methods '_step' and '_reset' rather than 'step' and 'reset'. Compatibility code invoked. Set _gym_disable_underscore_compat = True to disable this behavior." - % str(type(env)) - ) - warn_once = False - env.reset = env._reset - env.step = env._step - env.seed = env._seed - - def render(mode): - return env._render(mode, close=False) - - def close(): - env._render("human", close=True) - - env.render = render - env.close = close
Changes: Re-registering the same environment ID in using gym.register() now raises a warning instead of an exception Deprecate Python 2.7 by changing ImportError to ModuleNotFoundError Remove the deprecated _step, _reset, and render(close) methods (These have been deprecated since at least 2018, but not removed) Please let me know if you would like me to remove any of these changes.
https://api.github.com/repos/openai/gym/pulls/2375
2021-08-29T17:20:28Z
2021-09-01T18:27:01Z
2021-09-01T18:27:01Z
2021-09-01T18:27:01Z
732
openai/gym
5,429
Disable Initial Prompt Task for en and es Locales
diff --git a/.github/workflows/deploy-to-node.yaml b/.github/workflows/deploy-to-node.yaml index bbb04f7b3a..4a16cffd4c 100644 --- a/.github/workflows/deploy-to-node.yaml +++ b/.github/workflows/deploy-to-node.yaml @@ -38,6 +38,7 @@ jobs: S3_REGION: ${{ secrets.S3_REGION }} AWS_ACCESS_KEY: ${{ secrets.AWS_ACCESS_KEY }} AWS_SECRET_KEY: ${{ secrets.AWS_SECRET_KEY }} + INIT_PROMPT_DISABLED_LANGS: ${{ vars.INIT_PROMPT_DISABLED_LANGS }} MAX_ACTIVE_TREES: ${{ vars.MAX_ACTIVE_TREES }} MAX_INITIAL_PROMPT_REVIEW: ${{ vars.MAX_INITIAL_PROMPT_REVIEW }} MAX_TREE_DEPTH: ${{ vars.MAX_TREE_DEPTH }} diff --git a/ansible/deploy-to-node.yaml b/ansible/deploy-to-node.yaml index a690aa45e8..7a0c70e956 100644 --- a/ansible/deploy-to-node.yaml +++ b/ansible/deploy-to-node.yaml @@ -112,6 +112,9 @@ "{{ lookup('ansible.builtin.env', 'SKIP_TOXICITY_CALCULATION') | default('true', true) }}" OFFICIAL_WEB_API_KEY: "{{ web_api_key }}" + TREE_MANAGER__INIT_PROMPT_DISABLED_LANGS: + "{{ lookup('ansible.builtin.env', 'INIT_PROMPT_DISABLED_LANGS') | + default('', true) }}" TREE_MANAGER__MAX_ACTIVE_TREES: "{{ lookup('ansible.builtin.env', 'MAX_ACTIVE_TREES') | default('10', true) }}" diff --git a/backend/oasst_backend/config.py b/backend/oasst_backend/config.py index 2edd061601..e3d37c7ba0 100644 --- a/backend/oasst_backend/config.py +++ b/backend/oasst_backend/config.py @@ -149,6 +149,12 @@ class TreeManagerConfiguration(BaseModel): """Maximum number of prompts in prompt_lottery_waiting state per language. If this value is exceeded no new initial prompt tasks for that language are generated.""" + init_prompt_disabled_langs: str = "" + + @property + def init_prompt_disabled_langs_list(self) -> list[str]: + return self.init_prompt_disabled_langs.split(",") + class Settings(BaseSettings): PROJECT_NAME: str = "open-assistant backend" diff --git a/backend/oasst_backend/tree_manager.py b/backend/oasst_backend/tree_manager.py index 1161240c0e..59ef964b35 100644 --- a/backend/oasst_backend/tree_manager.py +++ b/backend/oasst_backend/tree_manager.py @@ -367,8 +367,12 @@ def determine_task_availability(self, lang: str) -> dict[protocol_schema.TaskReq lang = "en" logger.warning("Task availability request without lang tag received, assuming lang='en'.") + if lang in self.cfg.init_prompt_disabled_langs_list: + num_missing_prompts = 0 + else: + num_missing_prompts = self._prompt_lottery(lang=lang, max_activate=1) + self._auto_moderation(lang=lang) - num_missing_prompts = self._prompt_lottery(lang=lang, max_activate=1) extendible_parents, _ = self.query_extendible_parents(lang=lang) prompts_need_review = self.query_prompts_need_review(lang=lang) replies_need_review = self.query_replies_need_review(lang=lang) @@ -718,7 +722,7 @@ async def handle_interaction(self, interaction: protocol_schema.AnyInteraction) logger.info( f"TreeManager: Inserting new tree state for initial prompt {message.id=} [{message.lang}]" ) - self._insert_default_state(message.id, message.lang) + self._insert_default_state(message.id, lang=message.lang) if not settings.DEBUG_SKIP_EMBEDDING_COMPUTATION: try:
To help clear the prompt backlog, as per https://github.com/LAION-AI/Open-Assistant/issues/1659, and Andreas's suggestions in https://github.com/LAION-AI/Open-Assistant/pull/1824, this adds the option to disable initial prompts for configured languages.
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/1849
2023-02-24T19:40:18Z
2023-04-04T20:48:16Z
2023-04-04T20:48:16Z
2023-04-04T20:52:00Z
878
LAION-AI/Open-Assistant
37,424
ref(text-overflow): Update TextOverflow Component
diff --git a/docs-ui/components/textOverflow.stories.js b/docs-ui/components/textOverflow.stories.js index 1bee66a89e19da..aa94836eb2277c 100644 --- a/docs-ui/components/textOverflow.stories.js +++ b/docs-ui/components/textOverflow.stories.js @@ -1,5 +1,6 @@ import React from 'react'; import {withInfo} from '@storybook/addon-info'; +import {boolean, select} from '@storybook/addon-knobs'; import TextOverflow from 'app/components/textOverflow'; @@ -11,7 +12,16 @@ export const _TextOverflow = withInfo( 'Simple component that adds "text-overflow: ellipsis" and "overflow: hidden", still depends on container styles' )(() => ( <div style={{width: 50}}> - <TextOverflow>AReallyLongTextString</TextOverflow> + <TextOverflow + isParagraph={boolean('isParagraph', false)} + ellipsisDirection={select( + 'ellipsisDirection', + {right: 'right', left: 'left'}, + 'right' + )} + > + AReallyLongTextString + </TextOverflow> </div> )); diff --git a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryDevice.tsx b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryDevice.tsx index 54ac5fc64643d9..c8b8c64b7d4b2b 100644 --- a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryDevice.tsx +++ b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryDevice.tsx @@ -8,7 +8,7 @@ import {getMeta} from 'app/components/events/meta/metaProxy'; import AnnotatedText from 'app/components/events/meta/annotatedText'; import DeviceName from 'app/components/deviceName'; import space from 'app/styles/space'; -import {ParagraphOverflow} from 'app/components/textOverflow'; +import TextOverflow from 'app/components/textOverflow'; import generateClassName from './generateClassName'; import ContextSummaryNoSummary from './contextSummaryNoSummary'; @@ -79,10 +79,10 @@ const ContextSummaryDevice = ({data}: Props) => { <Item className={className} icon={<span className="context-item-icon" />}> <h3>{renderName()}</h3> {subTitle && ( - <ParagraphOverflow> + <TextOverflow isParagraph> <Subject>{subTitle.subject}</Subject> <AnnotatedText value={subTitle.value} meta={subTitle.meta} /> - </ParagraphOverflow> + </TextOverflow> )} </Item> ); diff --git a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGPU.tsx b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGPU.tsx index 3164ccc09f343d..e7d7fd105e82bd 100644 --- a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGPU.tsx +++ b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGPU.tsx @@ -7,7 +7,7 @@ import {Meta} from 'app/types'; import {getMeta} from 'app/components/events/meta/metaProxy'; import AnnotatedText from 'app/components/events/meta/annotatedText'; import space from 'app/styles/space'; -import {ParagraphOverflow} from 'app/components/textOverflow'; +import TextOverflow from 'app/components/textOverflow'; import ContextSummaryNoSummary from './contextSummaryNoSummary'; import generateClassName from './generateClassName'; @@ -62,10 +62,10 @@ const ContextSummaryGPU = ({data}: Props) => { return ( <Item className={className} icon={<span className="context-item-icon" />}> <h3>{renderName()}</h3> - <ParagraphOverflow> + <TextOverflow isParagraph> <Subject>{versionElement.subject}</Subject> <AnnotatedText value={versionElement.value} meta={versionElement.meta} /> - </ParagraphOverflow> + </TextOverflow> </Item> ); }; diff --git a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGeneric.tsx b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGeneric.tsx index 7f6f117ac5b787..7e5d2cb1d85597 100644 --- a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGeneric.tsx +++ b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryGeneric.tsx @@ -5,7 +5,7 @@ import {t} from 'app/locale'; import {getMeta} from 'app/components/events/meta/metaProxy'; import AnnotatedText from 'app/components/events/meta/annotatedText'; import space from 'app/styles/space'; -import {ParagraphOverflow} from 'app/components/textOverflow'; +import TextOverflow from 'app/components/textOverflow'; import ContextSummaryNoSummary from './contextSummaryNoSummary'; import generateClassName from './generateClassName'; @@ -36,10 +36,10 @@ const ContextSummaryGeneric = ({data, unknownTitle}: Props) => { return ( <Item className={className} icon={<span className="context-item-icon" />}> <h3>{renderValue('name')}</h3> - <ParagraphOverflow> + <TextOverflow isParagraph> <Subject>{t('Version:')}</Subject> {!data.version ? t('Unknown') : renderValue('version')} - </ParagraphOverflow> + </TextOverflow> </Item> ); }; diff --git a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryOS.tsx b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryOS.tsx index c7da5b194f1ef4..b4b9e438fa27ef 100644 --- a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryOS.tsx +++ b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryOS.tsx @@ -7,7 +7,7 @@ import {Meta} from 'app/types'; import {getMeta} from 'app/components/events/meta/metaProxy'; import AnnotatedText from 'app/components/events/meta/annotatedText'; import space from 'app/styles/space'; -import {ParagraphOverflow} from 'app/components/textOverflow'; +import TextOverflow from 'app/components/textOverflow'; import ContextSummaryNoSummary from './contextSummaryNoSummary'; import generateClassName from './generateClassName'; @@ -68,10 +68,10 @@ const ContextSummaryOS = ({data}: Props) => { return ( <Item className={className} icon={<span className="context-item-icon" />}> <h3>{renderName()}</h3> - <ParagraphOverflow> + <TextOverflow isParagraph> <Subject>{versionElement.subject}</Subject> <AnnotatedText value={versionElement.value} meta={versionElement.meta} /> - </ParagraphOverflow> + </TextOverflow> </Item> ); }; diff --git a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryUser.tsx b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryUser.tsx index a2287f78da898c..7147c929f02ccf 100644 --- a/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryUser.tsx +++ b/src/sentry/static/sentry/app/components/events/contextSummary/contextSummaryUser.tsx @@ -8,7 +8,7 @@ import UserAvatar from 'app/components/avatar/userAvatar'; import {getMeta} from 'app/components/events/meta/metaProxy'; import AnnotatedText from 'app/components/events/meta/annotatedText'; import space from 'app/styles/space'; -import {ParagraphOverflow} from 'app/components/textOverflow'; +import TextOverflow from 'app/components/textOverflow'; import ContextSummaryNoSummary from './contextSummaryNoSummary'; import Item from './item'; @@ -49,10 +49,10 @@ const ContextSummaryUser = ({data}: Props) => { } return ( - <ParagraphOverflow> + <TextOverflow isParagraph> <Subject>{userDetails.subject}</Subject> <AnnotatedText value={userDetails.value} meta={userDetails.meta} /> - </ParagraphOverflow> + </TextOverflow> ); }; diff --git a/src/sentry/static/sentry/app/components/textOverflow.tsx b/src/sentry/static/sentry/app/components/textOverflow.tsx index 05d1828efca500..ee2d0266533a3f 100644 --- a/src/sentry/static/sentry/app/components/textOverflow.tsx +++ b/src/sentry/static/sentry/app/components/textOverflow.tsx @@ -1,18 +1,27 @@ +import React from 'react'; import styled from '@emotion/styled'; -const overflow = ` - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; -`; +import overflowEllipsisLeft from 'app/styles/overflowEllipsisLeft'; +import overflowEllipsis from 'app/styles/overflowEllipsis'; -const TextOverflow = styled('div')` - ${overflow} -`; +type Props = { + children: React.ReactNode; + isParagraph?: boolean; + ellipsisDirection?: 'left' | 'right'; + className?: string; +}; -const ParagraphOverflow = styled('p')` - ${overflow} +const TextOverflow = styled(({isParagraph, className, children}: Props) => { + const Component = isParagraph ? 'p' : 'div'; + return <Component className={className}>{children}</Component>; +})` + ${p => (p.ellipsisDirection === 'right' ? overflowEllipsis : overflowEllipsisLeft)}; + width: auto; `; -export {TextOverflow, ParagraphOverflow}; +TextOverflow.defaultProps = { + ellipsisDirection: 'right', + isParagraph: false, +}; + export default TextOverflow;
Unites the `ParagraphOverflow` and `TextOverflow` components Introduce the prop `ellipsisDirection` which can be `left` or `right` ![image](https://user-images.githubusercontent.com/29228205/98688301-fcd11b00-236a-11eb-851e-f8f858aa7b1f.png) ![image](https://user-images.githubusercontent.com/29228205/98688327-065a8300-236b-11eb-86b4-b4413f745d12.png)
https://api.github.com/repos/getsentry/sentry/pulls/21901
2020-11-10T14:17:24Z
2020-11-11T08:45:49Z
2020-11-11T08:45:49Z
2020-12-17T22:29:25Z
2,197
getsentry/sentry
44,591
VMware: new module : vmware_cluster_facts
diff --git a/lib/ansible/modules/cloud/vmware/vmware_cluster_facts.py b/lib/ansible/modules/cloud/vmware/vmware_cluster_facts.py new file mode 100644 index 00000000000000..55d9366c01cd62 --- /dev/null +++ b/lib/ansible/modules/cloud/vmware/vmware_cluster_facts.py @@ -0,0 +1,225 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright: (c) 2018, Ansible Project +# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = ''' +--- +module: vmware_cluster_facts +short_description: Gather facts about clusters available in given vCenter +description: + - This module can be used to gather facts about clusters in VMWare infrastructure. + - All values and VMware object names are case sensitive. +version_added: '2.6' +author: + - Abhijeet Kasurde (@akasurde) +notes: + - Tested on vSphere 6.5 +requirements: + - "python >= 2.6" + - PyVmomi +options: + datacenter: + description: + - Datacenter to search for cluster/s. + - This parameter is required, if C(cluster_name) is not supplied. + required: False + cluster_name: + description: + - Name of the cluster. + - If set, facts of this cluster will be returned. + - This parameter is required, if C(datacenter) is not supplied. + required: False +extends_documentation_fragment: vmware.documentation +''' + +EXAMPLES = ''' +- name: Gather cluster facts from given datacenter + vmware_cluster_facts: + hostname: 192.168.1.209 + username: administrator@vsphere.local + password: vmware + datacenter: ha-datacenter + validate_certs: False + delegate_to: localhost + register: cluster_facts + +- name: Gather facts from datacenter about specific cluster + vmware_cluster_facts: + hostname: 192.168.1.209 + username: administrator@vsphere.local + password: vmware + cluster_name: DC0_C0 + validate_certs: False + delegate_to: localhost + register: cluster_facts +''' + +RETURN = """ +clusters: + description: metadata about the available clusters + returned: always + type: dict + sample: { + "DC0_C0": { + "drs_default_vm_behavior": null, + "drs_enable_vm_behavior_overrides": null, + "drs_vmotion_rate": null, + "enable_ha": null, + "enabled_drs": true, + "enabled_vsan": false, + "ha_admission_control_enabled": null, + "ha_failover_level": null, + "ha_host_monitoring": null, + "ha_restart_priority": null, + "ha_vm_failure_interval": null, + "ha_vm_max_failure_window": null, + "ha_vm_max_failures": null, + "ha_vm_min_up_time": null, + "ha_vm_monitoring": null, + "ha_vm_tools_monitoring": null, + "vsan_auto_claim_storage": false + }, + } +""" + +try: + from pyVmomi import vim +except ImportError: + pass + + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, find_datacenter_by_name, find_cluster_by_name + + +class VmwreClusterFactsManager(PyVmomi): + def __init__(self, module): + super(VmwreClusterFactsManager, self).__init__(module) + datacenter = self.params.get('datacenter') + cluster_name = self.params.get('cluster_name') + self.cluster_objs = [] + if datacenter: + datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter) + if datacenter_obj is None: + self.module.fail_json(msg="Failed to find datacenter '%s'" % datacenter) + self.cluster_objs = self.get_all_cluster_objs(parent=datacenter_obj) + elif cluster_name: + cluster_obj = find_cluster_by_name(self.content, cluster_name=cluster_name) + if cluster_obj is None: + self.module.fail_json(msg="Failed to find cluster '%s'" % cluster_name) + + self.cluster_objs = [cluster_obj] + + def get_all_cluster_objs(self, parent): + """ + Function to get all cluster managed objects from given parent object + Args: + parent: Managed objected of datacenter or host folder + + Returns: List of host managed objects + + """ + cluster_objs = [] + if isinstance(parent, vim.Datacenter): + folder = parent.hostFolder + else: + folder = parent + + for child in folder.childEntity: + if isinstance(child, vim.Folder): + cluster_objs = cluster_objs + self.get_all_cluster_objs(child) + if isinstance(child, vim.ClusterComputeResource): + cluster_objs.append(child) + return cluster_objs + + def gather_cluster_facts(self): + """ + Function to gather facts about cluster + + """ + results = dict(changed=False, clusters=dict()) + for cluster in self.cluster_objs: + # Default values + ha_failover_level = None + ha_restart_priority = None + ha_vm_tools_monitoring = None + ha_vm_min_up_time = None + ha_vm_max_failures = None + ha_vm_max_failure_window = None + ha_vm_failure_interval = None + enabled_vsan = False + vsan_auto_claim_storage = False + + # HA + das_config = cluster.configurationEx.dasConfig + if das_config.admissionControlPolicy: + ha_failover_level = das_config.admissionControlPolicy.failoverLevel + if das_config.defaultVmSettings: + ha_restart_priority = das_config.defaultVmSettings.restartPriority, + ha_vm_tools_monitoring = das_config.defaultVmSettings.vmToolsMonitoringSettings.vmMonitoring, + ha_vm_min_up_time = das_config.defaultVmSettings.vmToolsMonitoringSettings.minUpTime, + ha_vm_max_failures = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailures, + ha_vm_max_failure_window = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailureWindow, + ha_vm_failure_interval = das_config.defaultVmSettings.vmToolsMonitoringSettings.failureInterval, + + # DRS + drs_config = cluster.configurationEx.drsConfig + + # VSAN + if hasattr(cluster.configurationEx, 'vsanConfig'): + vsan_config = cluster.configurationEx.vsanConfig + enabled_vsan = vsan_config.enabled, + vsan_auto_claim_storage = vsan_config.defaultConfig.autoClaimStorage, + + results['clusters'][cluster.name] = dict( + enable_ha=das_config.enabled, + ha_failover_level=ha_failover_level, + ha_vm_monitoring=das_config.vmMonitoring, + ha_host_monitoring=das_config.hostMonitoring, + ha_admission_control_enabled=das_config.admissionControlEnabled, + ha_restart_priority=ha_restart_priority, + ha_vm_tools_monitoring=ha_vm_tools_monitoring, + ha_vm_min_up_time=ha_vm_min_up_time, + ha_vm_max_failures=ha_vm_max_failures, + ha_vm_max_failure_window=ha_vm_max_failure_window, + ha_vm_failure_interval=ha_vm_failure_interval, + enabled_drs=drs_config.enabled, + drs_enable_vm_behavior_overrides=drs_config.enableVmBehaviorOverrides, + drs_default_vm_behavior=drs_config.defaultVmBehavior, + drs_vmotion_rate=drs_config.vmotionRate, + enabled_vsan=enabled_vsan, + vsan_auto_claim_storage=vsan_auto_claim_storage, + ) + + self.module.exit_json(**results) + + +def main(): + argument_spec = vmware_argument_spec() + argument_spec.update( + datacenter=dict(type='str'), + cluster_name=dict(type='str') + ) + module = AnsibleModule( + argument_spec=argument_spec, + required_one_of=[ + ['cluster_name', 'datacenter'], + ], + ) + pyv = VmwreClusterFactsManager(module) + pyv.gather_cluster_facts() + + +if __name__ == '__main__': + main() diff --git a/test/integration/targets/vmware_cluster_facts/aliases b/test/integration/targets/vmware_cluster_facts/aliases new file mode 100644 index 00000000000000..6ee4e3d4f9fee3 --- /dev/null +++ b/test/integration/targets/vmware_cluster_facts/aliases @@ -0,0 +1,3 @@ +posix/ci/cloud/group4/vcenter +cloud/vcenter + diff --git a/test/integration/targets/vmware_cluster_facts/tasks/main.yml b/test/integration/targets/vmware_cluster_facts/tasks/main.yml new file mode 100644 index 00000000000000..a19791931786b4 --- /dev/null +++ b/test/integration/targets/vmware_cluster_facts/tasks/main.yml @@ -0,0 +1,91 @@ +# Test code for the vmware_cluster_facts module. +# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +- name: make sure pyvmomi is installed + pip: + name: pyvmomi + state: latest + when: "{{ ansible_user_id == 'root' }}" + +- name: store the vcenter container ip + set_fact: + vcsim: "{{ lookup('env', 'vcenter_host') }}" + +- debug: var=vcsim + +- name: Wait for Flask controller to come up online + wait_for: + host: "{{ vcsim }}" + port: 5000 + state: started + +- name: kill vcsim + uri: + url: http://{{ vcsim }}:5000/killall + +- name: start vcsim + uri: + url: http://{{ vcsim }}:5000/spawn?cluster=2 + register: vcsim_instance + +- debug: + var: vcsim_instance + +- name: Wait for vcsim server to come up online + wait_for: + host: "{{ vcsim }}" + port: 443 + state: started + +- name: get a list of Cluster from vcsim + uri: + url: http://{{ vcsim }}:5000/govc_find?filter=CCR + register: clusters + +- name: get a cluster + set_fact: + ccr1: "{{ clusters.json[0] | basename }}" + +- debug: var=ccr1 + +- name: get a list of datacenter + uri: + url: http://{{ vcsim }}:5000/govc_find?filter=DC + register: datacenters + +- name: get a datacenter + set_fact: + dc1: "{{ datacenters.json[0] | basename }}" + +- debug: var=dc1 + +- name: gather facts about all clusters in given datacenter + vmware_cluster_facts: + hostname: "{{ vcsim }}" + username: "{{ vcsim_instance.json.username }}" + password: "{{ vcsim_instance.json.password }}" + datacenter: "{{ dc1 }}" + validate_certs: False + register: all_cluster_result + +- name: ensure facts are gathered for all cluster + assert: + that: + - all_cluster_result.clusters + - not all_cluster_result.changed + +- name: gather facts about given cluster + vmware_cluster_facts: + hostname: "{{ vcsim }}" + username: "{{ vcsim_instance.json.username }}" + password: "{{ vcsim_instance.json.password }}" + cluster_name: "{{ ccr1 }}" + validate_certs: False + register: cluster_result + +- name: ensure facts are gathered for the given cluster + assert: + that: + - cluster_result.clusters + - not cluster_result.changed \ No newline at end of file
##### SUMMARY Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com> ##### ISSUE TYPE - New Module Pull Request ##### COMPONENT NAME lib/ansible/modules/cloud/vmware/vmware_cluster_facts.py test/integration/targets/vmware_cluster_facts/aliases test/integration/targets/vmware_cluster_facts/tasks/main.yml ##### ANSIBLE VERSION <!--- Paste verbatim output from "ansible --version" between quotes below --> ``` 2.6devel ```
https://api.github.com/repos/ansible/ansible/pulls/37105
2018-03-07T08:24:45Z
2018-04-19T09:41:04Z
2018-04-19T09:41:04Z
2019-04-27T00:20:52Z
2,973
ansible/ansible
48,713
Remove deprecated code
diff --git a/CHANGES.rst b/CHANGES.rst index cc96f441bf..825b2e2733 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,16 @@ Version 2.2.0 Unreleased +- Remove previously deprecated code. :pr:`4337` + + - Old names for some ``send_file`` parameters have been removed. + ``download_name`` replaces ``attachment_filename``, ``max_age`` + replaces ``cache_timeout``, and ``etag`` replaces ``add_etags``. + Additionally, ``path`` replaces ``filename`` in + ``send_from_directory``. + - The ``RequestContext.g`` property returning ``AppContext.g`` is + removed. + - Add new customization points to the ``Flask`` app object for many previously global behaviors. diff --git a/src/flask/ctx.py b/src/flask/ctx.py index caecbcc2b2..dc1f23b340 100644 --- a/src/flask/ctx.py +++ b/src/flask/ctx.py @@ -327,32 +327,6 @@ def __init__( # functions. self._after_request_functions: t.List[ft.AfterRequestCallable] = [] - @property - def g(self) -> _AppCtxGlobals: - import warnings - - warnings.warn( - "Accessing 'g' on the request context is deprecated and" - " will be removed in Flask 2.2. Access `g` directly or from" - "the application context instead.", - DeprecationWarning, - stacklevel=2, - ) - return _app_ctx_stack.top.g - - @g.setter - def g(self, value: _AppCtxGlobals) -> None: - import warnings - - warnings.warn( - "Setting 'g' on the request context is deprecated and" - " will be removed in Flask 2.2. Set it on the application" - " context instead.", - DeprecationWarning, - stacklevel=2, - ) - _app_ctx_stack.top.g = value - def copy(self) -> "RequestContext": """Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. diff --git a/src/flask/helpers.py b/src/flask/helpers.py index d1a84b9cf9..79c562c019 100644 --- a/src/flask/helpers.py +++ b/src/flask/helpers.py @@ -3,7 +3,6 @@ import socket import sys import typing as t -import warnings from datetime import datetime from functools import lru_cache from functools import update_wrapper @@ -390,53 +389,12 @@ def get_flashed_messages( return flashes -def _prepare_send_file_kwargs( - download_name: t.Optional[str] = None, - attachment_filename: t.Optional[str] = None, - etag: t.Optional[t.Union[bool, str]] = None, - add_etags: t.Optional[t.Union[bool]] = None, - max_age: t.Optional[ - t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] - ] = None, - cache_timeout: t.Optional[int] = None, - **kwargs: t.Any, -) -> t.Dict[str, t.Any]: - if attachment_filename is not None: - warnings.warn( - "The 'attachment_filename' parameter has been renamed to" - " 'download_name'. The old name will be removed in Flask" - " 2.2.", - DeprecationWarning, - stacklevel=3, - ) - download_name = attachment_filename - - if cache_timeout is not None: - warnings.warn( - "The 'cache_timeout' parameter has been renamed to" - " 'max_age'. The old name will be removed in Flask 2.2.", - DeprecationWarning, - stacklevel=3, - ) - max_age = cache_timeout - - if add_etags is not None: - warnings.warn( - "The 'add_etags' parameter has been renamed to 'etag'. The" - " old name will be removed in Flask 2.2.", - DeprecationWarning, - stacklevel=3, - ) - etag = add_etags - - if max_age is None: - max_age = current_app.get_send_file_max_age +def _prepare_send_file_kwargs(**kwargs: t.Any) -> t.Dict[str, t.Any]: + if kwargs.get("max_age") is None: + kwargs["max_age"] = current_app.get_send_file_max_age kwargs.update( environ=request.environ, - download_name=download_name, - etag=etag, - max_age=max_age, use_x_sendfile=current_app.use_x_sendfile, response_class=current_app.response_class, _root_path=current_app.root_path, # type: ignore @@ -449,16 +407,13 @@ def send_file( mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, - attachment_filename: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, - add_etags: t.Optional[bool] = None, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, - cache_timeout: t.Optional[int] = None, -): +) -> "Response": """Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths @@ -560,20 +515,17 @@ def send_file( .. versionadded:: 0.2 """ - return werkzeug.utils.send_file( + return werkzeug.utils.send_file( # type: ignore[return-value] **_prepare_send_file_kwargs( path_or_file=path_or_file, environ=request.environ, mimetype=mimetype, as_attachment=as_attachment, download_name=download_name, - attachment_filename=attachment_filename, conditional=conditional, etag=etag, - add_etags=add_etags, last_modified=last_modified, max_age=max_age, - cache_timeout=cache_timeout, ) ) @@ -581,7 +533,6 @@ def send_file( def send_from_directory( directory: t.Union[os.PathLike, str], path: t.Union[os.PathLike, str], - filename: t.Optional[str] = None, **kwargs: t.Any, ) -> "Response": """Send a file from within a directory using :func:`send_file`. @@ -617,16 +568,7 @@ def download_file(name): .. versionadded:: 0.5 """ - if filename is not None: - warnings.warn( - "The 'filename' parameter has been renamed to 'path'. The" - " old name will be removed in Flask 2.2.", - DeprecationWarning, - stacklevel=2, - ) - path = filename - - return werkzeug.utils.send_from_directory( # type: ignore + return werkzeug.utils.send_from_directory( # type: ignore[return-value] directory, path, **_prepare_send_file_kwargs(**kwargs) )
- Some argument to `send_file` and `send_from_directory` were renamed in Flask 2.0. The removal of the old names was deferred for an extra release. They have now been issuing a deprecation warning for over a year. `download_name` replaces `attachment_filename`, `max_age` replaces `cache_timeout`, `etag` replaces `add_etags`, and `path` replaces `filename`. - `RequestContext.g` was a property returning `AppContext.g`. Since `g` is not part of the request context, the property is removed.
https://api.github.com/repos/pallets/flask/pulls/4667
2022-07-01T21:04:41Z
2022-07-01T21:14:37Z
2022-07-01T21:14:37Z
2022-07-16T00:06:34Z
1,715
pallets/flask
20,743
[MRG] Fix small spelling mistake in comment
diff --git a/sklearn/utils/metaestimators.py b/sklearn/utils/metaestimators.py index ff16cd3671955..ae909140b10e0 100644 --- a/sklearn/utils/metaestimators.py +++ b/sklearn/utils/metaestimators.py @@ -45,7 +45,7 @@ def _set_params(self, attr, **params): for name in list(six.iterkeys(params)): if '__' not in name and name in names: self._replace_estimator(attr, name, params.pop(name)) - # 3. Step parameters and other initilisation arguments + # 3. Step parameters and other initialisation arguments super(_BaseComposition, self).set_params(**params) return self
#### Reference Issues/PRs fixes a typo introduced in #1769 #### What does this implement/fix? Explain your changes. just fixes a small spelling mistake in a comment
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/10348
2017-12-20T19:17:21Z
2017-12-20T22:16:56Z
2017-12-20T22:16:56Z
2017-12-20T22:16:56Z
167
scikit-learn/scikit-learn
45,887
Add note to feature_request.yml about not opening issues for new algorithms
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 09a159b2193e..20823bd58ab1 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -6,6 +6,7 @@ body: attributes: value: > Before requesting please search [existing issues](https://github.com/TheAlgorithms/Python/labels/enhancement). + Do not create issues to implement new algorithms as these will be closed. Usage questions such as "How do I...?" belong on the [Discord](https://discord.gg/c7MnfGFGa6) and will be closed. @@ -13,7 +14,6 @@ body: attributes: label: "Feature description" description: > - This could be new algorithms, data structures or improving any existing - implementations. + This could include new topics or improving any existing implementations. validations: required: true
### Describe your change: Modify feature_request.yml to indicate any issues about implementations of new algorithms will be closed. See #9343 * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
https://api.github.com/repos/TheAlgorithms/Python/pulls/10142
2023-10-08T20:13:53Z
2023-10-15T23:44:07Z
2023-10-15T23:44:07Z
2023-10-15T23:44:07Z
238
TheAlgorithms/Python
29,544
Update README.md
diff --git a/README.md b/README.md index baddd8b864..86c2a080ba 100644 --- a/README.md +++ b/README.md @@ -100,14 +100,14 @@ For a new language request, please refer to [Guideline for new language_requests - [Quick Start](./doc/doc_en/quickstart_en.md) - [PaddleOCR Overview and Installation](./doc/doc_en/paddleOCR_overview_en.md) - PP-OCR Industry Landing: from Training to Deployment - - [PP-OCR Model and Configuration](./doc/doc_en/models_and_config_en.md) + - [PP-OCR Model Zoo](./doc/doc_en/models_en.md) - [PP-OCR Model Download](./doc/doc_en/models_list_en.md) - - [Yml Configuration](./doc/doc_en/config_en.md) - [Python Inference for PP-OCR Model Library](./doc/doc_en/inference_ppocr_en.md) - [PP-OCR Training](./doc/doc_en/training_en.md) - [Text Detection](./doc/doc_en/detection_en.md) - [Text Recognition](./doc/doc_en/recognition_en.md) - [Direction Classification](./doc/doc_en/angle_class_en.md) + - [Yml Configuration](./doc/doc_en/config_en.md) - Inference and Deployment - [C++ Inference](./deploy/cpp_infer/readme_en.md) - [Serving](./deploy/pdserving/README.md) diff --git a/README_ch.md b/README_ch.md index 7e8a8e241b..5cd675ed09 100755 --- a/README_ch.md +++ b/README_ch.md @@ -92,14 +92,14 @@ PaddleOCR旨在打造一套丰富、领先、且实用的OCR工具库,助力 - [快速开始(中英文/多语言/文档分析)](./doc/doc_ch/quickstart.md) - [PaddleOCR全景图与项目克隆](./doc/doc_ch/paddleOCR_overview.md) - PP-OCR产业落地:从训练到部署 - - [PP-OCR模型与配置文件](./doc/doc_ch/models_and_config.md) + - [PP-OCR模型库](./doc/doc_ch/models.md) - [PP-OCR模型下载](./doc/doc_ch/models_list.md) - - [配置文件内容与生成](./doc/doc_ch/config.md) - - [PP-OCR模型库快速推理](./doc/doc_ch/inference_ppocr.md) + - [PP-OCR模型库Python推理](./doc/doc_ch/inference_ppocr.md) - [PP-OCR模型训练](./doc/doc_ch/training.md) - [文本检测](./doc/doc_ch/detection.md) - [文本识别](./doc/doc_ch/recognition.md) - [方向分类器](./doc/doc_ch/angle_class.md) + - [配置文件内容与生成](./doc/doc_ch/config.md) - PP-OCR模型推理部署 - [基于C++预测引擎推理](./deploy/cpp_infer/readme.md) - [服务化部署](./deploy/pdserving/README_CN.md) diff --git a/doc/doc_ch/inference_ppocr.md b/doc/doc_ch/inference_ppocr.md index 0a2ffbf6be..4c37a69557 100644 --- a/doc/doc_ch/inference_ppocr.md +++ b/doc/doc_ch/inference_ppocr.md @@ -1,4 +1,4 @@ -# PP-OCR模型库快速推理 +# PP-OCR模型库Python推理 本文介绍针对PP-OCR模型库的Python推理引擎使用方法,内容依次为文本检测、文本识别、方向分类器以及三者串联在CPU、GPU上的预测方法。
Update README.md
https://api.github.com/repos/PaddlePaddle/PaddleOCR/pulls/3960
2021-09-07T13:30:37Z
2021-09-07T13:30:47Z
2021-09-07T13:30:47Z
2021-09-07T13:30:47Z
879
PaddlePaddle/PaddleOCR
42,738
Add unit tests to test openai tools agent
diff --git a/libs/langchain/langchain/agents/openai_tools/base.py b/libs/langchain/langchain/agents/openai_tools/base.py index 56868d903adeb1..c1206ea4efc12b 100644 --- a/libs/langchain/langchain/agents/openai_tools/base.py +++ b/libs/langchain/langchain/agents/openai_tools/base.py @@ -19,7 +19,6 @@ def create_openai_tools_agent( Examples: - .. code-block:: python from langchain import hub @@ -56,7 +55,6 @@ def create_openai_tools_agent( A runnable sequence representing an agent. It takes as input all the same input variables as the prompt passed in does. It returns as output either an AgentAction or AgentFinish. - """ missing_vars = {"agent_scratchpad"}.difference(prompt.input_variables) if missing_vars: diff --git a/libs/langchain/tests/unit_tests/agents/test_agent.py b/libs/langchain/tests/unit_tests/agents/test_agent.py index 7baee92e072019..6ba908b6ad05ba 100644 --- a/libs/langchain/tests/unit_tests/agents/test_agent.py +++ b/libs/langchain/tests/unit_tests/agents/test_agent.py @@ -25,8 +25,10 @@ AgentExecutor, AgentType, create_openai_functions_agent, + create_openai_tools_agent, initialize_agent, ) +from langchain.agents.output_parsers.openai_tools import OpenAIToolAgentAction from langchain.callbacks.manager import CallbackManagerForLLMRun from langchain.prompts import ChatPromptTemplate from langchain.tools import tool @@ -626,6 +628,140 @@ def find_pet(pet: str) -> str: assert messages == ["looking", " ", "for", " ", "pet...", "Found", " ", "Pet"] +async def test_runnable_with_multi_action_per_step() -> None: + """Test an agent that can make multiple function calls at once.""" + # Will alternate between responding with hello and goodbye + infinite_cycle = cycle( + [AIMessage(content="looking for pet..."), AIMessage(content="Found Pet")] + ) + model = GenericFakeChatModel(messages=infinite_cycle) + + template = ChatPromptTemplate.from_messages( + [("system", "You are Cat Agent 007"), ("human", "{question}")] + ) + + parser_responses = cycle( + [ + [ + AgentAction( + tool="find_pet", + tool_input={ + "pet": "cat", + }, + log="find_pet()", + ), + AgentAction( + tool="pet_pet", # A function that allows you to pet the given pet. + tool_input={ + "pet": "cat", + }, + log="pet_pet()", + ), + ], + AgentFinish( + return_values={"foo": "meow"}, + log="hard-coded-message", + ), + ], + ) + + def fake_parse(inputs: dict) -> Union[AgentFinish, AgentAction]: + """A parser.""" + return cast(Union[AgentFinish, AgentAction], next(parser_responses)) + + @tool + def find_pet(pet: str) -> str: + """Find the given pet.""" + if pet != "cat": + raise ValueError("Only cats allowed") + return "Spying from under the bed." + + @tool + def pet_pet(pet: str) -> str: + """Pet the given pet.""" + if pet != "cat": + raise ValueError("Only cats should be petted.") + return "purrrr" + + agent = template | model | fake_parse + executor = AgentExecutor(agent=agent, tools=[find_pet]) + + # Invoke + result = executor.invoke({"question": "hello"}) + assert result == {"foo": "meow", "question": "hello"} + + # ainvoke + result = await executor.ainvoke({"question": "hello"}) + assert result == {"foo": "meow", "question": "hello"} + + # astream + results = [r async for r in executor.astream({"question": "hello"})] + assert results == [ + { + "actions": [ + AgentAction( + tool="find_pet", tool_input={"pet": "cat"}, log="find_pet()" + ) + ], + "messages": [AIMessage(content="find_pet()")], + }, + { + "actions": [ + AgentAction(tool="pet_pet", tool_input={"pet": "cat"}, log="pet_pet()") + ], + "messages": [AIMessage(content="pet_pet()")], + }, + { + # By-default observation gets converted into human message. + "messages": [HumanMessage(content="Spying from under the bed.")], + "steps": [ + AgentStep( + action=AgentAction( + tool="find_pet", tool_input={"pet": "cat"}, log="find_pet()" + ), + observation="Spying from under the bed.", + ) + ], + }, + { + "messages": [ + HumanMessage( + content="pet_pet is not a valid tool, try one of [find_pet]." + ) + ], + "steps": [ + AgentStep( + action=AgentAction( + tool="pet_pet", tool_input={"pet": "cat"}, log="pet_pet()" + ), + observation="pet_pet is not a valid tool, try one of [find_pet].", + ) + ], + }, + {"foo": "meow", "messages": [AIMessage(content="hard-coded-message")]}, + ] + + # astream log + + messages = [] + async for patch in executor.astream_log({"question": "hello"}): + for op in patch.ops: + if op["op"] != "add": + continue + + value = op["value"] + + if not isinstance(value, AIMessageChunk): + continue + + if value.content == "": # Then it's a function invocation message + continue + + messages.append(value.content) + + assert messages == ["looking", " ", "for", " ", "pet...", "Found", " ", "Pet"] + + def _make_func_invocation(name: str, **kwargs: Any) -> AIMessage: """Create an AIMessage that represents a function invocation. @@ -788,3 +924,310 @@ def find_pet(pet: str) -> str: " ", "bed.", ] + + +def _make_tools_invocation(name_to_arguments: Dict[str, Dict[str, Any]]) -> AIMessage: + """Create an AIMessage that represents a tools invocation. + + Args: + name_to_arguments: A dictionary mapping tool names to an invocation. + + Returns: + AIMessage that represents a request to invoke a tool. + """ + tool_calls = [ + {"function": {"name": name, "arguments": json.dumps(arguments)}, "id": idx} + for idx, (name, arguments) in enumerate(name_to_arguments.items()) + ] + + return AIMessage( + content="", + additional_kwargs={ + "tool_calls": tool_calls, + }, + ) + + +async def test_openai_agent_tools_agent() -> None: + """Test OpenAI tools agent.""" + infinite_cycle = cycle( + [ + _make_tools_invocation( + { + "find_pet": {"pet": "cat"}, + "check_time": {}, + } + ), + AIMessage(content="The cat is spying from under the bed."), + ] + ) + + model = GenericFakeChatModel(messages=infinite_cycle) + + @tool + def find_pet(pet: str) -> str: + """Find the given pet.""" + if pet != "cat": + raise ValueError("Only cats allowed") + return "Spying from under the bed." + + @tool + def check_time() -> str: + """Find the given pet.""" + return "It's time to pet the cat." + + template = ChatPromptTemplate.from_messages( + [ + ("system", "You are a helpful AI bot. Your name is kitty power meow."), + ("human", "{question}"), + MessagesPlaceholder( + variable_name="agent_scratchpad", + ), + ] + ) + + # type error due to base tool type below -- would need to be adjusted on tool + # decorator. + agent = create_openai_tools_agent( + model, + [find_pet], # type: ignore[list-item] + template, + ) + executor = AgentExecutor(agent=agent, tools=[find_pet]) + + # Invoke + result = executor.invoke({"question": "hello"}) + assert result == { + "output": "The cat is spying from under the bed.", + "question": "hello", + } + + # astream + chunks = [chunk async for chunk in executor.astream({"question": "hello"})] + assert chunks == [ + { + "actions": [ + OpenAIToolAgentAction( + tool="find_pet", + tool_input={"pet": "cat"}, + log="\nInvoking: `find_pet` with `{'pet': 'cat'}`\n\n\n", + message_log=[ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": { + "name": "check_time", + "arguments": "{}", + }, + "id": 1, + }, + ] + }, + ) + ], + tool_call_id="0", + ) + ], + "messages": [ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": {"name": "check_time", "arguments": "{}"}, + "id": 1, + }, + ] + }, + ) + ], + }, + { + "actions": [ + OpenAIToolAgentAction( + tool="check_time", + tool_input={}, + log="\nInvoking: `check_time` with `{}`\n\n\n", + message_log=[ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": { + "name": "check_time", + "arguments": "{}", + }, + "id": 1, + }, + ] + }, + ) + ], + tool_call_id="1", + ) + ], + "messages": [ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": {"name": "check_time", "arguments": "{}"}, + "id": 1, + }, + ] + }, + ) + ], + }, + { + "messages": [ + FunctionMessage(content="Spying from under the bed.", name="find_pet") + ], + "steps": [ + AgentStep( + action=OpenAIToolAgentAction( + tool="find_pet", + tool_input={"pet": "cat"}, + log="\nInvoking: `find_pet` with `{'pet': 'cat'}`\n\n\n", + message_log=[ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": { + "name": "check_time", + "arguments": "{}", + }, + "id": 1, + }, + ] + }, + ) + ], + tool_call_id="0", + ), + observation="Spying from under the bed.", + ) + ], + }, + { + "messages": [ + FunctionMessage( + content="check_time is not a valid tool, try one of [find_pet].", + name="check_time", + ) + ], + "steps": [ + AgentStep( + action=OpenAIToolAgentAction( + tool="check_time", + tool_input={}, + log="\nInvoking: `check_time` with `{}`\n\n\n", + message_log=[ + AIMessageChunk( + content="", + additional_kwargs={ + "tool_calls": [ + { + "function": { + "name": "find_pet", + "arguments": '{"pet": "cat"}', + }, + "id": 0, + }, + { + "function": { + "name": "check_time", + "arguments": "{}", + }, + "id": 1, + }, + ] + }, + ) + ], + tool_call_id="1", + ), + observation="check_time is not a valid tool, " + "try one of [find_pet].", + ) + ], + }, + { + "messages": [AIMessage(content="The cat is spying from under the bed.")], + "output": "The cat is spying from under the bed.", + }, + ] + + # astream_log + log_patches = [ + log_patch async for log_patch in executor.astream_log({"question": "hello"}) + ] + + # Get the tokens from the astream log response. + messages = [] + + for log_patch in log_patches: + for op in log_patch.ops: + if op["op"] == "add" and isinstance(op["value"], AIMessageChunk): + value = op["value"] + if value.content: # Filter out function call messages + messages.append(value.content) + + assert messages == [ + "The", + " ", + "cat", + " ", + "is", + " ", + "spying", + " ", + "from", + " ", + "under", + " ", + "the", + " ", + "bed.", + ]
This PR adds unit testing to test openai tools agent.
https://api.github.com/repos/langchain-ai/langchain/pulls/15843
2024-01-10T20:27:47Z
2024-01-10T22:06:31Z
2024-01-10T22:06:30Z
2024-01-10T22:06:31Z
3,466
langchain-ai/langchain
43,735
Add alipay
diff --git a/README.md b/README.md index be530c0ed..3f7260772 100644 --- a/README.md +++ b/README.md @@ -469,6 +469,7 @@ A curated list of awesome Python frameworks, libraries and software. Inspired by * [merchant](https://github.com/agiliq/merchant) - A Django app to accept payments from various payment processors. * [money](https://github.com/carlospalol/money) - Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution. * [python-currencies](https://github.com/Alir3z4/python-currencies) - Display money format and its filthy currencies. +* [alipay](https://github.com/lxneng/alipay) - Unofficial Alipay API for Python. ## RESTful API
An Unofficial Alipay API for Python
https://api.github.com/repos/vinta/awesome-python/pulls/357
2015-04-16T07:16:12Z
2015-04-16T14:43:12Z
2015-04-16T14:43:12Z
2015-04-16T14:43:12Z
187
vinta/awesome-python
27,237
[zero] refactor model data tracing
diff --git a/colossalai/utils/memory_tracer/model_data_memtracer.py b/colossalai/utils/memory_tracer/model_data_memtracer.py index e8cb9f7c6748..fafe3169049c 100644 --- a/colossalai/utils/memory_tracer/model_data_memtracer.py +++ b/colossalai/utils/memory_tracer/model_data_memtracer.py @@ -22,6 +22,7 @@ class ModelDataTracer(metaclass=SingletonMeta): def __init__(self) -> None: self._cuda_usage = 0 + self._cpu_usage = 0 self._start_flag = False def start(self) -> None: @@ -30,22 +31,33 @@ def start(self) -> None: def close(self) -> None: self._start_flag = False - def add_tensor(self, t: torch.Tensor) -> None: + def add_tensor(self, t: Union[torch.Tensor, ShardedTensor]) -> None: if not self._start_flag: return - assert isinstance(t, torch.Tensor), f"ModelDataTracer add_tensor() should accept a torch.Tensor" - mem_use = _col_tensor_mem_usage(t) - self._cuda_usage += mem_use + t_payload = t.payload if isinstance(t, ShardedTensor) else t + mem_use = _col_tensor_mem_usage(t_payload) + if t_payload.device.type == 'cuda': + self._cuda_usage += mem_use + elif t_payload.device.type == 'cpu': + self._cpu_usage += mem_use + else: + raise TypeError - def delete_tensor(self, t: torch.Tensor) -> None: + def delete_tensor(self, t: Union[torch.Tensor, ShardedTensor]) -> None: if not self._start_flag: return - assert isinstance(t, torch.Tensor), f"ModelDataTracer delete_tensor() should accept a torch.Tensor" - mem_use = _col_tensor_mem_usage(t) - self._cuda_usage -= mem_use + t_payload = t.payload if isinstance(t, ShardedTensor) else t + mem_use = _col_tensor_mem_usage(t_payload) + if t_payload.device.type == 'cuda': + self._cuda_usage -= mem_use + elif t_payload.device.type == 'cpu': + self._cpu_usage -= mem_use + else: + raise TypeError def clear(self) -> None: self._cuda_usage = 0 + self._cpu_usage = 0 @property def cpu_usage(self): diff --git a/colossalai/utils/memory_utils/utils.py b/colossalai/utils/memory_utils/utils.py index 52bb487d0508..df41ac95d1a9 100644 --- a/colossalai/utils/memory_utils/utils.py +++ b/colossalai/utils/memory_utils/utils.py @@ -3,7 +3,7 @@ from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER -from typing import Union, Optional +from typing import Union _GLOBAL_CUDA_MEM_FRACTION = 1.0 @@ -52,11 +52,9 @@ def colo_model_data_tensor_move(src_t: Union[ShardedTensor, torch.Tensor], tgt_t tgt_t_payload = tgt_t.data tgt_dev = tgt_t_payload.device - if src_dev.type == 'cuda' and tgt_dev.type == 'cpu': - GLOBAL_MODEL_DATA_TRACER.delete_tensor(src_t_payload) - elif src_dev.type == 'cpu' and tgt_dev.type == 'cuda': - GLOBAL_MODEL_DATA_TRACER.add_tensor(tgt_t_payload) + GLOBAL_MODEL_DATA_TRACER.delete_tensor(src_t_payload) tgt_t_payload.copy_(src_t_payload) + GLOBAL_MODEL_DATA_TRACER.add_tensor(tgt_t_payload) # remove payload of src_t if isinstance(src_t, ShardedTensor): @@ -65,7 +63,9 @@ def colo_model_data_tensor_move(src_t: Union[ShardedTensor, torch.Tensor], tgt_t src_t.data = torch.tensor([], device=src_dev, dtype=src_t_payload.dtype) -def colo_model_data_tensor_move_inline(t: Union[ShardedTensor, torch.Tensor], target_device: torch.device) -> None: +def colo_model_data_tensor_move_inline(t: Union[ShardedTensor, torch.Tensor], + target_device: torch.device, + use_tracer: bool = True) -> None: """ move a tensor to the target_device Args: @@ -84,13 +84,11 @@ def colo_model_data_tensor_move_inline(t: Union[ShardedTensor, torch.Tensor], ta # deal with torch.device('cpu') and torch.device('cpu:0) if t_payload.device.type == target_device.type: return - - if target_device.type == 'cuda': - GLOBAL_MODEL_DATA_TRACER.add_tensor(t_payload) - elif target_device.type == 'cpu': + if use_tracer: GLOBAL_MODEL_DATA_TRACER.delete_tensor(t_payload) - t_payload.data = t_payload.data.to(target_device) + if use_tracer: + GLOBAL_MODEL_DATA_TRACER.add_tensor(t_payload) def colo_model_data_move_to_cpu(t: Union[ShardedTensor, torch.Tensor]) -> None: @@ -115,3 +113,4 @@ def colo_model_data_move_to_cpu(t: Union[ShardedTensor, torch.Tensor]) -> None: # TODO() optimize the tensor moving with non-blocking GLOBAL_MODEL_DATA_TRACER.delete_tensor(t_payload) t_payload.data = t_payload.data.cpu() + GLOBAL_MODEL_DATA_TRACER.add_tensor(t_payload) diff --git a/colossalai/zero/init_ctx/init_context.py b/colossalai/zero/init_ctx/init_context.py index 9ff4a81c5f57..32352e469da0 100644 --- a/colossalai/zero/init_ctx/init_context.py +++ b/colossalai/zero/init_ctx/init_context.py @@ -177,13 +177,11 @@ def _post_init_method(self, module: torch.nn.Module): self.initialized_param_list.append(param) + GLOBAL_MODEL_DATA_TRACER.add_tensor(param.col_attr.sharded_data_tensor) + if self.shard_param: self.shard_strategy.shard([param.col_attr.sharded_data_tensor], self.dp_process_group) - if param.col_attr.sharded_data_tensor.device.type == 'cuda': - GLOBAL_MODEL_DATA_TRACER.add_tensor(param.col_attr.sharded_data_tensor.payload) - # if param.col_attr.grad and self.shard_grad: - # self.shard_strategy.shard([param.col_attr._grad_sharded_tensor], self.dp_process_group) - # GLOBAL_MODEL_DATA_TRACER.add_tensor(param.col_attr._grad_sharded_tensor.payload) + # We must cast buffers # If we use BN, buffers may be on CPU and Float # We must cast them diff --git a/colossalai/zero/shard_utils/bucket_tensor_shard_strategy.py b/colossalai/zero/shard_utils/bucket_tensor_shard_strategy.py index 90b447de14fc..06683af6aea7 100644 --- a/colossalai/zero/shard_utils/bucket_tensor_shard_strategy.py +++ b/colossalai/zero/shard_utils/bucket_tensor_shard_strategy.py @@ -7,6 +7,7 @@ from torch._utils import _flatten_dense_tensors as flatten from .tensor_shard_strategy import TensorShardStrategy +from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER class BucketTensorShardStrategy(TensorShardStrategy): @@ -17,6 +18,9 @@ class BucketTensorShardStrategy(TensorShardStrategy): """ def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): + for t in tensor_list: + GLOBAL_MODEL_DATA_TRACER.delete_tensor(t) + tensor_list: List[ShardedTensor] = [t for t in tensor_list if t.is_sharded] if len(tensor_list) == 0: return @@ -46,3 +50,6 @@ def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist. t.reset_payload(gathered_payload) t.is_sharded = False offset += tensor_numels[i] + + for t in tensor_list: + GLOBAL_MODEL_DATA_TRACER.add_tensor(t) diff --git a/colossalai/zero/shard_utils/tensor_shard_strategy.py b/colossalai/zero/shard_utils/tensor_shard_strategy.py index 31210a1900f9..25914f6f3527 100644 --- a/colossalai/zero/shard_utils/tensor_shard_strategy.py +++ b/colossalai/zero/shard_utils/tensor_shard_strategy.py @@ -3,13 +3,16 @@ import torch import torch.distributed as dist from colossalai.utils import get_current_device +from colossalai.utils.memory_utils.utils import colo_model_data_tensor_move, colo_model_data_tensor_move_inline from colossalai.zero.shard_utils import BaseShardStrategy from colossalai.zero.shard_utils.commons import get_shard from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor +from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER class TensorShardStrategy(BaseShardStrategy): - """A naive implementation which shard each tensor evenly over all ranks + """ + A naive implementation which shard each tensor evenly over all ranks """ def shard(self, tensor_list: List[ShardedTensor], process_group: Optional[dist.ProcessGroup] = None): @@ -21,13 +24,22 @@ def gather(self, tensor_list: List[ShardedTensor], process_group: Optional[dist. self._gather_tensor(t, process_group) def _shard_tensor(self, t: ShardedTensor, process_group: Optional[dist.ProcessGroup] = None): + """ Shard tensor among processes. + + Args: + t (ShardedTensor): a tensor to be sharded. + process_group (Optional[dist.ProcessGroup], optional): the process group among which tensor shards. + Defaults to None. + """ if t.is_sharded: return if t.payload.device.type == 'cuda': assert t.payload.device.index == get_current_device(), f"shard tensor on cuda device index {t.payload.device.index},"\ f" but current cuda device is {get_current_device()}" + GLOBAL_MODEL_DATA_TRACER.delete_tensor(t.payload) sharded_payload, _ = get_shard(t.payload, dist.get_rank(process_group), dist.get_world_size(process_group)) t.reset_payload(sharded_payload) + GLOBAL_MODEL_DATA_TRACER.add_tensor(t.payload) t.is_sharded = True def _gather_tensor(self, t: ShardedTensor, process_group: Optional[dist.ProcessGroup] = None): @@ -44,8 +56,10 @@ def _gather_tensor(self, t: ShardedTensor, process_group: Optional[dist.ProcessG else: buffer_list.append(torch.zeros(payload_numel, dtype=t.dtype, device=get_current_device())) + GLOBAL_MODEL_DATA_TRACER.delete_tensor(t.payload) dist.all_gather(buffer_list, buffer_list[rank], group=process_group, async_op=False) gathered_payload = torch.narrow(torch.cat(buffer_list), 0, 0, t.origin_numel).reshape(t.origin_shape) t.reset_payload(gathered_payload) - t.to(target_device) + colo_model_data_tensor_move_inline(t, target_device, use_tracer=False) + GLOBAL_MODEL_DATA_TRACER.delete_tensor(t.payload) t.is_sharded = False diff --git a/colossalai/zero/sharded_param/sharded_tensor.py b/colossalai/zero/sharded_param/sharded_tensor.py index cde257d77597..c678f22da07b 100644 --- a/colossalai/zero/sharded_param/sharded_tensor.py +++ b/colossalai/zero/sharded_param/sharded_tensor.py @@ -56,7 +56,10 @@ def dtype(self): return self._origin_dtype def to(self, device: torch.device): - self._payload = self._payload.to(device) + raise RuntimeError("Use colo_model_tensor_move install of call .to() on ShardedTensor") + + def to_(self, device: torch.device): + raise RuntimeError("Use colo_model_tensor_move install of call .to_() on ShardedTensor") @property def shape(self): diff --git a/tests/test_utils/test_tensor_move.py b/tests/test_utils/test_tensor_move.py new file mode 100644 index 000000000000..223db83adc81 --- /dev/null +++ b/tests/test_utils/test_tensor_move.py @@ -0,0 +1,66 @@ +import pytest + +from colossalai.utils.cuda import get_current_device +from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER +from colossalai.utils.memory_utils.utils import colo_model_data_tensor_move, colo_model_data_tensor_move_inline +from colossalai.zero.sharded_param import ShardedTensor + +import colossalai + +import torch + +from functools import partial +import torch.multiprocessing as mp +from colossalai.utils import free_port + + +def _run_colo_model_data_tensor_move_inline(): + assert (GLOBAL_MODEL_DATA_TRACER.cuda_usage == 0) + GLOBAL_MODEL_DATA_TRACER.start() + + for t in [torch.randn(2, 3), ShardedTensor(torch.randn(2, 3))]: + GLOBAL_MODEL_DATA_TRACER.add_tensor(t) + assert GLOBAL_MODEL_DATA_TRACER.cpu_usage == 2 * 3 * 4 + assert GLOBAL_MODEL_DATA_TRACER.cuda_usage == 0 + colo_model_data_tensor_move_inline(t, torch.device(f"cuda:{get_current_device()}")) + assert t.device == torch.device(f"cuda:{get_current_device()}") + assert GLOBAL_MODEL_DATA_TRACER.cpu_usage == 0 + assert GLOBAL_MODEL_DATA_TRACER.cuda_usage == 2 * 3 * 4 + GLOBAL_MODEL_DATA_TRACER.clear() + + GLOBAL_MODEL_DATA_TRACER.close() + + +def _run_colo_model_data_tensor_move(): + assert (GLOBAL_MODEL_DATA_TRACER.cuda_usage == 0) + GLOBAL_MODEL_DATA_TRACER.start() + + for t in [(torch.ones(2, 3), torch.zeros(2, 3).cuda(get_current_device())), + (ShardedTensor(torch.ones(2, 3)), ShardedTensor(torch.zeros(2, 3).cuda(get_current_device())))]: + cpu_t, cuda_t = t + GLOBAL_MODEL_DATA_TRACER.add_tensor(cpu_t) + assert GLOBAL_MODEL_DATA_TRACER.cpu_usage == 2 * 3 * 4 + assert GLOBAL_MODEL_DATA_TRACER.cuda_usage == 0 + colo_model_data_tensor_move(cpu_t, cuda_t) + assert GLOBAL_MODEL_DATA_TRACER.cpu_usage == 0 + assert GLOBAL_MODEL_DATA_TRACER.cuda_usage == 2 * 3 * 4 + GLOBAL_MODEL_DATA_TRACER.clear() + + GLOBAL_MODEL_DATA_TRACER.close() + + +def run_dist(rank, world_size, port): + colossalai.launch(config={}, rank=rank, world_size=world_size, host='localhost', port=port, backend='nccl') + _run_colo_model_data_tensor_move_inline() + _run_colo_model_data_tensor_move() + + +@pytest.mark.dist +@pytest.mark.parametrize("world_size", [1, 4]) +def test_tensor_move(world_size): + run_func = partial(run_dist, world_size=world_size, port=free_port()) + mp.spawn(run_func, nprocs=world_size) + + +if __name__ == '__main__': + test_tensor_move(4) diff --git a/tests/test_zero_data_parallel/test_init_context.py b/tests/test_zero_data_parallel/test_init_context.py index 84a8b63ff876..2bb0f973a5e9 100644 --- a/tests/test_zero_data_parallel/test_init_context.py +++ b/tests/test_zero_data_parallel/test_init_context.py @@ -47,6 +47,8 @@ def run_model_test(init_device_type, shard_strategy_class): f'{param.col_attr.sharded_data_tensor.payload.device.type} vs. {init_device.type}' if init_device.type == 'cuda': assert (GLOBAL_MODEL_DATA_TRACER.cuda_usage > 0) + else: + assert (GLOBAL_MODEL_DATA_TRACER.cpu_usage > 0) GLOBAL_MODEL_DATA_TRACER.clear() @@ -63,5 +65,4 @@ def test_zero_init_context(world_size): if __name__ == '__main__': - # test_zero_init_context(2, torch.device('cpu'), TensorShardStrategy) test_zero_init_context(4)
Tracing cpu model data changes.
https://api.github.com/repos/hpcaitech/ColossalAI/pulls/522
2022-03-25T06:43:26Z
2022-03-25T10:03:33Z
2022-03-25T10:03:32Z
2022-03-25T10:03:36Z
3,817
hpcaitech/ColossalAI
11,292
Added --timeout command line option
diff --git a/AUTHORS.md b/AUTHORS.md index cb60bfd8701..d82ddcb7688 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -138,6 +138,7 @@ Authors * [Joubin Jabbari](https://github.com/joubin) * [Juho Juopperi](https://github.com/jkjuopperi) * [Kane York](https://github.com/riking) +* [Katsuyoshi Ozaki](https://github.com/moratori) * [Kenichi Maehashi](https://github.com/kmaehashi) * [Kenneth Skovhede](https://github.com/kenkendk) * [Kevin Burke](https://github.com/kevinburke) diff --git a/certbot/CHANGELOG.md b/certbot/CHANGELOG.md index 0a5849d82b2..3f665881059 100644 --- a/certbot/CHANGELOG.md +++ b/certbot/CHANGELOG.md @@ -10,6 +10,8 @@ Certbot adheres to [Semantic Versioning](https://semver.org/). * The function certbot.util.parse_loose_version was added to parse version strings in the same way as the now deprecated distutils.version.LooseVersion class from the Python standard library. +* Added `--issuance-timeout`. This option specifies how long (in seconds) Certbot will wait + for the server to issue a certificate. ### Changed diff --git a/certbot/certbot/_internal/cli/__init__.py b/certbot/certbot/_internal/cli/__init__.py index 63b0dd097e7..a69f9666680 100644 --- a/certbot/certbot/_internal/cli/__init__.py +++ b/certbot/certbot/_internal/cli/__init__.py @@ -364,6 +364,11 @@ def prepare_and_parse_args(plugins: plugins_disco.PluginsRegistry, args: List[st 'ACME Challenges are versioned, but if you pick "http" rather ' 'than "http-01", Certbot will select the latest version ' 'automatically.') + helpful.add( + [None, "certonly", "run"], "--issuance-timeout", type=nonnegative_int, + dest="issuance_timeout", + default=flag_default("issuance_timeout"), + help=config_help("issuance_timeout")) helpful.add( "renew", "--pre-hook", help="Command to be run in a shell before obtaining any certificates." diff --git a/certbot/certbot/_internal/client.py b/certbot/certbot/_internal/client.py index 4c472df5520..fad48b3d33a 100644 --- a/certbot/certbot/_internal/client.py +++ b/certbot/certbot/_internal/client.py @@ -330,9 +330,14 @@ def obtain_certificate_from_csr(self, csr: util.CSR, if orderr is None: orderr = self._get_order_and_authorizations(csr.data, best_effort=False) - deadline = datetime.datetime.now() + datetime.timedelta(seconds=90) + deadline = datetime.datetime.now() + datetime.timedelta( + seconds=self.config.issuance_timeout) + + logger.debug("Will poll for certificate issuance until %s", deadline) + orderr = self.acme.finalize_order( orderr, deadline, fetch_alternative_chains=self.config.preferred_chain is not None) + fullchain = orderr.fullchain_pem if self.config.preferred_chain and orderr.alternative_fullchains_pem: fullchain = crypto_util.find_chain_with_issuer( diff --git a/certbot/certbot/_internal/constants.py b/certbot/certbot/_internal/constants.py index c2b4e6556ac..18160d47ed8 100644 --- a/certbot/certbot/_internal/constants.py +++ b/certbot/certbot/_internal/constants.py @@ -78,6 +78,7 @@ random_sleep_on_renew=True, eab_hmac_key=None, eab_kid=None, + issuance_timeout=90, # Subparsers num=None, diff --git a/certbot/certbot/configuration.py b/certbot/certbot/configuration.py index 4648cbda17d..1a72cbce720 100644 --- a/certbot/certbot/configuration.py +++ b/certbot/certbot/configuration.py @@ -293,6 +293,13 @@ def renewal_post_hooks_dir(self) -> str: return os.path.join(self.renewal_hooks_dir, constants.RENEWAL_POST_HOOKS_DIR) + @property + def issuance_timeout(self) -> int: + """This option specifies how long (in seconds) Certbot will wait + for the server to issue a certificate. + """ + return self.namespace.issuance_timeout + # Magic methods def __deepcopy__(self, _memo: Any) -> 'NamespaceConfig': diff --git a/certbot/tests/client_test.py b/certbot/tests/client_test.py index 330fd2852f1..8d8073f6f09 100644 --- a/certbot/tests/client_test.py +++ b/certbot/tests/client_test.py @@ -1,4 +1,5 @@ """Tests for certbot._internal.client.""" +import datetime import contextlib import platform import shutil @@ -12,6 +13,7 @@ from certbot import util from certbot._internal.display import obj as display_obj from certbot._internal import account +from certbot._internal import constants from certbot.compat import os import certbot.tests.util as test_util @@ -320,6 +322,24 @@ def test_obtain_certificate_from_csr(self, mock_logger, mock_crypto_util): "some issuer", True) self.config.preferred_chain = None + # Test for default issuance_timeout + expected_deadline = \ + datetime.datetime.now() + datetime.timedelta( + seconds=constants.CLI_DEFAULTS["issuance_timeout"]) + self.client.obtain_certificate_from_csr(test_csr, orderr=orderr) + ((_, deadline), _) = self.client.acme.finalize_order.call_args + self.assertTrue( + abs(expected_deadline - deadline) <= datetime.timedelta(seconds=1)) + + # Test for specific issuance_timeout (300 seconds) + expected_deadline = \ + datetime.datetime.now() + datetime.timedelta(seconds=300) + self.config.issuance_timeout = 300 + self.client.obtain_certificate_from_csr(test_csr, orderr=orderr) + ((_, deadline), _) = self.client.acme.finalize_order.call_args + self.assertTrue( + abs(expected_deadline - deadline) <= datetime.timedelta(seconds=1)) + # Test for orderr=None self.assertEqual( (mock.sentinel.cert, mock.sentinel.chain),
Fixes #6513 Added --timeout command line option. This option specifies the timeout value in seconds for obtaining a certificate from Certificate Authority. Default timeout value currently hard-coded as 90sec moved to constants. ## Pull Request Checklist - [x] If the change being made is to a [distributed component](https://certbot.eff.org/docs/contributing.html#code-components-and-layout), edit the `master` section of `certbot/CHANGELOG.md` to include a description of the change being made. - [x] Add or update any documentation as needed to support the changes in this PR. - [x] Include your name in `AUTHORS.md` if you like.
https://api.github.com/repos/certbot/certbot/pulls/9056
2021-10-05T11:30:23Z
2021-11-29T21:17:07Z
2021-11-29T21:17:06Z
2021-11-29T21:17:07Z
1,574
certbot/certbot
3,007
manual update improve
diff --git a/code/default/launcher/lang/zh_CN/LC_MESSAGES/messages.po b/code/default/launcher/lang/zh_CN/LC_MESSAGES/messages.po index 135bd53cd0..885b5a33aa 100644 --- a/code/default/launcher/lang/zh_CN/LC_MESSAGES/messages.po +++ b/code/default/launcher/lang/zh_CN/LC_MESSAGES/messages.po @@ -177,10 +177,19 @@ msgid "no hash check" msgstr "不校验" msgid "Set as local version" -msgstr "设置本地版本" +msgstr "设置为本地版本" -msgid "Input version" -msgstr "输入版本" +msgid "Delete local version" +msgstr "删除本地版本" + +msgid "Target version" +msgstr "目标版本" + +msgid "Local" +msgstr "本地" + +msgid "Released" +msgstr "已发布" msgid "(Remote Web Control Enabled)" msgstr "(已允许远程连接)" @@ -224,6 +233,9 @@ msgstr "下载中……" msgid "Download completed" msgstr "下载完成" +msgid "Deleted successfully" +msgstr "删除成功" + msgid "System" msgstr "系统" diff --git a/code/default/launcher/update_from_github.py b/code/default/launcher/update_from_github.py index 76058d5e92..8f78e98e68 100644 --- a/code/default/launcher/update_from_github.py +++ b/code/default/launcher/update_from_github.py @@ -302,6 +302,23 @@ def download_overwrite_new_version(xxnet_version,checkhash=1): os.remove(xxnet_zip_file) shutil.rmtree(xxnet_unzip_path, ignore_errors=True) +def get_local_versions(): + code_path = os.path.join(root_path, os.pardir) + files_in_code_path = os.listdir(code_path) + local_versions = [] + for name in files_in_code_path: + start_script = os.path.join(code_path, name, "launcher", "start.py") + if os.path.isfile(start_script): + local_versions.append(name) + return local_versions + +def del_version(version): + try: + shutil.rmtree( os.path.join(top_path, "code", version) ) + return True + except Exception as e: + xlog.warn("deleting fail: %s", e) + return False def update_current_version(version): start_script = os.path.join(top_path, "code", version, "launcher", "start.py") diff --git a/code/default/launcher/web_control.py b/code/default/launcher/web_control.py index da8381fef3..e95a9b7fd4 100644 --- a/code/default/launcher/web_control.py +++ b/code/default/launcher/web_control.py @@ -491,7 +491,22 @@ def req_update_handler(self): data = '{"res":"success"}' else: data = '{"res":"false", "reason": "version not exist"}' - + elif reqs['cmd'] == ['get_localversions']: + local_versions = update_from_github.get_local_versions() + + s = "" + for v in local_versions: + if not s == "": + s += "," + s += ' { "v":"%s" } ' % (v) + data = '[ %s ]' %(s) + elif reqs['cmd'] == ['del_localversion']: + if update_from_github.del_version( reqs['version'][0] ): + data = '{"res":"success"}' + else: + data = '{"res":"fail"}' + + self.send_response('text/html', data) def req_config_proxy_handler(self): diff --git a/code/default/launcher/web_ui/config_update.html b/code/default/launcher/web_ui/config_update.html index 13ea3c0f6a..27d1f1deda 100644 --- a/code/default/launcher/web_ui/config_update.html +++ b/code/default/launcher/web_ui/config_update.html @@ -62,24 +62,34 @@ </div> <br/> <div class="row-fluid"> - <div class="span2"> - <label>{{ _( "Input version" ) }} :</label> - </div> - <div class="span2"> - <input id="manual-version" style="width: 8em"/> - </div> + <table> + <tr> + <td > + <label>{{ _( "Target version" ) }} :</label> + </td> + <td> + <input id="manual-version" style="width: 8em"/> + </td> + <td> + <select id="local-versions-selector"> <option>{{ _( "Local" ) }}</option> </select> + </td> + <td> + <select id="released-versions-selector"><option>{{ _( "Released" ) }}</option> </select> + </td> + </tr> + </table> </div> <br/> <div class="row-fluid"> - <div class="span2"> - <button class="btn btn-primary ladda-button" data-style="slide-up" id="manual-upgrade-to">{{ _( "Upgrade to" ) }} ({{ _( "no hash check" ) }})</button> - </div> - </div> - <br/> - <div class="row-fluid"> - <div class="span2"> - <button class="btn btn-primary ladda-button" data-style="slide-up" id="set-as-local-version">{{ _( "Set as local version" ) }}</button> - </div> + <table> + <tr> + <button class="btn btn-primary ladda-button" data-style="slide-up" id="manual-upgrade-to">{{ _( "Upgrade to" ) }} ({{ _( "no hash check" ) }})</button> + + <button class="btn btn-primary ladda-button" data-style="slide-up" id="set-as-local-version">{{ _( "Set as local version" ) }}</button> + + <button class="btn btn-warning ladda-button" data-style="slide-up" id="delete-local-version">{{ _( "Delete local version" ) }}</button> + </tr> + </table> </div> </div> @@ -265,7 +275,8 @@ $('#set-as-local-version').click(function(){ var v = $('#manual-version').val(); - + + var pageRequests={}; pageRequests['cmd'] = 'set_localversion'; pageRequests['version'] = v; $.ajax({ @@ -285,5 +296,100 @@ } }); }); + + $('#delete-local-version').click(function(){ -</script> \ No newline at end of file + var v = $('#manual-version').val(); + + var pageRequests={}; + pageRequests['cmd'] = 'del_localversion'; + pageRequests['version'] = v; + $.ajax({ + type: 'GET', + url: '/update', + data: pageRequests, + dataType: 'JSON', + success: function(result) { + if ( result['res'] == 'success' ) { + tip('{{ _( "Deleted successfully" ) }}', 'success'); + }else{ + tip('{{ _( "Deleting local version fail" ) }}', 'warning'); + } + }, + error: function() { + displayErrorMessage(); + } + }); + }); + + function show_localversions() + { + var pageRequests = {}; + pageRequests['cmd'] = 'get_localversions'; + $.ajax({ + type: 'GET', + url: '/update', + data: pageRequests, + dataType: 'json', + success: function(result) { + + $("#local-versions-selector").html(""); + + var lv = result; + for(var i = 0 ; i < lv.length; ++i) + { + var v = lv[i]['v']; + var new_option = document.getElementById("local-versions-selector").appendChild(document.createElement("option")); + new_option.value=v; + $(new_option).text(v); + } + }, + error: function() { + tip( 'Getting local versions failed.'); + } + }); + } + + function show_releasedversions() + { + $.ajax({ + type: 'GET', + url: 'https://api.github.com/repos/XX-net/XX-Net/releases', + dataType: 'json', + success: function(result) { + + $("#released-versions-selector").html(""); + + var vs = result; + for(var i = 0 ; i < 30 && vs[i]; ++i) + { + var v = vs[i]['tag_name']; + var new_option = document.getElementById("released-versions-selector").appendChild(document.createElement("option")); + new_option.value=v; + $(new_option).text(v); + } + }, + error: function() { + tip( 'Getting released versions failed.'); + } + }); + show_releasedversions = function(){}; + } + + $(function(){ + $("#local-versions-selector").focus(function(){ + show_localversions(); + }); + $("#local-versions-selector").change(function(){ + $("#manual-version").val($("#local-versions-selector").val()); + }); + + $("#released-versions-selector").focus(function(){ + show_releasedversions(); + }); + $("#released-versions-selector").change(function(){ + $("#manual-version").val($("#released-versions-selector").val()); + }); + + }); +</script>
https://api.github.com/repos/XX-net/XX-Net/pulls/9109
2017-12-19T03:14:43Z
2017-12-19T09:28:58Z
2017-12-19T09:28:58Z
2017-12-21T02:52:26Z
2,198
XX-net/XX-Net
17,157
Update `is_writeable()` for 2 methods
diff --git a/utils/general.py b/utils/general.py index 6201320d3c6..e8b158a773d 100755 --- a/utils/general.py +++ b/utils/general.py @@ -112,17 +112,19 @@ def user_config_dir(dir='Ultralytics'): return path -def is_writeable(dir): - # Return True if directory has write permissions - # return os.access(path, os.R_OK) # known issue on Windows - file = Path(dir) / 'tmp.txt' - try: - with open(file, 'w'): - pass - file.unlink() # remove file - return True - except IOError: - return False +def is_writeable(dir, test=False): + # Return True if directory has write permissions, test opening a file with write permissions if test=True + if test: # method 1 + file = Path(dir) / 'tmp.txt' + try: + with open(file, 'w'): # open file with write permissions + pass + file.unlink() # remove file + return True + except IOError: + return False + else: # method 2 + return os.access(dir, os.R_OK) # possible issues on Windows def is_docker():
## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Enhanced directory write permission checking in Ultralytics YOLOv5's utility functions. ### 📊 Key Changes - 🛠️ Modified the `is_writeable` function in `utils/general.py` to include two methods for checking directory write permissions. - ✨ Added a `test` parameter to the existing function to toggle between the original file creation method (method 1) and a new method using `os.access` (method 2). ### 🎯 Purpose & Impact - 💡 The purpose is to improve the reliability of the write permission check across different environments, including potential edge cases on Windows. - 🔒 Potential Impact: Provides users and developers with a more robust way to determine if a directory is writeable, which can prevent errors and improve the overall experience when interacting with file systems.
https://api.github.com/repos/ultralytics/yolov5/pulls/4744
2021-09-10T15:10:23Z
2021-09-10T15:52:33Z
2021-09-10T15:52:33Z
2024-01-19T15:48:06Z
300
ultralytics/yolov5
24,811
[extractor/rbgtum] fix m3u8 regex, add new hostname
diff --git a/yt_dlp/extractor/_extractors.py b/yt_dlp/extractor/_extractors.py index ae73a9f9608..5245c92a3cf 100644 --- a/yt_dlp/extractor/_extractors.py +++ b/yt_dlp/extractor/_extractors.py @@ -1585,6 +1585,7 @@ from .rbgtum import ( RbgTumIE, RbgTumCourseIE, + RbgTumNewCourseIE, ) from .rcs import ( RCSIE, diff --git a/yt_dlp/extractor/rbgtum.py b/yt_dlp/extractor/rbgtum.py index 47649cfc586..c8a331f3ee6 100644 --- a/yt_dlp/extractor/rbgtum.py +++ b/yt_dlp/extractor/rbgtum.py @@ -1,10 +1,11 @@ import re from .common import InfoExtractor +from ..utils import parse_qs, remove_start, traverse_obj, ExtractorError class RbgTumIE(InfoExtractor): - _VALID_URL = r'https://live\.rbg\.tum\.de/w/(?P<id>.+)' + _VALID_URL = r'https://(?:live\.rbg\.tum\.de|tum\.live)/w/(?P<id>[^?#]+)' _TESTS = [{ # Combined view 'url': 'https://live.rbg.tum.de/w/cpp/22128', @@ -35,16 +36,18 @@ class RbgTumIE(InfoExtractor): 'title': 'Fachschaftsvollversammlung', 'series': 'Fachschaftsvollversammlung Informatik', } + }, { + 'url': 'https://tum.live/w/linalginfo/27102', + 'only_matching': True, }, ] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) - m3u8 = self._html_search_regex(r'(https://.+?\.m3u8)', webpage, 'm3u8') - lecture_title = self._html_search_regex(r'(?si)<h1.*?>(.*)</h1>', webpage, 'title') - lecture_series_title = self._html_search_regex( - r'(?s)<title\b[^>]*>\s*(?:TUM-Live\s\|\s?)?([^:]+):?.*?</title>', webpage, 'series') + m3u8 = self._html_search_regex(r'"(https://[^"]+\.m3u8[^"]*)', webpage, 'm3u8') + lecture_title = self._html_search_regex(r'<h1[^>]*>([^<]+)</h1>', webpage, 'title', fatal=False) + lecture_series_title = remove_start(self._html_extract_title(webpage), 'TUM-Live | ') formats = self._extract_m3u8_formats(m3u8, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls') @@ -57,9 +60,9 @@ def _real_extract(self, url): class RbgTumCourseIE(InfoExtractor): - _VALID_URL = r'https://live\.rbg\.tum\.de/course/(?P<id>.+)' + _VALID_URL = r'https://(?P<hostname>(?:live\.rbg\.tum\.de|tum\.live))/old/course/(?P<id>(?P<year>\d+)/(?P<term>\w+)/(?P<slug>[^/?#]+))' _TESTS = [{ - 'url': 'https://live.rbg.tum.de/course/2022/S/fpv', + 'url': 'https://live.rbg.tum.de/old/course/2022/S/fpv', 'info_dict': { 'title': 'Funktionale Programmierung und Verifikation (IN0003)', 'id': '2022/S/fpv', @@ -69,7 +72,7 @@ class RbgTumCourseIE(InfoExtractor): }, 'playlist_count': 13, }, { - 'url': 'https://live.rbg.tum.de/course/2022/W/set', + 'url': 'https://live.rbg.tum.de/old/course/2022/W/set', 'info_dict': { 'title': 'SET FSMPIC', 'id': '2022/W/set', @@ -78,16 +81,62 @@ class RbgTumCourseIE(InfoExtractor): 'noplaylist': False, }, 'playlist_count': 6, + }, { + 'url': 'https://tum.live/old/course/2023/S/linalginfo', + 'only_matching': True, }, ] def _real_extract(self, url): - course_id = self._match_id(url) - webpage = self._download_webpage(url, course_id) + course_id, hostname, year, term, slug = self._match_valid_url(url).group('id', 'hostname', 'year', 'term', 'slug') + meta = self._download_json( + f'https://{hostname}/api/courses/{slug}/', course_id, fatal=False, + query={'year': year, 'term': term}) or {} + lecture_series_title = meta.get('Name') + lectures = [self.url_result(f'https://{hostname}/w/{slug}/{stream_id}', RbgTumIE) + for stream_id in traverse_obj(meta, ('Streams', ..., 'ID'))] + + if not lectures: + webpage = self._download_webpage(url, course_id) + lecture_series_title = remove_start(self._html_extract_title(webpage), 'TUM-Live | ') + lectures = [self.url_result(f'https://{hostname}{lecture_path}', RbgTumIE) + for lecture_path in re.findall(r'href="(/w/[^/"]+/[^/"]+)"', webpage)] + + return self.playlist_result(lectures, course_id, lecture_series_title) - lecture_series_title = self._html_search_regex(r'(?si)<h1.*?>(.*)</h1>', webpage, 'title') - lecture_urls = [] - for lecture_url in re.findall(r'(?i)href="/w/(.+)(?<!/cam)(?<!/pres)(?<!/chat)"', webpage): - lecture_urls.append(self.url_result('https://live.rbg.tum.de/w/' + lecture_url, ie=RbgTumIE.ie_key())) +class RbgTumNewCourseIE(InfoExtractor): + _VALID_URL = r'https://(?P<hostname>(?:live\.rbg\.tum\.de|tum\.live))/\?' + _TESTS = [{ + 'url': 'https://live.rbg.tum.de/?year=2022&term=S&slug=fpv&view=3', + 'info_dict': { + 'title': 'Funktionale Programmierung und Verifikation (IN0003)', + 'id': '2022/S/fpv', + }, + 'params': { + 'noplaylist': False, + }, + 'playlist_count': 13, + }, { + 'url': 'https://live.rbg.tum.de/?year=2022&term=W&slug=set&view=3', + 'info_dict': { + 'title': 'SET FSMPIC', + 'id': '2022/W/set', + }, + 'params': { + 'noplaylist': False, + }, + 'playlist_count': 6, + }, { + 'url': 'https://tum.live/?year=2023&term=S&slug=linalginfo&view=3', + 'only_matching': True, + }] + + def _real_extract(self, url): + query = parse_qs(url) + errors = [key for key in ('year', 'term', 'slug') if not query.get(key)] + if errors: + raise ExtractorError(f'Input URL is missing query parameters: {", ".join(errors)}') + year, term, slug = query['year'][0], query['term'][0], query['slug'][0] + hostname = self._match_valid_url(url).group('hostname') - return self.playlist_result(lecture_urls, course_id, lecture_series_title) + return self.url_result(f'https://{hostname}/old/course/{year}/{term}/{slug}', RbgTumCourseIE)
**IMPORTANT**: PRs without the template will be CLOSED ### Description of your *pull request* and other information <!-- Explanation of your *pull request* in arbitrary form goes here. Please **make sure the description explains the purpose and effect** of your *pull request* and is worded well enough to be understood. Provide as much **context and examples** as possible --> This pr contains: 1. adjust some regex to capture the jwt after m3u8 url 2. add support for new hostname tum.live <details open><summary>Template</summary> <!-- OPEN is intentional --> <!-- # PLEASE FOLLOW THE GUIDE BELOW - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [x] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check all of the following options that apply: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Fix or improvement to an extractor (Make sure to add/update tests) - [ ] New extractor ([Piracy websites will not be accepted](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#is-the-website-primarily-used-for-piracy)) - [ ] Core bug fix/improvement - [ ] New feature (It is strongly [recommended to open an issue first](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#adding-new-feature-or-making-overarching-changes)) <!-- Do NOT edit/remove anything below this! --> </details><details><summary>Copilot Summary</summary> <!-- copilot:all --> ### <samp>🤖 Generated by Copilot at 05a2890</samp> ### Summary 🆕🛠️🧹 <!-- 1. 🆕 for adding support for the new domain `tum.live`. 2. 🛠️ for fixing the extraction of some videos with query strings in their m3u8 URLs. 3. 🧹 for making the extractors more consistent and flexible. --> Improved and fixed `RbgTumIE` and `RbgTumCourseIE` extractors to handle new domain and URL formats. Added tests and refactored code for clarity and robustness. > _Oh we are the coders of the `tum.live` domain_ > _We extract the videos with skill and with brain_ > _We fix the URLs and we test every case_ > _We heave away and haul away and keep up with the pace_ ### Walkthrough * Update the `RbgTumIE` and `RbgTumCourseIE` extractors to support the new domain `tum.live` as an alternative to `live.rbg.tum.de` ([link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L7-R7), [link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L60-R64)) * Fix the extraction of some videos that have a query string in their m3u8 URL by including the optional query string in the `_html_search_regex` call for the `m3u8` variable in the `RbgTumIE` extractor ([link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L44-R48)) * Use the `hostname` variable from the `_match_valid_url` call instead of hardcoding the `live.rbg.tum.de` domain in the `RbgTumCourseIE` extractor, to make it more flexible and consistent with the `RbgTumIE` extractor ([link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L81-R93), [link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L91-R100)) * Add test cases to the `RbgTumIE` and `RbgTumCourseIE` extractors to check the extraction of videos and courses from the new domain `tum.live` ([link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983R38-R41), [link](https://github.com/yt-dlp/yt-dlp/pull/7690/files?diff=unified&w=0#diff-7323ff06817f10b74d5ee71e449638fe3d088f9c476a5e46e77477ef01cf2983L81-R93)) </details> 1. 213
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/7690
2023-07-25T12:19:12Z
2023-09-21T17:37:58Z
2023-09-21T17:37:58Z
2023-09-21T17:37:58Z
1,948
yt-dlp/yt-dlp
7,975
use request parameter resolvers
diff --git a/localstack/services/apigateway/helpers.py b/localstack/services/apigateway/helpers.py index d29b4fc1264ee..5233a9c586b6c 100644 --- a/localstack/services/apigateway/helpers.py +++ b/localstack/services/apigateway/helpers.py @@ -401,8 +401,7 @@ def resolve(self, context: ApiInvocationContext) -> IntegrationParameters: # } request_params = context.integration.get("requestParameters", {}) - # resolve all integration request parameters with the already resolved method - # request parameters + # resolve all integration request parameters with the already resolved method request parameters integrations_parameters = {} for k, v in request_params.items(): if v.lower() in method_request_params: @@ -591,7 +590,7 @@ def get_stage_variables(context: ApiInvocationContext) -> Optional[Dict[str, str ).apigateway try: response = api_gateway_client.get_stage(restApiId=context.api_id, stageName=context.stage) - return response.get("variables") + return response.get("variables", {}) except Exception: LOG.info("Failed to get stage %s for API id %s", context.stage, context.api_id) return {} @@ -1505,22 +1504,6 @@ def extract_api_id_from_hostname_in_url(hostname: str) -> str: return match.group(1) -# This need to be extended to handle mappings and not just literal values. -def create_invocation_headers(invocation_context: ApiInvocationContext) -> Dict[str, Any]: - headers = invocation_context.headers - integration = invocation_context.integration - - if request_parameters := integration.get("requestParameters"): - for req_parameter_key, req_parameter_value in request_parameters.items(): - if ( - header_name := req_parameter_key.lstrip("integration.request.header.") - if "integration.request.header." in req_parameter_key - else None - ): - headers.update({header_name: req_parameter_value}) - return headers - - def is_greedy_path(path_part: str) -> bool: return path_part.startswith("{") and path_part.endswith("+}") diff --git a/localstack/services/apigateway/integration.py b/localstack/services/apigateway/integration.py index 3c36706b03a1e..aae94b80575d9 100644 --- a/localstack/services/apigateway/integration.py +++ b/localstack/services/apigateway/integration.py @@ -402,9 +402,14 @@ def invoke(self, invocation_context: ApiInvocationContext): class LambdaIntegration(BackendIntegration): def invoke(self, invocation_context: ApiInvocationContext): - headers = helpers.create_invocation_headers(invocation_context) invocation_context.context = helpers.get_event_request_context(invocation_context) invocation_context.stage_variables = helpers.get_stage_variables(invocation_context) + headers = invocation_context.headers + + # resolve integration parameters + integration_parameters = self.request_params_resolver.resolve(context=invocation_context) + headers.update(integration_parameters.get("headers", {})) + if invocation_context.authorizer_type: invocation_context.context["authorizer"] = invocation_context.authorizer_result @@ -622,10 +627,15 @@ def invoke(self, invocation_context: ApiInvocationContext): integration = invocation_context.integration path_params = invocation_context.path_params method = invocation_context.method - headers = helpers.create_invocation_headers(invocation_context) + headers = invocation_context.headers + relative_path, query_string_params = extract_query_string_params(path=invocation_path) uri = integration.get("uri") or integration.get("integrationUri") or "" + # resolve integration parameters + integration_parameters = self.request_params_resolver.resolve(context=invocation_context) + headers.update(integration_parameters.get("headers", {})) + if ":servicediscovery:" in uri: # check if this is a servicediscovery integration URI client = connect_to().servicediscovery diff --git a/tests/unit/test_apigateway.py b/tests/unit/test_apigateway.py index b51912b003e7b..1218f112a0e7e 100644 --- a/tests/unit/test_apigateway.py +++ b/tests/unit/test_apigateway.py @@ -19,7 +19,6 @@ OpenAPISpecificationResolver, RequestParametersResolver, apply_json_patch_safe, - create_invocation_headers, extract_path_params, extract_query_string_params, get_resource_for_path, @@ -677,14 +676,24 @@ def test_create_invocation_headers(): invocation_context.integration = { "requestParameters": {"integration.request.header.X-Custom": "'Event'"} } - headers = create_invocation_headers(invocation_context) - assert headers == {"X-Header": "foobar", "X-Custom": "'Event'"} + headers = invocation_context.headers + + req_params_resolver = RequestParametersResolver() + req_params = req_params_resolver.resolve(invocation_context) + + headers.update(req_params.get("headers", {})) + assert headers == {"X-Header": "foobar", "X-Custom": "Event"} invocation_context.integration = { "requestParameters": {"integration.request.path.foobar": "'CustomValue'"} } - headers = create_invocation_headers(invocation_context) - assert headers == {"X-Header": "foobar", "X-Custom": "'Event'"} + + req_params = req_params_resolver.resolve(invocation_context) + headers.update(req_params.get("headers", {})) + assert headers == {"X-Header": "foobar", "X-Custom": "Event"} + + path = req_params.get("path", {}) + assert path == {"foobar": "CustomValue"} class TestApigatewayEvents:
## Motivation Improves community PR by using the `RequestParametersResolver` that can handle, headers, path and query strings and also static values. Fixes the previous test - static values are configured using single quotes, "'Fixed-Header-Value'", but transformed into normal header values when passed to the integration.
https://api.github.com/repos/localstack/localstack/pulls/10049
2024-01-10T23:11:03Z
2024-01-23T07:46:44Z
2024-01-23T07:46:44Z
2024-01-23T07:46:45Z
1,269
localstack/localstack
29,248
multipart-fix
diff --git a/mitmproxy/net/http/multipart.py b/mitmproxy/net/http/multipart.py index a854d47fd4..4edf76acd3 100644 --- a/mitmproxy/net/http/multipart.py +++ b/mitmproxy/net/http/multipart.py @@ -1,8 +1,43 @@ import re - +import mimetypes +from urllib.parse import quote from mitmproxy.net.http import headers +def encode(head, l): + + k = head.get("content-type") + if k: + k = headers.parse_content_type(k) + if k is not None: + try: + boundary = k[2]["boundary"].encode("ascii") + boundary = quote(boundary) + except (KeyError, UnicodeError): + return b"" + hdrs = [] + for key, value in l: + file_type = mimetypes.guess_type(str(key))[0] or "text/plain; charset=utf-8" + + if key: + hdrs.append(b"--%b" % boundary.encode('utf-8')) + disposition = b'form-data; name="%b"' % key + hdrs.append(b"Content-Disposition: %b" % disposition) + hdrs.append(b"Content-Type: %b" % file_type.encode('utf-8')) + hdrs.append(b'') + hdrs.append(value) + hdrs.append(b'') + + if value is not None: + # If boundary is found in value then raise ValueError + if re.search(rb"^--%b$" % re.escape(boundary.encode('utf-8')), value): + raise ValueError(b"boundary found in encoded string") + + hdrs.append(b"--%b--\r\n" % boundary.encode('utf-8')) + temp = b"\r\n".join(hdrs) + return temp + + def decode(hdrs, content): """ Takes a multipart boundary encoded string and returns list of (key, value) tuples. @@ -19,14 +54,14 @@ def decode(hdrs, content): rx = re.compile(br'\bname="([^"]+)"') r = [] - - for i in content.split(b"--" + boundary): - parts = i.splitlines() - if len(parts) > 1 and parts[0][0:2] != b"--": - match = rx.search(parts[1]) - if match: - key = match.group(1) - value = b"".join(parts[3 + parts[2:].index(b""):]) - r.append((key, value)) + if content is not None: + for i in content.split(b"--" + boundary): + parts = i.splitlines() + if len(parts) > 1 and parts[0][0:2] != b"--": + match = rx.search(parts[1]) + if match: + key = match.group(1) + value = b"".join(parts[3 + parts[2:].index(b""):]) + r.append((key, value)) return r return [] diff --git a/mitmproxy/net/http/request.py b/mitmproxy/net/http/request.py index 959fdd3399..783fd5ff4a 100644 --- a/mitmproxy/net/http/request.py +++ b/mitmproxy/net/http/request.py @@ -468,7 +468,8 @@ def _get_multipart_form(self): return () def _set_multipart_form(self, value): - raise NotImplementedError() + self.content = mitmproxy.net.http.multipart.encode(self.headers, value) + self.headers["content-type"] = "multipart/form-data" @property def multipart_form(self): diff --git a/mitmproxy/tools/console/consoleaddons.py b/mitmproxy/tools/console/consoleaddons.py index a40cdeaa76..58f236c087 100644 --- a/mitmproxy/tools/console/consoleaddons.py +++ b/mitmproxy/tools/console/consoleaddons.py @@ -368,7 +368,8 @@ def edit_focus_options(self) -> typing.Sequence[str]: """ return [ "cookies", - "form", + "urlencoded form", + "multipart form", "path", "method", "query", @@ -403,8 +404,10 @@ def edit_focus(self, part: str) -> None: flow.response = http.HTTPResponse.make() if part == "cookies": self.master.switch_view("edit_focus_cookies") - elif part == "form": - self.master.switch_view("edit_focus_form") + elif part == "urlencoded form": + self.master.switch_view("edit_focus_urlencoded_form") + elif part == "multipart form": + self.master.switch_view("edit_focus_multipart_form") elif part == "path": self.master.switch_view("edit_focus_path") elif part == "query": diff --git a/mitmproxy/tools/console/grideditor/editors.py b/mitmproxy/tools/console/grideditor/editors.py index 61fcf6b456..09666d5880 100644 --- a/mitmproxy/tools/console/grideditor/editors.py +++ b/mitmproxy/tools/console/grideditor/editors.py @@ -53,14 +53,30 @@ def set_data(self, vals, flow): flow.response.headers = Headers(vals) -class RequestFormEditor(base.FocusEditor): - title = "Edit URL-encoded Form" +class RequestMultipartEditor(base.FocusEditor): + title = "Edit Multipart Form" columns = [ col_text.Column("Key"), col_text.Column("Value") ] def get_data(self, flow): + + return flow.request.multipart_form.items(multi=True) + + def set_data(self, vals, flow): + flow.request.multipart_form = vals + + +class RequestUrlEncodedEditor(base.FocusEditor): + title = "Edit UrlEncoded Form" + columns = [ + col_text.Column("Key"), + col_text.Column("Value") + ] + + def get_data(self, flow): + return flow.request.urlencoded_form.items(multi=True) def set_data(self, vals, flow): diff --git a/mitmproxy/tools/console/window.py b/mitmproxy/tools/console/window.py index 7669299c79..fb2e8c1e6a 100644 --- a/mitmproxy/tools/console/window.py +++ b/mitmproxy/tools/console/window.py @@ -64,7 +64,8 @@ def __init__(self, master, base): edit_focus_cookies = grideditor.CookieEditor(master), edit_focus_setcookies = grideditor.SetCookieEditor(master), edit_focus_setcookie_attrs = grideditor.CookieAttributeEditor(master), - edit_focus_form = grideditor.RequestFormEditor(master), + edit_focus_multipart_form=grideditor.RequestMultipartEditor(master), + edit_focus_urlencoded_form=grideditor.RequestUrlEncodedEditor(master), edit_focus_path = grideditor.PathEditor(master), edit_focus_request_headers = grideditor.RequestHeaderEditor(master), edit_focus_response_headers = grideditor.ResponseHeaderEditor(master), diff --git a/test/mitmproxy/net/http/test_multipart.py b/test/mitmproxy/net/http/test_multipart.py index 68ae6bbdfb..6d2e50170b 100644 --- a/test/mitmproxy/net/http/test_multipart.py +++ b/test/mitmproxy/net/http/test_multipart.py @@ -1,5 +1,6 @@ from mitmproxy.net.http import Headers from mitmproxy.net.http import multipart +import pytest def test_decode(): @@ -22,3 +23,39 @@ def test_decode(): assert len(form) == 2 assert form[0] == (b"field1", b"value1") assert form[1] == (b"field2", b"value2") + + boundary = 'boundary茅莽' + headers = Headers( + content_type='multipart/form-data; boundary=' + boundary + ) + result = multipart.decode(headers, content) + assert result == [] + + headers = Headers( + content_type='' + ) + assert multipart.decode(headers, content) == [] + + +def test_encode(): + data = [("file".encode('utf-8'), "shell.jpg".encode('utf-8')), + ("file_size".encode('utf-8'), "1000".encode('utf-8'))] + headers = Headers( + content_type='multipart/form-data; boundary=127824672498' + ) + content = multipart.encode(headers, data) + + assert b'Content-Disposition: form-data; name="file"' in content + assert b'Content-Type: text/plain; charset=utf-8\r\n\r\nshell.jpg\r\n\r\n--127824672498\r\n' in content + assert b'1000\r\n\r\n--127824672498--\r\n' + assert len(content) == 252 + + with pytest.raises(ValueError, match=r"boundary found in encoded string"): + multipart.encode(headers, [("key".encode('utf-8'), "--127824672498".encode('utf-8'))]) + + boundary = 'boundary茅莽' + headers = Headers( + content_type='multipart/form-data; boundary=' + boundary + ) + result = multipart.encode(headers, data) + assert result == b'' diff --git a/test/mitmproxy/net/http/test_request.py b/test/mitmproxy/net/http/test_request.py index ef581a9147..71d5c7a125 100644 --- a/test/mitmproxy/net/http/test_request.py +++ b/test/mitmproxy/net/http/test_request.py @@ -371,6 +371,7 @@ def test_get_multipart_form(self): assert list(request.multipart_form.items()) == [] def test_set_multipart_form(self): - request = treq(content=b"foobar") - with pytest.raises(NotImplementedError): - request.multipart_form = "foobar" + request = treq() + request.multipart_form = [("file", "shell.jpg"), ("file_size", "1000")] + assert request.headers["Content-Type"] == 'multipart/form-data' + assert request.content is None
Fixes #3175
https://api.github.com/repos/mitmproxy/mitmproxy/pulls/3420
2018-12-14T16:03:11Z
2019-11-15T18:04:48Z
2019-11-15T18:04:48Z
2019-11-16T13:13:19Z
2,275
mitmproxy/mitmproxy
28,052
update code-owners
diff --git a/CODEOWNERS b/CODEOWNERS index d4b74d4ce8..b0658a770f 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,7 +1,7 @@ * @yk @andreaskoepf /website/ @AbdBarho @notmd @yk @andreaskoepf /website/src/data/team.json @yk @andreaskoepf @fozziethebeat @AbdBarho @notmd @theblackcat102 @sanagno @olliestanley @andrewm4894 -/model/ @theblackcat102 @sanagno @dvruette @andreaskoepf @yk @jordiclive +/model/ @theblackcat102 @sanagno @dvruette @andreaskoepf @yk @jordiclive @shahules786 /copilot/ @andreaskoepf @yk /docs/ @andrewm4894 @olliestanley @andreaskoepf @yk /.devcontainer/ @andrewm4894 @andreaskoepf @yk
## What Added @shahules786 to Code owners
https://api.github.com/repos/LAION-AI/Open-Assistant/pulls/3584
2023-07-19T07:19:18Z
2023-07-19T07:41:59Z
2023-07-19T07:41:59Z
2023-07-19T07:41:59Z
258
LAION-AI/Open-Assistant
37,744
added Transfer Learning for Natural Language Processing
diff --git a/courses.md b/courses.md index 73f13f90..69cdcf0e 100644 --- a/courses.md +++ b/courses.md @@ -38,4 +38,6 @@ The following is a list of free or paid online courses on machine learning, stat * [Transfer Learning for Natural Language Processing](https://www.manning.com/books/transfer-learning-for-natural-language-processing) - $ * [Grokking Artificial Intelligence Algorithms](https://www.manning.com/books/grokking-artificial-intelligence-algorithms) - $ * [Machine Learning for Business](https://www.manning.com/books/machine-learning-for-business) - $ +* [Transfer Learning for Natural Language Processing](https://www.manning.com/books/transfer-learning-for-natural-language-processing) - $ * [In-depth introduction to machine learning in 15 hours of expert videos (by Prof. Trevor Hastie, Prof. Rob Tibshirani, Stanford)](https://www.dataschool.io/15-hours-of-expert-machine-learning-videos/) - free +
Hi, Branko from Manning here, I thought this book of ours could be a good resource here. Thanks for checking it out!
https://api.github.com/repos/josephmisiti/awesome-machine-learning/pulls/726
2020-09-29T14:13:54Z
2020-09-30T13:23:38Z
2020-09-30T13:23:38Z
2020-09-30T13:23:38Z
229
josephmisiti/awesome-machine-learning
52,288
Invoke pipstrap in tox and during the CI
diff --git a/.azure-pipelines/templates/jobs/extended-tests-jobs.yml b/.azure-pipelines/templates/jobs/extended-tests-jobs.yml index 0e1a988614a..67fa3488029 100644 --- a/.azure-pipelines/templates/jobs/extended-tests-jobs.yml +++ b/.azure-pipelines/templates/jobs/extended-tests-jobs.yml @@ -3,6 +3,8 @@ jobs: variables: - name: IMAGE_NAME value: ubuntu-18.04 + - name: PYTHON_VERSION + value: 3.8 - group: certbot-common strategy: matrix: diff --git a/.azure-pipelines/templates/jobs/packaging-jobs.yml b/.azure-pipelines/templates/jobs/packaging-jobs.yml index b0c7998cbed..2d659aef5b7 100644 --- a/.azure-pipelines/templates/jobs/packaging-jobs.yml +++ b/.azure-pipelines/templates/jobs/packaging-jobs.yml @@ -78,9 +78,16 @@ jobs: artifact: windows-installer path: $(Build.SourcesDirectory)/bin displayName: Retrieve Windows installer + # pip 9.0 provided by pipstrap is not able to resolve properly the pywin32 dependency + # required by certbot-ci: as a temporary workaround until pipstrap is updated, we install + # a recent version of pip, but we also to disable the isolated feature as described in + # https://github.com/certbot/certbot/issues/8256 - script: | py -3 -m venv venv + venv\Scripts\python -m pip install pip==20.2.3 setuptools==50.3.0 wheel==0.35.1 venv\Scripts\python tools\pip_install.py -e certbot-ci + env: + PIP_NO_BUILD_ISOLATION: no displayName: Prepare Certbot-CI - script: | set PATH=%ProgramFiles(x86)%\Certbot\bin;%PATH% @@ -135,10 +142,16 @@ jobs: pool: vmImage: ubuntu-18.04 steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: 3.8 + addToPath: true - script: | sudo apt-get update sudo apt-get install -y --no-install-recommends nginx-light snapd - python tools/pip_install.py -U tox + python3 -m venv venv + venv/bin/python letsencrypt-auto-source/pieces/pipstrap.py + venv/bin/python tools/pip_install.py -U tox displayName: Install dependencies - task: DownloadPipelineArtifact@2 inputs: @@ -149,7 +162,7 @@ jobs: sudo snap install --dangerous --classic snap/certbot_*_amd64.snap displayName: Install Certbot snap - script: | - python -m tox -e integration-external,apacheconftest-external-with-pebble + venv/bin/python -m tox -e integration-external,apacheconftest-external-with-pebble displayName: Run tox - job: snap_dns_run dependsOn: snaps_build @@ -171,6 +184,7 @@ jobs: displayName: Retrieve Certbot snaps - script: | python3 -m venv venv + venv/bin/python letsencrypt-auto-source/pieces/pipstrap.py venv/bin/python tools/pip_install.py -e certbot-ci displayName: Prepare Certbot-CI - script: | diff --git a/.azure-pipelines/templates/jobs/standard-tests-jobs.yml b/.azure-pipelines/templates/jobs/standard-tests-jobs.yml index 3bb73b67e2a..d5b3a0a1632 100644 --- a/.azure-pipelines/templates/jobs/standard-tests-jobs.yml +++ b/.azure-pipelines/templates/jobs/standard-tests-jobs.yml @@ -1,5 +1,7 @@ jobs: - job: test + variables: + PYTHON_VERSION: 3.8 strategy: matrix: macos-py27: diff --git a/.azure-pipelines/templates/steps/tox-steps.yml b/.azure-pipelines/templates/steps/tox-steps.yml index 828552e4379..7f6c3150f3f 100644 --- a/.azure-pipelines/templates/steps/tox-steps.yml +++ b/.azure-pipelines/templates/steps/tox-steps.yml @@ -21,7 +21,6 @@ steps: inputs: versionSpec: $(PYTHON_VERSION) addToPath: true - condition: ne(variables['PYTHON_VERSION'], '') # tools/pip_install.py is used to pin packages to a known working version # except in tests where the environment variable CERTBOT_NO_PIN is set. # virtualenv is listed here explicitly to make sure it is upgraded when @@ -30,6 +29,7 @@ steps: # set, pip updates dependencies it thinks are already satisfied to avoid some # problems with its lack of real dependency resolution. - bash: | + python letsencrypt-auto-source/pieces/pipstrap.py python tools/pip_install.py -I tox virtualenv displayName: Install runtime dependencies - task: DownloadSecureFile@1 diff --git a/letsencrypt-auto-source/letsencrypt-auto b/letsencrypt-auto-source/letsencrypt-auto index 7168ee2d1cf..5c5434323fd 100755 --- a/letsencrypt-auto-source/letsencrypt-auto +++ b/letsencrypt-auto-source/letsencrypt-auto @@ -1615,6 +1615,11 @@ maybe_argparse = ( if sys.version_info < (2, 7, 0) else []) +# Be careful when updating the pinned versions here, in particular for pip. +# Indeed starting from 10.0, pip will build dependencies in isolation if the +# related projects are compliant with PEP 517. This is not something we want +# as of now, so the isolation build will need to be disabled wherever +# pipstrap is used (see https://github.com/certbot/certbot/issues/8256). PACKAGES = maybe_argparse + [ # Pip has no dependencies, as it vendors everything: ('11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/' diff --git a/letsencrypt-auto-source/pieces/pipstrap.py b/letsencrypt-auto-source/pieces/pipstrap.py index 346e239386f..7610c268637 100755 --- a/letsencrypt-auto-source/pieces/pipstrap.py +++ b/letsencrypt-auto-source/pieces/pipstrap.py @@ -67,6 +67,11 @@ def check_output(*popenargs, **kwargs): if sys.version_info < (2, 7, 0) else []) +# Be careful when updating the pinned versions here, in particular for pip. +# Indeed starting from 10.0, pip will build dependencies in isolation if the +# related projects are compliant with PEP 517. This is not something we want +# as of now, so the isolation build will need to be disabled wherever +# pipstrap is used (see https://github.com/certbot/certbot/issues/8256). PACKAGES = maybe_argparse + [ # Pip has no dependencies, as it vendors everything: ('11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/' diff --git a/tox.ini b/tox.ini index 0336a57df8a..5c1ceedb1db 100644 --- a/tox.ini +++ b/tox.ini @@ -62,6 +62,7 @@ source_paths = [testenv] passenv = CERTBOT_NO_PIN +commands_pre = python {toxinidir}/letsencrypt-auto-source/pieces/pipstrap.py commands = !cover: {[base]install_and_test} {[base]all_packages} !cover: python tests/lock_test.py
Partial fix for #8256 This PR makes tox calls pipstrap before any `commands` is executed, and Azure Pipelines calls pipstrap when appropriate (when an actual call to `pip` is done). Docker is already covered since `pipstrap` is called in the `certbot/certbot` docker on the Python system interpreter, and that interpreter is reused during the build of the relevant Docker images for DNS plugins.
https://api.github.com/repos/certbot/certbot/pulls/8316
2020-09-23T18:47:10Z
2020-09-25T00:12:13Z
2020-09-25T00:12:13Z
2020-09-25T00:12:13Z
1,847
certbot/certbot
2,257
Bump llama-index-core from 0.10.12 to 0.10.24 in /llama-index-integrations/llms/llama-index-llms-friendli
diff --git a/llama-index-integrations/llms/llama-index-llms-friendli/poetry.lock b/llama-index-integrations/llms/llama-index-llms-friendli/poetry.lock index bc69700e34256..bdb6af63c50b1 100644 --- a/llama-index-integrations/llms/llama-index-llms-friendli/poetry.lock +++ b/llama-index-integrations/llms/llama-index-llms-friendli/poetry.lock @@ -2537,13 +2537,13 @@ files = [ [[package]] name = "llama-index-core" -version = "0.10.12" +version = "0.10.24" description = "Interface between LLMs and your data" optional = false -python-versions = ">=3.8.1,<4.0" +python-versions = "<4.0,>=3.8.1" files = [ - {file = "llama_index_core-0.10.12-py3-none-any.whl", hash = "sha256:47663cc3282684e6b7f06e905d98382aa3dbec5191ab72c239b4f19e0b08c041"}, - {file = "llama_index_core-0.10.12.tar.gz", hash = "sha256:071e3a9ab2071c900657149cabf39199818e7244d16ef5cc096e5c0bff8174f4"}, + {file = "llama_index_core-0.10.24-py3-none-any.whl", hash = "sha256:c4b979160e813f2f41b6aeaa243293b5297f83aed1c3654d2673aa881551d479"}, + {file = "llama_index_core-0.10.24.tar.gz", hash = "sha256:0bb28871a44d697a06df8668602828c9132ffe3289b4a598f8928b887ac70901"}, ] [package.dependencies] @@ -2575,7 +2575,7 @@ gradientai = ["gradientai (>=1.4.0)"] html = ["beautifulsoup4 (>=4.12.2,<5.0.0)"] langchain = ["langchain (>=0.0.303)"] local-models = ["optimum[onnxruntime] (>=1.13.2,<2.0.0)", "sentencepiece (>=0.1.99,<0.2.0)", "transformers[torch] (>=4.33.1,<5.0.0)"] -postgres = ["asyncpg (>=0.28.0,<0.29.0)", "pgvector (>=0.1.0,<0.2.0)", "psycopg2-binary (>=2.9.9,<3.0.0)"] +postgres = ["asyncpg (>=0.29.0,<0.30.0)", "pgvector (>=0.2.4,<0.3.0)", "psycopg2-binary (>=2.9.9,<3.0.0)"] query-tools = ["guidance (>=0.0.64,<0.0.65)", "jsonpath-ng (>=1.6.0,<2.0.0)", "lm-format-enforcer (>=0.4.3,<0.5.0)", "rank-bm25 (>=0.2.2,<0.3.0)", "scikit-learn", "spacy (>=3.7.1,<4.0.0)"] [[package]]
Bumps [llama-index-core](https://github.com/run-llama/llama_index) from 0.10.12 to 0.10.24. <details> <summary>Release notes</summary> <p><em>Sourced from <a href="https://github.com/run-llama/llama_index/releases">llama-index-core's releases</a>.</em></p> <blockquote> <h2>v0.10.24</h2> <p>No release notes provided.</p> <h2>v0.10.23</h2> <p>No release notes provided.</p> <h2>v0.10.22</h2> <p>No release notes provided.</p> <h2>v0.10.20</h2> <p>No release notes provided.</p> <h2>v0.10.19</h2> <h3><code>llama-index-cli</code> [0.1.9]</h3> <ul> <li>Removed chroma as a bundled dep to reduce <code>llama-index</code> deps</li> </ul> <h3><code>llama-index-core</code> [0.10.19]</h3> <ul> <li>Introduce retries for rate limits in <code>OpenAI</code> llm class (<a href="https://redirect.github.com/run-llama/llama_index/issues/11867">#11867</a>)</li> <li>Added table comments to SQL table schemas in <code>SQLDatabase</code> (<a href="https://redirect.github.com/run-llama/llama_index/issues/11774">#11774</a>)</li> <li>Added <code>LogProb</code> type to <code>ChatResponse</code> object (<a href="https://redirect.github.com/run-llama/llama_index/issues/11795">#11795</a>)</li> <li>Introduced <code>LabelledSimpleDataset</code> (<a href="https://redirect.github.com/run-llama/llama_index/issues/11805">#11805</a>)</li> <li>Fixed insert <code>IndexNode</code> objects with unserializable objects (<a href="https://redirect.github.com/run-llama/llama_index/issues/11836">#11836</a>)</li> <li>Fixed stream chat type error when writing response to history in <code>CondenseQuestionChatEngine</code> (<a href="https://redirect.github.com/run-llama/llama_index/issues/11856">#11856</a>)</li> <li>Improve post-processing for json query engine (<a href="https://redirect.github.com/run-llama/llama_index/issues/11862">#11862</a>)</li> </ul> <h3><code>llama-index-embeddings-cohere</code> [0.1.4]</h3> <ul> <li>Fixed async kwarg error (<a href="https://redirect.github.com/run-llama/llama_index/issues/11822">#11822</a>)</li> </ul> <h3><code>llama-index-embeddings-dashscope</code> [0.1.2]</h3> <ul> <li>Fixed pydantic import (<a href="https://redirect.github.com/run-llama/llama_index/issues/11765">#11765</a>)</li> </ul> <h3><code>llama-index-graph-stores-neo4j</code> [0.1.3]</h3> <ul> <li>Properly close connection after verifying connectivity (<a href="https://redirect.github.com/run-llama/llama_index/issues/11821">#11821</a>)</li> </ul> <h3><code>llama-index-llms-cohere</code> [0.1.3]</h3> <ul> <li>Add support for new <code>command-r</code> model (<a href="https://redirect.github.com/run-llama/llama_index/issues/11852">#11852</a>)</li> </ul> <h3><code>llama-index-llms-huggingface</code> [0.1.4]</h3> <ul> <li>Fixed streaming decoding with special tokens (<a href="https://redirect.github.com/run-llama/llama_index/issues/11807">#11807</a>)</li> </ul> <h3><code>llama-index-llms-mistralai</code> [0.1.5]</h3> <ul> <li>Added support for latest and open models (<a href="https://redirect.github.com/run-llama/llama_index/issues/11792">#11792</a>)</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Changelog</summary> <p><em>Sourced from <a href="https://github.com/run-llama/llama_index/blob/main/CHANGELOG.md">llama-index-core's changelog</a>.</em></p> <blockquote> <h3><code>llama-index-core</code> [0.10.24]</h3> <ul> <li>pretty prints in <code>LlamaDebugHandler</code> (<a href="https://redirect.github.com/run-llama/llama_index/issues/12216">#12216</a>)</li> <li>stricter interpreter constraints on pandas query engine (<a href="https://redirect.github.com/run-llama/llama_index/issues/12278">#12278</a>)</li> <li>PandasQueryEngine can now execute 'pd.*' functions (<a href="https://redirect.github.com/run-llama/llama_index/issues/12240">#12240</a>)</li> <li>delete proper metadata in docstore delete function (<a href="https://redirect.github.com/run-llama/llama_index/issues/12276">#12276</a>)</li> <li>improved openai agent parsing function hook (<a href="https://redirect.github.com/run-llama/llama_index/issues/12062">#12062</a>)</li> <li>add raise_on_error flag for SimpleDirectoryReader (<a href="https://redirect.github.com/run-llama/llama_index/issues/12263">#12263</a>)</li> <li>remove un-caught openai import in core (<a href="https://redirect.github.com/run-llama/llama_index/issues/12262">#12262</a>)</li> <li>Fix download_llama_dataset and download_llama_pack (<a href="https://redirect.github.com/run-llama/llama_index/issues/12273">#12273</a>)</li> <li>Implement EvalQueryEngineTool (<a href="https://redirect.github.com/run-llama/llama_index/issues/11679">#11679</a>)</li> <li>Expand instrumenation Span coverage for AgentRunner (<a href="https://redirect.github.com/run-llama/llama_index/issues/12249">#12249</a>)</li> <li>Adding concept of function calling agent/llm (mistral supported for now) (<a href="https://redirect.github.com/run-llama/llama_index/issues/12222">#12222</a>, )</li> </ul> <h3><code>llama-index-embeddings-huggingface</code> [0.2.0]</h3> <ul> <li>Use <code>sentence-transformers</code> as a backend (<a href="https://redirect.github.com/run-llama/llama_index/issues/12277">#12277</a>)</li> </ul> <h3><code>llama-index-postprocessor-voyageai-rerank</code> [0.1.0]</h3> <ul> <li>Added voyageai as a reranker (<a href="https://redirect.github.com/run-llama/llama_index/issues/12111">#12111</a>)</li> </ul> <h3><code>llama-index-readers-gcs</code> [0.1.0]</h3> <ul> <li>Added google cloud storage reader (<a href="https://redirect.github.com/run-llama/llama_index/issues/12259">#12259</a>)</li> </ul> <h3><code>llama-index-readers-google</code> [0.2.1]</h3> <ul> <li>Support for different drives (<a href="https://redirect.github.com/run-llama/llama_index/issues/12146">#12146</a>)</li> <li>Remove unnecessary PyDrive dependency from Google Drive Reader (<a href="https://redirect.github.com/run-llama/llama_index/issues/12257">#12257</a>)</li> </ul> <h3><code>llama-index-readers-readme</code> [0.1.0]</h3> <ul> <li>added readme.com reader (<a href="https://redirect.github.com/run-llama/llama_index/issues/12246">#12246</a>)</li> </ul> <h3><code>llama-index-packs-raft</code> [0.1.3]</h3> <ul> <li>added pack for RAFT (<a href="https://redirect.github.com/run-llama/llama_index/issues/12275">#12275</a>)</li> </ul> <h2>[2024-03-23]</h2> <h3><code>llama-index-core</code> [0.10.23]</h3> <ul> <li>Added <code>(a)predict_and_call()</code> function to base LLM class + openai + mistralai (<a href="https://redirect.github.com/run-llama/llama_index/issues/12188">#12188</a>)</li> <li>fixed bug with <code>wait()</code> in async agent streaming (<a href="https://redirect.github.com/run-llama/llama_index/issues/12187">#12187</a>)</li> </ul> <h3><code>llama-index-embeddings-alephalpha</code> [0.1.0]</h3> <ul> <li>Added alephalpha embeddings (<a href="https://redirect.github.com/run-llama/llama_index/issues/12149">#12149</a>)</li> </ul> <!-- raw HTML omitted --> </blockquote> <p>... (truncated)</p> </details> <details> <summary>Commits</summary> <ul> <li><a href="https://github.com/run-llama/llama_index/commit/3d3a8b9608af9f7aea30bcd9e115dcf37379a5d6"><code>3d3a8b9</code></a> v0.10.24 (<a href="https://redirect.github.com/run-llama/llama_index/issues/12291">#12291</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/178e0684ebad203dcc004148daac7c87c6a9d82e"><code>178e068</code></a> Add class name method (<a href="https://redirect.github.com/run-llama/llama_index/issues/12290">#12290</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/070104d0bd81e2cc2b91d7d3e7d490488cc7a195"><code>070104d</code></a> Small fixes to instrumentation (<a href="https://redirect.github.com/run-llama/llama_index/issues/12287">#12287</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/53c33e18b74dd842207fae0edf72d49308ba8148"><code>53c33e1</code></a> Make Google Drive Reader serializable (<a href="https://redirect.github.com/run-llama/llama_index/issues/12286">#12286</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/f30d024a2e1f40be896325552287841c91d0959a"><code>f30d024</code></a> Bump langchain-core from 0.1.30 to 0.1.34 in /llama-index-core (<a href="https://redirect.github.com/run-llama/llama_index/issues/12289">#12289</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/d3de336e6f665266f9c5e7241e0d7fa23a2c9408"><code>d3de336</code></a> [enhancement] Core callback handlers: Allow people to print with loggers -- m...</li> <li><a href="https://github.com/run-llama/llama_index/commit/c5bd9ed4280cc5c7c147bd3c730630b282fc0810"><code>c5bd9ed</code></a> Added support for different drives (<a href="https://redirect.github.com/run-llama/llama_index/issues/12146">#12146</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/2c92e88838a5f481d50840240b1dd3180066c6f5"><code>2c92e88</code></a> stricter access to builting in pandas query engine (<a href="https://redirect.github.com/run-llama/llama_index/issues/12278">#12278</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/6882171a95db8dbaa65295c5b750d08cda970db4"><code>6882171</code></a> Add new reader for GCS (<a href="https://redirect.github.com/run-llama/llama_index/issues/12259">#12259</a>)</li> <li><a href="https://github.com/run-llama/llama_index/commit/20724b0819974234987d30f83774ecbaee5cd27d"><code>20724b0</code></a> fix(core): delete the metadata with the wrong key when delete ref doc… (<a href="https://redirect.github.com/run-llama/llama_index/issues/12276">#12276</a>)</li> <li>Additional commits viewable in <a href="https://github.com/run-llama/llama_index/compare/v0.10.12...v0.10.24">compare view</a></li> </ul> </details> <br /> [![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=llama-index-core&package-manager=pip&previous-version=0.10.12&new-version=0.10.24)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) --- <details> <summary>Dependabot commands and options</summary> <br /> You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/run-llama/llama_index/network/alerts). </details>
https://api.github.com/repos/run-llama/llama_index/pulls/12730
2024-04-10T22:25:48Z
2024-04-11T00:51:07Z
2024-04-11T00:51:06Z
2024-04-11T00:51:07Z
831
run-llama/llama_index
6,282
Add LeetCode
diff --git a/data.json b/data.json index 199e56c5d..1dc39f80c 100644 --- a/data.json +++ b/data.json @@ -643,6 +643,14 @@ "username_claimed": "blue", "username_unclaimed": "noonewouldeverusethis7" }, + "LeetCode": { + "errorType": "status_code", + "rank": 0, + "url": "https://leetcode.com/{}", + "urlMain": "https://leetcode.com/", + "username_claimed": "blue", + "username_unclaimed": "noonewouldeverusethis7" + }, "Letterboxd": { "errorMsg": "Sorry, we can\u2019t find the page you\u2019ve requested.", "errorType": "message",
Add support for [LeetCode](https://leetcode.com/) Best regards
https://api.github.com/repos/sherlock-project/sherlock/pulls/240
2019-07-14T07:44:31Z
2019-07-14T07:54:09Z
2019-07-14T07:54:09Z
2019-07-14T07:54:10Z
198
sherlock-project/sherlock
36,422
Add LCEL to output parser doc
diff --git a/docs/docs/modules/model_io/output_parsers/index.ipynb b/docs/docs/modules/model_io/output_parsers/index.ipynb new file mode 100644 index 00000000000000..8e445eb08c48e6 --- /dev/null +++ b/docs/docs/modules/model_io/output_parsers/index.ipynb @@ -0,0 +1,259 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "38831021-76ed-48b3-9f62-d1241a68b6ad", + "metadata": {}, + "source": [ + "---\n", + "sidebar_position: 2\n", + "title: Output parsers\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a745f98b-c495-44f6-a882-757c38992d76", + "metadata": {}, + "source": [ + "Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.\n", + "\n", + "Output parsers are classes that help structure language model responses. There are two main methods an output parser must implement:\n", + "\n", + "- \"Get format instructions\": A method which returns a string containing instructions for how the output of a language model should be formatted.\n", + "- \"Parse\": A method which takes in a string (assumed to be the response from a language model) and parses it into some structure.\n", + "\n", + "And then one optional one:\n", + "\n", + "- \"Parse with prompt\": A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so.\n", + "\n", + "## Get started\n", + "\n", + "Below we go over the main type of output parser, the `PydanticOutputParser`." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "1594b2bf-2a6f-47bb-9a81-38930f8e606b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from typing import List\n", + "\n", + "from langchain.llms import OpenAI\n", + "from langchain.output_parsers import PydanticOutputParser\n", + "from langchain.prompts import PromptTemplate\n", + "from langchain.pydantic_v1 import BaseModel, Field, validator\n", + "\n", + "\n", + "model = OpenAI(model_name='text-davinci-003', temperature=0.0)\n", + "\n", + "# Define your desired data structure.\n", + "class Joke(BaseModel):\n", + " setup: str = Field(description=\"question to set up a joke\")\n", + " punchline: str = Field(description=\"answer to resolve the joke\")\n", + "\n", + " # You can add custom validation logic easily with Pydantic.\n", + " @validator('setup')\n", + " def question_ends_with_question_mark(cls, field):\n", + " if field[-1] != '?':\n", + " raise ValueError(\"Badly formed question!\")\n", + " return field\n", + "\n", + "# Set up a parser + inject instructions into the prompt template.\n", + "parser = PydanticOutputParser(pydantic_object=Joke)\n", + "\n", + "prompt = PromptTemplate(\n", + " template=\"Answer the user query.\\n{format_instructions}\\n{query}\\n\",\n", + " input_variables=[\"query\"],\n", + " partial_variables={\"format_instructions\": parser.get_format_instructions()}\n", + ")\n", + "\n", + "# And a query intended to prompt a language model to populate the data structure.\n", + "prompt_and_model = prompt | model\n", + "output = prompt_and_model.invoke({\"query\": \"Tell me a joke.\"})\n", + "parser.invoke(output)" + ] + }, + { + "cell_type": "markdown", + "id": "75976cd6-78e2-458b-821f-3ddf3683466b", + "metadata": {}, + "source": [ + "## LCEL\n", + "\n", + "Output parsers implement the [Runnable interface](/docs/expression_language/interface), the basic building block of the [LangChain Expression Language (LCEL)](/docs/expression_language/). This means they support `invoke`, `ainvoke`, `stream`, `astream`, `batch`, `abatch`, `astream_log` calls.\n", + "\n", + "Output parsers accept a string or `BaseMessage` as input and can return an arbitrary type." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "34f7ff0c-8443-4eb9-8704-b4f821811d93", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "parser.invoke(output)" + ] + }, + { + "cell_type": "markdown", + "id": "bdebf4a5-57a8-4632-bd17-56723d431cf1", + "metadata": {}, + "source": [ + "Instead of manually invoking the parser, we also could've just added it to our `Runnable` sequence:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "51f7fff5-e9bd-49a1-b5ab-b9ff281b93cb", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "chain = prompt | model | parser\n", + "chain.invoke({\"query\": \"Tell me a joke.\"})" + ] + }, + { + "cell_type": "markdown", + "id": "d88590a0-f36b-4ad5-8a56-d300971a6440", + "metadata": {}, + "source": [ + "While all parsers support the streaming interface, only certain parsers can stream through partially parsed objects, since this is highly dependent on the output type. Parsers which cannot construct partial objects will simply yield the fully parsed output.\n", + "\n", + "The `SimpleJsonOutputParser` for example can stream through partial outputs:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "d7ecfe4d-dae8-4452-98ea-e48bdc498788", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.output_parsers.json import SimpleJsonOutputParser\n", + "\n", + "json_prompt = PromptTemplate.from_template(\"Return a JSON object with an `answer` key that answers the following question: {question}\")\n", + "json_parser = SimpleJsonOutputParser()\n", + "json_chain = json_prompt | model | json_parser" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "cc2b999e-47aa-41f4-ba6a-13b20a204576", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[{},\n", + " {'answer': ''},\n", + " {'answer': 'Ant'},\n", + " {'answer': 'Anton'},\n", + " {'answer': 'Antonie'},\n", + " {'answer': 'Antonie van'},\n", + " {'answer': 'Antonie van Lee'},\n", + " {'answer': 'Antonie van Leeu'},\n", + " {'answer': 'Antonie van Leeuwen'},\n", + " {'answer': 'Antonie van Leeuwenho'},\n", + " {'answer': 'Antonie van Leeuwenhoek'}]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(json_chain.stream({\"question\": \"Who invented the microscope?\"}))" + ] + }, + { + "cell_type": "markdown", + "id": "3ca23082-c602-4ee8-af8c-a185b1f42bd1", + "metadata": {}, + "source": [ + "While the PydanticOutputParser cannot:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "07420e8f-e144-42aa-93ac-de890b6222f5", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(chain.stream({\"query\": \"Tell me a joke.\"}))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "poetry-venv", + "language": "python", + "name": "poetry-venv" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/docs/modules/model_io/output_parsers/index.mdx b/docs/docs/modules/model_io/output_parsers/index.mdx deleted file mode 100644 index 0c5461851713a3..00000000000000 --- a/docs/docs/modules/model_io/output_parsers/index.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -sidebar_position: 2 ---- -# Output parsers - -Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in. - -Output parsers are classes that help structure language model responses. There are two main methods an output parser must implement: - -- "Get format instructions": A method which returns a string containing instructions for how the output of a language model should be formatted. -- "Parse": A method which takes in a string (assumed to be the response from a language model) and parses it into some structure. - -And then one optional one: - -- "Parse with prompt": A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. - -## Get started - -Below we go over the main type of output parser, the `PydanticOutputParser`. - -```python -from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate -from langchain.llms import OpenAI -from langchain.chat_models import ChatOpenAI - -from langchain.output_parsers import PydanticOutputParser -from pydantic import BaseModel, Field, validator -from typing import List -``` - - -```python -model_name = 'text-davinci-003' -temperature = 0.0 -model = OpenAI(model_name=model_name, temperature=temperature) -``` - - -```python -# Define your desired data structure. -class Joke(BaseModel): - setup: str = Field(description="question to set up a joke") - punchline: str = Field(description="answer to resolve the joke") - - # You can add custom validation logic easily with Pydantic. - @validator('setup') - def question_ends_with_question_mark(cls, field): - if field[-1] != '?': - raise ValueError("Badly formed question!") - return field -``` - - -```python -# Set up a parser + inject instructions into the prompt template. -parser = PydanticOutputParser(pydantic_object=Joke) -``` - - -```python -prompt = PromptTemplate( - template="Answer the user query.\n{format_instructions}\n{query}\n", - input_variables=["query"], - partial_variables={"format_instructions": parser.get_format_instructions()} -) -``` - - -```python -# And a query intended to prompt a language model to populate the data structure. -joke_query = "Tell me a joke." -_input = prompt.format_prompt(query=joke_query) -``` - - -```python -output = model(_input.to_string()) -``` - - -```python -parser.parse(output) -``` - -<CodeOutputBlock lang="python"> - -``` - Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!') -``` - -</CodeOutputBlock>
https://api.github.com/repos/langchain-ai/langchain/pulls/11880
2023-10-16T19:06:33Z
2023-10-16T19:35:18Z
2023-10-16T19:35:18Z
2023-10-16T19:35:19Z
3,518
langchain-ai/langchain
43,676
Add PatentsView API
diff --git a/README.md b/README.md index aa684c5568..2ea0e66051 100644 --- a/README.md +++ b/README.md @@ -992,6 +992,7 @@ API | Description | Auth | HTTPS | CORS | API | Description | Auth | HTTPS | CORS | |---|---|---|---|---| | [EPO](https://developers.epo.org/) | European patent search system api | `OAuth` | Yes | Unknown | +| [PatentsView ](https://patentsview.org/apis/purpose) | API is intended to explore and visualize trends/patterns across the US innovation landscape | No | Yes | Unknown | | [TIPO](https://tiponet.tipo.gov.tw/Gazette/OpenData/OD/OD05.aspx?QryDS=API00) | Taiwan patent search system api | `apiKey` | Yes | Unknown | | [USPTO](https://www.uspto.gov/learning-and-resources/open-data-and-mobility) | USA patent api services | No | Yes | Unknown |
<!-- Thank you for taking the time to work on a Pull Request for this project! --> <!-- To ensure your PR is dealt with swiftly please check the following: --> - [✔] My submission is formatted according to the guidelines in the [contributing guide](/CONTRIBUTING.md) - [✔] My addition is ordered alphabetically - [✔] My submission has a useful description - [✔] The description does not have more than 100 characters - [✔] The description does not end with punctuation - [✔] Each table column is padded with one space on either side - [✔] I have searched the repository for any relevant issues or pull requests - [✔] Any category I am creating has the minimum requirement of 3 items - [✔] All changes have been [squashed][squash-link] into a single commit [squash-link]: <https://github.com/todotxt/todo.txt-android/wiki/Squash-All-Commits-Related-to-a-Single-Issue-into-a-Single-Commit>
https://api.github.com/repos/public-apis/public-apis/pulls/2489
2021-10-11T13:47:26Z
2021-10-24T21:10:16Z
2021-10-24T21:10:16Z
2021-10-25T08:41:50Z
234
public-apis/public-apis
35,628
Fixed #30259 -- Fixed crash of admin views when properties don't have admin_order_field attribute.
diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index fe4249ae5b16b..4fd9c45a57353 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -130,7 +130,7 @@ def result_headers(cl): admin_order_field = getattr(attr, "admin_order_field", None) # Set ordering for attr that is a property, if defined. if isinstance(attr, property) and hasattr(attr, 'fget'): - admin_order_field = getattr(attr.fget, 'admin_order_field') + admin_order_field = getattr(attr.fget, 'admin_order_field', None) if not admin_order_field: is_field_sortable = False diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 3e8df5b7c2c28..8f0aaf843f3c7 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -104,7 +104,7 @@ class ArticleAdmin(admin.ModelAdmin): list_display = ( 'content', 'date', callable_year, 'model_year', 'modeladmin_year', 'model_year_reversed', 'section', lambda obj: obj.title, - 'order_by_expression', 'model_property_year', + 'order_by_expression', 'model_property_year', 'model_month', ) list_editable = ('section',) list_filter = ('date', 'section') diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index aaf86ea1cde59..9ac3c53bab531 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -60,6 +60,10 @@ def property_year(self): property_year.admin_order_field = 'date' model_property_year = property(property_year) + @property + def model_month(self): + return self.date.month + class Book(models.Model): """
Ticket [30259](https://code.djangoproject.com/ticket/30259). I didn't add a separate test because the original test `test_change_list_sorting_property()` is falling after adding a property to the list of fields.
https://api.github.com/repos/django/django/pulls/11154
2019-04-01T08:38:56Z
2019-04-01T13:11:55Z
2019-04-01T13:11:55Z
2019-04-01T14:35:55Z
475
django/django
51,397
fix: Do not call lastEventId
diff --git a/src/sentry/static/sentry/app/utils/sdk.js b/src/sentry/static/sentry/app/utils/sdk.js index 4681c35e23e9e3..c0baa857807124 100644 --- a/src/sentry/static/sentry/app/utils/sdk.js +++ b/src/sentry/static/sentry/app/utils/sdk.js @@ -58,7 +58,7 @@ document.addEventListener('sentryLoaded', function() { }; _lastEventId = () => { // TODO: eventually implement this - window.Sentry.lastEventId('Would have called lastEventId()'); + window.Sentry.captureMessage('Would have called lastEventId()'); }; });
https://api.github.com/repos/getsentry/sentry/pulls/9046
2018-07-16T08:30:45Z
2018-07-17T11:32:19Z
2018-07-17T11:32:19Z
2020-12-21T18:13:15Z
153
getsentry/sentry
44,392
Refs #31169 -- Added DatabaseCreation.setup_worker_connection() hook.
diff --git a/django/db/backends/base/creation.py b/django/db/backends/base/creation.py index 78480fc0f8c88..15c2167be4bf3 100644 --- a/django/db/backends/base/creation.py +++ b/django/db/backends/base/creation.py @@ -369,3 +369,13 @@ def test_db_signature(self): settings_dict["ENGINE"], self._get_test_db_name(), ) + + def setup_worker_connection(self, _worker_id): + settings_dict = self.get_test_db_clone_settings(str(_worker_id)) + # connection.settings_dict must be updated in place for changes to be + # reflected in django.db.connections. If the following line assigned + # connection.settings_dict = settings_dict, new threads would connect + # to the default database instead of the appropriate clone. + self.connection.settings_dict.update(settings_dict) + self.mark_expected_failures_and_skips() + self.connection.close() diff --git a/django/test/runner.py b/django/test/runner.py index 113d5216a6521..aba515e73512c 100644 --- a/django/test/runner.py +++ b/django/test/runner.py @@ -407,13 +407,7 @@ def _init_worker(counter): for alias in connections: connection = connections[alias] - settings_dict = connection.creation.get_test_db_clone_settings(str(_worker_id)) - # connection.settings_dict must be updated in place for changes to be - # reflected in django.db.connections. If the following line assigned - # connection.settings_dict = settings_dict, new threads would connect - # to the default database instead of the appropriate clone. - connection.settings_dict.update(settings_dict) - connection.close() + connection.creation.setup_worker_connection(_worker_id) def _run_subsuite(args):
https://api.github.com/repos/django/django/pulls/15457
2022-02-23T10:36:58Z
2022-02-23T11:16:42Z
2022-02-23T11:16:42Z
2022-02-23T11:16:55Z
414
django/django
51,544
Fixed #2250
diff --git a/requests/utils.py b/requests/utils.py index 1868f861ba..182348daad 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -567,7 +567,7 @@ def parse_header_links(value): replace_chars = " '\"" - for val in value.split(","): + for val in re.split(", *<", value): try: url, params = val.split(";", 1) except ValueError:
Fixed #2250 with #2271
https://api.github.com/repos/psf/requests/pulls/2271
2014-10-09T02:28:13Z
2014-10-10T18:30:18Z
2014-10-10T18:30:18Z
2021-09-08T10:01:06Z
111
psf/requests
32,552
Update README.md
diff --git a/Server Side Template Injection/README.md b/Server Side Template Injection/README.md index 656dc05b54..6018c46301 100644 --- a/Server Side Template Injection/README.md +++ b/Server Side Template Injection/README.md @@ -199,7 +199,11 @@ You can try your payloads at [https://try.freemarker.apache.org](https://try.fre ### Freemarker - Basic injection -The template can be `${3*3}` or the legacy `#{3*3}`. +The template can be : + +* Default: `${3*3}` +* Legacy: `#{3*3}` +* Alternative: `[=3*3]` since [FreeMarker 2.3.4](https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html) ### Freemarker - Read File @@ -214,6 +218,8 @@ Convert the returned bytes to ASCII <#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")} [#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')} ${"freemarker.template.utility.Execute"?new()("id")} +#{"freemarker.template.utility.Execute"?new()("id")} +[="freemarker.template.utility.Execute"?new()("id")] ``` ### Freemarker - Sandbox bypass
Add some efficient but new payloads in freemaker
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/608
2022-12-27T10:35:59Z
2022-12-27T17:26:52Z
2022-12-27T17:26:52Z
2022-12-27T17:26:52Z
299
swisskyrepo/PayloadsAllTheThings
8,639
Highlight -o/--options
diff --git a/httpie/output/ui/rich_help.py b/httpie/output/ui/rich_help.py index c897a51e75..57cda0e961 100644 --- a/httpie/output/ui/rich_help.py +++ b/httpie/output/ui/rich_help.py @@ -29,17 +29,19 @@ LEFT_PADDING_4 = (0, 0, 0, 4) -class RequestItemHighlighter(RegexHighlighter): +class OptionsHighlighter(RegexHighlighter): highlights = [ - rf'(?P<key>\w+)(?P<sep>({SEPARATORS}))(?P<value>.+)', + r"(^|\W)(?P<option>\-{1,2}[\w|-]+)(?![a-zA-Z0-9])" ] -request_item_highlighter = RequestItemHighlighter() +options_highlighter = OptionsHighlighter() def unpack_argument(argument: Argument) -> Tuple[Text, Text]: opt1 = opt2 = '' + + style = None if argument.aliases: if len(argument.aliases) >= 2: opt2, opt1 = argument.aliases @@ -47,8 +49,9 @@ def unpack_argument(argument: Argument) -> Tuple[Text, Text]: (opt1,) = argument.aliases else: opt1 = argument.metavar + style = STYLE_USAGE_REGULAR - return Text(opt1), Text(opt2) + return Text(opt1, style=style), Text(opt2) def to_usage( @@ -142,16 +145,16 @@ def to_help_message(spec: ParserSpec) -> Iterable[RenderableType]: desc += ')' rows = [ - Padding(opt1, LEFT_PADDING_2), + Padding(options_highlighter(opt1), LEFT_PADDING_2), metavar, - desc, + options_highlighter(desc), ] options_rows.append(rows) if argument.configuration.get('nested_options'): options_rows.extend( [ - (Padding(key, LEFT_PADDING_4), value, dec) + (Padding(Text(key, style=STYLE_USAGE_OPTIONAL), LEFT_PADDING_4), value, dec) for key, value, dec in argument.nested_options ] ) diff --git a/httpie/output/ui/rich_palette.py b/httpie/output/ui/rich_palette.py index eb7de95f64..c3b6b424bb 100644 --- a/httpie/output/ui/rich_palette.py +++ b/httpie/output/ui/rich_palette.py @@ -11,6 +11,7 @@ 'bar.complete': 'purple', 'bar.finished': 'green', 'bar.pulse': 'purple', + 'option': 'pink' } RICH_THEME_PALETTE = COLOR_PALETTE.copy() # noqa diff --git a/httpie/output/ui/rich_utils.py b/httpie/output/ui/rich_utils.py index 7907cf7fb7..82567ba571 100644 --- a/httpie/output/ui/rich_utils.py +++ b/httpie/output/ui/rich_utils.py @@ -1,6 +1,10 @@ import os +from typing import Iterator +from contextlib import contextmanager + from rich.console import Console, RenderableType +from rich.highlighter import Highlighter def render_as_string(renderable: RenderableType) -> str: @@ -10,8 +14,22 @@ def render_as_string(renderable: RenderableType) -> str: with open(os.devnull, "w") as null_stream: fake_console = Console( file=null_stream, - stderr=null_stream, record=True ) fake_console.print(renderable) return fake_console.export_text() + + +@contextmanager +def enable_highlighter( + console: Console, + highlighter: Highlighter, +) -> Iterator[Console]: + """Enable a higlighter temporarily.""" + + original_highlighter = console.highlighter + try: + console.highlighter = highlighter + yield console + finally: + console.highlighter = original_highlighter
![image](https://user-images.githubusercontent.com/47358913/161071162-df45941e-eb29-4a01-a019-6abded903b1f.png)
https://api.github.com/repos/httpie/cli/pulls/1340
2022-03-31T13:50:33Z
2022-03-31T13:50:40Z
2022-03-31T13:50:40Z
2022-03-31T13:50:40Z
903
httpie/cli
33,824
fix(ui): Fix releases + issues pagination
diff --git a/static/app/components/asyncComponent.tsx b/static/app/components/asyncComponent.tsx index 4ed9632eade038..5bc0a8151714b2 100644 --- a/static/app/components/asyncComponent.tsx +++ b/static/app/components/asyncComponent.tsx @@ -247,7 +247,7 @@ export default class AsyncComponent< let query = (params && params.query) || {}; // If paginate option then pass entire `query` object to API call // It should only be expecting `query.cursor` for pagination - if (options.paginate || locationQuery.cursor) { + if ((options.paginate || locationQuery.cursor) && !options.disableEntireQuery) { query = {...locationQuery, ...query}; } diff --git a/static/app/components/issues/groupList.tsx b/static/app/components/issues/groupList.tsx index f366cfe2cf30c5..45589fd06f43dd 100644 --- a/static/app/components/issues/groupList.tsx +++ b/static/app/components/issues/groupList.tsx @@ -154,7 +154,7 @@ class GroupList extends React.Component<Props, State> { } handleCursorChange( - cursor: string, + cursor: string | undefined, path: string, query: Record<string, any>, pageDiff: number @@ -163,19 +163,18 @@ class GroupList extends React.Component<Props, State> { let nextPage: number | undefined = isNaN(queryPageInt) ? pageDiff : queryPageInt + pageDiff; - let nextCursor: string | undefined = cursor; // unset cursor and page when we navigate back to the first page // also reset cursor if somehow the previous button is enabled on // first page and user attempts to go backwards if (nextPage <= 0) { - nextCursor = undefined; + cursor = undefined; nextPage = undefined; } browserHistory.push({ pathname: path, - query: {...query, cursor: nextCursor}, + query: {...query, cursor, page: nextPage}, }); } diff --git a/static/app/views/releases/list/index.tsx b/static/app/views/releases/list/index.tsx index 5ebe322843c18a..94a507f4b8f005 100644 --- a/static/app/views/releases/list/index.tsx +++ b/static/app/views/releases/list/index.tsx @@ -85,7 +85,12 @@ class ReleasesList extends AsyncView<Props, State> { }; const endpoints: ReturnType<AsyncView['getEndpoints']> = [ - ['releases', `/organizations/${organization.slug}/releases/`, {query}], + [ + 'releases', + `/organizations/${organization.slug}/releases/`, + {query}, + {disableEntireQuery: true}, + ], ]; return endpoints;
- fixes pagination of issues on release detail page - fixes pagination on releases page when the statsPeriod is different than 14d (https://app.asana.com/0/1168903747282474/1192198721871433/f)
https://api.github.com/repos/getsentry/sentry/pulls/26707
2021-06-18T08:45:53Z
2021-06-21T08:38:22Z
2021-06-21T08:38:22Z
2022-05-09T11:42:51Z
643
getsentry/sentry
44,743
community: add len() implementation to Chroma
diff --git a/libs/community/langchain_community/vectorstores/chroma.py b/libs/community/langchain_community/vectorstores/chroma.py index 3bcb389cff5e10..7723285fafa6c7 100644 --- a/libs/community/langchain_community/vectorstores/chroma.py +++ b/libs/community/langchain_community/vectorstores/chroma.py @@ -795,3 +795,7 @@ def delete(self, ids: Optional[List[str]] = None, **kwargs: Any) -> None: ids: List of ids to delete. """ self._collection.delete(ids=ids) + + def __len__(self) -> int: + """Count the number of documents in the collection.""" + return self._collection.count() diff --git a/libs/community/tests/integration_tests/vectorstores/test_chroma.py b/libs/community/tests/integration_tests/vectorstores/test_chroma.py index 58e9bcf454e93a..0a0cf529d08e63 100644 --- a/libs/community/tests/integration_tests/vectorstores/test_chroma.py +++ b/libs/community/tests/integration_tests/vectorstores/test_chroma.py @@ -21,6 +21,7 @@ def test_chroma() -> None: ) output = docsearch.similarity_search("foo", k=1) assert output == [Document(page_content="foo")] + assert len(docsearch) == 3 async def test_chroma_async() -> None:
Thank you for contributing to LangChain! - [x] **Add len() implementation to Chroma**: "package: community" - [x] **PR message**: - **Description:** add an implementation of the __len__() method for the Chroma vectostore, for convenience. - **Issue:** no exposed method to know the size of a Chroma vectorstore - **Dependencies:** None - **Twitter handle:** lowrank_adrian - [x] **Add tests and docs** - [x] **Lint and test**
https://api.github.com/repos/langchain-ai/langchain/pulls/19419
2024-03-22T00:02:58Z
2024-03-26T16:53:11Z
2024-03-26T16:53:11Z
2024-03-26T16:53:11Z
312
langchain-ai/langchain
43,289
Create karatsuba.py
diff --git a/maths/karatsuba.py b/maths/karatsuba.py new file mode 100644 index 000000000000..be4630184933 --- /dev/null +++ b/maths/karatsuba.py @@ -0,0 +1,31 @@ +""" Multiply two numbers using Karatsuba algorithm """ + +def karatsuba(a, b): + """ + >>> karatsuba(15463, 23489) == 15463 * 23489 + True + >>> karatsuba(3, 9) == 3 * 9 + True + """ + if len(str(a)) == 1 or len(str(b)) == 1: + return (a * b) + else: + m1 = max(len(str(a)), len(str(b))) + m2 = m1 // 2 + + a1, a2 = divmod(a, 10**m2) + b1, b2 = divmod(b, 10**m2) + + x = karatsuba(a2, b2) + y = karatsuba((a1 + a2), (b1 + b2)) + z = karatsuba(a1, b1) + + return ((z * 10**(2*m2)) + ((y - z - x) * 10**(m2)) + (x)) + + +def main(): + print(karatsuba(15463, 23489)) + + +if __name__ == "__main__": + main()
Added karatsuba algorithm for multiplication of two numbers
https://api.github.com/repos/TheAlgorithms/Python/pulls/1309
2019-10-08T10:20:40Z
2019-10-08T12:25:51Z
2019-10-08T12:25:51Z
2019-10-08T12:25:51Z
353
TheAlgorithms/Python
30,263
fix: check fill size none zero when resize (fixes #11425)
diff --git a/modules/images.py b/modules/images.py index 7bbfc3e0b10..7935b122a2d 100644 --- a/modules/images.py +++ b/modules/images.py @@ -302,12 +302,14 @@ def resize(im, w, h): if ratio < src_ratio: fill_height = height // 2 - src_h // 2 - res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0)) - res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h)) + if fill_height > 0: + res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0)) + res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h)) elif ratio > src_ratio: fill_width = width // 2 - src_w // 2 - res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0)) - res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0)) + if fill_width > 0: + res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0)) + res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0)) return res
## Description * a simple description of what you're trying to accomplish * a summary of changes in code * which issues it fixes, if any ## Screenshots/videos: ## Checklist: - [x] I have read [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) - [x] I have performed a self-review of my own code - [x] My code follows the [style guidelines](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing#code-style) - [x] My code passes [tests](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Tests)
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/11748
2023-07-12T08:55:02Z
2023-07-13T11:48:20Z
2023-07-13T11:48:20Z
2023-07-13T11:48:20Z
416
AUTOMATIC1111/stable-diffusion-webui
39,997
Updating the readme.md to make it easier to follow
diff --git a/README.md b/README.md index 5978a0e5dd7c55..523f459f3b7dc4 100644 --- a/README.md +++ b/README.md @@ -39,13 +39,17 @@ Running on a dedicated device in a car ------ To use openpilot in a car, you need four things -* A supported device to run this software: a [comma 3X](https://comma.ai/shop/comma-3x) or comma three. -* This software. The setup procedure of the comma 3/3X allows the user to enter a URL for custom software. -The URL, openpilot.comma.ai will install the release version of openpilot. To install openpilot master, you can use installer.comma.ai/commaai/master, and replacing commaai with another GitHub username can install a fork. -* One of [the 250+ supported cars](docs/CARS.md). We support Honda, Toyota, Hyundai, Nissan, Kia, Chrysler, Lexus, Acura, Audi, VW, Ford and more. If your car is not supported but has adaptive cruise control and lane-keeping assist, it's likely able to run openpilot. -* A [car harness](https://comma.ai/shop/products/car-harness) to connect to your car. - -We have detailed instructions for [how to mount the device in a car](https://comma.ai/setup). +1. **Supported Device:** A comma 3/3X. You can purchase these devices from (https://comma.ai/shop/comma-3x) + +2. **Software:** The setup procedure for the comma 3/3X allows users to enter a URL for custom software. + To install the release version of openpilot, use the URL `openpilot.comma.ai`. + To install openpilot master (for more advanced users), use the URL `installer.comma.ai/commaai/master`. You can replace "commaai" with another GitHub username to install a fork. + +3. **Supported Car:** Ensure that you have one of [the 250+ supported cars](docs/CARS.md). openpilot supports a wide range of car makes including Honda, Toyota, Hyundai, Nissan, Kia, Chrysler, Lexus, Acura, Audi, VW, Ford, and many more. + If your car is not officially listed as supported but has adaptive cruise control and lane-keeping assist, it's likely capable of running openpilot. + +4. **Car Harness:** You will also need a [car harness](https://comma.ai/shop/car-harness) to connect your comma 3/3X to your car. + We have detailed instructions for [how to install the harness and device in a car](https://comma.ai/setup). Running on PC ------
<!-- Please copy and paste the relevant template --> <!--- ***** Template: Car bug fix ***** **Description** [](A description of the bug and the fix. Also link any relevant issues.) **Verification** [](Explain how you tested this bug fix.) **Route** Route: [a route with the bug fix] --> <!--- ***** Template: Bug fix ***** **Description** [](A description of the bug and the fix. Also link any relevant issues.) **Verification** [](Explain how you tested this bug fix.) --> <!--- ***** Template: Car port ***** **Checklist** - [ ] added entry to CarInfo in selfdrive/car/*/values.py and ran `selfdrive/car/docs.py` to generate new docs - [ ] test route added to [routes.py](https://github.com/commaai/openpilot/blob/master/selfdrive/car/tests/routes.py) - [ ] route with openpilot: - [ ] route with stock system: --> <!--- ***** Template: Refactor ***** **Description** [](A description of the refactor, including the goals it accomplishes.) **Verification** [](Explain how you tested the refactor for regressions.) -->
https://api.github.com/repos/commaai/openpilot/pulls/29820
2023-09-07T20:23:22Z
2023-09-12T18:38:29Z
2023-09-12T18:38:29Z
2023-09-12T18:38:29Z
607
commaai/openpilot
9,228
Explicitly use event timestamp when recording data in similarity index.
diff --git a/src/sentry/similarity.py b/src/sentry/similarity.py index f59889b5174cb..65ad43ee14c11 100644 --- a/src/sentry/similarity.py +++ b/src/sentry/similarity.py @@ -12,6 +12,7 @@ from sentry.utils import redis from sentry.utils.datastructures import BidirectionalMapping +from sentry.utils.dates import to_timestamp from sentry.utils.iterators import shingle from sentry.utils.redis import load_script @@ -299,6 +300,7 @@ def record(self, event): '{}'.format(event.project_id), '{}'.format(event.group_id), items, + timestamp=to_timestamp(event.datetime), ) def query(self, group):
https://api.github.com/repos/getsentry/sentry/pulls/5071
2017-03-13T19:59:45Z
2017-03-13T20:10:58Z
2017-03-13T20:10:58Z
2020-12-23T04:40:49Z
174
getsentry/sentry
44,769
[AIRFLOW-6686] Fix syntax error constructing list of process ids
diff --git a/airflow/utils/helpers.py b/airflow/utils/helpers.py index 35da593c79c17..1f57f0b746cbe 100644 --- a/airflow/utils/helpers.py +++ b/airflow/utils/helpers.py @@ -211,7 +211,7 @@ def signal_procs(sig): # use sudo -n(--non-interactive) to kill the process if err.errno == errno.EPERM: subprocess.check_call( - ["sudo", "-n", "kill", "-" + str(sig)] + map(children, lambda p: str(p.pid)) + ["sudo", "-n", "kill", "-" + str(sig)] + [str(p.pid) for p in children] ) else: raise
Construction of list of pids passed in kill command raises a Syntax error because ordering of the arguments to `map` function doesn't conform to function parameter definition. A list comprehension replaces the existing `map` function to make the code forward compatible with Python 3 and at the same time expand to a list of pids. --- Issue link: [AIRFLOW-6686](https://issues.apache.org/jira/browse/AIRFLOW-6686) Make sure to mark the boxes below before creating PR: [x] - [x] Description above provides context of the change - [x] Commit message/PR title starts with `[AIRFLOW-NNNN]`. AIRFLOW-NNNN = JIRA ID<sup>*</sup> - [x] ~Unit tests coverage for changes (not needed for documentation changes)~ - [x] ~Commits follow "[How to write a good git commit message](http://chris.beams.io/posts/git-commit/)"~ - [x] ~Relevant documentation is updated including usage instructions.~ - [x] I will engage committers as explained in [Contribution Workflow Example](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#contribution-workflow-example). <sup>*</sup> For document-only changes commit message can start with `[AIRFLOW-XXXX]`. --- In case of fundamental code change, Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed. In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x). In case of backwards incompatible changes please leave a note in [UPDATING.md](https://github.com/apache/airflow/blob/master/UPDATING.md). Read the [Pull Request Guidelines](https://github.com/apache/airflow/blob/master/CONTRIBUTING.rst#pull-request-guidelines) for more information.
https://api.github.com/repos/apache/airflow/pulls/7298
2020-01-30T20:23:28Z
2020-02-02T16:31:58Z
2020-02-02T16:31:58Z
2020-02-02T16:31:58Z
169
apache/airflow
14,496
Only show gps event after 1 km
diff --git a/selfdrive/controls/controlsd.py b/selfdrive/controls/controlsd.py index c078b3c4b6c6f5..37b7e802d64eda 100755 --- a/selfdrive/controls/controlsd.py +++ b/selfdrive/controls/controlsd.py @@ -128,6 +128,7 @@ def __init__(self, sm=None, pm=None, can_sock=None): self.can_error_counter = 0 self.last_blinker_frame = 0 self.saturated_count = 0 + self.distance_traveled = 0 self.events_prev = [] self.current_alert_types = [] @@ -213,8 +214,9 @@ def update_events(self, CS): if not self.sm['liveLocationKalman'].inputsOK and os.getenv("NOSENSOR") is None: if self.sm.frame > 5 / DT_CTRL: # Give locationd some time to receive all the inputs self.events.add(EventName.sensorDataInvalid) - if not self.sm['liveLocationKalman'].gpsOK and os.getenv("NOSENSOR") is None: - self.events.add(EventName.noGps) + if not self.sm['liveLocationKalman'].gpsOK and (self.distance_traveled > 1000) and os.getenv("NOSENSOR") is None: + # Not show in first 1 km to allow for driving out of garage. This event shows after 5 minutes + self.events.add(EventName.noGps) if not self.sm['pathPlan'].paramsValid: self.events.add(EventName.vehicleModelInvalid) if not self.sm['liveLocationKalman'].posenetOK: @@ -259,6 +261,8 @@ def data_sample(self): if not self.sm['health'].controlsAllowed and self.enabled: self.mismatch_counter += 1 + self.distance_traveled += CS.vEgo * DT_CTRL + return CS def state_transition(self, CS):
Fixes #1745
https://api.github.com/repos/commaai/openpilot/pulls/1747
2020-06-19T20:51:19Z
2020-06-19T21:11:24Z
2020-06-19T21:11:23Z
2020-06-19T21:11:25Z
431
commaai/openpilot
9,330
Add string_rotation to create multiple words from single word
diff --git a/string_rotation.py b/string_rotation.py new file mode 100644 index 0000000000..a7928a1b07 --- /dev/null +++ b/string_rotation.py @@ -0,0 +1,20 @@ +def rotate(n): + a = list(n) + if len(a) == 0: + return print ([]) + l = [] + for i in range(1,len(a)+1): + a = [a[(i+1)%(len(a))] for i in range(0,len(a))] + l += ["".join(a)] + print(l) + +string = str(input()) +print("Your input is :" ,string) +print("The rotation is :") +rotate(string) + + +# Input : Python +# output : +# The rotation is : +# ['ythonp', 'thonpy', 'honpyt', 'onpyth', 'npytho', 'python']
https://api.github.com/repos/geekcomputers/Python/pulls/639
2019-10-20T16:47:58Z
2019-10-20T18:36:14Z
2019-10-20T18:36:14Z
2019-10-20T18:36:14Z
212
geekcomputers/Python
31,696
docs: fix simple typo, assigining -> assigning
diff --git a/patterns/creational/borg.py b/patterns/creational/borg.py index 3ddc8c1d..ab364f61 100644 --- a/patterns/creational/borg.py +++ b/patterns/creational/borg.py @@ -13,7 +13,7 @@ its own dictionary, but the Borg pattern modifies this so that all instances have the same dictionary. In this example, the __shared_state attribute will be the dictionary -shared between all instances, and this is ensured by assigining +shared between all instances, and this is ensured by assigning __shared_state to the __dict__ variable when initializing a new instance (i.e., in the __init__ method). Other attributes are usually added to the instance's attribute dictionary, but, since the attribute
There is a small typo in patterns/creational/borg.py. Should read `assigning` rather than `assigining`. Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md
https://api.github.com/repos/faif/python-patterns/pulls/394
2022-07-02T09:50:09Z
2022-07-04T19:27:22Z
2022-07-04T19:27:22Z
2022-07-04T19:27:22Z
183
faif/python-patterns
33,619
Validations for Events.CreateConnection
diff --git a/localstack/services/events/provider.py b/localstack/services/events/provider.py index 03484d8549ca1..c9fc1c6b18aed 100644 --- a/localstack/services/events/provider.py +++ b/localstack/services/events/provider.py @@ -11,8 +11,13 @@ from localstack import config from localstack.aws.api import RequestContext +from localstack.aws.api.core import CommonServiceException from localstack.aws.api.events import ( Boolean, + ConnectionAuthorizationType, + ConnectionDescription, + ConnectionName, + CreateConnectionAuthRequestParameters, EventBusNameOrArn, EventPattern, EventsApi, @@ -41,6 +46,7 @@ EVENTS_TMP_DIR = "cw_events" DEFAULT_EVENT_BUS_NAME = "default" CONTENT_BASE_FILTER_KEYWORDS = ["prefix", "anything-but", "numeric", "cidr", "exists"] +CONNECTION_NAME_PATTERN = re.compile("^[\\.\\-_A-Za-z0-9]+$") class EventsProvider(EventsApi): @@ -148,6 +154,37 @@ def disable_rule( JobScheduler.instance().disable_job(job_id=job_id) call_moto(context) + def create_connection( + self, + context: RequestContext, + name: ConnectionName, + authorization_type: ConnectionAuthorizationType, + auth_parameters: CreateConnectionAuthRequestParameters, + description: ConnectionDescription = None, + ): + errors = [] + + if not CONNECTION_NAME_PATTERN.match(name): + error = f"{name} at 'name' failed to satisfy: Member must satisfy regular expression pattern: [\\.\\-_A-Za-z0-9]+" + errors.append(error) + + if len(name) > 64: + error = f"{name} at 'name' failed to satisfy: Member must have length less than or equal to 64" + errors.append(error) + + if authorization_type not in ["BASIC", "API_KEY", "OAUTH_CLIENT_CREDENTIALS"]: + error = f"{authorization_type} at 'authorizationType' failed to satisfy: Member must satisfy enum value set: [BASIC, OAUTH_CLIENT_CREDENTIALS, API_KEY]" + errors.append(error) + + if len(errors) > 0: + error_description = "; ".join(errors) + error_plural = "errors" if len(errors) > 1 else "error" + errors_amount = len(errors) + message = f"{errors_amount} validation {error_plural} detected: {error_description}" + raise CommonServiceException(message=message, code="ValidationException") + + return call_moto(context) + class EventsBackend(RegionBackend): # maps rule name to job_id @@ -337,7 +374,7 @@ def filter_event(event_pattern_filter: Dict[str, Any], event: Dict[str, Any]): if not handle_prefix_filtering(value.get(key_a), value_a): return False - # 2. check if the pattern is a list and event values are not contained in it + # 2. check if the pattern is a list and event values are not contained in itEventsApi if isinstance(value, list): if identify_content_base_parameter_in_pattern(value): if not filter_event_with_content_base_parameter(value, event_value): diff --git a/tests/integration/test_events.py b/tests/integration/test_events.py index cc453061c2eb1..c862282ea3f22 100644 --- a/tests/integration/test_events.py +++ b/tests/integration/test_events.py @@ -7,6 +7,7 @@ from typing import Dict, List, Tuple import pytest +from botocore.exceptions import ClientError from localstack import config from localstack.services.awslambda.lambda_utils import LAMBDA_RUNTIME_PYTHON36 @@ -769,6 +770,25 @@ def check(): # clean up proxy.stop() + def test_create_connection_validations(self, events_client): + connection_name = "This should fail with two errors 123467890123412341234123412341234" + + with pytest.raises(ClientError) as ctx: + events_client.create_connection( + Name=connection_name, + AuthorizationType="INVALID", + AuthParameters={"BasicAuthParameters": {"Username": "user", "Password": "pass"}}, + ), + + assert ctx.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert ctx.value.response["Error"]["Code"] == "ValidationException" + + message = ctx.value.response["Error"]["Message"] + assert "3 validation errors" in message + assert "must satisfy regular expression pattern" in message + assert "must have length less than or equal to 64" in message + assert "must satisfy enum value set: [BASIC, OAUTH_CLIENT_CREDENTIALS, API_KEY]" in message + def test_put_events_with_target_firehose(self, events_client, s3_client, firehose_client): s3_bucket = "s3-{}".format(short_uid()) s3_prefix = "testeventdata"
This PR addresses issue #5943 where is shown that Localstack doesn't validate the name parameter when creating a new Connection for the Events service, which could lead to several problems. Changes: - Validation for the Name parameter and the AuthorizationType. - Test addition.
https://api.github.com/repos/localstack/localstack/pulls/5964
2022-04-30T04:08:28Z
2022-05-20T18:00:40Z
2022-05-20T18:00:40Z
2022-07-13T22:24:19Z
1,113
localstack/localstack
28,652
TFTrainer dataset doc & fix evaluation bug
diff --git a/src/transformers/trainer_tf.py b/src/transformers/trainer_tf.py index 9b03fc614edb6..ecc15719a9aa9 100644 --- a/src/transformers/trainer_tf.py +++ b/src/transformers/trainer_tf.py @@ -38,9 +38,17 @@ class TFTrainer: args (:class:`~transformers.TFTrainingArguments`): The arguments to tweak training. train_dataset (:class:`~tf.data.Dataset`, `optional`): - The dataset to use for training. + The dataset to use for training. The dataset should yield tuples of ``(features, labels)`` where + ``features`` is a dict of input features and ``labels`` is the labels. If ``labels`` is a tensor, the loss is + calculated by the model by calling ``model(features, labels=labels)``. If ``labels`` is a dict, such as when + using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling + ``model(features, **labels)``. eval_dataset (:class:`~tf.data.Dataset`, `optional`): - The dataset to use for evaluation. + The dataset to use for evaluation. The dataset should yield tuples of ``(features, labels)`` where + ``features`` is a dict of input features and ``labels`` is the labels. If ``labels`` is a tensor, the loss is + calculated by the model by calling ``model(features, labels=labels)``. If ``labels`` is a dict, such as when + using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling + ``model(features, **labels)``. compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`): The function that will be used to compute metrics at evaluation. Must take a :class:`~transformers.EvalPrediction` and return a dictionary string to metric values. @@ -145,7 +153,11 @@ def get_eval_tfdataset(self, eval_dataset: Optional[tf.data.Dataset] = None) -> Args: eval_dataset (:class:`~tf.data.Dataset`, `optional`): - If provided, will override `self.eval_dataset`. + If provided, will override `self.eval_dataset`. The dataset should yield tuples of ``(features, + labels)`` where ``features`` is a dict of input features and ``labels`` is the labels. If ``labels`` + is a tensor, the loss is calculated by the model by calling ``model(features, labels=labels)``. If + ``labels`` is a dict, such as when using a QuestionAnswering head model with multiple targets, the + loss is instead calculated by calling ``model(features, **labels)``. Subclass and override this method if you want to inject some custom behavior. """ @@ -173,7 +185,12 @@ def get_test_tfdataset(self, test_dataset: tf.data.Dataset) -> tf.data.Dataset: Returns a test :class:`~tf.data.Dataset`. Args: - test_dataset (:class:`~tf.data.Dataset`): The dataset to use. + test_dataset (:class:`~tf.data.Dataset`): + The dataset to use. The dataset should yield tuples of ``(features, labels)`` where ``features`` is + a dict of input features and ``labels`` is the labels. If ``labels`` is a tensor, the loss is + calculated by the model by calling ``model(features, labels=labels)``. If ``labels`` is a dict, such + as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated + by calling ``model(features, **labels)``. Subclass and override this method if you want to inject some custom behavior. """ @@ -405,14 +422,18 @@ def evaluate(self, eval_dataset: Optional[tf.data.Dataset] = None) -> Dict[str, Args: eval_dataset (:class:`~tf.data.Dataset`, `optional`): - Pass a dataset if you wish to override :obj:`self.eval_dataset`. + Pass a dataset if you wish to override :obj:`self.eval_dataset`. The dataset should yield tuples of + ``(features, labels)`` where ``features`` is a dict of input features and ``labels`` is the labels. + If ``labels`` is a tensor, the loss is calculated by the model by calling ``model(features, + labels=labels)``. If ``labels`` is a dict, such as when using a QuestionAnswering head model with + multiple targets, the loss is instead calculated by calling ``model(features, **labels)``. Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. """ eval_ds, steps, num_examples = self.get_eval_tfdataset(eval_dataset) - output = self._prediction_loop(eval_ds, steps, num_examples, description="Evaluation") + output = self.prediction_loop(eval_ds, steps, num_examples, description="Evaluation") logs = {**output.metrics} logs["epoch"] = self.epoch_logging @@ -666,7 +687,11 @@ def predict(self, test_dataset: tf.data.Dataset) -> PredictionOutput: Args: test_dataset (:class:`~tf.data.Dataset`): - Dataset to run the predictions on. + Dataset to run the predictions on. The dataset should yield tuples of ``(features, labels)`` where + ``features`` is a dict of input features and ``labels`` is the labels. If ``labels`` is a tensor, + the loss is calculated by the model by calling ``model(features, labels=labels)``. If ``labels`` is + a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead + calculated by calling ``model(features, **labels)``. Returns: `NamedTuple`: predictions (:obj:`np.ndarray`):
discussed in #6551
https://api.github.com/repos/huggingface/transformers/pulls/6618
2020-08-20T15:15:36Z
2020-08-20T16:11:37Z
2020-08-20T16:11:37Z
2020-08-28T15:10:26Z
1,302
huggingface/transformers
12,349
Update aspect ratio image overlay selectors after ui and core overhaul
diff --git a/javascript/aspectRatioOverlay.js b/javascript/aspectRatioOverlay.js index 52e9f3817e9..96f1c00d0de 100644 --- a/javascript/aspectRatioOverlay.js +++ b/javascript/aspectRatioOverlay.js @@ -18,9 +18,9 @@ function dimensionChange(e,dimname){ return; } - var img2imgMode = gradioApp().querySelector("input[name=radio-img2img_mode]:checked") + var img2imgMode = gradioApp().querySelector('#mode_img2img.tabs > div > button.rounded-t-lg.border-gray-200') if(img2imgMode){ - img2imgMode=img2imgMode.value + img2imgMode=img2imgMode.innerText }else{ return; } @@ -30,12 +30,10 @@ function dimensionChange(e,dimname){ var targetElement = null; - if(img2imgMode=='Redraw whole image' && redrawImage){ + if(img2imgMode=='img2img' && redrawImage){ targetElement = redrawImage; - }else if(img2imgMode=='Inpaint a part of image' && inpaintImage){ + }else if(img2imgMode=='Inpaint' && inpaintImage){ targetElement = inpaintImage; - }else if(img2imgMode=='SD upscale' && redrawImage){ - targetElement = redrawImage; } if(targetElement){ @@ -119,6 +117,3 @@ onUiUpdate(function(){ }) } }); - - -
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/852
2022-09-22T14:23:22Z
2022-09-22T16:29:20Z
2022-09-22T16:29:20Z
2022-09-22T16:44:12Z
348
AUTOMATIC1111/stable-diffusion-webui
40,193
[utils] Change Firefox 44 to 47
diff --git a/youtube_dl/utils.py b/youtube_dl/utils.py index f77ab865093..0acbd67de28 100644 --- a/youtube_dl/utils.py +++ b/youtube_dl/utils.py @@ -76,7 +76,7 @@ def register_socks_protocols(): compiled_regex_type = type(re.compile('')) std_headers = { - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/44.0 (Chrome)', + 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/47.0 (Chrome)', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate',
See commit title.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/9755
2016-06-11T09:36:45Z
2016-06-11T09:38:45Z
2016-06-11T09:38:45Z
2016-06-11T09:39:37Z
229
ytdl-org/youtube-dl
49,693
FROM nvcr.io/nvidia/pytorch:21.05-py3
diff --git a/Dockerfile b/Dockerfile index a5b9da06a3d..e22c1106f23 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch -FROM nvcr.io/nvidia/pytorch:21.06-py3 +FROM nvcr.io/nvidia/pytorch:21.05-py3 # Install linux packages RUN apt update && apt install -y zip htop screen libgl1-mesa-glx
## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Updated the base Docker image in the `ultralytics/yolov5` project. ### 📊 Key Changes - Changed the Nvidia PyTorch base image from version 21.06 to 21.05. ### 🎯 Purpose & Impact - This adjustment ensures compatibility or leverages specific features available in the 21.05 PyTorch image. - Users building the Docker container may notice differences in dependencies or performance associated with the version change.
https://api.github.com/repos/ultralytics/yolov5/pulls/3794
2021-06-26T15:12:37Z
2021-06-26T15:12:43Z
2021-06-26T15:12:43Z
2024-01-19T17:16:57Z
140
ultralytics/yolov5
25,306
Added a function that checks if given string can be rearranged to form a palindrome.
diff --git a/strings/can_string_be_rearranged_as_palindrome.py b/strings/can_string_be_rearranged_as_palindrome.py new file mode 100644 index 000000000000..92bc3b95b243 --- /dev/null +++ b/strings/can_string_be_rearranged_as_palindrome.py @@ -0,0 +1,113 @@ +# Created by susmith98 + +from collections import Counter +from timeit import timeit + +# Problem Description: +# Check if characters of the given string can be rearranged to form a palindrome. +# Counter is faster for long strings and non-Counter is faster for short strings. + + +def can_string_be_rearranged_as_palindrome_counter(input_str: str = "",) -> bool: + """ + A Palindrome is a String that reads the same forward as it does backwards. + Examples of Palindromes mom, dad, malayalam + >>> can_string_be_rearranged_as_palindrome_counter("Momo") + True + >>> can_string_be_rearranged_as_palindrome_counter("Mother") + False + >>> can_string_be_rearranged_as_palindrome_counter("Father") + False + >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") + True + """ + return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 + + +def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: + """ + A Palindrome is a String that reads the same forward as it does backwards. + Examples of Palindromes mom, dad, malayalam + >>> can_string_be_rearranged_as_palindrome("Momo") + True + >>> can_string_be_rearranged_as_palindrome("Mother") + False + >>> can_string_be_rearranged_as_palindrome("Father") + False + >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") + True + """ + if len(input_str) == 0: + return True + lower_case_input_str = input_str.replace(" ", "").lower() + # character_freq_dict: Stores the frequency of every character in the input string + character_freq_dict = {} + + for character in lower_case_input_str: + character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 + """ + Above line of code is equivalent to: + 1) Getting the frequency of current character till previous index + >>> character_freq = character_freq_dict.get(character, 0) + 2) Incrementing the frequency of current character by 1 + >>> character_freq = character_freq + 1 + 3) Updating the frequency of current character + >>> character_freq_dict[character] = character_freq + """ + """ + OBSERVATIONS: + Even length palindrome + -> Every character appears even no.of times. + Odd length palindrome + -> Every character appears even no.of times except for one character. + LOGIC: + Step 1: We'll count number of characters that appear odd number of times i.e oddChar + Step 2:If we find more than 1 character that appears odd number of times, + It is not possible to rearrange as a palindrome + """ + oddChar = 0 + + for character_count in character_freq_dict.values(): + if character_count % 2: + oddChar += 1 + if oddChar > 1: + return False + return True + + +def benchmark(input_str: str = "") -> None: + """ + Benchmark code for comparing above 2 functions + """ + print("\nFor string = ", input_str, ":") + print( + "> can_string_be_rearranged_as_palindrome_counter()", + "\tans =", + can_string_be_rearranged_as_palindrome_counter(input_str), + "\ttime =", + timeit( + "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", + setup="import __main__ as z", + ), + "seconds", + ) + print( + "> can_string_be_rearranged_as_palindrome()", + "\tans =", + can_string_be_rearranged_as_palindrome(input_str), + "\ttime =", + timeit( + "z.can_string_be_rearranged_as_palindrome(z.check_str)", + setup="import __main__ as z", + ), + "seconds", + ) + + +if __name__ == "__main__": + check_str = input( + "Enter string to determine if it can be rearranged as a palindrome or not: " + ).strip() + benchmark(check_str) + status = can_string_be_rearranged_as_palindrome_counter(check_str) + print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
### **Describe your change:** * [x] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### **Checklist:** * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
https://api.github.com/repos/TheAlgorithms/Python/pulls/2450
2020-09-19T10:20:48Z
2020-09-19T19:49:38Z
2020-09-19T19:49:38Z
2020-09-19T19:49:38Z
1,145
TheAlgorithms/Python
30,066
Update MySQL Injection.md
diff --git a/SQL Injection/MySQL Injection.md b/SQL Injection/MySQL Injection.md index c4df66b94f..1764a1325a 100644 --- a/SQL Injection/MySQL Injection.md +++ b/SQL Injection/MySQL Injection.md @@ -389,6 +389,10 @@ Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The ' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- ``` +```sql +UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php')); +``` + If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query ```sql
TO_base64(LOAD_FILE('/var/www/html/index.php'));
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/422
2021-09-25T10:53:43Z
2021-09-25T16:17:11Z
2021-09-25T16:17:10Z
2021-09-25T16:17:11Z
161
swisskyrepo/PayloadsAllTheThings
8,708
Add PiXHost API to readme
diff --git a/README.md b/README.md index 11e5c8034f..253af9cc92 100644 --- a/README.md +++ b/README.md @@ -509,6 +509,7 @@ API | Description | Auth | HTTPS | Link | | Giphy | Get all your gifs | No | Yes | [Go!](https://github.com/Giphy/GiphyAPI) | | Imgur | Images | `OAuth` | Yes | [Go!](https://apidocs.imgur.com/) | | Pixabay | Photography | `apiKey` | Yes | [Go!](https://pixabay.com/sk/service/about/api/) | +| Pixhost | Upload images, photos, galleries | No | Yes | [Go!](https://pixhost.org/api/index.html) | | PlaceKitten | Resizable kitten placeholder images | No | Yes | [Go!](https://placekitten.com/) | | ScreenShotLayer | URL 2 Image | No | Yes | [Go!](https://screenshotlayer.com) | | Unsplash | Photography | `OAuth` | Yes | [Go!](https://unsplash.com/developers) |
PiXhost like imgur is a image hosting service and is free to all users. Some people who have slightly more graphical content that gets rejected at imgur switch to PiXhost because it has more lenient rules. It also has an API that is not known. From their website: "Welcome to the PiXhost API! You can use this API to upload images, covers or galleries. The following image formats are supported: image/gif, image/png, image/jpeg. Maximum image size is 10 MB. In case you have any ideas, questions or issues, feel free to contact us at: admin@pixhost.org. Old API users: We recently enforced https, please update your scripts." Thank you for taking the time to work on a Pull Request for this project! To ensure your PR is dealt with swiftly please check the following: - [x] Your submissions are formatted according to the guidelines in the [contributing guide](CONTRIBUTING.md). - [x] Your changes are made in the [README](../README.md) file, not the auto-generated JSON. - [x] Your additions are ordered alphabetically. - [x] Your submission has a useful description. - [x] Each table column should be padded with one space on either side. - [x] You have searched the repository for any relevant issues or PRs. - [x] Any category you are creating has the minimum requirement of 3 items.
https://api.github.com/repos/public-apis/public-apis/pulls/502
2017-10-07T13:22:01Z
2017-10-24T14:34:21Z
2017-10-24T14:34:21Z
2017-10-24T14:34:24Z
252
public-apis/public-apis
35,205
[sharesix] Add new extractor
diff --git a/youtube_dl/extractor/__init__.py b/youtube_dl/extractor/__init__.py index 7adca7df918..c76fb37273b 100644 --- a/youtube_dl/extractor/__init__.py +++ b/youtube_dl/extractor/__init__.py @@ -296,6 +296,7 @@ from .screencast import ScreencastIE from .servingsys import ServingSysIE from .shared import SharedIE +from .sharesix import ShareSixIE from .sina import SinaIE from .slideshare import SlideshareIE from .slutload import SlutloadIE diff --git a/youtube_dl/extractor/sharesix.py b/youtube_dl/extractor/sharesix.py new file mode 100644 index 00000000000..7531e8325bf --- /dev/null +++ b/youtube_dl/extractor/sharesix.py @@ -0,0 +1,91 @@ +# coding: utf-8 +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor +from ..utils import ( + compat_urllib_parse, + compat_urllib_request, + parse_duration, +) + + +class ShareSixIE(InfoExtractor): + _VALID_URL = r'https?://(?:www\.)?sharesix\.com/(?:f/)?(?P<id>[0-9a-zA-Z]+)' + _TESTS = [ + { + 'url': 'http://sharesix.com/f/OXjQ7Y6', + 'md5': '9e8e95d8823942815a7d7c773110cc93', + 'info_dict': { + 'id': 'OXjQ7Y6', + 'ext': 'mp4', + 'title': 'big_buck_bunny_480p_surround-fix.avi', + 'duration': 596, + 'width': 854, + 'height': 480, + }, + }, + { + 'url': 'http://sharesix.com/lfrwoxp35zdd', + 'md5': 'dd19f1435b7cec2d7912c64beeee8185', + 'info_dict': { + 'id': 'lfrwoxp35zdd', + 'ext': 'flv', + 'title': 'WhiteBoard___a_Mac_vs_PC_Parody_Cartoon.mp4.flv', + 'duration': 65, + 'width': 1280, + 'height': 720, + }, + } + ] + + def _real_extract(self, url): + mobj = re.match(self._VALID_URL, url) + video_id = mobj.group('id') + + fields = { + 'method_free': 'Free' + } + post = compat_urllib_parse.urlencode(fields) + req = compat_urllib_request.Request(url, post) + req.add_header('Content-type', 'application/x-www-form-urlencoded') + + webpage = self._download_webpage(req, video_id, + 'Downloading video page') + + video_url = self._search_regex( + r"var\slnk1\s=\s'([^']+)'", webpage, 'video URL') + title = self._html_search_regex( + r'(?s)<dt>Filename:</dt>.+?<dd>(.+?)</dd>', webpage, 'title') + duration = parse_duration( + self._search_regex( + r'(?s)<dt>Length:</dt>.+?<dd>(.+?)</dd>', + webpage, + 'duration', + fatal=False + ) + ) + + m = re.search( + r'''(?xs)<dt>Width\sx\sHeight</dt>.+? + <dd>(?P<width>\d+)\sx\s(?P<height>\d+)</dd>''', + webpage + ) + width = height = None + if m: + width, height = int(m.group('width')), int(m.group('height')) + + formats = [{ + 'format_id': 'sd', + 'url': video_url, + 'width': width, + 'height': height, + }] + + return { + 'id': video_id, + 'title': title, + 'duration': duration, + 'formats': formats, + }
Hi, this adds support for [sharesix](http://sharesix.com/). The download URL only works with the same user agent string that was used during extraction. Shouldn't there be some info message when he/she uses the `-g`, `--get-url` flag? As it might not be obvious to everyone.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/3690
2014-09-06T16:06:50Z
2014-09-09T14:14:59Z
2014-09-09T14:14:59Z
2014-09-09T18:11:21Z
1,014
ytdl-org/youtube-dl
49,803
Add blogs to dataset materials section
diff --git a/doc/source/data/dataset.rst b/doc/source/data/dataset.rst index d14a4f3e0e604..2089a4051ba08 100644 --- a/doc/source/data/dataset.rst +++ b/doc/source/data/dataset.rst @@ -392,6 +392,8 @@ Talks and Materials ------------------- - [slides] `Talk given at PyData 2021 <https://docs.google.com/presentation/d/1zANPlmrxQkjPU62I-p92oFO3rJrmjVhs73hL4YbM4C4>`_ +- [blog] `Data Ingest in a Third Generation ML Architecture <https://www.anyscale.com/blog/deep-dive-data-ingest-in-a-third-generation-ml-architecture>`_ +- [blog] `Building an end-to-end ML pipeline using Mars and XGBoost on Ray <https://www.anyscale.com/blog/building-an-end-to-end-ml-pipeline-using-mars-and-xgboost-on-ray>`_ Contributing
https://api.github.com/repos/ray-project/ray/pulls/21546
2022-01-12T03:11:49Z
2022-01-12T06:09:57Z
2022-01-12T06:09:57Z
2022-01-12T06:09:57Z
230
ray-project/ray
19,498
Fixed lbfgs for ray-cluster
diff --git a/examples/lbfgs/driver.py b/examples/lbfgs/driver.py index f74af6ddd0497..f81f1923363bf 100644 --- a/examples/lbfgs/driver.py +++ b/examples/lbfgs/driver.py @@ -10,103 +10,102 @@ from tensorflow.examples.tutorials.mnist import input_data -if __name__ == "__main__": - ray.init(num_workers=10) - - # Define the dimensions of the data and of the model. - image_dimension = 784 - label_dimension = 10 - w_shape = [image_dimension, label_dimension] - w_size = np.prod(w_shape) - b_shape = [label_dimension] - b_size = np.prod(b_shape) - dim = w_size + b_size - - # Define a function for initializing the network. Note that this code does not - # call initialize the network weights. If it did, the weights would be - # randomly initialized on each worker and would differ from worker to worker. - # We pass the weights into the remote functions loss and grad so that the - # weights are the same on each worker. - def net_initialization(): - x = tf.placeholder(tf.float32, [None, image_dimension]) - w = tf.Variable(tf.zeros(w_shape)) - b = tf.Variable(tf.zeros(b_shape)) +class LinearModel(object): + """Simple class for a one layer neural network. + + Note that this code does not initialize the network weights. Instead weights + are set via self.variables.set_weights. + + Example: + net = LinearModel([10,10]) + weights = [np.random.normal(size=[10,10]), np.random.normal(size=[10])] + variable_names = [v.name for v in net.variables] + net.variables.set_weights(dict(zip(variable_names, weights))) + + Attributes: + x (tf.placeholder): Input vector. + w (tf.Variable): Weight matrix. + b (tf.Variable): Bias vector. + y_ (tf.placeholder): Input result vector. + cross_entropy (tf.Operation): Final layer of network. + cross_entropy_grads (tf.Operation): Gradient computation. + sess (tf.Session): Session used for training. + variables (TensorFlowVariables): Extracted variables and methods to + manipulate them. + """ + def __init__(self, shape): + """Creates a LinearModel object.""" + x = tf.placeholder(tf.float32, [None, shape[0]]) + w = tf.Variable(tf.zeros(shape)) + b = tf.Variable(tf.zeros(shape[1])) + self.x = x + self.w = w + self.b = b y = tf.nn.softmax(tf.matmul(x, w) + b) - y_ = tf.placeholder(tf.float32, [None, label_dimension]) + y_ = tf.placeholder(tf.float32, [None, shape[1]]) + self.y_ = y_ cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) - cross_entropy_grads = tf.gradients(cross_entropy, [w, b]) - - sess = tf.Session() - - # In order to set the weights of the TensorFlow graph on a worker, we add - # assignment nodes. To get the network weights (as a list of numpy arrays) - # and to set the network weights (from a list of numpy arrays), use the - # methods get_weights and set_weights. This can be done from within a remote - # function or on the driver. - def get_and_set_weights_methods(): - assignment_placeholders = [] - assignment_nodes = [] - for var in tf.trainable_variables(): - assignment_placeholders.append(tf.placeholder(var.value().dtype, var.get_shape().as_list())) - assignment_nodes.append(var.assign(assignment_placeholders[-1])) - - def get_weights(): - return [v.eval(session=sess) for v in tf.trainable_variables()] - - def set_weights(new_weights): - sess.run(assignment_nodes, feed_dict={p: w for p, w in zip(assignment_placeholders, new_weights)}) - - return get_weights, set_weights - - get_weights, set_weights = get_and_set_weights_methods() - - return sess, cross_entropy, cross_entropy_grads, x, y_, get_weights, set_weights - - # By default, when a reusable variable is used by a remote function, the - # initialization code will be rerun at the end of the remote task to ensure - # that the state of the variable is not changed by the remote task. However, - # the initialization code may be expensive. This case is one example, because - # a TensorFlow network is constructed. In this case, we pass in a special - # reinitialization function which gets run instead of the original - # initialization code. As users, if we pass in custom reinitialization code, - # we must ensure that no state is leaked between tasks. - def net_reinitialization(net_vars): - return net_vars - - # Create a reusable variable for the network. - ray.reusables.net_vars = ray.Reusable(net_initialization, net_reinitialization) - - # Load the weights into the network. - def load_weights(theta): - sess, _, _, _, _, get_weights, set_weights = ray.reusables.net_vars - set_weights([theta[:w_size].reshape(w_shape), theta[w_size:].reshape(b_shape)]) - - # Compute the loss on a batch of data. - @ray.remote - def loss(theta, xs, ys): - sess, cross_entropy, _, x, y_, _, _ = ray.reusables.net_vars - load_weights(theta) - return float(sess.run(cross_entropy, feed_dict={x: xs, y_: ys})) - - # Compute the gradient of the loss on a batch of data. - @ray.remote - def grad(theta, xs, ys): - sess, _, cross_entropy_grads, x, y_, _, _ = ray.reusables.net_vars - load_weights(theta) - gradients = sess.run(cross_entropy_grads, feed_dict={x: xs, y_: ys}) - return np.concatenate([g.flatten() for g in gradients]) - - # Compute the loss on the entire dataset. - def full_loss(theta): - theta_id = ray.put(theta) - loss_ids = [loss.remote(theta_id, xs_id, ys_id) for (xs_id, ys_id) in batch_ids] - return sum(ray.get(loss_ids)) - - # Compute the gradient of the loss on the entire dataset. - def full_grad(theta): - theta_id = ray.put(theta) - grad_ids = [grad.remote(theta_id, xs_id, ys_id) for (xs_id, ys_id) in batch_ids] - return sum(ray.get(grad_ids)).astype("float64") # This conversion is necessary for use with fmin_l_bfgs_b. + self.cross_entropy = cross_entropy + self.cross_entropy_grads = tf.gradients(cross_entropy, [w, b]) + self.sess = tf.Session() + # In order to get and set the weights, we pass in the loss function to Ray's + # TensorFlowVariables to automatically create methods to modify the weights. + self.variables = ray.experimental.TensorFlowVariables(cross_entropy, self.sess) + + def loss(self, xs, ys): + """Computes the loss of the network.""" + return float(self.sess.run(self.cross_entropy, feed_dict={self.x: xs, self.y_: ys})) + + def grad(self, xs, ys): + """Computes the gradients of the network.""" + return self.sess.run(self.cross_entropy_grads, feed_dict={self.x: xs, self.y_: ys}) + +def net_initialization(): + return LinearModel([784,10]) + +# By default, when a reusable variable is used by a remote function, the +# initialization code will be rerun at the end of the remote task to ensure +# that the state of the variable is not changed by the remote task. However, +# the initialization code may be expensive. This case is one example, because +# a TensorFlow network is constructed. In this case, we pass in a special +# reinitialization function which gets run instead of the original +# initialization code. As users, if we pass in custom reinitialization code, +# we must ensure that no state is leaked between tasks. +def net_reinitialization(net): + return net + +# Register the network with Ray and create a reusable variable for it. +ray.reusables.net = ray.Reusable(net_initialization, net_reinitialization) + +# Compute the loss on a batch of data. +@ray.remote +def loss(theta, xs, ys): + net = ray.reusables.net + net.variables.set_flat(theta) + return net.loss(xs,ys) + +# Compute the gradient of the loss on a batch of data. +@ray.remote +def grad(theta, xs, ys): + net = ray.reusables.net + net.variables.set_flat(theta) + gradients = net.grad(xs, ys) + return np.concatenate([g.flatten() for g in gradients]) + +# Compute the loss on the entire dataset. +def full_loss(theta): + theta_id = ray.put(theta) + loss_ids = [loss.remote(theta_id, xs_id, ys_id) for (xs_id, ys_id) in batch_ids] + return sum(ray.get(loss_ids)) + +# Compute the gradient of the loss on the entire dataset. +def full_grad(theta): + theta_id = ray.put(theta) + grad_ids = [grad.remote(theta_id, xs_id, ys_id) for (xs_id, ys_id) in batch_ids] + return sum(ray.get(grad_ids)).astype("float64") # This conversion is necessary for use with fmin_l_bfgs_b. + +if __name__ == "__main__": + ray.init(num_workers=10) # From the perspective of scipy.optimize.fmin_l_bfgs_b, full_loss is simply a # function which takes some parameters theta, and computes a loss. Similarly, @@ -128,7 +127,9 @@ def full_grad(theta): batch_ids = [(ray.put(xs), ray.put(ys)) for (xs, ys) in batches] # Initialize the weights for the network to the vector of all zeros. + dim = ray.reusables.net.variables.get_flat_size() theta_init = 1e-2 * np.random.normal(size=dim) + # Use L-BFGS to minimize the loss function. print("Running L-BFGS.") result = scipy.optimize.fmin_l_bfgs_b(full_loss, theta_init, maxiter=10, fprime=full_grad, disp=True) diff --git a/lib/python/ray/experimental/tfutils.py b/lib/python/ray/experimental/tfutils.py index f70ebd5c8cc01..6f51e3a0d22eb 100644 --- a/lib/python/ray/experimental/tfutils.py +++ b/lib/python/ray/experimental/tfutils.py @@ -1,6 +1,18 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function +import numpy as np + +def unflatten(vector, shapes): + i = 0 + arrays = [] + for shape in shapes: + size = np.prod(shape) + array = vector[i:(i + size)].reshape(shape) + arrays.append(array) + i += size + assert len(vector) == i, "Passed weight does not have the correct shape." + return arrays class TensorFlowVariables(object): """An object used to extract variables from a loss function. @@ -35,12 +47,32 @@ def set_session(self, sess): """Modifies the current session used by the class.""" self.sess = sess + def get_flat_size(self): + return sum([np.prod(v.get_shape().as_list()) for v in self.variables]) + + def _check_sess(self): + """Checks if the session is set, and if not throw an error message.""" + assert self.sess is not None, "The session is not set. Set the session either by passing it into the TensorFlowVariables constructor or by calling set_session(sess)." + + def get_flat(self): + """Gets the weights and returns them as a flat array.""" + self._check_sess() + return np.concatenate([v.eval(session=self.sess).flatten() for v in self.variables]) + + def set_flat(self, new_weights): + """Sets the weights to new_weights, converting from a flat array.""" + self._check_sess() + shapes = [v.get_shape().as_list() for v in self.variables] + arrays = unflatten(new_weights, shapes) + placeholders = [self.assignment_placeholders[v.op.node_def.name] for v in self.variables] + self.sess.run(self.assignment_nodes, feed_dict=dict(zip(placeholders,arrays))) + def get_weights(self): """Returns the weights of the variables of the loss function in a list.""" - assert self.sess is not None, "The session is not set. Set the session either by passing it into the TensorFlowVariables constructor or by calling set_session(sess)." + self._check_sess() return {v.op.node_def.name: v.eval(session=self.sess) for v in self.variables} def set_weights(self, new_weights): """Sets the weights to new_weights.""" - assert self.sess is not None, "The session is not set. Set the session either by passing it into the TensorFlowVariables constructor or by calling set_session(sess)." + self._check_sess() self.sess.run(self.assignment_nodes, feed_dict={self.assignment_placeholders[name]: value for (name, value) in new_weights.items()}) diff --git a/test/tensorflow_test.py b/test/tensorflow_test.py index d9ad347bb9276..7ec5404d053cd 100644 --- a/test/tensorflow_test.py +++ b/test/tensorflow_test.py @@ -5,6 +5,7 @@ import unittest import tensorflow as tf import ray +from numpy.testing import assert_almost_equal class TensorFlowTest(unittest.TestCase): @@ -47,6 +48,16 @@ def testTensorFlowVariables(self): variables2.set_weights(weights2) self.assertEqual(weights2, variables2.get_weights()) + flat_weights = variables2.get_flat() + 2.0 + variables2.set_flat(flat_weights) + assert_almost_equal(flat_weights, variables2.get_flat()) + + variables3 = ray.experimental.TensorFlowVariables(loss2) + self.assertEqual(variables3.sess, None) + sess = tf.Session() + variables3.set_session(sess) + self.assertEqual(variables3.sess, sess) + ray.worker.cleanup() if __name__ == "__main__":
https://api.github.com/repos/ray-project/ray/pulls/180
2017-01-06T00:07:12Z
2017-01-11T02:40:06Z
2017-01-11T02:40:06Z
2017-01-11T02:40:09Z
3,325
ray-project/ray
19,701
Reduce tests for applications
diff --git a/tests/integration_tests/applications_test.py b/tests/integration_tests/applications_test.py index 6c707240cb2..04ec41f0c17 100644 --- a/tests/integration_tests/applications_test.py +++ b/tests/integration_tests/applications_test.py @@ -15,13 +15,22 @@ reason='Runs only when the relevant files have been modified.') -MOBILENET_LIST = [(applications.MobileNet, 1024), - (applications.MobileNetV2, 1280)] -DENSENET_LIST = [(applications.DenseNet121, 1024), - (applications.DenseNet169, 1664), - (applications.DenseNet201, 1920)] -NASNET_LIST = [(applications.NASNetMobile, 1056), - (applications.NASNetLarge, 4032)] +MODEL_LIST = [ + (applications.ResNet50, 2048), + (applications.VGG16, 512), + (applications.VGG19, 512), + (applications.Xception, 2048), + (applications.InceptionV3, 2048), + (applications.InceptionResNetV2, 1536), + (applications.MobileNet, 1024), + (applications.MobileNetV2, 1280), + (applications.DenseNet121, 1024), + (applications.DenseNet169, 1664), + (applications.DenseNet201, 1920) + # TODO: enable nasnet tests if they support Theano and CNTK + # (applications.NASNetMobile, 1056), + # (applications.NASNetLarge, 4032) +] def _get_output_shape(model_fn): @@ -64,103 +73,11 @@ def _test_application_notop(app, last_dim): assert output_shape == (None, None, None, last_dim) -@keras_test -def _test_application_variable_input_channels(app, last_dim): - if K.image_data_format() == 'channels_first': - input_shape = (1, None, None) - else: - input_shape = (None, None, 1) - output_shape = _get_output_shape( - lambda: app(weights=None, include_top=False, input_shape=input_shape)) - assert output_shape == (None, None, None, last_dim) - - if K.image_data_format() == 'channels_first': - input_shape = (4, None, None) - else: - input_shape = (None, None, 4) - output_shape = _get_output_shape( - lambda: app(weights=None, include_top=False, input_shape=input_shape)) - assert output_shape == (None, None, None, last_dim) - - -@keras_test -def _test_app_pooling(app, last_dim): - output_shape = _get_output_shape( - lambda: app(weights=None, - include_top=False, - pooling=random.choice(['avg', 'max']))) - assert output_shape == (None, last_dim) - - -def test_resnet50(): - app = applications.ResNet50 - last_dim = 2048 - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_vgg(): - app = random.choice([applications.VGG16, applications.VGG19]) - last_dim = 512 - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_xception(): - app = applications.Xception - last_dim = 2048 - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_inceptionv3(): - app = applications.InceptionV3 - last_dim = 2048 - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_inceptionresnetv2(): - app = applications.InceptionResNetV2 - last_dim = 1536 - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_mobilenet(): - app, last_dim = random.choice(MOBILENET_LIST) - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -def test_densenet(): - app, last_dim = random.choice(DENSENET_LIST) - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) - - -@pytest.mark.skipif((K.backend() != 'tensorflow'), - reason='NASNets are supported only on TensorFlow') -def test_nasnet(): - app, last_dim = random.choice(NASNET_LIST) - _test_application_basic(app) - _test_application_notop(app, last_dim) - _test_application_variable_input_channels(app, last_dim) - _test_app_pooling(app, last_dim) +def test_applications(): + for _ in range(3): + app, last_dim = random.choice(MODEL_LIST) + _test_application_basic(app) + _test_application_notop(app, last_dim) if __name__ == '__main__':
This PR reduces tests for applications and is a follow-up of #10341.
https://api.github.com/repos/keras-team/keras/pulls/10346
2018-06-03T07:10:30Z
2018-06-04T17:07:24Z
2018-06-04T17:07:24Z
2018-06-05T00:26:14Z
1,328
keras-team/keras
47,188
cleanup Amazon `CHANGELOG.rst`
diff --git a/airflow/providers/amazon/CHANGELOG.rst b/airflow/providers/amazon/CHANGELOG.rst index a337648c50bd6..906de481a7851 100644 --- a/airflow/providers/amazon/CHANGELOG.rst +++ b/airflow/providers/amazon/CHANGELOG.rst @@ -40,7 +40,6 @@ Features * ``Add deferrable mode for S3KeySensor (#31018)`` * ``Add Deferrable mode to Emr Add Steps operator (#30928)`` * ``Add deferrable mode in Redshift delete cluster (#30244)`` -* ``Add discoverability for triggers in provider.yaml (#31576)`` * ``Add deferrable mode to AWS glue operators (Job & Crawl) (#30948)`` * ``Add deferrable param in BatchOperator (#30865)`` * ``Add Deferrable Mode to RedshiftCreateClusterSnapshotOperator (#30856)`` @@ -83,7 +82,7 @@ Misc * ``Replace spelling directive with spelling:word-list (#31752)`` * ``Remove aws unused code (#31610)`` * ``Add note about dropping Python 3.7 for providers (#32015)`` - + * ``Add discoverability for triggers in provider.yaml (#31576)`` 8.1.0 .....
<!-- Thank you for contributing! Please make sure that your code changes are covered with tests. And in case of new features or big changes remember to adjust the documentation. Feel free to ping committers for the review! In case of an existing issue, reference it using one of the following: closes: #ISSUE related: #ISSUE How to write a good git commit message: http://chris.beams.io/posts/git-commit/ --> --- **^ Add meaningful description above** Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information. In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed. In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x). In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
https://api.github.com/repos/apache/airflow/pulls/32031
2023-06-20T13:21:13Z
2023-06-21T05:48:26Z
2023-06-21T05:48:26Z
2023-06-21T11:32:05Z
298
apache/airflow
14,291
🌐 Add Korean translation for `docs/ko/docs/deployment/cloud.md`
diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md new file mode 100644 index 0000000000000..f2b965a9113b8 --- /dev/null +++ b/docs/ko/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI를 클라우드 제공업체에서 배포하기 + +사실상 거의 **모든 클라우드 제공업체**를 사용하여 여러분의 FastAPI 애플리케이션을 배포할 수 있습니다. + +대부분의 경우, 주요 클라우드 제공업체에서는 FastAPI를 배포할 수 있도록 가이드를 제공합니다. + +## 클라우드 제공업체 - 후원자들 + +몇몇 클라우드 제공업체들은 [**FastAPI를 후원하며**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, 이를 통해 FastAPI와 FastAPI **생태계**가 지속적이고 건전한 **발전**을 할 수 있습니다. + +이는 FastAPI와 **커뮤니티** (여러분)에 대한 진정한 헌신을 보여줍니다. 그들은 여러분에게 **좋은 서비스**를 제공할 뿐 만이 아니라 여러분이 **훌륭하고 건강한 프레임워크인** FastAPI 를 사용하길 원하기 때문입니다. 🙇 + +아래와 같은 서비스를 사용해보고 각 서비스의 가이드를 따를 수도 있습니다: + +* <a href="https://docs.platform.sh/languages/python.html?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023" class="external-link" target="_blank">Platform.sh</a> +* <a href="https://docs.porter.run/language-specific-guides/fastapi" class="external-link" target="_blank">Porter</a> +* <a href="https://www.deta.sh/?ref=fastapi" class="external-link" target="_blank">Deta</a>
- Add Korean translation for ```docs/ko/docs/deployment/cloud.md``` - Related [FEATURE] Korean translations #2017
https://api.github.com/repos/tiangolo/fastapi/pulls/10191
2023-09-02T05:47:04Z
2023-09-25T23:03:00Z
2023-09-25T23:03:00Z
2023-09-25T23:03:00Z
462
tiangolo/fastapi
23,121
Windows build
diff --git a/src/you_get/common.py b/src/you_get/common.py index 5ee03631f0..faa7f7660a 100755 --- a/src/you_get/common.py +++ b/src/you_get/common.py @@ -555,7 +555,8 @@ def update(self): def update_received(self, n): self.received += n - bytes_ps = n / (time.time() - self.last_updated) + time_diff = time.time() - self.last_updated + bytes_ps = n / time_diff if time_diff else 0 if bytes_ps >= 1048576: self.speed = '{:4.0f} MB/s'.format(bytes_ps / 1048576) elif bytes_ps >= 1024: diff --git a/src/you_get/version.py b/src/you_get/version.py index 6fd1692900..3ea5f9fe96 100644 --- a/src/you_get/version.py +++ b/src/you_get/version.py @@ -1,4 +1,4 @@ #!/usr/bin/env python script_name = 'you-get' -__version__ = '0.4.125' +__version__ = '0.4.136'
Starting from version **[0.4.136](https://github.com/soimort/you-get/releases/tag/v0.4.136)**, we will ship Windows binaries for every release of `you-get`, as I promised. Those binaries were built with [PyInstaller](https://github.com/pyinstaller/pyinstaller), so no more Python installation is required. The download [you-get-0.4.136-win32.exe](https://github.com/soimort/you-get/releases/download/v0.4.136/you-get-0.4.136-win32.exe) is a standalone executable of `you-get`; the download [you-get-0.4.136-win32-full.7z](https://github.com/soimort/you-get/releases/download/v0.4.136/you-get-0.4.136-win32-full.7z) also contains ffmpeg and rtmpdump for convenience. If you are already using ffmpeg on Windows, you just need the `exe` file; otherwise, use the `7z` package. Of course we don't have a GUI for `you-get`; instead, double click on the `you-get.bat` file, and it will open a command window where you'll able to run some commands like `you-get`, `ffmpeg` and `rtmpdump` there. ![you-get](https://cloud.githubusercontent.com/assets/342945/11025539/99a28b2e-869c-11e5-842e-4bca14cd7f81.png) This (32-bit) executable has only been roughly tested on Windows 7. If you have issues running on other platforms, just let me know. <!-- Reviewable:start --> [<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/soimort/you-get/755) <!-- Reviewable:end -->
https://api.github.com/repos/soimort/you-get/pulls/755
2015-11-09T03:51:17Z
2015-11-09T03:54:39Z
2015-11-09T03:54:39Z
2020-09-28T23:18:50Z
277
soimort/you-get
21,333
[generic] ImportError fix - change get_testcases to gettestcases in check-porn.py
diff --git a/devscripts/check-porn.py b/devscripts/check-porn.py index 7a219ebe97c..72b2ee42276 100644 --- a/devscripts/check-porn.py +++ b/devscripts/check-porn.py @@ -14,7 +14,7 @@ import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from test.helper import get_testcases +from test.helper import gettestcases from youtube_dl.utils import compat_urllib_parse_urlparse from youtube_dl.utils import compat_urllib_request @@ -24,7 +24,7 @@ else: METHOD = 'EURISTIC' -for test in get_testcases(): +for test in gettestcases(): if METHOD == 'EURISTIC': try: webpage = compat_urllib_request.urlopen(test['url'], timeout=10).read()
## Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [adding new extractor tutorial](https://github.com/rg3/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/rg3/youtube-dl#youtube-dl-coding-conventions) sections - [x] [Searched](https://github.com/rg3/youtube-dl/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests ### In order to be accepted and merged into youtube-dl each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Bug fix - [ ] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information check-porn was trying to import get_testcases from test.helper, but it does not exist in this package. gettestcases exists instead, which works when the code is run.
https://api.github.com/repos/ytdl-org/youtube-dl/pulls/14259
2017-09-19T02:26:28Z
2017-09-19T15:51:21Z
2017-09-19T15:51:21Z
2017-09-19T15:51:21Z
192
ytdl-org/youtube-dl
50,587
force refresh tqdm before close
diff --git a/modules/shared.py b/modules/shared.py index 2fb9e3b5ada..f28a12ccc31 100644 --- a/modules/shared.py +++ b/modules/shared.py @@ -714,6 +714,7 @@ def updateTotal(self, new_total): def clear(self): if self._tqdm is not None: + self._tqdm.refresh() self._tqdm.close() self._tqdm = None
trivial pr to fix a bug where console tqdm total progress bar can be left ~90% upon completion of all operations.
https://api.github.com/repos/AUTOMATIC1111/stable-diffusion-webui/pulls/8548
2023-03-12T13:21:42Z
2023-03-12T13:51:30Z
2023-03-12T13:51:30Z
2023-03-12T14:29:42Z
108
AUTOMATIC1111/stable-diffusion-webui
40,017
[mediaset] Fix extraction for more videos
diff --git a/yt_dlp/extractor/mediaset.py b/yt_dlp/extractor/mediaset.py index f4db58e64af..26e7abc4930 100644 --- a/yt_dlp/extractor/mediaset.py +++ b/yt_dlp/extractor/mediaset.py @@ -44,7 +44,7 @@ class MediasetIE(ThePlatformBaseIE): }, }, { 'url': 'https://www.mediasetplay.mediaset.it/video/matrix/puntata-del-25-maggio_F309013801000501', - 'md5': '288532f0ad18307705b01e581304cd7b', + 'md5': '1276f966ac423d16ba255ce867de073e', 'info_dict': { 'id': 'F309013801000501', 'ext': 'mp4', @@ -74,6 +74,22 @@ class MediasetIE(ThePlatformBaseIE): 'uploader': 'Italia 1', 'uploader_id': 'I1', }, + }, { + 'url': 'https://www.mediasetplay.mediaset.it/video/cameracafe5/episodio-51-tu-chi-sei_F303843107000601', + 'md5': '567e9ad375b7a27a0e370650f572a1e3', + 'info_dict': { + 'id': 'F303843107000601', + 'ext': 'mp4', + 'title': 'Episodio 51 - Tu chi sei?', + 'description': '', + 'thumbnail': r're:^https?://.*\.jpg$', + 'duration': 367.021, + 'upload_date': '20200902', + 'series': 'Camera Café 5', + 'timestamp': 1599069817, + 'uploader': 'Italia 1', + 'uploader_id': 'I1', + }, }, { # clip 'url': 'https://www.mediasetplay.mediaset.it/video/gogglebox/un-grande-classico-della-commedia-sexy_FAFU000000661680', @@ -148,7 +164,7 @@ def _real_extract(self, url): formats = [] subtitles = {} first_e = None - asset_type = 'HD,browser,geoIT|SD,browser,geoIT|geoNo:HD,browser,geoIT|geoNo:SD,browser,geoIT|geoNo|HD|SD' + asset_type = 'geoNo:HD,browser,geoIT|geoNo:HD,geoIT|geoNo:SD,browser,geoIT|geoNo:SD,geoIT|geoNo|HD|SD' # TODO: fixup ISM+none manifest URLs for f in ('MPEG4', 'MPEG-DASH+none', 'M3U+none'): try:
## Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes [ ] relevant to your *pull request* (like that [x]) - Use *Preview* tab to see how your *pull request* will actually look like --- ### Before submitting a *pull request* make sure you have: - [x] At least skimmed through [adding new extractor tutorial](https://github.com/ytdl-org/youtube-dl#adding-support-for-a-new-site) and [youtube-dl coding conventions](https://github.com/ytdl-org/youtube-dl#youtube-dl-coding-conventions) sections - [x] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [x] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [x] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [x] Bug fix - [ ] Improvement - [ ] New extractor - [ ] New feature --- ### Description of your *pull request* and other information This should fix the geo-restriction error in #851 happening even when you're using an Italian residential IP.
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/852
2021-09-01T16:59:22Z
2021-09-01T18:53:20Z
2021-09-01T18:53:19Z
2021-09-01T18:53:20Z
677
yt-dlp/yt-dlp
7,450
Update doc references for RTD
diff --git a/docs/changelog.md b/docs/changelog.md index 1f7b10b0b3ea..fcae13ed251e 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -24,13 +24,13 @@ _Release date: May 18, 2020_ - ↕️ Ability to set the height of an `st.text_area` with the `height` argument (expressed in pixels). See - [docs](https://docs.streamlit.io/api.html#streamlit.text_area) for more. + [docs](https://docs.streamlit.io/en/latest/api.html#streamlit.text_area) for more. - 🔡 Ability to set the maximimum number of characters allowed in `st.text_area` or `st.text_input`. Check out the `max_chars` argument in the - [docs](https://docs.streamlit.io/api.html#streamlit.text_area). + [docs](https://docs.streamlit.io/en/latest/api.html#streamlit.text_area). - 🗺️ Better DeckGL support for the [H3](https://h3geo.org/) geospatial indexing system. So now you can use things like `H3HexagonLayer` in - [`st.pydeck_chart`](https://docs.streamlit.io/api.html#streamlit.pydeck_chart). + [`st.pydeck_chart`](https://docs.streamlit.io/en/latest/api.html#streamlit.pydeck_chart). - 📦 Improved `@st.cache` support for PyTorch TensorBase and Model. ## Version 0.59.0 @@ -40,10 +40,10 @@ _Release date: May 05, 2020_ **Highlights:** - 🎨 New color-picker widget! Use it with - [`st.beta_color_picker()`](https://docs.streamlit.io/api.html#streamlit.beta_color_picker) + [`st.beta_color_picker()`](https://docs.streamlit.io/en/latest/api.html#streamlit.beta_color_picker) - 🧪 Introducing `st.beta_*` and `st.experimental_*` function prefixes, for faster Streamlit feature releases. See - [docs](https://docs.streamlit.io/pre_release_features.html) for more info. + [docs](https://docs.streamlit.io/en/latest/pre_release_features.html) for more info. - 📦 Improved `@st.cache` support for SQL Alchemy objects, CompiledFFI, PyTorch Tensors, and `builtins.mappingproxy`. @@ -67,7 +67,7 @@ _Release date: March 26, 2020_ - ⏲️ Ability to set expiration options for `@st.cache`'ed functions by setting the `max_entries` and `ttl` arguments. See - [docs](https://docs.streamlit.io/api.html#streamlit.cache). + [docs](https://docs.streamlit.io/en/latest/api.html#streamlit.cache). - 🆙 Improved the machinery behind `st.file_uploader`, so it's much more performant now! Also increased the default upload limit to 200MB (configurable via `server.max_upload_size`). @@ -132,11 +132,11 @@ _Release date: January 14, 2020_ - 🗺️ Support for all DeckGL features! Just use [Pydeck](https://deckgl.readthedocs.io/en/latest/) instead of - [`st.deck_gl_chart`](https://docs.streamlit.io/api.html#streamlit.pydeck_chart). + [`st.deck_gl_chart`](https://docs.streamlit.io/en/latest/api.html#streamlit.pydeck_chart). To do that, simply pass a PyDeck object to - [`st.pydeck_chart`](https://docs.streamlit.io/api.html#streamlit.pydeck_chart), - [`st.write`](https://docs.streamlit.io/api.html#streamlit.write), - or [magic](https://docs.streamlit.io/api.html#magic). + [`st.pydeck_chart`](https://docs.streamlit.io/en/latest/api.html#streamlit.pydeck_chart), + [`st.write`](https://docs.streamlit.io/en/latest/api.html#streamlit.write), + or [magic](https://docs.streamlit.io/en/latest/api.html#magic). _Note that as a **preview release** things may change in the near future. Looking forward to hearing input from the community before we stabilize the @@ -174,7 +174,7 @@ _Release date: December 20, 2019_ **Highlights:** - 📤 Preview release of the file uploader widget. To try it out just call - [`st.file_uploader`](https://docs.streamlit.io/api.html#streamlit.file_uploader)! + [`st.file_uploader`](https://docs.streamlit.io/en/latest/api.html#streamlit.file_uploader)! _Note that as a **preview release** things may change in the near future. Looking forward to hearing input from the community before we stabilize the @@ -190,7 +190,7 @@ _Release date: December 20, 2019_ having to call [`pyplot.clf`](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.clf.html) every time. If you want to turn this behavior off, use - [`st.pyplot(clear_figure=False)`](https://docs.streamlit.io/api.html#streamlit.pyplot) + [`st.pyplot(clear_figure=False)`](https://docs.streamlit.io/en/latest/api.html#streamlit.pyplot) - 📣 `st.cache` no longer checks for input mutations. This is the first change of our ongoing effort to simplify the caching system and prepare Streamlit for the launch of other caching primitives like Session State! @@ -302,7 +302,7 @@ _Release date: September 19, 2019_ **Highlights:** - ✨ Magic commands! Use `st.write` without typing `st.write`. See - https://docs.streamlit.io/api.html#magic-commands + https://docs.streamlit.io/en/latest/api.html#magic-commands - 🎛️ New `st.multiselect` widget. - 🐍 Fixed numerous install issues so now you can use `pip install streamlit` even in Conda! We've therefore deactivated our Conda repo. diff --git a/docs/tutorial/create_a_data_explorer_app.md b/docs/tutorial/create_a_data_explorer_app.md index 85239ce20ab2..c8bdfe03b406 100644 --- a/docs/tutorial/create_a_data_explorer_app.md +++ b/docs/tutorial/create_a_data_explorer_app.md @@ -1,7 +1,7 @@ # Tutorial: Create a data explorer app If you've made it this far, chances are you've -[installed Streamlit](https://docs.streamlit.io/#install-streamlit) and +[installed Streamlit](https://docs.streamlit.io/en/latest/#install-streamlit) and run through the basics in our [get started guide](../getting_started.md). If not, now is a good time to take a look. diff --git a/lib/streamlit/DeltaGenerator.py b/lib/streamlit/DeltaGenerator.py index b06d0caddc1a..1caa62935a34 100644 --- a/lib/streamlit/DeltaGenerator.py +++ b/lib/streamlit/DeltaGenerator.py @@ -2151,7 +2151,7 @@ def beta_color_picker(self, element, label, value=None, key=None): """Display a color picker widget. Note: This is a beta feature. See - https://docs.streamlit.io/pre_release_features.html for more + https://docs.streamlit.io/en/latest/pre_release_features.html for more information. Parameters @@ -2726,7 +2726,7 @@ def map(self, element, data=None, zoom=None, use_container_width=True): To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See - https://docs.streamlit.io/cli.html#view-all-config-options for more + https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters @@ -2774,7 +2774,7 @@ def deck_gl_chart(self, element, spec=None, use_container_width=False, **kwargs) To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See - https://docs.streamlit.io/cli.html#view-all-config-options for more + https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters @@ -2898,7 +2898,7 @@ def pydeck_chart(self, element, pydeck_obj=None, use_container_width=False): To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels) See - https://docs.streamlit.io/cli.html#view-all-config-options for more + https://docs.streamlit.io/en/latest/cli.html#view-all-config-options for more info on how to set config options. Parameters diff --git a/lib/streamlit/__init__.py b/lib/streamlit/__init__.py index abe2e084c819..1fdfec1197a2 100644 --- a/lib/streamlit/__init__.py +++ b/lib/streamlit/__init__.py @@ -420,7 +420,7 @@ def experimental_show(*args): 2. It returns None, so it's "slot" in the app cannot be reused. Note: This is an experimental feature. See - https://docs.streamlit.io/pre_release_features.html for more information. + https://docs.streamlit.io/en/latest/pre_release_features.html for more information. Parameters ---------- diff --git a/lib/streamlit/caching.py b/lib/streamlit/caching.py index 494fd556254f..f4d56579665a 100644 --- a/lib/streamlit/caching.py +++ b/lib/streamlit/caching.py @@ -848,7 +848,7 @@ def _get_message(self, orig_exc): doing so, just annotate the function with `@st.cache(allow_output_mutation=True)`. For more information and detailed solutions check out [our documentation.] -(https://docs.streamlit.io/advanced_caching.html) +(https://docs.streamlit.io/en/latest/advanced_caching.html) """ % {"func_name": orig_exc.cached_func_name} ).strip("\n") diff --git a/lib/streamlit/hello/hello.py b/lib/streamlit/hello/hello.py index 56c861ae7de2..1887d66d3ec4 100644 --- a/lib/streamlit/hello/hello.py +++ b/lib/streamlit/hello/hello.py @@ -55,7 +55,7 @@ demos.mapping_demo, """ This demo shows how to use -[`st.deck_gl_chart`](https://docs.streamlit.io/api.html#streamlit.deck_gl_chart) +[`st.deck_gl_chart`](https://docs.streamlit.io/en/latest/api.html#streamlit.deck_gl_chart) to display geospatial data. """, ), diff --git a/lib/tests/streamlit/caching_test.py b/lib/tests/streamlit/caching_test.py index 98ffce9bd43d..a7f77492bbe9 100644 --- a/lib/tests/streamlit/caching_test.py +++ b/lib/tests/streamlit/caching_test.py @@ -458,7 +458,7 @@ def mutation_warning_func(): doing so, just annotate the function with `@st.cache(allow_output_mutation=True)`. For more information and detailed solutions check out [our -documentation.](https://docs.streamlit.io/advanced_caching.html) +documentation.](https://docs.streamlit.io/en/latest/advanced_caching.html) """ ), ) diff --git a/lib/tests/streamlit/write_test.py b/lib/tests/streamlit/write_test.py index f7c9acccb567..85af335d8bed 100644 --- a/lib/tests/streamlit/write_test.py +++ b/lib/tests/streamlit/write_test.py @@ -30,7 +30,7 @@ class StreamlitWriteTest(unittest.TestCase): """Test st.write. - Unit tests for https://docs.streamlit.io/api/text.html#streamlit.write + Unit tests for https://docs.streamlit.io/en/latest/api/text.html#streamlit.write Because we're going to test st.markdown, st.pyplot, st.altair_chart later on, we don't have to test it in st.write In st.write, all we're
Fixes #1482
https://api.github.com/repos/streamlit/streamlit/pulls/1485
2020-05-21T19:02:28Z
2020-05-22T13:27:33Z
2020-05-22T13:27:33Z
2020-05-22T13:27:38Z
2,821
streamlit/streamlit
22,485
requirements.txt: manimpango v0.3.0
diff --git a/requirements.txt b/requirements.txt index c5f049a0f3..a265599b9b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,4 +16,4 @@ pyreadline; sys_platform == 'win32' validators ipython PyOpenGL -manimpango>=0.2.0,<0.3.0' +manimpango>=0.2.0,<0.4.0
## Motivation manimpango v0.3.0 should work as there are no breaking changes for the API used here I should bring in MarkupText here...
https://api.github.com/repos/3b1b/manim/pulls/1521
2021-05-24T16:55:51Z
2021-06-12T12:29:53Z
2021-06-12T12:29:53Z
2021-06-12T13:12:36Z
107
3b1b/manim
18,285
UX: make the fetch_opeml version warning more informative by listing alternative version numbers
diff --git a/sklearn/datasets/_openml.py b/sklearn/datasets/_openml.py index 54ac34de64e24..99f78e3116187 100644 --- a/sklearn/datasets/_openml.py +++ b/sklearn/datasets/_openml.py @@ -307,12 +307,19 @@ def _get_data_info_by_name( ) res = json_data["data"]["dataset"] if len(res) > 1: - warn( + first_version = version = res[0]["version"] + warning_msg = ( "Multiple active versions of the dataset matching the name" - " {name} exist. Versions may be fundamentally different, " - "returning version" - " {version}.".format(name=name, version=res[0]["version"]) + f" {name} exist. Versions may be fundamentally different, " + f"returning version {first_version}. " + "Available versions:\n" ) + for r in res: + warning_msg += f"- version {r['version']}, status: {r['status']}\n" + warning_msg += ( + f" url: https://www.openml.org/search?type=data&id={r['did']}\n" + ) + warn(warning_msg) return res[0] # an integer version has been provided diff --git a/sklearn/datasets/tests/test_openml.py b/sklearn/datasets/tests/test_openml.py index 7047b376d4b57..875921df9f7ca 100644 --- a/sklearn/datasets/tests/test_openml.py +++ b/sklearn/datasets/tests/test_openml.py @@ -1103,10 +1103,14 @@ def test_fetch_openml_iris_warn_multiple_version(monkeypatch, gzip_response): _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) - msg = ( + msg = re.escape( "Multiple active versions of the dataset matching the name" " iris exist. Versions may be fundamentally different, " - "returning version 1." + "returning version 1. Available versions:\n" + "- version 1, status: active\n" + " url: https://www.openml.org/search?type=data&id=61\n" + "- version 3, status: active\n" + " url: https://www.openml.org/search?type=data&id=969\n" ) with pytest.warns(UserWarning, match=msg): fetch_openml(
Quick fix for an annoying UX problem that I endured for so many years ;) /cc @glemaitre.
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/27885
2023-12-01T18:55:59Z
2023-12-08T14:51:41Z
2023-12-08T14:51:41Z
2023-12-10T18:12:57Z
573
scikit-learn/scikit-learn
46,381
Simplified GIS test by removing unneeded Oracle branch.
diff --git a/tests/gis_tests/geoapp/tests.py b/tests/gis_tests/geoapp/tests.py index 9d03d6ff78b88..3ec620dc8ec6c 100644 --- a/tests/gis_tests/geoapp/tests.py +++ b/tests/gis_tests/geoapp/tests.py @@ -103,35 +103,19 @@ def test_lookup_insert_transform(self): # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 - - # Oracle doesn't have SRID 3084, using 41157. - if oracle: - # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157) - # Used the following Oracle SQL to get this value: - # SELECT SDO_UTIL.TO_WKTGEOMETRY( - # SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) - # ) - # FROM DUAL; - nad_wkt = 'POINT (300662.034646583 5416427.45974934)' - nad_srid = 41157 - else: - # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) - # Used ogr.py in gdal 1.4.1 for this transform - nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' - nad_srid = 3084 - + # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857) + other_srid_pnt = wgs_pnt.transform(3857, clone=True) # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. - nad_pnt = fromstr(nad_wkt, srid=nad_srid) if oracle: - tx = Country.objects.get(mpoly__contains=nad_pnt) + tx = Country.objects.get(mpoly__contains=other_srid_pnt) else: - tx = Country.objects.get(mpoly__intersects=nad_pnt) + tx = Country.objects.get(mpoly__intersects=other_srid_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. - sa = City.objects.create(name='San Antonio', point=nad_pnt) + sa = City.objects.create(name='San Antonio', point=other_srid_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio')
https://api.github.com/repos/django/django/pulls/7672
2016-12-09T19:40:09Z
2016-12-15T14:32:12Z
2016-12-15T14:32:12Z
2016-12-15T18:29:02Z
680
django/django
51,349
Fix typo in README.md
diff --git a/API Key Leaks/README.md b/API Key Leaks/README.md index 3a07a180d0..26a3a9a752 100644 --- a/API Key Leaks/README.md +++ b/API Key Leaks/README.md @@ -224,7 +224,7 @@ A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, #Check token validity curl "https://api.mapbox.com/tokens/v2?access_token=YOUR_MAPBOX_ACCESS_TOKEN" -#Get list of all tokens associated with an account. (only works if the token is a Secret Token (sk), and has the appropiate scope) +#Get list of all tokens associated with an account. (only works if the token is a Secret Token (sk), and has the appropriate scope) curl "https://api.mapbox.com/tokens/v2/MAPBOX_USERNAME_HERE?access_token=YOUR_MAPBOX_ACCESS_TOKEN" ```
appropiate -> appropriate
https://api.github.com/repos/swisskyrepo/PayloadsAllTheThings/pulls/674
2023-09-21T15:11:42Z
2023-09-22T12:50:50Z
2023-09-22T12:50:50Z
2023-09-22T12:50:50Z
213
swisskyrepo/PayloadsAllTheThings
8,695
Release/1.26.0
diff --git a/frontend/app/package.json b/frontend/app/package.json index 28a52a53df00..8980a80a5dc8 100644 --- a/frontend/app/package.json +++ b/frontend/app/package.json @@ -1,6 +1,6 @@ { "name": "@streamlit/app", - "version": "1.24.1", + "version": "1.26.0", "license": "Apache-2.0", "private": true, "homepage": "./", @@ -33,7 +33,7 @@ "@emotion/react": "^11.10.5", "@emotion/serialize": "^1.1.1", "@emotion/styled": "^11.10.5", - "@streamlit/lib": "1.24.1", + "@streamlit/lib": "1.26.0", "axios": "^0.27.2", "baseui": "12.2.0", "classnames": "^2.3.2", diff --git a/frontend/lib/package.json b/frontend/lib/package.json index bf56be5af1da..8795d7b3cf4a 100644 --- a/frontend/lib/package.json +++ b/frontend/lib/package.json @@ -1,6 +1,6 @@ { "name": "@streamlit/lib", - "version": "1.24.1", + "version": "1.26.0", "private": true, "license": "Apache-2.0", "main": "dist/index.js", diff --git a/frontend/package.json b/frontend/package.json index 6188b66927c8..ebbb48c3e740 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "streamlit", - "version": "1.25.0", + "version": "1.26.0", "private": true, "workspaces": [ "app", diff --git a/lib/setup.py b/lib/setup.py index 72e5bdd96299..16ab0c045f54 100644 --- a/lib/setup.py +++ b/lib/setup.py @@ -21,7 +21,7 @@ THIS_DIRECTORY = Path(__file__).parent -VERSION = "1.25.0" # PEP-440 +VERSION = "1.26.0" # PEP-440 NAME = "streamlit" diff --git a/lib/test-requirements.txt b/lib/test-requirements.txt index 906385d4f579..f6c0442d355d 100644 --- a/lib/test-requirements.txt +++ b/lib/test-requirements.txt @@ -28,7 +28,7 @@ pytest-playwright>=0.1.2 pixelmatch>=0.3.0 pytest-xdist -mypy-protobuf>=3.2 +mypy-protobuf>=3.2, <3.4 # These requirements exist only for `@st.cache` tests. st.cache is deprecated, and # we're not going to update its associated tests anymore. Please don't modify
**Contribution License Agreement** By submitting this pull request you agree that all contributions to this project are made under the Apache 2.0 license.
https://api.github.com/repos/streamlit/streamlit/pulls/7232
2023-08-24T20:05:03Z
2023-08-24T23:23:18Z
2023-08-24T23:23:18Z
2023-08-24T23:23:18Z
703
streamlit/streamlit
22,025
Fix for Arial.ttf redownloads with hub inference
diff --git a/utils/__init__.py b/utils/__init__.py index 649b288b358..2af1466f1f1 100644 --- a/utils/__init__.py +++ b/utils/__init__.py @@ -1,3 +1,4 @@ +import sys from pathlib import Path import torch @@ -5,6 +6,8 @@ FILE = Path(__file__).absolute() ROOT = FILE.parents[1] # yolov5/ dir +if str(ROOT) not in sys.path: + sys.path.append(str(ROOT)) # add ROOT to PATH # Check YOLOv5 Annotator font font = 'Arial.ttf'
## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Improved module import handling in YOLOv5 utility scripts. ### 📊 Key Changes - Added an import statement for the `sys` module. - Ensured the root directory of YOLOv5 is added to Python's system path. ### 🎯 Purpose & Impact - **Purpose**: These changes ensure that when utility scripts are run, Python can find and import other modules from the YOLOv5 package without issues. - **Impact**: Provides smoother experience for developers working with the YOLOv5 codebase, as it minimizes module not found errors and simplifies the import process. Non-expert users may not notice this change directly, but it can result in fewer errors when using the YOLOv5 tools. 🛠️🐍
https://api.github.com/repos/ultralytics/yolov5/pulls/4627
2021-08-31T11:54:05Z
2021-08-31T13:01:42Z
2021-08-31T13:01:42Z
2024-01-19T15:58:51Z
152
ultralytics/yolov5
25,625
docs: Update apify.ipynb for Document class import
diff --git a/docs/docs/integrations/tools/apify.ipynb b/docs/docs/integrations/tools/apify.ipynb index 949bc93efad1b8..96e2fef7a99f6e 100644 --- a/docs/docs/integrations/tools/apify.ipynb +++ b/docs/docs/integrations/tools/apify.ipynb @@ -41,8 +41,8 @@ "outputs": [], "source": [ "from langchain.indexes import VectorstoreIndexCreator\n", - "from langchain_community.document_loaders.base import Document\n", - "from langchain_community.utilities import ApifyWrapper" + "from langchain_community.utilities import ApifyWrapper\n", + "from langchain_core.documents import Document" ] }, {
- **Description:** Update to correctly import Document class - from langchain_core.documents import Document - **Issue:** Fixes the notebook and the hosted documentation [here](https://python.langchain.com/docs/integrations/tools/apify)
https://api.github.com/repos/langchain-ai/langchain/pulls/19598
2024-03-26T17:16:12Z
2024-03-26T21:46:29Z
2024-03-26T21:46:29Z
2024-03-26T21:46:29Z
175
langchain-ai/langchain
43,298
Update the error message for invalid use of poke-only sensors
diff --git a/airflow/sensors/base.py b/airflow/sensors/base.py index 13b386d247c73..d3cf6451a047c 100644 --- a/airflow/sensors/base.py +++ b/airflow/sensors/base.py @@ -322,7 +322,7 @@ def mode_getter(_): def mode_setter(_, value): if value != "poke": - raise ValueError("cannot set mode to 'poke'.") + raise ValueError(f"Cannot set mode to '{value}'. Only 'poke' is acceptable") if not issubclass(cls_type, BaseSensorOperator): raise ValueError( diff --git a/tests/sensors/test_base.py b/tests/sensors/test_base.py index 3b1571e09439a..6798dd9972c78 100644 --- a/tests/sensors/test_base.py +++ b/tests/sensors/test_base.py @@ -862,14 +862,14 @@ def test_poke_mode_only_allows_poke_mode(self): def test_poke_mode_only_bad_class_method(self): sensor = DummyPokeOnlySensor(task_id="foo", mode="poke", poke_changes_mode=False) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="Cannot set mode to 'reschedule'. Only 'poke' is acceptable"): sensor.change_mode("reschedule") def test_poke_mode_only_bad_init(self): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="Cannot set mode to 'reschedule'. Only 'poke' is acceptable"): DummyPokeOnlySensor(task_id="foo", mode="reschedule", poke_changes_mode=False) def test_poke_mode_only_bad_poke(self): sensor = DummyPokeOnlySensor(task_id="foo", mode="poke", poke_changes_mode=True) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="Cannot set mode to 'reschedule'. Only 'poke' is acceptable"): sensor.poke({})
<!-- Thank you for contributing! Please make sure that your code changes are covered with tests. And in case of new features or big changes remember to adjust the documentation. Feel free to ping committers for the review! In case of an existing issue, reference it using one of the following: closes: #ISSUE related: #ISSUE How to write a good git commit message: http://chris.beams.io/posts/git-commit/ --> Update the error message in the assertion thrown when there's an attempt to change the mode of a poke-only sensor. A minor change, but it's something that caused me to do a double-take while writing a DAG. So thought I'd submit a patch 😄
https://api.github.com/repos/apache/airflow/pulls/30821
2023-04-23T07:09:05Z
2023-04-23T10:37:43Z
2023-04-23T10:37:43Z
2023-04-23T13:00:06Z
435
apache/airflow
14,367
[extractor/radiofrance] Add support for FIP, Le Mouv, France Musique
diff --git a/yt_dlp/extractor/radiofrance.py b/yt_dlp/extractor/radiofrance.py index 0972f2c4f66..7b60b2617b2 100644 --- a/yt_dlp/extractor/radiofrance.py +++ b/yt_dlp/extractor/radiofrance.py @@ -58,7 +58,7 @@ def _real_extract(self, url): class FranceCultureIE(InfoExtractor): - _VALID_URL = r'https?://(?:www\.)?radiofrance\.fr/franceculture/podcasts/(?:[^?#]+/)?(?P<display_id>[^?#]+)-(?P<id>\d+)($|[?#])' + _VALID_URL = r'https?://(?:www\.)?radiofrance\.fr/(?:franceculture|fip|francemusique|mouv|franceinter)/podcasts/(?:[^?#]+/)?(?P<display_id>[^?#]+)-(?P<id>\d+)($|[?#])' _TESTS = [ { 'url': 'https://www.radiofrance.fr/franceculture/podcasts/science-en-questions/la-physique-d-einstein-aiderait-elle-a-comprendre-le-cerveau-8440487', @@ -73,6 +73,10 @@ class FranceCultureIE(InfoExtractor): 'duration': 2750, }, }, + { + 'url': 'https://www.radiofrance.fr/franceinter/podcasts/la-rafle-du-vel-d-hiv-une-affaire-d-etat/les-racines-du-crime-episode-1-3715507', + 'only_matching': True, + } ] def _real_extract(self, url):
<!-- # Please follow the guide below - You will be asked some questions, please read them **carefully** and answer honestly - Put an `x` into all the boxes `[ ]` relevant to your *pull request* (like [x]) - Use *Preview* tab to see how your *pull request* will actually look like --> ### Before submitting a *pull request* make sure you have: - [X] At least skimmed through [contributing guidelines](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) including [yt-dlp coding conventions](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#yt-dlp-coding-conventions) - [X] [Searched](https://github.com/yt-dlp/yt-dlp/search?q=is%3Apr&type=Issues) the bugtracker for similar pull requests - [X] Checked the code with [flake8](https://pypi.python.org/pypi/flake8) and [ran relevant tests](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) ### In order to be accepted and merged into yt-dlp each piece of code must be in public domain or released under [Unlicense](http://unlicense.org/). Check one of the following options: - [X] I am the original author of this code and I am willing to release it under [Unlicense](http://unlicense.org/) - [ ] I am not the original author of this code but it is in public domain or released under [Unlicense](http://unlicense.org/) (provide reliable evidence) ### What is the purpose of your *pull request*? - [X] Fix or improvement to an extractor (Make sure to add/update tests) --- ### Description of your *pull request* and other information This adds support for FIP, Le Mouv and France Musique.
https://api.github.com/repos/yt-dlp/yt-dlp/pulls/4065
2022-06-13T09:44:51Z
2022-06-19T01:36:14Z
2022-06-19T01:36:14Z
2022-06-19T07:31:45Z
405
yt-dlp/yt-dlp
8,144
Added a shorter solution for the directory diff exercise
diff --git a/topics/shell/README.md b/topics/shell/README.md index be96da865..2ec3c63ec 100644 --- a/topics/shell/README.md +++ b/topics/shell/README.md @@ -14,7 +14,7 @@ |Sum|Functions|[Exercise](sum.md)|[Solution](solutions/sum.md) | Basic |Number of Arguments|Case Statement|[Exercise](num_of_args.md)|[Solution](solutions/num_of_args.md) | Basic |Empty Files|Misc|[Exercise](empty_files.md)|[Solution](solutions/empty_files.md) | Basic -|Directories Comparison|Misc|[Exercise](directories_comparison.md)| :( | Basic +|Directories Comparison|Misc|[Exercise](directories_comparison.md)|[Solution](solutions/directories_comparison.md) | Basic |It's alive!|Misc|[Exercise](host_status.md)|[Solution](solutions/host_status.md) | Intermediate ## Shell Scripting - Self Assessment diff --git a/topics/shell/solutions/directories_comparison.md b/topics/shell/solutions/directories_comparison.md index 083ed7445..f9719c303 100644 --- a/topics/shell/solutions/directories_comparison.md +++ b/topics/shell/solutions/directories_comparison.md @@ -4,7 +4,7 @@ 1. You are given two directories as arguments and the output should be any difference between the two directories -### Solution +### Solution 1 Suppose the name of the bash script is ```dirdiff.sh``` @@ -26,5 +26,12 @@ then fi diff -q $1 $2 +``` + +### Solution 2 -``` \ No newline at end of file +With gnu find, you can use diff to compare directories recursively. + +```shell +diff --recursive directory1 directory2 +```
Signed-off-by: Fabio Kruger <10956489+krufab@users.noreply.github.com>
https://api.github.com/repos/bregman-arie/devops-exercises/pulls/344
2023-02-01T00:25:50Z
2023-02-02T11:00:24Z
2023-02-02T11:00:23Z
2023-02-03T14:15:24Z
418
bregman-arie/devops-exercises
17,602
VW MQB: Audi RS3
diff --git a/RELEASES.md b/RELEASES.md index 8d8ee06d632fab..be6f2bb641dbe9 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -2,6 +2,7 @@ Version 0.8.14 (2022-0X-XX) ======================== * bigmodel! * comma body support + * Audi RS3 support thanks to jyoung8607! * Hyundai Ioniq Plug-in Hybrid 2019 support thanks to sunnyhaibin! * Hyundai Tucson Diesel 2019 support thanks to sunnyhaibin! * Toyota Alphard Hybrid 2021 support diff --git a/docs/CARS.md b/docs/CARS.md index 1c134b38690533..5bdd13874841c8 100644 --- a/docs/CARS.md +++ b/docs/CARS.md @@ -77,6 +77,7 @@ How We Rate The Cars |Audi|A3 Sportback e-tron 2017-18|ACC + Lane Assist|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| |Audi|Q2 2018|ACC + Lane Assist|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| |Audi|Q3 2020-21|ACC + Lane Assist|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| +|Audi|RS3 2018|ACC + Lane Assist|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| |Audi|S3 2015-17|ACC + Lane Assist|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| |Genesis|G70 2018|All|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| |Genesis|G80 2018|All|<a href="#"><img valign="top" src="assets/icon-star-empty.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>|<a href="#"><img valign="top" src="assets/icon-star-full.svg" width="22" /></a>| diff --git a/selfdrive/car/volkswagen/values.py b/selfdrive/car/volkswagen/values.py index b2b43c98f3a8a3..89637c184f7605 100755 --- a/selfdrive/car/volkswagen/values.py +++ b/selfdrive/car/volkswagen/values.py @@ -143,6 +143,7 @@ class VWCarInfo(CarInfo): CAR.AUDI_A3_MK3: [ VWCarInfo("Audi A3 2014-19", "ACC + Lane Assist"), VWCarInfo("Audi A3 Sportback e-tron 2017-18", "ACC + Lane Assist"), + VWCarInfo("Audi RS3 2018", "ACC + Lane Assist"), VWCarInfo("Audi S3 2015-17", "ACC + Lane Assist"), ], CAR.AUDI_Q2_MK1: VWCarInfo("Audi Q2 2018", "ACC + Lane Assist"), @@ -617,6 +618,7 @@ class VWCarInfo(CarInfo): b'\xf1\x878V0906259K \xf1\x890001', b'\xf1\x878V0906264B \xf1\x890003', b'\xf1\x878V0907115B \xf1\x890007', + b'\xf1\x878V0907404A \xf1\x890005', ], (Ecu.transmission, 0x7e1, None): [ b'\xf1\x870CW300044T \xf1\x895245', @@ -628,12 +630,14 @@ class VWCarInfo(CarInfo): b'\xf1\x870DD300046A \xf1\x891602', b'\xf1\x870DD300046F \xf1\x891602', b'\xf1\x870DD300046G \xf1\x891601', + b'\xf1\x870DL300012E \xf1\x892012', b'\xf1\x870GC300013M \xf1\x892402', b'\xf1\x870GC300042J \xf1\x891402', ], (Ecu.srs, 0x715, None): [ b'\xf1\x875Q0959655AB\xf1\x890388\xf1\x82\0211111001111111206110412111321139114', b'\xf1\x875Q0959655AM\xf1\x890315\xf1\x82\x1311111111111111311411011231129321212100', + b'\xf1\x875Q0959655BJ\xf1\x890339\xf1\x82\x1311110011131100311111011731179321342100', b'\xf1\x875Q0959655J \xf1\x890825\xf1\x82\023111112111111--171115141112221291163221', b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\023121111111211--261117141112231291163221', b'\xf1\x875Q0959655J \xf1\x890830\xf1\x82\x13121111111111--341117141212231291163221', @@ -643,6 +647,7 @@ class VWCarInfo(CarInfo): (Ecu.eps, 0x712, None): [ b'\xf1\x873Q0909144H \xf1\x895061\xf1\x82\00566G0HA14A1', b'\xf1\x873Q0909144K \xf1\x895072\xf1\x82\x0571G0HA16A1', + b'\xf1\x873Q0909144L \xf1\x895081\xf1\x82\x0571G0JA14A1', b'\xf1\x875Q0909144AB\xf1\x891082\xf1\x82\00521G0G809A1', b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\00503G00303A0', b'\xf1\x875Q0909144P \xf1\x891043\xf1\x82\00503G00803A0',
**Audi RS3** Adding the fastest sibling of the A3 :: S3 :: RS3 family. - [x] owner dongle ID: not available - [x] added to CARS - [x] added to RELEASES Thanks to RS3 owner mabnz!
https://api.github.com/repos/commaai/openpilot/pulls/24329
2022-04-26T03:36:59Z
2022-04-26T04:06:23Z
2022-04-26T04:06:23Z
2022-06-03T21:14:40Z
2,114
commaai/openpilot
9,203
Fix voice assistant error variable
diff --git a/homeassistant/components/voice_assistant/pipeline.py b/homeassistant/components/voice_assistant/pipeline.py index ef13d54e6a1781..b41ab8ef9f74dc 100644 --- a/homeassistant/components/voice_assistant/pipeline.py +++ b/homeassistant/components/voice_assistant/pipeline.py @@ -197,7 +197,7 @@ async def prepare_speech_to_text(self, metadata: stt.SpeechMetadata) -> None: raise SpeechToTextError( code="stt-provider-unsupported-metadata", message=( - f"Provider {engine} does not support input speech " + f"Provider {stt_provider.name} does not support input speech " "to text metadata" ), )
<!-- You are amazing! Thanks for contributing to our project! Please, DO NOT DELETE ANY TEXT from this template! (unless instructed). --> ## Breaking change <!-- If your PR contains a breaking change for existing users, it is important to tell them what breaks, how to make it work again and why we did this. This piece of text is published with the release notes, so it helps if you write it towards our users, not us. Note: Remove this section if this PR is NOT a breaking change. --> ## Proposed change <!-- Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue in the additional information section. --> We referenced the wrong variable when printing the error if the STT provider did not support all passed in metadata. ## Type of change <!-- What type of change does your PR introduce to Home Assistant? NOTE: Please, check only 1! box! If your PR requires multiple boxes to be checked, you'll most likely need to split it into multiple PRs. This makes things easier and faster to code review. --> - [ ] Dependency upgrade - [x] Bugfix (non-breaking change which fixes an issue) - [ ] New integration (thank you!) - [ ] New feature (which adds functionality to an existing integration) - [ ] Deprecation (breaking change to happen in the future) - [ ] Breaking change (fix/feature causing existing functionality to break) - [ ] Code quality improvements to existing code or addition of tests ## Additional information <!-- Details are important, and help maintainers processing your PR. Please be sure to fill out additional details, if applicable. --> - This PR fixes or closes issue: fixes # - This PR is related to issue: - Link to documentation pull request: ## Checklist <!-- Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code. --> - [ ] The code change is tested and works locally. - [ ] Local tests pass. **Your PR cannot be merged unless tests pass** - [ ] There is no commented out code in this PR. - [ ] I have followed the [development checklist][dev-checklist] - [ ] I have followed the [perfect PR recommendations][perfect-pr] - [ ] The code has been formatted using Black (`black --fast homeassistant tests`) - [ ] Tests have been added to verify that the new code works. If user exposed functionality or configuration variables are added/changed: - [ ] Documentation added/updated for [www.home-assistant.io][docs-repository] If the code communicates with devices, web services, or third-party tools: - [ ] The [manifest file][manifest-docs] has all fields filled out correctly. Updated and included derived files by running: `python3 -m script.hassfest`. - [ ] New or updated dependencies have been added to `requirements_all.txt`. Updated by running `python3 -m script.gen_requirements_all`. - [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description. - [ ] Untested files have been added to `.coveragerc`. <!-- This project is very active and we have a high turnover of pull requests. Unfortunately, the number of incoming pull requests is higher than what our reviewers can review and merge so there is a long backlog of pull requests waiting for review. You can help here! By reviewing another pull request, you will help raise the code quality of that pull request and the final review will be faster. This way the general pace of pull request reviews will go up and your wait time will go down. When picking a pull request to review, try to choose one that hasn't yet been reviewed. Thanks for helping out! --> To help with the load of incoming pull requests: - [ ] I have reviewed two other [open pull requests][prs] in this repository. [prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure <!-- Thank you for contributing <3 Below, some useful links you could explore: --> [dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html [manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html [quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html [docs-repository]: https://github.com/home-assistant/home-assistant.io [perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr
https://api.github.com/repos/home-assistant/core/pulls/90658
2023-04-02T03:22:48Z
2023-04-02T03:34:53Z
2023-04-02T03:34:53Z
2023-04-04T01:28:22Z
168
home-assistant/core
39,186
Remove broken external link
diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index 34ba30e0a82df..d275f28611a09 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -25,8 +25,6 @@ Here's an incomplete list of some of them. * <a href="https://medium.com/data-rebels/fastapi-authentication-revisited-enabling-api-key-authentication-122dc5975680" class="external-link" target="_blank">FastAPI authentication revisited: Enabling API key authentication</a> by <a href="https://medium.com/@nils_29588" class="external-link" target="_blank">Nils de Bruin</a>. -* <a href="https://blog.bartab.fr/fastapi-logging-on-the-fly/" class="external-link" target="_blank">FastAPI, a simple use case on logging</a> by <a href="https://blog.bartab.fr/" class="external-link" target="_blank">@euri10</a>. - * <a href="https://medium.com/@nico.axtmann95/deploying-a-scikit-learn-model-with-onnx-und-fastapi-1af398268915" class="external-link" target="_blank">Deploying a scikit-learn model with ONNX and FastAPI</a> by <a href="https://www.linkedin.com/in/nico-axtmann" class="external-link" target="_blank">Nico Axtmann</a>. * <a href="https://geekflare.com/python-asynchronous-web-frameworks/" class="external-link" target="_blank">Top 5 Asynchronous Web Frameworks for Python</a> by <a href="https://geekflare.com/author/ankush/" class="external-link" target="_blank">Ankush Thakur</a> on <a href="https://geekflare.com" class="external-link" target="_blank">GeekFlare</a>.
Fixes/ related to #1265 .
https://api.github.com/repos/tiangolo/fastapi/pulls/1565
2020-06-13T04:31:25Z
2020-06-13T21:07:12Z
2020-06-13T21:07:12Z
2020-06-13T21:07:27Z
447
tiangolo/fastapi
23,013
Fix the documented default of `tracebacks_word_wrap`
diff --git a/rich/logging.py b/rich/logging.py index 8d166fd53..ca0605095 100644 --- a/rich/logging.py +++ b/rich/logging.py @@ -34,7 +34,7 @@ class RichHandler(Handler): tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None. tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None. tracebacks_theme (str, optional): Override pygments theme used in traceback. - tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to False. + tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True. tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10.
## Type of changes - [ ] Bug fix - [ ] New feature - [x] Documentation / docstrings - [ ] Tests - [ ] Other ## Checklist - [x] I've run the latest [black](https://github.com/psf/black) with default args on new code. - [x] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate. - [ ] I've added tests for new code. - [x] I accept that @willmcgugan may be pedantic in the code review. ## Description The documented default for `tracebacks_word_wrap` is not the actual default.
https://api.github.com/repos/Textualize/rich/pulls/974
2021-01-29T21:50:33Z
2021-01-30T11:02:03Z
2021-01-30T11:02:02Z
2022-05-02T09:32:39Z
235
Textualize/rich
47,940
Fix `pretty` cyclic reference handling
diff --git a/CHANGELOG.md b/CHANGELOG.md index 409c0280c..d678c0050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Handle stdout/stderr being null https://github.com/Textualize/rich/pull/2513 - Fix NO_COLOR support on legacy Windows https://github.com/Textualize/rich/pull/2458 +- Fix pretty printer handling of cyclic references https://github.com/Textualize/rich/pull/2524 - Fix missing `mode` property on file wrapper breaking uploads via `requests` https://github.com/Textualize/rich/pull/2495 ## [12.5.2] - 2022-07-18 diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 533eb2bf3..1972229ab 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,6 +8,7 @@ The following people have contributed to the development of Rich: - [Gregory Beauregard](https://github.com/GBeauregard/pyffstream) - [Dennis Brakhane](https://github.com/brakhane) - [Darren Burns](https://github.com/darrenburns) +- [Jim Crist-Harif](https://github.com/jcrist) - [Ed Davis](https://github.com/davised) - [Pete Davison](https://github.com/pd93) - [James Estevez](https://github.com/jstvz) diff --git a/rich/pretty.py b/rich/pretty.py index 12c2454db..3e83b200b 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -636,6 +636,11 @@ def to_repr(obj: Any) -> str: def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node: """Walk the object depth first.""" + obj_id = id(obj) + if obj_id in visited_ids: + # Recursion detected + return Node(value_repr="...") + obj_type = type(obj) py_version = (sys.version_info.major, sys.version_info.minor) children: List[Node] @@ -673,6 +678,7 @@ def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]: pass if rich_repr_result is not None: + push_visited(obj_id) angular = getattr(obj.__rich_repr__, "angular", False) args = list(iter_rich_args(rich_repr_result)) class_name = obj.__class__.__name__ @@ -720,7 +726,9 @@ def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]: children=[], last=root, ) + pop_visited(obj_id) elif _is_attr_object(obj) and not fake_attributes: + push_visited(obj_id) children = [] append = children.append @@ -767,19 +775,14 @@ def iter_attrs() -> Iterable[ node = Node( value_repr=f"{obj.__class__.__name__}()", children=[], last=root ) - + pop_visited(obj_id) elif ( is_dataclass(obj) and not _safe_isinstance(obj, type) and not fake_attributes and (_is_dataclass_repr(obj) or py_version == (3, 6)) ): - obj_id = id(obj) - if obj_id in visited_ids: - # Recursion detected - return Node(value_repr="...") push_visited(obj_id) - children = [] append = children.append if reached_max_depth: @@ -801,8 +804,9 @@ def iter_attrs() -> Iterable[ child_node.key_separator = "=" append(child_node) - pop_visited(obj_id) + pop_visited(obj_id) elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj): + push_visited(obj_id) class_name = obj.__class__.__name__ if reached_max_depth: # If we've reached the max depth, we still show the class name, but not its contents @@ -824,16 +828,13 @@ def iter_attrs() -> Iterable[ child_node.last = last child_node.key_separator = "=" append(child_node) + pop_visited(obj_id) elif _safe_isinstance(obj, _CONTAINERS): for container_type in _CONTAINERS: if _safe_isinstance(obj, container_type): obj_type = container_type break - obj_id = id(obj) - if obj_id in visited_ids: - # Recursion detected - return Node(value_repr="...") push_visited(obj_id) open_brace, close_brace, empty = _BRACES[obj_type](obj) diff --git a/tests/test_pretty.py b/tests/test_pretty.py index 163a9d92b..2b24d9073 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -4,7 +4,7 @@ from array import array from collections import UserDict, defaultdict from dataclasses import dataclass, field -from typing import List, NamedTuple +from typing import List, NamedTuple, Any from unittest.mock import patch import attr @@ -315,12 +315,112 @@ def __repr__(self): assert result == "BrokenAttr()" -def test_recursive(): +def test_reference_cycle_container(): test = [] test.append(test) - result = pretty_repr(test) - expected = "[...]" - assert result == expected + res = pretty_repr(test) + assert res == "[...]" + + test = [1, []] + test[1].append(test) + res = pretty_repr(test) + assert res == "[1, [...]]" + + # Not a cyclic reference, just a repeated reference + a = [2] + test = [1, [a, a]] + res = pretty_repr(test) + assert res == "[1, [[2], [2]]]" + + +def test_reference_cycle_namedtuple(): + class Example(NamedTuple): + x: int + y: Any + + test = Example(1, [Example(2, [])]) + test.y[0].y.append(test) + res = pretty_repr(test) + assert res == "Example(x=1, y=[Example(x=2, y=[...])])" + + # Not a cyclic reference, just a repeated reference + a = Example(2, None) + test = Example(1, [a, a]) + res = pretty_repr(test) + assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" + + +def test_reference_cycle_dataclass(): + @dataclass + class Example: + x: int + y: Any + + test = Example(1, None) + test.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=...)" + + test = Example(1, Example(2, None)) + test.y.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=Example(x=2, y=...))" + + # Not a cyclic reference, just a repeated reference + a = Example(2, None) + test = Example(1, [a, a]) + res = pretty_repr(test) + assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" + + +def test_reference_cycle_attrs(): + @attr.define + class Example: + x: int + y: Any + + test = Example(1, None) + test.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=...)" + + test = Example(1, Example(2, None)) + test.y.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=Example(x=2, y=...))" + + # Not a cyclic reference, just a repeated reference + a = Example(2, None) + test = Example(1, [a, a]) + res = pretty_repr(test) + assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" + + +def test_reference_cycle_custom_repr(): + class Example: + def __init__(self, x, y): + self.x = x + self.y = y + + def __rich_repr__(self): + yield ("x", self.x) + yield ("y", self.y) + + test = Example(1, None) + test.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=...)" + + test = Example(1, Example(2, None)) + test.y.y = test + res = pretty_repr(test) + assert res == "Example(x=1, y=Example(x=2, y=...))" + + # Not a cyclic reference, just a repeated reference + a = Example(2, None) + test = Example(1, [a, a]) + res = pretty_repr(test) + assert res == "Example(x=1, y=[Example(x=2, y=None), Example(x=2, y=None)])" def test_max_depth():
## Type of changes - [x] Bug fix - [ ] New feature - [ ] Documentation / docstrings - [ ] Tests - [ ] Other ## Checklist - [x] I've run the latest [black](https://github.com/psf/black) with default args on new code. - [x] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate. - [x] I've added tests for new code. - [x] I accept that @willmcgugan may be pedantic in the code review. ## Description Previously cyclic references were only handled for container and dataclass types, but not namedtuple, attrs, or custom types. This fixes that, and expands the tests to cover these cases.
https://api.github.com/repos/Textualize/rich/pulls/2524
2022-09-14T20:52:03Z
2022-09-20T10:16:20Z
2022-09-20T10:16:20Z
2022-09-20T10:16:21Z
2,226
Textualize/rich
48,002
Fix inconsistent exception type in response.json() method
diff --git a/HISTORY.md b/HISTORY.md index 59e4a9f707..ccf4e17400 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -4,7 +4,12 @@ Release History dev --- -- \[Short description of non-trivial change.\] +- \[Short description of non-trivial change.\] + +- Added a `requests.exceptions.JSONDecodeError` to decrease inconsistencies + in the library. This gets raised in the `response.json()` method, and is + backwards compatible as it inherits from previously thrown exceptions. + Can be caught from `requests.exceptions.RequestException` as well. 2.26.0 (2021-07-13) ------------------- diff --git a/docs/user/quickstart.rst b/docs/user/quickstart.rst index b4649f00d5..73d0b2931a 100644 --- a/docs/user/quickstart.rst +++ b/docs/user/quickstart.rst @@ -153,9 +153,9 @@ There's also a builtin JSON decoder, in case you're dealing with JSON data:: In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, -attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is -installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or -``json.JSONDecodeError`` on Python 3. +attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception +provides interoperability for multiple exceptions that may be thrown by different +python versions and json serialization libraries. It should be noted that the success of the call to ``r.json()`` does **not** indicate the success of the response. Some servers may return a JSON object in a diff --git a/requests/__init__.py b/requests/__init__.py index 0ac7713b81..53a5b42af6 100644 --- a/requests/__init__.py +++ b/requests/__init__.py @@ -139,7 +139,7 @@ def _check_cryptography(cryptography_version): from .exceptions import ( RequestException, Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError, - FileModeWarning, ConnectTimeout, ReadTimeout + FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError ) # Set default logging handler to avoid "No handler found" warnings. diff --git a/requests/compat.py b/requests/compat.py index 0b14f5015c..029ae62ac3 100644 --- a/requests/compat.py +++ b/requests/compat.py @@ -28,8 +28,10 @@ #: Python 3.x? is_py3 = (_ver[0] == 3) +has_simplejson = False try: import simplejson as json + has_simplejson = True except ImportError: import json @@ -49,13 +51,13 @@ # Keep OrderedDict for backwards compatibility. from collections import Callable, Mapping, MutableMapping, OrderedDict - builtin_str = str bytes = str str = unicode basestring = basestring numeric_types = (int, long, float) integer_types = (int, long) + JSONDecodeError = ValueError elif is_py3: from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag @@ -66,6 +68,10 @@ # Keep OrderedDict for backwards compatibility. from collections import OrderedDict from collections.abc import Callable, Mapping, MutableMapping + if has_simplejson: + from simplejson import JSONDecodeError + else: + from json import JSONDecodeError builtin_str = str str = str diff --git a/requests/exceptions.py b/requests/exceptions.py index c412ec9868..957e31f384 100644 --- a/requests/exceptions.py +++ b/requests/exceptions.py @@ -8,6 +8,8 @@ """ from urllib3.exceptions import HTTPError as BaseHTTPError +from .compat import JSONDecodeError as CompatJSONDecodeError + class RequestException(IOError): """There was an ambiguous exception that occurred while handling your @@ -29,6 +31,10 @@ class InvalidJSONError(RequestException): """A JSON error occurred.""" +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): + """Couldn't decode the text into json""" + + class HTTPError(RequestException): """An HTTP error occurred.""" diff --git a/requests/models.py b/requests/models.py index aa6fb86e4e..e7d292d580 100644 --- a/requests/models.py +++ b/requests/models.py @@ -29,7 +29,9 @@ from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, - ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError) + ContentDecodingError, ConnectionError, StreamConsumedError, + InvalidJSONError) +from .exceptions import JSONDecodeError as RequestsJSONDecodeError from ._internal_utils import to_native_string, unicode_is_ascii from .utils import ( guess_filename, get_auth_from_url, requote_uri, @@ -38,7 +40,7 @@ from .compat import ( Callable, Mapping, cookielib, urlunparse, urlsplit, urlencode, str, bytes, - is_py2, chardet, builtin_str, basestring) + is_py2, chardet, builtin_str, basestring, JSONDecodeError) from .compat import json as complexjson from .status_codes import codes @@ -468,9 +470,9 @@ def prepare_body(self, data, files, json=None): content_type = 'application/json' try: - body = complexjson.dumps(json, allow_nan=False) + body = complexjson.dumps(json, allow_nan=False) except ValueError as ve: - raise InvalidJSONError(ve, request=self) + raise InvalidJSONError(ve, request=self) if not isinstance(body, bytes): body = body.encode('utf-8') @@ -882,12 +884,8 @@ def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. - :raises simplejson.JSONDecodeError: If the response body does not - contain valid json and simplejson is installed. - :raises json.JSONDecodeError: If the response body does not contain - valid json and simplejson is not installed on Python 3. - :raises ValueError: If the response body does not contain valid - json and simplejson is not installed on Python 2. + :raises requests.exceptions.JSONDecodeError: If the response body does not + contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: @@ -907,7 +905,16 @@ def json(self, **kwargs): # and the server didn't bother to tell us what codec *was* # used. pass - return complexjson.loads(self.text, **kwargs) + + try: + return complexjson.loads(self.text, **kwargs) + except JSONDecodeError as e: + # Catch JSON-related errors and raise as requests.JSONDecodeError + # This aliases json.JSONDecodeError and simplejson.JSONDecodeError + if is_py2: # e is a ValueError + raise RequestsJSONDecodeError(e.message) + else: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) @property def links(self): diff --git a/tests/test_requests.py b/tests/test_requests.py index b77cba007d..b6d97dd9f4 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -2570,4 +2570,9 @@ def test_parameters_for_nonstandard_schemes(self, input, params, expected): def test_post_json_nan(self, httpbin): data = {"foo": float("nan")} with pytest.raises(requests.exceptions.InvalidJSONError): - r = requests.post(httpbin('post'), json=data) \ No newline at end of file + r = requests.post(httpbin('post'), json=data) + + def test_json_decode_compatibility(self, httpbin): + r = requests.get(httpbin('bytes/20')) + with pytest.raises(requests.exceptions.JSONDecodeError): + r.json() \ No newline at end of file
## Summary Fixes the inconsistency of errors thrown in the `response.json()` method in `models.py`, while preserving backwards compatibility. ### What we used to have Depending on whether or not `simplejson` was installed in the user's library, and whether the user was running Python 3+ versus Python 2, a different exception would get thrown when there was an issue with decoding response text as JSON. If `simplejson` was installed, `simplejson.JSONDecodeError` would get thrown. If not, `json.JSONDecodeError` would get thrown for Python 3+ users, and `ValueError` for Python 2 users. Thus, depending on the scenario, users would find themselves having to catch either `simplejson.JSONDecodeError`, `json.JSONDecodeError`, or `ValueError` in the case of the `response.json()` method failing. This inconsistency is not ideal. ### What we have now There is now one error class in `exceptions.py` that will represent all errors that can be thrown or caught in the `response.json()` method: `requests.JSONDecodeError`. All `simplejson` functionality was replaced with `json` functionality, but the new error type aliases both `json.JSONDecodeError` and `simplejson.JSONDecodeError`. If `simplejson` is not installed, its `JSONDecodError` is replaced with a plain `Exception` when aliased. If the user is running Python 3+, `json.JSONDecodeError` is aliased, but if the user is running Python 2, that is replaced with `ValueError` when aliased, as the `JSONDecodeError` was not previously a part of the `json` library. Now, all five error types, `json.JSONDecodeError`, `simplejson.JSONDecodeError`, `ValueError`, and `requests.JSONDecodeError` and its parent class `requests.RequestException`, will be caught from the `requests.JSONDecodeError` that will be raised. Fixes #5794 @sigmavirus24
https://api.github.com/repos/psf/requests/pulls/5856
2021-07-03T21:08:32Z
2021-07-26T15:56:44Z
2021-07-26T15:56:44Z
2021-12-01T08:00:28Z
1,980
psf/requests
32,581
DOC add example to make_ spd_matrix
diff --git a/sklearn/datasets/_samples_generator.py b/sklearn/datasets/_samples_generator.py index dd170942eb224..0f2c1b517d1eb 100644 --- a/sklearn/datasets/_samples_generator.py +++ b/sklearn/datasets/_samples_generator.py @@ -1603,6 +1603,13 @@ def make_spd_matrix(n_dim, *, random_state=None): See Also -------- make_sparse_spd_matrix: Generate a sparse symmetric definite positive matrix. + + Examples + -------- + >>> from sklearn.datasets import make_spd_matrix + >>> make_spd_matrix(n_dim=2, random_state=42) + array([[2.09..., 0.34...], + [0.34..., 0.21...]]) """ generator = check_random_state(random_state)
#### Reference Issues/PRs Contributes to #27982 #### What does this implement/fix? Explain your changes. It adds an example to the docstring of sklearn.datasets.make_spd_matrix
https://api.github.com/repos/scikit-learn/scikit-learn/pulls/28170
2024-01-18T16:00:49Z
2024-01-22T13:51:28Z
2024-01-22T13:51:28Z
2024-01-27T10:51:59Z
192
scikit-learn/scikit-learn
46,060
Update blns.json
diff --git a/blns.json b/blns.json index fc77c76..c935bcc 100644 --- a/blns.json +++ b/blns.json @@ -389,6 +389,8 @@ "<<SCRIPT>alert(\"XSS\");//<</SCRIPT>", "<SCRIPT SRC=http://ha.ckers.org/xss.js?< B >", "<SCRIPT SRC=//ha.ckers.org/.j>", + "'); alert('pwned'); console.log('", + "\"); alert('pwned'); console.log(\"", "<IMG SRC=\"javascript:alert('XSS')\"", "<iframe src=http://ha.ckers.org/scriptlet.html <", "\\\";alert('XSS');//",
those two strings is naughty if you want to prepare javascript in jsp
https://api.github.com/repos/minimaxir/big-list-of-naughty-strings/pulls/69
2015-09-04T12:18:05Z
2015-09-06T01:52:45Z
2015-09-06T01:52:45Z
2015-09-06T01:52:45Z
164
minimaxir/big-list-of-naughty-strings
4,831
Renewer errors
diff --git a/letsencrypt/errors.py b/letsencrypt/errors.py index 82331fcedd8..b15728c39f5 100644 --- a/letsencrypt/errors.py +++ b/letsencrypt/errors.py @@ -5,10 +5,6 @@ class Error(Exception): """Generic Let's Encrypt client error.""" -class SubprocessError(Error): - """Subprocess handling error.""" - - class AccountStorageError(Error): """Generic `.AccountStorage` error.""" @@ -21,6 +17,14 @@ class ReverterError(Error): """Let's Encrypt Reverter error.""" +class SubprocessError(Error): + """Subprocess handling error.""" + + +class CertStorageError(Error): + """Generic `.CertStorage` error.""" + + # Auth Handler Errors class AuthorizationError(Error): """Authorization error.""" diff --git a/letsencrypt/renewer.py b/letsencrypt/renewer.py index bc527733332..e26e8742bb8 100644 --- a/letsencrypt/renewer.py +++ b/letsencrypt/renewer.py @@ -20,6 +20,7 @@ from letsencrypt import cli from letsencrypt import client from letsencrypt import crypto_util +from letsencrypt import errors from letsencrypt import notify from letsencrypt import storage @@ -164,7 +165,7 @@ def main(config=None, args=sys.argv[1:]): # dramatically improve performance for large deployments # where autorenewal is widely turned off. cert = storage.RenewableCert(rc_config, cli_config=cli_config) - except ValueError: + except errors.CertStorageError: # This indicates an invalid renewal configuration file, such # as one missing a required parameter (in the future, perhaps # also one that is internally inconsistent or is missing a diff --git a/letsencrypt/storage.py b/letsencrypt/storage.py index 4ad1216e6cb..431f56aff4b 100644 --- a/letsencrypt/storage.py +++ b/letsencrypt/storage.py @@ -11,6 +11,7 @@ import pyrfc3339 from letsencrypt import constants +from letsencrypt import errors from letsencrypt import le_util ALL_FOUR = ("cert", "privkey", "chain", "fullchain") @@ -90,7 +91,7 @@ def __init__(self, configfile, config_opts=None, cli_config=None): renewal config file. :param .RenewerConfiguration cli_config: - :raises ValueError: if the configuration file's name didn't end + :raises .CertStorageError: if the configuration file's name didn't end in ".conf", or the file is missing or broken. :raises TypeError: if the provided renewal configuration isn't a ConfigObj object. @@ -99,7 +100,8 @@ def __init__(self, configfile, config_opts=None, cli_config=None): self.cli_config = cli_config if isinstance(configfile, configobj.ConfigObj): if not os.path.basename(configfile.filename).endswith(".conf"): - raise ValueError("renewal config file name must end in .conf") + raise errors.CertStorageError( + "renewal config file name must end in .conf") self.lineagename = os.path.basename( configfile.filename)[:-len(".conf")] else: @@ -117,8 +119,9 @@ def __init__(self, configfile, config_opts=None, cli_config=None): self.configuration.merge(self.configfile) if not all(x in self.configuration for x in ALL_FOUR): - raise ValueError("renewal config file {0} is missing a required " - "file reference".format(configfile)) + raise errors.CertStorageError( + "renewal config file {0} is missing a required " + "file reference".format(configfile)) self.cert = self.configuration["cert"] self.privkey = self.configuration["privkey"] @@ -213,7 +216,7 @@ def current_target(self, kind): """ if kind not in ALL_FOUR: - raise ValueError("unknown kind of item") + raise errors.CertStorageError("unknown kind of item") link = getattr(self, kind) if not os.path.exists(link): return None @@ -236,7 +239,7 @@ def current_version(self, kind): """ if kind not in ALL_FOUR: - raise ValueError("unknown kind of item") + raise errors.CertStorageError("unknown kind of item") pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind)) target = self.current_target(kind) if target is None or not os.path.exists(target): @@ -263,12 +266,12 @@ def version(self, kind, version): """ if kind not in ALL_FOUR: - raise ValueError("unknown kind of item") + raise errors.CertStorageError("unknown kind of item") where = os.path.dirname(self.current_target(kind)) return os.path.join(where, "{0}{1}.pem".format(kind, version)) def available_versions(self, kind): - """Which lternative versions of the specified kind of item exist? + """Which alternative versions of the specified kind of item exist? The archive directory where the current version is stored is consulted to obtain the list of alternatives. @@ -281,7 +284,7 @@ def available_versions(self, kind): """ if kind not in ALL_FOUR: - raise ValueError("unknown kind of item") + raise errors.CertStorageError("unknown kind of item") where = os.path.dirname(self.current_target(kind)) files = os.listdir(where) pattern = re.compile(r"^{0}([0-9]+)\.pem$".format(kind)) @@ -308,7 +311,7 @@ def latest_common_version(self): :rtype: int """ - # TODO: this can raise ValueError if there is no version overlap + # TODO: this can raise CertStorageError if there is no version overlap # (it should probably return None instead) # TODO: this can raise a spurious AttributeError if the current # link for any kind is missing (it should probably return None) @@ -355,7 +358,7 @@ def update_link_to(self, kind, version): """ if kind not in ALL_FOUR: - raise ValueError("unknown kind of item") + raise errors.CertStorageError("unknown kind of item") link = getattr(self, kind) filename = "{0}{1}.pem".format(kind, version) # Relative rather than absolute target directory @@ -550,7 +553,8 @@ def new_lineage(cls, lineagename, cert, privkey, chain, config_file, config_filename = le_util.unique_lineage_name( cli_config.renewal_configs_dir, lineagename) if not config_filename.endswith(".conf"): - raise ValueError("renewal config file name must end in .conf") + raise errors.CertStorageError( + "renewal config file name must end in .conf") # Determine where on disk everything will go # lineagename will now potentially be modified based on which @@ -559,9 +563,11 @@ def new_lineage(cls, lineagename, cert, privkey, chain, archive = os.path.join(cli_config.archive_dir, lineagename) live_dir = os.path.join(cli_config.live_dir, lineagename) if os.path.exists(archive): - raise ValueError("archive directory exists for " + lineagename) + raise errors.CertStorageError( + "archive directory exists for " + lineagename) if os.path.exists(live_dir): - raise ValueError("live directory exists for " + lineagename) + raise errors.CertStorageError( + "live directory exists for " + lineagename) os.mkdir(archive) os.mkdir(live_dir) relative_archive = os.path.join("..", "..", "archive", lineagename) diff --git a/letsencrypt/tests/renewer_test.py b/letsencrypt/tests/renewer_test.py index 65bfce314c1..1b58d9e0f13 100644 --- a/letsencrypt/tests/renewer_test.py +++ b/letsencrypt/tests/renewer_test.py @@ -10,6 +10,7 @@ import pytz from letsencrypt import configuration +from letsencrypt import errors from letsencrypt.storage import ALL_FOUR from letsencrypt.tests import test_util @@ -78,7 +79,8 @@ def test_renewal_bad_config(self): for kind in ALL_FOUR: config["cert"] = "nonexistent_" + kind + ".pem" config.filename = "nonexistent_sillyfile" - self.assertRaises(ValueError, storage.RenewableCert, config, defaults) + self.assertRaises( + errors.CertStorageError, storage.RenewableCert, config, defaults) self.assertRaises(TypeError, storage.RenewableCert, "fun", defaults) def test_renewal_incomplete_config(self): @@ -92,7 +94,8 @@ def test_renewal_incomplete_config(self): config["chain"] = "imaginary_chain.pem" config["fullchain"] = "imaginary_fullchain.pem" config.filename = "imaginary_config.conf" - self.assertRaises(ValueError, storage.RenewableCert, config, defaults) + self.assertRaises( + errors.CertStorageError, storage.RenewableCert, config, defaults) def test_consistent(self): # pylint: disable=too-many-statements oldcert = self.test_rc.cert @@ -481,11 +484,13 @@ def test_new_lineage(self): # Now trigger the detection of already existing files os.mkdir(os.path.join( self.cli_config.live_dir, "the-lineage.com-0002")) - self.assertRaises(ValueError, storage.RenewableCert.new_lineage, + self.assertRaises(errors.CertStorageError, + storage.RenewableCert.new_lineage, "the-lineage.com", "cert3", "privkey3", "chain3", None, self.defaults, self.cli_config) os.mkdir(os.path.join(self.cli_config.archive_dir, "other-example.com")) - self.assertRaises(ValueError, storage.RenewableCert.new_lineage, + self.assertRaises(errors.CertStorageError, + storage.RenewableCert.new_lineage, "other-example.com", "cert4", "privkey4", "chain4", None, self.defaults, self.cli_config) # Make sure it can accept renewal parameters @@ -518,20 +523,27 @@ def test_new_lineage_nonexistent_dirs(self): def test_invalid_config_filename(self, mock_uln): from letsencrypt import storage mock_uln.return_value = "this_does_not_end_with_dot_conf", "yikes" - self.assertRaises(ValueError, storage.RenewableCert.new_lineage, + self.assertRaises(errors.CertStorageError, + storage.RenewableCert.new_lineage, "example.com", "cert", "privkey", "chain", None, self.defaults, self.cli_config) def test_bad_kind(self): - self.assertRaises(ValueError, self.test_rc.current_target, "elephant") - self.assertRaises(ValueError, self.test_rc.current_version, "elephant") - self.assertRaises(ValueError, self.test_rc.version, "elephant", 17) - self.assertRaises(ValueError, self.test_rc.available_versions, - "elephant") - self.assertRaises(ValueError, self.test_rc.newest_available_version, - "elephant") - self.assertRaises(ValueError, self.test_rc.update_link_to, - "elephant", 17) + self.assertRaises( + errors.CertStorageError, self.test_rc.current_target, "elephant") + self.assertRaises( + errors.CertStorageError, self.test_rc.current_version, "elephant") + self.assertRaises( + errors.CertStorageError, self.test_rc.version, "elephant", 17) + self.assertRaises( + errors.CertStorageError, + self.test_rc.available_versions, "elephant") + self.assertRaises( + errors.CertStorageError, + self.test_rc.newest_available_version, "elephant") + self.assertRaises( + errors.CertStorageError, + self.test_rc.update_link_to, "elephant", 17) def test_ocsp_revoked(self): # XXX: This is currently hardcoded to False due to a lack of an @@ -651,7 +663,7 @@ def test_bad_config_file(self): f.write("incomplete = configfile\n") renewer.main(self.defaults, args=[ '--config-dir', self.cli_config.config_dir]) - # The ValueError is caught inside and nothing happens. + # The errors.CertStorageError is caught inside and nothing happens. if __name__ == "__main__":
Replace Value Errors within storage.py with a more appropriate CertStorageError.
https://api.github.com/repos/certbot/certbot/pulls/650
2015-08-04T22:00:17Z
2015-08-04T22:50:09Z
2015-08-04T22:50:09Z
2016-05-06T19:22:13Z
2,875
certbot/certbot
958
Fixed comment in example code of F.54
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index b5a98b25e..1d8730505 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -3835,9 +3835,9 @@ It's confusing. Writing `[=]` in a member function appears to capture by value, // [=,this] and [&,this] are not much better, and confusing x = 42; - lambda(); // calls use(42); + lambda(); // calls use(0, 42); x = 43; - lambda(); // calls use(43); + lambda(); // calls use(0, 43); // ...
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1082
2017-11-17T14:28:46Z
2017-11-17T15:20:10Z
2017-11-17T15:20:10Z
2017-11-17T15:20:10Z
168
isocpp/CppCoreGuidelines
15,272
Fix check for Alpine Linux
diff --git a/localstack/utils/common.py b/localstack/utils/common.py index ee9cae06e9f3e..912ad777baad1 100644 --- a/localstack/utils/common.py +++ b/localstack/utils/common.py @@ -637,7 +637,7 @@ def is_linux(): def is_alpine(): try: - if not os.path.exists('cat /etc/issue'): + if not os.path.exists('/etc/issue'): return False out = to_str(subprocess.check_output('cat /etc/issue', shell=True)) return 'Alpine' in out
Fix check for Alpine Linux
https://api.github.com/repos/localstack/localstack/pulls/1826
2019-12-04T21:58:41Z
2019-12-04T21:58:49Z
2019-12-04T21:58:49Z
2019-12-04T21:58:53Z
135
localstack/localstack
28,830
Tensorboard model visualization bug fix
diff --git a/train.py b/train.py index 1f2b467e732..82043b7fff3 100644 --- a/train.py +++ b/train.py @@ -332,7 +332,7 @@ def train(hyp, opt, device, tb_writer=None): Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() # if tb_writer: # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch) - # tb_writer.add_graph(model, imgs) # add model to tensorboard + # tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph elif plots and ni == 10 and wandb_logger.wandb: wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in save_dir.glob('train*.jpg') if x.exists()]})
This fix should allow for visualizing YOLOv5 model graphs correctly in Tensorboard by uncommenting line 335 in train.py: ```python if tb_writer: tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph ``` The problem identified in #2284 was that the detect() layer checks the input size to adapt the grid if required, and tracing does not seem to like this shape check (even if the shape is fine and no grid recomputation is required). The following will warn: https://github.com/ultralytics/yolov5/blob/0cae7576a9241110157cd154fc2237e703c2719e/train.py#L335 Solution is below. This is a YOLOv5s model displayed in TensorBoard. You can see the Detect() layer merging the 3 layers into a single output for example, and everything appears to work and visualize correctly. ```python tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) ``` <img width="893" alt="Screenshot 2021-04-11 at 01 10 09" src="https://user-images.githubusercontent.com/26833433/114286928-349bd600-9a63-11eb-941f-7139ee6cd602.png"> ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Optimized TensorBoard model graph logging with JIT tracing. ### 📊 Key Changes - Commented-out code for adding the unoptimized model graph to TensorBoard has been replaced with JIT-traced model graph. - This change is in the `train.py` file, specifically in the model training loop. ### 🎯 Purpose & Impact - 🚀 **Purpose**: To enable more efficient and possibly more accurate graph logging in TensorBoard. - 📈 **Impact**: Users gain the ability to visualize a traced version of their model's graph, which might be faster and more optimized than directly logging the model. - 🧑‍💻 **For Developers**: This could help with better understanding model performance and optimizations applied by JIT. - 🔄 **For Users**: Insights from detailed visualizations might help in tweaking the model and potentially achieving better results.
https://api.github.com/repos/ultralytics/yolov5/pulls/2758
2021-04-10T23:31:04Z
2021-04-10T23:33:55Z
2021-04-10T23:33:55Z
2024-01-19T18:50:02Z
219
ultralytics/yolov5
25,100
[Java] Re-enable remaining skipped Java test cases
diff --git a/java/test/src/main/java/io/ray/test/ExitActorTest.java b/java/test/src/main/java/io/ray/test/ExitActorTest.java index a1c40e2ac8a1c..279af55c05e59 100644 --- a/java/test/src/main/java/io/ray/test/ExitActorTest.java +++ b/java/test/src/main/java/io/ray/test/ExitActorTest.java @@ -15,9 +15,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -@Test( - groups = {"cluster"}, - enabled = false) +@Test(groups = {"cluster"}) public class ExitActorTest extends BaseTest { private static class ExitingActor { diff --git a/java/test/src/main/java/io/ray/test/MultiDriverTest.java b/java/test/src/main/java/io/ray/test/MultiDriverTest.java index 3feb981927c06..9c781f56283f9 100644 --- a/java/test/src/main/java/io/ray/test/MultiDriverTest.java +++ b/java/test/src/main/java/io/ray/test/MultiDriverTest.java @@ -17,9 +17,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -@Test( - groups = {"cluster"}, - enabled = false) +@Test(groups = {"cluster"}) public class MultiDriverTest extends BaseTest { private static final int DRIVER_COUNT = 10; diff --git a/java/test/src/main/java/io/ray/test/PlacementGroupTest.java b/java/test/src/main/java/io/ray/test/PlacementGroupTest.java index 89d1fab694523..655479bd43f97 100644 --- a/java/test/src/main/java/io/ray/test/PlacementGroupTest.java +++ b/java/test/src/main/java/io/ray/test/PlacementGroupTest.java @@ -32,7 +32,7 @@ public int getValue() { // It's not comprehensive to test all placement group test cases. public void testCreateAndCallActor() { PlacementGroup placementGroup = PlacementGroupTestUtils.createSimpleGroup(); - Assert.assertTrue(placementGroup.wait(10)); + Assert.assertTrue(placementGroup.wait(60)); Assert.assertEquals(placementGroup.getName(), "unnamed_group"); // Test creating an actor from a constructor. @@ -53,8 +53,8 @@ public void testGetPlacementGroup() { PlacementGroup secondPlacementGroup = PlacementGroupTestUtils.createNameSpecifiedSimpleGroup( "CPU", 1, PlacementStrategy.PACK, 1.0, "second_placement_group"); - Assert.assertTrue(firstPlacementGroup.wait(10)); - Assert.assertTrue(secondPlacementGroup.wait(10)); + Assert.assertTrue(firstPlacementGroup.wait(60)); + Assert.assertTrue(secondPlacementGroup.wait(60)); PlacementGroup firstPlacementGroupRes = Ray.getPlacementGroup((firstPlacementGroup).getId()); PlacementGroup secondPlacementGroupRes = Ray.getPlacementGroup((secondPlacementGroup).getId()); @@ -83,16 +83,17 @@ public void testGetPlacementGroup() { Assert.assertEquals(placementGroupRes.getStrategy(), expectPlacementGroup.getStrategy()); } - @Test( - groups = {"cluster"}, - enabled = false) + @Test(groups = {"cluster"}) public void testRemovePlacementGroup() { - PlacementGroupTestUtils.createNameSpecifiedSimpleGroup( - "CPU", 1, PlacementStrategy.PACK, 1.0, "first_placement_group"); + PlacementGroup firstPlacementGroup = + PlacementGroupTestUtils.createNameSpecifiedSimpleGroup( + "CPU", 1, PlacementStrategy.PACK, 1.0, "first_placement_group"); PlacementGroup secondPlacementGroup = PlacementGroupTestUtils.createNameSpecifiedSimpleGroup( "CPU", 1, PlacementStrategy.PACK, 1.0, "second_placement_group"); + Assert.assertTrue(firstPlacementGroup.wait(60)); + Assert.assertTrue(secondPlacementGroup.wait(60)); List<PlacementGroup> allPlacementGroup = Ray.getAllPlacementGroups(); Assert.assertEquals(allPlacementGroup.size(), 2); @@ -114,6 +115,7 @@ public void testRemovePlacementGroup() { public void testCheckBundleIndex() { PlacementGroup placementGroup = PlacementGroupTestUtils.createSimpleGroup(); + Assert.assertTrue(placementGroup.wait(60)); int exceptionCount = 0; try { diff --git a/python/ray/tests/test_placement_group.py b/python/ray/tests/test_placement_group.py index 024ff6c5557a7..a311189a380f6 100644 --- a/python/ray/tests/test_placement_group.py +++ b/python/ray/tests/test_placement_group.py @@ -312,6 +312,7 @@ def test_remove_placement_group(ray_start_cluster): # Creating a placement group as soon as it is # created should work. placement_group = ray.util.placement_group([{"CPU": 2}, {"CPU": 2}]) + assert placement_group.wait(10) ray.util.remove_placement_group(placement_group) def is_placement_group_removed(): @@ -324,6 +325,7 @@ def is_placement_group_removed(): # # Now let's create a placement group. placement_group = ray.util.placement_group([{"CPU": 2}, {"CPU": 2}]) + assert placement_group.wait(10) # Create an actor that occupies resources. @ray.remote(num_cpus=2)
<!-- Thank you for your contribution! Please review https://github.com/ray-project/ray/blob/master/CONTRIBUTING.rst before opening a pull request. --> <!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. --> ## Why are these changes needed? Re-enable `ExitActorTest`, `MultiDriverTest`. Fix `PlacementGroupTest` (by @clay4444). One remaining issue: Raylet fails to start occasionally ([CI log](https://travis-ci.com/github/ray-project/ray/jobs/481590843)). The root cause is that the grpc server port of node manager was occupied by another process. This is a known issue (see #8254 and #9615). However the error message is unclear, I'll address it in another PR. ## Related issue number Closes #13714 ## Checks - [ ] I've run `scripts/format.sh` to lint the changes in this PR. - [ ] I've included any doc changes needed for https://docs.ray.io/en/master/. - [ ] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [ ] Unit tests - [ ] Release tests - [ ] This PR is not tested :(
https://api.github.com/repos/ray-project/ray/pulls/13979
2021-02-08T10:25:48Z
2021-02-19T02:57:28Z
2021-02-19T02:57:28Z
2021-02-19T02:57:30Z
1,183
ray-project/ray
19,045
Fixed #33508 -- Fixed DatabaseFeatures.supports_index_column_ordering on MariaDB 10.8+.
diff --git a/django/db/backends/mysql/features.py b/django/db/backends/mysql/features.py index f5b9ef9b557be..1996208b46402 100644 --- a/django/db/backends/mysql/features.py +++ b/django/db/backends/mysql/features.py @@ -316,10 +316,9 @@ def can_introspect_json_field(self): @cached_property def supports_index_column_ordering(self): - return ( - not self.connection.mysql_is_mariadb - and self.connection.mysql_version >= (8, 0, 1) - ) + if self.connection.mysql_is_mariadb: + return self.connection.mysql_version >= (10, 8) + return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self):
ticket-33508
https://api.github.com/repos/django/django/pulls/15452
2022-02-21T15:34:32Z
2022-02-26T15:25:22Z
2022-02-26T15:25:22Z
2022-02-28T04:52:15Z
190
django/django
51,419
Fix: Exception in thread & KeyError: 'displayName'
diff --git a/gpt4free/quora/api.py b/gpt4free/quora/api.py index 9e3c0b91fe..6402148940 100644 --- a/gpt4free/quora/api.py +++ b/gpt4free/quora/api.py @@ -168,9 +168,9 @@ def get_bots(self, download_next_data=True): else: next_data = self.next_data - if not "availableBots" in self.viewer: + if not "viewerBotList" in self.viewer: raise RuntimeError("Invalid token or no bots are available.") - bot_list = self.viewer["availableBots"] + bot_list = self.viewer["viewerBotList"] threads = [] bots = {}
This was due to a change with Poe. They changed the availableBots key to viewerBotList in the viewer data.
https://api.github.com/repos/xtekky/gpt4free/pulls/636
2023-06-01T19:19:02Z
2023-06-03T22:28:23Z
2023-06-03T22:28:23Z
2023-06-03T22:28:23Z
167
xtekky/gpt4free
38,157
Added MarkDown formatting support to examples/babi_memnn.py
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 6a2c733bef0..e6b74030bc7 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -70,3 +70,4 @@ nav: - Examples: - Addition RNN: examples/addition_rnn.md - Baby RNN: examples/babi_rnn.md + - Baby MemNN: examples/babi_memnn.md diff --git a/examples/babi_memnn.py b/examples/babi_memnn.py index cc16acd258c..fa85e855a53 100644 --- a/examples/babi_memnn.py +++ b/examples/babi_memnn.py @@ -1,14 +1,14 @@ -'''Trains a memory network on the bAbI dataset. +''' +#Trains a memory network on the bAbI dataset. References: - Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush, - "Towards AI-Complete Question Answering: A Set of Prerequisite Toy Tasks", - http://arxiv.org/abs/1502.05698 + ["Towards AI-Complete Question Answering: + A Set of Prerequisite Toy Tasks"](http://arxiv.org/abs/1502.05698) - Sainbayar Sukhbaatar, Arthur Szlam, Jason Weston, Rob Fergus, - "End-To-End Memory Networks", - http://arxiv.org/abs/1503.08895 + ["End-To-End Memory Networks"](http://arxiv.org/abs/1503.08895) Reaches 98.6% accuracy on task 'single_supporting_fact_10k' after 120 epochs. Time per epoch: 3s on CPU (core i7).
<!-- Please make sure you've read and understood our contributing guidelines; https://github.com/keras-team/keras/blob/master/CONTRIBUTING.md --> ### Summary This pull request adds MarkDown formatting to ```examples/babi_memnn.py```. ### Related Issues https://github.com/keras-team/keras/issues/12219 ### PR Overview - [ ] This PR requires new unit tests [y/n] (make sure tests are included) - [ ] This PR requires to update the documentation [y/n] (make sure the docs are up-to-date) - [x] This PR is backwards compatible [y/n] - [ ] This PR changes the current API [y/n] (all API changes need to be approved by fchollet)
https://api.github.com/repos/keras-team/keras/pulls/12221
2019-02-07T11:09:22Z
2019-02-07T17:35:11Z
2019-02-07T17:35:11Z
2019-02-07T17:35:11Z
407
keras-team/keras
46,976
Remove hamming option from string distance tests
diff --git a/libs/langchain/tests/unit_tests/evaluation/string_distance/test_base.py b/libs/langchain/tests/unit_tests/evaluation/string_distance/test_base.py index eff632f454f17e..70dc7aaa789851 100644 --- a/libs/langchain/tests/unit_tests/evaluation/string_distance/test_base.py +++ b/libs/langchain/tests/unit_tests/evaluation/string_distance/test_base.py @@ -56,8 +56,13 @@ async def test_zero_distance_pairwise_async(distance: StringDistance) -> None: assert result["score"] == 0 +valid_distances = [ + distance for distance in StringDistance if distance != StringDistance.HAMMING +] + + @pytest.mark.requires("rapidfuzz") -@pytest.mark.parametrize("distance", list(StringDistance)) +@pytest.mark.parametrize("distance", valid_distances) @pytest.mark.parametrize("normalize_score", [True, False]) def test_non_zero_distance(distance: StringDistance, normalize_score: bool) -> None: eval_chain = StringDistanceEvalChain( @@ -74,7 +79,7 @@ def test_non_zero_distance(distance: StringDistance, normalize_score: bool) -> N @pytest.mark.asyncio @pytest.mark.requires("rapidfuzz") -@pytest.mark.parametrize("distance", list(StringDistance)) +@pytest.mark.parametrize("distance", valid_distances) async def test_non_zero_distance_async(distance: StringDistance) -> None: eval_chain = StringDistanceEvalChain(distance=distance) prediction = "I like to eat apples." @@ -87,7 +92,7 @@ async def test_non_zero_distance_async(distance: StringDistance) -> None: @pytest.mark.requires("rapidfuzz") -@pytest.mark.parametrize("distance", list(StringDistance)) +@pytest.mark.parametrize("distance", valid_distances) def test_non_zero_distance_pairwise(distance: StringDistance) -> None: eval_chain = PairwiseStringDistanceEvalChain(distance=distance) prediction = "I like to eat apples." @@ -101,7 +106,7 @@ def test_non_zero_distance_pairwise(distance: StringDistance) -> None: @pytest.mark.asyncio @pytest.mark.requires("rapidfuzz") -@pytest.mark.parametrize("distance", list(StringDistance)) +@pytest.mark.parametrize("distance", valid_distances) async def test_non_zero_distance_pairwise_async(distance: StringDistance) -> None: eval_chain = PairwiseStringDistanceEvalChain(distance=distance) prediction = "I like to eat apples."
Description: We should not test Hamming string distance for strings that are not equal length, since this is not defined. Removing hamming distance tests for unequal string distances.
https://api.github.com/repos/langchain-ai/langchain/pulls/9882
2023-08-28T21:16:32Z
2023-09-11T20:50:20Z
2023-09-11T20:50:20Z
2023-09-11T21:02:08Z
524
langchain-ai/langchain
43,565
Update CONTRIBUTING.md
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9a03948a724870..e639d827bf8be4 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,7 +9,7 @@ to contributions, whether they be in the form of new features, improved infra, b ### 👩‍💻 Contributing Code To contribute to this project, please follow a ["fork and pull request"](https://docs.github.com/en/get-started/quickstart/contributing-to-projects) workflow. -Please do not try to push directly to this repo unless you are maintainer. +Please do not try to push directly to this repo unless you are a maintainer. Please follow the checked-in pull request template when opening pull requests. Note related issues and tag relevant maintainers. @@ -21,7 +21,7 @@ It's essential that we maintain great documentation and testing. If you: - Fix a bug - Add a relevant unit or integration test when possible. These live in `tests/unit_tests` and `tests/integration_tests`. - Make an improvement - - Update any affected example notebooks and documentation. These lives in `docs`. + - Update any affected example notebooks and documentation. These live in `docs`. - Update unit and integration tests when relevant. - Add a feature - Add a demo notebook in `docs/modules`. @@ -43,7 +43,7 @@ If you start working on an issue, please assign it to yourself. If you are adding an issue, please try to keep it focused on a single, modular bug/improvement/feature. If two issues are related, or blocking, please link them rather than combining them. -We will try to keep these issues as up to date as possible, though +We will try to keep these issues as up-to-date as possible, though with the rapid rate of development in this field some may get out of date. If you notice this happening, please let us know. @@ -63,7 +63,7 @@ we do not want these to get in the way of getting good code into the codebase. This project uses [Poetry](https://python-poetry.org/) v1.5.1 as a dependency manager. Check out Poetry's [documentation on how to install it](https://python-poetry.org/docs/#installation) on your system before proceeding. -❗Note: If you use `Conda` or `Pyenv` as your environment / package manager, avoid dependency conflicts by doing the following first: +❗Note: If you use `Conda` or `Pyenv` as your environment/package manager, avoid dependency conflicts by doing the following first: 1. *Before installing Poetry*, create and activate a new Conda env (e.g. `conda create -n langchain python=3.9`) 2. Install Poetry v1.5.1 (see above) 3. Tell Poetry to use the virtualenv python environment (`poetry config virtualenvs.prefer-active-python true`) @@ -174,7 +174,7 @@ Langchain relies heavily on optional dependencies to keep the Langchain package If you're adding a new dependency to Langchain, assume that it will be an optional dependency, and that most users won't have it installed. -Users that do not have the dependency installed should be able to **import** your code without +Users who do not have the dependency installed should be able to **import** your code without any side effects (no warnings, no errors, no exceptions). To introduce the dependency to the pyproject.toml file correctly, please do the following: @@ -188,7 +188,7 @@ To introduce the dependency to the pyproject.toml file correctly, please do the ```bash poetry lock --no-update ``` -4. Add a unit test that the very least attempts to import the new code. Ideally the unit +4. Add a unit test that the very least attempts to import the new code. Ideally, the unit test makes use of lightweight fixtures to test the logic of the code. 5. Please use the `@pytest.mark.requires(package_name)` decorator for any tests that require the dependency. @@ -238,7 +238,7 @@ If you add support for a new external API, please add a new integration test. ### Adding a Jupyter Notebook -If you are adding a Jupyter notebook example, you'll want to install the optional `dev` dependencies. +If you are adding a Jupyter Notebook example, you'll want to install the optional `dev` dependencies. To install dev dependencies:
fiixed few typos
https://api.github.com/repos/langchain-ai/langchain/pulls/10700
2023-09-17T11:29:33Z
2023-09-17T23:35:18Z
2023-09-17T23:35:18Z
2023-09-17T23:35:18Z
1,011
langchain-ai/langchain
43,137
Fix timeout in create_async
diff --git a/g4f/Provider/AiAsk.py b/g4f/Provider/AiAsk.py index 0a44af3ed2..870dd1ab43 100644 --- a/g4f/Provider/AiAsk.py +++ b/g4f/Provider/AiAsk.py @@ -1,11 +1,9 @@ from __future__ import annotations -from aiohttp import ClientSession - +from aiohttp import ClientSession, ClientTimeout from ..typing import AsyncGenerator from .base_provider import AsyncGeneratorProvider - class AiAsk(AsyncGeneratorProvider): url = "https://e.aiask.me" supports_gpt_35_turbo = True @@ -24,7 +22,7 @@ async def create_async_generator( "origin": cls.url, "referer": f"{cls.url}/chat", } - async with ClientSession(headers=headers, timeout=timeout) as session: + async with ClientSession(headers=headers, timeout=ClientTimeout(timeout)) as session: data = { "continuous": True, "id": "fRMSQtuHl91A4De9cCvKD", diff --git a/g4f/Provider/Aichat.py b/g4f/Provider/Aichat.py index 4149676595..2e141b535f 100644 --- a/g4f/Provider/Aichat.py +++ b/g4f/Provider/Aichat.py @@ -1,6 +1,6 @@ from __future__ import annotations -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout from .base_provider import AsyncProvider, format_prompt @@ -34,7 +34,7 @@ async def create_async( "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36", } async with ClientSession( - headers=headers, timeout=timeout + headers=headers, timeout=ClientTimeout(timeout) ) as session: json_data = { "message": format_prompt(messages), diff --git a/g4f/Provider/Bing.py b/g4f/Provider/Bing.py index aa2db990b4..f4275a5f54 100644 --- a/g4f/Provider/Bing.py +++ b/g4f/Provider/Bing.py @@ -250,7 +250,7 @@ async def stream_generate( conversation = await create_conversation(session) try: async with session.ws_connect( - f'wss://sydney.bing.com/sydney/ChatHub?sec_access_token={urllib.parse.quote_plus(conversation.conversationSignature)}', + f'wss://sydney.bing.com/sydney/ChatHub', autoping=False, params={'sec_access_token': conversation.conversationSignature} ) as wss: diff --git a/g4f/Provider/ChatForAi.py b/g4f/Provider/ChatForAi.py index 47ac46f053..86b296396b 100644 --- a/g4f/Provider/ChatForAi.py +++ b/g4f/Provider/ChatForAi.py @@ -1,7 +1,5 @@ from __future__ import annotations -import time, hashlib - from ..typing import AsyncGenerator from ..requests import StreamSession from .base_provider import AsyncGeneratorProvider @@ -21,11 +19,9 @@ async def create_async_generator( **kwargs ) -> AsyncGenerator: async with StreamSession(impersonate="chrome107", timeout=timeout) as session: - conversation_id = f"id_{int(time.time())}" prompt = messages[-1]["content"] - timestamp = int(time.time()) data = { - "conversationId": conversation_id, + "conversationId": "temp", "conversationType": "chat_continuous", "botId": "chat_continuous", "globalSettings":{ @@ -39,8 +35,6 @@ async def create_async_generator( "botSettings": {}, "prompt": prompt, "messages": messages, - "sign": generate_signature(timestamp, conversation_id, prompt), - "timestamp": timestamp } async with session.post(f"{cls.url}/api/handle/provider-openai", json=data) as response: response.raise_for_status() @@ -56,8 +50,4 @@ def params(cls): ("stream", "bool"), ] param = ", ".join([": ".join(p) for p in params]) - return f"g4f.provider.{cls.__name__} supports: ({param})" - -def generate_signature(timestamp, id, prompt): - data = f"{timestamp}:{id}:{prompt}:6B46K4pt" - return hashlib.sha256(data.encode()).hexdigest() + return f"g4f.provider.{cls.__name__} supports: ({param})" \ No newline at end of file diff --git a/g4f/Provider/ChatgptAi.py b/g4f/Provider/ChatgptAi.py index 0ae0fa38b4..553a986032 100644 --- a/g4f/Provider/ChatgptAi.py +++ b/g4f/Provider/ChatgptAi.py @@ -1,7 +1,7 @@ from __future__ import annotations import re -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout from .base_provider import AsyncProvider, format_prompt @@ -40,7 +40,7 @@ async def create_async( "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", } async with ClientSession( - headers=headers, timeout=timeout + headers=headers, timeout=ClientTimeout(timeout) ) as session: if not cls._nonce: async with session.get(cls.url, proxy=proxy) as response: diff --git a/g4f/Provider/ChatgptDemo.py b/g4f/Provider/ChatgptDemo.py index fdd7730b41..c9d2894aa0 100644 --- a/g4f/Provider/ChatgptDemo.py +++ b/g4f/Provider/ChatgptDemo.py @@ -1,7 +1,7 @@ from __future__ import annotations import time, json, re -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout from typing import AsyncGenerator from .base_provider import AsyncGeneratorProvider @@ -34,7 +34,7 @@ async def create_async_generator( "sec-fetch-site": "same-origin", "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36" } - async with ClientSession(headers=headers, timeout=timeout) as session: + async with ClientSession(headers=headers, timeout=ClientTimeout(timeout)) as session: async with session.get(f"{cls.url}/", proxy=proxy) as response: response.raise_for_status() response = await response.text() diff --git a/g4f/Provider/GptGo.py b/g4f/Provider/GptGo.py index 1948429195..be62250ca6 100644 --- a/g4f/Provider/GptGo.py +++ b/g4f/Provider/GptGo.py @@ -1,6 +1,6 @@ from __future__ import annotations -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout import json from ..typing import AsyncGenerator @@ -32,7 +32,7 @@ async def create_async_generator( "Sec-Fetch-Site" : "same-origin", } async with ClientSession( - headers=headers, timeout=timeout + headers=headers, timeout=ClientTimeout(timeout) ) as session: async with session.get( "https://gptgo.ai/action_get_token.php", diff --git a/g4f/Provider/Liaobots.py b/g4f/Provider/Liaobots.py index e65c3a0d3e..2e0154d5c7 100644 --- a/g4f/Provider/Liaobots.py +++ b/g4f/Provider/Liaobots.py @@ -1,9 +1,8 @@ from __future__ import annotations -import json import uuid -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout from ..typing import AsyncGenerator from .base_provider import AsyncGeneratorProvider @@ -55,7 +54,7 @@ async def create_async_generator( "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36", } async with ClientSession( - headers=headers, timeout=timeout + headers=headers, timeout=ClientTimeout(timeout) ) as session: cls._auth_code = auth if isinstance(auth, str) else cls._auth_code if not cls._auth_code: diff --git a/g4f/Provider/Vitalentum.py b/g4f/Provider/Vitalentum.py index 9125c28503..ccaaeb00f8 100644 --- a/g4f/Provider/Vitalentum.py +++ b/g4f/Provider/Vitalentum.py @@ -1,7 +1,7 @@ from __future__ import annotations import json -from aiohttp import ClientSession +from aiohttp import ClientSession, ClientTimeout from .base_provider import AsyncGeneratorProvider from ..typing import AsyncGenerator @@ -41,7 +41,7 @@ async def create_async_generator( **kwargs } async with ClientSession( - headers=headers, timeout=timeout + headers=headers, timeout=ClientTimeout(timeout) ) as session: async with session.post(cls.url + "/api/converse-edge", json=data, proxy=proxy) as response: response.raise_for_status()
https://api.github.com/repos/xtekky/gpt4free/pulls/997
2023-10-06T16:22:07Z
2023-10-06T17:41:23Z
2023-10-06T17:41:23Z
2023-10-06T17:41:23Z
2,277
xtekky/gpt4free
37,863
Add fetchOpenOrders to SouthXchange
diff --git a/js/southxchange.js b/js/southxchange.js index 2e891490f2ee..014a03083f0c 100644 --- a/js/southxchange.js +++ b/js/southxchange.js @@ -190,6 +190,45 @@ module.exports = class southxchange extends Exchange { return this.parseTrades (response, market, since, limit); } + parseOrder (order, market = undefined) { + let status = 'open'; + let symbol = order['ListingCurrency'] + '/' + order['ReferenceCurrency']; + let timestamp = undefined; + let price = parseFloat (order['LimitPrice']); + let amount = parseFloat (order['OriginalAmount']); + let remaining = this.safeFloat (order, 'Amount', 0.0); + let filled = Math.max (amount - remaining, 0.0); + let result = { + 'info': order, + 'id': order['Code'].toString (), + 'timestamp': timestamp, + 'datetime': this.iso8601 (timestamp), + 'symbol': symbol, + 'type': order['Type'].toLowerCase (), + 'side': undefined, + 'price': price, + 'amount': amount, + 'cost': price * amount, + 'filled': filled, + 'remaining': remaining, + 'status': status, + 'fee': undefined, + }; + return result; + } + + async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) { + await this.loadMarkets (); + let market = undefined; + if (symbol) { + market = this.market (symbol); + } + let response = await this.privatePostListOrders (); + if (!response) + throw new ExchangeError (this.id + ' fetchOpenOrders got an unrecognized response'); + return this.parseOrders (response, market, since, limit); + } + async createOrder (symbol, type, side, amount, price = undefined, params = {}) { await this.loadMarkets (); let market = this.market (symbol);
https://api.github.com/repos/ccxt/ccxt/pulls/2030
2018-02-23T14:45:46Z
2018-02-25T03:53:18Z
2018-02-25T03:53:18Z
2018-02-25T03:53:18Z
482
ccxt/ccxt
13,631
langchain, community: Fixes in the Ontotext GraphDB Graph and QA Chain
diff --git a/docs/docs/use_cases/graph/graph_ontotext_graphdb_qa.ipynb b/docs/docs/use_cases/graph/graph_ontotext_graphdb_qa.ipynb index b1afd3320af557..3f0a6c09c9b3b4 100644 --- a/docs/docs/use_cases/graph/graph_ontotext_graphdb_qa.ipynb +++ b/docs/docs/use_cases/graph/graph_ontotext_graphdb_qa.ipynb @@ -69,7 +69,7 @@ "pip install openai==1.6.1\n", "pip install rdflib==7.0.0\n", "pip install langchain-openai==0.0.2\n", - "pip install langchain\n", + "pip install langchain>=0.1.5\n", "```\n", "\n", "Run Jupyter with\n", diff --git a/libs/community/langchain_community/graphs/ontotext_graphdb_graph.py b/libs/community/langchain_community/graphs/ontotext_graphdb_graph.py index bf5d1a7177747b..8bc30492d6dfa0 100644 --- a/libs/community/langchain_community/graphs/ontotext_graphdb_graph.py +++ b/libs/community/langchain_community/graphs/ontotext_graphdb_graph.py @@ -204,11 +204,7 @@ def query( """ Query the graph. """ - from rdflib.exceptions import ParserError from rdflib.query import ResultRow - try: - res = self.graph.query(query) - except ParserError as e: - raise ValueError(f"Generated SPARQL statement is invalid\n{e}") + res = self.graph.query(query) return [r for r in res if isinstance(r, ResultRow)] diff --git a/libs/community/tests/integration_tests/graphs/test_ontotext_graphdb_graph.py b/libs/community/tests/integration_tests/graphs/test_ontotext_graphdb_graph.py index bba6c1ebb0b819..9f20afb6bcca37 100644 --- a/libs/community/tests/integration_tests/graphs/test_ontotext_graphdb_graph.py +++ b/libs/community/tests/integration_tests/graphs/test_ontotext_graphdb_graph.py @@ -10,7 +10,7 @@ """ -def test_query() -> None: +def test_query_method_with_valid_query() -> None: graph = OntotextGraphDBGraph( query_endpoint="http://localhost:7200/repositories/langchain", query_ontology="CONSTRUCT {?s ?p ?o}" @@ -31,6 +31,36 @@ def test_query() -> None: assert str(query_results[0][0]) == "yellow" +def test_query_method_with_invalid_query() -> None: + graph = OntotextGraphDBGraph( + query_endpoint="http://localhost:7200/repositories/langchain", + query_ontology="CONSTRUCT {?s ?p ?o}" + "FROM <https://swapi.co/ontology/> WHERE {?s ?p ?o}", + ) + + with pytest.raises(ValueError) as e: + graph.query( + "PREFIX : <https://swapi.co/vocabulary/> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "SELECT ?character (MAX(?lifespan) AS ?maxLifespan) " + "WHERE {" + " ?species a :Species ;" + " :character ?character ;" + " :averageLifespan ?lifespan ." + " FILTER(xsd:integer(?lifespan))" + "} " + "ORDER BY DESC(?maxLifespan) " + "LIMIT 1" + ) + + assert ( + str(e.value) + == "You did something wrong formulating either the URI or your SPARQL query" + ) + + def test_get_schema_with_query() -> None: graph = OntotextGraphDBGraph( query_endpoint="http://localhost:7200/repositories/langchain", diff --git a/libs/langchain/langchain/chains/graph_qa/ontotext_graphdb.py b/libs/langchain/langchain/chains/graph_qa/ontotext_graphdb.py index 4a4d89b6753a52..29d07d9d75b982 100644 --- a/libs/langchain/langchain/chains/graph_qa/ontotext_graphdb.py +++ b/libs/langchain/langchain/chains/graph_qa/ontotext_graphdb.py @@ -1,7 +1,10 @@ """Question answering over a graph.""" from __future__ import annotations -from typing import Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +if TYPE_CHECKING: + import rdflib from langchain_community.graphs import OntotextGraphDBGraph from langchain_core.callbacks.manager import CallbackManager @@ -97,10 +100,10 @@ def _call( self.sparql_generation_chain.output_key ] - generated_sparql = self._get_valid_sparql_query( + generated_sparql = self._get_prepared_sparql_query( _run_manager, callbacks, generated_sparql, ontology_schema ) - query_results = self.graph.query(generated_sparql) + query_results = self._execute_query(generated_sparql) qa_chain_result = self.qa_chain.invoke( {"prompt": prompt, "context": query_results}, callbacks=callbacks @@ -108,7 +111,7 @@ def _call( result = qa_chain_result[self.qa_chain.output_key] return {self.output_key: result} - def _get_valid_sparql_query( + def _get_prepared_sparql_query( self, _run_manager: CallbackManagerForChainRun, callbacks: CallbackManager, @@ -153,10 +156,10 @@ def _prepare_sparql_query( from rdflib.plugins.sparql import prepareQuery prepareQuery(generated_sparql) - self._log_valid_sparql_query(_run_manager, generated_sparql) + self._log_prepared_sparql_query(_run_manager, generated_sparql) return generated_sparql - def _log_valid_sparql_query( + def _log_prepared_sparql_query( self, _run_manager: CallbackManagerForChainRun, generated_query: str ) -> None: _run_manager.on_text("Generated SPARQL:", end="\n", verbose=self.verbose) @@ -180,3 +183,9 @@ def _log_invalid_sparql_query( _run_manager.on_text( error_message, color="red", end="\n\n", verbose=self.verbose ) + + def _execute_query(self, query: str) -> List[rdflib.query.ResultRow]: + try: + return self.graph.query(query) + except Exception: + raise ValueError("Failed to execute the generated SPARQL query.") diff --git a/libs/langchain/tests/integration_tests/chains/test_ontotext_graphdb_qa.py b/libs/langchain/tests/integration_tests/chains/test_ontotext_graphdb_qa.py index bab407ec1c3ed7..4f46559585c3ca 100644 --- a/libs/langchain/tests/integration_tests/chains/test_ontotext_graphdb_qa.py +++ b/libs/langchain/tests/integration_tests/chains/test_ontotext_graphdb_qa.py @@ -165,6 +165,65 @@ def test_valid_sparql_after_first_retry(max_fix_retries: int) -> None: assert result == {chain.output_key: answer, chain.input_key: question} +@pytest.mark.requires("langchain_openai", "rdflib") +@pytest.mark.parametrize("max_fix_retries", [1, 2, 3]) +def test_invalid_sparql_server_response_400(max_fix_retries: int) -> None: + from langchain_openai import ChatOpenAI + + question = "Who is the oldest character?" + generated_invalid_sparql = ( + "PREFIX : <https://swapi.co/vocabulary/> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "SELECT ?character (MAX(?lifespan) AS ?maxLifespan) " + "WHERE {" + " ?species a :Species ;" + " :character ?character ;" + " :averageLifespan ?lifespan ." + " FILTER(xsd:integer(?lifespan))" + "} " + "ORDER BY DESC(?maxLifespan) " + "LIMIT 1" + ) + + graph = OntotextGraphDBGraph( + query_endpoint="http://localhost:7200/repositories/starwars", + query_ontology="CONSTRUCT {?s ?p ?o} " + "FROM <https://swapi.co/ontology/> WHERE {?s ?p ?o}", + ) + chain = OntotextGraphDBQAChain.from_llm( + Mock(ChatOpenAI), + graph=graph, + max_fix_retries=max_fix_retries, + ) + chain.sparql_generation_chain = Mock(LLMChain) + chain.sparql_fix_chain = Mock(LLMChain) + chain.qa_chain = Mock(LLMChain) + + chain.sparql_generation_chain.output_key = "text" + chain.sparql_generation_chain.invoke = MagicMock( + return_value={ + "text": generated_invalid_sparql, + "prompt": question, + "schema": "", + } + ) + chain.sparql_fix_chain.output_key = "text" + chain.sparql_fix_chain.invoke = MagicMock() + chain.qa_chain.output_key = "text" + chain.qa_chain.invoke = MagicMock() + + with pytest.raises(ValueError) as e: + chain.invoke({chain.input_key: question}) + + assert str(e.value) == "Failed to execute the generated SPARQL query." + + assert chain.sparql_generation_chain.invoke.call_count == 1 + assert chain.sparql_fix_chain.invoke.call_count == 0 + assert chain.qa_chain.invoke.call_count == 0 + + @pytest.mark.requires("langchain_openai", "rdflib") @pytest.mark.parametrize("max_fix_retries", [1, 2, 3]) def test_invalid_sparql_after_all_retries(max_fix_retries: int) -> None:
- **Description:** Fixes in the Ontotext GraphDB Graph and QA Chain related to the error handling in case of invalid SPARQL queries, for which `prepareQuery` doesn't throw an exception, but the server returns 400 and the query is indeed invalid - **Issue:** N/A - **Dependencies:** N/A - **Twitter handle:** @OntotextGraphDB
https://api.github.com/repos/langchain-ai/langchain/pulls/17239
2024-02-08T14:08:07Z
2024-02-08T20:05:43Z
2024-02-08T20:05:43Z
2024-02-09T07:09:38Z
2,462
langchain-ai/langchain
42,848
conditionally unused parameters can be declared using maybe_unused attribute.
diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 9e9046796..df74ca978 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -2849,12 +2849,24 @@ Suppression of unused parameter warnings. ##### Example - X* find(map<Blob>& m, const string& s, Hint); // once upon a time, a hint was used + widget* find(const set<widget>& s, const widget& w, Hint); // once upon a time, a hint was used ##### Note Allowing parameters to be unnamed was introduced in the early 1980 to address this problem. +If parameters are conditionally unused, declare them with the `[[maybe_unused]]` attribute. +For example: + + template <typename Value> + Value* find(const set<Value>& s, const Value& v, [[maybe_unused]] Hint h) + { + if constexpr (sizeof(Value) > CacheSize) + { + // a hint is used only if Value is of a certain size + } + } + ##### Enforcement Flag named unused parameters.
conditionally unused parameters can be declared using maybe_unused attribute.
https://api.github.com/repos/isocpp/CppCoreGuidelines/pulls/1863
2021-12-02T09:11:51Z
2022-02-10T21:34:32Z
2022-02-10T21:34:32Z
2022-02-10T22:18:33Z
264
isocpp/CppCoreGuidelines
15,958
Missing apostophe.
diff --git a/docs/patterns/sqlalchemy.rst b/docs/patterns/sqlalchemy.rst index cdf663a681..40e048e003 100644 --- a/docs/patterns/sqlalchemy.rst +++ b/docs/patterns/sqlalchemy.rst @@ -33,7 +33,7 @@ SQLAlchemy. It allows you to define tables and models in one go, similar to how Django works. In addition to the following text I recommend the official documentation on the `declarative`_ extension. -Here the example :file:`database.py` module for your application:: +Here's the example :file:`database.py` module for your application:: from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker
https://api.github.com/repos/pallets/flask/pulls/1565
2015-08-27T04:33:32Z
2015-10-31T02:20:27Z
2015-10-31T02:20:27Z
2020-11-14T06:23:45Z
166
pallets/flask
20,532
Update pycairo requirement
diff --git a/requirements.txt b/requirements.txt index 33c71720ab..df5fe4078a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,5 +6,5 @@ progressbar==2.5 scipy==1.1.0 tqdm==4.24.0 opencv-python==3.4.2.17 -pycairo==1.17.1 +pycairo>=1.17.1 pydub==0.23.0
Many issues, such as #535, stem from the odd installation procedure of cairo and pycairo on Windows. By changing the pycairo requirement in requirements.txt, pip will no longer attempt to uninstall the working version. This should have no effect on the functionality of manim, though new installations are likely to default to pycairo 1.18.0 now.
https://api.github.com/repos/3b1b/manim/pulls/555
2019-05-28T02:01:22Z
2019-05-28T02:55:59Z
2019-05-28T02:55:58Z
2019-06-20T06:15:06Z
117
3b1b/manim
18,282
add the dropout_p parameter
diff --git a/models/common.py b/models/common.py index 8b5ec1c786d..71340688d2e 100644 --- a/models/common.py +++ b/models/common.py @@ -846,12 +846,19 @@ def forward(self, x): class Classify(nn.Module): # YOLOv5 classification head, i.e. x(b,c1,20,20) to x(b,c2) - def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups + def __init__(self, + c1, + c2, + k=1, + s=1, + p=None, + g=1, + dropout_p=0.0): # ch_in, ch_out, kernel, stride, padding, groups, dropout probability super().__init__() c_ = 1280 # efficientnet_b0 size self.conv = Conv(c1, c_, k, s, autopad(k, p), g) self.pool = nn.AdaptiveAvgPool2d(1) # to x(b,c_,1,1) - self.drop = nn.Dropout(p=0.0, inplace=True) + self.drop = nn.Dropout(p=dropout_p, inplace=True) self.linear = nn.Linear(c_, c2) # to x(b,c2) def forward(self, x):
Addressing this issue #10804 ## 🛠️ PR Summary <sub>Made with ❤️ by [Ultralytics Actions](https://github.com/ultralytics/actions)<sub> ### 🌟 Summary Enhancement of the YOLOv5 classification head with customizable dropout. ### 📊 Key Changes - Added a new parameter `dropout_p` to the `Classify` class initializer to specify dropout probability. - Modified the `Dropout` layer to use the new `dropout_p` argument instead of a fixed value. ### 🎯 Purpose & Impact - **Flexibility**: This change allows developers to customize the dropout rate, offering more control over model regularization. - **Model Performance**: With adjustable dropout, users can potentially improve model generalization and reduce overfitting, leading to better performance on diverse datasets. 🌐📈 - **Usability**: It simplifies experimenting with different dropout rates without altering the codebase, enhancing user experience and expediting model tuning. ⚙️💡
https://api.github.com/repos/ultralytics/yolov5/pulls/10805
2023-01-20T23:00:01Z
2023-02-08T07:32:30Z
2023-02-08T07:32:30Z
2024-01-19T03:18:56Z
336
ultralytics/yolov5
25,437
hitbtc3 parseTransaction unification
diff --git a/js/hitbtc3.js b/js/hitbtc3.js index 9e9dfe363c6e..f29c6a9c0e76 100644 --- a/js/hitbtc3.js +++ b/js/hitbtc3.js @@ -1120,33 +1120,36 @@ module.exports = class hitbtc3 extends Exchange { const sender = this.safeValue (native, 'senders'); const addressFrom = this.safeString (sender, 0); const amount = this.safeNumber (native, 'amount'); - let fee = undefined; + const fee = { + 'currency': undefined, + 'cost': undefined, + 'rate': undefined, + }; const feeCost = this.safeNumber (native, 'fee'); if (feeCost !== undefined) { - fee = { - 'currency': code, - 'cost': feeCost, - }; + fee['currency'] = code; + fee['cost'] = feeCost; } return { 'info': transaction, 'id': id, 'txid': txhash, + 'type': type, 'code': code, // kept here for backward-compatibility, but will be removed soon 'currency': code, - 'amount': amount, 'network': undefined, + 'amount': amount, + 'status': status, + 'timestamp': timestamp, + 'datetime': this.iso8601 (timestamp), 'address': address, 'addressFrom': addressFrom, 'addressTo': addressTo, 'tag': tag, 'tagFrom': undefined, 'tagTo': tagTo, - 'timestamp': timestamp, - 'datetime': this.iso8601 (timestamp), 'updated': updated, - 'status': status, - 'type': type, + 'comment': undefined, 'fee': fee, }; }
``` 2022-12-29T22:33:25.327Z Node.js: v18.4.0 CCXT v2.4.74 hitbtc3.fetchTransactions () 2022-12-29T22:33:27.368Z iteration 0 passed in 477 ms id | txid | type | code | currency | network | amount | status | timestamp | datetime | address | addressFrom | addressTo | tag | tagFrom | tagTo | updated | comment | fee ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 212653927 | 95489690a0bcf03acffb00754504abbb63ab5c3b480d74a1fe5c877ee4a08a00 | deposit | LTC | LTC | | 0.009 | ok | 1672352106916 | 2022-12-29T22:15:06.916Z | LQs1i1gpBpjcJgdRQiABrktvPK13vBeYBK | LZEjckteAtWrugbsy9zU8VHEZ4iUiXo9Nm | LQs1i1gpBpjcJgdRQiABrktvPK13vBeYBK | | | | 1672352638967 | | {} 1 objects 2022-12-29T22:33:27.368Z iteration 1 passed in 477 ms ```
https://api.github.com/repos/ccxt/ccxt/pulls/16265
2022-12-29T22:34:06Z
2022-12-30T23:28:15Z
2022-12-30T23:28:15Z
2022-12-31T20:17:26Z
431
ccxt/ccxt
12,983