helloadhavan/github_issues huggingface dataset:
Repository: ollama/ollama
Pull request: Add allowed host middleware and remove `workDir` middleware


Changed files:
filename: server/routes.go
patch: @@ -10,6 +10,7 @@ import (
 	"log/slog"
 	"net"
 	"net/http"
+	"net/netip"
 	"os"
 	"os/signal"
 	"path/filepath"
@@ -35,7 +36,7 @@ import (
 var mode string = gin.DebugMode
 
 type Server struct {
-	WorkDir string
+	addr net.Addr
 }
 
 func init() {
@@ -904,15 +905,64 @@ var defaultAllowOrigins = []string{
 	"0.0.0.0",
 }
 
-func NewServer() (*Server, error) {
-	workDir, err := os.MkdirTemp("", "ollama")
-	if err != nil {
-		return nil, err
+func allowedHost(host string) bool {
+	if host == "" || host == "localhost" {
+		return true
+	}
+
+	if hostname, err := os.Hostname(); err == nil && host == hostname {
+		return true
+	}
+
+	var tlds = []string{
+		".localhost",
+		".local",
+		".internal",
+	}
+
+	for _, tld := range tlds {
+		if strings.HasSuffix(host, "."+tld) {
+			return true
+		}
 	}
 
-	return &Server{
-		WorkDir: workDir,
-	}, nil
+	return false
+}
+
+func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
+	return func(c *gin.Context) {
+		if addr == nil {
+			c.Next()
+			return
+		}
+
+		if !netip.MustParseAddrPort(addr.String()).Addr().IsLoopback() {
+			c.Next()
+			return
+		}
+
+		if addrPort, _ := netip.ParseAddrPort(c.Request.Host); addrPort.Addr().IsLoopback() {
+			c.Next()
+			return
+		}
+
+		if addr, _ := netip.ParseAddr(c.Request.Host); addr.IsLoopback() {
+			c.Next()
+			return
+		}
+
+		host, _, err := net.SplitHostPort(c.Request.Host)
+		if err != nil {
+			host = c.Request.Host
+		}
+
+		if allowedHost(host) {
+			c.Next()
+			return
+		}
+
+		c.AbortWithStatus(http.StatusForbidden)
+	}
 }
 
 func (s *Server) GenerateRoutes() http.Handler {
@@ -938,10 +988,7 @@ func (s *Server) GenerateRoutes() http.Handler {
 	r := gin.Default()
 	r.Use(
 		cors.New(config),
-		func(c *gin.Context) {
-			c.Set("workDir", s.WorkDir)
-			c.Next()
-		},
+		allowedHostsMiddleware(s.addr),
 	)
 
 	r.POST("/api/pull", PullModelHandler)
@@ -1010,10 +1057,7 @@ func Serve(ln net.Listener) error {
 		}
 	}
 
-	s, err := NewServer()
-	if err != nil {
-		return err
-	}
+	s := &Server{addr: ln.Addr()}
 	r := s.GenerateRoutes()
 
 	slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
@@ -1029,7 +1073,6 @@ func Serve(ln net.Listener) error {
 		if loaded.runner != nil {
 			loaded.runner.Close()
 		}
-		os.RemoveAll(s.WorkDir)
 		os.Exit(0)
 	}()
 

filename: server/routes_test.go
patch: @@ -21,12 +21,6 @@ import (
 	"github.com/jmorganca/ollama/version"
 )
 
-func setupServer(t *testing.T) (*Server, error) {
-	t.Helper()
-
-	return NewServer()
-}
-
 func Test_Routes(t *testing.T) {
 	type testCase struct {
 		Name     string
@@ -207,9 +201,7 @@ func Test_Routes(t *testing.T) {
 		},
 	}
 
-	s, err := setupServer(t)
-	assert.Nil(t, err)
-
+	s := Server{}
 	router := s.GenerateRoutes()
 
 	httpSrv := httptest.NewServer(router)
Repository: facebook/react
Pull request: [compiler] Handle earlier creation of early return on scopes

Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom):
* __->__ #30333

I'm experimenting with a new pass that sometimes creates scopes with early returns earlier in the pipeline, but there are a few passes that assume that can't happen. This PR is updating those passes just to be more resilient to help unblock experimentation.

Changed files:
filename: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PropagateEarlyReturns.ts
patch: @@ -24,8 +24,6 @@ import { EARLY_RETURN_SENTINEL } from "./CodegenReactiveFunction";
 import { ReactiveFunctionTransform, Transformed } from "./visitors";
 
 /**
- * TODO: Actualy propagate early return information, for now we throw a Todo bailout.
- *
  * This pass ensures that reactive blocks honor the control flow behavior of the
  * original code including early return semantics. Specifically, if a reactive
  * scope early returned during the previous execution and the inputs to that block
@@ -135,6 +133,14 @@ class Transform extends ReactiveFunctionTransform<State> {
     scopeBlock: ReactiveScopeBlock,
     parentState: State
   ): void {
+    /**
+     * Exit early if an earlier pass has already created an early return,
+     * which may happen in alternate compiler configurations.
+     */
+    if (scopeBlock.scope.earlyReturnValue !== null) {
+      return;
+    }
+
     const innerState: State = {
       withinReactiveScope: true,
       earlyReturnValue: parentState.earlyReturnValue,

filename: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneNonEscapingScopes.ts
patch: @@ -932,10 +932,14 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
      * is early-returned from within the scope. For now we intentionaly keep
      * these scopes, and let them get pruned later by PruneUnusedScopes
      * _after_ handling the early-return case in PropagateEarlyReturns.
+     *
+     * Also keep the scope if an early return was created by some earlier pass,
+     * which may happen in alternate compiler configurations.
      */
     if (
-      scopeBlock.scope.declarations.size === 0 &&
-      scopeBlock.scope.reassignments.size === 0
+      (scopeBlock.scope.declarations.size === 0 &&
+        scopeBlock.scope.reassignments.size === 0) ||
+      scopeBlock.scope.earlyReturnValue !== null
     ) {
       return { kind: "keep" };
     }
Repository: facebook/react
Pull request: [compiler] Fix mode for generating scopes for reassignments

Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom):
* __->__ #30321

We have an experimental mode where we generate scopes for simple phi values, even if they aren't subsequently mutated. This mode was incorrectly generating scope ranges, leaving the start at 0 which is invalid. The fix is to allow non-zero identifier ranges to overwrite the scope start (rather than taking the min) if the scope start is still zero.

Changed files:
filename: compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/InferReactiveScopeVariables.ts
patch: @@ -114,12 +114,12 @@ export function inferReactiveScopeVariables(fn: HIRFunction): void {
       };
       scopes.set(groupIdentifier, scope);
     } else {
-      if (identifier.mutableRange.start !== 0 && scope.range.start !== 0) {
+      if (scope.range.start === 0) {
+        scope.range.start = identifier.mutableRange.start;
+      } else if (identifier.mutableRange.start !== 0) {
         scope.range.start = makeInstructionId(
           Math.min(scope.range.start, identifier.mutableRange.start)
         );
-      } else if (identifier.mutableRange.start !== 0) {
-        scope.range.start = identifier.mutableRange.start;
       }
       scope.range.end = makeInstructionId(
         Math.max(scope.range.end, identifier.mutableRange.end)
Repository: denoland/deno
Pull request: fix(deploy): bypass minimumDependencyAge

Closes #32135

Changed files:
filename: cli/tools/deploy.rs
patch: @@ -2,6 +2,7 @@
 
 use std::sync::Arc;
 
+use deno_config::deno_json::NewestDependencyDate;
 use deno_config::deno_json::NodeModulesDirMode;
 use deno_core::error::AnyError;
 use deno_core::url::Url;
@@ -22,6 +23,7 @@ pub async fn deploy(
 ) -> Result<i32, AnyError> {
   flags.node_modules_dir = Some(NodeModulesDirMode::None);
   flags.no_lock = true;
+  flags.minimum_dependency_age = Some(NewestDependencyDate::Disabled);
   if deploy_flags.sandbox {
     // SAFETY: only this subcommand is running, nothing else, so it's safe to set an env var.
     unsafe {
Repository: huggingface/transformers
Pull request: [generate] cache missing custom generate file

# What does this PR do?

Reorders code in `load_custom_generate` such that we load the `.py` file first, and check whether it is to be used later. This way, we can cache the result of the Hub request even when the file doesn't exist.

⚠️ Since we try to load `custom_generate` at model-loading time, this results in much fewer Hub requests in situations like CIs. Some downstream CIs were hitting rate limits, in part due to this feature's uncached requests prior to this change.

______________________

✅ ran `custom_generation` tests, including existing slow tests.

Changed files:
filename: src/transformers/generation/utils.py
patch: @@ -22,7 +22,6 @@
 
 import torch
 import torch.distributed as dist
-from huggingface_hub import file_exists
 from packaging import version
 from torch import nn
 
@@ -392,23 +391,20 @@ def load_custom_generate(
         Returns:
             A callable that can be used to generate text.
         """
-        # Does `pretrained_model_name_or_path` have a `custom_generate` subdirectory? If not -> OSError
-        is_local_code = os.path.exists(pretrained_model_name_or_path)
-        has_custom_generate_folder = True
-        if is_local_code:
-            if not os.path.exists(os.path.join(pretrained_model_name_or_path, "custom_generate/generate.py")):
-                has_custom_generate_folder = False
-        else:
-            if not file_exists(pretrained_model_name_or_path, "custom_generate/generate.py"):
-                has_custom_generate_folder = False
-
-        if not has_custom_generate_folder:
+        # Fetches the generate.py file from the model repo. If it doesn't exist, a file in `.no_exist` cache directory
+        # is created (preventing future hub requests), and an OSError is raised.
+        try:
+            module = get_cached_module_file(
+                pretrained_model_name_or_path, module_file="custom_generate/generate.py", **kwargs
+            )
+        except OSError:
             raise OSError(
                 f"`{pretrained_model_name_or_path}` does not contain a `custom_generate` subdirectory with a "
                 "`generate.py` file, can't load the custom generate function."
             )
 
         # Handle opt-in `trust_remote_code` and related exceptions
+        is_local_code = os.path.exists(pretrained_model_name_or_path)
         error_message = (
             f"The repository `{pretrained_model_name_or_path}` contains custom generation code that will override "
             "the default `generate` method."
@@ -425,9 +421,6 @@ def load_custom_generate(
         check_python_requirements(
             pretrained_model_name_or_path, requirements_file="custom_generate/requirements.txt", **kwargs
         )
-        module = get_cached_module_file(
-            pretrained_model_name_or_path, module_file="custom_generate/generate.py", **kwargs
-        )
         custom_generate_function = get_class_in_module("generate", module)
         return custom_generate_function
Repository: facebook/react
Pull request: [native-fb] set disableDefaultPropsExceptForClasses flag to true


Reflecting D59402048


Changed files:
filename: packages/shared/forks/ReactFeatureFlags.native-fb-dynamic.js
patch: @@ -18,7 +18,6 @@
 // add a test configuration for React Native.
 
 export const alwaysThrottleRetries = __VARIANT__;
-export const disableDefaultPropsExceptForClasses = __VARIANT__;
 export const enableAddPropertiesFastPath = __VARIANT__;
 export const enableFastJSX = __VARIANT__;
 export const enableObjectFiber = __VARIANT__;

filename: packages/shared/forks/ReactFeatureFlags.native-fb.js
patch: @@ -20,7 +20,6 @@ const dynamicFlags: DynamicExportsType = (dynamicFlagsUntyped: any);
 // the exports object every time a flag is read.
 export const {
   alwaysThrottleRetries,
-  disableDefaultPropsExceptForClasses,
   enableAddPropertiesFastPath,
   enableFastJSX,
   enableObjectFiber,
@@ -34,6 +33,7 @@ export const consoleManagedByDevToolsDuringStrictMode = true;
 export const debugRenderPhaseSideEffectsForStrictMode = __DEV__;
 export const disableClientCache = true;
 export const disableCommentsAsDOMContainers = true;
+export const disableDefaultPropsExceptForClasses = true;
 export const disableIEWorkarounds = true;
 export const disableInputAttributeSyncing = false;
 export const disableLegacyContext = false;

filename: packages/shared/forks/ReactFeatureFlags.test-renderer.native-fb.js
patch: @@ -16,7 +16,7 @@ export const consoleManagedByDevToolsDuringStrictMode = false;
 export const debugRenderPhaseSideEffectsForStrictMode = false;
 export const disableClientCache = true;
 export const disableCommentsAsDOMContainers = true;
-export const disableDefaultPropsExceptForClasses = false;
+export const disableDefaultPropsExceptForClasses = true;
 export const disableIEWorkarounds = true;
 export const disableInputAttributeSyncing = false;
 export const disableLegacyContext = false;
Repository: nodejs/node
Pull request: sqlite: avoid useless call to FromMaybe()

`v8::MaybeLocal<v8::Value>::FromMaybe()` is only useful for its return value, which is ignored.

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: src/node_sqlite.cc
patch: @@ -507,8 +507,7 @@ class BackupJob : public ThreadPoolWork {
 
         Local<Value> argv[] = {progress_info};
         TryCatch try_catch(env()->isolate());
-        fn->Call(env()->context(), Null(env()->isolate()), 1, argv)
-            .FromMaybe(Local<Value>());
+        USE(fn->Call(env()->context(), Null(env()->isolate()), 1, argv));
         if (try_catch.HasCaught()) {
           Finalize();
           resolver->Reject(env()->context(), try_catch.Exception()).ToChecked();
Repository: ollama/ollama
Pull request: fix: default terminal width, height

resolves #2970 

Changed files:
filename: readline/buffer.go
patch: @@ -19,10 +19,9 @@ type Buffer struct {
 
 func NewBuffer(prompt *Prompt) (*Buffer, error) {
 	fd := int(os.Stdout.Fd())
-	width, height, err := term.GetSize(fd)
-	if err != nil {
-		fmt.Println("Error getting size:", err)
-		return nil, err
+	width, height := 80, 24
+	if termWidth, termHeight, err := term.GetSize(fd); err == nil {
+		width, height = termWidth, termHeight
 	}
 
 	lwidth := width - len(prompt.prompt())
Repository: facebook/react
Pull request: [native-fb] set consoleManagedByDevToolsDuringStrictMode flag to true


Reflecting D59232098.


Changed files:
filename: packages/shared/forks/ReactFeatureFlags.native-fb-dynamic.js
patch: @@ -18,7 +18,6 @@
 // add a test configuration for React Native.
 
 export const alwaysThrottleRetries = __VARIANT__;
-export const consoleManagedByDevToolsDuringStrictMode = __VARIANT__;
 export const disableDefaultPropsExceptForClasses = __VARIANT__;
 export const enableAddPropertiesFastPath = __VARIANT__;
 export const enableFastJSX = __VARIANT__;

filename: packages/shared/forks/ReactFeatureFlags.native-fb.js
patch: @@ -20,7 +20,6 @@ const dynamicFlags: DynamicExportsType = (dynamicFlagsUntyped: any);
 // the exports object every time a flag is read.
 export const {
   alwaysThrottleRetries,
-  consoleManagedByDevToolsDuringStrictMode,
   disableDefaultPropsExceptForClasses,
   enableAddPropertiesFastPath,
   enableFastJSX,
@@ -31,6 +30,7 @@ export const {
 
 // The rest of the flags are static for better dead code elimination.
 export const allowConcurrentByDefault = false;
+export const consoleManagedByDevToolsDuringStrictMode = true;
 export const debugRenderPhaseSideEffectsForStrictMode = __DEV__;
 export const disableClientCache = true;
 export const disableCommentsAsDOMContainers = true;
Repository: vercel/next.js
Pull request: [Cache Components] default to filtering unhandledRejection after abort

defaulting this filtering to enabled but can still be disabled by environment variable.

Changed files:
filename: packages/next/src/server/node-environment-extensions/unhandled-rejection.test.ts
patch: @@ -146,7 +146,7 @@ export function runWorkerCode(fn: Function): Promise<WorkerResult> {
 
 describe('unhandled-rejection filter', () => {
   describe('environment variable configuration', () => {
-    it('should not install filter by default', async () => {
+    it('should install filter by default', async () => {
       async function testForWorker() {
         require('next/dist/server/node-environment-extensions/unhandled-rejection')
 
@@ -160,7 +160,7 @@ describe('unhandled-rejection filter', () => {
 
       expect(exitCode).toBe(0)
       expect(messages).toEqual(
-        expect.arrayContaining([expect.objectContaining({ count: 0 })])
+        expect.arrayContaining([expect.objectContaining({ count: 1 })])
       )
     })
 

filename: packages/next/src/server/node-environment-extensions/unhandled-rejection.tsx
patch: @@ -32,23 +32,23 @@ const MODE:
   | string
   | undefined = process.env.NEXT_USE_UNHANDLED_REJECTION_FILTER
 
-let ENABLE_UHR_FILTER = false
+let ENABLE_UHR_FILTER = true
 let DEBUG_UHR_FILTER = false
 
 switch (MODE) {
   case 'debug':
     DEBUG_UHR_FILTER = true
-  // fallthrough
-  case 'enabled':
-  case 'true':
-  case '1':
-    ENABLE_UHR_FILTER = true
     break
   case 'false':
   case 'disabled':
   case '0':
+    ENABLE_UHR_FILTER = false
+    break
   case '':
   case undefined:
+  case 'enabled':
+  case 'true':
+  case '1':
     break
   default:
     if (typeof MODE === 'string') {
Repository: facebook/react
Pull request: [Flight] Encode the name of a function as an object property

Unfortunately, Firefox doesn't include the name of a function in stack traces if you set it as either `.name` or `.displayName` at runtime. Only if you include it declarative.

We also can't include it into a named function expression because not all possible names are expressible declaratively. E.g. spaces or punctuations.

However, we can express any name if it's an object property and since object properties now give their name declarative to the function defined inside of them, we can declaratively express any name this way.

Changed files:
filename: packages/react-client/src/ReactFlightClient.js
patch: @@ -1891,19 +1891,33 @@ function createFakeFunction<T>(
   const comment =
     '/* This module was rendered by a Server Component. Turn on Source Maps to see the server source. */';
 
+  if (!name) {
+    // An eval:ed function with no name gets the name "eval". We give it something more descriptive.
+    name = '(anonymous)';
+  }
+  const encodedName = JSON.stringify(name);
   // We generate code where the call is at the line and column of the server executed code.
   // This allows us to use the original source map as the source map of this fake file to
   // point to the original source.
   let code;
   if (line <= 1) {
-    code = '_=>' + ' '.repeat(col < 4 ? 0 : col - 4) + '_()\n' + comment;
+    const minSize = encodedName.length + 7;
+    code =
+      '({' +
+      encodedName +
+      ':_=>' +
+      ' '.repeat(col < minSize ? 0 : col - minSize) +
+      '_()})\n' +
+      comment;
   } else {
     code =
       comment +
       '\n'.repeat(line - 2) +
-      '_=>\n' +
+      '({' +
+      encodedName +
+      ':_=>\n' +
       ' '.repeat(col < 1 ? 0 : col - 1) +
-      '_()';
+      '_()})';
   }
 
   if (filename.startsWith('/')) {
@@ -1931,7 +1945,7 @@ function createFakeFunction<T>(
   let fn: FakeFunction<T>;
   try {
     // eslint-disable-next-line no-eval
-    fn = (0, eval)(code);
+    fn = (0, eval)(code)[name];
   } catch (x) {
     // If eval fails, such as if in an environment that doesn't support it,
     // we fallback to creating a function here. It'll still have the right
@@ -1940,10 +1954,6 @@ function createFakeFunction<T>(
       return _();
     };
   }
-  // $FlowFixMe[cannot-write]
-  Object.defineProperty(fn, 'name', {value: name || '(anonymous)'});
-  // $FlowFixMe[prop-missing]
-  fn.displayName = name;
   return fn;
 }
Repository: electron/electron
Pull request: fix: regression with directory selection in macOS dialogs

Backport of #47259

See that PR for details.


Notes: fix regression with directory selection in macOS dialogs

Changed files:
filename: shell/browser/ui/file_dialog_mac.mm
patch: @@ -306,7 +306,7 @@ void ReadDialogPathsWithBookmarks(NSOpenPanel* dialog,
       BOOL is_package_as_directory =
           [[NSWorkspace sharedWorkspace] isFilePackageAtPath:path] &&
           [dialog treatsFilePackagesAsDirectories];
-      if (!exists || !is_directory || !is_package_as_directory)
+      if (!exists || !(is_directory || is_package_as_directory))
         continue;
     }
Repository: ggml-org/llama.cpp
Pull request: ci : skip winget update when not in ggml-org

Prevent forks from generating daily failure notifications.

Changed files:
filename: .github/workflows/winget.yml
patch: @@ -9,6 +9,7 @@ jobs:
   update:
     name: Update Winget Package
     runs-on: ubuntu-latest
+    if: ${{ github.repository.owner.login == 'ggml-org' }}
 
     steps:
       - name: Install cargo binstall
Repository: denoland/deno
Pull request: feat(publish): support more license file types

As per https://github.com/jsr-io/jsr/pull/1287

Changed files:
filename: cli/tools/publish/mod.rs
patch: @@ -1280,13 +1280,19 @@ async fn check_if_git_repo_dirty(cwd: &Path) -> Option<String> {
   }
 }
 
-static SUPPORTED_LICENSE_FILE_NAMES: [&str; 6] = [
+static SUPPORTED_LICENSE_FILE_NAMES: [&str; 12] = [
   "LICENSE",
   "LICENSE.md",
   "LICENSE.txt",
   "LICENCE",
   "LICENCE.md",
   "LICENCE.txt",
+  "COPYING",
+  "COPYING.md",
+  "COPYING.txt",
+  "COPYING.LESSER",
+  "COPYING.LESSER.md",
+  "COPYING.LESSER.txt",
 ];
 
 fn resolve_license_file(
Repository: ollama/ollama
Pull request: fix: allow importing a model from name reference

fixes #3003 

Changed files:
filename: server/images.go
patch: @@ -10,6 +10,7 @@ import (
 	"errors"
 	"fmt"
 	"io"
+	"io/fs"
 	"log"
 	"log/slog"
 	"net/http"
@@ -322,9 +323,12 @@ func CreateModel(ctx context.Context, name, modelFileDir string, commands []pars
 
 			ggufName, err := convertSafetensors(name, pathName)
 			if err != nil {
+				var pathErr *fs.PathError
 				switch {
 				case errors.Is(err, zip.ErrFormat):
 					// it's not a safetensor archive
+				case errors.As(err, &pathErr):
+					// it's not a file on disk, could be a model reference
 				default:
 					return err
 				}