两相知

文章 评论 浏览 31

两相知 2025-02-20 22:13:20

尝试

function transform(input) {
  return (input.replace(/<\/ul>/g, '</table>')
    .replace(/<ul>/g, '<table>')
    .replace(/<\/li>/g, '</td></tr>')
    .replace(/<li>/g, '<tr><td>')
    .replace(/:/g, '</td><td>'))
}

Try

function transform(input) {
  return (input.replace(/<\/ul>/g, '</table>')
    .replace(/<ul>/g, '<table>')
    .replace(/<\/li>/g, '</td></tr>')
    .replace(/<li>/g, '<tr><td>')
    .replace(/:/g, '</td><td>'))
}

enter image description here

拆分&lt; ul&gt;进入a&lt; table&gt;和a&lt; ul&gt;

两相知 2025-02-20 11:12:23

要点是,您的 实例模拟标准 Scikit-Learn 分类器。换句话说,它是 scikit-learn beast ,而且它不提供方法 .evaluate()

因此,您可能只会调用 best_model.score(x_test,y_test),它将自动返回准确性,因为标准的Sklearn分类器会返回。另一方面,您可以通过历史记录_ kerasclassifier 实例访问培训期间获得的损失值。

这是一个示例:

!pip install scikeras    

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_validate, KFold
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from scikeras.wrappers import KerasClassifier

X, y = make_classification(n_samples=100, n_features=20, n_informative=5, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

def build_nn():
    ann = Sequential()
    ann.add(Dense(20, input_dim=X_train.shape[1], activation='relu', name="Hidden_Layer_1"))
    ann.add(Dense(1, activation='sigmoid', name='Output_Layer'))
    ann.compile(loss='binary_crossentropy', optimizer= 'adam', metrics = 'accuracy')
return ann

keras_clf = KerasClassifier(model = build_nn, optimizer="adam", optimizer__learning_rate=0.001, epochs=100, verbose=0)

kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=keras_clf, X=X_train, y=y_train, scoring=scoring, cv=kfold, return_train_score=True, return_estimator=True)

best_model = results['estimator'][2]

# accuracy
best_model.score(X_test, y_test)

# loss values
best_model.history_['loss']

最终观察到,如有疑问,您可以调用 dir(object)获取指定对象的所有属性和方法的列表( dir(best_model)在您的情况下)。

Point is that your KerasClassifier instance mimics standard scikit-learn classifiers. In other terms, it is kind of a scikit-learn beast and, as is, it does not provide method .evaluate().

Therefore, you might just call best_model.score(X_test, y_test) which will automatically return the accuracy as standard sklearn classifiers do. On the other hand, you can access the loss values obtained during training via the history_ attribute of your KerasClassifier instance.

Here's an example:

!pip install scikeras    

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_validate, KFold
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from scikeras.wrappers import KerasClassifier

X, y = make_classification(n_samples=100, n_features=20, n_informative=5, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

def build_nn():
    ann = Sequential()
    ann.add(Dense(20, input_dim=X_train.shape[1], activation='relu', name="Hidden_Layer_1"))
    ann.add(Dense(1, activation='sigmoid', name='Output_Layer'))
    ann.compile(loss='binary_crossentropy', optimizer= 'adam', metrics = 'accuracy')
return ann

keras_clf = KerasClassifier(model = build_nn, optimizer="adam", optimizer__learning_rate=0.001, epochs=100, verbose=0)

kfold = KFold(n_splits=10)
scoring = ['accuracy', 'precision', 'recall', 'f1']
results = cross_validate(estimator=keras_clf, X=X_train, y=y_train, scoring=scoring, cv=kfold, return_train_score=True, return_estimator=True)

best_model = results['estimator'][2]

# accuracy
best_model.score(X_test, y_test)

# loss values
best_model.history_['loss']

Eventually observe that, when in doubt, you can call dir(object) to get the list of all properties and methods of the specified object (dir(best_model) in your case).

如何用角班轮计算损失

两相知 2025-02-20 09:06:48

您需要每个URL实例化一个WebClient。对于每个WebClient,您可以设置连接超时:

HttpClient httpClient = HttpClient.create()
  .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
WebClient client = WebClient.builder()
  .baseUrl("http://yourendpoint:8080")
  .clientConnector(new ReactorClientHttpConnector(httpClient))
  .build();

然后将此网络电量重复使用为已配置的URL的所有调用。

You need to instantiate one webclient per url. For each webclient, you can set the connection timeout :

HttpClient httpClient = HttpClient.create()
  .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
WebClient client = WebClient.builder()
  .baseUrl("http://yourendpoint:8080")
  .clientConnector(new ReactorClientHttpConnector(httpClient))
  .build();

Then reuse this webclient for all the calls to the configured url.

Java特定的WebClient连接超时每个请求超时

两相知 2025-02-20 05:27:07

我们在本地苹果中复制了此问题,并试图在info.plist中添加uibackgroundModes“ audio”和“ voip”,以查看它们是否有所作为。

不幸的是,他们没有。因此,这是一个Apple / Webkit问题。我们在苹果论坛上找到了一个线程,讨论了WKWebView中的WebRTC应用程序:

另外,还有一个webkit错误报告: 233419 - wkwebview microphone casscect out Backgack not (webkit.org)。因此,请跟进他们。

We reproduced this issue in native Apple and tried to add UIBackgroundModes "audio" and "voip" in info.plist to see if they make a difference.

Unfortunately, they did not. So this is an Apple / WebKit issue. We found a thread on Apple's forum talking about the same issue with a webRTC app in WKWebView: WKWebView getUserMedia microphone … | Apple Developer Forums.

Also, there is a WebKit bug report as well: 233419 – WKWebView microphone access not working in background (webkit.org). So please follow up with them.

Xamarin IOS WKWebView和WebRTC麦克风在后台不起作用

两相知 2025-02-20 01:17:22

使用 scanf(“%c”,&amp; c2); 。这将解决您的问题。

Use scanf(" %c", &c2);. This will solve your problem.

scanf()将newline字符留在缓冲区中

两相知 2025-02-19 18:12:54

这不是答案,而是处理DB2例外的建议,以解决此类错误。
如果您无法重写错误处理,那么您唯一可以的事情就是在客户端上启用JDBC跟踪或/并将DB2 DBM CFG Diaglevel 参数设置为4。

PreparedStatement pst = null;
try 
{
    pst = ...;
    ...
    int [] updateCounts = pst.executeBatch();
    System.out.println("Batch results:");
    for (int i = 0; i < updateCounts.length; i++) 
      System.out.println("  Statement " + i + ":" + updateCounts[i]);
} catch (SQLException ex) 
{
    while (ex != null) 
    {
      if (ex instanceof com.ibm.db2.jcc.DB2Diagnosable) 
      {
        com.ibm.db2.jcc.DB2Diagnosable db2ex = com.ibm.db2.jcc.DB2Diagnosable) ex;
        com.ibm.db2.jcc.DB2Sqlca sqlca = db2ex.getSqlca();
        if (sqlca != null) 
        {
          System.out.println("SQLCODE: " + sqlca.getSqlCode());
          System.out.println("MESSAGE: " + sqlca.getMessage());
        } 
        else 
        {
          System.out.println("Error code: " + ex.getErrorCode());
          System.out.println("Error msg : " + ex.getMessage());
        }
      } 
      else 
      {
        System.out.println("Error code (no db2): " + ex.getErrorCode());
        System.out.println("Error msg  (no db2): " + ex.getMessage());
      }
      if (ex instanceof BatchUpdateException) 
      {
        System.out.println("Contents of BatchUpdateException:");
        System.out.println(" Update counts: ");
        System.out.println(" Statement.SUCCESS_NO_INFO: " + Statement.SUCCESS_NO_INFO);
        System.out.println(" Statement.EXECUTE_FAILED : " + Statement.EXECUTE_FAILED); 
      
        BatchUpdateException buex = (BatchUpdateException) ex;
        int [] updateCounts = buex.getUpdateCounts(); 
        for (int i = 0; i < updateCounts.length; i++) 
          System.out.println("  Statement " + i + ":" + updateCounts[i]);
      }
      ex = ex.getNextException();
    }
}
...

It's not an answer, but a suggestion to handle Db2 exceptions to have an ability to deal with such errors.
If you are unable to rewrite your error handling, the only thing you can to is to enable JDBC trace on the client or/and set the Db2 dbm cfg DIAGLEVEL parameter to 4.

PreparedStatement pst = null;
try 
{
    pst = ...;
    ...
    int [] updateCounts = pst.executeBatch();
    System.out.println("Batch results:");
    for (int i = 0; i < updateCounts.length; i++) 
      System.out.println("  Statement " + i + ":" + updateCounts[i]);
} catch (SQLException ex) 
{
    while (ex != null) 
    {
      if (ex instanceof com.ibm.db2.jcc.DB2Diagnosable) 
      {
        com.ibm.db2.jcc.DB2Diagnosable db2ex = com.ibm.db2.jcc.DB2Diagnosable) ex;
        com.ibm.db2.jcc.DB2Sqlca sqlca = db2ex.getSqlca();
        if (sqlca != null) 
        {
          System.out.println("SQLCODE: " + sqlca.getSqlCode());
          System.out.println("MESSAGE: " + sqlca.getMessage());
        } 
        else 
        {
          System.out.println("Error code: " + ex.getErrorCode());
          System.out.println("Error msg : " + ex.getMessage());
        }
      } 
      else 
      {
        System.out.println("Error code (no db2): " + ex.getErrorCode());
        System.out.println("Error msg  (no db2): " + ex.getMessage());
      }
      if (ex instanceof BatchUpdateException) 
      {
        System.out.println("Contents of BatchUpdateException:");
        System.out.println(" Update counts: ");
        System.out.println(" Statement.SUCCESS_NO_INFO: " + Statement.SUCCESS_NO_INFO);
        System.out.println(" Statement.EXECUTE_FAILED : " + Statement.EXECUTE_FAILED); 
      
        BatchUpdateException buex = (BatchUpdateException) ex;
        int [] updateCounts = buex.getUpdateCounts(); 
        for (int i = 0; i < updateCounts.length; i++) 
          System.out.println("  Statement " + i + ":" + updateCounts[i]);
      }
      ex = ex.getNextException();
    }
}
...

db2 -errorCode = -4229,sqlstate = null

两相知 2025-02-19 13:48:59

data.table 选项

setDT(df)[
  ,
  lapply(
    .SD,
    function(x) {
      unlist(
        lapply(
          seq_along(x),
          combn,
          x = x,
          function(v) {
            ifelse(all(is.character(v)), toString, sum)(v)
          }
        )
      )
    }
  ),
  id
]

给出

   id           name number value
1:  a            bob      1     1
2:  a           jane      2     2
3:  a      bob, jane      3     3
4:  b           mark      1     1
5:  b       brittney      2     2
6:  b mark, brittney      3     3

A data.table option

setDT(df)[
  ,
  lapply(
    .SD,
    function(x) {
      unlist(
        lapply(
          seq_along(x),
          combn,
          x = x,
          function(v) {
            ifelse(all(is.character(v)), toString, sum)(v)
          }
        )
      )
    }
  ),
  id
]

gives

   id           name number value
1:  a            bob      1     1
2:  a           jane      2     2
3:  a      bob, jane      3     3
4:  b           mark      1     1
5:  b       brittney      2     2
6:  b mark, brittney      3     3

按组创建组合和总和

两相知 2025-02-19 13:34:10

默认情况下,节点是单线线程,因此为“下一个开始”。我使用PM2群集模式,并且没有任何问题。

要启动群集,您要做以下:

  1. create pm2.json文件旁边的package.json
{
    "apps": [
        {
            "name": "myNextApp",
            "script": "node_modules/next/dist/bin/next",
            "args": "start",
            "cwd": "./",
            "instances": "max",
            "exec_mode": "cluster",
            "out_file": "/var/log/myNextApp/myNextApp.log",
            "error_file": "/var/log/myNextApp/myNextAppError.log",
            "watch": "true"
        }
    ]
}

pls注意“脚本”:“ node_modules/next/dist/dist/bin/next”如果您在接下来的thexcript中,则使用此config是6一个月大,也许您需要更改此行,检查

  1. 包装中的PM2文档。JSON添加:
{
   ...
   "scripts: {
      ...,
      "pm2": "pm2"
      },
   ...,
}
  1. 添加DevDependencie PM2(YARN ADD -D PM2)

  2. 启动群集您应该能够使用:

npm run pm2 start pm2.json
or
yarn pm2 start pm2.json

从项目root

P.S.我对您是否需要将PM2添加到您的项目deps中有一些疑问,我认为使用NPM i -G和APT -GET安装YARN/PM2时会有一些差异,这可能会导致较轻的配置,但我不确定...

Node is single threaded by default so as ‘next start’. I use pm2 cluster mode, and haven’t got any issues about it.

to start cluster you do following:

  1. create pm2.json file next to your package.json
{
    "apps": [
        {
            "name": "myNextApp",
            "script": "node_modules/next/dist/bin/next",
            "args": "start",
            "cwd": "./",
            "instances": "max",
            "exec_mode": "cluster",
            "out_file": "/var/log/myNextApp/myNextApp.log",
            "error_file": "/var/log/myNextApp/myNextAppError.log",
            "watch": "true"
        }
    ]
}

pls note the "script": "node_modules/next/dist/bin/next" is used if you are under Typescript in Next, this config is 6 month old maybe you gonna need to change this line, check the pm2 docs

  1. in package.json add:
{
   ...
   "scripts: {
      ...,
      "pm2": "pm2"
      },
   ...,
}
  1. add devDependencie pm2 (yarn add -D pm2)

  2. to start cluster you should be able to use:

npm run pm2 start pm2.json
or
yarn pm2 start pm2.json

from project root

p.s. I have some doubts on whether you need to add pm2 to your project deps, I think there is some differences when you install yarn/pm2 with npm i -G and apt-get that might result a lighter config, but I'm not sure...

默认情况下,下一个JS后端多线程吗?

两相知 2025-02-19 03:31:50

要获取随机数组项使用:

var item = charClasses[Math.floor(Math.random()*charClasses.length)];

选择项目使用:

$('#classMenu').val("item ");

您可以使用这样的按钮事件:

$('#btnRandom').click(function() {
  var item = charClasses[Math.floor(Math.random()*charClasses.length)];
  $('#classMenu').val(item);
});

代码从数组中选择一个随机值,然后放入变量项目中。接下来,在选择字段中选择项目。

To get a random item of array use:

var item = charClasses[Math.floor(Math.random()*charClasses.length)];

To select the item use:

$('#classMenu').val("item ");

You can use a button event like this:

$('#btnRandom').click(function() {
  var item = charClasses[Math.floor(Math.random()*charClasses.length)];
  $('#classMenu').val(item);
});

The code select a random value from array and put in variable item. Next select the item in select field.

如何使切换开关触发选择下拉列表以随机化其选项值?

两相知 2025-02-18 21:25:48

使用 super().__ INT __()方法时,您需要精确使用所继承的参数。即使在鳟鱼构造器内部,您也需要提及其所有参数,包括其继承的IE def __init __(self,first_name,last_name,water =“ freshwater”)。因此,您的鳟鱼课应该看起来像下面的代码

class Trout(Fish):
  def __init__(self, first_name, last_name, water="freshwater"):
    self.water=water
    super().__init__(first_name, last_name)

When using super().__init__() method, you need to precise the parameters you are inheriting. and even inside your Trout constructor you need to mention all its parameters including the ones its inheriting i.e def __init__(self, first_name, last_name, water="freshwater"). So your Trout class should look like the code below

class Trout(Fish):
  def __init__(self, first_name, last_name, water="freshwater"):
    self.water=water
    super().__init__(first_name, last_name)

为什么使用super().__ init__我只能在父级中初始化第一个参数

两相知 2025-02-18 17:10:11

一个简单的可执行应用程序,该应用程序从

在此示例中,只有最后一个选项可以通过编程表明确保侦听器不会多次添加到同一阶段。

import javafx.application.Application;
import javafx.beans.property.ReadOnlyProperty;
import javafx.beans.value.ChangeListener;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class StageClosureApp extends Application {
    private static final ChangeListener<Boolean> CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER =
            (o, wasFocused, isFocused) -> {
                if (!isFocused) ((Stage) ((ReadOnlyProperty<?>) o).getBean()).close();
            };

    private static ChangeListener<Boolean> closeOnFocusLossListener(Stage stage) {
        return (o, wasFocused, isFocused) -> {
            if (!isFocused) stage.close();
        };
    }

    private static void closeOnFocusLoss(Stage stage) {
        stage.focusedProperty().removeListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);
        stage.focusedProperty().addListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);
    }

    @Override
    public void start(Stage stage) {
        // all options perform the same function (close the stage on losing focus).
        // when testing, only enable one option, commenting the others out.

        // option 1: use a closure to reference the stage in a lambda function defined inline.
        stage.focusedProperty().addListener((o, wasFocused, isFocused) -> {
            if (!isFocused) stage.close();
        });

        // option 2: pass the stage instance to a static listener generation function.
        stage.focusedProperty().addListener(closeOnFocusLossListener(stage));

        // option 3: get the stage from the bean in an inline lambda function.
        stage.focusedProperty().addListener((o, wasFocused, isFocused) -> {
            if (!isFocused) ((Stage) ((ReadOnlyProperty<?>) o).getBean()).close();
        });

        // option 4: use a single instance static change listener that get the stage from the bean.
        stage.focusedProperty().addListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);

        // option 5: update stage to add a focus loss listener when it is not focused (can safely be called multiple time for a stage)
        closeOnFocusLoss(stage);
            
        stage.setScene(new Scene(new Label("hello, world")));
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}

如果阶段失去焦点是应用程序中显示的唯一阶段(如在这些测试用例中),则默认情况下,该应用程序将自动关闭,根据应用程序生命周期,一旦关注阶段就丢失了。

我不确定这个示例会增加Slaw的答案,但这可能很有用,因此我将暂时保留该帖子。

A simple executable application that demonstrates some of the techniques from Slaw's answer, plus one or two more. I won't add any additional explanation on these techniques as that is already covered well in Slaw's answer.

Only the last option in this example demonstrates programmatically ensuring that the listener is not added to the same stage more than once.

import javafx.application.Application;
import javafx.beans.property.ReadOnlyProperty;
import javafx.beans.value.ChangeListener;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class StageClosureApp extends Application {
    private static final ChangeListener<Boolean> CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER =
            (o, wasFocused, isFocused) -> {
                if (!isFocused) ((Stage) ((ReadOnlyProperty<?>) o).getBean()).close();
            };

    private static ChangeListener<Boolean> closeOnFocusLossListener(Stage stage) {
        return (o, wasFocused, isFocused) -> {
            if (!isFocused) stage.close();
        };
    }

    private static void closeOnFocusLoss(Stage stage) {
        stage.focusedProperty().removeListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);
        stage.focusedProperty().addListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);
    }

    @Override
    public void start(Stage stage) {
        // all options perform the same function (close the stage on losing focus).
        // when testing, only enable one option, commenting the others out.

        // option 1: use a closure to reference the stage in a lambda function defined inline.
        stage.focusedProperty().addListener((o, wasFocused, isFocused) -> {
            if (!isFocused) stage.close();
        });

        // option 2: pass the stage instance to a static listener generation function.
        stage.focusedProperty().addListener(closeOnFocusLossListener(stage));

        // option 3: get the stage from the bean in an inline lambda function.
        stage.focusedProperty().addListener((o, wasFocused, isFocused) -> {
            if (!isFocused) ((Stage) ((ReadOnlyProperty<?>) o).getBean()).close();
        });

        // option 4: use a single instance static change listener that get the stage from the bean.
        stage.focusedProperty().addListener(CLOSE_ON_FOCUS_LOSS_USING_BEAN_LISTENER);

        // option 5: update stage to add a focus loss listener when it is not focused (can safely be called multiple time for a stage)
        closeOnFocusLoss(stage);
            
        stage.setScene(new Scene(new Label("hello, world")));
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
}

If the stage losing focus is the only stage displayed in the application (as it is in these test cases), then, by default, the application will automatically shut down, according to the application lifecycle, as soon as focus on the stage is lost.

I'm not sure that this example adds much to Slaw's answer, but it might be useful, so I'll keep the post for now.

如何从ObservableValue获得呼叫者舞台?扩展Boolean&gt;在焦点更改听众

两相知 2025-02-18 15:28:31

您可以使用 flutter_svg package。使用非常简单。而不是像以下内容那样显示试剂图像:

Image.asset('path_to_img'), 

您将使用:

SvgPicture.asset('path_to_svg.svg')

不要忘记在 pubspec.yaml 文件中添加SVG

You can use the flutter_svg package. It's quite simple to use. Instead of displaying a reagular image as you would with:

Image.asset('path_to_img'), 

You would use:

SvgPicture.asset('path_to_svg.svg')

Don't forget to add the SVG in your pubspec.yaml file

如何与SVG图像在颤动中的相互作用?

两相知 2025-02-18 09:22:31

因此,在尝试了一些问题之后,我发现了我自己的问题的2个解决方案,这些解决方案使用螺纹

1。修改 foo 函数

from time import sleep
from threading import Thread

x = True
def foo():
    sleep(3)

    global x
    x = False
    print('finished')


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()

2。使用装饰器保持 foo 不变

from time import sleep
from threading import Thread

x = True
def sets_true(func):

    def wrapper():
        returned_value = func()
        global x
        x = False

        print('finished')

    return wrapper

@sets_true
def foo():
    sleep(3)
    return True


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()

So, after trying somethings I found 2 solutions, of my own question, that uses threading.

1. Modifies the foo function

from time import sleep
from threading import Thread

x = True
def foo():
    sleep(3)

    global x
    x = False
    print('finished')


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()

2. Uses decorator to keep foo unchanged

from time import sleep
from threading import Thread

x = True
def sets_true(func):

    def wrapper():
        returned_value = func()
        global x
        x = False

        print('finished')

    return wrapper

@sets_true
def foo():
    sleep(3)
    return True


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()

如何继续执行代码直到另一个函数返回值?

两相知 2025-02-18 03:39:50

在源代码中看起来并不是这样,所有子命令当前均已明确注册( cf。):

    // create subcommands
    cmd.AddCommand(NewCmdCreateNamespace(f, ioStreams))
    cmd.AddCommand(NewCmdCreateQuota(f, ioStreams))
    cmd.AddCommand(NewCmdCreateSecret(f, ioStreams))
    cmd.AddCommand(NewCmdCreateConfigMap(f, ioStreams))
    cmd.AddCommand(NewCmdCreateServiceAccount(f, ioStreams))
    cmd.AddCommand(NewCmdCreateService(f, ioStreams))
    cmd.AddCommand(NewCmdCreateDeployment(f, ioStreams))
    cmd.AddCommand(NewCmdCreateClusterRole(f, ioStreams))
    cmd.AddCommand(NewCmdCreateClusterRoleBinding(f, ioStreams))
    cmd.AddCommand(NewCmdCreateRole(f, ioStreams))
    cmd.AddCommand(NewCmdCreateRoleBinding(f, ioStreams))
    cmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams))
    cmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams))
    cmd.AddCommand(NewCmdCreateJob(f, ioStreams))
    cmd.AddCommand(NewCmdCreateCronJob(f, ioStreams))
    cmd.AddCommand(NewCmdCreateIngress(f, ioStreams))
    cmd.AddCommand(NewCmdCreateToken(f, ioStreams))
    return cmd

It does not look like that in source code, all sub-commands are currently registered explicitly (cf.):

    // create subcommands
    cmd.AddCommand(NewCmdCreateNamespace(f, ioStreams))
    cmd.AddCommand(NewCmdCreateQuota(f, ioStreams))
    cmd.AddCommand(NewCmdCreateSecret(f, ioStreams))
    cmd.AddCommand(NewCmdCreateConfigMap(f, ioStreams))
    cmd.AddCommand(NewCmdCreateServiceAccount(f, ioStreams))
    cmd.AddCommand(NewCmdCreateService(f, ioStreams))
    cmd.AddCommand(NewCmdCreateDeployment(f, ioStreams))
    cmd.AddCommand(NewCmdCreateClusterRole(f, ioStreams))
    cmd.AddCommand(NewCmdCreateClusterRoleBinding(f, ioStreams))
    cmd.AddCommand(NewCmdCreateRole(f, ioStreams))
    cmd.AddCommand(NewCmdCreateRoleBinding(f, ioStreams))
    cmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams))
    cmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams))
    cmd.AddCommand(NewCmdCreateJob(f, ioStreams))
    cmd.AddCommand(NewCmdCreateCronJob(f, ioStreams))
    cmd.AddCommand(NewCmdCreateIngress(f, ioStreams))
    cmd.AddCommand(NewCmdCreateToken(f, ioStreams))
    return cmd

是否可以扩展“ kubectl create&quot”?

两相知 2025-02-17 16:55:32

您可以创建一个虚拟类,该类没有do <代码>写方法。 ExitStack 用于确保自动关闭任何打开的文件。

from contextlib import ExitStack


class NoWrite:
    def write(self, value):
        pass


def myFunc(output1=None, output2=None):
    X,Y = 0,0
    with ExitStack() as es:
        file1 = es.enter_context(open(output1, "w")) if output1 is not None else NoWrite()
        file2 = es.enter_context(open(output2, "w")) if output2 is not None else NoWrite()

        for i in range(1000):
            X,Y = someCalculation(X, Y) #calculations happen here
            file1.write(X)
            file2.write(Y)
    return X,Y

当您似乎正在记录 x 和/或 y 值时,您可能需要考虑使用 logging 模块,为适当的记录器创建 fileHandler ,而不是将输出文件名称为 myFunc 本身。

import logging

# configuration of the logger objects is the responsibility
# of the *user* of the function, not the function itself.
def myFunc():
    x_logger = logging.getLogger("myFunc.x_logger")
    y_logger = logging.getLogger("myFunc.y_logger")

    X,Y = 0,0
    for i in range(1000):
        X,Y = someCalculation(X, Y)
        x_logger.info("%s", X)
        y_logger.info("%s", Y)
    return X,Y

You can create a dummy class that has a do-nothing write method. ExitStack is used to ensure any opened files are closed automatically.

from contextlib import ExitStack


class NoWrite:
    def write(self, value):
        pass


def myFunc(output1=None, output2=None):
    X,Y = 0,0
    with ExitStack() as es:
        file1 = es.enter_context(open(output1, "w")) if output1 is not None else NoWrite()
        file2 = es.enter_context(open(output2, "w")) if output2 is not None else NoWrite()

        for i in range(1000):
            X,Y = someCalculation(X, Y) #calculations happen here
            file1.write(X)
            file2.write(Y)
    return X,Y

As you appear to be logging the X and/or Y values at each step, you may want to look into using the logging module instead, creating a FileHandler for the appropriate logger instead of passing output file names to myFunc itself.

import logging

# configuration of the logger objects is the responsibility
# of the *user* of the function, not the function itself.
def myFunc():
    x_logger = logging.getLogger("myFunc.x_logger")
    y_logger = logging.getLogger("myFunc.y_logger")

    X,Y = 0,0
    for i in range(1000):
        X,Y = someCalculation(X, Y)
        x_logger.info("%s", X)
        y_logger.info("%s", Y)
    return X,Y

在循环中,可选地将输出写入文件

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文