问:
Bitbake build fails because of a python function
During execution of a bitbake command the task which builds rpm package fails because of a python function. I have been unable to determine what could cause this function to fail. Do you guys have any ideas?</p>
```<code>    ERROR: perl-5.30.1-r0 do_package_write_rpm: Error executing a python function in exec_func_python()
autogenerated:The stack trace of python calls that resulted in this exception/failure was: File: 'exec_func_python() autogenerated', lineno: 2, function: <module>
0001: ***
0002:do_package_rpm(d)
0003:
File: '/srv/yocto/poky/meta/classes/package_rpm.bbclass', lineno: 712, function: do_package_rpm
0708:
0709:    # Build the rpm package!
0710:    d.setVar('BUILDSPEC', cmd + \"\\n\" + cleanupcmd + \"\\n\")
0711:    d.setVarFlag('BUILDSPEC', 'func', '1')
0712:    bb.build.exec_func('BUILDSPEC', d)
0713:
0714:    if d.getVar('RPM_SIGN_PACKAGES') == '1':
0715:        bb.build.exec_func(\"sign_rpm\", d)
0716:}
File: '/srv/yocto/poky/bitbake/lib/bb/build.py', lineno: 254, function: exec_func
0250:    with bb.utils.fileslocked(lockfiles):
0251:    if ispython:
0252:            exec_func_python(func, d, runfile, cwd=adir)
0253:    else: ***
0254:            exec_func_shell(func, d, runfile, cwd=adir)
0255:
0256:    try:
0257:        curcwd = os.getcwd()
0258:    except:
File: '/srv/yocto/poky/bitbake/lib/bb/build.py', lineno: 455, function: exec_func_shell
0451:    with open(fifopath, 'r+b', buffering=0) as fifo:
0452:        try:
0453:            bb.debug(2, \"Executing shell function %s\" % func)
0454:            with open(os.devnull, 'r+') as stdin, logfile: ***
0455:                bb.process.run(cmd, shell=False, stdin=stdin, log=logfile, extrafiles=[(fifo,readfifo)])
0456:        finally:
0457:            os.unlink(fifopath)
0458:
0459:    bb.debug(2, \"Shell function %s finished\" % func)
File: '/srv/yocto/poky/bitbake/lib/bb/process.py', lineno: 184, function: run
0180:
0181:    if pipe.returncode != 0:
0182:        if log:
0183:            # Don't duplicate the output in the exception if logging it ***
0184:            raise ExecutionError(cmd, pipe.returncode, None, None)
0185:        raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
0186:    return stdout, stderr Exception: bb.process.ExecutionError: Execution of '/srv/yocto/build/tmp/work/corei7-64-poky-linux/perl/5.30.1-r0/temp/run.BUILDSPEC.35372' failed with exit code 1
</code>```

答: I had the same problem and it was happening because my SECTION variable in my recipe was empty (SECTION=""). I attributed any value to it, like SECTION = "a", and it fixed the problem.

Body:
During execution of a bitbake command the task which builds rpm package fails because of a python function. I have been unable to determine what could cause this function to fail. Do you guys have any ideas?

    ERROR: perl-5.30.1-r0 do_package_write_rpm: Error executing a python function in exec_func_python()
autogenerated:The stack trace of python calls that resulted in this exception/failure was: File: 'exec_func_python() autogenerated', lineno: 2, function: <module>
0001: ***
0002:do_package_rpm(d)
0003:
File: '/srv/yocto/poky/meta/classes/package_rpm.bbclass', lineno: 712, function: do_package_rpm
0708:
0709:    # Build the rpm package!
0710:    d.setVar('BUILDSPEC', cmd + \"\\n\" + cleanupcmd + \"\\n\")
0711:    d.setVarFlag('BUILDSPEC', 'func', '1')
0712:    bb.build.exec_func('BUILDSPEC', d)
0713:
0714:    if d.getVar('RPM_SIGN_PACKAGES') == '1':
0715:        bb.build.exec_func(\"sign_rpm\", d)
0716:}
File: '/srv/yocto/poky/bitbake/lib/bb/build.py', lineno: 254, function: exec_func
0250:    with bb.utils.fileslocked(lockfiles):
0251:    if ispython:
0252:            exec_func_python(func, d, runfile, cwd=adir)
0253:    else: ***
0254:            exec_func_shell(func, d, runfile, cwd=adir)
0255:
0256:    try:
0257:        curcwd = os.getcwd()
0258:    except:
File: '/srv/yocto/poky/bitbake/lib/bb/build.py', lineno: 455, function: exec_func_shell
0451:    with open(fifopath, 'r+b', buffering=0) as fifo:
0452:        try:
0453:            bb.debug(2, \"Executing shell function %s\" % func)
0454:            with open(os.devnull, 'r+') as stdin, logfile: ***
0455:                bb.process.run(cmd, shell=False, stdin=stdin, log=logfile, extrafiles=[(fifo,readfifo)])
0456:        finally:
0457:            os.unlink(fifopath)
0458:
0459:    bb.debug(2, \"Shell function %s finished\" % func)
File: '/srv/yocto/poky/bitbake/lib/bb/process.py', lineno: 184, function: run
0180:
0181:    if pipe.returncode != 0:
0182:        if log:
0183:            # Don't duplicate the output in the exception if logging it ***
0184:            raise ExecutionError(cmd, pipe.returncode, None, None)
0185:        raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
0186:    return stdout, stderr Exception: bb.process.ExecutionError: Execution of '/srv/yocto/build/tmp/work/corei7-64-poky-linux/perl/5.30.1-r0/temp/run.BUILDSPEC.35372' failed with exit code 1


来源: stackexchange

问:
Would this login function be secure?
Would this login function be secure, I put the url data straight into the function, but would this be unsafe? Could this be injected, I know it has no SQL, but is it venerable?

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $login = check_login($_POST['emailusername'], $_POST['password']);
    if ($login) {
        // Registration Success
       header("location: /");
    } else {
        // Registration Failed
        echo 'Username / password wrong';
    }
}
</code>```

function:

```<code>// CHECK LOGIN SCRIPT
   function check_login($emailusername, $password)
    {

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'example';
$username1 = 'root';
$password1 = 'root';

$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username1, $password1);

                $password = md5($password);

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($emailusername, $emailusername, $password));

if ($result = $statement->fetchObject()) {
    $_SESSION['login'] = true;
    $_SESSION['uid'] = $result->uid;
    return TRUE;
}else{
    return FALSE;
}    }
</code>```

答:
To make a good authentication system isn't that simple, my friend. Here are some 'first steps'.

If you aren't sure, you shouldn't make your own. It's anti-pattern called 'reinventing the square wheel'!

ContentLicense: CC BY-SA 3.0

Title: Would this login function be secure?

Body:
Would this login function be secure, I put the url data straight into the function, but would this be unsafe? Could this be injected, I know it has no SQL, but is it venerable?

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $login = check_login($_POST['emailusername'], $_POST['password']);
    if ($login) {
        // Registration Success
       header("location: /");
    } else {
        // Registration Failed
        echo 'Username / password wrong';
    }
}

function:

// CHECK LOGIN SCRIPT
   function check_login($emailusername, $password)
    {

$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'example';
$username1 = 'root';
$password1 = 'root';

$dsn = "mysql:host=$host;port=$port;dbname=$database";
$db = new PDO($dsn, $username1, $password1);

                $password = md5($password);

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?');
$statement->execute(array($emailusername, $emailusername, $password));

if ($result = $statement->fetchObject()) {
    $_SESSION['login'] = true;
    $_SESSION['uid'] = $result->uid;
    return TRUE;
}else{
    return FALSE;
}    }


问:
Angular Router - named router-outlets under children routes
I try to use multiple router outlets in my Angular app. I experience problems whenever I try to use multiple router outlets inside my shell container.

The intended behaviour is to have both the main component and the details component to be rendered when I visit their paths:

https://stackblitz.com/edit/angular-ivy-w9omb3?file=src%2Fapp%2Fapp.component.html

However, in this example, the app-routing.module uses a flat route structure without any children routes.

```<code>// app-routing.module.ts in flat solution
const routes: Routes = [
  { path: '', component: EmptyShellComponent },
  {
    path: 'feature1',
    loadChildren: () =>
      import('./feature-one/feature-one.module').then(
        (m) => m.FeatureOneModule
      ),
  },
  {
    path: 'feature2',
    loadChildren: () =>
      import('./feature-two/feature-two.module').then(
        (m) => m.FeatureTwoModule
      ),
  },
];
</code>```

How I want my routes in the app.routing-module to look like:

```<code>//app-routing.module.ts in solution with children routes
const routes: Routes = [
  {
    path: '',
    component: ShellComponent,
    children: [
      { path: '', component: EmptyShellComponent },
      {
        path: 'feature1',
        loadChildren: () =>
          import('./feature-one/feature-one.module').then(
            (m) => m.FeatureOneModule
          ),
      },
      {
        path: 'feature2',
        loadChildren: () =>
          import('./feature-two/feature-two.module').then(
            (m) => m.FeatureTwoModule
          ),
      },
    ],
  },
];
</code>```

However, when I use this structure I don't manage to get the router-outlet for the details to render anything: https://stackblitz.com/edit/angular-ivy-yasztr?file=src%2Fapp%2Fapp-routing.module.ts

What approach should I take to tackle this problem to allow multiple router outlets in the children modules of the shell?

EDIT

A requirement is that I would like to have a designated space for the details view at the shell-level, where one can load different detail components from different modules. Is this possible somehow? I want to be able to view feature1's main component at the same time as I am viewing feature2's details and I want both modules to be lazy loaded.

EDIT 2

By adding an the named router-outlet in the app.component.html I get the following state:

The details from the different module is rendered, but outside of the shell.

Updated stackblitz: https://stackblitz.com/edit/angular-ivy-ahptuq?file=src%2Fapp%2Fapp.component.html

答:
In case of children routes, what you are talking about is nested router outlet where the multiple router-outlet directive is not part of one component html. In that case naming of outlet is not required. You can read more at :-

https://blog.devgenius.io/the-art-of-nested-router-outlets-in-angular-dafb38245a30

ContentLicense: CC BY-SA 4.0

Body:
I try to use multiple router outlets in my Angular app. I experience problems whenever I try to use multiple router outlets inside my shell container.

The intended behaviour is to have both the main component and the details component to be rendered when I visit their paths:

https://stackblitz.com/edit/angular-ivy-w9omb3?file=src%2Fapp%2Fapp.component.html

However, in this example, the app-routing.module uses a flat route structure without any children routes.

// app-routing.module.ts in flat solution
const routes: Routes = [
  { path: '', component: EmptyShellComponent },
  {
    path: 'feature1',
    loadChildren: () =>
      import('./feature-one/feature-one.module').then(
        (m) => m.FeatureOneModule
      ),
  },
  {
    path: 'feature2',
    loadChildren: () =>
      import('./feature-two/feature-two.module').then(
        (m) => m.FeatureTwoModule
      ),
  },
];

How I want my routes in the app.routing-module to look like:

//app-routing.module.ts in solution with children routes
const routes: Routes = [
  {
    path: '',
    component: ShellComponent,
    children: [
      { path: '', component: EmptyShellComponent },
      {
        path: 'feature1',
        loadChildren: () =>
          import('./feature-one/feature-one.module').then(
            (m) => m.FeatureOneModule
          ),
      },
      {
        path: 'feature2',
        loadChildren: () =>
          import('./feature-two/feature-two.module').then(
            (m) => m.FeatureTwoModule
          ),
      },
    ],
  },
];

However, when I use this structure I don't manage to get the router-outlet for the details to render anything: https://stackblitz.com/edit/angular-ivy-yasztr?file=src%2Fapp%2Fapp-routing.module.ts

What approach should I take to tackle this problem to allow multiple router outlets in the children modules of the shell?

EDIT

A requirement is that I would like to have a designated space for the details view at the shell-level, where one can load different detail components from different modules. Is this possible somehow? I want to be able to view feature1's main component at the same time as I am viewing feature2's details and I want both modules to be lazy loaded.

EDIT 2

By adding an the named router-outlet in the app.component.html I get the following state:

The details from the different module is rendered, but outside of the shell.

Updated stackblitz: https://stackblitz.com/edit/angular-ivy-ahptuq?file=src%2Fapp%2Fapp.component.html


问:
Unable to convert runtime connection string to its design-time equivalent
I updated to Visual Studio 2013 last week and I can no longer update my Entity Data model through the visual studio designer (.edmx file).

When I right click > update model from database I now receive this error:

An Exception of type 'System.ArgumentException' occurred while
  attempting to update from the database.  The exception message is:
  'Unable to convert runtime connection string to its design-time
  equivalent.  Connection string: server=192.168.100.103;user
  id=xxx;password=xxx;database=xxx;persist security info=True'.

My connection string is as follows:

```<code>  <connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/Db.csdl|res://*/Db.ssdl|res://*/Db.msl;provider=MySql.Data.MySqlClient;provider connection string="server=192.168.100.103;user id=xxx;password=xxx;database=xxx;persist security info=True"" providerName="System.Data.EntityClient" />
</code>```

The process still works fine in Visual Studio 2012

答:
The problem is likely that MySQL for Visual Studio is missing. This can happen when Microsoft updates Visual Studio OR any related components.

You can check by:

Open your VS project.

Open Server Explorer and click on the connection.

Right click and open Properties. If the connection or provider are missing reinstall the connector and provider according to the instructions shown below:

STEPS on how to fix the problem:

NOTE: This uses version 6.8.10, your version may be different. Whatever version you use, all installed components MUST BE COMPATIBLE. That includes the Connector, MySQL for VS, and the MySql.Data components in your project.

Body:
I updated to Visual Studio 2013 last week and I can no longer update my Entity Data model through the visual studio designer (.edmx file).

When I right click > update model from database I now receive this error:

An Exception of type 'System.ArgumentException' occurred while
  attempting to update from the database.  The exception message is:
  'Unable to convert runtime connection string to its design-time
  equivalent.  Connection string: server=192.168.100.103;user
  id=xxx;password=xxx;database=xxx;persist security info=True'.

My connection string is as follows:

  <connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/Db.csdl|res://*/Db.ssdl|res://*/Db.msl;provider=MySql.Data.MySqlClient;provider connection string="server=192.168.100.103;user id=xxx;password=xxx;database=xxx;persist security info=True"" providerName="System.Data.EntityClient" />

The process still works fine in Visual Studio 2012


问:
Python Loop and Range function
Can anyone please explain this python code, how the answer is "5050" ?

total = 0
for number in range(0, 101):
    total += number
print(total)
```

答:
what happen is when run the this code is the for loop going to add the number to the total variable
so in the first loop the total = 0 and the number = 0 so the total will equal to 0
in the second loop the total = 0 and the number = 1 so the total will equal to 1
in the second loop the total = 1 and the number = 2 so the total will equal to 3
and so on
in the last loop :
the total = 4950 and the number = 100 so the total will equal to 5050 and this is output you've got

hope you understood

Title: Python Loop and Range function


问:
WebApplication.Models.Category instead of value
I want to add a DropDownList in my Insert View.

Controller:

```
public ActionResult Create()
{
    ViewBag.CategoryList = new SelectList(Category.GetCategories());
    return View("Insert", new Category());
}
```

View:

```
    @Html.DropDownListFor(model => model.Category, (IEnumerable<SelectListItem>)
   (ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
```

The Category class has only one string field named Title. Instead of getting the value of Title I'm getting WebApplication.Models.Category.

答:
Check that the Title is defined as property and not a field to be data binding work properly.

Then try the following:

public ActionResult Create()
{
    ViewBag.CategoryList = Category.GetCategories();
    return View("Insert", new Product());
}
```
<p>And in the <code>Insert</code> view:</p>
```@using WebApplication1.Models @* Category namespace *@
@model WebApplication1.Models.Product

@{
    IEnumerable<Category> categories = (IEnumerable<Category>)ViewBag.CategoryList;
}

@Html.DropDownListFor(m => categories.GetEnumerator().Current,
          categories.Select(d =>
          {
              return new SelectListItem() { Text = d.Title, Value = d.Title };
          }),
          "Select Category", new { @class = "form-control" })
```

Body:
I want to add a DropDownList in my Insert View.

Controller:

public ActionResult Create()
{
    ViewBag.CategoryList = new SelectList(Category.GetCategories());
    return View("Insert", new Category());
}

View:

    @Html.DropDownListFor(model => model.Category, (IEnumerable<SelectListItem>)
   (ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })

The Category class has only one string field named Title. Instead of getting the value of Title I'm getting WebApplication.Models.Category.

Body:
Check that the Title is defined as property and not a field to be data binding work properly.

Then try the following:

public ActionResult Create()
{
    ViewBag.CategoryList = Category.GetCategories();
    return View("Insert", new Product());
}

And in the Insert view:

@using WebApplication1.Models @* Category namespace *@
@model WebApplication1.Models.Product

@{
    IEnumerable<Category> categories = (IEnumerable<Category>)ViewBag.CategoryList;
}

@Html.DropDownListFor(m => categories.GetEnumerator().Current,
          categories.Select(d =>
          {
              return new SelectListItem() { Text = d.Title, Value = d.Title };
          }),
          "Select Category", new { @class = "form-control" })


问:
How to grab the onSubmit event for a form?
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

```<code>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    <title>Hello World</title>
    </head>
    <body>
    <h2>Test</h2>
    <form action="#" method="post" id="commentform">

    <p><input type="text" name="author" id="author" size="22" tabindex="1" />
    <label for="author"><small>Name (required)</small></label></p>

    <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

    <script type="text/JavaScript">
    <!--
    alert("Hello world");

    var formCheck = document.getElementById("commentform");

    formCheck.onSubmit = doMapping();

    function doMapping() {
        alert("form submitted");
        return false;
    }

    -->
    </script>

    </body>
    </html>
</code>```

答:
Using jQuery.</p>

```<code>$(document).ready( function() {
    $('#commentform').submit( function() {
        alert('form submitted');
        return false;
    });
});
</code>```

OwnerDisplayName: Dan

LastEditorDisplayName: Dan

Body:
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <title>Hello World</title>

Test

    <form action="#" method="post" id="commentform">

<input type="text" name="author" id="author" size="22" tabindex="1" />
    Name (required)

<input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

Body:
Using jQuery.

$(document).ready( function() {
    $('#commentform').submit( function() {
        alert('form submitted');
        return false;
    });
});

OwnerDisplayName: tvanfosson

ContentLicense: CC BY-SA 2.5


问:
Whitespace at top and within body div tags
Can someone please just tell me what my sorry, stupid eyes are missing?

Whitespace appears at the top of my browser window, and between two div tag containers (all browsers.)

p, body, html, every div, all margin:0px;

Gracias.

答:
remove the margin-top: 20px; off of
 and put padding-top: 20px; onto

The reasoning is that since it's the top most container it's margin-top put onto the parent container, I'm sure there's a W3C doc on why this is, but it's just like that. If you want to move something away that's the top element of a container, you need to use padding instead on it's parent.

Body:
remove the margin-top: 20px; off of <div class="menucontainer"> and put padding-top: 20px; onto <div class="lightsandcolorscontainer">

The reasoning is that since it's the top most container it's margin-top put onto the parent container, I'm sure there's a W3C doc on why this is, but it's just like that. If you want to move something away that's the top element of a container, you need to use padding instead on it's parent.


问:
How do I have to declare copyright on my Website?
I have a Javascript, Html and Css Website and have some Pictures that aren't mine.
Now I have the Question how is the correct way how you give credits.
I just want to be on the safe Site.
For now I made a direct link to the Photo.

Here is the code :

```<code><p title="Copyright">
     <a href="https://unsplash.com/photos/cMcake-xZVY">Link to the Picture</a></p>
</code>```

答: you can add an element where on hover you can pop that up in which it is written that the owner of the picture is someone else and you want to give credit to them, another way is to take permission from that person to use the image in your website</p>

Body:
I have a Javascript, Html and Css Website and have some Pictures that aren't mine.
Now I have the Question how is the correct way how you give credits.
I just want to be on the safe Site.
For now I made a direct link to the Photo.

Here is the code :

     Link to the Picture


问:
ViewCompat.getLayoutDirection doesn't return the correct layout until after onResume()
I'm trying to handle RTL (Right-to-left) layouts within a complex layout that contains two TextViews and an ImageButton.

However, the layout direction is never returning RTL as the layout direction until some time after the onResume() method has been called. The call to ViewCompat.getLayoutDirection(getView()) always returns LTR at every point in the life cycle I have checked except for in onStop()

We use this method all the time to handle bind viewholders in a RecyclerView but this is the first time we've tried to use it on a complex layout outside of a RecyclerView.

Has anyone else seen this behavior or know how (or when) to get the proper layout direction?

Here is what I am doing to handle RTL:

MyFragment.java:

```<code>private TextView title;
private TextView subtitle;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_preview_audio, container, false);
    loadAsset();
    validateAsset();

    int layoutDirection = ViewCompat.getLayoutDirection(container);
    setupUi(layoutDirection);

    populateData();

    return view;
}

private void setupUi(int layoutDirection) {
    int gravity = GravityCompat.getAbsoluteGravity(GravityCompat.START, layoutDirection);
    title.setGravity(gravity);
    subtitle.setGravity(gravity);
}
</code>```

details.xml (included in fragment_preview_audio)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/details_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="vertical"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="@color/text_dark_grey"
        android:textStyle="bold"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="8dp"
        android:layout_weight="1"
        />

    <ImageButton
        android:id="@+id/menu_button"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/ic_more_vert_black_24dp"
        style="?android:attr/buttonBarButtonStyle"
        tools:ignore="ContentDescription"/>

</LinearLayout>

<TextView
    android:id="@+id/subtitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="@color/text_light_grey"
    android:singleLine="false"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    />
</code>```

答:
Create resource file named booleans.xml in values folder with this resource:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_rtl">false</bool>
</resources>
</code>```

Create another booleans.xml but this time in values-ldrtl folder with this resource:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_rtl">true</bool>
</resources>
</code>```

then you easily access it by this

```<code>boolean isRtl = getResources().getBoolean(R.bool.is_rtl);
</code>```

and get if layout direction is from right to left or not.

Body:
I'm trying to handle RTL (Right-to-left) layouts within a complex layout that contains two TextViews and an ImageButton.

However, the layout direction is never returning RTL as the layout direction until some time after the onResume() method has been called. The call to ViewCompat.getLayoutDirection(getView()) always returns LTR at every point in the life cycle I have checked except for in onStop()

We use this method all the time to handle bind viewholders in a RecyclerView but this is the first time we've tried to use it on a complex layout outside of a RecyclerView.

Has anyone else seen this behavior or know how (or when) to get the proper layout direction?

Here is what I am doing to handle RTL:

MyFragment.java:

private TextView title;
private TextView subtitle;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_preview_audio, container, false);
    loadAsset();
    validateAsset();

    int layoutDirection = ViewCompat.getLayoutDirection(container);
    setupUi(layoutDirection);

    populateData();

    return view;
}

private void setupUi(int layoutDirection) {
    int gravity = GravityCompat.getAbsoluteGravity(GravityCompat.START, layoutDirection);
    title.setGravity(gravity);
    subtitle.setGravity(gravity);
}

details.xml (included in fragment_preview_audio)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/details_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="vertical"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="@color/text_dark_grey"
        android:textStyle="bold"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="8dp"
        android:layout_weight="1"
        />

    <ImageButton
        android:id="@+id/menu_button"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="8dp"
        android:src="@drawable/ic_more_vert_black_24dp"
        style="?android:attr/buttonBarButtonStyle"
        tools:ignore="ContentDescription"/>

</LinearLayout>

<TextView
    android:id="@+id/subtitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textColor="@color/text_light_grey"
    android:singleLine="false"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    />

Body:
Create resource file named booleans.xml in values folder with this resource:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_rtl">false</bool>
</resources>

Create another booleans.xml but this time in values-ldrtl folder with this resource:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_rtl">true</bool>
</resources>

then you easily access it by this

boolean isRtl = getResources().getBoolean(R.bool.is_rtl);

and get if layout direction is from right to left or not.


问:
Spring AMQP - anonymous queue declaration
I am trying to declare anonymous queue using Spring AMQP annotations, but seems it is not working.

```<code>@RabbitListener(
  id = "b1",
  bindings =
      @QueueBinding(
          value =
              @Queue(
                  name = "",
                  durable = "false",
                  exclusive = "true",
                  autoDelete = "true",
                  admins = "amqpAdmin1"),
          exchange =
              @Exchange(
                  value = "${my.rabbitmq[0].exchange}", declare = "false",
                  ignoreDeclarationExceptions = "true",
                  type = ExchangeTypes.TOPIC,
                  admins = "amqpAdmin1"),
          key = "*.*.*.*.*.*.*.-",
          admins = "amqpAdmin1"),
  admin = "amqpAdmin1",
  containerFactory = "lf1",
  autoStartup = "true")
</code>```

I read that I can use empty name param, and it should create anonymous queue - but the thing is that I need server-generated name (I have no privileges to name my own queue). Is this possible at all with spring AMQP lib currently?

I see in the code that it currently uses

```<code>private String declareQueue(org.springframework.amqp.rabbit.annotation.Queue bindingQueue,
        Collection<Declarable> declarables) {
    String queueName = (String) resolveExpression(bindingQueue.value());
    boolean isAnonymous = false;
    if (!StringUtils.hasText(queueName)) {
        queueName = Base64UrlNamingStrategy.DEFAULT.generateName(); //<---- HERE
        // default exclusive/autodelete and non-durable when anonymous
        isAnonymous = true;
    }
</code>```

but here instead of Base64UrlNamingStrategy.DEFAULT.generateName(); -> I would need to spring to go to RabbitMQ broker and fetch RabbitMQ generated name and use that one.

UPDATE

```<code>@Bean
  public Queue q2(){
    Queue q = QueueBuilder.nonDurable().exclusive().autoDelete().build();
    //Queue q = new Queue("", false, true, true); --> same
    q.setAdminsThatShouldDeclare(amqpAdmin2());
    return q;
  }

  @Bean
  public Exchange e2(@Value("${my.rabbitmq[1].exchange}") String name){
    Exchange e = ExchangeBuilder.topicExchange(name).ignoreDeclarationExceptions().build();
    e.setAdminsThatShouldDeclare(amqpAdmin2());
    return e;
  }

  @Bean
  public Binding bin2(Queue q2, Exchange e2){
    Binding b = BindingBuilder.bind(q2).to(e2).with("*.*.*.*.*.*.*.-").noargs();
    b.setAdminsThatShouldDeclare(amqpAdmin2());
    return b;
  }

  @RabbitListener(id = "b2", queues = "#{q2}",
      admin = "amqpAdmin2",
      containerFactory = "lf2", autoStartup = "true")
  public void listen2(GenericMessage<?> msg) {
    comparator.recordForComparison(props.getRabbitmq().get(1).getId(), msg.getPayload());
  }
</code>```

and this is in the logs:

```<code>Auto-declaring a non-durable, auto-delete, or exclusive Queue () durable:false, auto-delete:true, exclusive:true. It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.
2022-02-10 09:22:43.660  INFO 30076 --- [           main] o.s.a.r.l.DirectMessageListenerContainer : Container initialized for queues: [spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration]
2022-02-10 09:22:43.661  INFO 30076 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: my.server.com:5671
2022-02-10 09:22:43.765 ERROR 30076 --- [           b2-1] o.s.a.r.l.DirectMessageListenerContainer : Queue not present, scheduling consumer SimpleConsumer [queue=spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration, index=0, consumerTag=null identity=3f844994] for restart
</code>```

and this is what I added after removing @RabbitListener. Now it works with this:

```<code>@Bean
  public MessageListenerContainer c2(DirectRabbitListenerContainerFactory lf2, Queue q2){
    DirectMessageListenerContainer lc = lf2.createListenerContainer();
    lc.setQueues(q2);
    lc.setAutoStartup(true);
    MessageListenerAdapter a = new MessageListenerAdapter();
    a.setMessageConverter(converter());
    a.setDefaultListenerMethod("receive");
    a.setDelegate(new MessageReceiver(props.getRabbitmq().get(1).getId()));
    lc.setupMessageListener(a);
    lc.afterPropertiesSet();
    return lc;
  }

class MessageReceiver{

    private final int id;

    public MessageReceiver(int id){
      this.id= id;
    }

    void receive(Object o){
      comparator.recordForComparison(this.id, o);
    }
  }
</code>```

答:
I think this one should be treated as a bug and missing part when we implemented this https://jira.spring.io/browse/AMQP-816. So, with regular Queue bean definition you are able to set the name to empty string and the actualName is going to be set after declaration on the broker via RabbitAdmin.

Consider that as a workaround for your use-case. You must move this @QueueBinding to the Binding, Queue and Exchange bean definitions. And then you just use queues = "#{myQueueBean}". See docs for more info: https://docs.spring.io/spring-amqp/docs/current/reference/html/#builder-api.

Please, raise a GH issue for this bug and we will fix it soon.

Body:
I am trying to declare anonymous queue using Spring AMQP annotations, but seems it is not working.

@RabbitListener(
  id = "b1",
  bindings =
      @QueueBinding(
          value =
              @Queue(
                  name = "",
                  durable = "false",
                  exclusive = "true",
                  autoDelete = "true",
                  admins = "amqpAdmin1"),
          exchange =
              @Exchange(
                  value = "${my.rabbitmq[0].exchange}", declare = "false",
                  ignoreDeclarationExceptions = "true",
                  type = ExchangeTypes.TOPIC,
                  admins = "amqpAdmin1"),
          key = "*.*.*.*.*.*.*.-",
          admins = "amqpAdmin1"),
  admin = "amqpAdmin1",
  containerFactory = "lf1",
  autoStartup = "true")

I read that I can use empty name param, and it should create anonymous queue - but the thing is that I need server-generated name (I have no privileges to name my own queue). Is this possible at all with spring AMQP lib currently?

I see in the code that it currently uses

private String declareQueue(org.springframework.amqp.rabbit.annotation.Queue bindingQueue,
        Collection<Declarable> declarables) {
    String queueName = (String) resolveExpression(bindingQueue.value());
    boolean isAnonymous = false;
    if (!StringUtils.hasText(queueName)) {
        queueName = Base64UrlNamingStrategy.DEFAULT.generateName(); //<---- HERE
        // default exclusive/autodelete and non-durable when anonymous
        isAnonymous = true;
    }

but here instead of Base64UrlNamingStrategy.DEFAULT.generateName(); -> I would need to spring to go to RabbitMQ broker and fetch RabbitMQ generated name and use that one.

UPDATE

@Bean
  public Queue q2(){
    Queue q = QueueBuilder.nonDurable().exclusive().autoDelete().build();
    //Queue q = new Queue("", false, true, true); --> same
    q.setAdminsThatShouldDeclare(amqpAdmin2());
    return q;
  }

  @Bean
  public Exchange e2(@Value("${my.rabbitmq[1].exchange}") String name){
    Exchange e = ExchangeBuilder.topicExchange(name).ignoreDeclarationExceptions().build();
    e.setAdminsThatShouldDeclare(amqpAdmin2());
    return e;
  }

  @Bean
  public Binding bin2(Queue q2, Exchange e2){
    Binding b = BindingBuilder.bind(q2).to(e2).with("*.*.*.*.*.*.*.-").noargs();
    b.setAdminsThatShouldDeclare(amqpAdmin2());
    return b;
  }

  @RabbitListener(id = "b2", queues = "#{q2}",
      admin = "amqpAdmin2",
      containerFactory = "lf2", autoStartup = "true")
  public void listen2(GenericMessage<?> msg) {
    comparator.recordForComparison(props.getRabbitmq().get(1).getId(), msg.getPayload());
  }

and this is in the logs:

Auto-declaring a non-durable, auto-delete, or exclusive Queue () durable:false, auto-delete:true, exclusive:true. It will be redeclared if the broker stops and is restarted while the connection factory is alive, but all messages will be lost.
2022-02-10 09:22:43.660  INFO 30076 --- [           main] o.s.a.r.l.DirectMessageListenerContainer : Container initialized for queues: [spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration]
2022-02-10 09:22:43.661  INFO 30076 --- [           main] o.s.a.r.c.CachingConnectionFactory       : Attempting to connect to: my.server.com:5671
2022-02-10 09:22:43.765 ERROR 30076 --- [           b2-1] o.s.a.r.l.DirectMessageListenerContainer : Queue not present, scheduling consumer SimpleConsumer [queue=spring.gen-ZAVana-pSSW2WaanrkVZXw_awaiting_declaration, index=0, consumerTag=null identity=3f844994] for restart

and this is what I added after removing @RabbitListener. Now it works with this:

@Bean
  public MessageListenerContainer c2(DirectRabbitListenerContainerFactory lf2, Queue q2){
    DirectMessageListenerContainer lc = lf2.createListenerContainer();
    lc.setQueues(q2);
    lc.setAutoStartup(true);
    MessageListenerAdapter a = new MessageListenerAdapter();
    a.setMessageConverter(converter());
    a.setDefaultListenerMethod("receive");
    a.setDelegate(new MessageReceiver(props.getRabbitmq().get(1).getId()));
    lc.setupMessageListener(a);
    lc.afterPropertiesSet();
    return lc;
  }

class MessageReceiver{

    private final int id;

    public MessageReceiver(int id){
      this.id= id;
    }

    void receive(Object o){
      comparator.recordForComparison(this.id, o);
    }
  }


问:
Measure to compare other table values
I have two tables A&B and I created two measures to find sales of both tables 1&2. When I use the matrix visual to see the values of both tables by using measures, Its showing correct values as per date hierarchy.

But, when I use the 2nd measure of table-b in table-a matrix visual its showing the subtotal values but not as per hierarchy.

I have a requirement to show the measure of table-B in visual 1 which contains table-a regions and date along with measure1 to compare the measure 1&2 in single visual as per hierarchy.

For Visual 1(matrix) - used columns: Region column from table A, date column from date table, measure1

For Visual 2(matrix) - used columns: Region column from table B, date column from date table,measure2

Table A, Table B,Date table : by using date as common column b/w date and table a& b form the 1 to many relationship.

Requirement: formula of measure 2: sum(sales), Its splitting the values as per hierarchy when I use it 2nd visual. I want to see the same in 1st visual, it contains same date column & region for table-A

Can anyone help me to how to solve this?

答: when I use the 2nd measure of table-b in table-a matrix visual <- This means that you don't have a dimension table that contains information for both a and b. In order to be able to split it, it needs to have the same 'reference', so it knows what date is used for calculating.</p>

Title: Measure to compare other table values


问:
Can we create an object in Java with out class like in js or python with random key and values
Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object

EX:

url: .../employee (Post)

request body: {option: {filter: "suman"}}

In Python or JS we can just do request_body.option.filter and get the data

How can I achieve the same with Java ?
Do I need need to create a class for the reqeust_body and for option and make an instance object request_body

答:
I was able to parse the request body with JSONObject like below

```<code>@PostMapping("/customers")
    public List<Customer> getCustomerById(@RequestBody Map<String, Object> req) {

        // {option: {filter: "alf"}}
        JSONObject json = new JSONObject(req);
        System.out.println(json.toString(4));
        System.out.println(json.getJSONObject("option").get("filter"));

        -----------------------
        -----------------------
        -----------------------

}
</code>```

Output

Body:
I was able to parse the request body with JSONObject like below

@PostMapping("/customers")
    public List<Customer> getCustomerById(@RequestBody Map<String, Object> req) {

        // {option: {filter: "alf"}}
        JSONObject json = new JSONObject(req);
        System.out.println(json.toString(4));
        System.out.println(json.getJSONObject("option").get("filter"));

        -----------------------
        -----------------------
        -----------------------

}

Output


问:
sending the value from jsp to java or javascript to java
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

```<code>aaa       bbb
          ccc
</code>```

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

```<code><a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}
</code>```

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.

答:
Remember that Javascript runs on the client side only, while Java is server side only. Java can  set a Javascript variable since Java is processed by the server first and then javascript, csss, and html is sent back to the browser for processing.

To send Javascript variable to the server you must post your data from the client to the server. One way to do that is to submit a form another is to create an Ajax request (XML over HTTP) there are lots of JS libraries out there that can help with doing Ajax.

Body:
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

aaa       bbb
          ccc

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

<a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.


问:
Using condition for redirecting in react router dom v6
I'm currently getting troubled with the react router dom@6. Like, I want to redirect users to other pages If they logged in. But when I use Navigate component It threw error saying that :

"[Navigate] is not a  component. All component children of Routes must be a Route or React.Fragment"

Though I have wrapped it in the fragment but the result still the same. Please help me, this is my code:

```<code>import {BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom';
import Home from './pages/Home';
import ProductList from './pages/ProductList';
import Product from './pages/Product';
import Register from './pages/Register';
import Login from './pages/Login';
import Cart from './pages/Cart';
import ErrorPage from './pages/ErrorPage';

function App() {
  const user = true;
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="/products/:category" element={<ProductList/>} />
        <Route path="/product/:id" element={<Product/>} />
        <Route path="/cart" element={<Cart/>} />
        <Route path="/dang-ky" element={<Register/>} />
        <Route path="/dang-nhap" element={<Login/>} >
          {user ? <><Navigate to="/" replace/></> : <Login/>}
        </Route>
        <Route path="*" element={<ErrorPage/>} />
      </Routes>
    </Router>
  );
}

export default App;
</code>```

答:
Redirecting users if logged in, necessarily does not need a navigation, you could simply just specify the element you want to reach eg:</p>
```<code><Route exact path="/"   element={user ? <Home/> : <Login />}/>
</code>```

Body:
I'm currently getting troubled with the react router dom@6. Like, I want to redirect users to other pages If they logged in. But when I use Navigate component It threw error saying that :

"[Navigate] is not a  component. All component children of Routes must be a Route or React.Fragment"

Though I have wrapped it in the fragment but the result still the same. Please help me, this is my code:

import {BrowserRouter as Router, Routes, Route, Navigate} from 'react-router-dom';
import Home from './pages/Home';
import ProductList from './pages/ProductList';
import Product from './pages/Product';
import Register from './pages/Register';
import Login from './pages/Login';
import Cart from './pages/Cart';
import ErrorPage from './pages/ErrorPage';

function App() {
  const user = true;
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="/products/:category" element={<ProductList/>} />
        <Route path="/product/:id" element={<Product/>} />
        <Route path="/cart" element={<Cart/>} />
        <Route path="/dang-ky" element={<Register/>} />
        <Route path="/dang-nhap" element={<Login/>} >
          {user ? <><Navigate to="/" replace/></> : <Login/>}
        </Route>
        <Route path="*" element={<ErrorPage/>} />
      </Routes>
    </Router>
  );
}

export default App;

Body:
Redirecting users if logged in, necessarily does not need a navigation, you could simply just specify the element you want to reach eg:

<Route exact path="/"   element={user ? <Home/> : <Login />}/>


问:
Why is the cursor shaking?
My marker has a problem that when I do mouse:hover the cursor is shaking.

I put my component into codesandbox with the same code I'm using on my application.

You may notice when you bring the mouse closer to the edge of the marker, the cursor starts to shaking.

.marker {
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 100%;
  width: 20px;
  height: 20px;
}

.marker:hover {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="marker"></div></code>```

I don't know why this is happening, can you help me?

Thanks in advance.

答:
It's shaking because your object is originally 20x20 pixels in size. Once it your mouse :hover's it shrinks in size.

Since the cursor is not perfectly centered on the object it reaches a point where the mouse is out of the bounding box of your element, which restores it's original width... which then makes it bigger and the mouse it's again inside the bounding box...

You see where this is going right? We have an infinite loop of shrinking and growing the element's bounding box.

A trick for getting around this may be to provide a wrapper that stays in size 20x20 and have the marker respond to the wrapper being :hover'ed

Title: Why is the cursor shaking?

Body:
My marker has a problem that when I do mouse:hover the cursor is shaking.

I put my component into codesandbox with the same code I'm using on my application.

You may notice when you bring the mouse closer to the edge of the marker, the cursor starts to shaking.

.marker {
  transition: all 0.5s ease;
  border: 2px solid #fff;
  background-color: #61ba9e;
  border-radius: 100%;
  width: 20px;
  height: 20px;
}

.marker:hover {
  height: 12.5px;
  width: 12.5px;
  box-shadow: 0 0 0 4px rgb(97 186 158 / 60%);
  cursor: pointer;
}

I don't know why this is happening, can you help me?

Thanks in advance.


问:
How do I find the highest float from a list?
I have made a program that gets a movie you pick from a list and tells you its directors and rating it also tells you if a movie is the highest-rated. I want the program to do the same thing it is doing but instead of just checking if the title is 5 stars, it checks if the rating is higher than all the other floats.</p>
```<code>movieDirectorRatingList = [
  ["Munich: The Edge of War", "Christian Schwochow", 4.1],
  ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", 4.8],
  ["Tombstone", "Cosmatos and Kevin Jarre", 4.1],
  ["Waterloo", "George P. and Sergei Bondarchuk", 4.0],
  ["Iron Man", "Jon Favreau", 5.0],
  ["Harry Potter", "Chris Columbus", 4.1],
  ["Percy Jackson", "Thor Freudenthal and Chris Columbus", 3.8],
  ["John Wick", "Chad Stahelski", 4.9],
  ["Avengers:Civil War", "Joe Russo and Anthony Russo" , 2.2]
  #Made a 2d list called movieDirectorRatingList which stores the movies with their name, director and rating
]

movieSelection = input("What movie would you like to know about?\nMunich: The Edge of War, Avengers:Endgame, Tombstone, Waterloo, Iron Man, Harry Potter, Percy Jackson, John Wick or Avengers:Civil War\n")
#Asks the user what movie they would like to know about and stores it in a variable called movieSelection

for movie in movieDirectorRatingList:
  #divides the 2d list into smaller sections each known as movie
  title, director, rating = movie
  #Unpacks each of the movie bits from movieDirectorRatingList and explains what each of the variables within it are in the order of title, director and lastly, rating
  if movieSelection in movie and rating != 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    break
    #stops the program
  elif movieSelection in movie and rating == 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    print("This is one of the highest rated movies")
    break
    #stops the program
else:
    print("Movie selection not found")
    #prints that the movie selection wasn't found
</code>```

答:
In Python you can get the highest value in a list (or in an iterable in general) with the built-in function max:

```<code>>>> l = [1, 2, 4, 3]
>>> max(l)
4
</code>```

In your case you just have to put the ratings into a list:

```<code>ratings = [x[2] for x in movieDirectorRatingList]
</code>```

and then find the highest value:

```<code>max(ratings)
</code>```

An even better solution would be this one suggested by @Matthias:

```<code>max(movieDirectorRatingList, key=lambda x: x[2])
</code>```

This is the same thing, but it allows you to avoid initializing a useless list.

Body:
I have made a program that gets a movie you pick from a list and tells you its directors and rating it also tells you if a movie is the highest-rated. I want the program to do the same thing it is doing but instead of just checking if the title is 5 stars, it checks if the rating is higher than all the other floats.

movieDirectorRatingList = [
  ["Munich: The Edge of War", "Christian Schwochow", 4.1],
  ["Avengers:Endgame", "Anthony Russo, Joe Russo and Joss Whedon", 4.8],
  ["Tombstone", "Cosmatos and Kevin Jarre", 4.1],
  ["Waterloo", "George P. and Sergei Bondarchuk", 4.0],
  ["Iron Man", "Jon Favreau", 5.0],
  ["Harry Potter", "Chris Columbus", 4.1],
  ["Percy Jackson", "Thor Freudenthal and Chris Columbus", 3.8],
  ["John Wick", "Chad Stahelski", 4.9],
  ["Avengers:Civil War", "Joe Russo and Anthony Russo" , 2.2]
  #Made a 2d list called movieDirectorRatingList which stores the movies with their name, director and rating
]

movieSelection = input("What movie would you like to know about?\nMunich: The Edge of War, Avengers:Endgame, Tombstone, Waterloo, Iron Man, Harry Potter, Percy Jackson, John Wick or Avengers:Civil War\n")
#Asks the user what movie they would like to know about and stores it in a variable called movieSelection

for movie in movieDirectorRatingList:
  #divides the 2d list into smaller sections each known as movie
  title, director, rating = movie
  #Unpacks each of the movie bits from movieDirectorRatingList and explains what each of the variables within it are in the order of title, director and lastly, rating
  if movieSelection in movie and rating != 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    break
    #stops the program
  elif movieSelection in movie and rating == 5.0:
    print(f"{movieSelection} directed by {director}: {rating}" )
    #prints the movie selec with it's director and rating
    print("This is one of the highest rated movies")
    break
    #stops the program
else:
    print("Movie selection not found")
    #prints that the movie selection wasn't found

Body:
In Python you can get the highest value in a list (or in an iterable in general) with the built-in function max:

>>> l = [1, 2, 4, 3]
>>> max(l)
4

In your case you just have to put the ratings into a list:

ratings = [x[2] for x in movieDirectorRatingList]

and then find the highest value:

max(ratings)

An even better solution would be this one suggested by @Matthias:

max(movieDirectorRatingList, key=lambda x: x[2])

This is the same thing, but it allows you to avoid initializing a useless list.


问:
Django strict checking for aware timestamps
In Django, if you have USE_TZ = True and pass a naive datetime to a database call, it logs the error:

DateTimeField Model.field received a naive datetime (2021-01-01 00:00:00) while time zone support is active.

However, Django goes ahead and does the operation anyway, using settings.TIME_ZONE.  Is there any way to do stricter checking?  Is there a setting so that Django will raise an exception rather than just logging a warning?

答:
The Django docs do include a way to raise an exception instead of just getting a warning (Django 4.0, have not checked how long it has been there). For me this reads as though you should only add this during development, and not for production deploy.

"
Finally, in order to help you locate code that needs upgrading, Django raises a warning when you attempt to save a naive datetime to the database:
During development, you can turn such warnings into exceptions and get a traceback by adding the following to your settings file:

```<code>import warnings
warnings.filterwarnings(
    'error', r"DateTimeField .* received a naive datetime",
    RuntimeWarning, r'django\.db\.models\.fields',
)
</code>```

"

https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/#code

Body:
The Django docs do include a way to raise an exception instead of just getting a warning (Django 4.0, have not checked how long it has been there). For me this reads as though you should only add this during development, and not for production deploy.

"
Finally, in order to help you locate code that needs upgrading, Django raises a warning when you attempt to save a naive datetime to the database:
During development, you can turn such warnings into exceptions and get a traceback by adding the following to your settings file:

import warnings
warnings.filterwarnings(
    'error', r"DateTimeField .* received a naive datetime",
    RuntimeWarning, r'django\.db\.models\.fields',
)

"

https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/#code


问:
Postgres Crosstab on double columns with unknown value
So i have a table like this in my Postgres v.10 DB

```<code>CREATE TABLE t1(id integer primary key, ref integer,v_id integer,total numeric, year varchar, total_lastyear numeric,lastyear varchar ) ;
    INSERT INTO t1 VALUES

    (1,  2077,15,10000,2020,9000,2019),
    (2,  2000,13,190000,2020,189000,2019),
    (3,  2065,11,10000,2020,10000,2019),
    (4,  1999,14,2300,2020,9000,2019);
</code>```

select * from t1 =

```<code>id  ref    v_id total   year    total_lastyear  lastyear
1   2077    15  10000   2020       9000          2019
2   2000    13  190000  2020       189000        2019
3   2065    11  10000   2020       10000         2019
4   1999    14  2300    2020       9000          2019
</code>```

Now i want to Pivot this table so that i have 2020 and 2019 as columns with the total amounts as values.

My Problems:

I don't know how two pivot two columns in the same query, is that even possibly or do you have to make two steps?

The years 2020 and 2019 are dynamic and can change from one day to another. The year inside the column is the same on every row.

So basicly i need to save the years inside lastyear and year in some variable and pass it to the Crosstab query.

This far i made it myself but i only managed to pivot one year and the 2019 and 2020 years is hardcoded.
Demo

答:
You can pivot one at a time with WITH.

```<code>WITH xd1 AS (
        SELECT * FROM crosstab('SELECT ref,v_id,year,total FROM t1 ORDER BY 1,3',
 'SELECT DISTINCT year FROM t1 ORDER BY 1') AS ct1(ref int,v_id int,"2020" int)
     ), xd2 AS (
        SELECT * FROM crosstab('SELECT ref,v_id,lastyear,total_lastyear FROM t1 ORDER BY 1,3',
 'SELECT DISTINCT lastyear FROM t1 ORDER BY 1') AS ct2(ref int,v_id int,"2019" int)
     )
SELECT xd1.ref,xd1.v_id,xd1."2020",xxx."2019"
FROM xd1
LEFT JOIN xd2 AS xxx ON xxx.ref = xd1.ref AND xxx.v_id = xd1.v_id;
</code>```

This doesn't prevent from last_year and year colliding.
You still have to know the years query will return as you have to define record as it is returned by crosstab.

You could wrap it in an EXECUTE format() to make it more dynamic and deal with some stringology.
This issue was mentioned here.

Body:
So i have a table like this in my Postgres v.10 DB

CREATE TABLE t1(id integer primary key, ref integer,v_id integer,total numeric, year varchar, total_lastyear numeric,lastyear varchar ) ;
    INSERT INTO t1 VALUES

    (1,  2077,15,10000,2020,9000,2019),
    (2,  2000,13,190000,2020,189000,2019),
    (3,  2065,11,10000,2020,10000,2019),
    (4,  1999,14,2300,2020,9000,2019);

select * from t1 =

id  ref    v_id total   year    total_lastyear  lastyear
1   2077    15  10000   2020       9000          2019
2   2000    13  190000  2020       189000        2019
3   2065    11  10000   2020       10000         2019
4   1999    14  2300    2020       9000          2019

Now i want to Pivot this table so that i have 2020 and 2019 as columns with the total amounts as values.

My Problems:

I don't know how two pivot two columns in the same query, is that even possibly or do you have to make two steps?

The years 2020 and 2019 are dynamic and can change from one day to another. The year inside the column is the same on every row.

So basicly i need to save the years inside lastyear and year in some variable and pass it to the Crosstab query.

This far i made it myself but i only managed to pivot one year and the 2019 and 2020 years is hardcoded.
Demo

Body:
You can pivot one at a time with WITH.

WITH xd1 AS (
        SELECT * FROM crosstab('SELECT ref,v_id,year,total FROM t1 ORDER BY 1,3',
 'SELECT DISTINCT year FROM t1 ORDER BY 1') AS ct1(ref int,v_id int,"2020" int)
     ), xd2 AS (
        SELECT * FROM crosstab('SELECT ref,v_id,lastyear,total_lastyear FROM t1 ORDER BY 1,3',
 'SELECT DISTINCT lastyear FROM t1 ORDER BY 1') AS ct2(ref int,v_id int,"2019" int)
     )
SELECT xd1.ref,xd1.v_id,xd1."2020",xxx."2019"
FROM xd1
LEFT JOIN xd2 AS xxx ON xxx.ref = xd1.ref AND xxx.v_id = xd1.v_id;

This doesn't prevent from last_year and year colliding.
You still have to know the years query will return as you have to define record as it is returned by crosstab.

You could wrap it in an EXECUTE format() to make it more dynamic and deal with some stringology.
This issue was mentioned here.


问:
com.google.code.gson cannot parse tamil results
So, I'm trying to fetch JSON results from https://api-thirukkural.vercel.app/api?num=1139 using Java-Telegram-Bot-Api and send it to telegram. I use com.google.code.gson dependency for parsing JSON.

The expected results from API:

```{"number":1139,"sect_tam":"காமத்துப்பால்","chapgrp_tam":"களவியல்","chap_tam":"நாணுத் துறவுரைத்தல்","line1":"அறிகிலார் எல்லாரும் என்றேஎன் காமம்","line2":"மறுகின் மறுகும் மருண்டு.","tam_exp":"என்னைத் தவிர யாரும் அறியவில்லை என்பதற்காக என் காதல் தெருவில் பரவி மயங்கித் திரிகின்றது போலும்!","sect_eng":"Love","chapgrp_eng":"The Pre-marital love","chap_eng":"Declaration of Love's special Excellence","eng":"My perplexed love roves public street Believing that none knows its secret","eng_exp":"And thus, in public ways, perturbed will rove"}```

Here is a piece of my java code:

```<code>  String results = "";
        Random random = new Random();
        SendMessage message = new SendMessage();
        String apiUrl = "https://api-thirukkural.vercel.app/api?num=" + random.nextInt(1329 + 1);
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            Scanner sc = new Scanner(url.openStream());
            while (sc.hasNext()) {
                results += sc.nextLine();
            }
            sc.close();
            JSONArray jsonArray = new JSONArray("[" + results + "]");
            JSONObject object = jsonArray.getJSONObject(0);
            message.setChatId(update.getMessage().getChatId().toString());
            message.setText("Number: " + object.getInt("number") + "\n\n" + object.getString("line1") + "\n"
                    + object.getString("line2") + "\n\n" + object.getString("tam_exp") + "\n\n" + object.getString("eng_exp"));
            conn.disconnect();
            execute(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

The result in telegram:

```Number: 1139

à®…à®±à®¿à®•à®¿à®²à®¾à®°à¯� à®Žà®²à¯�à®²à®¾à®°à¯�à®®à¯� à®Žà®©à¯�à®±à¯‡à®Žà®©à¯� à®•à®¾à®®à®®à¯�
à®®à®±à¯�à®•à®¿à®©à¯� à®®à®±à¯�à®•à¯�à®®à¯� à®®à®°à¯�à®£à¯�à®Ÿà¯�.

à®Žà®©à¯�à®©à¯ˆà®¤à¯� à®¤à®µà®¿à®° à®¯à®¾à®°à¯�à®®à¯� à®…à®±à®¿à®¯à®µà®¿à®²à¯�à®²à¯ˆ à®Žà®©à¯�à®ªà®¤à®±à¯�à®•à®¾à®• à®Žà®©à¯� à®•à®¾à®¤à®²à¯� à®¤à¯†à®°à¯�à®µà®¿à®²à¯� à®ªà®°à®µà®¿ à®®à®¯à®™à¯�à®•à®¿à®¤à¯� à®¤à®¿à®°à®¿à®•à®¿à®©à¯�à®±à®¤à¯� à®ªà¯‹à®²à¯�à®®à¯�!

And thus, in public ways, perturbed will rove```

Is this a problem in gson dependency? Can someone help me fix this? Thanks.

答:
You need to specify the Charset on Scanner. That is probably the problem.

Example:

```<code>new Scanner(url.openStream(), StandardCharsets.UTF_8.name());
</code>```

You should use the Charset that fits.

Body:
So, I'm trying to fetch JSON results from https://api-thirukkural.vercel.app/api?num=1139 using Java-Telegram-Bot-Api and send it to telegram. I use com.google.code.gson dependency for parsing JSON.

The expected results from API:

{"number":1139,"sect_tam":"காமத்துப்பால்","chapgrp_tam":"களவியல்","chap_tam":"நாணுத் துறவுரைத்தல்","line1":"அறிகிலார் எல்லாரும் என்றேஎன் காமம்","line2":"மறுகின் மறுகும் மருண்டு.","tam_exp":"என்னைத் தவிர யாரும் அறியவில்லை என்பதற்காக என் காதல் தெருவில் பரவி மயங்கித் திரிகின்றது போலும்!","sect_eng":"Love","chapgrp_eng":"The Pre-marital love","chap_eng":"Declaration of Love's special Excellence","eng":"My perplexed love roves public street Believing that none knows its secret","eng_exp":"And thus, in public ways, perturbed will rove"}

Here is a piece of my java code:

  String results = "";
        Random random = new Random();
        SendMessage message = new SendMessage();
        String apiUrl = "https://api-thirukkural.vercel.app/api?num=" + random.nextInt(1329 + 1);
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            Scanner sc = new Scanner(url.openStream());
            while (sc.hasNext()) {
                results += sc.nextLine();
            }
            sc.close();
            JSONArray jsonArray = new JSONArray("[" + results + "]");
            JSONObject object = jsonArray.getJSONObject(0);
            message.setChatId(update.getMessage().getChatId().toString());
            message.setText("Number: " + object.getInt("number") + "\n\n" + object.getString("line1") + "\n"
                    + object.getString("line2") + "\n\n" + object.getString("tam_exp") + "\n\n" + object.getString("eng_exp"));
            conn.disconnect();
            execute(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

The result in telegram:

Number: 1139

à®…à®±à®¿à®•à®¿à®²à®¾à®°à¯� à®Žà®²à¯�à®²à®¾à®°à¯�à®®à¯� à®Žà®©à¯�à®±à¯‡à®Žà®©à¯� à®•à®¾à®®à®®à¯�
à®®à®±à¯�à®•à®¿à®©à¯� à®®à®±à¯�à®•à¯�à®®à¯� à®®à®°à¯�à®£à¯�à®Ÿà¯�.

à®Žà®©à¯�à®©à¯ˆà®¤à¯� à®¤à®µà®¿à®° à®¯à®¾à®°à¯�à®®à¯� à®…à®±à®¿à®¯à®µà®¿à®²à¯�à®²à¯ˆ à®Žà®©à¯�à®ªà®¤à®±à¯�à®•à®¾à®• à®Žà®©à¯� à®•à®¾à®¤à®²à¯� à®¤à¯†à®°à¯�à®µà®¿à®²à¯� à®ªà®°à®µà®¿ à®®à®¯à®™à¯�à®•à®¿à®¤à¯� à®¤à®¿à®°à®¿à®•à®¿à®©à¯�à®±à®¤à¯� à®ªà¯‹à®²à¯�à®®à¯�!

And thus, in public ways, perturbed will rove

Is this a problem in gson dependency? Can someone help me fix this? Thanks.

Body:
You need to specify the Charset on Scanner. That is probably the problem.

Example:

new Scanner(url.openStream(), StandardCharsets.UTF_8.name());

You should use the Charset that fits.


问:
Importing classes from other projects in Eclipse?
So I have a Project1 with class A. I have Project2 with class B. How do I import class A to B without having to create a new class in the Project2 etc. I get this has to do with the build path, but how do I add so I can write something like
import Project1/A;
Along with my JRESL imports?

答:
You can make Project1 as a jar file and import that into the build path of Porject2 . Then you can call class A in class B as usual .

Note : Above approach is good if you are doing it once . If Project 1 changes often, this method can be tiresome . Each time you have to make Project1  as jar file and import it .

If Project1 changes frequently, do the following.

Right click on Project2, then click on Properties. In the dialog that comes up, select Java Build Path, and then click on the Projects tab. There, add Project1 to the build path.

If Project2 is a web app, you need to make sure your Deployment Assembly (same Properties UI) has Project1 there as well.


问:
Update photoURL Firebase v9 web, react Javascript
I'm following a Udemy firebase Udemy tutorial for creating a firebase web application using javascript and react. The course material is a bit our of date. I want to know how to change a user's photoURL - they log up with email and password, and I have a seperate hook to handle the sign up information.

Below is the code the Udemy course gives to update a user's photoURL - does anyone know how I would write this in Firebase v9? Thank you!

```<code>// upload user thumbnail
      const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
      const img = await projectStorage.ref(uploadPath).put(thumbnail)
      const imgUrl = await img.ref.getDownloadURL()

      // add display AND PHOTO_URL name to user
      await res.user.updateProfile({ displayName, photoURL: imgUrl })
</code>```

答:
Rewriting from pre-v9 to v9 is usually quite simple, especially if you follow the upgrade guide or compare the v8 and v9 samples in the documentation on uploading files.

In your code, this v8 code:

```<code>const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
const img = await projectStorage.ref(uploadPath).put(thumbnail)
const imgUrl = await img.ref.getDownloadURL()

// add display AND PHOTO_URL name to user
await res.user.updateProfile({ displayName, photoURL: imgUrl })
</code>```

Becomes this in v9 and above:

```<code>const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
const img = await uploadBytes(ref(projectStorage, uploadPath, thumbnail))
const imgUrl = await getDownloadUrl(img.ref)

// add display AND PHOTO_URL name to user
await updateProfile(res.user, { displayName, photoURL: imgUrl })
</code>```

If you watch carefully, you'll see that most of the change is just in moving the namespaced object.operation() method calls into a modular/functional operation(object) form. Aside from that, the biggest difference here is that put is now called uploadBytes.

Body:
I'm following a Udemy firebase Udemy tutorial for creating a firebase web application using javascript and react. The course material is a bit our of date. I want to know how to change a user's photoURL - they log up with email and password, and I have a seperate hook to handle the sign up information.

Below is the code the Udemy course gives to update a user's photoURL - does anyone know how I would write this in Firebase v9? Thank you!

// upload user thumbnail
      const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
      const img = await projectStorage.ref(uploadPath).put(thumbnail)
      const imgUrl = await img.ref.getDownloadURL()

      // add display AND PHOTO_URL name to user
      await res.user.updateProfile({ displayName, photoURL: imgUrl })

Body:
Rewriting from pre-v9 to v9 is usually quite simple, especially if you follow the upgrade guide or compare the v8 and v9 samples in the documentation on uploading files.

In your code, this v8 code:

const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
const img = await projectStorage.ref(uploadPath).put(thumbnail)
const imgUrl = await img.ref.getDownloadURL()

// add display AND PHOTO_URL name to user
await res.user.updateProfile({ displayName, photoURL: imgUrl })

Becomes this in v9 and above:

const uploadPath = `thumbnails/${res.user.uid}/${thumbnail.name}`
const img = await uploadBytes(ref(projectStorage, uploadPath, thumbnail))
const imgUrl = await getDownloadUrl(img.ref)

// add display AND PHOTO_URL name to user
await updateProfile(res.user, { displayName, photoURL: imgUrl })

If you watch carefully, you'll see that most of the change is just in moving the namespaced object.operation() method calls into a modular/functional operation(object) form. Aside from that, the biggest difference here is that put is now called uploadBytes.


问:
How to set multiple output parameters in stored procedures
Is there a way to set multiple output parameters?

For example, in the stored procedure shown here, I wish to get the NUM_OF_ROWS and the TicketNumberz from the same stored procedure.

Since, I am new I don't know how to go about it...

```<code>DECLARE @TicketNumberz VARCHAR(15) OUT
DECLARE @NUM_OF_ROWS INT OUT
DECLARE @INIT INT=1 OUT

SET @TicketNumberz = (SELECT TICKETNUMBER
                      FROM TicketHistory s1
                      WHERE TICKETTIME IN (SELECT MAX(S2.TICKETTIME)
                                           FROM TicketHistory] S2
                                           WHERE s1.TICKETNUMBER = S2.TICKETNUMBER)
                        AND CURRENTSTATUS_ANALYST != 'Closed'
                        AND CURRENTSTATUS_ANALYST = 'Resolved'
                        AND TICKETTIME < GETDATE() - 5)

-- after getting all the list of ticket numbers, update query follows to update the ticket status to 'Closed'

WHILE (@INIT <= @NUM_OF_ROWS)
BEGIN
    INSERT INTO TicketHistory (CURRENTSTATUS_ANALYST, TICKETNUMBER,
                               PREVIOUSSTATUS_ANALYST, TICKETTIME, FIELD, CREATEDBY)
    VALUES ('Closed', @TicketNumberz,
            'Resolved', CURRENT_TIMESTAMP, 'Status', 'Auto.User')
END
</code>```

What this query basically does it, it would fetch all the ''Resolved' tickets which are older than 5 days and had not been 'Closed' automatically. So doing it manually through this stored procedure.

But, I am stuck because of the following error :

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

This is how the db looks like :

答:
I would probably rework the subquery in this but not crucial. It seems that perhaps that table structure is a bit of a challenge here but I think you are looking for something along these lines. This would replace all of the code you posted. There is no need for loops or variables of any kind based on what you posted.

--EDIT--

With the clarification from the OP's comment all that need to happen is add the insert above this select

```<code>insert into TicketHistory (CURRENTSTATUS_ANALYST,TICKETNUMBER,PREVIOUSSTATUS_ANALYST,TICKETTIME,FIELD,CREATEDBY)
SELECT 'Closed'
    , th.TICKETNUMBER
    , 'Resolved'
    , CURRENT_TIMESTAMP
    , 'Status'
    , 'Auto.User'
FROM TicketHistory th
WHERE TICKETTIME IN
(
    SELECT MAX(S2.TICKETTIME)
    FROM TicketHistory S2
    WHERE s1.TICKETNUMBER = S2.TICKETNUMBER
)
    --AND CURRENTSTATUS_ANALYST != 'Closed' --there is no value that equals 'Resolved' where it could also equal 'Closed'
    AND th.CURRENTSTATUS_ANALYST = 'Resolved'
    AND th.TICKETTIME < dateadd(day, -5, GETDATE()) --use dateadd instead of shorthand
</code>```

Body:
Is there a way to set multiple output parameters?

For example, in the stored procedure shown here, I wish to get the NUM_OF_ROWS and the TicketNumberz from the same stored procedure.

Since, I am new I don't know how to go about it...

DECLARE @TicketNumberz VARCHAR(15) OUT
DECLARE @NUM_OF_ROWS INT OUT
DECLARE @INIT INT=1 OUT

SET @TicketNumberz = (SELECT TICKETNUMBER
                      FROM TicketHistory s1
                      WHERE TICKETTIME IN (SELECT MAX(S2.TICKETTIME)
                                           FROM TicketHistory] S2
                                           WHERE s1.TICKETNUMBER = S2.TICKETNUMBER)
                        AND CURRENTSTATUS_ANALYST != 'Closed'
                        AND CURRENTSTATUS_ANALYST = 'Resolved'
                        AND TICKETTIME < GETDATE() - 5)

-- after getting all the list of ticket numbers, update query follows to update the ticket status to 'Closed'

WHILE (@INIT <= @NUM_OF_ROWS)
BEGIN
    INSERT INTO TicketHistory (CURRENTSTATUS_ANALYST, TICKETNUMBER,
                               PREVIOUSSTATUS_ANALYST, TICKETTIME, FIELD, CREATEDBY)
    VALUES ('Closed', @TicketNumberz,
            'Resolved', CURRENT_TIMESTAMP, 'Status', 'Auto.User')
END

What this query basically does it, it would fetch all the ''Resolved' tickets which are older than 5 days and had not been 'Closed' automatically. So doing it manually through this stored procedure.

But, I am stuck because of the following error :

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

This is how the db looks like :

Body:
I would probably rework the subquery in this but not crucial. It seems that perhaps that table structure is a bit of a challenge here but I think you are looking for something along these lines. This would replace all of the code you posted. There is no need for loops or variables of any kind based on what you posted.

--EDIT--

With the clarification from the OP's comment all that need to happen is add the insert above this select

insert into TicketHistory (CURRENTSTATUS_ANALYST,TICKETNUMBER,PREVIOUSSTATUS_ANALYST,TICKETTIME,FIELD,CREATEDBY)
SELECT 'Closed'
    , th.TICKETNUMBER
    , 'Resolved'
    , CURRENT_TIMESTAMP
    , 'Status'
    , 'Auto.User'
FROM TicketHistory th
WHERE TICKETTIME IN
(
    SELECT MAX(S2.TICKETTIME)
    FROM TicketHistory S2
    WHERE s1.TICKETNUMBER = S2.TICKETNUMBER
)
    --AND CURRENTSTATUS_ANALYST != 'Closed' --there is no value that equals 'Resolved' where it could also equal 'Closed'
    AND th.CURRENTSTATUS_ANALYST = 'Resolved'
    AND th.TICKETTIME < dateadd(day, -5, GETDATE()) --use dateadd instead of shorthand


问:
Splunk query to check if time taken of specific log is greater than N ms?
For Splunk I was trying something like below along with what has been provided in the link
But it's mostly related to extracting digits, what I'm looking for is to check value is greater than some xyz number.
It will be great if someone can help me with it.

I'm not much good at regex, so tried a couple of stuff like as given in link as well. But it's not working.

Splunk query:
index=1234 application_instance_name=service-name "[FooBarService#write] <--- HTTP/1.1 200 (2300ms)"
I know the above is for exactly matching, but I played with regex as given in both the links.

log: [FooBarService#write] <--- HTTP/1.1 200 (2300ms)

In this case, how should I check how many logs for this match have crossed 5000ms?
What query shall I build in spunk search for the same?

答:
Perhaps this will help.  The rex command uses a regex to extract the duration from each event.  The where command filters out those not over 5000ms.  Finally, stats counts the remaining events, leaving the number of events with values greater than 5000ms.

```<code>index=1234 application_instance_name=service-name "[FooBarService#write] <--- HTTP/1.1 200 (*)"
| rex "\((?<ms>\d+)ms"
| where ms > 5000
| stats count
</code>```

Body:
Perhaps this will help.  The rex command uses a regex to extract the duration from each event.  The where command filters out those not over 5000ms.  Finally, stats counts the remaining events, leaving the number of events with values greater than 5000ms.

index=1234 application_instance_name=service-name "[FooBarService#write] <--- HTTP/1.1 200 (*)"
| rex "\((?<ms>\d+)ms"
| where ms > 5000
| stats count


问:
Is there any way to build a JSON that looks like this using SQL Server 2019?
I have this SQL Query:

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    c.telephone as telephone,
    c.email as email,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE
    c.id_customer = 2
FOR JSON PATH

SELECT * FROM Customer WHERE ID_CUSTOMER = 2
SELECT * FROM User WHERE ID_Customer = 2
```
<p>This query returns this JSON :</p>
<pre class="lang-json prettyprint-override"><code>[
    {
      "name": "blablabla",
      "social": "123123123",
      "telephone": "91123123",
      "email": "blabla@gmail.com",
      "name":"blabla"
    }
]
</code>```

Is there any way to get a JSON that looks like this:

```<code>{
  "name": "blabla",
  "social_number": "123123123",
  "emails": [
    {
      "email": "blabla@gmail.com"
    },
    {
      "email": "blablabla@gmail.com"
    }
  ],
  "telephones": [
    {
      "number": "(604)6622141"
    },
    {
      "number": "(652) 2123223"
    }
  ],
</code>```

Thank you for the help!

I'm still new to coding and StackOverflow... sorry for any mistakes!

答:
You can use correlated subqueries, with FOR JSON in each one

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    telephones = (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
    ),
    emails = (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
    ),
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE
    c.id_customer = 2
FOR JSON PATH;
```
<p>You can also do this as an <code>APPLY</code></p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    t.telephones,
    e.emails,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
OUTER APPLY (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
) t(telephones)
OUTER APPLY (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
) e(emails)
WHERE
    c.id_customer = 2
FOR JSON PATH;
</code>```

Body:
I have this SQL Query:

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    c.telephone as telephone,
    c.email as email,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE
    c.id_customer = 2
FOR JSON PATH

SELECT * FROM Customer WHERE ID_CUSTOMER = 2
SELECT * FROM User WHERE ID_Customer = 2

This query returns this JSON :

[
    {
      "name": "blablabla",
      "social": "123123123",
      "telephone": "91123123",
      "email": "blabla@gmail.com",
      "name":"blabla"
    }
]

Is there any way to get a JSON that looks like this:

{
  "name": "blabla",
  "social_number": "123123123",
  "emails": [
    {
      "email": "blabla@gmail.com"
    },
    {
      "email": "blablabla@gmail.com"
    }
  ],
  "telephones": [
    {
      "number": "(604)6622141"
    },
    {
      "number": "(652) 2123223"
    }
  ],

Thank you for the help!

I'm still new to coding and StackOverflow... sorry for any mistakes!

Body:
You can use correlated subqueries, with FOR JSON in each one

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    telephones = (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
    ),
    emails = (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
    ),
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
WHERE
    c.id_customer = 2
FOR JSON PATH;

You can also do this as an APPLY

SELECT
    c.customer_name as name,
    c.customer_ssn as social_number,
    t.telephones,
    e.emails,
    u.user_name as name
FROM
    Customer c
LEFT OUTER JOIN
    User u ON c.id_customer = u.id_customer
OUTER APPLY (
        SELECT telephone
        FROM telephone t
        WHERE t.id_customer = c.id_customer
        FOR JSON PATH
) t(telephones)
OUTER APPLY (
        SELECT email
        FROM email e
        WHERE e.id_customer = c.id_customer
        FOR JSON PATH
) e(emails)
WHERE
    c.id_customer = 2
FOR JSON PATH;


问:
How to "pip install" latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT?
I am working in Django. I want to install all the python modules which are the latest. What should in HAVE to do to update all the latest versions of modules?

How to "pip install" the latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT?

Let's say, Inside requirements.txt is:

```<code>asn1crypto==1.0.1
astroid==2.3.1
</code>```

so I want to install the latest version of:
asn1crypto and astroid

答:
Use >= instead of ==

Tip: you can replace it with using of vscode CTRL + F (or CTRL + H)

Body:
I am working in Django. I want to install all the python modules which are the latest. What should in HAVE to do to update all the latest versions of modules?

How to "pip install" the latest versions of modules from requirements.txt neglecting the old versions written in REQUIREMENTs.TXT?

Let's say, Inside requirements.txt is:

asn1crypto==1.0.1
astroid==2.3.1

so I want to install the latest version of:
asn1crypto and astroid


问:
python dictionary sorting oddly (want non-alphabetical)
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

```<code>def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)
</code>```

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

```<code>for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '
</code>```

答:
Since dictionaries in Python are unordered and all that you need is to output results ordered by the specified rule you can do something like this:

```<code>order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')

for key in order:
    print key, infos.get(key)#if infos is your dictionary
</code>```

Or you can get/pass list instead of dict the following way:

```<code>print [(key, infos.get(key)) for key in order]
</code>```

Body:
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.

I'm currently using this function to try and achieve this.

def array_sort(array, sort): #yeah, it's array cuz i php like that.
    ordered = {}
    for i in range(0,len(sort)):
        if sort[i] in array:
            ordered[sort[i]] = array[sort[i]]
    keys = array.keys()
    return ordered

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)

for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)

If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.

EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).

for i in range(0, len(order)):
    if order[i] in infos:
        packet += order[i] + '="' + infos[order[i]] + '" '

Body:
Since dictionaries in Python are unordered and all that you need is to output results ordered by the specified rule you can do something like this:

order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')

for key in order:
    print key, infos.get(key)#if infos is your dictionary

Or you can get/pass list instead of dict the following way:

print [(key, infos.get(key)) for key in order]


问:
How to "describe" a column in pandas for python
I'm using pandas in python and I have a dataframe where one column is a timestamp and others contain data.

The blue line stays constant for a while, then suddenly increases to zero, then at some point descends again to about -98 and stays there until it suddenly goes up to zero. What I need is a new column with the status of the blue color: constant,sudden increase, constant, decrease, constant, sudden increase, constant or somehow an object that describes the data:

```<code>blue line{
'08.02.2022 08:30:00.000' : 'sudden increase',
'08.02.2022 10:39:30.000' : 'start decrease',
'08.02.2022 10:59:40.000' : 'end decrease',
'08.02.2022 13:50:30.000' : 'sudden increase'
}
</code>```

Is there a package for something like this? I hope it isn't too far feched

Kind Regards, Alexander

答:
Here is how your data looks like.

In blue the data, in red the gradient. As the time interval is uniform, you can directly use the diff to compute the gradient (here clipped to a max of 1).

Now you can use numpy.select to map thresholds in the gradient to your labels.

Then, in pandas it is easy to filter the rows by changes in labels:

```<code># input data
df = pd.read_excel('test.xlsx').set_index('time')
df.index = pd.to_datetime(df.index)

# compute gradient
grad = df['Col1'].diff()
# set labels
thresh_sudden = 10
thresh_gradual = 0.25
df['state'] = np.select([grad>thresh_sudden, grad<-thresh_gradual],
                        ['sudden increase', 'start decrease'],
                        'constant')  # default

# add end of decrease
df.loc[df['state'].eq('start decrease') & df['state'].shift(-1).eq('constant'),
       'state'] = 'end decrease'

# find changing points
change = df['state'].ne(df['state'].shift())
df['change'] = df['state'].where(change)

# slice
df[change]
</code>```

output:

```<code>                      Col1      Col2            state           change
time
2022-08-02 08:00:00 -98.05       NaN         constant         constant
2022-08-02 08:29:50 -96.99       NaN  sudden increase  sudden increase
2022-08-02 08:30:10  -0.01       NaN         constant         constant
2022-08-02 10:39:30  -0.89  1.351546   start decrease   start decrease
2022-08-02 10:59:20 -97.86  1.415426     end decrease     end decrease
2022-08-02 10:59:30 -98.04  1.415426         constant         constant
2022-08-02 13:50:20 -98.09  0.441630  sudden increase  sudden increase
2022-08-02 13:50:50  -0.12  0.441630         constant         constant
</code>```

Body:
I'm using pandas in python and I have a dataframe where one column is a timestamp and others contain data.

The blue line stays constant for a while, then suddenly increases to zero, then at some point descends again to about -98 and stays there until it suddenly goes up to zero. What I need is a new column with the status of the blue color: constant,sudden increase, constant, decrease, constant, sudden increase, constant or somehow an object that describes the data:

blue line{
'08.02.2022 08:30:00.000' : 'sudden increase',
'08.02.2022 10:39:30.000' : 'start decrease',
'08.02.2022 10:59:40.000' : 'end decrease',
'08.02.2022 13:50:30.000' : 'sudden increase'
}

Is there a package for something like this? I hope it isn't too far feched

Kind Regards, Alexander

Body:
Here is how your data looks like.

In blue the data, in red the gradient. As the time interval is uniform, you can directly use the diff to compute the gradient (here clipped to a max of 1).

Now you can use numpy.select to map thresholds in the gradient to your labels.

Then, in pandas it is easy to filter the rows by changes in labels:

# input data
df = pd.read_excel('test.xlsx').set_index('time')
df.index = pd.to_datetime(df.index)

# compute gradient
grad = df['Col1'].diff()
# set labels
thresh_sudden = 10
thresh_gradual = 0.25
df['state'] = np.select([grad>thresh_sudden, grad<-thresh_gradual],
                        ['sudden increase', 'start decrease'],
                        'constant')  # default

# add end of decrease
df.loc[df['state'].eq('start decrease') & df['state'].shift(-1).eq('constant'),
       'state'] = 'end decrease'

# find changing points
change = df['state'].ne(df['state'].shift())
df['change'] = df['state'].where(change)

# slice
df[change]

output:

                      Col1      Col2            state           change
time
2022-08-02 08:00:00 -98.05       NaN         constant         constant
2022-08-02 08:29:50 -96.99       NaN  sudden increase  sudden increase
2022-08-02 08:30:10  -0.01       NaN         constant         constant
2022-08-02 10:39:30  -0.89  1.351546   start decrease   start decrease
2022-08-02 10:59:20 -97.86  1.415426     end decrease     end decrease
2022-08-02 10:59:30 -98.04  1.415426         constant         constant
2022-08-02 13:50:20 -98.09  0.441630  sudden increase  sudden increase
2022-08-02 13:50:50  -0.12  0.441630         constant         constant