问:
CriteriaBuilder and or condition is not applying required/proper parenthesis
I am new this board. I tried to find solution but could not find solution. In case it is available please share me that.

```<code>    CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<DmdInventory> criteriaQuery = criteriaBuilder.createQuery(ItemInventory.class);
    Root<ItemInventory> itemRoot = criteriaQuery.from(ItemInventory.class);

    Predicate first = criteriaBuilder.equal(itemRoot.get("margin"), 1.0);
    first = criteriaBuilder.and(first, criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0));
    first = criteriaBuilder.and(first, criteriaBuilder.equal(itemRoot.get("markup"), 1.0));

    Predicate second = criteriaBuilder.and(criteriaBuilder.equal(itemRoot.get("lastImportCost"), 2.0));
    second = criteriaBuilder.and(second, criteriaBuilder.equal(itemRoot.get("expenses"), 2.0));
    second = criteriaBuilder.and(second, criteriaBuilder.equal(itemRoot.get("profit"), 2.0));

    Predicate third = criteriaBuilder.and(criteriaBuilder.equal(itemRoot.get("totalCost"), 2.0));
    third = criteriaBuilder.and(third, criteriaBuilder.equal(itemRoot.get("cost"), 2.0));
    third = criteriaBuilder.and(third, criteriaBuilder.equal(itemRoot.get("quantity"), 2.0));
    Predicate allPredicate[] = { first, second, third };
    Predicate finalPredicate = criteriaBuilder.or(allPredicate);

    criteriaQuery.where(finalPredicate);
    List<ItemInventory> items = this.entityManager.createQuery(criteriaQuery).getResultList();
</code>```

Current result

```<code> select * from
    item_nventory inven
where
    inven.last_import_cost=2.0
    and inven.expenses=2.0
    and inven.profit=2.0
    or inven.total_cost=2.0
    and inven.cost=2.0
    and inven.quantity=2
    or inven.margin=1.0
    and inven.cost_without_expense=1.0
    and inven.markup=1.0
</code>```

Expected result

```<code>  select * from
    item_nventory inven
where
     inven.last_import_cost=2.0
and inven.expenses=2.0
and inven.profit=2.0
or (inven.total_cost=2.0
and inven.cost=2.0
and inven.quantity=2 )
or (inven.margin=1.0
and inven.cost_without_expense=1.0
and inven.markup=1.0)
</code>```

My final requirement will be something like below

```<code> select * from
    item_nventory inven
where
    inven.last_import_cost=2.0
and inven.expenses=2.0
and inven.profit=2.0
or ((inven.total_cost=2.0
and inven.cost=2.0
and inven.quantity=2 ) or (inven.quantity_on_hand>0))
or (inven.margin=1.0
and inven.cost_without_expense=1.0
and inven.markup=1.0)
</code>```

Please help out me in this.

答:
I think, problem is in gradual contruction of predicates. Try contruction below.

```<code>Predicate firstA = criteriaBuilder.equal(itemRoot.get("margin"), 1.0);
Predicate firstB = criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0);
Predicate firstC = criteriaBuilder.equal(itemRoot.get("markup"), 1.0);
Predicate first = criteriaBuilder.and(firstA, firstB, firstC);

 . . .

Predicate finalPredicate = criteriaBuilder.or(first, second, third);
</code>```

Or alternative solution with list - easy to add or remove another predicates (event dynamically)

```<code>List<Predicate> allPredList = new LinkedList<>();
{
  List<Predicate> firstPredList = new LinkedList<>();
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("margin"), 1.0));
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0));
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("markup"), 1.0));
  allPredList.add(criteriaBuilder.and(firstPredList.toArray(new Predicate[0])));
}

 . . .

Predicate finalPredicate = criteriaBuilder.or(allPredList.toArray(new Predicate[0]));
</code>```

Body:
I am new this board. I tried to find solution but could not find solution. In case it is available please share me that.

    CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<DmdInventory> criteriaQuery = criteriaBuilder.createQuery(ItemInventory.class);
    Root<ItemInventory> itemRoot = criteriaQuery.from(ItemInventory.class);

    Predicate first = criteriaBuilder.equal(itemRoot.get("margin"), 1.0);
    first = criteriaBuilder.and(first, criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0));
    first = criteriaBuilder.and(first, criteriaBuilder.equal(itemRoot.get("markup"), 1.0));

    Predicate second = criteriaBuilder.and(criteriaBuilder.equal(itemRoot.get("lastImportCost"), 2.0));
    second = criteriaBuilder.and(second, criteriaBuilder.equal(itemRoot.get("expenses"), 2.0));
    second = criteriaBuilder.and(second, criteriaBuilder.equal(itemRoot.get("profit"), 2.0));

    Predicate third = criteriaBuilder.and(criteriaBuilder.equal(itemRoot.get("totalCost"), 2.0));
    third = criteriaBuilder.and(third, criteriaBuilder.equal(itemRoot.get("cost"), 2.0));
    third = criteriaBuilder.and(third, criteriaBuilder.equal(itemRoot.get("quantity"), 2.0));
    Predicate allPredicate[] = { first, second, third };
    Predicate finalPredicate = criteriaBuilder.or(allPredicate);

    criteriaQuery.where(finalPredicate);
    List<ItemInventory> items = this.entityManager.createQuery(criteriaQuery).getResultList();

Current result

 select * from
    item_nventory inven
where
    inven.last_import_cost=2.0
    and inven.expenses=2.0
    and inven.profit=2.0
    or inven.total_cost=2.0
    and inven.cost=2.0
    and inven.quantity=2
    or inven.margin=1.0
    and inven.cost_without_expense=1.0
    and inven.markup=1.0

Expected result

  select * from
    item_nventory inven
where
     inven.last_import_cost=2.0
and inven.expenses=2.0
and inven.profit=2.0
or (inven.total_cost=2.0
and inven.cost=2.0
and inven.quantity=2 )
or (inven.margin=1.0
and inven.cost_without_expense=1.0
and inven.markup=1.0)

My final requirement will be something like below

 select * from
    item_nventory inven
where
    inven.last_import_cost=2.0
and inven.expenses=2.0
and inven.profit=2.0
or ((inven.total_cost=2.0
and inven.cost=2.0
and inven.quantity=2 ) or (inven.quantity_on_hand>0))
or (inven.margin=1.0
and inven.cost_without_expense=1.0
and inven.markup=1.0)

Please help out me in this.

Body:
I think, problem is in gradual contruction of predicates. Try contruction below.

Predicate firstA = criteriaBuilder.equal(itemRoot.get("margin"), 1.0);
Predicate firstB = criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0);
Predicate firstC = criteriaBuilder.equal(itemRoot.get("markup"), 1.0);
Predicate first = criteriaBuilder.and(firstA, firstB, firstC);

 . . .

Predicate finalPredicate = criteriaBuilder.or(first, second, third);

Or alternative solution with list - easy to add or remove another predicates (event dynamically)

List<Predicate> allPredList = new LinkedList<>();
{
  List<Predicate> firstPredList = new LinkedList<>();
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("margin"), 1.0));
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("costWithoutExpense"), 1.0));
  firstPredList.add(criteriaBuilder.equal(itemRoot.get("markup"), 1.0));
  allPredList.add(criteriaBuilder.and(firstPredList.toArray(new Predicate[0])));
}

 . . .

Predicate finalPredicate = criteriaBuilder.or(allPredList.toArray(new Predicate[0]));


来源: stackexchange

问:
How can I display a bing map in any HTML page?
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control. </p>

<p>How can I use this control? </p>

答:
With lots of JavaScript? Look on the http://www.bingmapsportal.com/ site where there is ample documentation.

There are also many other ways to embed a dynamic map in a site - take a look GIS.stackexchange.com's comparison of JavaScript mapping libraries. If you have more specific questions, we'll be happy to help over at GIS.se.

ContentLicense: CC BY-SA 3.0

Body:
Bing's got something they call "an AJAX control" that can dynamically embed generated maps into any webpage. There's an online interactive demo for the control.

How can I use this control?


问:
How to change the voice in pyttsx3?
This code is working but I'm only able to switch between the voices which came preInstalled in Microsoft Windows. These voices are "Microsoft David Mobile" and "Microsoft Zira Mobile".

Later I installed "Microsoft Kalpana Mobile" and set it as the default Windows voice. But still I'm not able to switch to "Microsoft Kalpana Mobile". The code is-

```<code>import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.say('Hello World')
engine.runAndWait()
</code>```

Only 0 and 1 are working as indices inside voices[].

I want the "Microsoft Kalpana Mobile" to speak. I'm working on this project for past 2 months. If this doesn't work, all my efforts will go in vein. Please Help:(

Thanks in advance.

答:
Windows 11 comes installed with 3 audios in its Voices folder present inside its parent Speech folder.

You need to add "Microsoft Kalpana Mobile" in the window's registry file.

Few voices and its address location.

DAVID(index = 0)

HAZEL(index = 1)

ZIRA(index = 2)

These voices are stored at:
*HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices*

You can print these addresses in any editor using the following code:

```<code>import pyttsx3

engine = pyttsx3.init('sapi5')

print('DAVID: ' + voices[0].id)
print('HAZEL: ' + voices[1].id)
print('ZIRA: ' + voices[2].id)
</code>```

You can also use the following method to know the name of the audio.

.name

Title: How to change the voice in pyttsx3?

Body:
This code is working but I'm only able to switch between the voices which came preInstalled in Microsoft Windows. These voices are "Microsoft David Mobile" and "Microsoft Zira Mobile".

Later I installed "Microsoft Kalpana Mobile" and set it as the default Windows voice. But still I'm not able to switch to "Microsoft Kalpana Mobile". The code is-

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #changing index changes voices but ony 0 and 1 are working here
engine.say('Hello World')
engine.runAndWait()

Only 0 and 1 are working as indices inside voices[].

I want the "Microsoft Kalpana Mobile" to speak. I'm working on this project for past 2 months. If this doesn't work, all my efforts will go in vein. Please Help:(

Thanks in advance.

Body:
Windows 11 comes installed with 3 audios in its Voices folder present inside its parent Speech folder.

You need to add "Microsoft Kalpana Mobile" in the window's registry file.

Few voices and its address location.

DAVID(index = 0)

HAZEL(index = 1)

ZIRA(index = 2)

These voices are stored at:
*HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices*

You can print these addresses in any editor using the following code:

import pyttsx3

engine = pyttsx3.init('sapi5')

print('DAVID: ' + voices[0].id)
print('HAZEL: ' + voices[1].id)
print('ZIRA: ' + voices[2].id)

You can also use the following method to know the name of the audio.

.name

ContentLicense: CC BY-SA 4.0


问:
Accessing a getter from a parameterized getter
tl;dr

How to access other getters from a parameterized getter?
Normally, you can use this.myGetter; but a parameterized getter is implemented as an arrow function, wherein this is undefined.
What's the preferred way to handle this case in Pinia?

I'd like to create a parameterized getter (multiSum) in my Pinia store, which accesses another getter (sum).

Getters can be accessed via this, but that won't work from within an arrow function which is used to implemented a parameterized getter: multiSum crashes because this is undefined in the context of the nested arrow function.

getters: {
  sum: (state) => state.a + state.b,
  multiSum: (state) => (count) => this.sum * count // crash: this is undefined
}
```
<p>In Vuex, parameterized getters can access other getters via a parameter instead of <code>this</code>, which also works in arrow functions. But afaik this API does not existing in Pinia.</p>
<p>I can work around this by capturing the store instance:</p>
<pre class="lang-js prettyprint-override"><code>multiSum(state) {
  const store = this
  return (count) => store.sum * count
}
</code>```

This works, but is pretty verbose. Is there a better (more framework-compliant) way to do this?

答:
this can be undefined inside arrow function because it's not interchangeable with regular function and gets a context from parent scope.

The usage of this and state is explained in details in the documentation. Either this or state can be used, but this has better Typescript and thus IDE support.

In the first snippet, state is already available in function scope, there is no need to access this:

```<code>multiSum: (state) => (count) => state.sum * count
</code>```

In the second snippet, const store = this isn't needed because a store is already this.

```<code>multiSum() {
  return (count) => this.sum * count
}
</code>```

Body:
tl;dr

How to access other getters from a parameterized getter?
Normally, you can use this.myGetter; but a parameterized getter is implemented as an arrow function, wherein this is undefined.
What's the preferred way to handle this case in Pinia?

I'd like to create a parameterized getter (multiSum) in my Pinia store, which accesses another getter (sum).

Getters can be accessed via this, but that won't work from within an arrow function which is used to implemented a parameterized getter: multiSum crashes because this is undefined in the context of the nested arrow function.

getters: {
  sum: (state) => state.a + state.b,
  multiSum: (state) => (count) => this.sum * count // crash: this is undefined
}

In Vuex, parameterized getters can access other getters via a parameter instead of this, which also works in arrow functions. But afaik this API does not existing in Pinia.

I can work around this by capturing the store instance:

multiSum(state) {
  const store = this
  return (count) => store.sum * count
}

This works, but is pretty verbose. Is there a better (more framework-compliant) way to do this?

Body:
this can be undefined inside arrow function because it's not interchangeable with regular function and gets a context from parent scope.

The usage of this and state is explained in details in the documentation. Either this or state can be used, but this has better Typescript and thus IDE support.

In the first snippet, state is already available in function scope, there is no need to access this:

multiSum: (state) => (count) => state.sum * count

In the second snippet, const store = this isn't needed because a store is already this.

multiSum() {
  return (count) => this.sum * count
}


问:
'NoneType' error when using PegasusTokenizer
I tried to use the transformers PegasusTokenizer from_pretrained method to load the "google/pegasus-large" tokenizer:

from transformers import PegasusTokenizer

tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-large")
```

This raised the following error:

TypeError: 'NoneType' object is not callable

Important: I am using a python notebook.

答:
The solution was to install sentencepiece package and restart the kernel of the python notebook.

```<code>pip install sentencepiece
</code>```

Body:
I tried to use the transformers PegasusTokenizer from_pretrained method to load the "google/pegasus-large" tokenizer:

from transformers import PegasusTokenizer

tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-large")

This raised the following error:

TypeError: 'NoneType' object is not callable

Important: I am using a python notebook.

Body:
The solution was to install sentencepiece package and restart the kernel of the python notebook.

pip install sentencepiece


问:
understanding private setters
I don't understand the need of having private setters which started with C# 2.

Having a setter method for me is letting the user to set some variables in that class. In doing so, we will not expose the variables directly to the users. Instead we let them do it through this public setter method.

This for me is using "encapsulation". There are some arguments out there which claim that private setters will let you apply encapsulation.

Am I not using encapsulation by using public setter methods? Why do we need private setters?

What is the difference between immutable class and a class with private setters?

答:
Despite the easy an clean way to write both, readonly, auto and private setters are things totally different.

Readonly properties are simply a fast and clean way to declare constants/statics in code:

```<code>   //constants
   public const int Constant = 50;
   public readonly int ReadOnly = 50;
   public int ConstantMethod()
   {
       return 50;
   }
</code>```

And for statics:

```<code>   public static readonly int Value = 50;
   public static int ValueMethod()
   {
       return 50;
   }
</code>```

Any of them is the same thing, works the same way, except for readonly, that you can initialize in constructor. Even so, that´s a matter of how you like to code, changes nothing the results.

Remembering that static readonly is for types that don´t have literals, for methods inside classes or structs. Remembering also that new invokes the constructor of a class/struct.

Auto is the placeholder of:

```<code>    private int field;
    public int Property
    {
        get
        {
            return field;
        }

        set
        {
            field = value;
        }
     }

     //In the auto property case, the "field" field is supressed, but it´s still
     //there.
       public int Property {get; set;}
</code>```

So, private setters comes in auto properties, in any of this examples above. The keyword to considerate is private.

private, internal, protected and public are access keywords. So, if you declare:

```<code>    public int Property { get; private set; }
</code>```

You just are saying that you want that the "set" part of Property can be changed only for the class itself.

```<code>    public int Property { get; protected set; }
</code>```

Say that the "set" part of Property can be changed only by the class itself or for nested class of the base class. Also:

```<code>     private int Property { get; set; }
     public int Property {private get; private set; }
</code>```

Both are the same. This is because the modifier that goes with the Property itself reflects in both "get" and "set" parts.

ContentLicense: CC BY-SA 2.5

Title: understanding private setters

Body:
Despite the easy an clean way to write both, readonly, auto and private setters are things totally different.

Readonly properties are simply a fast and clean way to declare constants/statics in code:

   //constants
   public const int Constant = 50;
   public readonly int ReadOnly = 50;
   public int ConstantMethod()
   {
       return 50;
   }

And for statics:

   public static readonly int Value = 50;
   public static int ValueMethod()
   {
       return 50;
   }

Any of them is the same thing, works the same way, except for readonly, that you can initialize in constructor. Even so, that´s a matter of how you like to code, changes nothing the results.

Remembering that static readonly is for types that don´t have literals, for methods inside classes or structs. Remembering also that new invokes the constructor of a class/struct.

Auto is the placeholder of:

    private int field;
    public int Property
    {
        get
        {
            return field;
        }

        set
        {
            field = value;
        }
     }

     //In the auto property case, the "field" field is supressed, but it´s still
     //there.
       public int Property {get; set;}

So, private setters comes in auto properties, in any of this examples above. The keyword to considerate is private.

private, internal, protected and public are access keywords. So, if you declare:

    public int Property { get; private set; }

You just are saying that you want that the "set" part of Property can be changed only for the class itself.

    public int Property { get; protected set; }

Say that the "set" part of Property can be changed only by the class itself or for nested class of the base class. Also:

     private int Property { get; set; }
     public int Property {private get; private set; }

Both are the same. This is because the modifier that goes with the Property itself reflects in both "get" and "set" parts.


问:
convert html to image in byte array java
How can i easily convert html to image and then to byte array without create it

thanks

答:
I think you can use the library

html2image-0.9.jar

you can download this library at this page: http://code.google.com/p/java-html2image/


问:
How to animate spining wheel in CSS?
I don't know how to form the question. I have old animation that was done in Flash, that I'm not able to translate to CSS animation.

This is an animation of a Spinning Wheel.

The question is: How can I implement the CSS animation for the crank/handle that drives the wheel? It should work like a Piston but connected to a circe in id="rotator" (inside SVG). The handle is located at 0,0 on the image above. Both small circles should match when the rotator is rotating. I already tried to use translate, and used transform-origin but I have no idea how to implement the animation. I have Action Script code as a reference, but I don't know how to map it to CSS or SCSS.

I was able to convert SWF into SVG, using pyswf. And I have a hard time understanding the math behind the logic I've created long ago and translating it into CSS (I've also tried with JS approach).

The code in Action Script I've extracted long ago, probably some decompiler from the swf file.

```<code>// copyright (c) 2006 Jakub "JCubic" Jankiewicz
var
    factor1 = 180.0 / Math.PI,              // współczynniki dla zamiany
    factor2 = Math.PI / 180.0;              // radiany stopinie i odwrotnie

// radiany na katy
function rad2deg(rad){
    return rad * factor1;
}
// katy na radiany
function deg2rad(deg){
    return deg * factor2;
}
// dlugosc odcinka
function line_length(x1, y1, x2, y2){
    return Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
// funkcja testowa przenoszaca krzyzyk
function show(x, y){ cross._x = x; cross._y = y; }
// funkcja testowa rysująca linie
function line_(x1, y1, x2, y2, ang){
    line._height = Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
    line._x = (x2 + x1) / 2;
    line._y = (y2 + y1) / 2;
    line._rotation = ang;
}

function getSpeed(){
    return step;
}

function setSpeed(value){
    // inicjacja zmiennych
    var Ox = 0,
        Oy = 360,                               // punkt zaczepienia
        r = 83.0,                               // promien odleglosc od rotatora
        angle = 0,
        step = value,
        rad = deg2rad(step),                    // cosinnus i sinus stopnia
        sinA = Math.sin(rad),                   // jednostkowego
        cosA = Math.cos(rad),
        sinAlpha;

    onEnterFrame = function() {
        if (angle == 0) {
            napedzacz._x = 0;       // poczatek obrotu
            napedzacz._y = r;
        } else {
            Bx = napedzacz._x * cosA + napedzacz._y * sinA;
            By = napedzacz._y * cosA - napedzacz._x * sinA;
            napedzacz._x = Bx;
            napedzacz._y = By;
            sinAlpha = (Ox - Bx) / line_length(Bx, By, Ox, Oy);
            napedzacz._rotation = - rad2deg(Math.asin(sinAlpha));
            kolo._rotation = 180 - angle;
            szpulka._rotation = 180 - angle * 2;
            rotator._rotation = 180 - angle;
        }
        angle = (angle+step) % 360;
    }
}
</code>```

It has Polish comments but they don't explain how to modify the code.

Here is my CodePen demo where I've tried to create SVG+CSS animation. I was able to rotate part of the spinning wheel, but don't know how to animate the handle (that is used to drive the wheel).

I've wanted to use SCSS and trigonometry functions (included in Pen) to generate every frame of the animation, but I'm not sure how I should go about it.

I have the original SWF file but I'm not able to play it, since the only SWF player I've found doesn't execute code. And I'm not able to install Gnash on Fedora (even that I've written article how to do that long go, the solution doesn't work anymore). That's why I want to create something modern with SVG.

If you have something to open the SWF file here is the link to the original file:

https://jcubic.pl/kolowrotek.swf

the problem is that constants in the Action Script code use different coordinate systems and different scales, I have no idea how to map that code into JavaScript (I was able to run it, but it has issues, there are two commented-out lines in Pen). I also have no idea why the animation rotate in different direction than CSS, I was not able to reverse it. I would prefer not to use JavaScript since it will hard to match CSS animation with JavaScript, and doing aninmation in JavaScript make some delay when handle is in wrong position.

答:
Note, following answer content may be subject to edits in the near future, and is only intended as a starting point to assist the OP's author.

I believe what ya may need for turning the crank is the transform-origin CSS property.

In regards to rotate() direction, the StackExchange -- How to determine direction of rotation in CSS3 transitions? answers may be of use. TLDR; positive numbers rotate clockwise, and negative numbers rotate anticlockwise, however this may be modified via from configuration.

I'll dig into the source a bit over the next few minutes and attempt a more complete answer.

Updates

You were very close to a solution!  From what I spotted the #handle element was missing an animation property/value, and the @keyframes handle_rotate needed defined.

Here's a bit of code that should get ya a little closer to a full solution...

:root {
    --time: 5s;
    --handle-translate-x: 291.59718px;
    --handle-translate-y: 210.10511px;
    --handle-rotate-start: 20deg;
    --handle-transform-origin-x: 4.742px;
    --handle-transform-origin-y: 15.799px;
}
/* ... */
#handle {
    animation: handle_rotate var(--time) linear infinite;
    transform-origin: var(--handle-transform-origin-x) var(--handle-transform-origin-y);
    transform:
        translate(var(--handle-translate-x), var(--handle-translate-y))
        rotate(var(--handle-rotate-start));
}
/* ... */
@keyframes handle_rotate {
    to {
        transform:
            translate(var(--handle-translate-x), var(--handle-translate-y))
            rotate(calc(var(--handle-rotate-start) + 360deg));
    }
}
```

... Though be aware values still need a bit of fiddling with to get all the parts to sync-up with one another.  In this case I'd suggest leveraging CSS Custom Properties (variables)

Title: How to animate spining wheel in CSS?

Body:
I don't know how to form the question. I have old animation that was done in Flash, that I'm not able to translate to CSS animation.

This is an animation of a Spinning Wheel.

The question is: How can I implement the CSS animation for the crank/handle that drives the wheel? It should work like a Piston but connected to a circe in id="rotator" (inside SVG). The handle is located at 0,0 on the image above. Both small circles should match when the rotator is rotating. I already tried to use translate, and used transform-origin but I have no idea how to implement the animation. I have Action Script code as a reference, but I don't know how to map it to CSS or SCSS.

I was able to convert SWF into SVG, using pyswf. And I have a hard time understanding the math behind the logic I've created long ago and translating it into CSS (I've also tried with JS approach).

The code in Action Script I've extracted long ago, probably some decompiler from the swf file.

// copyright (c) 2006 Jakub "JCubic" Jankiewicz
var
    factor1 = 180.0 / Math.PI,              // współczynniki dla zamiany
    factor2 = Math.PI / 180.0;              // radiany stopinie i odwrotnie

// radiany na katy
function rad2deg(rad){
    return rad * factor1;
}
// katy na radiany
function deg2rad(deg){
    return deg * factor2;
}
// dlugosc odcinka
function line_length(x1, y1, x2, y2){
    return Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
}
// funkcja testowa przenoszaca krzyzyk
function show(x, y){ cross._x = x; cross._y = y; }
// funkcja testowa rysująca linie
function line_(x1, y1, x2, y2, ang){
    line._height = Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
    line._x = (x2 + x1) / 2;
    line._y = (y2 + y1) / 2;
    line._rotation = ang;
}

function getSpeed(){
    return step;
}

function setSpeed(value){
    // inicjacja zmiennych
    var Ox = 0,
        Oy = 360,                               // punkt zaczepienia
        r = 83.0,                               // promien odleglosc od rotatora
        angle = 0,
        step = value,
        rad = deg2rad(step),                    // cosinnus i sinus stopnia
        sinA = Math.sin(rad),                   // jednostkowego
        cosA = Math.cos(rad),
        sinAlpha;

    onEnterFrame = function() {
        if (angle == 0) {
            napedzacz._x = 0;       // poczatek obrotu
            napedzacz._y = r;
        } else {
            Bx = napedzacz._x * cosA + napedzacz._y * sinA;
            By = napedzacz._y * cosA - napedzacz._x * sinA;
            napedzacz._x = Bx;
            napedzacz._y = By;
            sinAlpha = (Ox - Bx) / line_length(Bx, By, Ox, Oy);
            napedzacz._rotation = - rad2deg(Math.asin(sinAlpha));
            kolo._rotation = 180 - angle;
            szpulka._rotation = 180 - angle * 2;
            rotator._rotation = 180 - angle;
        }
        angle = (angle+step) % 360;
    }
}

It has Polish comments but they don't explain how to modify the code.

Here is my CodePen demo where I've tried to create SVG+CSS animation. I was able to rotate part of the spinning wheel, but don't know how to animate the handle (that is used to drive the wheel).

I've wanted to use SCSS and trigonometry functions (included in Pen) to generate every frame of the animation, but I'm not sure how I should go about it.

I have the original SWF file but I'm not able to play it, since the only SWF player I've found doesn't execute code. And I'm not able to install Gnash on Fedora (even that I've written article how to do that long go, the solution doesn't work anymore). That's why I want to create something modern with SVG.

If you have something to open the SWF file here is the link to the original file:

https://jcubic.pl/kolowrotek.swf

the problem is that constants in the Action Script code use different coordinate systems and different scales, I have no idea how to map that code into JavaScript (I was able to run it, but it has issues, there are two commented-out lines in Pen). I also have no idea why the animation rotate in different direction than CSS, I was not able to reverse it. I would prefer not to use JavaScript since it will hard to match CSS animation with JavaScript, and doing aninmation in JavaScript make some delay when handle is in wrong position.

Body:
Note, following answer content may be subject to edits in the near future, and is only intended as a starting point to assist the OP's author.

I believe what ya may need for turning the crank is the transform-origin CSS property.

In regards to rotate() direction, the StackExchange -- How to determine direction of rotation in CSS3 transitions? answers may be of use. TLDR; positive numbers rotate clockwise, and negative numbers rotate anticlockwise, however this may be modified via from configuration.

I'll dig into the source a bit over the next few minutes and attempt a more complete answer.

Updates

You were very close to a solution!  From what I spotted the #handle element was missing an animation property/value, and the @keyframes handle_rotate needed defined.

Here's a bit of code that should get ya a little closer to a full solution...

:root {
    --time: 5s;
    --handle-translate-x: 291.59718px;
    --handle-translate-y: 210.10511px;
    --handle-rotate-start: 20deg;
    --handle-transform-origin-x: 4.742px;
    --handle-transform-origin-y: 15.799px;
}
/* ... */
#handle {
    animation: handle_rotate var(--time) linear infinite;
    transform-origin: var(--handle-transform-origin-x) var(--handle-transform-origin-y);
    transform:
        translate(var(--handle-translate-x), var(--handle-translate-y))
        rotate(var(--handle-rotate-start));
}
/* ... */
@keyframes handle_rotate {
    to {
        transform:
            translate(var(--handle-translate-x), var(--handle-translate-y))
            rotate(calc(var(--handle-rotate-start) + 360deg));
    }
}

... Though be aware values still need a bit of fiddling with to get all the parts to sync-up with one another.  In this case I'd suggest leveraging CSS Custom Properties (variables)


问:
Unity terrain texture missing after upgrade from 5 to 2020
I upgraded from Unity 5.4 to Unity 2020 and after my project was imported the terrain for one of the scenes seems to be missing the texture (see image below).

Anyone have any suggestions for a fix?

I've also include my Terrain Settings screenshots (2 images to cover the scrolling).

In case this is helpful, the terrain was part of a Free Rocks asset release over 5 years ago.

答: You can make a Backup and then try to delete the Library folder inside your project so that Unity rebuilds your project.</p>


问:
Weird behavior seting color to vtkPolyData
I'm trying to assign custom colours to cells in VTK. If I render my model without any colour assignment, it looks like this:

Now I'm trying to assign diferent colors to every triangle in the mesh. Inspired by this solution I tryied the following to color it in blue (this is a simplification, my colors will depend on the thickness):

```<code>color = vtk.vtkUnsignedCharArray()
color.SetName("Colors")
color.SetNumberOfComponents(3)
color.SetNumberOfTuples( surface.GetOutput().GetNumberOfCells() )

for i in range(surface.GetOutput().GetNumberOfCells()):
    color_tup=[0,0,255]
    color.SetTuple(i, color_tup)
</code>```

I confirm that dimensions of my vtkPolyData and the color array match:

```<code>assert color.GetNumberOfTuples()==surface.GetOutput().GetNumberOfCells(), "dimensions do not match"
</code>```

Then, I assign the color array to the PolyData as Scalars:

```<code>surface.GetOutput().GetCellData().SetScalars(color)

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
mapper.SetColorModeToDirectScalars()

actor = vtk.vtkActor()
actor.SetMapper(mapper)

renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

renderer.AddActor(actor)
renderer.SetBackground(1, 1, 1)

# Render and interact
renderWindow.Render()
renderWindowInteractor.Start()
</code>```

And obtained this (note that I had to change the background to white to distinguish the mesh):

If I run the code from here, it works like charm, but If I replace one of the shapes from that solution with my mesh, colours disappear again... Any Idea?

答:
I found out that this fix my problem:</p>
```<code>mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
mapper.SetColorModeToDirectScalars()
mapper.SetScalarModeToUseCellData()
</code>```

Body:
I'm trying to assign custom colours to cells in VTK. If I render my model without any colour assignment, it looks like this:

Now I'm trying to assign diferent colors to every triangle in the mesh. Inspired by this solution I tryied the following to color it in blue (this is a simplification, my colors will depend on the thickness):

color = vtk.vtkUnsignedCharArray()
color.SetName("Colors")
color.SetNumberOfComponents(3)
color.SetNumberOfTuples( surface.GetOutput().GetNumberOfCells() )

for i in range(surface.GetOutput().GetNumberOfCells()):
    color_tup=[0,0,255]
    color.SetTuple(i, color_tup)

I confirm that dimensions of my vtkPolyData and the color array match:

assert color.GetNumberOfTuples()==surface.GetOutput().GetNumberOfCells(), "dimensions do not match"

Then, I assign the color array to the PolyData as Scalars:

surface.GetOutput().GetCellData().SetScalars(color)

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
mapper.SetColorModeToDirectScalars()

actor = vtk.vtkActor()
actor.SetMapper(mapper)

renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

renderer.AddActor(actor)
renderer.SetBackground(1, 1, 1)

# Render and interact
renderWindow.Render()
renderWindowInteractor.Start()

And obtained this (note that I had to change the background to white to distinguish the mesh):

If I run the code from here, it works like charm, but If I replace one of the shapes from that solution with my mesh, colours disappear again... Any Idea?

Body:
I found out that this fix my problem:

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(surface.GetOutputPort())
mapper.SetColorModeToDirectScalars()
mapper.SetScalarModeToUseCellData()


问:
Pyinstaller creating empty dist folder
I have python 3.9.x and Pyinstaller 4.9 is compatible with all python versions. I am also running on Ubuntu 21.10. My python project contains one .py file and one .kv file. I have tried it also with only the .py file but still the dist folder is empty.

This is what I have tried :

pip install pyinstaller

pyinstaller --onefile -w filename.py

I also tried running these commands with sudo because I was desperate.

I tried uninstalling it : sudo pip uninstall pyinstaller and the reinstalling it again.

I use kivy in my project and I want to convert my python file into an exe so that my teacher won't have to download kivy. He has a Mac by the way.

```<code>29 INFO: PyInstaller: 4.9
29 INFO: Python: 3.9.7
30 INFO: Platform: Linux-5.13.0-28-generic-x86_64-with-glibc2.34
30 INFO: wrote /home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec
32 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/filzo/School/Lang Prog/Devoir 1']
153 INFO: checking Analysis
153 INFO: Building Analysis because Analysis-00.toc is non existent
153 INFO: Initializing module dependency graph...
154 INFO: Caching module graph hooks...
162 INFO: Analyzing base_library.zip ...
1624 INFO: Processing pre-find module path hook distutils from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py'.
1624 INFO: distutils: retargeting to non-venv dir '/usr/lib/python3.9'
3532 INFO: Caching module dependency graph...
3621 INFO: running Analysis Analysis-00.toc
3641 INFO: Analyzing /home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.py
4728 INFO: Processing module hooks...
4729 INFO: Loading module hook 'hook-multiprocessing.util.py' from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks'...
4729 INFO: Loading module hook 'hook-kivy.py' from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks'...
[INFO   ] [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_69.txt
4733 INFO: [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_69.txt
[INFO   ] [Kivy        ] v1.11.0
4733 INFO: [Kivy        ] v1.11.0
[INFO   ] [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
4733 INFO: [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
[INFO   ] [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
4733 INFO: [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
[INFO   ] [Python      ] Interpreter at "/usr/bin/python3"
4733 INFO: [Python      ] Interpreter at "/usr/bin/python3"
[INFO   ] [Factory     ] 184 symbols loaded
4734 INFO: [Factory     ] 184 symbols loaded
[INFO   ] [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_70.txt
[INFO   ] [Kivy        ] v1.11.0
[INFO   ] [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
[INFO   ] [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
[INFO   ] [Python      ] Interpreter at "/usr/bin/python3"
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
 Traceback (most recent call last):
4844 WARNING: stderr: Traceback (most recent call last):
   File "/usr/local/bin/pyinstaller", line 8, in <module>
4844 WARNING: stderr:   File "/usr/local/bin/pyinstaller", line 8, in <module>
     sys.exit(run())
4845 WARNING: stderr:     sys.exit(run())
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 124, in run
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 124, in run
     run_build(pyi_config, spec_file, **vars(args))
4845 WARNING: stderr:     run_build(pyi_config, spec_file, **vars(args))
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 58, in run_build
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 58, in run_build
     PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
4845 WARNING: stderr:     PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 793, in main
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 793, in main
     build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
4845 WARNING: stderr:     build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 725, in build
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 725, in build
     exec(code, spec_namespace)
4845 WARNING: stderr:     exec(code, spec_namespace)
   File "/home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec", line 7, in <module>
4845 WARNING: stderr:   File "/home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec", line 7, in <module>
     a = Analysis(['devoir_1_GUI.py'],
4845 WARNING: stderr:     a = Analysis(['devoir_1_GUI.py'],
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 277, in __init__
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 277, in __init__
     self.__postinit__()
4846 WARNING: stderr:     self.__postinit__()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/datastruct.py", line 155, in __postinit__
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/datastruct.py", line 155, in __postinit__
     self.assemble()
4846 WARNING: stderr:     self.assemble()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 445, in assemble
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 445, in assemble
     self.graph.process_post_graph_hooks(self)
4846 WARNING: stderr:     self.graph.process_post_graph_hooks(self)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/analysis.py", line 326, in process_post_graph_hooks
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/analysis.py", line 326, in process_post_graph_hooks
     module_hook.post_graph(analysis)
4846 WARNING: stderr:     module_hook.post_graph(analysis)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 398, in post_graph
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 398, in post_graph
     self._load_hook_module()
4846 WARNING: stderr:     self._load_hook_module()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 361, in _load_hook_module
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 361, in _load_hook_module
     self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
4846 WARNING: stderr:     self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/compat.py", line 606, in importlib_load_source
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/compat.py", line 606, in importlib_load_source
     return mod_loader.load_module()
4847 WARNING: stderr:     return mod_loader.load_module()
   File "<frozen importlib._bootstrap_external>", line 529, in _check_name_wrapper
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 529, in _check_name_wrapper
   File "<frozen importlib._bootstrap_external>", line 1029, in load_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 1029, in load_module
   File "<frozen importlib._bootstrap_external>", line 854, in load_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 854, in load_module
   File "<frozen importlib._bootstrap>", line 274, in _load_module_shim
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 274, in _load_module_shim
   File "<frozen importlib._bootstrap>", line 711, in _load
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 711, in _load
   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
   File "<frozen importlib._bootstrap_external>", line 850, in exec_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 850, in exec_module
   File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/hook-kivy.py", line 21, in <module>
4848 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/hook-kivy.py", line 21, in <module>
     hiddenimports = get_deps_all()['hiddenimports']
4848 WARNING: stderr:     hiddenimports = get_deps_all()['hiddenimports']
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 275, in get_deps_all
4848 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 275, in get_deps_all
     'binaries': _find_gst_binaries(),
4848 WARNING: stderr:     'binaries': _find_gst_binaries(),
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 354, in _find_gst_binaries
4848 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 354, in _find_gst_binaries
     gst_plugin_path = _find_gst_plugin_path()
4848 WARNING: stderr:     gst_plugin_path = _find_gst_plugin_path()
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 342, in _find_gst_plugin_path
4849 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 342, in _find_gst_plugin_path
     match = re.search(r'\s+(\S+libgstcoreelements\.\S+)', stdoutdata)
4849 WARNING: stderr:     match = re.search(r'\s+(\S+libgstcoreelements\.\S+)', stdoutdata)
   File "/usr/lib/python3.9/re.py", line 201, in search
4849 WARNING: stderr:   File "/usr/lib/python3.9/re.py", line 201, in search
     return _compile(pattern, flags).search(string)
4849 WARNING: stderr:     return _compile(pattern, flags).search(string)
 TypeError: cannot use a string pattern on a bytes-like object
4849 WARNING: stderr: TypeError: cannot use a string pattern on a bytes-like object
</code>```

答: Instead of using the desktop's terminal, I used Pycharm's terminal and it worked. I think it's because Pycharm uses venv.</p>

Title: Pyinstaller creating empty dist folder

Body:
I have python 3.9.x and Pyinstaller 4.9 is compatible with all python versions. I am also running on Ubuntu 21.10. My python project contains one .py file and one .kv file. I have tried it also with only the .py file but still the dist folder is empty.

This is what I have tried :

pip install pyinstaller

pyinstaller --onefile -w filename.py

I also tried running these commands with sudo because I was desperate.

I tried uninstalling it : sudo pip uninstall pyinstaller and the reinstalling it again.

I use kivy in my project and I want to convert my python file into an exe so that my teacher won't have to download kivy. He has a Mac by the way.

29 INFO: PyInstaller: 4.9
29 INFO: Python: 3.9.7
30 INFO: Platform: Linux-5.13.0-28-generic-x86_64-with-glibc2.34
30 INFO: wrote /home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec
32 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/filzo/School/Lang Prog/Devoir 1']
153 INFO: checking Analysis
153 INFO: Building Analysis because Analysis-00.toc is non existent
153 INFO: Initializing module dependency graph...
154 INFO: Caching module graph hooks...
162 INFO: Analyzing base_library.zip ...
1624 INFO: Processing pre-find module path hook distutils from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py'.
1624 INFO: distutils: retargeting to non-venv dir '/usr/lib/python3.9'
3532 INFO: Caching module dependency graph...
3621 INFO: running Analysis Analysis-00.toc
3641 INFO: Analyzing /home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.py
4728 INFO: Processing module hooks...
4729 INFO: Loading module hook 'hook-multiprocessing.util.py' from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks'...
4729 INFO: Loading module hook 'hook-kivy.py' from '/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks'...
[INFO   ] [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_69.txt
4733 INFO: [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_69.txt
[INFO   ] [Kivy        ] v1.11.0
4733 INFO: [Kivy        ] v1.11.0
[INFO   ] [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
4733 INFO: [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
[INFO   ] [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
4733 INFO: [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
[INFO   ] [Python      ] Interpreter at "/usr/bin/python3"
4733 INFO: [Python      ] Interpreter at "/usr/bin/python3"
[INFO   ] [Factory     ] 184 symbols loaded
4734 INFO: [Factory     ] 184 symbols loaded
[INFO   ] [Logger      ] Record log in /home/filzo/.kivy/logs/kivy_22-02-06_70.txt
[INFO   ] [Kivy        ] v1.11.0
[INFO   ] [Kivy        ] Installed at "/usr/lib/python3/dist-packages/kivy/__init__.py"
[INFO   ] [Python      ] v3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0]
[INFO   ] [Python      ] Interpreter at "/usr/bin/python3"
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
 Traceback (most recent call last):
4844 WARNING: stderr: Traceback (most recent call last):
   File "/usr/local/bin/pyinstaller", line 8, in <module>
4844 WARNING: stderr:   File "/usr/local/bin/pyinstaller", line 8, in <module>
     sys.exit(run())
4845 WARNING: stderr:     sys.exit(run())
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 124, in run
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 124, in run
     run_build(pyi_config, spec_file, **vars(args))
4845 WARNING: stderr:     run_build(pyi_config, spec_file, **vars(args))
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 58, in run_build
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/__main__.py", line 58, in run_build
     PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
4845 WARNING: stderr:     PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 793, in main
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 793, in main
     build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
4845 WARNING: stderr:     build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 725, in build
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 725, in build
     exec(code, spec_namespace)
4845 WARNING: stderr:     exec(code, spec_namespace)
   File "/home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec", line 7, in <module>
4845 WARNING: stderr:   File "/home/filzo/School/Lang Prog/Devoir 1/devoir_1_GUI.spec", line 7, in <module>
     a = Analysis(['devoir_1_GUI.py'],
4845 WARNING: stderr:     a = Analysis(['devoir_1_GUI.py'],
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 277, in __init__
4845 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 277, in __init__
     self.__postinit__()
4846 WARNING: stderr:     self.__postinit__()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/datastruct.py", line 155, in __postinit__
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/datastruct.py", line 155, in __postinit__
     self.assemble()
4846 WARNING: stderr:     self.assemble()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 445, in assemble
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/building/build_main.py", line 445, in assemble
     self.graph.process_post_graph_hooks(self)
4846 WARNING: stderr:     self.graph.process_post_graph_hooks(self)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/analysis.py", line 326, in process_post_graph_hooks
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/analysis.py", line 326, in process_post_graph_hooks
     module_hook.post_graph(analysis)
4846 WARNING: stderr:     module_hook.post_graph(analysis)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 398, in post_graph
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 398, in post_graph
     self._load_hook_module()
4846 WARNING: stderr:     self._load_hook_module()
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 361, in _load_hook_module
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/depend/imphook.py", line 361, in _load_hook_module
     self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
4846 WARNING: stderr:     self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/compat.py", line 606, in importlib_load_source
4846 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/compat.py", line 606, in importlib_load_source
     return mod_loader.load_module()
4847 WARNING: stderr:     return mod_loader.load_module()
   File "<frozen importlib._bootstrap_external>", line 529, in _check_name_wrapper
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 529, in _check_name_wrapper
   File "<frozen importlib._bootstrap_external>", line 1029, in load_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 1029, in load_module
   File "<frozen importlib._bootstrap_external>", line 854, in load_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 854, in load_module
   File "<frozen importlib._bootstrap>", line 274, in _load_module_shim
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 274, in _load_module_shim
   File "<frozen importlib._bootstrap>", line 711, in _load
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 711, in _load
   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
   File "<frozen importlib._bootstrap_external>", line 850, in exec_module
4847 WARNING: stderr:   File "<frozen importlib._bootstrap_external>", line 850, in exec_module
   File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
4847 WARNING: stderr:   File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/hook-kivy.py", line 21, in <module>
4848 WARNING: stderr:   File "/usr/local/lib/python3.9/dist-packages/PyInstaller/hooks/hook-kivy.py", line 21, in <module>
     hiddenimports = get_deps_all()['hiddenimports']
4848 WARNING: stderr:     hiddenimports = get_deps_all()['hiddenimports']
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 275, in get_deps_all
4848 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 275, in get_deps_all
     'binaries': _find_gst_binaries(),
4848 WARNING: stderr:     'binaries': _find_gst_binaries(),
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 354, in _find_gst_binaries
4848 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 354, in _find_gst_binaries
     gst_plugin_path = _find_gst_plugin_path()
4848 WARNING: stderr:     gst_plugin_path = _find_gst_plugin_path()
   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 342, in _find_gst_plugin_path
4849 WARNING: stderr:   File "/usr/lib/python3/dist-packages/kivy/tools/packaging/pyinstaller_hooks/__init__.py", line 342, in _find_gst_plugin_path
     match = re.search(r'\s+(\S+libgstcoreelements\.\S+)', stdoutdata)
4849 WARNING: stderr:     match = re.search(r'\s+(\S+libgstcoreelements\.\S+)', stdoutdata)
   File "/usr/lib/python3.9/re.py", line 201, in search
4849 WARNING: stderr:   File "/usr/lib/python3.9/re.py", line 201, in search
     return _compile(pattern, flags).search(string)
4849 WARNING: stderr:     return _compile(pattern, flags).search(string)
 TypeError: cannot use a string pattern on a bytes-like object
4849 WARNING: stderr: TypeError: cannot use a string pattern on a bytes-like object


问:
PHP & MySQL: How can I use "SET @rank=0;" in $query=
In my PHP file, I use this line to pull data from my mySQL database:

```<code>$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";
</code>```

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

```<code>public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }
</code>```

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

```<code>$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...
</code>```

I changed the result to:

```<code>$result = $mysqli_multi_query($query);
</code>```

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?

答:
This guy here seems to have a way of setting the variable in the same query to zero.  I don't have MySQL set on up on this machine to try it, though.

Here's the query he suggests in his blog post:

```<code>select @rownum:=@rownum+1 ‘rank’, p.* from player p, (SELECT @rownum:=0) r order by score desc limit 10;
</code>```

(Is there some homework assignment coming due somewhere having to do with computing ranks?  This is the third question I've seen on this in two days.)

Are you checking for duplicate scores?

Body:
In my PHP file, I use this line to pull data from my mySQL database:

$query = "SET @rank=0; SELECT @rank:=@rank +1 as rank, Blah Blah...";

If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.

But, if I use it in PHP, then I get an error. It doesn't like the "SET @rank=0;" bit. Is there a way to use "SET @rank=0;" when it's in "$query=" ? Is there a workaround?

The rest of the code is standard stuff for pulling data from a db:

public function getmyData() {

 $mysql = mysql_connect(connection stuff);

 $query = "SELECT @rank:=@rank +1 as rank, formatted_school_name,  blah blah";

 $result = mysql_query($query);

            $ret = array();
                 while ($row = mysql_fetch_object($result)) {
                    $tmp = new VOmyData1();
                    $tmp->stuff1 = $row-> stuff1;
                    $tmp->stuff2 = $row->stuff2;

                    $ret[] = $tmp;
                        }
                 mysql_free_result($result);

                 return $ret;

    }

Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:

$query = "SET @rank = 0";

$query .= "SELECT @rank:=@rank +1 as rank...

I changed the result to:

$result = $mysqli_multi_query($query);

But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?

Body:
This guy here seems to have a way of setting the variable in the same query to zero.  I don't have MySQL set on up on this machine to try it, though.

Here's the query he suggests in his blog post:

select @rownum:=@rownum+1 ‘rank’, p.* from player p, (SELECT @rownum:=0) r order by score desc limit 10;

(Is there some homework assignment coming due somewhere having to do with computing ranks?  This is the third question I've seen on this in two days.)

Are you checking for duplicate scores?


问:
How do I center navbar items in bootstrap (mx-auto doesn't work)
```<code>  <nav class="navbar navbar-expand-sm navbar-light">
    <button
      class="navbar-toggler"
      type="button"
      data-bs-toggle="collapse"
      data-bs-target="#navbarNav"
      aria-controls="navbarNav"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav mx-auto">
        <li class="nav-item">
          <a class="nav-link" href="#">
            Home
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">
            About
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">
            products
          </a>
        </li>

        <li class="nav-item">
          <a class="nav-link" href="#">
            gallery
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">
            order
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">
            contact
          </a>
        </li>
      </ul>
    </div>
  </nav>
</code>```

I can't center the nav-items. It would align to the right even when I put mx-auto. I tried margin-left but then it wouldn't be responsive. It would only center navbar-nav but not the item inside of them. How would I fix this? Thank you

答: You can use "display: flex" and "justify-content: center" which might help you to solve this issue. If you want to align the text, you can use "text-align: center".</p>

Body:
    <button
      class="navbar-toggler"
      type="button"
      data-bs-toggle="collapse"
      data-bs-target="#navbarNav"
      aria-controls="navbarNav"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >

    </button>

            Home

            About

            products

            gallery

            order

            contact

I can't center the nav-items. It would align to the right even when I put mx-auto. I tried margin-left but then it wouldn't be responsive. It would only center navbar-nav but not the item inside of them. How would I fix this? Thank you


问:
my text does not show inside absolute positioned div
My text doesn't show inside absolute positioned div. Some of them show but some of them don't. The divs are positioned absolute
and the styles are the same but I don't know why it doesn't show.

.shapeContainer {
  position: relative;
}

.shape {
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 255px;
  background: rgb(0, 31, 255);
  background: linear-gradient( 135deg, rgba(0, 31, 255, 1) 0%, rgba(0, 44, 119, 1) 27%);
  clip-path: polygon( 0 0, 100% 0, 100% 78.51%, 25.42% 78.51%, 27.25% 53.71%, 22.74% 53.71%, 18.92% 100%, 0 100%);
}

.shape2 {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 260px;
  background-color: white;
  clip-path: polygon( 0 0, 100% 0, 100% 79.67%, 24.85% 79.67%, 26.55% 55.28%, 22.88% 55.28%, 19.06% 100%, 0 100%);
}

.shape3 {
  position: absolute;
  z-index: 0;
  width: 100%;
  height: 265px;
  margin-bottom: 0;
  background-color: rgba(0, 44, 119, 1);
  clip-path: polygon( 0 0, 100% 0, 100% 80.95%, 24.15% 80.95%, 25.98% 57.14%, 23.02% 57.14%, 19.35% 100%, 0 100%);
}

.shape4 {
  position: absolute;
  z-index: 4;
  width: 100%;
  height: 30px;
  margin-top: 75px;
  background-color: #004be2;
}

.shape5 {
  position: absolute;
  z-index: 4;
  width: 100%;
  height: 255px;
  background-color: #002157;
  clip-path: polygon(0 0, 25% 0, 18% 92%, 0 92%);
}

.shape6 {
  position: absolute;
  z-index: 5;
  width: 100%;
  height: 240px;
  background-color: #0c00e0;
  clip-path: polygon(47% 19%, 100% 19%, 100% 72%, 42% 72%);
}

.shape7 {
  position: absolute;
  z-index: 6;
  width: 100%;
  height: 200px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(56% 0, 100% 0, 100% 47%, 52% 47%);
}

.shape8 {
  position: absolute;
  top: 100px;
  left: -45px;
  z-index: 7;
  width: 100%;
  height: 100px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(32.19% 61.15%, 38.25% 61.15%, 37.3% 90%, 31.26% 90%);
}

.shape9 {
  position: absolute;
  top: 100px;
  left: 25px;
  z-index: 8;
  width: 100%;
  height: 100px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(32.19% 61.15%, 38.25% 61.15%, 37.3% 90%, 31.26% 90%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header className="header">
  <div className="container">
    <div className="shapeContainer">
      <div className="shape">shape8 1</div>
      <div className="shape2"> shape 2</div>
      <div className="shape3">shape 3</div>
      <div className="shape4">shape 4</div>
      <div className="shape5">shape5 </div>
      <div className="shape6">shape6</div>
      <div className="shape7">shape 7</div>

              shape8

              shape9

    </div>
  </div>
</header></code>```

答:
The path cut of everything positioned out of the shape you draw. The text is still in the top left corner of div but cut off.

I guess there are more solutions.

I would use one more tag to wrap the text into. Than I would position it to the place I need via position:absolute;.

There is possibly more proper way to do it - change size of div to the size of shape you want and than draw the path in that container. Move it via position absolute. Text would still be in the top left corner, but easily moved by in wrapper div.

.shapeContainer {
    position: relative;
  }

 .shape5 {
    position: absolute;
    z-index: 4;
    width: 100%;
    height: 255px;
    background-color: red;
    clip-path: polygon(0 0, 25% 0, 18% 92%, 0 92%);
  }
 .textInShape{
    position: absolute;
    left: 5%;
    top: 20px;
    color: aliceblue;
}

.shape7 {
    position: absolute;
    left: 20%;
    z-index: 6;
    width: 50%;
    height: 100px;
    background-color: blue;
    opacity: 0.5;
    clip-path: polygon(0 0, 100% 0, 100% 82%, 44% 82%); /*changed size of div and path*/
  }
   .textInShape2 {
      position: absolute;
      color: aliceblue;
      width:100%;
      height: 100%;
      text-align: center;
/*if you dont mind exact position, u can also align the text to middle in this case*/
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
      <div class="container">
        <div class="shapeContainer">

          <div href="#" class="shape5">
            <div class="textInShape">shape5</div>
           </div>
          <div class="shape7">
            HALLOOO
          </div>
        </div>
      </div>
    </header></code>```

Body:
My text doesn't show inside absolute positioned div. Some of them show but some of them don't. The divs are positioned absolute
and the styles are the same but I don't know why it doesn't show.

.shapeContainer {
  position: relative;
}

.shape {
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 255px;
  background: rgb(0, 31, 255);
  background: linear-gradient( 135deg, rgba(0, 31, 255, 1) 0%, rgba(0, 44, 119, 1) 27%);
  clip-path: polygon( 0 0, 100% 0, 100% 78.51%, 25.42% 78.51%, 27.25% 53.71%, 22.74% 53.71%, 18.92% 100%, 0 100%);
}

.shape2 {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 260px;
  background-color: white;
  clip-path: polygon( 0 0, 100% 0, 100% 79.67%, 24.85% 79.67%, 26.55% 55.28%, 22.88% 55.28%, 19.06% 100%, 0 100%);
}

.shape3 {
  position: absolute;
  z-index: 0;
  width: 100%;
  height: 265px;
  margin-bottom: 0;
  background-color: rgba(0, 44, 119, 1);
  clip-path: polygon( 0 0, 100% 0, 100% 80.95%, 24.15% 80.95%, 25.98% 57.14%, 23.02% 57.14%, 19.35% 100%, 0 100%);
}

.shape4 {
  position: absolute;
  z-index: 4;
  width: 100%;
  height: 30px;
  margin-top: 75px;
  background-color: #004be2;
}

.shape5 {
  position: absolute;
  z-index: 4;
  width: 100%;
  height: 255px;
  background-color: #002157;
  clip-path: polygon(0 0, 25% 0, 18% 92%, 0 92%);
}

.shape6 {
  position: absolute;
  z-index: 5;
  width: 100%;
  height: 240px;
  background-color: #0c00e0;
  clip-path: polygon(47% 19%, 100% 19%, 100% 72%, 42% 72%);
}

.shape7 {
  position: absolute;
  z-index: 6;
  width: 100%;
  height: 200px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(56% 0, 100% 0, 100% 47%, 52% 47%);
}

.shape8 {
  position: absolute;
  top: 100px;
  left: -45px;
  z-index: 7;
  width: 100%;
  height: 100px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(32.19% 61.15%, 38.25% 61.15%, 37.3% 90%, 31.26% 90%);
}

.shape9 {
  position: absolute;
  top: 100px;
  left: 25px;
  z-index: 8;
  width: 100%;
  height: 100px;
  background-color: #00001a;
  opacity: 0.5;
  clip-path: polygon(32.19% 61.15%, 38.25% 61.15%, 37.3% 90%, 31.26% 90%);
}

shape8 1

 shape 2

shape 3

shape 4

shape5

shape6

shape 7

              shape8

              shape9

Body:
The path cut of everything positioned out of the shape you draw. The text is still in the top left corner of div but cut off.

I guess there are more solutions.

I would use one more tag to wrap the text into. Than I would position it to the place I need via position:absolute;.

There is possibly more proper way to do it - change size of div to the size of shape you want and than draw the path in that container. Move it via position absolute. Text would still be in the top left corner, but easily moved by in wrapper div.

.shapeContainer {
    position: relative;
  }

 .shape5 {
    position: absolute;
    z-index: 4;
    width: 100%;
    height: 255px;
    background-color: red;
    clip-path: polygon(0 0, 25% 0, 18% 92%, 0 92%);
  }
 .textInShape{
    position: absolute;
    left: 5%;
    top: 20px;
    color: aliceblue;
}

.shape7 {
    position: absolute;
    left: 20%;
    z-index: 6;
    width: 50%;
    height: 100px;
    background-color: blue;
    opacity: 0.5;
    clip-path: polygon(0 0, 100% 0, 100% 82%, 44% 82%); /*changed size of div and path*/
  }
   .textInShape2 {
      position: absolute;
      color: aliceblue;
      width:100%;
      height: 100%;
      text-align: center;
/*if you dont mind exact position, u can also align the text to middle in this case*/
  }

<header class="header">
      <div class="container">
        <div class="shapeContainer">

          <div href="#" class="shape5">
            <div class="textInShape">shape5</div>
           </div>
          <div class="shape7">
            <a href="#" class="textInShape2">HALLOOO</a>
          </div>
        </div>
      </div>
    </header>


问:
HTML CSS filling the empty space after style:display = none are clicked
I am currently working on the HTML and CSS part of the website
The question is that when I click the Classic and Premium and Fresh part I must hide all other
For example, if I click classic then premium and fresh are hidden and vice versa for all other.
I was able to show classic when I click. However, problem is that the space are not filling I will post the code and the picture of the case

```<code><%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<title>Menu or Content Type</title>

<style>

</style>

</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container" id="top">
    <h1>${fn:toUpperCase(content)}</h1>
    <hr>
    <c:choose>
        <c:when test="${content == 'menu'}">
        <h3>
            <span onclick="showAll('all')">Show All</span> | <span onclick="showCategory('c', 'pr', 'fr')">Classic</span> |
            <span onclick="showCategory('pr', 'c', 'fr')">Premium</span> | <span onclick="showCategory('fr', 'c', 'pr')"> Fresh</span>
        </h3>
        </c:when>
        <c:otherwise>
        <h2>Fast-Sub</h2>
        </c:otherwise>
    </c:choose>
</div>

<div class="container" id="middle">
    <!-- Meat Board -->
        <div class="row mt-5 mb-5">
            <c:forEach items="${mList}" var="mList" varStatus="status">
                <div class="col-lg-4 mb-4">
                <div class="card-horder">
                    <div class="card ${mList.category}">
                      <img src="images/tuna.png" class="card-img-top" height="250px">
                      <div class="card-body">
                        <p class="card-text">${mList.meat} ${mList.category}</p>
                      </div>
                      <br><br>
                    </div>
                </div>
                </div>
            </c:forEach>
        </div>
    <!-- Meat Board End -->
</div>

<script>

function display(menuCard){
    for (var i = 0; i < menuCard.length; i++){
        menuCard[i].style.display = "block";
    }
}

function hide(menuCard){
    for (var i = 0; i < menuCard.length; i++){
        menuCard[i].style.display = "none";
    }
}

function showAll(category){
    var cardC = document.getElementsByClassName("card c");
    var cardPr = document.getElementsByClassName("card pr");
    var cardFr = document.getElementsByClassName("card fr");

    var arrCard = [cardC, cardPr, cardFr];

    for(var i = 0; i < 3; i++){
        display(arrCard[i]);
    }
}

function showCategory(category, otherC1, otherC2){
    var menuCard = document.getElementsByClassName("card "+category);
    var other = document.getElementsByClassName("card "+otherC1);
    var other2 = document.getElementsByClassName("card "+otherC2);

    display(menuCard);
    hide(other);
    hide(other2);

}

</script>

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

and when I click Fresh

space are not filling up

答: You are hiding div with class card. You need to hide div with class "col-lg-4" for filling up space.</p>

Body:
I am currently working on the HTML and CSS part of the website
The question is that when I click the Classic and Premium and Fresh part I must hide all other
For example, if I click classic then premium and fresh are hidden and vice versa for all other.
I was able to show classic when I click. However, problem is that the space are not filling I will post the code and the picture of the case

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<title>Menu or Content Type</title>

${fn:toUpperCase(content)}

    <c:choose>
        <c:when test="${content == 'menu'}">

            Show All | Classic |
            Premium |  Fresh

        </c:when>
        <c:otherwise>

Fast-Sub

        </c:otherwise>
    </c:choose>

            <c:forEach items="${mList}" var="mList" varStatus="status">

${mList.meat} ${mList.category}

            </c:forEach>

and when I click Fresh

space are not filling up


问:
Shortcut to turn a ONE element dict into ONE tuple in Python
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

```<code>k,v=unpack_this({'unknown_key':'some value'})
</code>```

* does not work here.

I have come up with these that work:

```<code>k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not
</code>```

Or:

```<code>k,v=(next(((k,v) for k,v in di.items())))
</code>```

Or even:

```<code>k,v=next(zip(di.keys(), di.values()))
</code>```

Finally, the best I can come up with:

```<code>k,v=list(di.items())[0]      # probably the best...
</code>```

Which can be wrapped into a function if I want a length check:

```<code>def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')
</code>```

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

答:
@chepner has the right approach with .popitem():

```<code>>>> d = {'a': 1}
>>> d.popitem()
('a', 1)        # d is now {}
</code>```

This will return the pair associated with the last key added, with no error error if the dict has multiple keys. It will also destroy d.

You can keep d intact by using this idiom to create a new dict and pop off the last item from the new dict created with {**d}:

```<code>>>> {**d}.popitem()
('a', 1)
>>> d
{'a': 1}
</code>```

As far as a 1 line unpackable tuple that throws an error if the dict has more than one item, you can use a Python conditional expression with an alternate that throws the error desired:

```<code># success: k=='a' and v==1
>>> d={'a':1}
>>> k,v={**d}.popitem() if len(d)==1 else 'wrong number of values'

# len(d)!=1 - pass a string to k,v which is too long
>>> d={'a':1,'b':2}
>>> k,v={**d}.popitem() if len(d)==1 else 'wrong number of values'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

If you object to different types being passed, you could do:

```<code>>>> k,v={**d}.popitem() if len(d)==1 else {}.fromkeys('too many keys').items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
</code>```

Body:
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

k,v=unpack_this({'unknown_key':'some value'})

* does not work here.

I have come up with these that work:

k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not

Or:

k,v=(next(((k,v) for k,v in di.items())))

Or even:

k,v=next(zip(di.keys(), di.values()))

Finally, the best I can come up with:

k,v=list(di.items())[0]      # probably the best...

Which can be wrapped into a function if I want a length check:

def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

Body:
@chepner has the right approach with .popitem():

>>> d = {'a': 1}
>>> d.popitem()
('a', 1)        # d is now {}

This will return the pair associated with the last key added, with no error error if the dict has multiple keys. It will also destroy d.

You can keep d intact by using this idiom to create a new dict and pop off the last item from the new dict created with {**d}:

>>> {**d}.popitem()
('a', 1)
>>> d
{'a': 1}

As far as a 1 line unpackable tuple that throws an error if the dict has more than one item, you can use a Python conditional expression with an alternate that throws the error desired:

# success: k=='a' and v==1
>>> d={'a':1}
>>> k,v={**d}.popitem() if len(d)==1 else 'wrong number of values'

# len(d)!=1 - pass a string to k,v which is too long
>>> d={'a':1,'b':2}
>>> k,v={**d}.popitem() if len(d)==1 else 'wrong number of values'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

If you object to different types being passed, you could do:

>>> k,v={**d}.popitem() if len(d)==1 else {}.fromkeys('too many keys').items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)


问:
Jquery data tables need to show only selected rows from an integer array of IDs
I have a drop down with checkboxes in it. When I select multiple items, I have a method which gets those IDs in an integer array. In my data table one of the column, lets say 'User_ID:name' has those IDs. I want to loop through the data table and show only rows of selected IDs in the integer array. If array is empty, no rows should be visible.

I wrote a method, but it's only showing me only 1 row and it keeps overwriting that row when looping through.

```<code>var Gridupdate = function () {
    int[] checked = Checkbox.getCheckedIds(); /// integer array of selectedIDs from a checkbox
    if (dtable) {
        for (i = 0; i < checked.length; i++) {
            dtable.column("User_ID:name").search(checked[i].toString()).draw();
        }
    }
}
</code>```

答:
You can use regex in "DataTables" to achieve this. Add this to your "DataTables' initialisation options".

```<code>"search": {
    "regex": true, // enables the table to be filtered using regular expresion
    "smart": false // disables the table's "smart search" ability. Ensures a more accurate search.
}
</code>```

Example:

```<code>$('#example').DataTable( {
    "search": {
        "regex": true,
        "smart": false
    }
});
</code>```

And change your method to this

```<code>var Gridupdate = function () {
    var checked = Checkbox.getCheckedIds(); /// integer array of selectedIDs from a checkbox
    if (dtable) {
        dtable.column("User_ID:name").search(checked.join('|')).draw(); // eg .search(1|2|4)
    }
};
</code>```

Body:
I have a drop down with checkboxes in it. When I select multiple items, I have a method which gets those IDs in an integer array. In my data table one of the column, lets say 'User_ID:name' has those IDs. I want to loop through the data table and show only rows of selected IDs in the integer array. If array is empty, no rows should be visible.

I wrote a method, but it's only showing me only 1 row and it keeps overwriting that row when looping through.

var Gridupdate = function () {
    int[] checked = Checkbox.getCheckedIds(); /// integer array of selectedIDs from a checkbox
    if (dtable) {
        for (i = 0; i < checked.length; i++) {
            dtable.column("User_ID:name").search(checked[i].toString()).draw();
        }
    }
}

Body:
You can use regex in "DataTables" to achieve this. Add this to your "DataTables' initialisation options".

"search": {
    "regex": true, // enables the table to be filtered using regular expresion
    "smart": false // disables the table's "smart search" ability. Ensures a more accurate search.
}

Example:

$('#example').DataTable( {
    "search": {
        "regex": true,
        "smart": false
    }
});

And change your method to this

var Gridupdate = function () {
    var checked = Checkbox.getCheckedIds(); /// integer array of selectedIDs from a checkbox
    if (dtable) {
        dtable.column("User_ID:name").search(checked.join('|')).draw(); // eg .search(1|2|4)
    }
};


问:
How do I share user controls between web applications in ASP.NET?
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

```
Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3
```

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

答:
One option is to try "Add existing" and in the dialog that appears, the OK button has a drop arrow next to it, change it to Add with a link.

If that doesn't work, rewrite your controls as Custom Controls.

It will take a little while, but will make it much more maintainable in the future.

OwnerDisplayName: Jan Aagaard

Body:
This question is a follow up to my question about sharing resources between web applications, because I have not yet found a good solution.

I have a web application with user controls and resources that are shared by three other web applications.

Solution
|
+-CommonControlsWebApp
| +- resources
| |  +- images
| |  +- scripts
| |  +- stylesheets
| +- UserControls
|
+-WebApp1
|
+-WebApp2
|
+-WebApp3

This is what I know this far:

I can not compile CommonControlsWebApp into a single dll since I am creating user controls. This is only possible with custom server controls, where everything is in the code-behind file. So I need a way to share the ascx files between the four projects.

Copying the files from CommonControlsWebApp into the three other projects does not update their files in the solution explorer. I would have to 'add exting items' all in all three WebApps when a file is added or renamed in CommonControls.

Changing to the Web Site model would remedy this, but I am worried about the compile time for WebApp1-3 if I do this.

'Add as link' does not work for directories.

I could use Subversion to share the files between the projects, but i believe that this would require me to check the files in and out again all the time if I am developing a user control that I have to test through one of the WebApps.

Can it really be true that ASP.NET does not have a good solution for this? How are you guys organizing large web applications?

Edit: Thanks a lot for all the answers. I am going to copy my user controls with a build event for now, and then see if we have time to refactor them into server controls.

LastEditorDisplayName: Jan Aagaard

OwnerDisplayName: ck


问:
Java schedule a job to run at certain time for maximum period of time
I'm trying to schedule a task that should run every 10 seconds. However this task should have a dynamical allowed period execution time. In other words, if the max allowed time is 5 seconds and if the task runs for more than 5 secs it should be killed/shutdown.

I have tried to use @Schedule with a cron time but no matter what I try I can't kill once it is running.  However, an advice was given to me to not use the @Schedule and create a normal task with a ScheduledExecutorService but I have no idea how to do it.

My original method looks like that:

```<code>    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void testMethod(Integer period) {
        ThreadPoolTaskScheduler scheduler;

        scheduler.setAwaitTerminationSeconds(period);
        scheduler.setWaitForTasksToCompleteOnShutdown(false);

        importantMethod();

    }
</code>```

I have tried to rewrite it like so:

```<code>public void testMethod(){
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  scheduler.scheduleAtFixedRate(importantMethod(), delay,
                                  period, TimeUnit.SECONDS);
}
</code>```

However, I'm not sure how to set it up to have no delay to run every 10 seconds or every 5 mins and to only shut it down after the maximum allowed time is exceeded.

Any help will be greatly appreciated.

答:
As per the description, my assumptions:

Task should run every 10 seconds

Task should have maximum time-out of 5 seconds

Max time-out should be configurable

configuration in application.properties

```<code>scheduler.timeout = 5000
</code>```

Code

```<code>
    @Value("${scheduler.timeout}")
    private Long timeout;

    @Scheduled(cron = "0/10 * * * * ?")
    public void taskScheduler() {
        System.out.println("Task Started: " + LocalDateTime.now());
        this.executeTask((Callable<Object>) () -> {
            TimeUnit.MILLISECONDS.sleep(3000);//Change values for testing: sleep time
            System.out.println("Task Worked: " + LocalDateTime.now());
            return true;
        }, timeout);
    }

    ExecutorService service = Executors.newFixedThreadPool(1);
    ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();

    public <T> Future<T> executeTask(Callable<T> c, long timeoutMS) {
        final Future<T> future = service.submit(c);
        canceller.schedule(() -> {
            if (!future.isDone())
                System.out.println("Task Cancelled: " + LocalDateTime.now());
            future.cancel(true);
            return "done";
        }, timeoutMS, TimeUnit.MILLISECONDS);
        return future;
    }

</code>```

Output

When task completed in 3 seconds (sleep time)

```<code>Task Started: 2022-02-06T22:42:30.010704200
Task Worked: 2022-02-06T22:42:33.014775100
</code>```

When task completes in 6 seconds (sleep time)

```<code>Task Started: 2022-02-06T22:47:30.003249500
Task Cancelled: 2022-02-06T22:47:35.013195900
</code>```

Body:
I'm trying to schedule a task that should run every 10 seconds. However this task should have a dynamical allowed period execution time. In other words, if the max allowed time is 5 seconds and if the task runs for more than 5 secs it should be killed/shutdown.

I have tried to use @Schedule with a cron time but no matter what I try I can't kill once it is running.  However, an advice was given to me to not use the @Schedule and create a normal task with a ScheduledExecutorService but I have no idea how to do it.

My original method looks like that:

    @Scheduled(cron = "0/10 * * * * ?")
    @Transactional
    public void testMethod(Integer period) {
        ThreadPoolTaskScheduler scheduler;

        scheduler.setAwaitTerminationSeconds(period);
        scheduler.setWaitForTasksToCompleteOnShutdown(false);

        importantMethod();

    }

I have tried to rewrite it like so:

public void testMethod(){
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  scheduler.scheduleAtFixedRate(importantMethod(), delay,
                                  period, TimeUnit.SECONDS);
}

However, I'm not sure how to set it up to have no delay to run every 10 seconds or every 5 mins and to only shut it down after the maximum allowed time is exceeded.

Any help will be greatly appreciated.

Body:
As per the description, my assumptions:

Task should run every 10 seconds

Task should have maximum time-out of 5 seconds

Max time-out should be configurable

configuration in application.properties

scheduler.timeout = 5000

Code

    @Value("${scheduler.timeout}")
    private Long timeout;

    @Scheduled(cron = "0/10 * * * * ?")
    public void taskScheduler() {
        System.out.println("Task Started: " + LocalDateTime.now());
        this.executeTask((Callable<Object>) () -> {
            TimeUnit.MILLISECONDS.sleep(3000);//Change values for testing: sleep time
            System.out.println("Task Worked: " + LocalDateTime.now());
            return true;
        }, timeout);
    }

    ExecutorService service = Executors.newFixedThreadPool(1);
    ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();

    public <T> Future<T> executeTask(Callable<T> c, long timeoutMS) {
        final Future<T> future = service.submit(c);
        canceller.schedule(() -> {
            if (!future.isDone())
                System.out.println("Task Cancelled: " + LocalDateTime.now());
            future.cancel(true);
            return "done";
        }, timeoutMS, TimeUnit.MILLISECONDS);
        return future;
    }

Output

When task completed in 3 seconds (sleep time)

Task Started: 2022-02-06T22:42:30.010704200
Task Worked: 2022-02-06T22:42:33.014775100

When task completes in 6 seconds (sleep time)

Task Started: 2022-02-06T22:47:30.003249500
Task Cancelled: 2022-02-06T22:47:35.013195900