葬心

文章 评论 浏览 34

葬心 2025-02-20 18:36:28
    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If txtboxIdSize.TextLength > 0 then
    TblDiesBindingSource.Filter = 
quot;Descript LIKE '%{txtDescription.Text.Trim()}%'"
    TblDiesBindingSource.Position = TblDiesBindingSource.Find("IDSIZE", txtIdSize.Text)
End if
End Sub
    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If txtboxIdSize.TextLength > 0 then
    TblDiesBindingSource.Filter = 
quot;Descript LIKE '%{txtDescription.Text.Trim()}%'"
    TblDiesBindingSource.Position = TblDiesBindingSource.Find("IDSIZE", txtIdSize.Text)
End if
End Sub

使用BindingSource查找方法时,如何允许null TextBox?

葬心 2025-02-20 04:36:18

必须与Liz的自定义OP(在下面的评论中)一起去。

sub prefix:<²^>(uint $a) { (+^ $a) + 1 }

say ²^ 18446744073709551592; # 24

野生猜测”² @zentrunix可以接受,也是Liz's Op的基础:

say (+^ my uint $ = 18446744073709551592) + 1; # 24

/它起作用!

\ o

我原来的“半教育的 +^表格,将其子数字作为“两个补充”,然后避免看起来像^2

²一条思维是关于特定整数的。我看到 184444444073709551592 接近 2 ** 64 。另一个是,除非您采取其他行动使它们做某事,否则整数在Perl中的精度有限,而在Raku中,除非您做某事以使它们有其他方式,否则它们是任意的精度。第三条思维来自阅读 prefix +^ 说“使用所需的任意多字符将数字转换为二进制”这意味着表示形式很重要。唔。如果我尝试 int 变量怎么办?溢出。 (当然。) uint ?宾果游戏。

³我不知道此解决方案是否是正确的,原因是出于错误的原因。甚至更糟。关于Raku中的 uint 的一件事定义为对应于用于编译Raku代码的RAKU编译器支持的最大的本机无符号整数大小。 (iirc。)实际上,这意味着Rakudo和任何基础平台的目标,我认为几乎在几乎所有情况下,这几乎可以肯定意味着C的 uint64_t 。我想 perl 具有一些相似的平台依赖性定义。因此,如果我的解决方案(如果是合理的解决方案),则可能仅适用于Raku编译器(实际上在今天意味着Rakudo)与 perl 二进制(实际上在今天,今天意味着P5P的 perl )在某个平台上运行时。另请参阅下面的 @P6Steve的评论。

Gotta go with (my variant¹ of) Liz's custom op (in her comment below).

sub prefix:<²^>(uint $a) { (+^ $a) + 1 }

say ²^ 18446744073709551592; # 24

My original "semi-educated wild guess"² that turned out to be acceptable to @zentrunix and the basis for Liz's op:

say (+^ my uint $ = 18446744073709551592) + 1; # 24

\o/ It works!³

Footnotes

¹ I flipped the two character op because I wanted to follow the +^ form, have it sub-vocalize as "two's complement", and avoid it looking like ^2.

² One line of thinking was about the particular integer. I saw that 18446744073709551592 is close to 2**64. Another was that integers are limited precision in Perl unless you do something to make them otherwise, whereas in Raku they are arbitrary precision unless you do something to make them otherwise. A third line of thinking came from reading the doc for prefix +^ which says "converts the number to binary using as many bytes as needed" which I interpreted as meaning that the representation is somehow important. Hmm. What if I try an int variable? Overflow. (Of course.) uint? Bingo.

³ I've no idea if this solution is right for the wrong reasons. Or even worse. One thing that's concerning is that uint in Raku is defined to correspond to the largest native unsigned integer size supported by the Raku compiler used to compile the Raku code. (Iirc.) In practice today this means Rakudo and whatever underlying platform is being targeted, and I think that almost certainly means C's uint64_t in almost all cases. I imagine perl has some similar platform dependent definition. So my solution, if it is a reasonable one, is presumably only portable to the degree that the Raku compiler (which in practice today means Rakudo) agrees with the perl binary (which in practice today means P5P's perl) when run on some platform. See also @p6steve's comment below.

2&#x27的Raku操作员补充算术?

葬心 2025-02-19 16:22:02

好吧,根据评论&amp;问题似乎您需要在下面做:

public static void main(String[] args) {
           
     try {
 
        File file = new File("/Downloads/student.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Company.class);
 
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Student com= (Student) jaxbUnmarshaller.unmarshal(file);
        List<Student> list = com.getStudent();
        list.stream().forEach(stu->{
         if(stu.getGender().equalsIgnoreCase("M")){
          //write to file where Male gender details can be stored.
           
          }
         else {
          //write to file where Male gender details can be stored.
         }
         });
        
        }
     }}

在这里,您可以获取流&amp;比较每个元素&amp;按元素写入各自的文件元素。

请注意,您可以在 main 开始时声明文件。

编辑:当您正在寻找多级分组时,我的建议是:

Map<String, Map<String, List<Student>>> map = list.stream()
            .collect(Collectors.groupingBy(x -> x.getGender(), Collectors.groupingBy(y -> y.getAddress().getZipCode())));

此地图具有基于性别和ZIP的数据汇总。迭代这张地图&amp;将详细信息放入不同的文件中。

Well, as per comments & question it looks like you need to do below:

public static void main(String[] args) {
           
     try {
 
        File file = new File("/Downloads/student.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Company.class);
 
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Student com= (Student) jaxbUnmarshaller.unmarshal(file);
        List<Student> list = com.getStudent();
        list.stream().forEach(stu->{
         if(stu.getGender().equalsIgnoreCase("M")){
          //write to file where Male gender details can be stored.
           
          }
         else {
          //write to file where Male gender details can be stored.
         }
         });
        
        }
     }}

Here, you can obtain stream & compare each element & write to your respective files element by element.

Please note, you can declare your files at beginning of main.

Edit: As you are looking for multilevel grouping then below is what I am suggesting:

Map<String, Map<String, List<Student>>> map = list.stream()
            .collect(Collectors.groupingBy(x -> x.getGender(), Collectors.groupingBy(y -> y.getAddress().getZipCode())));

This map has aggregation of data based on gender and zip. Iterate this map & put details into different files.

如何根据索引将XML转换为收集和迭代?由于我需要进一步执行Java的收藏的操作

葬心 2025-02-19 12:01:21

在您的书籍课

public function author(){
    return $this->belongsTo(Author::class);
}

和控制器上执行此操作:

public function index(){
  $books=Book::with('author')->get();

  return response()->json([
        "books" => $books
  ], 200);
}

do this on your Book class

public function author(){
    return $this->belongsTo(Author::class);
}

and on your controller:

public function index(){
  $books=Book::with('author')->get();

  return response()->json([
        "books" => $books
  ], 200);
}

如何在Vue中显示两个模型

葬心 2025-02-19 10:33:01

使用插入...选择交叉加入表:

INSERT INTO IDMAPPING (metricid, storeid)
SELECT m.metrictid, s.storeid
FROM   METRIC m
       CROSS JOIN store s
WHERE  m.metrictid = 50441
AND    s.storeid = 18198;

或只使用PL/SQL并捕获错误:

DECLARE
  parent_key_not_found EXCEPTION;
  PRAGMA EXCEPTION_INIT(parent_key_not_found, -2291);
BEGIN
  INSERT INTO idmapping (metricid, storeid) VALUES (50441, 18198);
EXCEPTION
  WHEN parent_key_not_found THEN
    -- Ignore the exception
    NULL;
END;
/

db&lt;&gt; fiddle 在这里

Use INSERT ... SELECT and CROSS JOIN the tables:

INSERT INTO IDMAPPING (metricid, storeid)
SELECT m.metrictid, s.storeid
FROM   METRIC m
       CROSS JOIN store s
WHERE  m.metrictid = 50441
AND    s.storeid = 18198;

Or just use PL/SQL and catch the error:

DECLARE
  parent_key_not_found EXCEPTION;
  PRAGMA EXCEPTION_INIT(parent_key_not_found, -2291);
BEGIN
  INSERT INTO idmapping (metricid, storeid) VALUES (50441, 18198);
EXCEPTION
  WHEN parent_key_not_found THEN
    -- Ignore the exception
    NULL;
END;
/

db<>fiddle here

Oracle DB插入查询修复

葬心 2025-02-19 09:45:45

您可以使用按钮配置iOS 15:

private func makeButton(withTitle title: String) -> UIButton {

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    
    var configuration = UIButton.Configuration.filled()
    configuration.title = title
    configuration.baseBackgroundColor = .blue
    configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)
    
    button.configuration = configuration
    
    return button
}

您可以在创建按钮时简单地调用此方法,如下所示:

let button = makeButton(withTitle: "Get Started")

You can use button configuration iOS 15 onwards :

private func makeButton(withTitle title: String) -> UIButton {

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    
    var configuration = UIButton.Configuration.filled()
    configuration.title = title
    configuration.baseBackgroundColor = .blue
    configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)
    
    button.configuration = configuration
    
    return button
}

You can simply call this method while creating your button as given below:

let button = makeButton(withTitle: "Get Started")

&#x27; titleedgeinsets&#x27;在iOS 15.0中被弃用

葬心 2025-02-19 00:07:56

学生不应扩大人。
BCOZ,如果我们为学生创建OBJ,则将自动称为人员的构造函数。

student should not extend person.
bcoz, if we create obj for student, person’s constructor will be called automatically.

课堂上的Java构造函数不能应用于给定类型

葬心 2025-02-18 22:21:09

我认为您应该使用 debugger.isattached 与语句结合使用:

    public void Recursion(int depth) {
    if (Debugger.IsAttached) {
        //do something with depth
    }else {
        //do something without depth
    }
}

I think you should use Debugger.IsAttached in combination with an if statement:

    public void Recursion(int depth) {
    if (Debugger.IsAttached) {
        //do something with depth
    }else {
        //do something without depth
    }
}

debug = true时使用方法参数的任何方法

葬心 2025-02-18 20:06:25

您可以使用 grid 。更改按钮的尺寸时,这将更加健壮。

.act_button {
  width: 200px;
  height: 100px;
  background-color: #ADD8E6;
  border: none;
  display: grid;
  grid-template-columns: auto auto;
  place-content: space-between;
}

.act_button>span {
  padding: 5px;
}
<body>
  <button class="act_button" type="button">
    <span>Top left</span>
    <span>Top right</span>
    <span>Bottom left</span>
    <span>Bottom right</span>
  </button>
</body>

You can use a grid. This will be more robust when changing the dimensions of the button.

.act_button {
  width: 200px;
  height: 100px;
  background-color: #ADD8E6;
  border: none;
  display: grid;
  grid-template-columns: auto auto;
  place-content: space-between;
}

.act_button>span {
  padding: 5px;
}
<body>
  <button class="act_button" type="button">
    <span>Top left</span>
    <span>Top right</span>
    <span>Bottom left</span>
    <span>Bottom right</span>
  </button>
</body>

更改文本在html中的位置

葬心 2025-02-18 03:47:23

要处理道具的类型,您可以做:

type Props = ({ multiple: true; value: Item[] } | { multiple: false; value: Item }) & { label: string, ... }

然后,如果您检查props.multiple,它将成为一个物品数组。但是,诸如状态之类的事情仍然可能最终以项目| item [] 作为输入字样无法有效地跟踪(即使您的组件也可能会从多个= true - &gt; false更改,并且状态仍然是一个数组!)。为此,通常在组件中处理两种情况并在需要时断言类型可能是最简单的。

我看过的另一个常见选择是:

type Props<IsMultiple extends boolean> = {
 isMultiple: IsMultiple;
 value: IsMultiple extends true ? Item[] : Item;
}

这种方法的问题是,虽然 props&lt; true&gt; and props&lt; false&gt; 既正确键入(因此通常会输入typescript) {ismultiple:false,value:[]}不允许,因为它假定 props&lt; false&gt; ), props&lt; boolean&gt; 技术上允许iSmultiple和值不匹配。因此,检查props.ismultiple是否也不会打字值。

To handle the type for Props, you can do:

type Props = ({ multiple: true; value: Item[] } | { multiple: false; value: Item }) & { label: string, ... }

Then if you check props.multiple, it will typeguard value to be an array of Items. However, things like state will still likely end up typed as Item | Item[] as typescript cannot track that far effectively (and even its possible your component changes from multiple=true -> false, and the state is still an array!). For this purpose, it's likely simplest to handle both cases within the component generally, and assert types if needed.

Another common option I've seen is:

type Props<IsMultiple extends boolean> = {
 isMultiple: IsMultiple;
 value: IsMultiple extends true ? Item[] : Item;
}

The issue with this approach is that while Props<true> and Props<false> both type correctly (and thus Typescript generally infers that {isMultiple: false, value: []} isn't allowed as it assumes Props<false>), Props<boolean> technically allows isMultiple and value to not match. Because of this, checking if props.isMultiple will not typeguard value either.

基于React组件的boolean Prop确定通用

葬心 2025-02-17 20:55:33

如果有人需要“财务圆形”(总是0.5回合):

from decimal import ROUND_HALF_UP, Decimal, localcontext

def myround(x, base: int = 5):
    # starting with Python 3.11:
    # with localcontext(rounding=decimal.ROUND_HALF_UP):
    with localcontext() as ctx:
        ctx.rounding = ROUND_HALF_UP
        return base * int(decimal.Decimal(x / base).quantize(Decimal('0')))

文档圆形选项为:

  • round_ceiling (to infinity
  • round_down (to Zero)
  • round> round_floor (to -Infinity
  • round_half_down (到最接近零的关系)
  • round_half_even (到最接近的纽带,均为最接近整数)
  • round_half_up (到距离零的领带最接近)
  • round_up (远离零)
  • round_05up 是0或5;

默认情况下,python

In case someone needs "financial rounding" (0.5 rounds always up):

from decimal import ROUND_HALF_UP, Decimal, localcontext

def myround(x, base: int = 5):
    # starting with Python 3.11:
    # with localcontext(rounding=decimal.ROUND_HALF_UP):
    with localcontext() as ctx:
        ctx.rounding = ROUND_HALF_UP
        return base * int(decimal.Decimal(x / base).quantize(Decimal('0')))

As per documentation the rounding options are:

  • ROUND_CEILING (towards Infinity)
  • ROUND_DOWN (towards zero)
  • ROUND_FLOOR (towards -Infinity)
  • ROUND_HALF_DOWN (to nearest with ties going towards zero)
  • ROUND_HALF_EVEN (to nearest with ties going to nearest even integer)
  • ROUND_HALF_UP (to nearest with ties going away from zero)
  • ROUND_UP (away from zero)
  • ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)

By default Python uses ROUND_HALF_EVEN as it has some statistical advantages (the rounded results are not biased).

在Python中舍入到5(或其他数字)

葬心 2025-02-17 10:07:16

我现在看到它写下来后,这个答案在某种程度上是 Matthew Watson 维克多,但无论如何我都会提供。

首先,我同意维克多的观点,即摆脱所有筑巢是一个重要的进步。我也同意他们的观点,将您的代码分为方法在这方面可能非常有帮助。

其次,我同意Matthew的观点,如果 DO的结果可以直接用于定义条件3 的结果,也可以直接使用它,而不是将其调用评估条件3 之前。

如果可以将条件3 提取到将 do a 作为输入参数结果的方法中提取,则可以通过在每个嵌套级别创建一个方法来完全避免嵌套。例如:

public static void Main()
{
    DoYourThing();
    do E;
}
DoYourThing()
{
    if (<condition1>)
    {
        DoYourNextThing();
    }
    else
    {
        do D;
    }
}
DoYourNextThing()
{
    if (<condition2> && Condition3(A()))
    {
        do B;
    }
    else
    {
        do C;
    }
}
private bool Condition3(object a)
{
    //...
}

如果条件3 不能将其提取到将 do do a 作为输入参数的结果的方法中, doyournextthing( )可能需要以不同的方式实现。一种可能性是:

DoYourNextThing()
{
    if (ShouldDoB())
    {
        do B;
    }
    else
    {
        do C;
    }
}
ShouldDoB()
{
    if (!condition2)
    {
        return false;
    }
    
    var a = do A;
    
    return condition3; // based on a
}

作为旁注,我要说的是,使用描述性变量名称和方法名称通常比重构嵌套循环更为重要。而做 (以增强理解和可读性的方式)是黄金。

话虽这么说,我相信OP只是使用通用名称,只是为他们试图实现的逻辑提供了一个清晰,简单的例子。

I see now after writing it down that this answer is to some extent a mixture of that of Matthew Watson and that of Victor, but I will provide it anyway.

First of all, I agree with Victor that getting rid of all the nesting is an important improvement. I also agree with them that splitting your code into methods can be very helpful in that regard.

Secondly, I agree with Matthew that if the result of do A can be used directly to define the result of condition3, it may also be used directly rather than calling it before evaluating condition3.

If condition3 can be extracted to a method that takes the result of do A as an input parameter, you could avoid nesting entirely by creating one method per nesting level. As an example:

public static void Main()
{
    DoYourThing();
    do E;
}
DoYourThing()
{
    if (<condition1>)
    {
        DoYourNextThing();
    }
    else
    {
        do D;
    }
}
DoYourNextThing()
{
    if (<condition2> && Condition3(A()))
    {
        do B;
    }
    else
    {
        do C;
    }
}
private bool Condition3(object a)
{
    //...
}

If condition3 cannot be extracted to a method that takes the result of do A as an input parameter, DoYourNextThing() may need to be implemented differently. One possibility is:

DoYourNextThing()
{
    if (ShouldDoB())
    {
        do B;
    }
    else
    {
        do C;
    }
}
ShouldDoB()
{
    if (!condition2)
    {
        return false;
    }
    
    var a = do A;
    
    return condition3; // based on a
}

As a side note, I'd say that using descriptive variable names and method names is generally more important than refactoring away nested loops; whereas doing both (in a way that enhances comprehension and readability) is gold.

That being said, I trust that OP is using generic names simply to present a clear and easy example of the logic they are trying to achieve.

可以简化以下复杂的分支结构吗?

葬心 2025-02-17 07:41:42

注意:下面给出的代码是解决问题的一种方法,可能不是最好的方法。代码中的一切都可以改变。如果您在环境变量中没有mySQL,请在mysqldump和mysql之前添加路径(例如xampp,c:\ xampp \ mysql \ mysql \ bin \ mysqldump)

(希望,这会解决您的问题。完全找出所有内容并正确地实现)

备份方法:

public static void Backupdbtosql() {
    try {

        /*NOTE: Getting path to the Jar file being executed*/
        /*NOTE: YourImplementingClass-> replace with the class executing the code*/
        CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
        File jarFile = new File(codeSource.getLocation().toURI().getPath());
        String jarDir = jarFile.getParentFile().getPath();


        /*NOTE: Creating Database Constraints*/
        String dbName = "YourDBName";
        String dbUser = "YourUserName";
        String dbPass = "YourUserPassword";

        /*NOTE: Creating Path Constraints for folder saving*/
        /*NOTE: Here the backup folder is created for saving inside it*/
        String folderPath = jarDir + "\\backup";

        /*NOTE: Creating Folder if it does not exist*/
        File f1 = new File(folderPath);
        f1.mkdir();

        /*NOTE: Creating Path Constraints for backup saving*/
        /*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
         String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";

        /*NOTE: Used to create a cmd command*/
        String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;

        /*NOTE: Executing the command here*/
        Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
        if (processComplete == 0) {
            System.out.println("Backup Complete");
        } else {
            System.out.println("Backup Failure");
        }

    } catch (URISyntaxException | IOException | InterruptedException ex) {
        JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
    }
}

还原方法:

public static void Restoredbfromsql(String s) {
        try {
            /*NOTE: String s is the mysql file name including the .sql in its name*/
            /*NOTE: Getting path to the Jar file being executed*/
            /*NOTE: YourImplementingClass-> replace with the class executing the code*/
            CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(codeSource.getLocation().toURI().getPath());
            String jarDir = jarFile.getParentFile().getPath();

            /*NOTE: Creating Database Constraints*/
             String dbName = "YourDBName";
             String dbUser = "YourUserName";
             String dbPass = "YourUserPassword";

            /*NOTE: Creating Path Constraints for restoring*/
            String restorePath = jarDir + "\\backup" + "\\" + s;

            /*NOTE: Used to create a cmd command*/
            /*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
            String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            if (processComplete == 0) {
                JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
            } else {
                JOptionPane.showMessageDialog(null, "Error at restoring");
            }


        } catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
            JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
        }

    }

Note: The codes given below are one way of solving the problem and probably not the best method. Everything is changeable inside the code. If you do not have mysql in environment variables, add the path before mysqldump and mysql (e.g. For XAMPP, C:\xampp\mysql\bin\mysqldump)

(Hope, this will solve your problems. Took me a day to completely figure out everything and implement them properly)

Method for Backup:

public static void Backupdbtosql() {
    try {

        /*NOTE: Getting path to the Jar file being executed*/
        /*NOTE: YourImplementingClass-> replace with the class executing the code*/
        CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
        File jarFile = new File(codeSource.getLocation().toURI().getPath());
        String jarDir = jarFile.getParentFile().getPath();


        /*NOTE: Creating Database Constraints*/
        String dbName = "YourDBName";
        String dbUser = "YourUserName";
        String dbPass = "YourUserPassword";

        /*NOTE: Creating Path Constraints for folder saving*/
        /*NOTE: Here the backup folder is created for saving inside it*/
        String folderPath = jarDir + "\\backup";

        /*NOTE: Creating Folder if it does not exist*/
        File f1 = new File(folderPath);
        f1.mkdir();

        /*NOTE: Creating Path Constraints for backup saving*/
        /*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
         String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";

        /*NOTE: Used to create a cmd command*/
        String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;

        /*NOTE: Executing the command here*/
        Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        int processComplete = runtimeProcess.waitFor();

        /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
        if (processComplete == 0) {
            System.out.println("Backup Complete");
        } else {
            System.out.println("Backup Failure");
        }

    } catch (URISyntaxException | IOException | InterruptedException ex) {
        JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
    }
}

Method for Restore:

public static void Restoredbfromsql(String s) {
        try {
            /*NOTE: String s is the mysql file name including the .sql in its name*/
            /*NOTE: Getting path to the Jar file being executed*/
            /*NOTE: YourImplementingClass-> replace with the class executing the code*/
            CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
            File jarFile = new File(codeSource.getLocation().toURI().getPath());
            String jarDir = jarFile.getParentFile().getPath();

            /*NOTE: Creating Database Constraints*/
             String dbName = "YourDBName";
             String dbUser = "YourUserName";
             String dbPass = "YourUserPassword";

            /*NOTE: Creating Path Constraints for restoring*/
            String restorePath = jarDir + "\\backup" + "\\" + s;

            /*NOTE: Used to create a cmd command*/
            /*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
            String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
            int processComplete = runtimeProcess.waitFor();

            /*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
            if (processComplete == 0) {
                JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
            } else {
                JOptionPane.showMessageDialog(null, "Error at restoring");
            }


        } catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
            JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
        }

    }

简单备份并从Java为MySQL数据库还原

葬心 2025-02-16 23:58:37

您可以创建一个具有服务方法定义的 a ,并使两个服务都实现了该摘要类(在打字稿中,您可以像一个摘要类一样界面)

在您的组件 c 注入构造函数中的抽象类(与接口不同,抽象类可用作注入令牌),

constructor(private service: A)

c ,提供相关服务

// replace useExisting with useClass if
// the service isn't already available
@Component({
  selector: 'parent-one',
  /* . . . */
  providers: [{
    provide: A, useExisting: S
  }]
})

@Component({
  selector: 'parent-two',
  /* . . . */
  providers: [{
    provide: A, useExisting: S2
  }]
})

You could create an abstract class A that has the method definitions of the services, and have both services implement that abstract class (in typescript you can implement an abstract class just like an interface)

In your component C inject that abstract class in the constructor (unlike interfaces, abstract classes can be used as injection tokens)

constructor(private service: A)

In the parent components of the two different uses of C, provide the relevant services

// replace useExisting with useClass if
// the service isn't already available
@Component({
  selector: 'parent-one',
  /* . . . */
  providers: [{
    provide: A, useExisting: S
  }]
})

@Component({
  selector: 'parent-two',
  /* . . . */
  providers: [{
    provide: A, useExisting: S2
  }]
})

如何使用不同的实现处理 /注射服务接口

葬心 2025-02-16 21:18:53

不可避免地会创建新的索引。当您从一个数组移动到另一个数组时,它需要一个索引才能知道该项目的位置。

实际上,即使您在同一列表中更改项目的位置(同一数组),即使在此项目索引更改,也会因更改而影响的所有其他项目,并且由于单个项目的更改,因此更改了其他项目的索引(+1 / -1)。

  todo = ['Get to work', 'Pick up groceries', 'Go home', 'Fall asleep'];

  done = ['Get up', 'Brush teeth', 'Take a shower', 'Check e-mail', 'Walk dog'];

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); // when change happens in same array (same list)
      this.eventIndex = [event.previousIndex,event.currentIndex];
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
      this.eventIndex = [event.previousIndex,event.currentIndex]; // when changes arrays (lists)
    }
  }
    /** Index of the item when it was picked up. */
    previousIndex: number;
    /** Current index of the item. */
    currentIndex: number;
    /** Item that is being dropped. */
    item: CdkDrag<I>;
    /** Container in which the item was dropped. */
    container: CdkDropList<T>;
    /** Container from which the item was picked up. Can be the same as the `container`. */

It is unavoidable that new index is created. When you move from one array to another, it needs an index to know location of the item.

And actually, even when you change location of the item within the same list (same array), even then the item index changes and so does every other items that are affected by the change and now due to change of a single item, so have changed other items their index (+1 / -1).

  todo = ['Get to work', 'Pick up groceries', 'Go home', 'Fall asleep'];

  done = ['Get up', 'Brush teeth', 'Take a shower', 'Check e-mail', 'Walk dog'];

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); // when change happens in same array (same list)
      this.eventIndex = [event.previousIndex,event.currentIndex];
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
      this.eventIndex = [event.previousIndex,event.currentIndex]; // when changes arrays (lists)
    }
  }
    /** Index of the item when it was picked up. */
    previousIndex: number;
    /** Current index of the item. */
    currentIndex: number;
    /** Item that is being dropped. */
    item: CdkDrag<I>;
    /** Container in which the item was dropped. */
    container: CdkDropList<T>;
    /** Container from which the item was picked up. Can be the same as the `container`. */

https://stackblitz.com/edit/angular-mccx4a-b6etwg?file=src%2Fapp%2Fcdk-drag-drop-connected-sorting-group-example.ts

如何使用CDKDRAGDROP将元素从一个列表中删除到另一个列表时如何停止在列表中添加索引

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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