text:
Q: IE9 local filesystem security prevents js execution I'm developing a local JavaScript webapp for demo purposes. The webapp consists of a single HTML page and a few JS files that are included into the app using <script> tags in <head>.
When I run this file (from the local filesystem on windows) on FF or Chromium, everything is as it should be - the app works fine.
When I run it in IE9, there is a "Internet Explorer restricted this page from running scripts or ActiveX controls" and the app fails to load properly. Clicking on "Allow content" does not help that much because the app already is a train wreck.
How when I host a local webserver with
python -m http.server 8888

and point IE to it - everything works fine.
Because this is a corporate setting I am not interested in changing the security settings.
I've dealt with the problem by sending these files to a server, but the questions remains: why does IE treat files from the filesystem (within the same directory even) as some sort of cross-site request or security risk?
PS. Bonus WTF: When opening the page with the developer tools on, everything is ok.
EDIT: In case you're wandering: I did add a closing script tag.
<script type="text/javascript" src="vendor/d3.v3.js"></script>

A:
why does IE treat files from the filesystem [as a] security risk?

Historical Reasons.
When Microsoft came up with the idea of web security Zones, they originally decided that the My Computer Zone, containing the local filesystem, was more trusted than the Internet Zone.
This almost sounds like a sensible thing to do, except that (a) users expect web pages they download not to gain a load of privileges when run from the hard disc, and (b) lots of programs download files from the internet and put them in a predictable place... so if you can persuade them to download an HTML file, you are persauding them to inject privileged script into the My Computer Zone.
The original settings for the My Computer Zone were to allow ActiveX controls to install and run without prompting. This meant that if you could ever get some HTML onto the filesystem, you essentially had an execute-arbitrary-code security vulnerability. There were lots of web exploits that leveraged this as part of their infection mechanism to load malware.
Microsoft feared any change to My Computer Zone security settings would break applications that used the web browser control to render their own HTML content as part of their UI. So instead, the web browser control defaulted to existing settings, and browsers such as IE that used it were invited to enable "Local Machine Lockdown" mode, which would drop the extra privileges My Computer Zone pages got by default. IE turned this on by default.
Unfortunately in a classic over-reaction, "Local Machine Lockdown" was not just the same level of privilege as the Internet Zone would have been, but even more restrictive - blocking JavaScript as well as ActiveX. This broke pages that users had saved to the hard disc, so to work around that IE adds a marker to pages it downloads to allow them to escape the (formerly privileged, now restricted) My Computer Zone and be treated as normal Internet Zone pages.
This is the Mark of the Web and you can include it in your static files to make them behave normally too.
Of course this makes the added restrictiveness of Local Machine Lockdown completely pointless, as any file can opt out.
But then the whole thing is now completely pointless, because since then the default settings of the Local Machine Zone have been changed and now resemble the Internet Zone more closely, not allowing arbitrary ActiveX. So that's a lot of confusing added complexity for no gain whatsoever.


text:
Q: Date picker control does not capture data The date picker control worked perfectly when my site was on SharePoint 2013 once the SharePoint site collection was upgraded to SP2016 the date picker controls for all my InfoPath forms became disabled, icon is greyed out and won't capture any data.
If I preview the form prior to publishing it, the date control icons collapse and are able to capture the date as I save to the list. While troubleshooting the date control I came across the DateTime1033 is undefined error which led me to promote my site to a top-level site, but this found no success.
I've created a new list with InfoPath form with date picker controls to see if my new list with date pickers would work, but those controls aren't working either. Would appreciate some assistance in resolving this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can the frontend and backend share the same package.json? I have a small personal project which I'm developing in one single repo.
The backend is a Node.js server and the front is a Vue.js application.
I want both of them to share the same package.json
The only reason I want to do that is because I want to use the "scripts: {}" of that one common package.json to execute commands that refer to either backend or frontend modules.
Is this possible ?
Would this structure make sense and work:
- my-project
  - front
    - {Vue.js files & folders}
  - back
    - {files & folders for my server}
  - package.json (containining dependencies and yarn scripts for both front and back)

But does that also mean that when e.g. Vite/Vue compiles the .js files for production it will also "accidentally" include irrelevant node_modules that were actually there only for the backend to use?
UPDATE:
I tried it and it's pretty clean and straightforward and works fine.
I'm posting this here in case anyone is interested:
- /root
  - /back (contains server files & folders)
  - /front (contains Vue.js files & folders)
  - package.json
  - .eslintrc.cjs
  - .gitignore
  - vite.config.js
  - yarn.lock

// contents of package.json
{
  ......,
  ...,
  "type": "module",
  "scripts": {
    "back:start": "nodemon --experimental-modules --es-module-specifier-resolution=node ./back/server.js",
    "front:start": "vite",
    "front:build": "vite build",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore",
    "start": "yarn front:build && yarn back:start"
  },
  "dependencies": {
    .....,
    ...
  },
  "nodemonConfig": {
    "ignore": [...]
  },
  "engines": {
    "node": "^16.14.0"
  }
}

I'm deploying the above on Heroku as is and Heroku simply calls yarn start and the app is built and deployed. (You'll notice I have no "devDependencies" and that's because Heroku ignores everything under "devDependencies", including vite)

A: Yes this is possible and in fact quite common. This usage pattern is often called the monorepo in the JS community. The usual way of doing it is exactly the folder structure you describe.
Most frontend frameworks including Vue are designed to handle this however most of the usual tools assume your frontend is separate from your backend. You may need to manually configure your frontend framework to do this.
Some things to consider:

*

*Frontend development server (eg. webpack) may need to be configured to search for files in a subdirectory (eg. "frontend").

*You may want to install all frontend modules as --save--dev so they can be skipped when you deploy your backend.

There are of course additional advantages to this beyond shared package.json file (thus, a common npm run workflow). One advantage is that you can have shared libraries between frontend and backend. I usually have this structure:
├ .git
├ package.json
├ frontend/         - frontend project
│    ├ src/         - source files
│    └ public/
├ backend/          - backend project
│    ├ controllers/ - endpoint modules
│    └ lib/         - backend models/modules
└ lib/              - shared modules

In my package.json I usually have at least something like this:
{
  "scripts": [
    "frontend": "cd frontend; webpack serve",
    "backend": "cd backend; nodemon main.js"
  ]
}

The npm commands even look natural:
npm run backend
npm run frontend

I normally use a javascript script to run both backend and frontend together to reduce issues for my Windows using colleagues. So my start script is usually just:
{
  "scripts": [
    "start": "node ./scripts/start.js"
  ]
}

.. however writing such start scripts will more than double the length of this answer (which is already quite long as is) so I leave it to your creativity.


text:
Q: IndexOutOfRangeException on accessing attributes through String array? I have a treeView displayed on a winform.Now when i click on an xmlnode in the treeview its attributes get displayed in the listbox.Now i have divided the whole logic in UI and back end part. Now what i want that my back end class contains the method to display atrributes(name and value) of the xml node clicked and these are stored in an array and it is returned as a string to my front end class in the treev_AfterSelect event. How can i do it?I need to store attributes of the node i click on winform in a string array and display in listbox.Here is the code what i have for my Backhand class
enter code here
public  string[] selectedNode(XmlNode eventNode)
    {
        XmlAttributeCollection attCol = eventNode.Attributes;
        string[] strArray = new string[attCol.Count];
         if (attCol != null)
            for( int i = 0; i <= attCol.Count;i++)
            {  strArray[i] = "Attribute name: " + attCol[i].Name+","+" Attribute value: " + attCol[i].Value;//IndexOutOfRange Exception
                    }
            return strArray;
    }

Here i am getting an exception of IndexOutOfRangeException : The index being passed in is out of range. on this line
strArray[i] = "Attribute name: " + attCol[i].Name+","+" Attribute value: " + attCol[i].Value;

My Front end ( UI ) class contains this code to retrieve the Attribute and values, display
it on Listbox.
private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
        classObj = new MytreeNodeClass();
       listBox1.Items.Clear();
        XmlNode xNode = e.Node.Tag as XmlNode;
        string[] arrStr = classObj.selectedNode(xNode);
        listBox1.Items.Add(arrStr); //Is this the correct syntax to retrieve the data in listbox??
     }

Can you please help out where i m going wrong?? What  and where to put exactly to remove the exception and run the code successfully??i dont want Treenode to be used in backhand.
Thanks....

A: You're going too far in your loop.
for( int i = 0; i <= attCol.Count;i++)

should be
for( int i = 0; i < attCol.Count;i++)


text:
Q: Why does my for loop containing a simple while loop only run twice? And poorly I'm trying to loop over this while loop a few times to collect info about how long it takes to output the correct sequence of lines (to spell "CODER"). I expect my for loop to loop ten times. Instead, I only get one loop, and then one malfunctioning repetition done in 0 seconds.
I can replace the for i in (0, 10) line with a while i < 10 and add a i += 1 later on to get a longer piece of malfunctioning output (it will cycle the first conclusion to the while loop n times instead of 2 times). I also tried moving the lists and dictionary inside of the for loop but that didn't make the loop run properly.
from random import randint
from time import sleep
import datetime

stats_collection = []
correct_order = [0, 1, 2, 3, 4]  # A list of numbers between 0 and 4
output_order = []
iterations = 0
the_lines = {0: "...###.................#####...####..",
             1: "..#...#.........####...#.......#...#.",
             2: "..#.......###...#...#..##......##....",
             3: "..#...#..#...#..#...#..#.......#.#...",
             4: "...###....###...####...#####...#..#..",}

for i in (0,10):

    a_currentDT = str(datetime.datetime.now())

    while output_order[-5:] != correct_order:
        next = randint(0, 4) # Select between
        output_order.append(next)
        print(the_lines[next])
        iterations += 1
        # sleep(0.125)

    final_iterations = iterations

    b_currentDT = str(datetime.datetime.now())

    print("Finished!")
    print("Iterations: {num}".format(num=final_iterations))
    print(a_currentDT)
    print(b_currentDT)

    stats_collection.append(final_iterations)

print(stats_collection)

What I expect is something like a printed list from print(stats_collection) that is like: [134, 2948, 4001, 598, 910, 1000, 2000, 3003, 10593, 403] or another set of 10 numbers. But I only get the first run printed twice, or n times if I replace the for loop with a while loop (as in while i < 10 or something).
Here is what output I get from for i in (0, 10): as the mechanism for looping over the while loop:
Finished!
Iterations: 8598
2019-06-02 15:21:21.543503
2019-06-02 15:21:21.641444
Finished!
Iterations: 8598
2019-06-02 15:21:21.641444
2019-06-02 15:21:21.641444
[8598, 8598]

I'm expecting the code to run the while loop a second time and have a completely different result, including a total of 10 different results, something like this:
Finished!
Iterations: 8598
2019-06-02 15:21:21.543503
2019-06-02 15:21:21.641444
Finished!
Iterations: 159
2019-06-02 15:21:21.641445
2019-06-02 15:21:21.700555
[8598, 159]

But ten different results of course.
The code would work great except for this miscellaneous error. I actually don't understand why the code is doing this whatsoever.
It may be useful to see that the second loop is actually done instantaneously. I don't know what's going on at all. Am I not able to host a while loop inside of a for loop like that?

A: for i in (0,10): sets i to each of the elements of the tuple (0, 10) in turn.  Specifically, it means:

*

*Run the loop body with i=0

*Run the loop body with i=10

*Done.

If you want to loop over the range from 0 to (but not including) 10, you need to write:
for i in range(0, 10):

or just:
for i in range(10):

A: Two problems in your code:

*

*for i in (0,10) should be for i in range(0, 10), the former one iterates only 2 times, which i = 0 and i = 10.

*You should move output_order = [] and iterations = 0 into for-loop, this is also why your results keep repeating, because output_order doesn't reset and it keeps solution after first iteration.

A: Your while loop has a 1 in 3125 chance of producing the appropriate order on each iteration.  It will take about 2000 iterations to have 50% chance of finding the proper order.  5000 iterations will have 80% chance of finding it. This should give random execution times but, as your code is tight now, it will only repeat the first results over and over.
Printing lines as you go will slow it down considerably.
Since you're not resetting output_order between samples, your second pass will find a matching result immediately (as reflected in the times) but will show the previous number of iterations since you're not resetting that variable either.

A: I've modified your code a bit, as it seemed like you were performing a lot more repetitions than necessary. From what I understood of your specs, you want to compute how many repetitions it takes to spell coder. I changed the code to only move to the next line once the random integer matched the index of the current line to be printed.
`from random import randint
 from time import sleep
 import datetime

 stats_collection = []
 correct_order = [0, 1, 2, 3, 4]  # A list of numbers between 0 and 4
 iterations = 0
 the_lines = {0: "...###.................#####...####..",
         1: "..#...#.........####...#.......#...#.",
         2: "..#.......###...#...#..##......##....",
         3: "..#...#..#...#..#...#..#.......#.#...",
         4: "...###....###...####...#####...#..#..",}

for i in range(0,10):
    output_order = [None for i in range(len(correct_order))]

    a_currentDT = str(datetime.datetime.now())
    idx = 0
    while output_order != correct_order:
        next = randint(0, 4) # Select between
        if output_order[idx] == None and idx == next:
            output_order[idx] = next
            idx += 1
            print(the_lines[next])

        iterations += 1

        # sleep(0.125)
    print(output_order)

    final_iterations = iterations

    b_currentDT = str(datetime.datetime.now())

    print("Finished!")
    print("Iterations: {num}".format(num=final_iterations))
    print(a_currentDT)
    print(b_currentDT)

    stats_collection.append(final_iterations)
    iterations = 0

print(stats_collection)`

I also have a modified that matches most closely what you had in the beginning.
`from random import randint
from time import sleep
import datetime

stats_collection = []
correct_order = [0, 1, 2, 3, 4]  # A list of numbers between 0 and 4
iterations = 0
the_lines = {0: "...###.................#####...####..",
             1: "..#...#.........####...#.......#...#.",
             2: "..#.......###...#...#..##......##....",
             3: "..#...#..#...#..#...#..#.......#.#...",
             4: "...###....###...####...#####...#..#..",}

for i in range(0,10):
    output_order = []

    a_currentDT = str(datetime.datetime.now())

    while output_order[-5:] != correct_order:
        next = randint(0, 4) # Select between
        output_order.append(next)
        iterations += 1
        # print(the_lines[next])
        # sleep(0.125)
    # print(output_order[-5:])

    final_iterations = iterations

    b_currentDT = str(datetime.datetime.now())

    print("Finished!")
    print("Iterations: {num}".format(num=final_iterations))
    print(a_currentDT)
    print(b_currentDT)

    stats_collection.append(final_iterations)
    iterations = 0

print(stats_collection)`


text:
Q: How to remove the black sprite in the middle of my screen? I have a maze game that comprises of 3 different class, which includes 2 maze solving algorithms and a class for players to move around with the up, down, left and right key. So the way to toggle between the classes is to use a tab key. But however, when i reach the class where users can manually control the sprite, there will always be a random black arrow that looks like its going through spasm in the middle of my window. Even though i can manage to control the orange sprite, but that black arrow is still there. Is there anyway that i can remove it? I tried using hideturtle to hide the arrow, but to no avail.
I highly suspect that it was due to this part of my code that resulted in the appearance of the black arrowhead. But i wasn't able to find a replacement for that.
while True:
    ManualMovements()

This is how the black sprite looks like right now:

My current code:
from turtle import * # import the turtle library

# define the tile_size and cursor_size for usage later on
TILE_SIZE = 24
CURSOR_SIZE = 20

screen = Screen() # instantiate the Screen class from turtle
screen.setup(700, 700) # determine the size of the turtle pop out window

class Wall(Turtle): # create Wall class to plot out the walls
    def __init__(self):
        super().__init__() # inherit from Turtle(parent class)
        self.hideturtle() # hide the cursor
        self.shape('square') # define the shape of the object we wanna draw out
        self.shapesize(TILE_SIZE / CURSOR_SIZE) # define the size of the square
        self.pencolor('black') #  define the color that we are going to plot the grids out
        self.penup() # to prevent the pen from leaving a trace
        self.speed('fastest') # get the fastest speed

class Path(Turtle): # create Path class to plot out the path
    def __init__(self):
        super().__init__() # inherit from Turtle(parent class)
        self.hideturtle() # hide the cursor
        self.shape('square') # define the shape of the object we wanna draw out
        self.shapesize(TILE_SIZE / CURSOR_SIZE) # define the size of the square
        self.pencolor('white') #  define the color that we are going to plot the grids out
        self.penup() # to prevent the pen from leaving a trace
        self.speed('fastest') # get the fastest speed

class Sprite(Turtle): # create Sprite class to define the turtle and its characteristics
    def __init__(self):
        super().__init__() # inherit from Turtle(parent class)
        self.shape('turtle') # define the shape of the object we wanna draw out
        self.shapesize((TILE_SIZE / CURSOR_SIZE)-0.4) # define the size of the square
        self.color('orange') #  define the color that we are going to plot the turtle
        self.penup() # to prevent the pen from leaving a trace
        self.speed('slowest') # set speed to slowest to observe the sprite movement

class ManualMovements(Sprite): # create ManualMovement class to let the user manually control the sprite
    def __init__(self):
        super().__init__()
        self.moves = 0
        self.hideturtle()
        self.screen.onkeypress(self.go_up, "Up")
        self.screen.onkeypress(self.go_down, "Down")
        self.screen.onkeypress(self.go_left, "Left")
        self.screen.onkeypress(self.go_right, "Right")

    def go_up(self):
        xcor = sprite.xcor()
        ycor = sprite.ycor()

        if (xcor, ycor + TILE_SIZE) not in walls:
            sprite.setheading(90)
            sprite.goto(xcor, ycor + TILE_SIZE)

    def go_down(self):
        xcor = sprite.xcor()
        ycor = sprite.ycor()

        if (xcor, ycor - TILE_SIZE) not in walls:
            sprite.setheading(270)
            sprite.goto(xcor, ycor - TILE_SIZE)

    def go_left(self):
        xcor = sprite.xcor()
        ycor = sprite.ycor()

        if (xcor - TILE_SIZE, ycor) not in walls:
            sprite.setheading(180)
            sprite.goto(xcor - TILE_SIZE, ycor)

    def go_right(self):
        xcor = sprite.xcor()
        ycor = sprite.ycor()

        if (xcor + TILE_SIZE, ycor) not in walls:
            sprite.setheading(0)
            sprite.goto(xcor + TILE_SIZE, ycor)

def setup_maze(level): # create a setup_maze function so that we can plot out the map in turtle
    # declare maze_height and maze_width first as the limits for the entire maze
    maze_height, maze_width = len(level), len(level[0])

    # get the center point for each maze
    center_horizontal_point = (maze_width + 1) / 2
    center_vertical_point = (maze_height + 1) / 2

    for y in range(maze_height): # for loop to limit the entire maze
        for x in range(maze_width):
            character = level[y][x] # get the character at each x,y coordinate

            # calculate the screen x, y coordinates
            screen_x = ((x - maze_width) * TILE_SIZE) + (center_horizontal_point * TILE_SIZE)
            screen_y = ((maze_height - y) * TILE_SIZE) - (center_vertical_point * TILE_SIZE)

            if character == "X":
                maze.fillcolor('grey')
                maze.goto(screen_x, screen_y)
                maze.stamp()
                walls.append((screen_x, screen_y)) # add coordinates for the wall to the list
            else:
                maze.fillcolor('white')
                maze.goto(screen_x, screen_y)
                maze.stamp()
                paths.append((screen_x, screen_y)) # add coordinates for the path to the list

            if character == "e":
                maze.fillcolor(['white', 'red'][character == 'e'])
                maze.goto(screen_x, screen_y) # proceed on to the coordinates on turtle
                maze.stamp() # stamp out the boxes
                finish.append((screen_x, screen_y)) # add coordinates for the endpoint to the list

            if character == 's': # if statement to determine if the character is s
                maze.fillcolor('green')
                maze.goto(screen_x, screen_y)
                maze.stamp() # stamp out the boxes
                start.append((screen_x, screen_y)) # add coordinates for the startpoint to the list
                sprite.goto(screen_x, screen_y) # move the sprite to the location where it is supposed to start

def endProgram(): # exit the entire program upon clicking anywhere in the turtle window
    screen.exitonclick()

grid = []                               # create a grid list to store the labels while reading from the txt file
walls = []                              # create walls coordinate list
start = []
finish = []                             # enable the finish array
paths = []
maze = Wall()                           # enable the Wall class
sprite = Sprite()                       # enable the Sprite class
path = Path()

with open("map02.txt") as file:         # open the txt file and read contents and append it to maze
    for line in file:
        grid.append(line.strip())

setup_maze(grid)                        # call the setup maze function

start_x, start_y = (start[0])[0], (start[0])[1]

sprite.seth(0)
sprite.goto(start_x, start_y)

while True:
    ManualMovements()

screen.listen() # we need this in order to allow turtle to detect what key we are pressing and respond to it
screen.mainloop()

A sample txt file map:
XXXXXXXXXXXXXXXXXXXX
Xe.................X
XXXXXXX...X..XXXXX.X
XXXXXX....X.....XXXX
XXX.......X...X.XXXX
XXXXXX....X.....XXXX
X.........X...XXXXXX
X.XXXXXX..X...XXXXXX
X.X.......X..XXXXXXX
X.X...XXXX.........X
X.XXXXXsXX..XXXXXXXX
X..............XXXXX
XXXXXXXXXXXXXXXXXXXX

EDIT: Some edits have been made. Please relook again. In order to execute the code, you have to press tab once before pressing the up, down, left, right buttons from my side. I also have removed the 2 classes to prevent confusion and also since i pinpointed that this part of the code is where my error should come from. The current code above does replicate the same error too.

A: The problem is that your ManualMovements class is wrong-headed.  Rather than a bizarre helper class, it should be a subclass of Sprite.  (Akin to a fully automated Sprite subclass.)  I've reworked your code accordingly below as well as made other fixes and optimizations -- pick and choose as you see fit:
from turtle import Screen, Turtle

# define some global constants for use later
TILE_SIZE = 24
CURSOR_SIZE = 20

class Wall(Turtle):
    ''' class to plot out walls '''

    def __init__(self):
        super().__init__(shape='square')  # inherit from parent class

        self.hideturtle()
        self.shapesize(TILE_SIZE / CURSOR_SIZE)  # define the size of the square
        self.penup()  # prevent the pen from leaving a trace
        self.speed('fastest')

class Path(Wall):
    ''' class to plot out the path '''

    def __init__(self):
        super().__init__()  # inherit from parent class

        self.pencolor('white')  # define the color that we are going to plot the grids out

class Sprite(Turtle):
    ''' class to define turtle sprite and its characteristics '''

    def __init__(self):
        super().__init__(shape='turtle')  # inherit from parent class

        self.shapesize((TILE_SIZE / CURSOR_SIZE) - 0.4)  # define the size of the square
        self.color('orange')  # color that we are going to plot the turtle
        self.penup()  # prevent the pen from leaving a trace
        self.speed('slowest')  # set speed to slowest to observe the sprite movement

class ManualSprite(Sprite):
    ''' class to let the user manually control the sprite '''

    def __init__(self):
        super().__init__()

        screen.onkeypress(self.go_up, 'Up')
        screen.onkeypress(self.go_down, 'Down')
        screen.onkeypress(self.go_left, 'Left')
        screen.onkeypress(self.go_right, 'Right')

    def go_up(self):
        screen.onkeypress(None, 'Up')  # disable handler inside handler

        xcor = int(self.xcor())
        ycor = int(self.ycor())

        if (xcor, ycor + TILE_SIZE) not in walls:
            self.setheading(90)
            self.sety(ycor + TILE_SIZE)

        screen.onkeypress(self.go_up, 'Up')  # reenable handler on exit

    def go_down(self):
        screen.onkeypress(None, 'Down')

        xcor = int(self.xcor())
        ycor = int(self.ycor())

        if (xcor, ycor - TILE_SIZE) not in walls:
            self.setheading(270)
            self.sety(ycor - TILE_SIZE)

        screen.onkeypress(self.go_down, 'Down')

    def go_left(self):
        screen.onkeypress(None, 'Left')

        xcor = int(self.xcor())
        ycor = int(self.ycor())

        if (xcor - TILE_SIZE, ycor) not in walls:
            self.setheading(180)
            self.setx(xcor - TILE_SIZE)

        screen.onkeypress(self.go_left, 'Left')

    def go_right(self):
        screen.onkeypress(None, 'Right')

        xcor = int(self.xcor())
        ycor = int(self.ycor())

        if (xcor + TILE_SIZE, ycor) not in walls:
            self.setheading(0)
            self.setx(xcor + TILE_SIZE)

        screen.onkeypress(self.go_right, 'Right')

def setup_maze(level):
    ''' plot out the map as a maze in turtle '''

    # declare the limits for the entire maze
    maze_height, maze_width = len(level), len(level[0])

    # get the center point for each maze
    center_horizontal_point = (maze_width + 1) / 2
    center_vertical_point = (maze_height + 1) / 2

    start = finish = None

    for y in range(maze_height):
        for x in range(maze_width):
            character = level[y][x]  # get the character at each coordinate

            # calculate the screen x, y coordinates
            screen_x = int((x - maze_width) * TILE_SIZE + center_horizontal_point * TILE_SIZE)
            screen_y = int((maze_height - y) * TILE_SIZE - center_vertical_point * TILE_SIZE)
            maze.goto(screen_x, screen_y)

            if character == 'X':
                maze.fillcolor('grey')
                walls.append((screen_x, screen_y))  # add coordinates for the wall
            else:
                paths.append((screen_x, screen_y))  # add coordinates for the path

                if character == 'e':
                    maze.fillcolor('red')
                    finish = (screen_x, screen_y)
                elif character == 's':
                    maze.fillcolor('green')
                    start = (screen_x, screen_y)
                else:
                    maze.fillcolor('white')

            maze.stamp()

    return start, finish

grid = []  # create a grid list to store the labels while reading from the txt file

with open("map02.txt") as file:  # open the txt file and read contents and append it to maze
    for line in file:
        grid.append(line.strip())

screen = Screen()  # extract the Screen class from turtle
screen.setup(700, 700)  # set the size of the turtle window

sprite = ManualSprite()  # instantiate a Sprite instance

walls = []  # walls coordinate list
paths = []

maze = Wall()  # instantiate the Wall class
path = Path()

start, finish = setup_maze(grid)

sprite.setheading(0)
sprite.goto(start) # move the sprite to the start location

screen.listen() # allow turtle to detect key press and respond to it
screen.mainloop()

I've tossed comments that simply echo the obvious.  Also, your logic didn't take into account the imprecision of floating point coordinates which makes them difficult to compare -- I've converted those comparisons to int.


text:
Q: How do I log my user out using mvc's individual account authentication? In my account controller the logout method is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    return RedirectToAction("UserLogin", "Account");
}

Additionally on the LoginPartial, a javascript function is used to assist in logging the user out when he clicks the logoff link at the top of the page when he is logged in:

Log off

I am trying to duplicate this within my controller to prevent text from being input into the querystring. If text is input, I want to log the user out.
string newNum = Request.Params["unum"];
int unum = 0;
bool res = int.TryParse(newNum, out unum);
if(res == false)
{
    FormsAuthentication.SignOut();
    Session.Abandon();
    return RedirectToAction("UserLogin","Account");
}

The page redirects and user is still logged in. How is this done?


text:
Q: How do I refresh my html page every 2 mins? I am currently using an html page for a webview within my iOS and Android apps. I don't want to update the native code and was wondering if I could just refresh the homepage which is index.html every 2 mins? Is it possible?

A: You can try to use like this:
<meta http-equiv="refresh" content="120">

or you can use setInterval like this:
setInterval(function() {
    window.location.reload();
}, 120000);

A: You can use:
<meta http-equiv="refresh" content="120">

The <meta http-equiv="refresh"> tag causes a web page to refresh
automatically after a specified amount of time. Users generally don't
expect automatic refreshes, so they can be disorienting. Refreshing
also moves focus to the top of the page, which may frustrate or
confuse users, particularly those who rely on screen readers or other
assistive technologies.

*

*https://web.dev/meta-refresh/

*Meta equiv refresh

A: use this
  setTimeout(function(){
       window.location.reload(1);
    }, 120000);

EDIT
Put this in head
<script>
      setTimeout(function(){
           window.location.reload(1);
        }, 120000);
</script>

EDIT
to attach this function only when page is ready use this
<script>
     $('document').ready(function(){
        setTimeout(function(){
           window.location.reload(1);
        }, 120000);
     });
</script>

A: You can Put meta tag before html start
e.g.
<meta http-equiv="refresh" content="120">
  <html>
    <head>
      <meta charset="UTF-8">
        <title>Mart</title>


text:
Q: Como distribuir o espaçamento das colunas de uma table responsiva igualmente? Como posso distribuir o espaçamento das colunas igualmente de uma tabela usando CSS?
Ex:

    Nome
    Email
    Telefone

A: Você pode utilizar a propriedade table-layout: fixed

table {
  width: 100%;
  table-layout: fixed;
}

table td {
  border: 1px solid #000;
}

    Nome
    Email
    Telefone


text:
Q: Converting from ascii to utf-8 with Python I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way:
output = os.popen(cmd).read()
if not isinstance(output, unicode):
   output = unicode(output,'utf-8','ignore')
bot.send(xmpp.Message(mess.getFrom(),output))

But when Russian symbols appear in output they aren't converted well.
sys.getdefaultencoding()

says that default command prompt encoding is 'ascii', but when I try to do
output.decode('ascii')

in python console I get
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 1:
ordinal not in range(128)

OS: Win XP, Python 2.5.4
PS: Sorry for my English :(

A: sys.getdefaultencoding() returns python's default encoding - which is ASCII unless you have changed it. ASCII doesn't support Russian characters.
You need to work out what encoding the actual text is, either manually, or using the locale module.
Typically something like:
import locale
encoding = locale.getpreferredencoding(do_setlocale=True)¶

A: Ascii has no defined character values above 127 0x7F.   Perhaps you mean the Cyrillic code page? It's 866
See http://en.wikipedia.org/wiki/Code_page
edit: since this answer was marked correct presumably 886 worked, but as other answers have pointed it, 886 is not the only Russian language code page.  If you use a code page different from the one that was used when the Russian symbols were encoded, you will get the wrong result.

A: You say """sys.getdefaultencoding() says that default command prompt encoding is 'ascii'"""
sys.getdefaultencoding says NOTHING about the "command prompt" encoding.
On Windows, sys.stdout.encoding should do the job. On my machine, it contains cp850 when Python is run in a Command Prompt window, and cp1252 in IDLE. Yours should contain cp866 and cp1251 respectively.
Update You say that you still need cp866 in IDLE. Note this:
IDLE 2.6.4
>>> import os
>>> os.popen('chcp').read()
'Active code page: 850\n'
>>>

So when your app starts up, check if you are on Windows and if so, parse the result of os.popen('chcp').read(). The text before the : is probably locale-dependent. codepage = result.split()[-1] may be good enough "parsing". On Unix, which doesn't have a Windows/MS-DOS split personality, sys.stdout.encoding should be OK.

A: In Python 'cp855', 'cp866', 'cp1251', 'iso8859_5', 'koi8_r' are differing Russian code pages.  You'll need to use the right one to decode the output of popen.  In the Windows console, the 'chcp' command lists the code page used by console commands.  That won't necessarily be the same code page as Windows applications.  On US Windows, 'cp437' is used for the console and 'cp1252' is used for applications like Notepad.


text:
Q: Why Redirect is not working in laravel 8, when I click on the button view not redirect to view.blade.php I don't understand why Redirect() is not working when I click on the button view not redirect to view.blade.php
    public function view($id)
    {
        $orders = Order::where('id', $id)->where('user_id', Auth::id())->first();
        return view('frontend.orders.view', compact('orders'));

    }

id) }}" class="btn btn-primary">View

Route::get('view-order', [UserController::class, 'view']);

A: You should add the url parameter to the route definition.
Route::get('view-order/{id}', [UserController::class, 'view']);

For a more strict approach to routes, you can use route naming instead.
Route::get('view-order/{id}', [UserController::class, 'view'])
    ->name('orders.view');

Now you can refer to your route as so, this would have meant, you would have hit the correct route url. If you define the parameter it expects is as the second input on the route() call.
id) }}" class="btn btn-primary">View


text:
Q: how to fix "Java source root points to a non-existent location: " error in Android Studio I'm trying to get familiar with jetpack compose. I cloned the Android Developer Codelab, and I'm practicing the Navigation Codelab.
I haven't even done much in the codelab, but when i run the code I get an error;

I don't know the cause, or what is needed to solve this.
So I'm going to just paste the gradle files. Not to have a lengthy question. If you need anymore information, I'll happily provide it. Thanks in Advance.
Build.Gradle (Project Module);
buildscript {
    // Define versions in a single place
    ext {
        // Sdk and tools
        compileSdkVersion = 32
        minSdkVersion = 21
        targetSdkVersion = 32

        // App dependencies
        appCompatVersion = '1.4.2'
        activityComposeVersion = '1.6.0-alpha03'

        composeVersion = '1.2.0'
        // composeCompilerVersion = "1.2.0"
        composeCompilerVersion = "1.3.0-rc01"
        coreTestingVersion = '2.1.0'
        espressoVersion = '3.4.0'
        gradleVersion = '7.2.1'

        kotlinVersion = '1.7.10'
        // kotlinVersion = '1.7.0'
        ktlintVersion = '0.45.2'
        ktxVersion = '1.8.0'
        materialVersion = '1.6.1'
        navigationComposeVersion = '2.5.0'
    }

    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath "com.android.tools.build:gradle:$gradleVersion"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
    }
}

plugins {
    id 'com.diffplug.spotless' version '6.7.0'
}

subprojects {
    repositories {
        google()
        mavenCentral()
    }

    apply plugin: 'com.diffplug.spotless'
    spotless {
        kotlin {
            target '**/*.kt'
            targetExclude("$buildDir/**/*.kt")
            targetExclude('bin/**/*.kt')

            ktlint(rootProject.ktlintVersion)
            licenseHeaderFile rootProject.file('spotless/copyright.kt')
        }
    }
}

Build.gradle (App module);
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 32

    defaultConfig {
        applicationId "com.example.compose.rally"
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 1
        versionName '1.0'
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'

        vectorDrawables.useSupportLibrary = true
    }

    signingConfigs {
        // We use a bundled debug keystore, to allow debug builds from CI to be upgradable
        debug {
            storeFile rootProject.file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }

        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    buildFeatures {
        compose true
    }

    composeOptions {
        kotlinCompilerExtensionVersion rootProject.composeCompilerVersion
    }

    packagingOptions {
        exclude "META-INF/licenses/**"
        exclude "META-INF/AL2.0"
        exclude "META-INF/LGPL2.1"
    }
}

dependencies {

    implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
    implementation "androidx.core:core-ktx:$rootProject.ktxVersion"
    implementation "com.google.android.material:material:$rootProject.materialVersion"

    // Compose
    implementation "androidx.compose.runtime:runtime:$rootProject.composeVersion"
    implementation "androidx.compose.ui:ui:$rootProject.composeVersion"
    implementation "androidx.compose.foundation:foundation:$rootProject.composeVersion"
    implementation "androidx.compose.material:material:$rootProject.composeVersion"
    implementation "androidx.compose.material:material-icons-extended:$rootProject.composeVersion"
    implementation "androidx.activity:activity-compose:$rootProject.activityComposeVersion"
    implementation "androidx.navigation:navigation-compose:$rootProject.navigationComposeVersion"
    debugImplementation "androidx.compose.ui:ui-tooling:$rootProject.composeVersion"

    // Testing dependencies
    androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion"
    androidTestImplementation "androidx.test.espresso:espresso-contrib:$rootProject.espressoVersion"
    androidTestImplementation "androidx.test.espresso:espresso-core:$rootProject.espressoVersion"

    // Compose testing dependencies
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$rootProject.composeVersion"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$rootProject.composeVersion"
}

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
    kotlinOptions {
        // Treat all Kotlin warnings as errors
        allWarningsAsErrors = true

        freeCompilerArgs += '-opt-in=kotlin.RequiresOptIn'

        // Set JVM target to 1.8
        jvmTarget = "1.8"
    }
}

Thanks a lot for your help, in Advance. Again, if you need anymore information I'm happy to provide.


text:
Q: How to setup retries and timeout in trest and trestclient in Talend? I have a job which uses tRestClient to get a token, then uses tRest to get data from CRM based on the token. Both of these components seem to timeout sometimes while connecting to CRM. How can I set them up to have 10 retries for the connection and more minutes to wait before they timeout?

A: There is some setting to do that.
Check the documentation here:
https://help.talend.com/reader/7NvFnkWpbH8Gy3Rm6mUXnw/ECeCwoP1aVopmhqJe_dENA.
You need to go in the advanced setting in the component.
Moreover, there is some limitation to the studio like you see in the documentation.


text:
Q: Is is any way to read all history from Google chrome history and save it in an excel sheet? I search for a way that allow me read all history data from Google Chrome history and save it in any format for example excel sheet .. but i want a way in which i make it by copy data from page and paste in a sheet and formating it .. i search for automatic way or a tool ?

A: Google saves the history in an sqlite3 database located in C:\Users\\AppData\Local\Google\Chrome\User Data\Default (on Windows 7).
Try installing an ODBC driver for sqlite3, you will then be able to use Data->From Other sources (in Get External Data) -> From Microsoft Query to get hold of the file and the data it contains. (I haven't actually done this, I just opened the file in the sqlite manager addin in Firefox to have a quick peek.)


text:
Q: How to use ADO Query Parameters to specify table and field names? I'm executing an UPDATE statement in a TADOQuery and I'm using parameters for a few things. Initially, this was working just fine, but I added another parameter for the table name and field name, and now it's breaking.
The code looks like this:
Q.SQL.Text:= 'update :tablename set :fieldname = :newid where :fieldname = :oldid';
Q.Parameters.ParamValues['tablename']:= TableName;
Q.Parameters.ParamValues['fieldname']:= FieldName;
Q.Parameters.ParamValues['oldid']:= OldID;
Q.Parameters.ParamValues['newid']:= NewID;

And the error I get:

I'm assuming this is because I'm using this field name twice. I can overcome this by using another unique field name for the second time it's used, however I still have another error:

How do I use the parameters to specify the table and field to update?

A: Query parameters aren't designed to parameterize table names.
What you can do is use placeholders for the table name(s) in your SQL, and then use the Format function to replace those with the table name(s), and then use parameters for the other values as usual. This is still relatively safe from SQL injection (the malevolent person would have to know the precise table names, the specific SQL statement being used, and values to provide for parameters).
const
  QryText = 'update %s set :fieldname = :newid where :fieldname = :oldid';
begin
  Q.SQL.Text := Format(QryText, [TableName]);
  Q.Parameters.ParamValues['fieldname'] := FieldName;
  Q.Parameters.ParamValues['oldid'] := OldID;
  Q.Parameters.ParamValues['newid'] := NewID;
  ...
end;


text:
Q: regarding C# adding objects to list using foreach loop foreach (string f in fileName)
{
    if (list.Where(p => p.FileName.Trim().Equals(f.Trim(), StringComparison.OrdinalIgnoreCase)).Count() == 0)
    {
        ServerpathID = GetSourceServerPath(projectID, out ServerPath);
        DellDirectory dir = new DellDirectory(ServerPath);
        lstgAFPFileInfo = GetFilesFromSourceServer(new string[] { f }, ServerpathID, SearchOption.TopDirectoryOnly).ToList();

        if (lstgAFPFileInfo.Count() != 0)
        {
            foreach (Service.GAFPFileInfo lstg in lstgAFPFileInfo)
            {
                projectfile.Checksum = string.Empty;
                projectfile.IsAutoDeleted = (autoDelete == true) ? true : false;
                projectfile.Size = lstgAFPFileInfo[0].Size;
                projectfile.IsArchived = false;
                projectfile.ProjectFileId = 0;
                projectfile.Language.LanguageId = 1;
                projectfile.LastModifyDate = lstgAFPFileInfo[0].LastModified;
                projectfile.ProjectPartLink = projectPartLink;
                projectfile.FileName = f;
                list.Add(projectfile);
            }
        }
    }
}

I have two files 1.txt and 2.txt in string[] filename. I am comparing these files with db and getting values into lstgAFPFileInfo. The first time it got the filename 1.txt and added to list. 2nd time it got the value 2.txt but after adding the file to the list it is overwrite the value 1.txt and again it added 2.txt. Now the list values are like this list[0]:2.txt and list[1]: 2.txt
Can anyone help on this?

A: This is because your loop keeps adding the same object over and over, so your list ends up with multiple references to the same object.

Add projectfile  = new ProjectFile() to the top of your loop to fix this problem.

A: You seem to be reusing the same object every time in projectfile. Even after it has been added to the list you have the same object being referenced in the list and in the variable so when you update its properties you update it in both places.
What you need is just to have a line at the beginning of your foreach saying something like:
projectfile = new ProjectFileObject();

This will create a new instance that is totally separate from the one already added to the list.
It should be noted that depending on what you have done with the projectfile object before a more complicated solution may be required but this highlights your basic problem.

A: Becasue you're adding the same instance each time, just overwriting its properties.  You need
projectfile = new WhateverClassNameProjectFileIs();

at the top of your innermost foreach loop.

A: It looks like you are creating a new string array foreach f in filename.
foreach (string f in fileName)
{
lstgAFPFileInfo = GetFilesFromSourceServer(new string[] { f }, ServerpathID, SearchOption.TopDirectoryOnly).ToList();

Thus, each iteration through the foreach, only the value of f at that time is created in the array.  Try instantiating the array outside of your loop and then adding your value f inside.


text:
Q: How can I combine numbers into strings in R? I have a data frame with numbers resembling:
df$X1    df$X2

.9     1.442

How could I use elements from this data frame to create labels for a confidence intervals that will be nicely formatted string:
(0.90, 1.42)

I'm lost somewhere between paste, as.character and c() and nothing seems to work :/

A: How about something like:
paste("(",df$X1,",",df$X2,")",sep="")

In your example, it looks like you might want to round your numbers, but the rounding is incorrect. Do you want a certain number of digits after the decimal point?
Also, "1" and "2" are frowned upon as names in a data.frame - see ?make.names
EDIT:
To round in cases like this, I like using formatC():
paste("(", formatC(df$X1, digits = 2, format = "f"), ",",
  formatC(df$X2, digits = 2, format = "f"), ")", sep = "")

However, if there are values less than .005, note that they will end up being 0.00.

A: +1 to @BenBarnes, I just want to add 1 small point.  In addition to (or in place of) formatC() you can use round(df$X1, digits=2).  You may find round to be simpler than formatC().  Moreover, this won't have any effect on the status of the output as being character in mode.


text:
Q: Xamarin Execute SQLite Query without knowing tablemapping or classes I currently writing an android app with C#/Xamarin. The App uses a local SQLite Database. There i want to execute a query which is written in the app.
The Tables are created through classes like this one:
class TestClass
{
    [PrimaryKey, AutoIncrement, Column("id")]
    public int Id { get; set; }
    [NotNull, Column("messagetext")]
    public string MessageText { get; set; }
    [Column("messagetype")]
    public int MessageType { get; set; }

    public TestClass(string mText, int mType)
    {
        MessageText = mText;
        MessageType = mType;
    }
}

The Database has multiple Tables.
The function

DBConnection.Execute("this is a query")

only executes the Query.
Since I need to get a Result, i should use

DBConnection.Query

but while programming, I don't know what tables the query selects, joins...
The Query Function requires a TableMapping or Class.
Is there a way to execute a query and get a result without knowing a tablemapping or something else?
Thanks.

A: The generic parameter on the overloaded Query method indicates what type of value you want to return from the query.
For instance, say you want to select only the Id field from every row in your TestClass table. Since Id is an int the method call would look like this:
List<int> testIds = DBConnection.Query<int>("SELECT Id FROM TestClass");


text:
Q: Why is a Variable declared as NVARCHAR(MAX) dropping chunks of the string? For whatever reason, a query is being built as a string and passed off to be executed by another stored procedure.
The query is massive.
Over a thousand lines, and we've run into an issue that requires me to debug it.
The query is being built into a declared NVARCHAR(MAX) variable, but something odd is happening when I print it off using the following -
WHILE @Printed < @ToPrint BEGIN
    PRINT(SUBSTRING(
        @sql, @Printed, 4000))
    SET @Printed = @Printed + 4000
    PRINT('Printed: ' + CONVERT(VARCHAR, @Printed))
END

At a certain place in the printed message, it's just... dropping a chunk, and I don't understand why. NVARCHAR(MAX) should be able to hold War and Peace over 100 times, and this query is NOT War and Peace.
I know PRINT(...) has a limitation of only being able to print off 4000 characters at a time (hence the loop), but that doesn't explain why the @sql variable is just losing a chunk in places.
If it helps, specifically, the place where the chunk is dropping is about 1,600 characters after the first 4,000 characters are printed.
Why is it doing this? Am I missing setting a system variable at the start of the query (like NOCOUNT or ARITHABORT? I don't even know what those do, or if they're even involved.

EDIT : MCVE : Here. To reproduce, copy-paste into Microsoft SQL Server Management Studio and hit 'F5'. The message printed will not include @sql in its entirety.

A: This is working fine for me:
DECLARE @sql nvarchar(max) =
    REPLICATE(CONVERT(nvarchar(max), N'a'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'b'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'c'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'd'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'e'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'f'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'g'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'h'), 4000)
  + REPLICATE(CONVERT(nvarchar(max), N'i'), 4000);

PRINT LEN(@sql);  -- characters
PRINT DATALENGTH(@sql); -- bytes
PRINT '';

DECLARE @Printed int = 1, @ToPrint int = LEN(@sql);

WHILE @Printed < @ToPrint BEGIN
    PRINT(SUBSTRING(
        @sql, @Printed, 4000))
    SET @Printed = @Printed + 4000
    PRINT('Printed: ' + CONVERT(varchar(11), @Printed)) -- *
END

* Always specify length.
Output is:
36000
72000

aaaaaaaaaa... 4000 As ...aaa
Printed: 4001
bbbbbbbbbb... 4000 Bs ...bbb
Printed: 8001
cccccccccc... 4000 Cs ...ccc
Printed: 12001
dddddddddd... 4000 Ds ...ddd
Printed: 16001
eeeeeeeeee... 4000 Es ...eee
Printed: 20001
ffffffffff... 4000 Cs ...fff
Printed: 24001
gggggggggg... 4000 As ...ggg
Printed: 28001
hhhhhhhhhh... 4000 Bs ...hhh
Printed: 32001
iiiiiiiiii... 4000 Cs ...iii
Printed: 36001

So, I think the problem is elsewhere. In any case, this is a really sloppy way to validate the contents of dynamic SQL. Instead I would do:
SELECT CONVERT(xml, @sql);

Then you can click on the output cell and it opens in an XML text editor for review (you can then copy and paste that output into a query window if you want IntelliSense or any chance in executing, but you'll have to replace encoded characters like > --> >. I talk about this approach (and another one) here:

*

*Validate the contents of large dynamic SQL strings
If you insist on doing it this bricklaying way, perhaps there is some kind of non-printing or string-termination character that's at that point. If you say it is around character 5,600 then you could do:
DECLARE @i int = 5550, @c nchar(1);
WHILE @i <= 5650
BEGIN
  PRINT '';
  SET @c = SUBSTRING(@sql, @i, 1);
  PRINT '------   ' + RTRIM(@i) + '------:';
  PRINT 'Raw:     ' + @c;
  PRINT 'ASCII:   ' + ASCII(@c);
  PRINT 'UNICODE: ' + UNICODE(@c);
  SET @i += 1;
END

You should be able to scan down and match the last sequence of characters you see in the broken print output. Then look for anything where the Raw: line is empty and the ASCII: line is anything other than typical (9, 10, 13, 32).
But I don't think this is the problem. I'll go back to an earlier comment where I suggested that the string itself is the problem. In the question, you mention @sql, but don't show how it's populated. I would bet that some string you're adding to that is getting truncated. Some things to look out for:

*

*Intermediate variables/parameters declared as varchar/nvarchar but with no length (which sometimes leads to silent truncation at 1 character, and sometimes 30):
  DECLARE @sql nvarchar(max) = N'SELECT * FROM dbo.table ';
  DECLARE @where nvarchar = N'WHERE some condition...';
  SET @sql += @where;
  PRINT @sql;

Output:
  SELECT * FROM dbo.table W

*Intermediate variables/parameters declared as varchar/nvarchar but too short (which leads to silent truncation at whatever the declaration is):
  DECLARE @sql nvarchar(max) = N'SELECT * FROM dbo.table ';
  DECLARE @where nvarchar(10) = N'WHERE some condition...';
  SET @sql += @where;
  PRINT @sql;

Output:
  SELECT * FROM dbo.table WHERE some

*Explicit CONCAT with NULL, which leads to silently dropping any NULL input):
  DECLARE @sql nvarchar(max) = N'SELECT * FROM dbo.table ';
  DECLARE @where nvarchar(32);
  DECLARE @orderby nvarchar(32) = N' ORDER BY col1';
  SET @sql = CONCAT(@sql, @where, @orderby);
  PRINT @sql;

Output:
  SELECT * FROM dbo.table  ORDER BY col1

*Not using the N prefix when concatenating Unicode string literals > 4000 characters (example here):
  DECLARE @sql nvarchar(max) = '';

  SET @sql = @sql + '... literally 4001 characters ...';

The output here (as shown in the example) will be truncated at 4,000 characters. However if you define your strings properly, this won't happen:
  DECLARE @sql nvarchar(max) = N'';

  SET @sql = @sql + N'... literally 4001 characters ...';

These things can be hard to spot in overly complex dynamic SQL generation, so it's never a bad idea to simplify and try any way you can to divide & conquer the major components in the eventual string. Based on the repro you attempted I would almost certainly guess it is the "variable declared too short" symptom. Safest is to ensure every input to a dynamic SQL string should be declared as nvarchar(max); no real good reason to use anything else except for entity names which are constrained by metadata anyway.


text:
Q: cocos2d. How to create a popup modal dialog (with CCLayer) I need to make a modal dialog(inherited from CCLayer) that is showing in the center of the main layer.
While it is showing, you can not press any other button outside the dialog.
Just like a normal modal window in MS Windows System.
The problem is that I can not figure out how to disable the mainlayer's touch events while the dialog is showing.
Any help would be aprreciated.

A: Just set
self.isTouchEnabled = NO;

in the main layer while the popup is displayed. Then later set it back to YES.

A: This works for me in Cocos2d-x but can be adapted to Cocos2d too.
I've change setParent to:
virtual void setParent(CCNode* parent)
{
    CCLayerColor::setParent(parent);

    if (parent)
    {
        saveTouchesRecursive(parent);

        for (unsigned int i=0; i<mSavedTouches.size(); i++)
        {
            CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(mSavedTouches[i]);
        }
    }
    else
    {
        for (unsigned int i=0; i<mSavedTouches.size(); i++)
        {
            CCStandardTouchDelegate* standardTouchDelegate =  dynamic_cast<CCStandardTouchDelegate*>(mSavedTouches[i]);
            CCTargetedTouchDelegate* targetedTouchDelegate =  dynamic_cast<CCTargetedTouchDelegate*>(mSavedTouches[i]);

            CCLayer* layer =  dynamic_cast<CCLayer*>(mSavedTouches[i]);

            if (layer)
            {
                layer->registerWithTouchDispatcher();
            }
            else if (standardTouchDelegate)
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addStandardDelegate(mSavedTouches[i], 0);
            }
            else if (targetedTouchDelegate)
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0,  false);
            }
            else
            {
                CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(mSavedTouches[i], 0,  false);
            }
        }
    }
}

And added the following recursive code to save the touch delegates so I can restore them when the dialog dismissed:
std::vector<CCTouchDelegate*> mSavedTouches;
void saveTouchesRecursive(CCNode* node)
{
    if (node != this)
    {
        CCTouchDelegate* touchDelegate = dynamic_cast<CCTouchDelegate*>(node);
        if (touchDelegate)
        {
            CCTouchHandler* handler = CCDirector::sharedDirector()->getTouchDispatcher()->findHandler(touchDelegate);

            if (handler)
            {
                mSavedTouches.push_back(touchDelegate);
             }
        }

        for (unsigned int i=0; i<node->getChildrenCount(); i++)
        {
            CCNode* childNode = dynamic_cast<CCNode*>(node->getChildren()->objectAtIndex(i));

            if (childNode)
            {
                saveTouchesRecursive(childNode);
            }
        }
    }
}


text:
Q: Creating a new table in iWork numbers on a specific sheet using applescript I am having trouble creating a new table on a specific sheet using Applescript unless the sheet I want insert the new table in is either new or current selected.
The general form of the code I am using is:
    tell application "Numbers"
    tell document 1
    tell sheet "This is the sheet I want to use"
    make new table with properties {name:"A new table"}
    end tell
    end tell
    end tell

Has anyone had any more success at achieving this? This looks to me like a bit of a problem for some advanced spreadsheet scripts in Numbers.

A: OK. My first answer was accepted and could not be deleted, but was inadequate, so I have decided to edit it and add some code which really does solve the problem!
This code comes via Yvan Koenig, who credits Nigel Garvey. Both are active on the applescript-users list, which is excellent, by the way, not least because of the activity of these two gentlemen, and so many other great AppleScripters.
It relies on GUI scripting (which is always a horrible thing to have to fall back on, but it's what we've got).
The call to my activateGUIscripting() may cause a prompt for an admin password to appear. If you absolutely know that you have GUI scripting enabled (System Prefs->Universal Access->Enable Access for Assistive Devices) - then you can omit this line.
The next two lines are just example calls, so you need a sheet called "Sheet 1" for these example calls to work.
This will allow you to create a table in any sheet in any document, regardless of what is selected or frontmost.
--EXAMPLE CALLS
my activateGUIscripting()
my selectsheet(1, "Sheet 1")
my createNewTable(1, "Sheet 1", "myNewTable", 69, 13)

--NUMBERS UTILS
on createNewTable(dName, sName, newTable, nb_rows, nb_columns)
    tell application "Numbers" to tell document dName to tell sheet sName
        make new table with properties {name:newTable, row count:nb_rows, column count:nb_columns}
    end tell
end createNewTable

--=====
on activateGUIscripting()
    (* to be sure than GUI scripting will be active *)
    tell application "System Events"
        if not (UI elements enabled) then set (UI elements enabled) to true
    end tell
end activateGUIscripting
--=====
(*
==== Uses GUIscripting ====
 *)
on selectsheet(theDoc, theSheet)
    script myScript
        property listeObjets : {}
        local maybe, targetSheetRow
        --+++++
        -- set log_report to "point 2 : " & (current date) & return
        --+++++
        tell application "Numbers"
            activate
            set theDoc to name of document theDoc (* useful if the passed value is a number *)
            tell document theDoc to set my listeObjets to name of sheets
        end tell -- "Numbers"…

        set maybe to theSheet is in my listeObjets
        set my listeObjets to {} -- So it will not be saved in the script *)
        if not maybe then
            error "The sheet "" & theSheet & "" is unavailable in the spreadsheet "" & theDoc & "" !"
        end if -- not maybe

        set maybe to 5 > (system attribute "sys2")
        tell application "System Events" to tell application process "Numbers"
            tell outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window theDoc
                if maybe then (* macOS X 10.4.x
'(value of attributes contains 0)': '(value of attribute "AXDisclosureLevel" is 0)' sometimes works in Tiger, sometimes not.
The only possible instances of 0 amongst the attributes are the disclosure level of a sheet row and the index of the first row, which represents a sheet anyway.
Another possibility is '(value of attribute -1 is 0)', which makes me uneasy. *)
                    set targetSheetRow to first row where ((value of attributes contains 0) and (value of first static text is theSheet))
                else (* macOS X 10.5.x or higher *)
                    set targetSheetRow to first row where ((value of attribute "AXDisclosureLevel" is 0) and ((groups is {}) and (value of first static text is theSheet)) or (value of first group's first static text is theSheet))
                end if -- maybe…
                (*
Handler modified to accomodate sheets requiring a lot of time to get the focus
*)
                tell targetSheetRow to set value of attribute "AXSelected" to true
                set cnt to 0
                repeat (*
Must way that Numbers becomes ready to receive the value *)
                    try
                        tell targetSheetRow to set value of attribute "AXDisclosing" to true
                        exit repeat
                    on error
                        set cnt to cnt + 1
                        delay 0.5 -- half a second
                    end try
                end repeat
            end tell -- outline…
        end tell -- "System Events"…
        --+++++
        -- set log_report to log_report & "point 3, cnt = " & cnt & return & (current date) & return
        --+++++
        tell application "Numbers" to tell document theDoc to tell sheet theSheet to tell table 1
            with timeout of 20 * 60 seconds (*
WITH this setting, the script will be able to wait 20 minutes for the asked value.
I hope that the document will not be so huge that this delay prove to be too short. *)
                value of cell "A1"
            end timeout
        end tell -- "Numbers"…
        --+++++
        -- set log_report to log_report & "point 4 : " & (current date) & return
        --+++++
        tell application "System Events" to tell application process "Numbers" (*
Do the trick one more time to be sure that the sheet is open *)
            tell targetSheetRow to set value of attribute "AXDisclosing" to true
        end tell -- "System Events"…
        --+++++
        -- return log_report & "point 5 : " & (current date) & return
        --+++++
        (*
End of the modified piece of code
*)
    end script
    run myScript
end selectsheet


text:
Q: select_tag doesn't save the selected option I'm new in web development & Rails. I've been struggling to understand why my form is not getting saved completely. Here is the code I'm using:

    <%= f.label :type %>

    <%= select_tag(:type, options_for_select([['Verb', 'Verb'], ['Adjective', 'Adjective'], ['Noun','Noun'],['Preposition','Preposition'],['Article','Article'],['Adverb','Adverb']])) %>

    <%= f.label :category %>

    <%= select_tag "category",
                   "<option>Appliances</option>
                    <option>Clothes and Accessories</option>
                    <option>Colours</option>
                    <option>Communication and Technology</option>
                    <option>Documents and Texts</option>
                    <option>Education</option>
                    <option>Entertainment and Media</option>
                    <option>Family and Friends</option>
                    <option>Food and Drink</option>
                    <option>Health, Medicine and Exercise</option>
                    <option>Hobbies and Leisure</option>
                    <option>House and Home</option>
                    <option>Measurements</option>
                    <option>Personal Feelings, Opinions and Experiences (adjectives)</option>
                    <option>Places: Buildings</option>
                    <option>Places: Countryside</option>
                    <option>Places: Town and City</option>
                    <option>Services</option>
                    <option>Shopping</option>
                    <option>Sport</option>
                    <option>The Natural World</option>
                    <option>Time</option>
                    <option>Travel and Transport</option>
                    <option>Weather</option>
                    <option>Work and Jobs</option>".html_safe %>

PS: I've kept two different methods I tried to use.

A: use f.select instead of select_tag.
f.select(:type, [['Verb', 'Verb'], ['Adjective', 'Adjective'], ['Noun','Noun'],['Preposition','Preposition'],['Article','Article'],['Adverb','Adverb'])

or if you are using form_for and passing an object then you can also do it as follows.
select_tag(:type, options_for_select([['Verb', 'Verb'], ['Adjective', 'Adjective'], ['Noun','Noun'],['Preposition','Preposition'],['Article','Article'],['Adverb','Adverb']],f.object.type))

we are passing a value of type from actual object into option for select.
As you are using option_for_select it expects that you send selected value as a second parameter.

A: options_for_select also takes second parameter which is the selected value.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select
# this will show Preposition selected
options_for_select([['Verb', 'Verb'], ['Adjective', 'Adjective'], ['Noun','Noun'],['Preposition','Preposition'],['Article','Article'],['Adverb','Adverb']], 'Preposition')

For future reference, please always specify Rails version while posting question.
I noticed you are using f.label, in which case you might also want to take a look at http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
HTH

A: For the first one, you should use f.select instead of select_tag, rails tags are helpers for generate html elements, but in this case you need an item that is linked to your form, so you use the form helper for select instead.
For the other example, i'm not entearly sure if it will work like that, but try with the same idea, you should found that the select is passed to your controllers, also use the symbol name instead the string name, meaning :category instead "category",  if you want to have a phrase like "select a category...." add another option at the end with :prompt => "select a category...", hope it helps and look at Ryan Bates site, is an excellent place to learn rails


text:
Q: Inherited MS Access Database, Tracking Sources of Queries I have just inherited a database at my new company.  Old DB owner left no good documentation and queries very hard to keep track of.  Looking for programmatic answer to track sources of fields in every query (what table it come from).  Prefer something can be exported to Excel to study, Access visualization is no good.  Am familiar with VBA.

A: This is pretty messy but could save you time collecting each query's SQL code. The following code exports all SQL stored in the QueryDefs collection into a text file. I have it splitting the code with a space delimiter, but a comma might be preferable. The data will not be normalized, I don't have the time to go to that level of complexity. Just make sure to update strPath before you execute. Hopefully this helps.
Sub PullQuerySQL()

    Dim dbs As Database
    Dim i As Integer
    Dim fso As Object
    Dim oFile As Object
    Dim varParse() As String
    Dim element As Variant
    Dim strPath As String

    strPath = ".txt"

    Set dbs = CurrentDb()
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFile = fso.CreateTextFile(strPath)

    For i = 0 To dbs.QueryDefs.Count - 1
        oFile.WriteLine dbs.QueryDefs(i).Name
        varParse = Split(dbs.QueryDefs(i).SQL, " ")
        For Each element In varParse
            oFile.WriteLine element
        Next element
    Next i

    oFile.Close

    Set oFile = Nothing
    Set fso = Nothing
    Set dbs = Nothing

End Sub

A: I have been through this with many inherited databases.  I find it extremely helpful to create an Access table with the fields and the tables/queries that they come from.  Try this code below.  It will prompt you for the name of the query that you are looking to "map" as I call it.  It will then create a new table named "queryName Definitions".
Option Compare Database

Public Sub MapQuery()

 Dim strQueryName As String
 Dim rst As DAO.Recordset
 Dim fld As Field
 Dim strSource As String
 Dim strField As String
 Dim strValue As String
 Dim strSQL1 As String
 Dim strSQL2 As String
 Dim booExists As Boolean

strQueryName = InputBox("Please enter the name of the query that you are looking to map")

   Set rst = CurrentDb.OpenRecordset(strQueryName)

On Error GoTo error1
    booExists = IsObject(CurrentDb.TableDefs(strQueryName & " Definitions"))
    DoCmd.DeleteObject acTable, strQueryName & " Definitions"
continue:
    strSQL1 = "CREATE TABLE [" & strQueryName & " Definitions]" & " (FieldName CHAR, SourceName CHAR);"
    DoCmd.RunSQL (strSQL1)
    DoCmd.SetWarnings False
    For Each fld In rst.Fields

    strField = fld.Name
    strSource = fld.SourceTable

Debug.Print strValue

    strSQL2 = "INSERT INTO [" & strQueryName & " Definitions]" & "(FieldName, SourceName) VALUES(""" & strField & """, """ & strSource & """);"

    DoCmd.RunSQL (strSQL2)
    Next fld

error1:
    If Err.Number = 3265 Then
        Resume continue
    Else
    MsgBox Err.Description

    End If

    DoCmd.SetWarnings True
    Exit Sub

    DoCmd.SetWarnings True
End Sub


text:
Q: Adding custom markers to the mapbox gl I would like to add a custom marker to my map. I am using a mapbox gl script.
The only documentation that I found related to this topic is this one https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/.
I tried to customize given example and I managed to add a marker and modify it a little changing the size, but since I don't understand all the parameters, I don't know how to add my own marker. Is there any documentation that is more detailed?
Here is my code:
 <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoiYWl3YXRrbyIsImEiOiJjaXBncnI5ejgwMDE0dmJucTA5aDRrb2wzIn0.B2zm8WB9M_qiS1tNESWslg';
    var map = new mapboxgl.Map({
        container: 'map', // container id
        style: 'mapbox://styles/aiwatko/cipo0wkip002ddfm1tp395va4', //stylesheet location
        center: [7.449932,46.948856], // starting position
        zoom: 14.3, // starting zoom
        interactive: true
    });

    map.on('load', function () {
    map.addSource("markers", {
        "type": "geojson",
        "data": {
            "type": "FeatureCollection",
            "features": [{
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [7.4368330, 46.9516040]
                },
                "properties": {
                    "title": "Duotones",
                    "marker-symbol": "marker",

                }
            }]
        }
    });

    map.addLayer({
        "id": "markers",
        "type": "symbol",
        "source": "markers",
        "layout": {
            "icon-image": "{marker-symbol}-15",
            "icon-size": 3
        }
    });
});
</script>

Thanks in advance!
Oktawia

A: There are two ways to customize markers in Mapbox.
Raster Markers in Mapbox
See this link on Mapbox.com for Custom marker icons.  That example shows how to use a .png as a marker.
SVG Markers in Mapbox
You are pretty close to modifying the icons, but take some time to familiarize yourself with the parameters.
The icon-image may be the harder one to understand.  It takes the property "marker-symbol": "marker" from the GeoJson, and "icon-image": "{marker-symbol}-15", to create the final result of marker-15.
This brings up a further question: where/how are the markers defined?!?
The markers also come from Mapbox and are called Maki Icons.  You can change the "marker-symbol" to aquarium or cafe to see the results.
From the Mapbox GL Style Reference

*

*icon-size — Scale factor for icon. 1 is original size, 3 triples the size.

*icon-image — A string with {tokens} replaced, referencing the data property to pull from.


text:
Q: Statistical mechanics definition of temperature as the average kinetic energy In most text books of statistical physics, temperature is defined as :
$$T=\left(\frac{\partial E}{\partial S}\right)_V$$
where $V$ stands for any external variable(s) the system's Hamiltonian depends on.
However, it is often suggested that the temperature is also the average kinetic energy per degree of freedom as in the Generalized Helmotz theorem. Is this second definition always valid? If so, how can you prove or explain they are the same? Are there some condition for it? How do you relate it to the definition above?

A: No, they're not always the same. Temperature is not a measure of energy but of uncertainty. This is made clear by a two level system with possible energies $0,\epsilon$. The mean energy $\langle E \rangle := U \in [0,\epsilon]$ is confined to a bounded set whereas the temperature can be anything you like (including negative values, corresponding to $U > \epsilon/2$).
In this setup, the temperature is a measure of how uncertain we are about which of the two states the system is in. The probabilities of the two states are:
$$ p_\alpha = \frac{e^{-E_\alpha/T}}{1+e^{-\epsilon/T}}$$
Perfect uncertainty ($p_\alpha=1/2$) corresponds to $T=\infty$. Meanwhile perfect certainty corresponds to $T=0$ - you know exactly what state the system is in.
(Note: there are two cases of 'perfect certainty' - either its definitely in the ground state or definitely excited. These both correspond to $T=0$ but from different directions. Taking a positive temperature and lowering it to $T=0^+$, you reach $U=0$ and taking a negative temperature and raising to $T=0^-$ you reach $U=\epsilon$.)

A: You ask when it is true that
$$ \left\langle \frac{{p}_i^2}{2m_i} \right\rangle_{t} = \frac{1}{2}k_B \left(\frac{\partial S}{\partial E}\right)^{-1} \tag{1}$$
for a Hamiltonian system.
If the Hamiltonian can be written as
$$\mathcal{H} = U(\mathbf{q}) + \sum_i \frac{p_i^2}{2m_i} \tag{2} $$
the equipartition theorem implies that
$$ \left\langle \frac{{p}_i^2}{2m_i} \right\rangle_{eq} = \frac{1}{2}k_B \left(\frac{\partial S}{\partial E}\right)^{-1} \tag{3}$$
where the average is taken for a microcanonical ensemble. There are thus two reasons that (1) might fail to hold:

*

*We might have a Hamiltonian which cannot be written in the form of (2)

*We might find that $ \left\langle \cdot\right\rangle_{eq} \ne \left\langle \cdot\right\rangle_{t} $
One can show that $ \left\langle \cdot\right\rangle_{eq} = \left\langle \cdot\right\rangle_{t} $ whenever both averages are well-defined and all conserved quantities can be written as functions of the energy. The latter is related to the requirement in the generalized Helmholtz theorem that certain hypersurfaces be metrically indecomposable.
Examples:
To see an example of the first reason (1) might not hold, consider a charged particle in an electromagnetic field. We have
$$ \mathcal{H} = q\phi(\mathbf{r}) + \frac{1}{2m}\sum_i (p_i - qA_i(\mathbf{r}))^2  $$
This has terms linear in $\mathbf{p}$, so instead of something like (3) the equipartition theorem leaves us with
$$ \left\langle p_i \cdot \frac{1}{m}(p_i - qA_i(t,\mathbf{r}))\right\rangle_{eq} = k_B T $$
or
$$ \left\langle \frac{p_i^2}{2m} \right\rangle_{eq} = \frac{1}{2} k_B T + \left\langle \frac{p_i \cdot qA_i(\mathbf{r})}{2m} \right\rangle_{eq}$$
To see the second reason in action, consider the case of a particle in a one-dimensional potential $U(q)$ with two local minima $U_1 \gg U_2$ separated by a barrier of height $U_3$ at $q = 0$. Consider a particle with energy $E$ such that $U_1 < E < U_3 $. The canonical ensemble is mostly concentrated in well 2, so
$$\left\langle \frac{p^2}{2m}\right\rangle_{eq} \approx E - U_2 $$
The equipartition theorem does apply here, so this tells us $$ \frac{1}{2}k_B \left(\frac{\partial S}{\partial E}\right)^{-1} \approx E - U_2 $$
If the particle is initially located in well 1 it will stay there for all time, and so
$$\left\langle \frac{p^2}{2m}\right\rangle_{t} \approx E - U_1 $$
and thus (1) does not hold. This observation corresponds to the fact that we can define a conserved quantity like
$$
C(q,p) =
\begin{cases}
1 & \frac{p^2}{2m} + U(q) < U_3 \wedge q < 0 \\
2 & \frac{p^2}{2m} + U(q) < U_3 \wedge q > 0 \\
3 & \frac{p^2}{2m} + U(q) \geq U_3
\end{cases}
$$
which cannot be written as a function of energy alone.
This conserved quantity is rather strange. Another, more natural example is that of two noninteracting particles in a one-dimensional box. $p_1^2$ and $p_2^2$ are each conserved separately, and so it turns out that $\langle p_1^2 \rangle_{eq} \ne \langle p_1^2 \rangle_t $.

A: Let $\Omega(E,N,V)$ be the number of microstates with energy $E$, $N$ particles and volume $V$. Recall that $S=k \ln \Omega$. It is actually more convenient to define temperature as $\frac{1}{T}=(\frac{\partial S}{\partial E})_{V,N}$.
Let $\Phi(E)$ denote the total number of possible quantum states of a system which are characterised by energies less then $E$. Assume that we have now a system described by $f$ quantum numbers, then the energy per degree of freedom $\epsilon$ is roughly $\epsilon \approx E/f$.
Let now, $\Phi_1(\epsilon)$ be the total number of possible values which can be assumed by one particular quantum number when it contributes an amount $\epsilon$ or less to a system. It can be shown $\Phi_1(\epsilon)$ that is roughly propositional to $\epsilon$, and $\Phi(E) \approx \Phi_1(\epsilon)^f$.
Moreover in the range of energies between $E$ and $E+\delta E$, we have $\Omega(E)\approx \Phi(E)-\Phi(E+\delta E)\approx \frac{\partial \Phi}{\partial E} \delta E \approx \Phi_1^{f-1}\frac{\partial \Phi_1}{\partial \epsilon} \delta E$. Since $f$ is usually very large number (about $10^{24}$), we get $\ln \Omega \approx f \ln \Phi_1$, it follows that $\Omega \approx \Phi_1^f$ which is propositional to $E^f$. Thus $\ln \Omega \approx f\ln E + constant$. Thus when $E\approx \overline{E}$ (the average energy), we get $1/T = kf /\overline{E}$. So the temperature is indeed proportional to the average energy per degree of freedom. If the system has negligible interactions then $\overline{E}$ is the average kinetic energy.
It is important to keep in mind that in the derivation above we assumed that our system has no upper bound on the possible energy. In fact this is the case for the systems where one takes kinetic energy of particles into account. However if one focuses instead only on spin degrees of freedom, then when all the spins are lined up anti-parallel to the field a maximum of energy is reached.
A good exercise would be to consider the case of an ideal gas. In this case you get very simple analytic expressions. If you are interested you to learn more you may take a look at "Fundamentals of statistical and thermal physics" by Reif and also "Statistical Mechanics" by Pathria and Beale.


text:
Q: Form containing with ViewComponent I couldn't figure out how to use ViewComponent inside form
The form is rendered correctly (value in the dropdown), but the model binding, when posting form, fail
This is the view
<form asp-action="" method="post">

        <vc:periodi model="@(Model.Periodi)"></vc:periodi>

This is the ViewComponent

@(Html.Kendo().DropDownListFor(a => a.Anno)
                    .DataTextField("Text")
                    .DataValueField("Value")
                    .BindTo(Model.Anni)
                    .HtmlAttributes(new { style = "width: 100%" }))

No matter what I choose in the dropdown, the variable Anno inside the Object Periodi of the Model is null
I checked the rendered HTML
<input id="Anno" name="Anno" ...

I think, based on my experience with MVC, that should be something like "Periodi.Anno" for the model binder to work.
Any suggestion?

A: As your experience, the name should be Periodi.Anno to bind the ViewComponent property.
As my test with input tag like below:
<input asp-for="Name" name="MVCSubModel.Name" class="form-control" />

I suggest you try :
@(Html.Kendo().DropDownListFor(a => a.Anno)
                .DataTextField("Text")
                .DataValueField("Value")
                .BindTo(Model.Anni)
                .HtmlAttributes(new { style = "width: 100%"; name = "Periodi.Anno" }))


text:
Q: Cannot connect to kafka which is outside of network I'm trying to connect my job inside a container which sends events to kafka cluster in another container.
No matter what i've tried, i can't send the event to kafka topic
I 've tried telnet and kafkacat to the address listener port of my kafka, everything works just fine:
Telnet output
Kafkacat output
This is my job compose file, "172.16.33.91" is my local ip address:
version: '3'
services:
    events-processor:
        build:
            context: ./events-processor
        extra_hosts:
            - "host:172.16.33.91"
        restart: unless-stopped

This is my job code, which sends data from 1 -> 1000 to a existed topic num-test:
from time import sleep
from json import dumps
from kafka import KafkaProducer

if __name__=="__main__":
    producer = KafkaProducer(bootstrap_servers=['host:9093'],
                             value_serializer=lambda x: dumps(x).encode('utf-8'))
    for e in range(1000):
        data = {'number' : e}
        producer.send('numtest', value=data)
        print(data)
        sleep(5)

This is my kafka-zookeeper compose file:
version: '3'

services:
    zookeeper:
        image: confluentinc/cp-zookeeper
        environment:
            ZOOKEEPER_CLIENT_PORT: 2181
            ZOOKEEPER_TICK_TIME: 2000
        volumes:
            - zk-data:/var/lib/zookeeper/data
            - zk-logs:/var/lib/zookeeper/log
            - secrets:/etc/zookeeper/secrets
        restart: unless-stopped

    kafka:
        image: confluentinc/cp-kafka
        depends_on:
            - zookeeper
        ports:
            - "9093:9093"
        environment:
            KAFKA_BROKER_ID: 1
            KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
            KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:9092,EXTERNAL://:9093
            KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
            KAFKA_LISTENERS: INTERNAL://:9092,EXTERNAL://:9093
            KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
            KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
        volumes:
            - kafka-data:/var/lib/kafka/data
            - secrets:/etc/kafka/secrets
        restart: unless-stopped

volumes:
    zk-logs: {}
    zk-data: {}
    kafka-data: {}
    secrets: {}

Anyone have any idea what've i done wrong? Any help appreciated!!!

A: I remembering encountering a similar issue with connectivity. Turns out, for your container to be able to access the ports on your host machine, you may need to add additional rules to your firewall to open it up.
For example with iptables, you can add a rule like the below to allow your host machine to accept requests from your docker containers.
-A INPUT -i docker0 -j ACCEPT

Alternatively, you can put your job container on the same docker network as your kafka/zookeeper. Either by putting your application in the same docker-compose file, or using a common external docker network.

A: If there is a better place this information should be put, or keywords you're missing to find the solutions, let the community know
Multiple blogs are written on this already
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:9092,HOST://localhost:9093
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,HOST:PLAINTEXT
KAFKA_LISTENERS: INTERNAL://0.0.0.0:9092,HOST://0.0.0.0:9093

*

*Using ://:port address will only listen to the local hostname, container or not

*You must listen to external connections by binding to all interfaces, 0.0.0.0

*You must advertise internally and/or any external hostnames

A: Here is another Working Sample :
version: '2'
services:
  zookeeper1:
    image: confluentinc/cp-zookeeper:$CP_VERSION
    container_name: zookeeper1
    hostname: zookeeper1
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_SERVER_ID: 1
      ZOOKEEPER_SERVERS: "zookeeper1:22888:23888;zookeeper2:22888:23888;zookeeper3:22888:23888"
    ports:
      - 2181:2181
    volumes:
      - ./data/zoo-1/data:/var/lib/zookeeper/data
      - ./data/zoo-1/log:/var/lib/zookeeper/log

  zookeeper2:
    image: confluentinc/cp-zookeeper:$CP_VERSION
    container_name: zookeeper2
    hostname: zookeeper2
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_SERVER_ID: 2
      ZOOKEEPER_SERVERS: "zookeeper1:22888:23888;zookeeper2:22888:23888;zookeeper3:22888:23888"
    ports:
      - 2182:2181
    volumes:
      - ./data/zoo-2/data:/var/lib/zookeeper/data
      - ./data/zoo-2/log:/var/lib/zookeeper/log

  zookeeper3:
    image: confluentinc/cp-zookeeper:$CP_VERSION
    container_name: zookeeper3
    hostname: zookeeper3
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
      ZOOKEEPER_SERVER_ID: 3
      ZOOKEEPER_SERVERS: "zookeeper1:22888:23888;zookeeper2:22888:23888;zookeeper3:22888:23888"
    ports:
      - 2183:2181
    volumes:
      - ./data/zoo-3/data:/var/lib/zookeeper/data
      - ./data/zoo-3/log:/var/lib/zookeeper/log

  kafka1:
    image: confluentinc/cp-kafka:$CP_VERSION
    container_name: kafka1
    hostname: kafka1
    depends_on:
      - zookeeper1
      - zookeeper2
      - zookeeper3
    ports:
      - 9091:9091
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper1:2181,zookeeper2:2181,zookeeper3:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_LISTENERS: INTERNAL://:29092,OUTSIDE://:9091
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka1:29092,OUTSIDE://kafka1:9091
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_LOG_DIRS: /var/lib/kafka/logs

  kafka2:
    image: confluentinc/cp-kafka:$CP_VERSION
    container_name: kafka2
    hostname: kafka2
    depends_on:
      - zookeeper1
      - zookeeper2
      - zookeeper3
    ports:
      - 9092:9092
    environment:
      KAFKA_BROKER_ID: 2
      KAFKA_ZOOKEEPER_CONNECT: zookeeper1:2181,zookeeper2:2181,zookeeper3:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_LISTENERS: INTERNAL://:29092,OUTSIDE://:9092
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka2:29092,OUTSIDE://kafka2:9092
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_LOG_DIRS: /var/lib/kafka/logs

  kafka3:
    image: confluentinc/cp-kafka:$CP_VERSION
    container_name: kafka3
    hostname: kafka3
    depends_on:
      - zookeeper1
      - zookeeper2
      - zookeeper3
    ports:
      - 9093:9093
    environment:
      KAFKA_BROKER_ID: 3
      KAFKA_ZOOKEEPER_CONNECT: zookeeper1:2181,zookeeper2:2181,zookeeper3:2181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,OUTSIDE:PLAINTEXT
      KAFKA_LISTENERS: INTERNAL://:29092,OUTSIDE://:9093
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka3:29092,OUTSIDE://kafka3:9093
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_LOG_DIRS: /var/lib/kafka/logs

dont forget to edit /etc/hosts and the proper hostnames to ba able to work with above kafka cluster outside the Docker.
my /etc/hosts file is shown below :
127.0.0.1       localhost
127.0.0.1       kafka1
127.0.0.1       kafka2
127.0.0.1       kafka3


text:
Q: Spring security returns 401, On sending date as input to the rest controller @Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsInfoService userDetailsService;

    @Autowired
    private CustomLoginAuthenticationProvider authenticationProvider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
        auth.userDetailsService(userDetailsService);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring()
        .antMatchers("/api/user/authenticate/**")
        .antMatchers("/api/user/**")
        .antMatchers("/api/master/**")
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }

   @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
    }

   /* @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
    private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }

    }*/

}

This is my spring security configuration in the application.
It works fine most of the scenarios, but not able to track one issue.
Whenever I call a web service with a date format spring security returns 401 error.
http://localhost:9190/nazouki/api/master/create

with input
{"orgId":"11","birthDate":"2020-04-20T20:00:00.000Z"}

without date it works fine.
Controller code
@RequestMapping(value = "master/create", method = RequestMethod.POST)
    public @ResponseBody ResultDecorator createMaster(@RequestBody  TuMasterDto tuMasterDto){       handler.resolveResult(masterService.createMaster(tuMasterDto), OperationEnum.SAVE);
    }

Exception has been thrown from the CustomAuthenticationEntryPoint in the spring security.
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final Logger log = LoggerFactory.getLogger(CustomAuthenticationEntryPoint.class);

    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException ae) throws IOException, ServletException {

        log.info("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");

    }
}

A: We can't say for sure unless we also have a look at the handler.resolveResult() and the masterService.createMaster() methods.
My initial assumption would be that you have a GlobalMethodSecurity configuration on one or both of these methods (or a code path that is used by them), and since you ignore the security for the path web.ignoring().antMatchers("/api/master/**"), there is no SecurityContext created and therefore you get that response.
As to why it behaves differently when you add the date than without, I'm not so sure myself. Maybe you have 2 implementations? something like this
public void handleRequest(Dto dto) {
   if(dto.getDate() != null) {
      doSomethingWithTheDate(dto.getDate());
   }
   // handle normally
}

@PreAuthorize("hasRole('ROLE_USER')")
public void doSomethingWithTheDate(Date date) {
   ...
}


text:
Q: How to call listener class in robot.api? I have a bunch of testsuites which are executed using robot.api.
For Example,
from robot.api import TestSuite,ResultWriter
tc_dict = {
            'test case #1' : 'Passed'
            'test case #2' : 'Failed'
           }
suite = TestSuite('tests_with_listener.robot')
for k,v in tc_dict.items():
    test = suite.tests.create(k)
    test.keywords.create('should be equal',args=(tc_dict[k],'Passed'))
result = suite.run(output=xml_fpath)

Is there any way in robot.api by which we can execute the following code?
robot -b debug.txt --listener <ListenerLibrary> tests_with_listener.robot

A: In the documentation for the robot.api the note following note can be found:

APIs related to the command line entry points are exposed directly via
  the robot root package.

The referred documentation is robot.run or robot.run_cli.

A: Finally, after going through robot framework source code I was able to get an answer. The solution is simple but it's not well-documented in robot.api docs.
From RF source code's run(settings=None, **options) method from TestSuite class

If options are used, their names are the same as long command line
          options except without hyphens, and they also have the same semantics.
          Options that can be given on the command line multiple times can be
          passed as lists like variable=['VAR1:value1', 'VAR2:value2'].
          If such an option is used only once, it can be given also as a single
          string like variable='VAR:value'.

from robot.api import TestSuite,ResultWriter
tc_dict = {
            'test case #1' : 'Passed'
            'test case #2' : 'Failed'
           }
suite = TestSuite('tests_with_listener.robot')
for k,v in tc_dict.items():
    test = suite.tests.create(k)
    test.keywords.create('should be equal',args=(tc_dict[k],'Passed'))
result = suite.run(xunit=xunit_fpath,report=html_fpath,log=log_fpath,listener='AllureReportLibrary.AllureListener')


text:
Q: When do missed shots and/or suppression shot destroy objects? Mostly, indoor, a miss shot, or suppression destroy the wall behind target.
Sometime it destroy something useful(like navi computer) Sometime, the shot just go into sky.
The chance go up when weapon get better (Laser, Plasma)
Is it random, or do we have any chance do this on purpose ? Like on ancient Xcom (i mean DOS version long ago), we can command troop to shot at wall to destroy it.

A: There are a few ways to deliberately destroy damageable terrain, but they involve grenades, rockets, properly timed destruction of Sectopods, Mechtoids, Ethereals or Cyberdisks or the MEC trooper's collateral damage special ability.
Missed shots' fire angle is randomly determined; if it hits something else the game determines then and there whether that type of weapons fire has the capability to destroy the object (or in the case of cars, set it on fire) and resolves on the spot.