问:
PHP loop: How can I repeat this loop after it happend once
So I have this loop

```<code>         {% if employees %}
             {% set count = 1 %}
                 {% set multiplier = 1 %}
                    {% for employeeIndex, employee in employees %}
                         <tr>
                            <td>{{ employee.werknemers }}</td>
                            {% for workdayIndex, workday in workdays %}
                                {% if (employeeIndex * multiplier) ==  workdayIndex %}
                                 <td>x</td>
                                 {% if count == (employees|length) %}
                                    {% set multiplier = multiplier * employees|length %}
                                    {% set count = count + 1 %}
                                 {% endif %}
                                {% else %}
                                    <td></td>
                                {% endif %}
                          {% endfor %}
                         </tr>
                    {% endfor %}
                {% endif %}
</code>```

The result is this :

What I want too happen is for the loop too repeat it self after every employee has a date assigned to them. As u can see the first X begins at 3 and goes down too 13. What I want is the X to begin from 14 again and go down the same way. This should be possible in Twig I believe. Thanks for helping out!!

答:
I did not test this because I can't right now test twig but I think this should work</p>

```<code>{% if employees %}
    {% set employeeCount = (employees|length) %}
    {% for employeeIndex, employee in employees %}
        <tr>
            <td>{{ employee.werknemers }}</td>
            {% for workdayIndex, workday in workdays %}
                {% if (workdayIndex - employeeIndex) is divisible by (employeeCount) %}
                    <td>x</td>
                {% else %}
                    <td></td>
                {% endif %}
            {% endfor %}
        </tr>
    {% endfor %}
{% endif %}
</code>```

Body:
So I have this loop

         {% if employees %}
             {% set count = 1 %}
                 {% set multiplier = 1 %}
                    {% for employeeIndex, employee in employees %}

                            {{ employee.werknemers }}
                            {% for workdayIndex, workday in workdays %}
                                {% if (employeeIndex * multiplier) ==  workdayIndex %}
                                 x
                                 {% if count == (employees|length) %}
                                    {% set multiplier = multiplier * employees|length %}
                                    {% set count = count + 1 %}
                                 {% endif %}
                                {% else %}

                                {% endif %}
                          {% endfor %}

                    {% endfor %}
                {% endif %}

The result is this :

What I want too happen is for the loop too repeat it self after every employee has a date assigned to them. As u can see the first X begins at 3 and goes down too 13. What I want is the X to begin from 14 again and go down the same way. This should be possible in Twig I believe. Thanks for helping out!!

Body:
I did not test this because I can't right now test twig but I think this should work

{% if employees %}
    {% set employeeCount = (employees|length) %}
    {% for employeeIndex, employee in employees %}
        <tr>
            <td>{{ employee.werknemers }}</td>
            {% for workdayIndex, workday in workdays %}
                {% if (workdayIndex - employeeIndex) is divisible by (employeeCount) %}
                    <td>x</td>
                {% else %}
                    <td></td>
                {% endif %}
            {% endfor %}
        </tr>
    {% endfor %}
{% endif %}


来源: stackexchange

问:
Move minus sign from right to left?
I have a number '24.45-' and wanted to move the minus sign from right to left like '-24.45' in Python.I am dealing with huge data in data frame and trying to do this using regex so that I can apply on the whole column. Tried this but with no luck, any suggestions please.

```<code>print(re.sub(r"([0-9.]+)((\W$))","\2\1","24.45-"))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Move minus sign from right to left?

Body:
I have a number '24.45-' and wanted to move the minus sign from right to left like '-24.45' in Python.I am dealing with huge data in data frame and trying to do this using regex so that I can apply on the whole column. Tried this but with no luck, any suggestions please.

print(re.sub(r"([0-9.]+)((\W$))","\2\1","24.45-"))

Body:
You can always do something like this:

>>> n = '24.45-'
>>> n = n[-1] + n[:-1]
>>> n
'-24.45'
>>>


问:
Tensorflow Extra None dimension required for model
here is my model:

```<code>model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(40, 40, 3)),
  tf.keras.layers.Dense(150, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])
</code>```

and my input tensor is called image_batch . when I run np.shape(image_batch[0]), the result is TensorShape([40, 40, 3]). This is expected behavior, as each training example is 40x40x3 its an rgb image).
However when running the command predictions = model(image_batch[0]).numpy() in order to get the predictions of the model, I get the error:

```<code>WARNING:tensorflow:Model was constructed with shape Tensor("flatten_1_input:0", shape=(None, 40, 40, 3), dtype=float32) for input (None, 40, 40, 3), but it was re-called on a Tensor with incompatible shape (40, 40, 3).
</code>```

So my question is why does the keras model expect a shape with an extra "None" dimension, and how do I provide it to the model?

答:
The None dimension is the batch dimension. In other words, the input should have the shape (batch_size, height, width, num_channels).

If you want to predict on one input, change model(image_batch[0]).numpy() to model(image_batch[0:1]).numpy(). This will maintain the first dimension. The shape will be (1, 40, 40, 3) in this case.

Body:
here is my model:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(40, 40, 3)),
  tf.keras.layers.Dense(150, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])

and my input tensor is called image_batch . when I run np.shape(image_batch[0]), the result is TensorShape([40, 40, 3]). This is expected behavior, as each training example is 40x40x3 its an rgb image).
However when running the command predictions = model(image_batch[0]).numpy() in order to get the predictions of the model, I get the error:

WARNING:tensorflow:Model was constructed with shape Tensor("flatten_1_input:0", shape=(None, 40, 40, 3), dtype=float32) for input (None, 40, 40, 3), but it was re-called on a Tensor with incompatible shape (40, 40, 3).

So my question is why does the keras model expect a shape with an extra "None" dimension, and how do I provide it to the model?


问:
Trying to use Chrome API topSites
I am currently trying to get the list of top visited sites using the Chrome API, topSites. With the code below in my background page I am getting no luck so far, with the error code Cannot read property 'get' of undefined. For reference, I already have the API listed in my manifest.json under permissions.

background.js

chrome.topSites.get((arr) => {
  console.log(arr);
});
```

答: Found the solution for my problem, I did not update the extension package to use the chrome API topSites. I had to press load unpacked and update.

Title: Trying to use Chrome API topSites


问:
How can I put multi configmap in the same mount path in kubernetes?
I have two python files, testing_1.py and testing_2.py.
Then, I have created the configmap with testing-config1 to store testing_1.py and testing-config2 to store testing_2.py respectively.

In Kubernetes yaml,

```<code>...
      containers:
      - name: spark-master
        image: bde2020/spark-master:2.4.4-hadoop2.7
        volumeMounts:
        - name: testing
          mountPath: /jobs
        - name: testing2
          mountPath: /jobs
      volumes:
        - name: testing
          configMap:
            name: testing-config1
        - name: testing2
          configMap:
            name: testing-config2
...
</code>```

In the final result, the path only contains testing_1.py.

答:
You can put both files in the same ConfigMap.

Or, use a projected volume:

A projected volume maps several existing volume sources into the same
  directory.

Currently, the following types of volume sources can be projected:

secret

downwardAPI

configMap

serviceAccountToken

Body:
I have two python files, testing_1.py and testing_2.py.
Then, I have created the configmap with testing-config1 to store testing_1.py and testing-config2 to store testing_2.py respectively.

In Kubernetes yaml,

...
      containers:
      - name: spark-master
        image: bde2020/spark-master:2.4.4-hadoop2.7
        volumeMounts:
        - name: testing
          mountPath: /jobs
        - name: testing2
          mountPath: /jobs
      volumes:
        - name: testing
          configMap:
            name: testing-config1
        - name: testing2
          configMap:
            name: testing-config2
...

In the final result, the path only contains testing_1.py.


问:
Change font of tkinter menu
I've been struggling to change the font of the 'File' button in the menu class below.

The self.config(font=self.font) doesn't work nor does add_cascade(font=self.font)

I'm using Windows 10.

Any help much appreciated!

```<code>from tkinter import *
import sys

class DatabaseMenu(Menu):
    """Menu for configuring database"""

    def __init__(self, parent, callbacks, **kwargs):
        super().__init__(parent)
        self.callbacks = callbacks
        self.font = ("Calibri", 15)
        self.config(font=self.font)
        self._build_menu()

    def _build_menu(self):

        self.file_menu = Menu(self, tearoff=False)
        self.file_menu.add_command(
            label="Change database structure",
            command=self.callbacks['file->change_database_structure'],
            font=self.font
            )

        self.add_cascade(label=' File ', menu=self.file_menu, font=self.font)

if __name__ == '__main__':
    root = Tk()
    menu = DatabaseMenu(root, {'file->change_database_structure':sys.exit})
    root.config(menu=menu)
    root.mainloop()
</code>```

答: You cannot change the font of the menubar or its menus with tkinter. Those menus are rendered by the underlying OS rather than being rendered by tkinter.</p>

Title: Change font of tkinter menu

Body:
I've been struggling to change the font of the 'File' button in the menu class below.

The self.config(font=self.font) doesn't work nor does add_cascade(font=self.font)

I'm using Windows 10.

Any help much appreciated!

from tkinter import *
import sys

class DatabaseMenu(Menu):
    """Menu for configuring database"""

    def __init__(self, parent, callbacks, **kwargs):
        super().__init__(parent)
        self.callbacks = callbacks
        self.font = ("Calibri", 15)
        self.config(font=self.font)
        self._build_menu()

    def _build_menu(self):

        self.file_menu = Menu(self, tearoff=False)
        self.file_menu.add_command(
            label="Change database structure",
            command=self.callbacks['file->change_database_structure'],
            font=self.font
            )

        self.add_cascade(label=' File ', menu=self.file_menu, font=self.font)

if __name__ == '__main__':
    root = Tk()
    menu = DatabaseMenu(root, {'file->change_database_structure':sys.exit})
    root.config(menu=menu)
    root.mainloop()


问:
vpn ibm-cloud Cannot get to private addresses via VPN
Apparently Softlayer changed the VPN. So I've reinstalled my MotionPro client on Win10 and can now connect. But I can no longer connect to the 10 addresses beyond it. They don't show up in the netstat -rn listing.

I can ping the remote end of the VPN, but not the 10 addresses. What else do I need to do to make this happen?

Thanks.

答: No worries. It turned out the VPN entry point has changed, and when I use a different one it now gives me all the correct routing.</p>


问:
Angular 8 SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse httpPost
Iam trying to send form Data from my Service to the Server but i get an error Respons everytime also the File is Uploaded Properly: How can i avoid the error msg

Upload.Service.ts:

```<code>  uploadFile(id: number) {
    let success = false;
    const headers = new HttpHeaders({
      'Authorization' : ' Bearer ' + this.authService.authToken()
    });
    const options = {
      headers: headers
    };
    const formData: FormData = new FormData();
    formData.append('file', this.files[id]);
    this.http.post(URL, formData, options).toPromise().then(res => {
        console.log(res);
        success = true;
    }).catch(err => {
        console.log(err);
        success = false;
     });
     return success;
 }
</code>```

Error:

```<code>HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/upload", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:5000/api/upload"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:5000/api/upload"
error:
error: SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19729:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6246:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:81825:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6245:60) at Zone.runTask (http://localhost:4200/polyfills.js:6023:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6320:34) at invokeTask (http://localhost:4200/polyfills.js:7458:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:7495:21)
text: "BlaBla - Kopie.sds"
__proto__: Object
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object
</code>```

Can somebody Help with that please ?

答:
I believe that normally Angular will know have to handle FormData, and accept the right responseType if the server returns a JSON.

I would suggest you to create an interceptor to append the Authentication Header and not override the headers with the options as in your case.

@ryanchenkie|angular-authentication-using-the-http-client-and-http-interceptors

Body:
Iam trying to send form Data from my Service to the Server but i get an error Respons everytime also the File is Uploaded Properly: How can i avoid the error msg

Upload.Service.ts:

  uploadFile(id: number) {
    let success = false;
    const headers = new HttpHeaders({
      'Authorization' : ' Bearer ' + this.authService.authToken()
    });
    const options = {
      headers: headers
    };
    const formData: FormData = new FormData();
    formData.append('file', this.files[id]);
    this.http.post(URL, formData, options).toPromise().then(res => {
        console.log(res);
        success = true;
    }).catch(err => {
        console.log(err);
        success = false;
     });
     return success;
 }

Error:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/upload", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:5000/api/upload"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:5000/api/upload"
error:
error: SyntaxError: Unexpected token B in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19729:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6246:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:81825:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:6245:60) at Zone.runTask (http://localhost:4200/polyfills.js:6023:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:6320:34) at invokeTask (http://localhost:4200/polyfills.js:7458:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:7495:21)
text: "BlaBla - Kopie.sds"
__proto__: Object
__proto__: HttpResponseBase
constructor: class HttpErrorResponse
__proto__: Object

Can somebody Help with that please ?


问:
Error: Connection disconnected with error 'Error: Server returned an error on close: Connection closed with an error.'
I get this below error message on Blazor server app when I try to send images over 50KB

Error: Connection disconnected with error 'Error: Server returned an error on close: Connection closed with an error.'

I am using a richtext box and when I paste an image on it over 50KB I am getting this error. The error is happening on Blazor.server.js. This issue must be related to the data limit that can be send over web socket however even after I update this limit to larger size, I still see this issue.

This is my startup file code where I have modified the limit.

```<code> app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub(options =>
                {
                    **options.ApplicationMaxBufferSize = 10 * 1024 * 1024;
                    options.TransportMaxBufferSize = 10 * 1024 * 1024;**
                });
                endpoints.MapFallbackToPage("/_Host");
            });
</code>```

The error is happening on blazer.server.js and the connection is getting dropped eachtime it is happening. Has any one faced this issue with Blazor server

答:
I have increased the size for Singal R and that fixed the issue for now but this is not a proper solution.

```<code>services.AddSignalR(e => {
                e.MaximumReceiveMessageSize = 102400000;
            });
</code>```

The proper solution is to implement your own hub between client and server and process in chunks and stick it together.

refer to : https://learn.microsoft.com/en-us/aspnet/core/signalr/streaming?view=aspnetcore-3.1

Body:
I get this below error message on Blazor server app when I try to send images over 50KB

Error: Connection disconnected with error 'Error: Server returned an error on close: Connection closed with an error.'

I am using a richtext box and when I paste an image on it over 50KB I am getting this error. The error is happening on Blazor.server.js. This issue must be related to the data limit that can be send over web socket however even after I update this limit to larger size, I still see this issue.

This is my startup file code where I have modified the limit.

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub(options =>
                {
                    **options.ApplicationMaxBufferSize = 10 * 1024 * 1024;
                    options.TransportMaxBufferSize = 10 * 1024 * 1024;**
                });
                endpoints.MapFallbackToPage("/_Host");
            });

The error is happening on blazer.server.js and the connection is getting dropped eachtime it is happening. Has any one faced this issue with Blazor server

Body:
I have increased the size for Singal R and that fixed the issue for now but this is not a proper solution.

services.AddSignalR(e => {
                e.MaximumReceiveMessageSize = 102400000;
            });

The proper solution is to implement your own hub between client and server and process in chunks and stick it together.

refer to : https://learn.microsoft.com/en-us/aspnet/core/signalr/streaming?view=aspnetcore-3.1


问:
How to use instance-variable or param after a format.js on controller - Rails
I am new in rails and coding in general:

def startoffers
  id = params[:id]
  @id = params[:id]
  @product = Product.find(id)
  if @product.present?
    respond_to do |format|
      format.js {
        render "search/startoffers"
      }
    end
  end
end
```

<p>So, what this does is sending you to a JS that will hide/unhide a part html, and will also have it;s own JS there. My issue is that I can't seem to send a parameter or instance variable to be used there:</p>

<pre class="lang-js prettyprint-override"><code>$("#startoffers").html("<%= escape_javascript(render partial: 'search/startoffers')%>").show();
$("#close-offer").on("click",function(){
  $("#startoffers").hide();
});
$("#oneclick").on("click",function(id){
  var product_id = id;
  window.location.href = "/offers/chat/" + product_id;
});
</code>```

Partial:

 ">Click Here

```

I can't seem to be able to use id correctly. When redirected I'm redirected to:

http://localhost:3000/offers/chat/[object%20Object]

答:
Here is an example to use the instance variable in js.erb view templates

```<code>alert("<%= @product.id %>");
</code>```

It will print the id of the @product in alert box.

Body:
I am new in rails and coding in general:

def startoffers
  id = params[:id]
  @id = params[:id]
  @product = Product.find(id)
  if @product.present?
    respond_to do |format|
      format.js {
        render "search/startoffers"
      }
    end
  end
end

So, what this does is sending you to a JS that will hide/unhide a part html, and will also have it;s own JS there. My issue is that I can't seem to send a parameter or instance variable to be used there:

$("#startoffers").html("<%= escape_javascript(render partial: 'search/startoffers')%>").show();
$("#close-offer").on("click",function(){
  $("#startoffers").hide();
});
$("#oneclick").on("click",function(id){
  var product_id = id;
  window.location.href = "/offers/chat/" + product_id;
});

Partial:

 <a id="oneclick" data-id="<%= @product.id %>">Click Here

I can't seem to be able to use id correctly. When redirected I'm redirected to:

http://localhost:3000/offers/chat/[object%20Object]

Body:
Here is an example to use the instance variable in js.erb view templates

alert("<%= @product.id %>");

It will print the id of the @product in alert box.


问:
Java: check if value is 100 or 200 or 300 or x00
In java, I increase a value in a while statement and I would like to perform an action when this value has specific values (without hardcoding it because it can in theory go to infinite):

100, 200, 300, x00, etc.

I know this has a specific name, but I cannot remember it (Modulo ? But if so, how ?).

答:
The modulo (%) operation computes the remainder of a division operation. When a % b is 0, that means that a is divisible by b. Therefore, you could accomplish your task with an if statement with the condition number % 100 == 0.

You can find more details about arithmetic operators in the oracle java tutorial and the java language specification.


问:
Call a function without using eval?
I have an object attached as data to a DIV. I also have a string that contains the name of a function of that object.

```<code>function callFunction(divId, funcName, data) {
  o = $(divId).data('myObject');
  // how do I call o.funcName(data) ???

// Somewhere else...
callFunction('#myDivId', "myFunction", someData);
</code>```

The divId and funcName are actually coming from a Java applet on the page, which is why they're strings.

答:
Assuming it is a global function:

```<code>window['foo']()
</code>```

is the same as to

```<code>foo()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Call a function without using eval?

Body:
I have an object attached as data to a DIV. I also have a string that contains the name of a function of that object.

function callFunction(divId, funcName, data) {
  o = $(divId).data('myObject');
  // how do I call o.funcName(data) ???

// Somewhere else...
callFunction('#myDivId', "myFunction", someData);

The divId and funcName are actually coming from a Java applet on the page, which is why they're strings.

Body:
Assuming it is a global function:

window['foo']()

is the same as to

foo()


问:
How to get USB controller/gamepad to work with python
I have a USB controller that I'm trying to get inputs from, a Microsoft® SideWinder® Plug & Play Game Pad. I'm having difficulties trying to figure out how to receive its inputs correctly. Unfortunately, I cannot use pygame as it requires a window to receive inputs from, but I have to generate a pyglet window (via PsychoPy) to run my program. With pygame it can connect and show the state of buttons, but it cannot receive inputs without creating a window. I tried looking for other libraries, but all I encountered was Inputs, which isn't compatible with my controller (doesn't detect the device after installing). The controller itself works as I've tested it with an online gamepad tester. PsychoPy's joystick API is currently broken and does not work, so no luck there either.

I was really hoping anyone had advice on how to receive inputs from my controller/gamepad into my program?

答:
For Windows you can use the WINMM.dll directly.

Use the ctypes library to load the dll (see Loading shared libraries). Use ctypes.WINFUNCTYPE to create prototypes for the  function:

joyGetNumDevs

joyGetDevCapsW

joyGetPosEx

import ctypes

winmmdll = ctypes.WinDLL('winmm.dll')

# [joyGetNumDevs](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetnumdevs)
"""
UINT joyGetNumDevs();
"""
joyGetNumDevs_proto = ctypes.WINFUNCTYPE(ctypes.c_uint)
joyGetNumDevs_func  = joyGetNumDevs_proto(("joyGetNumDevs", winmmdll))

# [joyGetDevCaps](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetdevcaps)
"""
MMRESULT joyGetDevCaps(UINT uJoyID, LPJOYCAPS pjc, UINT cbjc);

32 bit: joyGetDevCapsA
64 bit: joyGetDevCapsW

sizeof(JOYCAPS): 728
"""
joyGetDevCaps_proto = ctypes.WINFUNCTYPE(ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint)
joyGetDevCaps_param = (1, "uJoyID", 0), (1, "pjc", None), (1, "cbjc", 0)
joyGetDevCaps_func  = joyGetDevCaps_proto(("joyGetDevCapsW", winmmdll), joyGetDevCaps_param)

# [joyGetPosEx](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetposex)
"""
MMRESULT joyGetPosEx(UINT uJoyID, LPJOYINFOEX pji);
sizeof(JOYINFOEX): 52
"""
joyGetPosEx_proto = ctypes.WINFUNCTYPE(ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p)
joyGetPosEx_param = (1, "uJoyID", 0), (1, "pji", None)
joyGetPosEx_func  = joyGetPosEx_proto(("joyGetPosEx", winmmdll), joyGetPosEx_param)
```
<p>Create the python function <code>joyGetNumDevs</code>, <code>joyGetDevCaps</code> and <code>joyGetPosEx</code> which delegate to the DLL. And create classes for the types <code>JOYCAPS</code> respectively <code>JOYINFOEX</code>:</p>
<pre class="lang-py prettyprint-override"><code># joystickapi - joyGetNumDevs
def joyGetNumDevs():
    try:
        num = joyGetNumDevs_func()
    except:
        num = 0
    return num

# joystickapi - joyGetDevCaps
def joyGetDevCaps(uJoyID):
    try:
        buffer = (ctypes.c_ubyte * JOYCAPS.SIZE_W)()
        p1 = ctypes.c_uint(uJoyID)
        p2 = ctypes.cast(buffer, ctypes.c_void_p)
        p3 = ctypes.c_uint(JOYCAPS.SIZE_W)
        ret_val = joyGetDevCaps_func(p1, p2, p3)
        ret = (False, None) if ret_val != JOYERR_NOERROR else (True, JOYCAPS(buffer))
    except:
        ret = False, None
    return ret

# joystickapi - joyGetPosEx
def joyGetPosEx(uJoyID):
    try:
        buffer = (ctypes.c_uint32 * (JOYINFOEX.SIZE // 4))()
        buffer[0] = JOYINFOEX.SIZE
        buffer[1] = JOY_RETURNALL
        p1 = ctypes.c_uint(uJoyID)
        p2 = ctypes.cast(buffer, ctypes.c_void_p)
        ret_val = joyGetPosEx_func(p1, p2)
        ret = (False, None) if ret_val != JOYERR_NOERROR else (True, JOYINFOEX(buffer))
    except:
        ret = False, None
    return ret

JOYERR_NOERROR = 0
JOY_RETURNX = 0x00000001
JOY_RETURNY = 0x00000002
JOY_RETURNZ = 0x00000004
JOY_RETURNR = 0x00000008
JOY_RETURNU = 0x00000010
JOY_RETURNV = 0x00000020
JOY_RETURNPOV = 0x00000040
JOY_RETURNBUTTONS = 0x00000080
JOY_RETURNRAWDATA = 0x00000100
JOY_RETURNPOVCTS = 0x00000200
JOY_RETURNCENTERED = 0x00000400
JOY_USEDEADZONE = 0x00000800
JOY_RETURNALL = (JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | \
                 JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | \
                 JOY_RETURNPOV | JOY_RETURNBUTTONS)

# joystickapi - JOYCAPS
class JOYCAPS:
    SIZE_W = 728
    OFFSET_V = 4 + 32*2
    def __init__(self, buffer):
        ushort_array = (ctypes.c_uint16 * 2).from_buffer(buffer)
        self.wMid, self.wPid = ushort_array

        wchar_array = (ctypes.c_wchar * 32).from_buffer(buffer, 4)
        self.szPname = ctypes.cast(wchar_array, ctypes.c_wchar_p).value

        uint_array = (ctypes.c_uint32 * 19).from_buffer(buffer, JOYCAPS.OFFSET_V)
        self.wXmin, self.wXmax, self.wYmin, self.wYmax, self.wZmin, self.wZmax, \
        self.wNumButtons, self.wPeriodMin, self.wPeriodMax, \
        self.wRmin, self.wRmax, self.wUmin, self.wUmax, self.wVmin, self.wVmax, \
        self.wCaps, self.wMaxAxes, self.wNumAxes, self.wMaxButtons = uint_array

# joystickapi - JOYINFOEX
class JOYINFOEX:
  SIZE = 52
  def __init__(self, buffer):
      uint_array = (ctypes.c_uint32 * (JOYINFOEX.SIZE // 4)).from_buffer(buffer)
      self.dwSize, self.dwFlags, \
      self.dwXpos, self.dwYpos, self.dwZpos, self.dwRpos, self.dwUpos, self.dwVpos, \
      self.dwButtons, self.dwButtonNumber, self.dwPOV, self.dwReserved1, self.dwReserved2 = uint_array
</code>```

See the simple example to test the API:

import joystickapi
import msvcrt
import time

print("start")

num = joystickapi.joyGetNumDevs()
ret, caps, startinfo = False, None, None
for id in range(num):
    ret, caps = joystickapi.joyGetDevCaps(id)
    if ret:
        print("gamepad detected: " + caps.szPname)
        ret, startinfo = joystickapi.joyGetPosEx(id)
        break
else:
    print("no gamepad detected")

run = ret
while run:
    time.sleep(0.1)
    if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode(): # detect ESC
        run = False

    ret, info = joystickapi.joyGetPosEx(id)
    if ret:
        btns = [(1 < 10 for v in axisXYZ]):
            print("axis:", axisXYZ)
        if any([abs(v) > 10 for v in axisRUV]):
            print("roation axis:", axisRUV)

print("end")
```

The api binding and example is provided in the GitHub repository python_windows_joystickapi

Body:
For Windows you can use the WINMM.dll directly.

Use the ctypes library to load the dll (see Loading shared libraries). Use ctypes.WINFUNCTYPE to create prototypes for the  function:

joyGetNumDevs

joyGetDevCapsW

joyGetPosEx

import ctypes

winmmdll = ctypes.WinDLL('winmm.dll')

# [joyGetNumDevs](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetnumdevs)
"""
UINT joyGetNumDevs();
"""
joyGetNumDevs_proto = ctypes.WINFUNCTYPE(ctypes.c_uint)
joyGetNumDevs_func  = joyGetNumDevs_proto(("joyGetNumDevs", winmmdll))

# [joyGetDevCaps](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetdevcaps)
"""
MMRESULT joyGetDevCaps(UINT uJoyID, LPJOYCAPS pjc, UINT cbjc);

32 bit: joyGetDevCapsA
64 bit: joyGetDevCapsW

sizeof(JOYCAPS): 728
"""
joyGetDevCaps_proto = ctypes.WINFUNCTYPE(ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint)
joyGetDevCaps_param = (1, "uJoyID", 0), (1, "pjc", None), (1, "cbjc", 0)
joyGetDevCaps_func  = joyGetDevCaps_proto(("joyGetDevCapsW", winmmdll), joyGetDevCaps_param)

# [joyGetPosEx](https://learn.microsoft.com/en-us/windows/win32/api/joystickapi/nf-joystickapi-joygetposex)
"""
MMRESULT joyGetPosEx(UINT uJoyID, LPJOYINFOEX pji);
sizeof(JOYINFOEX): 52
"""
joyGetPosEx_proto = ctypes.WINFUNCTYPE(ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p)
joyGetPosEx_param = (1, "uJoyID", 0), (1, "pji", None)
joyGetPosEx_func  = joyGetPosEx_proto(("joyGetPosEx", winmmdll), joyGetPosEx_param)

Create the python function joyGetNumDevs, joyGetDevCaps and joyGetPosEx which delegate to the DLL. And create classes for the types JOYCAPS respectively JOYINFOEX:

# joystickapi - joyGetNumDevs
def joyGetNumDevs():
    try:
        num = joyGetNumDevs_func()
    except:
        num = 0
    return num

# joystickapi - joyGetDevCaps
def joyGetDevCaps(uJoyID):
    try:
        buffer = (ctypes.c_ubyte * JOYCAPS.SIZE_W)()
        p1 = ctypes.c_uint(uJoyID)
        p2 = ctypes.cast(buffer, ctypes.c_void_p)
        p3 = ctypes.c_uint(JOYCAPS.SIZE_W)
        ret_val = joyGetDevCaps_func(p1, p2, p3)
        ret = (False, None) if ret_val != JOYERR_NOERROR else (True, JOYCAPS(buffer))
    except:
        ret = False, None
    return ret

# joystickapi - joyGetPosEx
def joyGetPosEx(uJoyID):
    try:
        buffer = (ctypes.c_uint32 * (JOYINFOEX.SIZE // 4))()
        buffer[0] = JOYINFOEX.SIZE
        buffer[1] = JOY_RETURNALL
        p1 = ctypes.c_uint(uJoyID)
        p2 = ctypes.cast(buffer, ctypes.c_void_p)
        ret_val = joyGetPosEx_func(p1, p2)
        ret = (False, None) if ret_val != JOYERR_NOERROR else (True, JOYINFOEX(buffer))
    except:
        ret = False, None
    return ret

JOYERR_NOERROR = 0
JOY_RETURNX = 0x00000001
JOY_RETURNY = 0x00000002
JOY_RETURNZ = 0x00000004
JOY_RETURNR = 0x00000008
JOY_RETURNU = 0x00000010
JOY_RETURNV = 0x00000020
JOY_RETURNPOV = 0x00000040
JOY_RETURNBUTTONS = 0x00000080
JOY_RETURNRAWDATA = 0x00000100
JOY_RETURNPOVCTS = 0x00000200
JOY_RETURNCENTERED = 0x00000400
JOY_USEDEADZONE = 0x00000800
JOY_RETURNALL = (JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | \
                 JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | \
                 JOY_RETURNPOV | JOY_RETURNBUTTONS)

# joystickapi - JOYCAPS
class JOYCAPS:
    SIZE_W = 728
    OFFSET_V = 4 + 32*2
    def __init__(self, buffer):
        ushort_array = (ctypes.c_uint16 * 2).from_buffer(buffer)
        self.wMid, self.wPid = ushort_array

        wchar_array = (ctypes.c_wchar * 32).from_buffer(buffer, 4)
        self.szPname = ctypes.cast(wchar_array, ctypes.c_wchar_p).value

        uint_array = (ctypes.c_uint32 * 19).from_buffer(buffer, JOYCAPS.OFFSET_V)
        self.wXmin, self.wXmax, self.wYmin, self.wYmax, self.wZmin, self.wZmax, \
        self.wNumButtons, self.wPeriodMin, self.wPeriodMax, \
        self.wRmin, self.wRmax, self.wUmin, self.wUmax, self.wVmin, self.wVmax, \
        self.wCaps, self.wMaxAxes, self.wNumAxes, self.wMaxButtons = uint_array

# joystickapi - JOYINFOEX
class JOYINFOEX:
  SIZE = 52
  def __init__(self, buffer):
      uint_array = (ctypes.c_uint32 * (JOYINFOEX.SIZE // 4)).from_buffer(buffer)
      self.dwSize, self.dwFlags, \
      self.dwXpos, self.dwYpos, self.dwZpos, self.dwRpos, self.dwUpos, self.dwVpos, \
      self.dwButtons, self.dwButtonNumber, self.dwPOV, self.dwReserved1, self.dwReserved2 = uint_array

See the simple example to test the API:

import joystickapi
import msvcrt
import time

print("start")

num = joystickapi.joyGetNumDevs()
ret, caps, startinfo = False, None, None
for id in range(num):
    ret, caps = joystickapi.joyGetDevCaps(id)
    if ret:
        print("gamepad detected: " + caps.szPname)
        ret, startinfo = joystickapi.joyGetPosEx(id)
        break
else:
    print("no gamepad detected")

run = ret
while run:
    time.sleep(0.1)
    if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode(): # detect ESC
        run = False

    ret, info = joystickapi.joyGetPosEx(id)
    if ret:
        btns = [(1 << i) & info.dwButtons != 0 for i in range(caps.wNumButtons)]
        axisXYZ = [info.dwXpos-startinfo.dwXpos, info.dwYpos-startinfo.dwYpos, info.dwZpos-startinfo.dwZpos]
        axisRUV = [info.dwRpos-startinfo.dwRpos, info.dwUpos-startinfo.dwUpos, info.dwVpos-startinfo.dwVpos]
        if info.dwButtons:
            print("buttons: ", btns)
        if any([abs(v) > 10 for v in axisXYZ]):
            print("axis:", axisXYZ)
        if any([abs(v) > 10 for v in axisRUV]):
            print("roation axis:", axisRUV)

print("end")

The api binding and example is provided in the GitHub repository python_windows_joystickapi


问:
How do I use secret variables with inline powershell scripts
So I have some powershell I'm trying to use to setup a Scheduled Task during an ADO deployment. In order to get the task set to "Run whether user is logged on or not" I am required to create it using a User and Password according to these:

Set a Scheduled Task to run when user isn't logged in

Schedule task creation with option ""Run whether user is logged in or not"" using powershell

https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskprincipal?view=win10-ps

And several others.

So with the security rules of the company all passwords from ADO have to be in secret variables. These do not decrypt when called basically from within the scripts, you'll get null values. According to these, you have to pass them in as Environment Variables and/or Parameters to the script:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=classic%2Cbatch

https://github.com/Microsoft/azure-pipelines-tasks/issues/8345

VSTS: Pass build/release variables into Powershell script task

https://github.com/microsoft/azure-pipelines-agent/issues/145

https://adamtheautomator.com/azure-devops-variables-complete-guide/

Many of these also only show the yaml side, but I'm using classic so this is of no use and I suspect irrelevant based on the next link which then contradicts them saying you can only use parameters on file base scripts and not inline:

https://github.com/MicrosoftDocs/vsts-docs/issues/1083

I have setup an Environment Variable per the MS link on variable usage as part of the ADO step where by i have a name and a value defined as $(mySecret).

I have tried accessing this through various means described in the links above:

$MYSECRET

$env:MYSECRET

$($MYSECRET)

$($env:MYSECRET)

$(MYSECRET)

$(env:MYSECRET)

(All of the following with both Param and param)

param([string]$mySecret)

param($mySecret)

param($MYSECRET)

param($env:mySecret)

param($env:MYSECRET)

All of these return a "Param is not a recognized function" which according to these, is usually due to param not being the first word in the script, which is not the case for me, I have already checked, double checked, pulled out the text to notepad, notepad++ (both just in case) and compared, and verified it is really the very first word in the script:

PowerShell 2.0 and "The term 'Param' is not recognized as the name of a cmdlet, function, script file, or operable program"

PowerShell parameters - "The term 'param' is not recognized as the name of a cmdlet"

powershell unable to recognize parameter

I've even tried to copy and paste some of the Param solutions suggested above, even from the ADO git, and they all fail for this. I believe because of the git issue 1083 linked above.

None of the suggestions or answers from any of the links I've posted have worked.

One of the other links I came across had a suggestion to create up to three other deployment steps for creating variables, pulling them from the ADO environment, executing direct decryption and assignment. Completely over the top for what I believe should be required here. Another suggestion was to create an extra step to create a temp function to pull the secret and parse it with substring with a couple of different start and end values and to piece those back together as apparently the substring function could see beyond the encryption. Even if that did work, that is ridiculous. As such I haven't tried these last 2 suggestions. If that's really the case I would like someone to point me to the git docs stating as such or there needs to be a bug written up on it.

I'm simply at a loss. I just need to access a secret variable in an inline powershell script for a single task during and ADO deployment, does anyone know how to achieve this. Note the task creation code below does work when I use plain text inputs for the user and password, but that's against policy so not an option.

Here is my script:

```<code>param($taskPass)

$taskName = $env:ScheduledTaskName
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }

if(!$taskExists) {
     $Trigger = New-ScheduledTaskTrigger -Daily -At 3am
     $Actions = (New-ScheduledTaskAction -Execute "powershell curl -Method POST -Uri $env:VarURL"),
                (New-ScheduledTaskAction -Execute "powershell Invoke-Sqlcmd -ServerInstance $env:Server -Database 'MyDB' -Query 'EXEC NightlyProc'")

    #The following was suggested from here http://duffney.io/Create-ScheduledTasks-SecurePassword
     $SecurePassword = "$taskPass"
     Write-Host "Pass: $SecurePassword"
     $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $env:ScheduledTaskUser, $SecurePassword
     $Password = $Credentials.GetNetworkCredential().Password

     $Task = New-ScheduledTask -Action $Actions -Trigger $Trigger
     $Task | Register-ScheduledTask -TaskName $taskName -User $env:ScheduledTaskUser -Password $Password
}
</code>```

答:
Ok so I finally worked this out. I used the YAML viewer to get a comparison of what the classic interface was creating vs what the MS link said it should be. This involved setting the Environment Variable to the value in the $(mySecret) format (no $env: here just the variable name). Then in the script using the $env:MYSECRET formatting. But also without all of the credential/password manipulation from the duffney.io site. Just setting the -Password parameter for the new Task directly to the $env:MYSECRET variable. No need for params. Task created as 'Run even when user not logged on' just as expected. Final code:

```<code>$taskName = $env:ScheduledTaskName
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }

if(!$taskExists) {
     $Trigger = New-ScheduledTaskTrigger -Daily -At 3am
     $Actions = (New-ScheduledTaskAction -Execute "powershell curl -Method POST -Uri $env:URL"),
 (New-ScheduledTaskAction -Execute "powershell Invoke-Sqlcmd -ServerInstance $env:Server -Database 'MyDB' -Query 'EXEC NightlyCache'")

     $Task = New-ScheduledTask -Action $Actions -Trigger $Trigger
     $Task | Register-ScheduledTask -TaskName $taskName -User $env:ScheduledTaskUser -Password  $env:TASKPASS
}
</code>```

Making sure to set an Environment Variable to the following values:

NOTE: CAPS on the name are not necessary here, seems to just be a standard. I've successfully deployed with both the CAPS version and 'TaskPass'. I say this because several of the links I posted above make it seem like they are.

Name: TASKPASS

Value $(ScheduledTaskPass)

Also of note that MS does it's best to hide this value from you. Even if you set it to a local script variable and try to output the value, as I was trying to do for confirmation purposes, you'll still only get asterisks. But it's really there, I/they promise.

Body:
So I have some powershell I'm trying to use to setup a Scheduled Task during an ADO deployment. In order to get the task set to "Run whether user is logged on or not" I am required to create it using a User and Password according to these:

Set a Scheduled Task to run when user isn't logged in

Schedule task creation with option ""Run whether user is logged in or not"" using powershell

https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskprincipal?view=win10-ps

And several others.

So with the security rules of the company all passwords from ADO have to be in secret variables. These do not decrypt when called basically from within the scripts, you'll get null values. According to these, you have to pass them in as Environment Variables and/or Parameters to the script:

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=classic%2Cbatch

https://github.com/Microsoft/azure-pipelines-tasks/issues/8345

VSTS: Pass build/release variables into Powershell script task

https://github.com/microsoft/azure-pipelines-agent/issues/145

https://adamtheautomator.com/azure-devops-variables-complete-guide/

Many of these also only show the yaml side, but I'm using classic so this is of no use and I suspect irrelevant based on the next link which then contradicts them saying you can only use parameters on file base scripts and not inline:

https://github.com/MicrosoftDocs/vsts-docs/issues/1083

I have setup an Environment Variable per the MS link on variable usage as part of the ADO step where by i have a name and a value defined as $(mySecret).

I have tried accessing this through various means described in the links above:

$MYSECRET

$env:MYSECRET

$($MYSECRET)

$($env:MYSECRET)

$(MYSECRET)

$(env:MYSECRET)

(All of the following with both Param and param)

param([string]$mySecret)

param($mySecret)

param($MYSECRET)

param($env:mySecret)

param($env:MYSECRET)

All of these return a "Param is not a recognized function" which according to these, is usually due to param not being the first word in the script, which is not the case for me, I have already checked, double checked, pulled out the text to notepad, notepad++ (both just in case) and compared, and verified it is really the very first word in the script:

PowerShell 2.0 and "The term 'Param' is not recognized as the name of a cmdlet, function, script file, or operable program"

PowerShell parameters - "The term 'param' is not recognized as the name of a cmdlet"

powershell unable to recognize parameter

I've even tried to copy and paste some of the Param solutions suggested above, even from the ADO git, and they all fail for this. I believe because of the git issue 1083 linked above.

None of the suggestions or answers from any of the links I've posted have worked.

One of the other links I came across had a suggestion to create up to three other deployment steps for creating variables, pulling them from the ADO environment, executing direct decryption and assignment. Completely over the top for what I believe should be required here. Another suggestion was to create an extra step to create a temp function to pull the secret and parse it with substring with a couple of different start and end values and to piece those back together as apparently the substring function could see beyond the encryption. Even if that did work, that is ridiculous. As such I haven't tried these last 2 suggestions. If that's really the case I would like someone to point me to the git docs stating as such or there needs to be a bug written up on it.

I'm simply at a loss. I just need to access a secret variable in an inline powershell script for a single task during and ADO deployment, does anyone know how to achieve this. Note the task creation code below does work when I use plain text inputs for the user and password, but that's against policy so not an option.

Here is my script:

param($taskPass)

$taskName = $env:ScheduledTaskName
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }

if(!$taskExists) {
     $Trigger = New-ScheduledTaskTrigger -Daily -At 3am
     $Actions = (New-ScheduledTaskAction -Execute "powershell curl -Method POST -Uri $env:VarURL"),
                (New-ScheduledTaskAction -Execute "powershell Invoke-Sqlcmd -ServerInstance $env:Server -Database 'MyDB' -Query 'EXEC NightlyProc'")

    #The following was suggested from here http://duffney.io/Create-ScheduledTasks-SecurePassword
     $SecurePassword = "$taskPass"
     Write-Host "Pass: $SecurePassword"
     $Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $env:ScheduledTaskUser, $SecurePassword
     $Password = $Credentials.GetNetworkCredential().Password

     $Task = New-ScheduledTask -Action $Actions -Trigger $Trigger
     $Task | Register-ScheduledTask -TaskName $taskName -User $env:ScheduledTaskUser -Password $Password
}

Body:
Ok so I finally worked this out. I used the YAML viewer to get a comparison of what the classic interface was creating vs what the MS link said it should be. This involved setting the Environment Variable to the value in the $(mySecret) format (no $env: here just the variable name). Then in the script using the $env:MYSECRET formatting. But also without all of the credential/password manipulation from the duffney.io site. Just setting the -Password parameter for the new Task directly to the $env:MYSECRET variable. No need for params. Task created as 'Run even when user not logged on' just as expected. Final code:

$taskName = $env:ScheduledTaskName
$taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName }

if(!$taskExists) {
     $Trigger = New-ScheduledTaskTrigger -Daily -At 3am
     $Actions = (New-ScheduledTaskAction -Execute "powershell curl -Method POST -Uri $env:URL"),
 (New-ScheduledTaskAction -Execute "powershell Invoke-Sqlcmd -ServerInstance $env:Server -Database 'MyDB' -Query 'EXEC NightlyCache'")

     $Task = New-ScheduledTask -Action $Actions -Trigger $Trigger
     $Task | Register-ScheduledTask -TaskName $taskName -User $env:ScheduledTaskUser -Password  $env:TASKPASS
}

Making sure to set an Environment Variable to the following values:

NOTE: CAPS on the name are not necessary here, seems to just be a standard. I've successfully deployed with both the CAPS version and 'TaskPass'. I say this because several of the links I posted above make it seem like they are.

Name: TASKPASS

Value $(ScheduledTaskPass)

Also of note that MS does it's best to hide this value from you. Even if you set it to a local script variable and try to output the value, as I was trying to do for confirmation purposes, you'll still only get asterisks. But it's really there, I/they promise.


问:
how to get possible sequences of array items in javascript without recursive function?
How to generate all permutation of array items order with javascript and without recursive.
I mean if array length is equal to n then n! possible sequences.
There are some solutions with recursive but I am looking for without recursive.
Maybe I can explain it better with the following example:

```<code>let arr = ['A','B','C'];

console.log(generateOrders(arr));

//and waiting followings:
A, B, C
A, C, B
B, A, C
B, C, A
C, A, B
C, B, A
</code>```

Thank you all.

答:
This is one of the functions I created when solving Project Euler problems, which gets the lexicographical permutations of an array:

Array.prototype.getPermutations = function() {
  const a = this.valueOf().sort((a, b) => a.localeCompare(b))
  const l = a.length - 1
  const findX = () => {
    for (let i = l - 1; i >= 0; i--) {
      if (a[i]  {
    for (let i = l; i >= 0; i--) {
      if (a[i] > a[x]) {
        return i
      }
    }
    return null
  }

  const swap = (arr, a, b) => {
    const t = arr[a]
    arr[a] = arr[b]
    arr[b] = t
    return arr
  }

  const p = [a.slice()]
  while (true) {
    let x = findX()
    if (x === null) return p
    let y = findY(x)
    swap(a, x, y)
    if (l - x > 1) {
      a.splice(x + 1, l - x + 2, ...a.slice(x + 1).reverse())
    }
    p.push(a.slice())
  }
}

const arr = ['A', 'B', 'C']
console.log(arr.getPermutations())```

It is based upon the algorithm described here:

The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.

Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.

Find the largest index l greater than k such that a[k] < a[l].

Swap the value of a[k] with that of a[l].

Reverse the sequence from a[k + 1] up to and including the final element a[n].

There are definitely better algorithms, but I noticed this output matched yours.

Body:
How to generate all permutation of array items order with javascript and without recursive.
I mean if array length is equal to n then n! possible sequences.
There are some solutions with recursive but I am looking for without recursive.
Maybe I can explain it better with the following example:

let arr = ['A','B','C'];

console.log(generateOrders(arr));

//and waiting followings:
A, B, C
A, C, B
B, A, C
B, C, A
C, A, B
C, B, A

Thank you all.

Body:
This is one of the functions I created when solving Project Euler problems, which gets the lexicographical permutations of an array:

Array.prototype.getPermutations = function() {
  const a = this.valueOf().sort((a, b) => a.localeCompare(b))
  const l = a.length - 1
  const findX = () => {
    for (let i = l - 1; i >= 0; i--) {
      if (a[i] < a[i + 1]) {
        return i
      }
    }
    return null
  }

  const findY = x => {
    for (let i = l; i >= 0; i--) {
      if (a[i] > a[x]) {
        return i
      }
    }
    return null
  }

  const swap = (arr, a, b) => {
    const t = arr[a]
    arr[a] = arr[b]
    arr[b] = t
    return arr
  }

  const p = [a.slice()]
  while (true) {
    let x = findX()
    if (x === null) return p
    let y = findY(x)
    swap(a, x, y)
    if (l - x > 1) {
      a.splice(x + 1, l - x + 2, ...a.slice(x + 1).reverse())
    }
    p.push(a.slice())
  }
}

const arr = ['A', 'B', 'C']
console.log(arr.getPermutations())

It is based upon the algorithm described here:

The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.

Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.

Find the largest index l greater than k such that a[k] < a[l].

Swap the value of a[k] with that of a[l].

Reverse the sequence from a[k + 1] up to and including the final element a[n].

There are definitely better algorithms, but I noticed this output matched yours.


问:
Push a div to the right
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">

    <h1 class="logo">
      <img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image">
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li">Home</li>
        <li class="navbar-li">Informations</li>
        <li class="navbar-li">About us</li>
      </ul>
      <ul class="connection">
        <li>S'inscrire</li>
        <li>Se connecter</li>
      </ul>
    </nav>
  </div>
</header></code>```

Thanks

答:
Float won't work because your container is a flex-container.

Just use:justify-content:space-between`

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
  justify-content: space-between;
}

.connection {
  line-height: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">

    <h1 class="logo">
      <img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image">
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li">Home</li>
        <li class="navbar-li">Informations</li>
        <li class="navbar-li">About us</li>
      </ul>
      <ul class="connection">
        <li>S'inscrire</li>
        <li>Se connecter</li>
      </ul>
    </nav>
  </div>
</header></code>```

Title: Push a div to the right

Body:
I'm coding a menu in french but I need to move all the buttons (Home, About us...) to the right.

I tried with float: right; but it doesn't work.

Here is my Result :

My Result

The  Home, Informations, etc.. are in a div. It's this div that i want to push right !

My Objective :

My Objective

My Code:

/*

            ==============================
            NAVBAR
            ==============================

            */

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

header::after {
  content: '';
  display: table;
  clear: both;
}

.logo {
  float: left;
  /*padding: 10px 0;*/
}

nav {
  float: right;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
}

.connection {
  line-height: 2;
}

Home

Informations

About us

S'inscrire

Se connecter

Thanks

Body:
Float won't work because your container is a flex-container.

Just use:justify-content:space-between`

.container {
  width: 80%;
  margin: 0 auto;
}

header {
  background: #9ebd11/*55d6aa*/
  ;
}

nav #navbar-ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

nav .navbar-li {
  display: inline-block;
  padding-top: 23px;
  position: relative;
}

nav .navbar-button {
  color: #444;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav .navbar-button:hover {
  color: #000;
}

nav .navbar-button::before {
  content: '';
  display: block;
  height: 5px;
  background-color: #444;
  position: absolute;
  top: 0;
  width: 0%;
  transition: all ease-in-out 250ms;
}

nav .navbar-button:hover::before {
  width: 100%;
}

nav #register-li {
  /*display: inline-block;*/
  margin-left: 70px;
  padding-top: 23px;
  position: relative;
}

nav #register-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

nav #login-li {
  position: relative;
}

nav #login-button {
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

ul {
  list-style-type: none;
}

nav,
.container {
  display: flex;
  justify-content: space-between;
}

.connection {
  line-height: 2;
}

<header>
  <div class="container">

    <h1 class="logo">
      <a href="#"><img src="images/Logo/logo_gp_.png" width="100" alt="Description de l'image"></a>
    </h1>

    <nav>
      <ul id="navbar-ul">
        <li class="navbar-li"><a href="#" class="navbar-button">Home</a></li>
        <li class="navbar-li"><a href="#" class="navbar-button">Informations</a></li>
        <li class="navbar-li"><a href="#" class="navbar-button">About us</a></li>
      </ul>
      <ul class="connection">
        <li><a href="" target="_blank" id="register-button">S'inscrire</a></li>
        <li><a href="" target="_blank" id="login-button">Se connecter</a></li>
      </ul>
    </nav>
  </div>
</header>


问:
VB delete last element in dynamic array
I need a way to delete the last element in an array when I don't know how big the array is.

Basically I need the VB version of php array_pop, but nothing relevant seems to be appearing in
search results.

答:
use </p>

```<code>Redim Preserve MyArray (UBound(MyArray) - 1)
</code>```

Title: VB delete last element in dynamic array

Body:
use

Redim Preserve MyArray (UBound(MyArray) - 1)


问:
Filter array of objects by common properties
Is it possible in some way to filter let's say such an array of object arrays:

```<code>[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]
</code>```

To get array of objects which all arrays have the same property (id), so in this case it output will be:

```<code>[{id: 2}] // becasue this id is the same in all three subarrays
</code>```

I've only try intersectionBy from loadash but it seems to work in completely other way :/

答:
You can use array reduce,forEach , findIndex and sort to get the most common object. In first inside the reduce callback use forEach to iterate each of the child array and then use findIndex to find if in accumulator array , there exist an object with same id. If it does not exist create a new object with key id & occurrence. If it exist then increase the value of occurrence. This will give the most common id, even if an id is not present in few child array

let data = [
 [{id: 1}, {id: 2}, { id: 3}],
 [{id: 6}, {id: 2}],
 [{id: 2}, {id: 1}, {id: 9}, { id: 3}]
];
let obj = data.reduce((acc, curr) => {
  curr.forEach((item) => {
    let getInd = acc.findIndex((elem) => {
      return elem.id === item.id
    });
    if (getInd === -1) {
      acc.push({
        id: item.id,
        occurence: 1
      })
    } else {
      acc[getInd].occurence += 1;
    }

  })

  return acc;
}, []).sort((a, b) => {
  return b.occurence - a.occurence;
});

console.log(obj[0])```

Body:
Is it possible in some way to filter let's say such an array of object arrays:

[[{id: 1}, {id: 2}, {id: 3}], [{id:6}, {id: 2}], [{id: 2}, {id: 1}, {id: 9}, {id: 3}]]

To get array of objects which all arrays have the same property (id), so in this case it output will be:

[{id: 2}] // becasue this id is the same in all three subarrays

I've only try intersectionBy from loadash but it seems to work in completely other way :/


问:
Is there a way to detect whether Mac OS or Windows OS is in Dark Mode in Java
Currently I am developing an application, However I am unaware of any methods to check if the system is in dark mode already.The application is made with JavaFX on a Mac. Currently I have a CheckMenuItem which when checked, loads up with the use of an IF statement a 'darkmode.css' file. And removes it if the file if the checkmenuitem box is unchecked.

However instead of a check MenuItem I want to be able to activate the css file when the OS is in darkmode and when its not for it to remove it again. I feel like that Java may not be able to do this. If there is any ways for this to be done I will be keen on learning and interested on how you may have implemented it.

In a nutshell native dark mode almost.

答:
There is no standard Java API for finding out whether the host's native UI is in "dark mode" or "night mode" .

In UI design terms, "dark mode" is a relatively new idea.  From what I can tell, it only really took off as an idea in 2018; see https://en.wikipedia.org/wiki/Light-on-dark_color_scheme.  This was well after both Swing and JavaFX had stabilized.  (In the case of Swing, decades after!)

There is a recent (December 2019) RFE in the OpenJDK Bug tracker for detecting the host OS's dark mode setting: JDK-8235460

In the absence of standard Java APIs, you could try OS specific ideas; e.g. as described in the following:

How can I detect Windows 10 light/dark mode?

How to detect if OS X is in dark mode?

For Android dark / night mode detection is supported:

Android - How to detect if night mode is on when using AppCompatDelegate.MODE_NIGHT_AUTO


问:
get values from xml by sql query when several attributes
There is xml with several attributes "Num"

```<code>DECLARE @XML XML = '
<FileId global_id="1234">
  <file id="12aa">
  </file>
  <file id="12bb">
    <Number Num = "1"/>
    <Number Num = "2"/>
  </file>
</FileId>';
</code>```

With this sql query only one attribute can be get

```<code>SELECT F.[File].value(N'../@global_id','varchar(100)') as id_payment,
  F.[File].value('@id', 'varchar(4)') AS id,
  F.[File].value('(Number/@Num)[1]', 'int') as [Num]
FROM (VALUES (@XML)) V (X)
  CROSS APPLY V.X.nodes('/FileId/file') F([File])
</code>```

How to get all attributes -- Num = 1 and Num = 2.
Can be a variable amount of attributes.

```<code>id_payment  id      Num
1234        12aa    NULL
1234        12bb    1
1234        12bb    2
</code>```

答:
Much simpler version. (1) No need to use the VALUES clause. (2) The OUTER APPLY simulates LEFT OUTER JOIN. (3) Most efficient way to retrieve the global_id attribute. The credit goes to Shnugo.

SQL

```<code>DECLARE @XML XML = N'
<FileId global_id="1234">
    <file id="12aa">
    </file>
    <file id="12bb">
        <Number Num="1"/>
        <Number Num="2"/>
    </file>
</FileId>';

SELECT @xml.value('(/FileId/@global_id)[1]','INT') AS id_payment
    , c.value('@id', 'VARCHAR(4)') AS id
    , n.value('@Num', 'INT') AS [Num]
FROM @xml.nodes('/FileId/file') AS t(c)
    OUTER APPLY t.c.nodes('Number') AS t2(n);
</code>```

Output

```<code>+------------+------+------+
| id_payment |  id  | Num  |
+------------+------+------+
|       1234 | 12aa | NULL |
|       1234 | 12bb | 1    |
|       1234 | 12bb | 2    |
+------------+------+------+
</code>```

Body:
There is xml with several attributes "Num"

DECLARE @XML XML = '
<FileId global_id="1234">
  <file id="12aa">
  </file>
  <file id="12bb">
    <Number Num = "1"/>
    <Number Num = "2"/>
  </file>
</FileId>';

With this sql query only one attribute can be get

SELECT F.[File].value(N'../@global_id','varchar(100)') as id_payment,
  F.[File].value('@id', 'varchar(4)') AS id,
  F.[File].value('(Number/@Num)[1]', 'int') as [Num]
FROM (VALUES (@XML)) V (X)
  CROSS APPLY V.X.nodes('/FileId/file') F([File])

How to get all attributes -- Num = 1 and Num = 2.
Can be a variable amount of attributes.

id_payment  id      Num
1234        12aa    NULL
1234        12bb    1
1234        12bb    2

Body:
Much simpler version. (1) No need to use the VALUES clause. (2) The OUTER APPLY simulates LEFT OUTER JOIN. (3) Most efficient way to retrieve the global_id attribute. The credit goes to Shnugo.

SQL

DECLARE @XML XML = N'
<FileId global_id="1234">
    <file id="12aa">
    </file>
    <file id="12bb">
        <Number Num="1"/>
        <Number Num="2"/>
    </file>
</FileId>';

SELECT @xml.value('(/FileId/@global_id)[1]','INT') AS id_payment
    , c.value('@id', 'VARCHAR(4)') AS id
    , n.value('@Num', 'INT') AS [Num]
FROM @xml.nodes('/FileId/file') AS t(c)
    OUTER APPLY t.c.nodes('Number') AS t2(n);

Output

+------------+------+------+
| id_payment |  id  | Num  |
+------------+------+------+
|       1234 | 12aa | NULL |
|       1234 | 12bb | 1    |
|       1234 | 12bb | 2    |
+------------+------+------+


问:
mp3 header reading problem in android
hi
i am doing a program for reading mp3 header. i get reading source code from the site.
if aware of this site or mp3 header reading. please help me.

code is:

```<code>    File oSourceFile = new File("D:\\Mp3\\a.mp3");

    // create an MP3File object representing our chosen file
    MediaFile oMediaFile = new MP3File(oSourceFile);

    // any tags read from the file are returned, in an array, in an order which you should not assume
    ID3Tag[] aoID3Tag = oMediaFile.getTags();
    // let's loop through and see what we've got
    // (NOTE:  we could also use getID3V1Tag() or getID3V2Tag() methods, if we specifically want one or the other)
    for (int i=0; i < aoID3Tag.length; i++)
    {
        // check to see if we read a v1.0 tag, or a v2.3.0 tag (just for example..)
        if (aoID3Tag[i] instanceof ID3V1_0Tag)
        {
            ID3V1_0Tag oID3V1_0Tag = (ID3V1_0Tag)aoID3Tag[i];
            // does this tag happen to contain a title?
            if (oID3V1_0Tag.getTitle() != null)
            {
                System.out.println("Title = " + oID3V1_0Tag.getTitle());
            }
            // etc.
        }
        else if (aoID3Tag[i] instanceof ID3V2_3_0Tag)
        {
            ID3V2_3_0Tag oID3V2_3_0Tag = (ID3V2_3_0Tag)aoID3Tag[i];
            // check if this v2.3.0 frame contains a title, using the actual frame name
            if (oID3V2_3_0Tag.getTIT2TextInformationFrame() != null)
            {
                System.out.println("Title = " + oID3V2_3_0Tag.getTIT2TextInformationFrame().getTitle());
            }
            // but check using the convenience method if it has a year set (either way works)
            try
            {
                System.out.println("Year = " + oID3V2_3_0Tag.getYear());  // reads TYER frame
            }
            catch (ID3Exception e)
            {
                // error getting year.. if one wasn't set
                System.out.println("Could get read year from tag: " + e.toString());
            }
            // etc.
        }
    }
</code>```

run the code i get java.lang.NoClassDefFoundError:

my console output:

```<code>  Exception in thread "main" java.lang.NoClassDefFoundError: junit/framework/TestCase
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at org.blinkenlights.jid3.test.ID3Test.testWriteV1_0Tag(ID3Test.java:60)
at org.blinkenlights.jid3.test.ID3Test.main(ID3Test.java:46)
    Caused by: java.lang.ClassNotFoundException: junit.framework.TestCase
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
     --- testWriteV1_0Tag ---

at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 14 more
</code>```

答: It looks like testWriteV1_0Tag depends on JUnit, which isn't in your classpath. Either change your code so it's not using JUnit (and not depending on anything else which uses JUnit) or include JUnit in your path.

Title: mp3 header reading problem in android

Body:
hi
i am doing a program for reading mp3 header. i get reading source code from the site.
if aware of this site or mp3 header reading. please help me.

code is:

    File oSourceFile = new File("D:\\Mp3\\a.mp3");

    // create an MP3File object representing our chosen file
    MediaFile oMediaFile = new MP3File(oSourceFile);

    // any tags read from the file are returned, in an array, in an order which you should not assume
    ID3Tag[] aoID3Tag = oMediaFile.getTags();
    // let's loop through and see what we've got
    // (NOTE:  we could also use getID3V1Tag() or getID3V2Tag() methods, if we specifically want one or the other)
    for (int i=0; i < aoID3Tag.length; i++)
    {
        // check to see if we read a v1.0 tag, or a v2.3.0 tag (just for example..)
        if (aoID3Tag[i] instanceof ID3V1_0Tag)
        {
            ID3V1_0Tag oID3V1_0Tag = (ID3V1_0Tag)aoID3Tag[i];
            // does this tag happen to contain a title?
            if (oID3V1_0Tag.getTitle() != null)
            {
                System.out.println("Title = " + oID3V1_0Tag.getTitle());
            }
            // etc.
        }
        else if (aoID3Tag[i] instanceof ID3V2_3_0Tag)
        {
            ID3V2_3_0Tag oID3V2_3_0Tag = (ID3V2_3_0Tag)aoID3Tag[i];
            // check if this v2.3.0 frame contains a title, using the actual frame name
            if (oID3V2_3_0Tag.getTIT2TextInformationFrame() != null)
            {
                System.out.println("Title = " + oID3V2_3_0Tag.getTIT2TextInformationFrame().getTitle());
            }
            // but check using the convenience method if it has a year set (either way works)
            try
            {
                System.out.println("Year = " + oID3V2_3_0Tag.getYear());  // reads TYER frame
            }
            catch (ID3Exception e)
            {
                // error getting year.. if one wasn't set
                System.out.println("Could get read year from tag: " + e.toString());
            }
            // etc.
        }
    }

run the code i get java.lang.NoClassDefFoundError:

my console output:

  Exception in thread "main" java.lang.NoClassDefFoundError: junit/framework/TestCase
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at org.blinkenlights.jid3.test.ID3Test.testWriteV1_0Tag(ID3Test.java:60)
at org.blinkenlights.jid3.test.ID3Test.main(ID3Test.java:46)
    Caused by: java.lang.ClassNotFoundException: junit.framework.TestCase
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
     --- testWriteV1_0Tag ---

at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 14 more


问:
Why hiding part of the HTML when using media-query does not work
Trying to practice I have created a landing page mock up and trying to hide an element in css media query.

```<code>@media (max-width:800){

 .right-pane{
    display: none;
    }
}
</code>```

But it does not work when resizing the screen.
Would appreciate your feedback

https://codepen.io/yanivlt/pen/eYNdKRV

答:
Replace 'max-width: 800' to 'max-width: 800px'. Can you try this.</p>

```<code>@media only screen and (max-width: 800px) {
.right-pane{
    display: none;
 }
}
</code>```

Body:
Trying to practice I have created a landing page mock up and trying to hide an element in css media query.

@media (max-width:800){

 .right-pane{
    display: none;
    }
}

But it does not work when resizing the screen.
Would appreciate your feedback

https://codepen.io/yanivlt/pen/eYNdKRV

Body:
Replace 'max-width: 800' to 'max-width: 800px'. Can you try this.

@media only screen and (max-width: 800px) {
.right-pane{
    display: none;
 }
}


问:
Jest TypeError: Path must be a string. Received undefined
Below settings for my package.json

If I run from command line npm test all jest test cases are executed properly.
In case I use directly the command jest from command line I receive this error:

Test suite failed to run

```<code>TypeError: Path must be a string. Received undefined

  at assertPath (path.js:7:11)
  at Object.relative (path.js:538:5)
</code>```

This happens on any test files.

Any idea what could be wrong and how to fix it?

```<code> "scripts": {
        "test": "standard && jest",
        "format": "standard --fix",
        "start": "webpack-dev-server --config webpack.config.dev.js",
        "build": "webpack --config webpack.config.prod.js"
    },
</code>```

答:
npm install react-dev-utils@10.1.0

Installing this version of react-dev-utils helped, when sometimes the commands in the accepted answers didn't.

Good luck y'all!

Body:
Below settings for my package.json

If I run from command line npm test all jest test cases are executed properly.
In case I use directly the command jest from command line I receive this error:

Test suite failed to run

TypeError: Path must be a string. Received undefined

  at assertPath (path.js:7:11)
  at Object.relative (path.js:538:5)

This happens on any test files.

Any idea what could be wrong and how to fix it?

 "scripts": {
        "test": "standard && jest",
        "format": "standard --fix",
        "start": "webpack-dev-server --config webpack.config.dev.js",
        "build": "webpack --config webpack.config.prod.js"
    },


问:
how to feed DataGenerator for KERAS multilabel issue?
I am working on a multilabel classification problem with KERAS.
When i execute the code like this i get the following error:

ValueError: Error when checking target: expected activation_19 to have 2 dimensions, but got array with shape (32, 6, 6)

This is because of my lists full of "0" and "1" in the labels dictionary, which dont fit to keras.utils.to_categorical in return statement, as i learned recently. softmax cant handle more than one "1" as well.

I guess I first need a Label_Encoder and afterwards One_Hot_Encoding for labels, to avoid multiple "1" in labels, which dont go together with softmax.

I hope someone can give me a hint how to preprocess or transform labels data, to get the code fixed. I will appreciate a lot.
Even a code snippet would be awesome.

csv looks like this:

```<code>Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    0       1       0       1     ...  id-2
ghi3.jpg    0       0       0       1     ...  id-3
...
</code>```

```<code>import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size, self.n_classes), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

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

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator)
</code>```

答: Since you already have the labels as a vector of 21 elements of 0 and 1, you shouldn't use keras.utils.to_categorical in  the function __data_generation(self, list_IDs_temp). Just return X and y.

Body:
I am working on a multilabel classification problem with KERAS.
When i execute the code like this i get the following error:

ValueError: Error when checking target: expected activation_19 to have 2 dimensions, but got array with shape (32, 6, 6)

This is because of my lists full of "0" and "1" in the labels dictionary, which dont fit to keras.utils.to_categorical in return statement, as i learned recently. softmax cant handle more than one "1" as well.

I guess I first need a Label_Encoder and afterwards One_Hot_Encoding for labels, to avoid multiple "1" in labels, which dont go together with softmax.

I hope someone can give me a hint how to preprocess or transform labels data, to get the code fixed. I will appreciate a lot.
Even a code snippet would be awesome.

csv looks like this:

Filename  label1  label2  label3  label4  ...   ID
abc1.jpg    1       0       0       1     ...  id-1
def2.jpg    0       1       0       1     ...  id-2
ghi3.jpg    0       0       0       1     ...  id-3
...

import numpy as np
import keras
from keras.layers import *
from keras.models import Sequential

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(224,224), n_channels=3,
                 n_classes=21, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size, self.n_classes), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('Folder with npy files/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

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

# Parameters
params = {'dim': (224, 224),
          'batch_size': 32,
          'n_classes': 21,
          'n_channels': 3,
          'shuffle': True}

# Datasets
partition = partition
labels = labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()

model.add(Conv2D(32, (3,3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

...

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dense(21))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator)


问:
Tensorflow Extra None dimension required for model
here is my model:

```<code>model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(40, 40, 3)),
  tf.keras.layers.Dense(150, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])
</code>```

and my input tensor is called image_batch . when I run np.shape(image_batch[0]), the result is TensorShape([40, 40, 3]). This is expected behavior, as each training example is 40x40x3 its an rgb image).
However when running the command predictions = model(image_batch[0]).numpy() in order to get the predictions of the model, I get the error:

```<code>WARNING:tensorflow:Model was constructed with shape Tensor("flatten_1_input:0", shape=(None, 40, 40, 3), dtype=float32) for input (None, 40, 40, 3), but it was re-called on a Tensor with incompatible shape (40, 40, 3).
</code>```

So my question is why does the keras model expect a shape with an extra "None" dimension, and how do I provide it to the model?

答: The None is the batch dimension. Its is set as None because it can vary. You can use batch sized of 512 during training and then use batches of size 1 when predicting, for example.

Body:
here is my model:

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(40, 40, 3)),
  tf.keras.layers.Dense(150, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10)
])

and my input tensor is called image_batch . when I run np.shape(image_batch[0]), the result is TensorShape([40, 40, 3]). This is expected behavior, as each training example is 40x40x3 its an rgb image).
However when running the command predictions = model(image_batch[0]).numpy() in order to get the predictions of the model, I get the error:

WARNING:tensorflow:Model was constructed with shape Tensor("flatten_1_input:0", shape=(None, 40, 40, 3), dtype=float32) for input (None, 40, 40, 3), but it was re-called on a Tensor with incompatible shape (40, 40, 3).

So my question is why does the keras model expect a shape with an extra "None" dimension, and how do I provide it to the model?


问:
python xml.etree.ElementTree remove empty tag in the middle of text
I have an xml document from which I want to extract text based on tags.

The part that I want to extract text from looks something like this :

```<code><BlockText attr1="blah" attr2=657 ID="Bhf76" lang="en">
Simply dummy text of the printing and typesetting industry. It has survived not only<TIP CONTENT=""/>\n five centuries, electronic typesetting, remaining essentially release.
</BlockText>
</code>```

When I do

```<code>tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = text.text
</code>```

I'm only able to grab the part that comes before the empty tag <TIP CONTENT=""/>

I tried to delete this tag before getting the rest of the text.

I did :

```<code>emptyTag = list(filter(lambda i: "TIP" in i, tags))
for e in root.iter(emptyTag) :
    root.remove(e)
</code>```

But this is not working.

None of <BlockText> and <TIP> are direct children of root.

Thank you.

答:
Ok this is what ended up working for me :

```<code>emptyTags = list(filter(lambda i: "TIP" in i, tags))
if emptyTags :
    emptyTag = list(filter(lambda i: "TIP" in i, emptyTags))[0]
for element in root.iter(emptyTag):
    print(element.tail)
</code>```

But I still can't get the text as a whole block (same order). I can get all the BlockText tags and all the TIP tags but not together.

Update :

I used :

```<code>tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = ''.join(text.itertext())
</code>```

Body:
I have an xml document from which I want to extract text based on tags.

The part that I want to extract text from looks something like this :

<BlockText attr1="blah" attr2=657 ID="Bhf76" lang="en">
Simply dummy text of the printing and typesetting industry. It has survived not only<TIP CONTENT=""/>\n five centuries, electronic typesetting, remaining essentially release.
</BlockText>

When I do

tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = text.text

I'm only able to grab the part that comes before the empty tag <TIP CONTENT=""/>

I tried to delete this tag before getting the rest of the text.

I did :

emptyTag = list(filter(lambda i: "TIP" in i, tags))
for e in root.iter(emptyTag) :
    root.remove(e)

But this is not working.

None of <BlockText> and <TIP> are direct children of root.

Thank you.

Body:
Ok this is what ended up working for me :

emptyTags = list(filter(lambda i: "TIP" in i, tags))
if emptyTags :
    emptyTag = list(filter(lambda i: "TIP" in i, emptyTags))[0]
for element in root.iter(emptyTag):
    print(element.tail)

But I still can't get the text as a whole block (same order). I can get all the BlockText tags and all the TIP tags but not together.

Update :

I used :

tree = ET.parse("myfile.xml")
root = tree.getroot()
tags = list(set([elem.tag for elem in root.iter()]))
tag = list(filter(lambda i: "BlockText" in i, tags))[0]
for text in root.iter(tag):
    texte = ''.join(text.itertext())


问:
How to use if-else statements in Appium Test (Java)
I want to use some construction like this in Appium in my Tests:

```<code>if (element.exists()) {
 System.out.println("OK");
}
</code>```

But Test failed with NoSuchElementException. Thy/catch constructiont doesnt work too.
How can I use if/else statements in Appium?

答:
You can check if the element exists or not by first fetching the list of that element and then checking its size. If the size is greater than 0 it means it is present on the page else it is not present.

You can do it like:

```<code>List<WebElement> elementList = driver.findElements(By.xpath("Enter your xpath here"));
if(elementList.size()>0){
   //Element is present
}
else{
   //Element is not present
}
</code>```

Body:
I want to use some construction like this in Appium in my Tests:

if (element.exists()) {
 System.out.println("OK");
}

But Test failed with NoSuchElementException. Thy/catch constructiont doesnt work too.
How can I use if/else statements in Appium?

Body:
You can check if the element exists or not by first fetching the list of that element and then checking its size. If the size is greater than 0 it means it is present on the page else it is not present.

You can do it like:

List<WebElement> elementList = driver.findElements(By.xpath("Enter your xpath here"));
if(elementList.size()>0){
   //Element is present
}
else{
   //Element is not present
}


问:
Python: Preserve last line in console for specific output
I have a program that does lots of printing. For UX, I want to have the line at the bottom of the console screen always display the same piece of information - a summary of how many jobs are done, and how many remain X done, Y remaining (X and Y are constantly changing throughout the program's runtime).

I tried using curses, however, I only need to control one line and I could not find a way to limit curses's screen scope.

I also tried using blessings:

```<code>with t.location(0, t.height - 1):
    print 'This is at the bottom.'
</code>```

but it only worked when there wasn't enough stdout to reach the last line in the console.

I am using python 2.7

答:
Try this:</p>

```<code>def print_with_fixed_bottom(message):
    fixed = 'This is at the bottom.'
    print '\r{: <{width}}\n{}'.format(message, fixed, width=len(fixed)), # comma is important
</code>```

Body:
I have a program that does lots of printing. For UX, I want to have the line at the bottom of the console screen always display the same piece of information - a summary of how many jobs are done, and how many remain X done, Y remaining (X and Y are constantly changing throughout the program's runtime).

I tried using curses, however, I only need to control one line and I could not find a way to limit curses's screen scope.

I also tried using blessings:

with t.location(0, t.height - 1):
    print 'This is at the bottom.'

but it only worked when there wasn't enough stdout to reach the last line in the console.

I am using python 2.7

Body:
Try this:

def print_with_fixed_bottom(message):
    fixed = 'This is at the bottom.'
    print '\r{: <{width}}\n{}'.format(message, fixed, width=len(fixed)), # comma is important


问:
SQL Server: SELECT only the rows with MAX(DATE)
I have a table of data (the db is MSSQL):

```<code>ID  OrderNO  PartCode  Quantity DateEntered
417 2144     44917     100      18-08-11
418 7235     11762     5        18-08-11
419 9999     60657     100      18-08-11
420 9999     60657     90       19-08-11
</code>```

I would like to make a query that returns OrderNO, PartCode and Quantity, but only for the last registered order.

From the example table I would like to get back the following info:

```<code> OrderNO  PartCode  Quantity
 2144     44917     100
 7235     11762     5
 9999     60657     90
</code>```

Notice that only one line was returned for order 9999.

Thanks!

答:
This works for me. use MAX(CONVERT(date, ReportDate)) to make sure you have date value

```<code>select max( CONVERT(date, ReportDate)) FROM [TraxHistory]
</code>```

Body:
I have a table of data (the db is MSSQL):

ID  OrderNO  PartCode  Quantity DateEntered
417 2144     44917     100      18-08-11
418 7235     11762     5        18-08-11
419 9999     60657     100      18-08-11
420 9999     60657     90       19-08-11

I would like to make a query that returns OrderNO, PartCode and Quantity, but only for the last registered order.

From the example table I would like to get back the following info:

 OrderNO  PartCode  Quantity
 2144     44917     100
 7235     11762     5
 9999     60657     90

Notice that only one line was returned for order 9999.

Thanks!

Body:
This works for me. use MAX(CONVERT(date, ReportDate)) to make sure you have date value

select max( CONVERT(date, ReportDate)) FROM [TraxHistory]


问:
Calculate multiple columns based on threshold
data

```<code>data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))
</code>```

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

答:
data.table solution:

```<code>setDT(data)
cols <- paste0("score", 1:4)
data[, paste0(cols, "x") := lapply(.SD, function(x) as.integer(x > 80)), .SDcols = cols]
data

   student score1 score2 score3 score4 score1x score2x score3x score4x
1:       1     77     95     92     84       0       1       1       1
2:       2     NA     89     52     57      NA       1       0       0
3:       3     52     79     73     78       0       0       0       0
4:       4     99     89     64     81       1       1       0       1
5:       5     89     73     90     66       1       0       1       0
</code>```

Body:
data

data=data.frame("student"=c(1,2,3,4,5),
"score1"=c(77,NA,52,99,89),
"score2"=c(95,89,79,89,73),
"score3"=c(92,52,73,64,90),
"score4"=c(84,57,78,81,66),
"score1x"=c(0,NA,0,1,1),
"score2x"=c(1,1,0,1,0),
"score3x"=c(1,0,0,0,1),
"score4x"=c(1,0,0,1,0))

I have data with student id and score1-score4 and hope to create score1x-score4x in a simple fast way. The rule is if say score1 is less than 80 then score1x is 0 otherwise it is 1.
I can do this by: data$score1x=ifelse(score1<80,0,1) but am wondering is there a way to do this for all of them at the same time to create score1x-score4x more quickly?

Body:
data.table solution:

setDT(data)
cols <- paste0("score", 1:4)
data[, paste0(cols, "x") := lapply(.SD, function(x) as.integer(x > 80)), .SDcols = cols]
data

   student score1 score2 score3 score4 score1x score2x score3x score4x
1:       1     77     95     92     84       0       1       1       1
2:       2     NA     89     52     57      NA       1       0       0
3:       3     52     79     73     78       0       0       0       0
4:       4     99     89     64     81       1       1       0       1
5:       5     89     73     90     66       1       0       1       0