Usage of ThreadPoolExecutor after extending

Question: According to Java concurrency in practice if we want to add logging, timing, monitoring  facility to ThreadPoolExecutor then we should extend it. Suppose if we extend it  like below:
// code taken from java concurrency in practice

public class TimingThreadPool extends ThreadPoolExecutor
{
private final ThreadLocal<Long> startTime
        = new ThreadLocal<Long>();
private final Logger log = Logger.getLogger("TimingThreadPool");
private final AtomicLong numTasks = new AtomicLong();
private final AtomicLong totalTime = new AtomicLong();

protected void beforeExecute(Thread t, Runnable r) {
    super.beforeExecute(t, r);
    log.fine(String.format("Thread %s: start %s", t, r));
    startTime.set(System.nanoTime());
}

protected void afterExecute(Runnable r, Throwable t) {
    try {
        long endTime = System.nanoTime();
        long taskTime = endTime - startTime.get();
        numTasks.incrementAndGet();
        totalTime.addAndGet(taskTime);
        log.fine(String.format("Thread %s: end %s, time=%dns",
                t, r, taskTime));
    } finally {
        super.afterExecute(r, t);
    }
}

protected void terminated() {
    try {
        log.info(String.format("Terminated: avg time=%dns",
                totalTime.get() / numTasks.get()));
    } finally {
        super.terminated();
    }
}
}

Here my doubt is how will you use this class, because if you create ExecutorService it always returns an instance of ThreadPoolExecutor. So how will u plug this class to show the loggings (need client code to use this).
Thanks in advance!!! Sorry if i made any mistake while mentioning the question.
Comment: `ExecutorService timedExecutor = new TimingThreadPool(...);` ?
Comment: "if you create ExecutorService" How do you usually create `ExecutorService`?
Comment: @assylias I have small doubt here. Is the ThreadPoolExecutor instance is shared by all the worker threads. If yes then the method beforeExecute(...) and afterExecute(...) shouldn't be synchronized? If the answer is no then is the reason is" the local variables are assigned in thread stack and state variables are thread confined / atomic". Please share ur feedback. thanks.
Comment: @user2030415 That is a very different question and you should probably ask it separately. Your current design is suspicious - in particular, your use of ThreadLocal does not make sense here as I believe that beforeExecute will be run in the main thread.
Answer: Your class is missing constuctors, it wont work without them
public class TimingThreadPool extends ThreadPoolExecutor {
    public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    // ...
}

Besides you could take a look at Executors implementation and do something similar in your class
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new TimingThreadPool(nThreads, nThreads,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
}


Using scrolling camera in pygame

Question: I have tried to implement a camera function in my 2d game made with pygame but the only I obtain is my player set in the middle of the window. I see how its x and y cordenates changes but the player does not move.I know I must use the camera's apply method to the map but I don't know how to do it since is my first approach to pygame. Here is my code:
import pygame, sys
from pygame.locals import *
import random

"""
dirt  0
grass 1
water 2
coal  3
"""

DIRT = 0
GRASS = 1
WATER = 2
COAL = 3
DIAMOND = 4
CLOUD = 5

cloudx = -200
cloudy = 0

WHITE = (255, 255, 255)
BLACK = (0,   0,   0  )
BROWN = (153, 76,  0  )
GREEN = (0,   255, 0  )
BLUE  = (0,   0,   255)

TILESIZE  = 40
MAPWIDTH  = 140
MAPHEIGHT = 120

WIN_WIDTH = 800
WIN_HEIGHT = 600

HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

fpsClock = pygame.time.Clock()

colours = {
            DIRT: BROWN,
            GRASS: GREEN,
            WATER: BLUE,
            COAL: BLACK
          }

"""tilemap = [
            [GRASS, COAL,  DIRT ],
            [WATER, WATER, GRASS],
            [COAL,  WATER, GRASS],
            [DIRT,  WATER, COAL ],
            [GRASS, WATER, DIRT]
          ]"""

resources = [WATER, GRASS, COAL, DIRT, DIAMOND]
tilemap = [[random.choice(resources) for w in range(MAPWIDTH)] for h in range(MAPHEIGHT)]

textures = {
            DIRT: pygame.image.load("dirt.gif"),
            GRASS: pygame.image.load("grass.gif"),
            COAL: pygame.image.load("coal.gif"),
            WATER: pygame.image.load("water.gif"),
            DIAMOND: pygame.image.load("diamond.gif"),
            CLOUD: pygame.image.load("nube.gif")
           }

inventory = {
                DIRT    :0,
                WATER   :0,
                GRASS   :0,
                COAL    :0,
                DIAMOND :0

            }

playerPos = [50,50]
move = 0
vel_x = 0
vel_y = 0
speed = 1

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = pygame.Rect(0, 0, width, height)

    def apply(self, rect):
        return rect.move(self.state.topleft)

    def update(self, target_rect):
        self.state = self.camera_func(self.state, target_rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera

    return pygame.Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-SCREEN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-SCREEN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return pygame.Rect(l, t, w, h)

global cameraX, cameraY
total_level_width = len(tilemap[0]) * TILESIZE
total_level_height = len(tilemap)*TILESIZE
camera = Camera(simple_camera ,total_level_width, total_level_height)

pygame.init()
DISPLAYSURF = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption("My first game :)")
pygame.display.set_icon(pygame.image.load("player.gif"))

PLAYER = pygame.image.load("player.gif")
playerrect = PLAYER.get_rect()

for rw in range(MAPHEIGHT):
    for cl in range(MAPWIDTH):
        randomNumber = random.randint(0,50)

        if randomNumber <= 10:
            tile = COAL
        elif randomNumber > 11 and randomNumber <= 20:
            tile = WATER
        elif randomNumber > 21 and randomNumber <= 45:
            tile = GRASS
        elif randomNumber > 46 and randomNumber <= 49:
            tile = DIRT
        else:
            tile = DIAMOND

        tilemap[rw][cl] = tile

INVFONT = pygame.font.Font("freeSansBold.ttf", 18)

while True:
    for event in pygame.event.get():
        if event.type == QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            #movement
            if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
                playerPos[0] += move
            elif event.key == K_LEFT and playerPos[0] > 1/TILESIZE:
                playerPos[0] -= move
            elif event.key == K_DOWN and playerPos[1] < MAPHEIGHT - 1:
                playerPos[1] += move
            elif event.key == K_UP and playerPos[1] > 1/TILESIZE:
                playerPos[1] -= move

            #pick up resource
            elif event.key == K_SPACE:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                inventory[currentTile] += 1
                tilemap[playerPos[1]][playerPos[0]] = DIRT

            #place resources
            elif event.key == K_1:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                if inventory[WATER] > 0:
                    inventory[WATER] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = WATER
                    inventory[currentTile] += 1
            elif event.key == K_2:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                if inventory[GRASS] > 0:
                    inventory[GRASS] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = GRASS
                    inventory[currentTile] += 1
            elif event.key == K_3:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                if inventory[COAL] > 0:
                    inventory[COAL] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = COAL
                    inventory[currentTile] += 1
            elif event.key == K_4:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                if inventory[DIRT] > 0:
                    inventory[DIRT] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = DIRT
                    inventory[currentTile] += 1
            elif event.key == K_5:
                currentTile = tilemap[playerPos[1]][playerPos[0]]
                if inventory[DIAMOND] > 0:
                    inventory[DIAMOND] -= 1
                    tilemap[playerPos[1]][playerPos[0]] = DIAMOND
                    inventory[currentTile] += 1
    keys = pygame.key.get_pressed()
    if keys[K_LEFT] and playerPos[0] > 1/TILESIZE:
        playerPos[0] -= speed
    if keys[K_RIGHT] and playerPos[0] < MAPWIDTH - 1:
        playerPos[0] += speed
    if keys[K_UP] and playerPos[1] > 1/TILESIZE:
        playerPos[1] -= speed
    if keys[K_DOWN] and playerPos[1] < MAPHEIGHT - 1:
        playerPos[1] += speed

    for row in range(MAPHEIGHT):
        for column in range(MAPWIDTH):
            DISPLAYSURF.blit(textures[tilemap[row][column]], (column*TILESIZE, row*TILESIZE))
            #DISPLAYSURF.blit(PLAYER, (playerPos[0]*TILESIZE, playerPos[1]*TILESIZE))

    DISPLAYSURF.blit(PLAYER, camera.apply(pygame.Rect(playerPos[0],playerPos[1],42,42)))
    camera.update(PLAYER.get_rect().move((playerPos[0],playerPos[1])))

    pygame.display.update()
    fpsClock.tick(10)
    print playerPos

Comment: The camera centers on the player, and it should be the world that moves, not the player, am I correct?
Comment: @Vicyorus yes but when you are in the map's limit the player is the one who moves and not the map
Comment: Related: [Add scrolling to a platformer in pygame](http://stackoverflow.com/a/14357169/142637)
Answer: First, remove this block of code:
        if event.key == K_RIGHT and playerPos[0] < MAPWIDTH - 1:
            playerPos[0] += move
        elif event.key == K_LEFT and playerPos[0] > 1/TILESIZE:
            playerPos[0] -= move
        elif event.key == K_DOWN and playerPos[1] < MAPHEIGHT - 1:
            playerPos[1] += move
        elif event.key == K_UP and playerPos[1] > 1/TILESIZE:
            playerPos[1] -= move

You already use pygame.key.get_pressed() for movement, so there's not need to check for a key press (Don't forget to change the following elif to if).

I know I must use the camera's apply method to the map

Yes, you're on the right track.
You already create a variable playerrect, so let's use it to store the position of the player. Also, let's create a Rect to store the size of the map. That will come in handy soon:
playerrect = PLAYER.get_rect(top=50, left=50)
mapsize = pygame.rect.Rect(0, 0, MAPWIDTH*TILESIZE, MAPHEIGHT*TILESIZE)

Now, when keys are hold down to move the player, we can simply use
keys = pygame.key.get_pressed()

if keys[K_LEFT]:  playerrect.move_ip(-speed, 0)
if keys[K_RIGHT]: playerrect.move_ip(speed, 0)
if keys[K_UP]:    playerrect.move_ip(0, -speed)
if keys[K_DOWN]:  playerrect.move_ip(0, speed)

playerrect.clamp_ip(mapsize)

to change the position of the player, and playerrect.clamp_ip(mapsize) makes sure that the player never leaves the map.
As for drawing, you should clear the screen first. To draw the tiles, you have to create a Rect for each tile (maybe later you could create them once and store/reuse them).
DISPLAYSURF.fill(pygame.color.Color('Black'))
for row in range(MAPHEIGHT):
    for column in range(MAPWIDTH):
        DISPLAYSURF.blit(textures[tilemap[row][column]], camera.apply(pygame.rect.Rect((column*TILESIZE, row*TILESIZE), (TILESIZE, TILESIZE))))

DISPLAYSURF.blit(PLAYER, camera.apply(playerrect))
camera.update(playerrect)

Comment: Finally I could solve the error just by myself but I thank you a lot for solve it too, the recommendation and information that you gave me to clean the code!
Comment: Yeah, it's satisfying to solve a problem yourself; but if you're stuck, don't hesitate to ask. Also, when your code is already working but you still feel it could be improved, I recommend asking on [codereview.stackexchange.com](http://codereview.stackexchange.com) for feedback!

Using scrolling camera in pygame


Magento SOAP API - catalog_product_attribute_media.list not finding SKU

Question: I've been trying to import several thousand product images into a Magento 220.127.116.11 website using the SOAP API.
Although some have been imported, several hundred were not.
To try and find where this has happened I am using the following API command:
catalog_product_attribute_media.list

This is returning an error for some SKU's: "Product not exists". This is a genuine API error documented at http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media#faults
However, the SKU's where this is happening definitely exist within Magento, as I can search for them and see them in the Admin panel.
$result = $client->call($session, 'catalog_product_attribute_media.list', '452103');

The above code will cause an Exception saying "Product not exists" meaning it can't find anything for the SKU 452103. But if I search for SKU 452103 in the Admin panel it's there!
What's strange is that if I get the Magento Product ID for that SKU (in the above example it happens to be 3478) and run the following it works without error:
$result = $client->call($session, 'catalog_product_attribute_media.list', '3478');

Does anyone know what I'm doing wrong or why this might happen? The API documentation says what I'm passing as the second parameter to call() can be either the Product ID or the SKU.
I can only use the SKU in practice because my source data doesn't know what the Magento Product ID's are, but the SKU has been imported without modification. The code above where I've used Product ID = 3478 is just something I put to test whether it would output anything but I had to find this Product ID manually, which isn't practical for the number of images I need to fix.
Answer: Please read the documentation for the API: http://www.magentocommerce.com/api/soap/catalog/catalogProductAttributeMedia/catalog_product_attribute_media.list.html
You will see there is a fourth parameter identifierType which says 'Defines whether the product ID or SKU is passed in the 'product' parameter'.
Every time you make your call at the moment the API is assuming it's the ID of the product. So to make it work by SKU only you should use the following;
$result = $client->call($session, 'catalog_product_attribute_media.list', '452103', 'sku');

There are numerous more API calls (product related) that all work in the same way but by default magento will always assume your using the product ID and not SKU unless you specify the identifier type.


Is there any way to display all information about an Object, to the console(in eclipse)

Question: Is there any way, to log information about all data members of an object to the console, in a similar fashion to JS in chrome?
Like how we get all information related to an object at a place in Chrome.
Answer: Yes, in a fashion. Set a breakpoint (if you must, make a static method called breakpoint() which does nothing (e.g. System.currentTimeMillis(); is the only thing in it, you do need an actual executable statement even if it does nothing), set a breakpoint on it, and now you can call ThatThingie.breakpoint(). Start using 'debug' and not 'run' (this also gets you Hot Code Replace, and in general has no real downsides vs. Run), and then the debugger will stop on that line, and let you inspect every local variable and from there, every relevant field, in the debug perspective.
From there you can even do things like set a 'watch' and then continue the program, and you'll see that object change in real-time.
You can set a breakpoint by double-clicking in the margin (where the line-numbers are). A little green dot should appear.
Answer: A solution might be to create a comprehensive toString() method in your class and then log it.


How to count number of items in a specific type in a table in sql?

Question: I have a table named Movie, with actors attribute. actors_type is specific and looks like this:
GEORGE.ACTOR_TYPE('Clint Eastwood', 'Christopher Carley', 'Bee Vang', 'Ahney Her')

ACTOR_TYPE is implemented as a varray(5) of varchar(20)
the query I tried to count the number of movies for each actor is :
select m.title, a.column_value, count(m.title)

from movie m, table(m.actors) a

group by m.title,  a.column_value

order by a.COLUMN_VALUE

which gives me a count of each row(?) Not the count of movies for each actor. the output is as below:

what I am trying to get is to List actors that acted in multiple movies and show movie title and the actor.
but when I add m.title in the select statement, it will count each row.
This is the other query I wrote:
select a.column_value, count(m.title)

from movie m, table(m.actors) a

having count(m.title) > 1

group by a.column_value

order by a.COLUMN_VALUE

and the result is:

I need to add the title to the output too, but when I add it, all the counts will be one, as the first table.
Movie Table:

There is no table for Actors, we create table for it via table(m.actors) a to access its items
Comment: *Never* use commas in the `FROM` clause.  *Always* use proper, explicit, **standard** `JOIN` syntax.
Answer: You have to remove m.title from group by and selection cause you are going to count that according to actor.I assume column_value is a common column between two tables , so i used that on join
 You need to try like below
select  a.column_value, count(m.title)
from movie m
join m.actors a  on m.column_value=a.column_value
group by  a.column_value
order by a.COLUMN_VALUE

Comment: I got this error "table or view does not exist." I think there is no m.column_value, cuz the Movie table is a simple entity table. We use COLUMN_VALUE to access the items inside the collection or varray table that we create. there is not such a column in movie table
Comment: @Jasmine then pleases share two tables available all column


Restrict SFTP users to their home folder

Question: I want to restrict SFTP users to their home folder so that they won't see anybody else's folder/home directories. Unfortunately all SFTP users can see other user's folders at the moment. All the posts and examples points out ChrootDirectory but for some reason I cannot get it working.
$ sudo nano /etc/ssh/sshd_config

Subsystem sftp internal-sftp
Match Group sftp
  ChrootDirectory %h            # The %h causes "Broken pipe" error while trying to login
  ChrootDirectory /var/sftp     # This allows login but all SFTP folders are visible to all user
  X11Forwarding no
  AllowTcpForwarding no
  AllowAgentForwarding no
  PermitTunnel no
  ForceCommand internal-sftp

Users, Permissions and Folders
I used command below to create users and folders.
sudo useradd -m -d /var/sftp/hello -G sftp hello --shell /usr/sbin/nologin

Result
ubuntu@linux:~$ grep hello /etc/passwd
hello:x:1001:1002::/var/sftp/hello:/usr/sbin/nologin

ubuntu@linux:~$ grep world /etc/passwd
world:x:1002:1003::/var/sftp/world:/usr/sbin/nologin

ubuntu@linux:~$ ls -l /var/
drwxr-xr-x  4 root root   4096 May  7 14:48 sftp

ubuntu@linux:~$ ls -l /var/sftp/
drwxr-xr-x 3 hello sftp 4096 May  7 14:01 hello
drwxr-xr-x 2 world sftp 4096 May  7 14:48 world

SOLUTION
The problem here is that, I had to let root:root own the home folder of my users and create another folder under users' home folder (e.g. uploads) then own it as hello|world:sftp. Originally the home folders were owned by hello|world:sftp.
Comment: Possible duplicate of [bad ownership or modes for chroot directory component](https://serverfault.com/questions/584986/bad-ownership-or-modes-for-chroot-directory-component)
Comment: What is in your sshd logs when you get "Broken pipe" error?
Comment: `linux sshd[3555]: fatal: bad ownership or modes for chroot directory "/var/sftp/hello"` and `linux sshd[3555]: fatal: bad ownership or modes for chroot directory "/var/sftp/world"`
Answer: For security reasons users under chroot shouldn't be able to create arbitrary files (for example /etc/shadow and countless others). That's why sshd forces you to take away ownership and writing privilege of the chrooted directory itself:
chown root:root /var/sftp/hello
chmod o-w       /var/sftp/hello

Alternative solution, without any sshd ChrootDirectory depends on the fact that user can only list a directory if they have r permission, while using it requires only x permission:
chown root:root /var/sftp
chmod o=x       /var/sftp    # implicitly removes rw, sets only x

Comment: I had to create sub folder under home folder then let individual users own it. That was the problem.
Comment: If I change the ownership to `root:root` my user `hello` can login. However, I want `hello` to be able to write/upload files into `/var/sftp/hello` folder which is currently not working.


File Upload to share storage

Question: I am trying to create a load balanced Drupal installation.  My setup has a shared storage that all the webservers can read write to.  At the moment I'm having trouble setting up the Drupal configuration at {mydomain}/admin/config/media/file-system/ to save our content to the correct file path.
The file path on the operating system that I'm trying to write content to is of the form:
\xx.xx.xx.xx\my\content\folder\
When I place this in the public file path I get the content written to the local path:
D:\myDrupalInstalation{mydomain}\sites\xx.xx.xx.xx\my\content\folder\
However I know the PHP has rights to write modify content on the shared storage because when I try the same path in private file path the content is written to the shared storage:
\xx.xx.xx.xx\my\content\folder\sites{mydomain}\allTheContent\
Which is what we require.
How can I configure the public file path to write to the same location?
P.S.  I think it is something due to the fact that the Drupal config page itself specifies "This directory must be relative to the Drupal installation directory and be accessible over the web." for public path and "* It should be writable by Drupal and not accessible over the web.*" for Private.
Thanks
Comment: a symbolic link did the trick.
Comment: Great! I made it an answer for other users.
Answer: In a Linux environment, this is done for NFS drives by creating a symbolic link under your Drupal webroot.
In the Windows environment, you can also create a symlink to a network drive path (e.g. \xx.xx.xx.xx\my\content\folder ).
Comment: Drupal won't save files into a symlinked location. I am trying to solve a very similar issue when saving a file attached to a node.

File Upload to share storage


Is it possible to change a domain controller's GUID?

Question: I have a large number of separate Active Directory domains (~150) consisting of 2 server clusters that I need to setup for smart card login. To do this I will have to request ~300 domain controller certificates manually due to my environment. Needless to say that is a huge amount of manual effort and I am looking to script it.
To request a domain controller certificate you need three pieces of information: the certificate request, domain name and GUID. I can generate all of that information automatically but I cannot figure out how to change each domain controller's GUID to match the cert short of a direct ldap change. Does anyone know if that would work or would I break the domain?
Answer: Nope, never ever do this. The GUID is AD's means of locating/identifying a domain controller for replication. It's important that it remain unchanged (and most importantly, unique to each DC).
Could you setup the machines to trust a central CA and have that issue the machine certs automatically?
Comment: Unfortunately none of these machines have any sort of network connectivity to each other and I have to use a specific third party CA. Oh well it was a thought that I could save myself some pain. Thanks though.


Installing IIS on Windows 2003

Question: I am attempting to install IIS on a Windows 2003 server with SP2.  During the install, it prompts me for a file called smtpsnap.hlp.  This file is not found on the Windows 2003 CD, nor is it found in any of the SP2 installation files.
What is this file?  Why is it prompting for it?  Where can I get it?
Answer: You will find it in the i386 directory of your server 2003 CD. Called SMTPSNAP.HL_
I just checked my CD and it is definetely there.
You can use the expand command to extract it if you really want to like
Expand d:\i386\SMTPSNAP.HL_ c:\windows\system32\SMTPSNAP.HLP
Comment: I ended up re-installing windows and it worked after that.  I just checked my CD, and it only has smtpsnap.dl_ (no .hl_ file).  It should be noted that I also tried using several different Windows 2003 CDs, including the original CD and one with SP2 slipstreamed into it.  Neither worked.
Comment: Also, after installing IIS, that file is not present in the system32 directory.
Comment: The expand command was just an example. The file should be installed in C:\WINDOWS\Help\mail so sorry about that.

On another note, I have just checked my 2003 Enterprise slipstreamed with SP2, 2003 Enterprise original and 2003 Standard CDs and all of them had the above file. Strange indeed.

Glad you got it fixed though!
Answer: It should be in the Windows Server 2003 Administration Tools Pack for 32-bit system that you can download from Microsoft:
http://support.microsoft.com/kb/304718
Comment: Installing the Admin pack did not work.
Answer: I ended up re-installing windows and it worked after that.  It should be noted that before re-installing, I tried using several different Windows 2003 CDs, including the original CD and one with SP2 slipstreamed into it. Neither worked.

Installing IIS on Windows 2003


What if a question marked as duplicate has a better answer then the orignal?

Question: Login problems after update to Magento 1.8 are a common question
However, the best answer and the only one that shows the right that to solve it that I found, is in a question marked as duplicate:
Customer Cannot Login After an Update to EE 220.127.116.11 (or CE 22.214.171.124)
I voted to close a new question as duplicate of this one and not the original one. However, people who find it will probably follow the link to the first one with less-quality answers.
How to handle this? Is it possible to reopen the question and close the "original"? Or should the answer copied to the original?
Answer: IMO you should vote to reopen the question with the better answer and when that gets reopened vote to close the one with the "lower quality" answers.
Answer: What I remember there is a way to merge questions for such cases, but dont remember the exact circumstances for this.
But as you can choose which gets marked as duplicated from what, i usually decide which has the more precise question.


Inconsistent behavior in .click() function in cypress

Question: I have an edit box would like to click and then type in value.
So, my code is
cy.get('.ag-row-last > [aria-colindex="3"] ').click().type('65{enter}')

The problem is 50% time, it can open that edit box like below image and then I can type in value

However, 50% time. I get failure. it cannot open it up as below image

therefore, it gives me this error

cy.type() failed because it requires a valid typeable element.
The element typed into was:

A typeable element matches one of the following selectors.....

I understand this error because the input was not found because the edit box was closed.
How could I get rid of this inconsistency issue?
Answer: Generally, inconsistent behaviour can be fixed by adding a "guard" check between actions (i.e the .click() and the .type() commands).
For example, see the ag-cell-not-inline-editing class, this changes to ag-cell-inline-editing after the click, so you could try
cy.get('.ag-row-last > [aria-colindex="3"] ')
  .should('have.class', 'ag-cell-not-inline-editing')
  .click()
  .should('have.class', 'ag-cell-inline-editing')      // wait for cell state change
  .type('65{enter}')

There are other changes after the click, for example the following block of HTML is added to the grid cell

      <input
        ref="eInput"
        class="ag-input-field-input ag-text-field-input"
        type="text"
        id="ag-895-input"
        aria-label="Input Editor"
      />

so you might use this in the test
cy.get('.ag-row-last > [aria-colindex="3"] ')
  .should('have.class', 'ag-cell-not-inline-editing')
  .click()
  .find('input.ag-input-field-input')               // waits for the input to appear
  .type('65{enter}')

Comment: Thanks for your effort, may i ask about what u mean "wait for cell state change" here
Comment: May I ask that the guard you mean is to prevent the next action to trigger too quickly right?
Right now, it seems that the edit box was closed after opening up, but not doing the .type() before .click() .
Coz the original value in edit box was cleared after .click() in the failed time. If the failure is because of doing the .type() too fast, then I think the original value should be still here


Difference between Metric Space and Topological Space

Question: I am reading Chapter 11 of Real Analysis written by Royden and Patrick (4th). It says "The concept of uniform convergence of a sequence of functions is a metric concept. The concept of pointwise convergence is NOT a metric concept." (page 222) I know the definitions for uniform and pointwise convergence of a sequence of functions. However, I could not understand the quote above. Could anyone explain it to me, please? Thank you!
Comment: Try to write down definition of uniform convergence when you do not have metric spaces as domain or range. If you cannot, then you see what the difference is. If you can, something is wrong with your definitions.
Comment: The notion of pointwise convergence can be defined on a topological set. Namely, a sequence of points $x_1,x_2,\ldots$ in $X$ converges to $x\in X$ if every neighborhood $U$ of $x$ contains all but finitely many of the $x_i$. The definition of uniform convergence requires the use of a metric, and its generalization to topological spaces requires the notion of a [uniformity](http://en.wikipedia.org/wiki/Uniform_space).
Comment: The domain needs no structure at all, it need not even be a topological space, @studiosus. Only the codomain.
Comment: Yes, you are right, I was thinking about uniform continuity for some reason.
Comment: You should note that the totality of all maps $f\colon X\to Y$ is just the product space $Y^X$, and the pointwise convergence is just the convergence in the product space with product topology.
Answer: Uniform convergence of a sequence of functions implies convergence of the sequence in the metric space of all functions.So it is a  metric concept.
Comment: This is quite a brief answer for a Question that has been around for almost three years.  At a minimum you should explain for the benefit of Readers what you mean by "the metric space of all functions" and why uniform convergence (of a sequence of functions) relates to this additional notion of convergence/topology.


How to select a combobox value in ExtJs?

Question: I am trying to simply select an item in the dropdown list after it has been loaded into a store.  This does not work:
Ext.getCmp('ddlModel').setValue(aircraftStore.getAt(0).data.ModelTypeCode);

This throws an exception:
Ext.getCmp('ddlModel').selectByValue(aircraftStore.getAt(0).data.ModelTypeCode);

Here is the exception:
'this.view' is null or not an object
Anyone know how to do this in ExtJs?
Comment: as docs suggests use setValue. "The store must be loaded and the list expanded for this function to work, otherwise use setValue". it works for me as expected
Answer: I created a function to set the value of the combo box in ExtJs:
function ComboSetter(comboBox, value) {
    var store = comboBox.store;
    var valueField = comboBox.valueField;
    var displayField = comboBox.displayField;

    var recordNumber = store.findExact(valueField, value, 0);

    if (recordNumber == -1)
        return -1;

    var displayValue = store.getAt(recordNumber).data[displayField];
    comboBox.setValue(value);
    comboBox.setRawValue(displayValue);
    comboBox.selectedIndex = recordNumber;
    return recordNumber;
}

Comment: I have spent 6 hours to know how to display the correct string and found it in ```comboBox.setRawValue(displayValue);```
Answer: Ext.getCmp('ddlModel').select(aircraftStore.getAt(0));
Comment: There must be a bug in ExtJs 3.4 because selectByValue and select both throw an exception even when the dropdown is expanded.
Answer: In many cases you may want to set the combobox to a certain index. In ExtJs 4.2 you can do this like so:
function setIndex(combobox, value)
{
    combobox.setValue(combobox.store.data.items[value].data.field1);
}

Answer: in my case, I needed to get the id of the combobox, then compare in an if, and thus able to pass a second window, use this method and it worked.
var ValorSeleccionado = Ext.getCmp('cmb_tipoderol_usr').getValue(); // 'cmb_tipoderol_usr' is the id of the combobox.

then compare to the action
if (ValorSeleccionado == 1 ) { Do Action }

Answer: I think the correct way is to configure your combobox with this property:
autoSelect: true

true to select the first result gathered by the data store (defaults
to true). A false value would require a manual selection from the
dropdown list to set the components value unless the value of
(typeAheadDelay) were true


Como ler comentários de uma classe, função ou método?

Question: Já vi algumas implementações no framework Symfony e Laravel que permitem definir através de comentários
rotas em métodos de controller, ou as definições de annotation dos Models do Doctrine.
Mais ou menos assim:
class Usuariosontroller

{
    /**
     * @Route('GET', 'usuarios')
    */
    public function getIndex()
    {

    }

}

Como os frameworks fazem pra ler esse bloco de comentários em cima dos métodos?
Comment: [ReflectionClass](https://i.ytimg.com/vi/2gbPukrSPLw/hqdefault.jpg)
Comment: @HomerSimpson responde aí pra ganhar votos, cara
Answer: Classe
Utilizando o ReflectionClass para acessar a classe, e assim obter o valor do comentário utilizando o método getDocComment:
$reflection = new ReflectionClass('Usuariosontroller');
echo $reflection->getDocComment();

Exemplo Ideone.
Método
Utilizando ainda o ReflectionClass para acessar a classe, agora utilize o getMethod para acessar o método que deseja obter a informação, utilizando o método getDocComment:
$reflection = new ReflectionClass('Usuariosontroller');
echo $reflection->getMethod('getIndex')->getDocComment();

Exemplo Ideone.
Função
Utilize o ReflectionFunction para acessar a função, em sequência o getDocComment para acessar o comentário:
$reflection = new ReflectionFunction('beber');
$reflection->getDocComment()

Exemplo Ideone.
Observação:
Existem algumas formas de se fazer um comentário, porém, os métodos acima funcionaram somente se utilizar o comentário cujo token seja T_DOC_COMMENT, ou seja, comentários que obedeçam a syntax: /** */, então comentários que utilizem o token T_COMMENT - syntax // or #, and /* */ - serão ignorados.
Comment: Show de bola, ficou bonito. Accept
Answer: Você também pode usar token_get_all nativo do php.
arquivo index.php
/**

    COMENTÁRIO

*/

function foo(){
    echo "foo";
}

Executando...
$array = token_get_all(file_get_contents("index.php"));

foreach($array as $arr){
    if(isset($arr[0]) && ($arr[0] == T_DOC_COMMENT || $arr[0] == T_COMMENT)){
        print_r($arr[1]);
    }
}

saída:

/** COMENTÁRIO */


Why I've got Fatal error of undefined validation function in my form?

Question: I get the error in below code, it is strange, why it occurred?
In hook_menu
$items['share/%'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ym_alter_sharing_content'),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

and:
function ym_alter_sharing_content($form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
  $nid=arg(1);
  $form = node_add('share');

  //$form['field_nid']['und'][0]['value']['#value']=$nid;
  //$form['#submit'][]='ym_alter_sharing_submit';
  //form_load_include($form_state, 'inc', 'node', 'node.pages');
  return $form;
}

but it return me:

Fatal error: Call to undefined function node_form_validate()

Where is the problem?
Comment: You haven't declared a callback function, you've declared a _form_ and are using `drupal_get_form()` as your callback. Change your callback to `ym_alter_sharing_content()` and return `node_add('share');` or something like that
Comment: It's because you're trying to include another form into your existing form. You need to use `hook_form_alter()`. I'm sure you know that already though
Comment: Glad you got it sorted :)
Comment: Maybe you forgot to include node.pages.inc from node module? that's where [`node_form_validate()`](https://api.drupal.org/api/drupal/modules!node!node.pages.inc/function/node_form_validate/7) is defined.
Comment: @Mołot I include it `module_load_include('inc', 'node', 'node.pages');`
Comment: @Clive how I should do it? I want in callback function I have add share content type
Comment: @Clive Today I have a bad day, I am sad, great,thank you very much Master Clive :). I found my mistake
Answer: Change page callback form drupal_get_form to function, because if you use drupal_get_form in call back it return form and in your function you create another form, it means form in form and make conflict.
$items['share/%'] = array(
    'page callback' => 'ym_alter_sharing_content',
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

Comment: Always use `form_load_include()` in forms. Otherwise you will not load your files when form is cached.
Answer: You got the error, because of missing &.
When you're using form_load_include() in hook_form_alter(), make sure you're following the right API syntax which is:
hook_form_alter(&$form, &$form_state, $form_id)

otherwise form_load_include() can't perform alterations of your current state of the form ($form_state).


How to setup wordpress to use ftps with pem file?

Question: On AWS Lightsail/EC2, there is a WordPress instance that is unable to upload images/templates/plugins from within WordPress.
I have been able to FTP into this instance with Filezilla and also ssh with bash. But the upload functionality inside WordPress needs to work.
When trying to install a new theme from within WordPress, it asks for ftps credentials. AWS requires the use of a pem file. The WordPress ui does not have the option of using a pem file.
The solution seems to be something like this, but I don't know the actual commands and steps: SSH in, create a user, give them access to something, create a new pem file, and tell WordPress to use the pem file via the FTP section in the wpconfig file.
The file structure is ~/htdocs/{wordpressFiles}
Comment: Do you mean SFTP?
Comment: Hi, thanks for replying... I double checked and attached a screenshot. This ui is calling it ftps.
Answer: It sounds like you created the folder via FTP thus the FTP User is the file owner, so Apache cannot access it.
1.) Check if the main user is daemon or bitnami with ls -l
2.) If the user is not daemon you can try sudo chown daemon:daemon path/to/wp-plugins
Comment: Thank you I will try this. Laptop crashed so I will update in about a week. Hope to mark this as the answer. You're right, I uploaded it with FTP.
Comment: Adding to that, the best way to do this is probably use "chown -R" on wp-content recursively, so this gets done for every folder.


Flask jinja2 dict value by key

Question: I have list of dicts:
[{'row': '1', 'number': '5'}, {'row': '1', 'number': '10'}, {'row': '1', 'number': '3'}, {'row': '1', 'number': '7'}, {'row': '1', 'number': '2'}, {'row': '1', 'number': '13'}, {'row': '1', 'number': '6'}, {'row': '1', 'number': '12'}, {'row': '1', 'number': '1'}, {'row': '1', 'number': '8'}, {'row': '1', 'number': '9'}, {'row': '1', 'number': '11'}, {'row': '1', 'number': '15'}, {'row': '1', 'number': '14'}, {'row': '1', 'number': '4'}, {'row': '2', 'number': '1'}, {'row': '2', 'number': '4'}, {'row': '2', 'number': '10'}...]

I want to iterate thru this loop in jinja and print numbers inline for particular row#
Something like this:

row#1 numbers for row #1: 1 2 3 4 ...

row#2 numbers for row #1: 1 2 3 4 ...

row#3 numbers for row #1: 1 2 3 4 ...

I need divs as many unique rows in dict.
Answer: One option is to reshape your dictionary so that the keys are the row and the values are the number, and then it will be easy to loop through this new dictionary and construct divs:
result = {}
for d in dd:          # dd is your list of dictionaries here
    result.setdefault(int(d['row']), []).append(d['number'])

result
#{'1': ['5',
#  '10',
#  '3',
#  '7',
#  '2',
#  '13',
#  '6',
#  '12',
#  '1',
#  '8',
#  '9',
#  '11',
#  '15',
#  '14',
#  '4'],
# '2': ['1', '4', '10']}

Comment: How i can sort it by int (rows and numbers inside each row)?
Comment: You can try this `{k: sorted(v, key=int) for k, v in result.items()}`
Comment: https://yadi.sk/i/p8gNam1F3FVEtF - worked for numbers but not for the rows. Code inside Jinja: {% for row in result|sort %}

           row#{{ row }} numbers:{{ ' '.join(result[row]) }}

{% endfor %}
Comment: Last question, how i can sort rows and numbers in result, which contains int and strings, like ['2', False], ['13', False]... ?  I got: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Comment: A dictionary in python is orderless, i.e, you can't guarantee the order of key, so you can't sort the dictionary by a key, if you want the result to be ordered by row, you need an [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) or a list of tuples.for instance  `sorted((k, sorted(v, key=int)) for k, v in result.items())` gives you a list of tuples which are sorted by the first element and have sorted second element(list) as well, loop through this data structure should always give you ordered result.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/137799/discussion-between-konstantin-rusanov-and-psidom).
Answer: Jinja2 will have a tough time doing that on its own. You want to aggregate all the numbers for each row into a single list, and then print that list out. I recommend doing this in two separate steps.
row_dict = {}
for num_dict in list_of_dicts:
    row = num_dict['row']
    if row not in row_dict:
        row_dict[row] = []
    row_dict[row].append(num_dict['number'])

Now you've got a row_dict that looks like:
{
    '1': ['5', '10', '3', '7', '2', '13', '6', '12', '1', '8', '9', ...],
    '2': ['1', '4', '10', ...],
}

Jinja2 is fine to print this out. You could write a template that does something like this:
{% for row in row_dict.keys()|sort %}

row#{{ row }} numbers for row #{{ row }}
  {{ ' '.join(row_dict[row]) }}

{% endfor %}

Flask jinja2 dict value by key


Update several UserDefaults files at the same time

Question: I am writing a function that overwrites the value stored in several UserDefaults files.
These files key names are similar but have different terminations due to dynamic saving, ex:
forKey: buyOrSellBitcoin-USD
forKey: buyOrSellBitcoin-GBP
forKey: buyOrSellBitcoin-CNY
Is it possible to overwrite every file at the same with a single line like:
forKey: buyOrSellBitcoin-\(x) ?
Answer: There are not multiple UserDefaults files. It is a single key/value store. You write key/value pairs into the store.
No, there is no way to specify a wildcard that would somehow tell the OS to update all the keys you have defined that follow a particular pattern.
However, you can write collection objects like dictionaries into UserDefaults:
let coinsDict = [
  "buyOrSellBitcoin-USD": valueForUSD,
  "buyOrSellBitcoin-GBP": valueForGBP,
  "buyOrSellBitcoin-CNY": valueForCNY
]

UserDefaults.standard.set(coinsDict, forKey: "coinsDict")

And then you would read the resulting dictionary back from UserDefaults and unpack it into your data model.
Comment: Wow that's great!


Comments don't want turn off

Question: I forgot to turn off the comments while creating a content type. Now when i set the Comments to Closed, the form for adding a comment is still being displayed in full node view.
Any suggestions?
Thanks!
Comment: Yes, tell us what error message are you getting, when you save with "comments: off". It's on the screen, in watchdog, or possibly in webserver's log. Oh, and have you cleared your caches?
Comment: No errors. The comments simply don't get closed.
Comment: Obviously, it's not Drupal's standard behaviour. It must be caused by something you or your sysadmin installed / coded / configured etc. And we have only the data you put in your question. So, sadly, it's up to you to find what exactly stopped your settings form from being saved. Only when we know what happened, we have a chance to tell you how to deal with it. Or you can hire a contractor and give him all needed credentials to debug this for you.
Comment: The problem was that i already had some content of this content type, and all nodes had the comments set to "Open" due to configuration of the content type at the moment of creation. Once I had it set to "Closed" on every node of this type, it worked like expected.

Thank you Sir for your time.
Comment: Welcome to Drupal Answers! We give answers, not suggestions. You should give all the details, in the question. You forgot saying you had nodes of that content type and you were wondering why on those nodes the comments were still open; from what you wrote, I took you changed the settings for a content type, and then created the first node of that content type.
Comment: To make it clear, the question has been closed to avoid users add an answer for their specific case. Since you are asking for suggestions, I am expecting users writing "In my case, it was the [name one] module." This is not something we want, indeed.
Comment: This question could also be closed as duplicate of the question where you find the solution. The fact the other question asks about Webform is not sufficient, since webforms are just nodes.
Comment: Sorry guys for the confusion, I didn't found it relevant to note that i already had some nodes of the content type. It's my bad, I will try to be more precise in the future. Thanks for the help though!
Answer: This setting only sets the default for nodes, so already created nodes will still have their comments turned on. Easiest way to update all the nodes is with a couple of SQL statements, back up your database first.
<code>UPDATE node SET comment = 0 WHERE type = 'your_content_type';

UPDATE node_revision nrev
  INNER JOIN node nd ON nrev.nid = nd.nid AND nd.type = 'your_content_type'
  SET nrev.comment = 0;
</code>
then clear cache.
Note that comment can equal the following:
0 = disabled
1 = readonly
2 = read/write.
More details at How to finally disable comments on content type?

Comments don't want turn off


Let $A$ be an $n\times n$ singular matrix. Describe how to construct...

Question: Let $A$ be an $n\times n$ singular matrix. Describe how to construct an $n\times n$ non zero matrix such that $AB = 0$.
I'm not sure how to approach this correctly. I think I am supposed to use the idea that $A$ is not invertible, which tells me that the columns of $A$ are linearly dependent and $A$ has less than $n$ pivots.
How can I use this information to construct $B$?
Comment: For an additional challenge, construct a nonzero $B$ with $AB=0$ **and** $BA=0$.
Answer: Guide:

Start by finding a non-zero $x$ such that $Ax=0$ (explain why you can find it).
Think of how to make good use of the $x$ that you find to construct $B$.
Comment: Since A is not invertible , that means that $Ax = 0$ doesn't have the trivial solution as the ONLY solution, so that implies that there MUST be a non zero $x$ which makes $Ax = 0$ true. But i think i need another hint on how to actually construct $B$ . Is it possible to put $x$ in a zero n x n matrix?
Comment: Can you try to evaluate $A \begin{bmatrix} x & \ldots &  x \end{bmatrix}$ ? what about $A \begin{bmatrix} 2x & 3x &  \ldots &  (n+1)x \end{bmatrix}$
Comment: so $[x ... x]$ is the matrix B then?
Comment: $B$ is clearly not unique. If you verified that it works then it is a candidate.
Comment: $$
\begin{pmatrix} 1 & 2\\ 1 & 2
\end{pmatrix} *
 \begin{pmatrix} -2 & -2\\ 1 & 1
\end{pmatrix} = 0

$$ the equation above represents $Ax = 0$... it seems to work
Comment: yup, it should work. note that we have $A \begin{bmatrix} x & \ldots & x \end{bmatrix} =  \begin{bmatrix} Ax & \ldots & Ax \end{bmatrix} $


jQuery UI autocomplete with pre-transformed json url

Question: Ok so I understand that jQueryUI expect the object in key/value form with the key's "value" and "label" so I've already transformed my data into a this json format. Now I'm just not sure how the easiest way to source my json url. All of the other articles on this matter show a need to pull the data in and transform it which isn't my case.
My json file at getuser.php?name=brian
[
   {"label":"Brian Aa","value":"7e36e"},
   {"label":"Brian Ba","value":"3e497"},
   {"label":"Brian Bc","value":"c3263"},
   {"label":"Brian Cc","value":"5be94"}
]

My Autocomplete JS:
$("#test").autocomplete({
  source: function(request, response) {
    "sample.com/getusers.php?name="+$("#test").val(), request, response;
  },
  minLength:2
});

And HTML

  Requested By:
  <input id="test">

Right now I'm getting nothing when I type, assuming I have to setup ajax but I thought I had seen an example of a pretty simple solution when the JSON is already formatted but cant seem to find it.
Comment: What do you mean by you need to "source your JSON URL"?
Comment: I have a page (getuser.php) that if you provide a parameter (?name=brian)  in the url it will provide json formatted data like the json dump ive shown in my question
Comment: Maybe I'm lacking sleep, but I still don't know what you mean. Are you saying you want to use a json array as the object's  "source" property? The very first example [here](https://jqueryui.com/autocomplete/) shows them using an array..
Comment: From the [documentation](http://api.jqueryui.com/autocomplete/)...."An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]" - this is the format of my json that I would like to use.
Answer: The source function is not right, you need to get data from server and use response as call, see Autocomplete API
  source: function(request, response) {
     var url = "sample.com/getusers.php?name="+$("#test").val();
     $.get(url).done(function(data){
       response(data);
     }).fail(function(error){
        //dosomething here
     });
  }

Comment: That's not true. The first example on that page uses an array instead of an AJAX call.
Answer: It was a matter of doing an ajax call, I just thought there was a more simple way.
$( function() {
  $( "#test" ).autocomplete({
    source: function( request, response ) {
      $.ajax( {
        url: "sample/getusers.php?name="+$("#test").val(),
        dataType: "json",
        data: {
          term: request.term
        },
        success: function( data ) {
          response( data );
        }
      } );
    },
    minLength: 2,
    select: function( event, ui ) {
    }
  } );
} );


Json web token generation in angular4 or javascript

Question: How can I generate JSon web token for a user who just login into the application in angular2/4 application
Comment: What are you going to use web token for? If you are simulating user login with back-end API that job `token generation` is done in the back-end not front-end.
Answer: You can't generate web token from client side. Please use https://jwt.io/ to use it in your own server side language and use https://github.com/auth0/angular2-jwt this library to consume it.
Answer: generating a token is a back-end side job and angularJs should just store it and send it to server to validate user data and basically generating it in front-end isn't a good idea cos you'r key will get in people's hand and they can generate tokens with it that server will validate it as True and it will make problems and error's for application.
Answer: Actually there are number of way by using you can create JSON web token for your app, for example using btoa approach , or using jwt.io etc.

But Why to generate JSON web token ?

Generally JSON web token should be generated from back end side and which is safe also, so don't try this on client side.


Yii meta tags output from db dynamically

Question: First of all i want say Sorry for my English.
Site write on Yii framework.
I have many modules, and they all have parameters "meta_keywords" in db.
In my main.php layout
<meta name="keywords" content="<?php echo CHtml::encode($this->meta_keywords) ?>" />

Add in my controller.php
public $meta_keywords = "";

But nothing work.
What i need to do ?
thank you for your advice
Answer: Ok , Now go to the action for eg :
 public function actionIndex(){
    // some code ...

    $this->meta_keywords = 'some  meta tag';  // assign values from database.

   // render view
 }


how to properly inform the user of reading progress

Question: Showing the user one screen at a time (or allowing him to scroll freely) the system will always have the variables:
top line visible. lines visible in the screen. total lines.
What's the best approach to tell the user of it's progress in the text?
If the system uses line 1 as 0% topLine * 100 / totalLines then at the end of the text, it will be something <100%, e.g.  97.5%
If the system accounts for the visible line in the screen (topLine + linesVisible) * 100 / totalLines, it would start at something >0%, e.g. 11%
If the system uses a curve to start at 0% and end at 100%, everytime he swtiches devices or resized font/screen size the percentage would change.
Is there a common pattern for this problem?
Comment: What application are you developing?
Answer: I don't think there would be a common pattern for this. The task is device-specific and application specific.
You should count all three variables top line visible, lines visible in the screen and  total lines when user changes font or font-size. And when user scrolls only top line visible and lines visible in the screen should be counted.
Take a look on how MS Word or even Amazon Kindle deal with the issue. MS Word shows progress when you hold the mouse on the scroll. And Amazon Kindle shows the progress at the bottom of the page.
They both show the page number or percentage of the pages and not lines, but their approach could be applied for lines too.
Also if your document isn't really huge it wouldn't be pleasant to show float numbers as progress. The rounded percentage would do in that case.
Comment: you're right. it's not solvable. will just treat % as a UI element and change it when the page size changes.


Refactor left recursion infinite loop

Question: When you trying to implement this formula

in a straightforward manner using this code
def P(n, p, limit):
    if n == limit:
        return 1

    if n == -limit:
        return 0

    return p*P(n+1, p, limit) + (1-p)*P(n-1, p, limit)

you will definitely end up with this error.

RecursionError: maximum recursion depth exceeded

So how to properly implement such class of problems using code? Is there a technique used to refactor this and get a solution? Or the only thing is to solve that mathematically first and only then feed into computation?
Comment: @meowgoesthedog: memoization doesn't solve infinite recursion; it merely removes redundancy.
Comment: @Prune oops thanks for the catch, don't know why I thought memoization would have even helped
Answer: To expand on @Prune's suggestions, this recurrence can be written as two other recurrences, by moving either of the terms on the RHS to LHS:

These are non-cyclic because each term only depends on terms either before or after it, not both.

However, they cannot be solved independently, because that requires knowledge of P1-l and Pl-1, where l = limit.
Making some substitutions for convenience:

Note that, since the relations only contain linear terms (no e.g. Pn × Pn-1 etc.), all terms in their expansions will also be linear in the variables x, y:

These newly introduced coefficients also obey similar recurrence relations:

Their boundary conditions are:

Now that the boundary conditions are known, the coefficients can be computed iteratively. It only remains to equate the expressions for P1-l and Pl-1 from both recurrences:

Solving this pair of simultaneous equations gives P1-l and Pl-1, from which any Pn can be calculated (using the coefficients computed earlier):

Update: sample Python implementation
# solve a recurrence of the form
# Tn = c1 * Tn-1 + c2 * Tn-2, n >= 0
def solve_recurrence(c1, c2, t1, t2, n):
    if n <= 0: return t2
    if n == 1: return t1
    a, b = t2, t1
    for i in range(1, n):
        a, b = b, c1 * b + c2 * a
    return b

# solve the loop recurrence
def solve_loop(limit, p, n):
    assert(limit > 0 and abs(n) <= limit)
    assert(p > 0 and p < 1)

    # corner cases
    if n == -limit: return 0
    if n ==  limit: return 1

    # constants
    a, c = 1 / p, 1 / (1 - p)
    b, d = 1 - a, 1 - c

    # coefficients at 2l - 1
    e = 2 * limit - 1
    l = solve_recurrence(a, b, 1, 0, e)
    m = solve_recurrence(a, b, 0, 0, e)
    s = solve_recurrence(c, d, 1, 0, e)
    t = solve_recurrence(c, d, 0, 1, e)
    # note that m can just be 0 but was left in for generality

    # solving the simultaneous equations
    # to get P at 1 - l and l - 1
    x = (s * m + t) / (1 - s * l)
    y = (l * t + m) / (1 - l * s)

    # iterate from the closest side to improve precision
    if n < 0:
        return solve_recurrence(a, b, x, 0, limit + n)
    else:
        return solve_recurrence(c, d, y, 1, limit - n)

Experimental results for limit = 10, p = 0.1:
n       | P(n)            abs. error
========================================
-10     | 0.0000000E+00   --
-9      | 6.5802107E-19   0.0000000E+00
-8      | 6.5802107E-18   1.7995889E-30
-7      | 5.9879917E-17   1.7995889E-29
-6      | 5.3957728E-16   5.0003921E-28
-5      | 4.8568535E-15   8.1994202E-27
-4      | 4.3712339E-14   8.9993252E-27
-3      | 3.9341171E-13   5.1002066E-25
-2      | 3.5407061E-12   5.9938283E-25
-1      | 3.1866355E-11   5.9339980E-18
 0      | 2.8679726E-10   5.3406100E-17
 1      | 2.5811749E-09   3.3000371E-21
 2      | 2.3230573E-08   2.6999175E-20
 3      | 2.0907516E-07   2.2999591E-19
 4      | 1.8816764E-06   7.9981086E-19
 5      | 1.6935088E-05   1.9989978E-18
 6      | 1.5241579E-04   3.5000757E-16
 7      | 1.3717421E-03   1.5998487E-15
 8      | 1.2345679E-02   3.2000444E-14
 9      | 1.1111111E-01   6.9999562E-14
 10     | 1.0000000E+00   --

Notes:

It is clear from the code and equations that the recurrence limits / boundary conditions can be arbitrary.
Numerical precision can be improved with summation techniques such as Kahan-Neumaier.
There also exists an alternative explicit formula for the iterative method used in solve_recurrence, which may produce more accurate results if used in conjunction with library functions.
Comment: I'm not sure I get the premise: once you have (i), you can compute everything, as long as you fix P1 and P2, no?
Comment: @BlackBear what do you mean by `P1, P2`? The boundary conditions that OP has given? The latter are not adjacent terms but at the opposite ends of the recurrence range.
Comment: Ah, now I understand, the boundary conditions are on the first and the last element, not on the first two.
Answer: Recursion depends on breaking the problem into pieces, each of which is closer to a base case.  The formula you give is infinite because it depends on series terms that are equally undefined.  A simple-looking mathematical notation is no guarantee of computability.
In this case, you have to rewrite the recursion relation in non-circular terms.  You can still use recursion, but there has to be a definite end.  In the given formula, P[n] depends on P[n+1] and P[n-1], each of which depends directly upon P[n].  This is algorithmically circular.
You need to extract the algorithm from the base cases, starting from the ends and working your way in.  One of the unfortunate results of this recursion relation is that you have to solve the entire range [-limit, limit] in order to get the value for your desired position.  The base-case values ripple from the ends to wherever you have your viewpoint.
There is no tool to symbolically unravel this for you.  Most of all, note that your base cases do not appear in the equation.  Even if you provided those as additional equations, deriving the exponential series from this relationship  is beyond the analysis capabilities of today's solvers.
Comment: I perfectly understand this explanation and that's what my question is implying? Is there something (e.g. symbolic computation) that can tackle this kind of issues?
Answer: I have another solution using symbolic computation.
class X(object):
    """Representing unknown value which will be resolved in future"""
    def __init__(self, value=1.0):
        self.value = value

    def __add__(self, other):
        cls = self.__class__
        return cls(value=self.value+other.value)

    def __sub__(self, other):
        cls = self.__class__
        return cls(value=self.value-other.value)

    def __mul__(self, other):
        cls = self.__class__
        if isinstance(other, cls):
            return cls(value=self.value*other.value)
        elif isinstance(other, numbers.Real):
            return cls(value=self.value*other)
        else:
            raise TypeError(f'Cannot multiply with type {type(other)}')

    def __rmul__(self, other):
        return self.__mul__(other)

Instead of obtaining numeric results immediately we rely on the fact that resulting value will be expressed in some way as

and each intermediate term will be represented as

That's why we define add/subtract/multiplicate operations for our object.
So having a representation of such a symbol in a code we can solve this equation with an approach similar to accepted answer (we go from both -limit and limit sides and express other terms as yet unknown product). When reaching base point (0 state) we would have ratio of our probability and numeric value for that ratio which allows us to calculate the result easily
_memory = []
def fill_memory(n):
    global _memory
    _memory = [(0, X(1))]*(2*n+1)
    _memory[-n] = (0, X(0))
    _memory[n] = (1, X(0))

def resolve(n, p):
    q = 1-p
    for i in reversed(range(n)):
        # resolve from right to center
        prob_next = _memory[i+1]
        prob_prev = _memory[i-i]
        _memory[i] = (
            q*prob_prev[0] + p*prob_next[0],
            q*prob_prev[1] + p*prob_next[1],
        )

        # resolve from left to center
        prob_prev = _memory[-i-1]
        prob_next = _memory[-i+1]
        _memory[-i] = (
            q*prob_prev[0] + p*prob_next[0],
            q*prob_prev[1] + p*prob_next[1],
        )

    # calculate base probability
    solution = _memory[0]
    coef = (X(value=1) - solution[1]).value
    p0 = solution[0] / coef
    return p0

I have obtained correct and very precise results with this approach (I'm using p=0.6 and N=4 (limit))
def main():
    N = 4
    p = 0.6
    fill_memory(N)
    p0 = resolve(N, p)
    print(f'Probability for N={N} steps is {p0*100:.4}%')
    for i in range(2*N+1):
        print(i-N, '->', _memory[i-N])

4 - 83.505%
3 - 77.143%
2 - 69.231%
1 - 60.0%

As you can see it's the same result as when resolving it mathematically.

Refactor left recursion infinite loop


Sorting binary numbers according to this order relation and finding k-th largest.

Question: We have the following  order relation on positive integers:
let number A be less than number B in two cases:
• When the binary notation of A has fewer "ones" than B has.
• When the binary notation of A contains the same amount of "ones" that B has, then A is less than B when A is less than B in decimal notation
How would i quickly determine the k-th largest number in this order ?
I need tips im stuck .
Answer: Hint. Observe that, since the binary representation of $2^n$ is $1$ followed by $n$ zeros, one has $2^0 < 2^1 < 2^2 < 2^3 < \cdots\ $ for your order. Then compare these numbers with numbers having at least two ones in their binary representation.
Comment: I maybe didnt ask the question properly. I want to find kth largest from 0 to  some N inclusive where these numbers are sorted according to the relation. I see that we have 0, 1,2,4,8 ... for 1 one in binary then 3 , 5, 6,9 ,10 with 2 ones and i see that those can be formed by addition like 2+1 , 4+1,2+4 etc but i dont really understand the pattern behind it :C


Simulating game results - impact of win streaks

Question: I have a few questions related to the same topic:
Imagine you have a game (e.g. chess), where every time you win you gain some skill rating (SR), and every time you lose, you lose SR. If, however, you go on a winning streak (defined as winninng 2 or more games in a row) the SR you gain from each win increases as a function of how many you've won consecutively up until that point.
Having read multiple forums online, there appears to be 2 common strategies to keep your SR relatively stable and to prevent massive losses of SR during any one gaming session. The two strategies are:

Stop your gaming session as soon as you lose 1 game
Stop your gaming session as soon as you lose 2 games in a row

My first question is: is it possible to determine which is the better strategy without simulation?
I have tried setting up a basic simulation of this scenario in Python to answer the question empirically. It looks something like this:
num_sessions = 1000000
sr_per_win = 23
sr_per_loss = 23
sr_streak_multiplier = 3

# Stopping after 1 loss
sr_diff_1_loss = []
for i in range(num_sessions):
    cur_sr = 0
    win_streak = 0

    while True:
        game_result = random.randint(0, 1)  # Randomly decide game outcome

        if game_result:  # Win
            cur_sr += (sr_per_win + win_streak * sr_streak_multiplier)
            win_streak += 1
        else:  # Lose
            cur_sr -= sr_per_loss
            break

    sr_diff_1_loss.append(cur_sr)

sr_avg_1_loss = sum(sr_diff_1_loss) / len(sr_diff_1_loss)

# Stopping after 2 losses in a row
sr_diff_2_loss = []
for i in range(num_sessions):
    cur_sr = 0
    win_streak = 0
    lose_streak = 0

    while True:
        game_result = random.randint(0, 1)  # Randomly decide game outcome

        if game_result:  # Win
            cur_sr += (sr_per_win + win_streak * sr_streak_multiplier)
            win_streak += 1
            lose_streak = 0
        else:  # Lose
            cur_sr -= sr_per_loss
            win_streak = 0
            lose_streak += 1

            if lose_streak == 2:
                break

    sr_diff_2_loss.append(cur_sr)

sr_avg_2_loss = sum(sr_diff_2_loss) / len(sr_diff_2_loss)

There are 2 for loops, one for each strategy. Each time you win, you gain 23 SR, each time you lose you lose 23 SR. If you go on a win streak, you gain additional SR (on top of the base 23) which is calculated as 3*number of wins in a row. The game outcome is randomly determined.
I get some strange values when I look at the average SR change due to each strategy. For strategy 1, the average SR change is always equal to the multiplier (3). For strategy 2, average SR change is always equal to 3*multiplier (9). This is true regardless of the multiplier value.
So my second question: is there a reason why the average SR change is always a multiple of the win streak multiplier value? Or is there an error in my code?
Comment: I think right now you calculate additional SR as 3 * (number of wins in a row - 1)?
Answer: Strategy 1: stop your gaming session as soon as you lose 1 game.
Consider $R = (N+1)SR(P(W)-P(L))+M(N-1)$, where

$R$ is the point result after playing a streak of games
$N$ is the length of the winning streak. Note that the terms are $N-1$, as we stop when there is a loss
$SR$ is the point change
$P(W)$ is the probability of winning
$P(L)$ is the probability of losing
$M$ is the multiplier

In the random simulation, $P(W) = P(L) = 1/2$, so $R = M(N-1)$.
As $N$ is a geometric random variable with parameter $P(W)$, then the expected value is $1/P(W)$. Therefore, the expected result from strategy 1 is:
$E(R) = M/P(W) - M = 3/(1/2) - 3 = 3$
Answer: Strategy 2 using Markov Chains

$M$ - multiplier
$S$ - point change in SR
$p$ - probability of winning

Model 1:
Let us have an infinite Markov graph with vertices

$X_{\epsilon}$ - starting state
$X_0$ - state after 1 loss
$X_{00}$ - state after 2 losses in a row
$X_i$ - state after i-th win in a row

Edges have natural probabilities, e.g. we have $X_i \to^{p} X_{i+1}$ and $X_i \to^{1-p} X_0$ and so on.
Now we define $\mu_v$ - expected increase in SR travelling from state $X_v$ to $X_{00}$. We want to calculate $\mu_{\epsilon}$. We have
$$\mu_{00} = 0,\  \mu_0 = p(\mu_1 + S) + (1-p)(-S),\ \mu_{\epsilon} = p(\mu_1 + S) + (1-p)(\mu_0 - S)$$
$$\mu_i = p(\mu_{i+1} + S + iM) + (1-p)(\mu_0 - S),\ i \ge 1$$
Now this is an infinite system of equations. It probably can be solved by some tricky partial formula, but, we can transform it into finite system of equations with infinite sums.
Model 2
Definitions are the same. We have vertices

$X_{\epsilon}$ - starting state
$X_0$ - state after 1 loss
$X_{00}$ - state after 2 losses in a row
$X_1$ - state after 1 win

We define new edges from state $X_1$.

$X_1 \stackrel{1 - p}\longrightarrow X_0$ with value $-S$
$X_1 \stackrel{p^i(1-p)}\longrightarrow X_0, \ i \ge 1$ with value $(\sum_{k=1}^{i}kM) + (i - 1)S$

New edges from $X_1$ represent whole paths $X_1 \to X_{11} \to \dots \to X_{1^n} \to X_0$ in the old graph with adequate value. Now we have
$$\mu_{00} = 0,\  \mu_0 = p(\mu_1 + S) + (1-p)(-S),\ \mu_{\epsilon} = p(\mu_1 + S) + (1-p)(\mu_0 - S)$$
$$\mu_1 = \sum_{i \ge 1}[p^i(1-p)(\mu_0 + \sum_{k=1}^{i}kM + (i - 1)S)] - (1-p)S $$
$$\mu_1 = \mu_0 + (1-p)M\sum_{i\ge1}(p^i\frac{i(i+1)}{2}) + S(1-p)\sum_{i\ge1}(p^i(i-1)) - (1-p)S$$
$$\mu_1 = \mu_0 + \frac{Mp}{(1-p)^2} + \frac{Sp^2}{1-p} - (1-p)S$$
And after solving the above with $p = 1/2$ we obtain
$$\mu_0 = 2M,\ \mu_1 = 4M,\ \mu_{\epsilon} = 3M$$
So the expected gain in SR from starting state is indeed $3M$, for any $S$.
Note: It's important to notice that $\mu_o = 2M$ is twice as much as in strategy 1 and it's no mistake, we model different things.


Why doesn't swapping male to female as the reference category in earnings regression change the value not just the sign on the coefficient?

Question: In an earnings regression (log linear, i.e. coefficient is an approximate % change), with gender why doesn't the coefficient value change (except the sign which obviously reverses) when you alternate between male and female as the base reference category? Gender pay gap % difference depends on the base used?
Comment: "Minimal" means an example that doesn't include a dozen or more irrelevant regressors!
Comment: Please post a minimal verifiable complete example as in https://stackoverflow.com/help/minimal-reproducible-example . Also consider that how much a percent is always depends on what the basis for your percents is.
Comment: So in Stata: reg lnSalaryMidpoint ib0.Female i.NACESector , base  and reg lnSalaryMidpoint ib1.Female  i.NACESector, base.....are giving me the same value on the gender coefficient, just different signs obviously, but since the base swaps from male to female, how can they be the same? Coefficient is  -.1182215  /  .1182215 depending on base
Comment: Can you please add that example (with outputs) to the post as an edit?
Answer: Because, as you say, a log-difference only approximates percentage changes.
When something goes up by 10% and then down by 10%, you are not back at the original value. Log-differences are symmetric. See also Are log difference time series models better than growth rates?.
This follows from Taylor-expanding the log as in
$$
\log(x)=\log(x_0)+\frac{1}{x_0}(x-x_0)+\text{Remainder}
$$
so that
$$
\log(x)-\log(x_0)\approx\frac{x-x_0}{x_0},
$$
where the approximation is good when $x$ and $x_0$ are close.
Illustration in R:
baseline <- 100
change <- 10
new.value <- baseline + change
(percentage.chg <- 100*((baseline + change)/baseline - 1))
(percentage.chg2 <- 100*((new.value + change)/new.value - 1))

(log.difference <- 100*(log(new.value) - log(baseline)))
(log.difference2 <- 100*(log(baseline) - log(new.value)))

Output:
> (percentage.chg <- 100*((baseline + change)/baseline - 1))
[1] 10

> (percentage.chg2 <- 100*((new.value + change)/new.value - 1))
[1] 9.090909

> (log.difference <- 100*(log(new.value) - log(baseline)))
[1] 9.531018

> (log.difference2 <- 100*(log(baseline) - log(new.value)))
[1] -9.531018

Graphically, the approximation looks as follows. The dark green curve is the log-function, the light green the Taylor approximation $\log(x_0)+(x-x_0)/x_0$ so that the red bar is the approximation error at the new value x_n:

Code:
x_0 <- 0.9
x_n <- 1.2

x <- seq(0.6, 1.3, by=.01)

plot(x, log(x), type="l", lwd=2, col="darkgreen", ylab="", cex.axis=.9)
segments(x_0, -0.6, x_0, log(x_0), lty=2)
segments(x_0, log(x_0), 0.5, log(x_0), lty=2)
segments(x_n, -0.6, x_n, log(x_n), lty=2)
segments(x_n, log(x_n), 0.5, log(x_n), lty=2)
lines(x, log(x_0) + 1/x_0*(x-x_0), lty=1, lwd=2, col="lightgreen")

segments(x_n, log(x_n), x_n, log(x_0) + (x_n-x_0)/x_0, lty=1, col="red", lwd=3)
segments(x_n, log(x_0) + (x_n-x_0)/x_0, 0.5, log(x_0) + (x_n-x_0)/x_0, lty=2)

segments(0.6, log(x_0), 0.6, log(x_n), lty=1, col="brown", lwd = 3)
text(0.61, 0, "log(x_n) - log(x_0)", col="brown", adj = 0, cex=.9, font=2)

segments(0.8, log(x_0), 0.8, log(x_0) + (x_n-x_0)/x_0, lty=1, col="orange", lwd = 3)
text(0.81, 0, "(x_n-x_0)/x_0", col="orange", adj = 0, cex=.9, font=2)

text(0.91, -0.52, "x_0", adj = 0, cex=.9)
text(1.21, -0.52, "x_n", adj = 0, cex=.9)
text(0.5, log(x_0), "log(x_0)", adj = 0, xpd=T, cex=.9)
text(0.5, log(x_n), "log(x_n)", adj = 0, xpd=T, cex=.9)
text(0.58, log(x_0) + (x_n-x_0)/x_0+.02, "log(x_0) + (x_n-x_0)/x_0", adj = 0, xpd=T, cex=.9)

text(0.65, -0.45, "log(x)", col="darkgreen", adj = 0, cex=.9, font=2)
text(0.58, -0.25, "log(x_0) + 1/x_0*(x-x_0)", col="lightgreen", adj = 0, cex=.9, font=2)

Answer: Other two explanations for your problem.

When estimating models with dummies, there is a very close relationship between the "omitted/base" category, the controlled category, and the constant.

For example:
$$ y = a_0+a_1 * female + a_2 * X +e $$
So, given the above model, a women's $Y$ would be
$$ \hat{y}_{female}=a_0+a_1+a_2*X $$
If we estimate the model, the other way round we would have:
$$ y = b_0+b_1 * male + b_2 * X +e $$
and the wages for a woman will be:
$$ \hat{y}_{female}=b_0+b_2*X $$
From here you see that $b_2$ and $a_2$ must be the same. and that $b_0=a_0+b1$
So, changing the base category, only re-arranges where the coefficient's sign not magnitude.
Now for your interpretation. It does have an impact on how you will interpret it.
Wage change for men: $(exp(b_1)-1)*100 = 12.52 $
Wage change for women: $(exp(a_1)-1)*100 =-11.13 $
Men earn approximately 12.52% more than women, or women earn 11.13% less than men.
HTH


Show that $P[x]+\langle x\rangle $ is a prime ideal of $R[x]$.

Question:
Show that if $P$ is a prime ideal of a  commutative ring $R$ with unity then $P[x]+\langle x\rangle $ is a prime ideal of $R[x]$.
Here $P[x]$ consists of all polynomials whose coefficients are in $P$.

I tried to show it using the fact that if $f(x)g(x)\in P[x]+\langle x\rangle $ then
either $f(x)\in P[x]+\langle x\rangle $ or $g(x)\in P[x]+\langle x\rangle $.
But I don't know how to show it.
Please help me out.
Answer: Consider the map
$$
\varphi\colon R[x]\to R/P, \qquad \varphi(f)=f(0)+P
$$
and prove it is a surjective ring homomorphism.
What's its kernel?
Comment: This a ridiculously simple and elegant proof (hint). +1
Comment: The kernel will contain P[x],but it is not equal to P[x] as any polynomial in R[x] with constant term belongs to P is in Lerner.Isn't it so?
Comment: @BalasubramannyanS The OP is interested in $P[x]+\langle x\rangle$, not in $P[x]$.
Answer: Let $p(x)q(x)\in P[x]+\langle x\rangle$
Now  $p(x)q(x)\in P[x]+\langle x\rangle$
$\implies p(x)q(x)=f(x)+\langle x\rangle $ where $f(x)\in P[x]$
$\implies p(x)q(x)-f(x)\in \langle x\rangle$
$\implies p(0)q(0)=f(0)\in P $
Now since $P$ is Prime ideal  $\implies $ either $p(0)\in P$ or $q(0)\in P$
Suppose $p(0)\in P$ then $p(x)=p(0)+xh(x) $ for some $h(x)\in R[x]$
Thus $p(x)\in P[x]+\langle x\rangle$


AD query - get bitlocker active computers

Question: I have query in Active Directory which should return all computers with bitlocker not active based on this script:
https://community.spiceworks.com/topic/1083065-bitlocker-status-on-all-computers
Script works fine so the values are there.
But my query is not returning anything.
It looks like this:
<code>(&(&(objectCategory=computer)(objectClass=msFVE-RecoveryInformation)(!(msFVE-RecoveryPassword=*))))
</code>
I want to return computers which dont have active bitlocker.
Can someone point me to right direction where could be mistake, still learning with ldap queries.
//EDIT
So i found out msFVE-RecoveryInformation is object by it self, when i do:
<code>(&(&(objectClass=msFVE-RecoveryInformation)(msFVE-RecoveryPassword=*)))
</code>
It filters objects with recovery keys but name of computers is coded in atribute "distinguishedName like this:
<code>CN=2020-02-10T16:32:51\+01:00{4C74584A-BF6C-4AFA-9E46-582DDFC207A6},CN=NAMEOFNTB,OU=computers,OU=blabla,DC=test,DC=local
</code>
Somehow i can filter only computers with this attribute?
Answer: You need to read the msDS-ParentDistName attribute in each msFVE-RecoveryInformation object, and then query for those distinguished names to get the computer objects.
Also, this is not a good way to measure this due to:

A system may have been re-imaged.
Encryption may be turned off or suspended indefinitely.
A system may be encrypted, but the recovery password/key not backed up to Active Directory.
A recovery password/key may have been re-generated/replaced but not backed up to Active Directory.
Some of the drives may be encrypted but others not.
It doesn't provide any information on the protectors used. For example, if only a TPM protector is used without a PIN.


Delete duplicates of values of two nested multidimensional arrays

Question: I'm struggling with the array_diff function and another solutions for my problem but nothing gives me the desired effect..
I have two multidimensional arrays (the nested depth not known) that returned from database and will encode and decode to JSON.
The arrays looks like this:
Array (
    [0] => Array ( [id] => 1 [lft] => 1  [rgt] => 2  )
    [1] => Array ( [id] => 2 [lft] => 3  [rgt] => 4  )
    [2] => Array ( [id] => 3 [lft] => 5  [rgt] => 6  )
    [3] => Array ( [id] => 4 [lft] => 7  [rgt] => 16 )
    [4] => Array ( [id] => 5 [lft] => 8  [rgt] => 9  )
    [5] => Array ( [id] => 6 [lft] => 10 [rgt] => 11 )
    [6] => Array ( [id] => 7 [lft] => 12 [rgt] => 15 )
    [7] => Array ( [id] => 8 [lft] => 13 [rgt] => 14 )
    [8] => Array ( [id] => 9 [lft] => 17 [rgt] => 18 )
)

Array (
    [0] => Array ( [id] => 17 [lft] => 1 [rgt] => 2  )
    [1] => Array ( [id] => 3  [lft] => 3 [rgt] => 10 )
    [2] => Array ( [id] => 9  [lft] => 4 [rgt] => 9  )
    [3] => Array ( [id] => 24 [lft] => 5 [rgt] => 6  )
    [4] => Array ( [id] => 81 [lft] => 7 [rgt] => 8  )
)

Now i would like to merge this two arrays so that i get the first array without elements that have the same id like elements from the second array.
The result should be like this:
Array (
    [0] => Array ( [id] => 1 [lft] => 1  [rgt] => 2  )
    [1] => Array ( [id] => 2 [lft] => 3  [rgt] => 4  )
    [3] => Array ( [id] => 4 [lft] => 7  [rgt] => 16 )
    [4] => Array ( [id] => 5 [lft] => 8  [rgt] => 9  )
    [5] => Array ( [id] => 6 [lft] => 10 [rgt] => 11 )
    [6] => Array ( [id] => 7 [lft] => 12 [rgt] => 15 )
    [7] => Array ( [id] => 8 [lft] => 13 [rgt] => 14 )
)

For example I have tried is with this modified function an other solution approaches but nothing seems to work. Can anybody help me?
Answer: You are right, you need array_udiff.
Try this:
$res = array_udiff($array1, $array2, function ($a, $b) {
    if ($a['id'] < $b['id']) {
        return -1;
    } elseif ($a['id'] > $b['id']) {
        return 1;
    } else {
        return 0;
    }
});


refresh section tag on submit using jquery in a jqueryMobile HTML page

Question: I am using a jquerymobile template from Dreamweaver6.0 and building a mobile app interface. On home screen, I have four buttons - say, View, Create, Update, Delete.
When I click Create, it opens a new screen (each screen that opens from these four buttons are defined as "sections" within the same index.html page).
In create "section", there are few form fields and a submit button. When I click on submit, my form values are being submitted to the database (I am using AJAX to do this). But the problem here is my page won't refresh when I click on Submit.
What I am looking for is, the "create section" should refresh once I click on submit and a drop down list existing in the "view" section of the same index.html page also should refresh (this section has newly entered details as drop-down elements, dynamically update from database.)
the HTML code:

CRUD Experiment

    <input value="View" type="button" data-role="button" data-icon="info">

    <input value="New" type="submit" data-role="button" data-icon="plus">

    <input value="Update" type="submit" data-role="button" data-icon="refresh">

    <input value="Delete" type="submit" data-role="button" data-icon="minus">

Cnonymn

    Back

CRUD Experiment

    <form>

        Select Employee
         <select name='names' id='names' size='1' onchange="getDetails(this)">
         <option>Select</option>
        </select>

        <input value="Show All" data-role="button" onClick = "getAllDetails()" type="button">

    </form>

Here are the details

Cnonymn

    Back

CRUD Experiment

    <form method="post" id="myForm">
      Name
      <input name="empName" id="emp_name" value="" type="text" data-theme="a">
      Date
      <input name="empDOB" id="emp_dob" value=""  data-theme="a">
      Gender
      <select name="empGender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true" style="display:none;">
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>
      Address
      <textarea name="empAddr" id="e_address" value="" type="text" data-theme="a"></textarea>

      Add Image
      <input name="image" id="image" value="" type="file" data-theme="a">

      Add Multimedia
      <input name="multimedia" id="multimedia" value="" type="file" data-theme="a">

      <input type="submit" id="insert" value="Submit">
    </form>

Cnonymn

What and where should I write the refresh functionality? This refresh should both "refresh the form screen" and "update dropdown list"
Comment: any help is appreciated. kindly look in to the issue. Thanks in advance
Answer: Instead refreshing the whole page(it would take longer time), you can reset(refresh) the forms.
Add IDs to your forms, and after ajax submit successfully, you can reset these forms.
Here is the demo http://jsfiddle.net/yeyene/SjbMd/5/
JQUERY
$(document).ready(function(){
    $('#btn_submit').on('vclick', function(){
        event.preventDefault();

        $(".ui-loader").show();
        $.ajax({
            type: 'POST',
            url: 'url',
            data: 'data',
            dataType: "json",
            success: function(data) {
                alert('Form successfully submitted!');
                $("#viewForm")[0].reset();
                $("#myForm")[0].reset();
                $(".ui-loader").hide();
            }
        });
    });
});

Comment: hi @yeyene - thank you for your response. I have exactly the same function written. But added the ".reset()" methods to the function. Only the current form fields are getting reset. The form which has the drop-down is not getting reset. I am not sure why. Is it because it's in a different section tag?
Comment: check here http://jsfiddle.net/yeyene/SjbMd/6/ , i didnt call the ajax submit and move the scripts outside ajax call, it also reset select form, you select anything first, then, fill the new form and submit. Then go back and check the select form.
Comment: ok. I think the problem here is - my drop-down works based on a script. It dynamically populates values from the database. and this is only working when I do a whole page refresh.
The code I am using for populating my dropdown is as follows -

function loadlist(selobj,url,nameattr)
{
    $(selobj).empty();
    $.getJSON(url,function(data)
    {
        $.each(data,function(i,obj)
        {
        $(selobj).append(''+obj['name']+'');
        });
    });
}
Comment: Just the form reset() (where my dynamically being populated drop-down is there) is not working here. reset() is only clearing off the field values or it's just setting back the form fields to their previous state.
what I am looking for is, the drop-down should "reload" - are there any methods that can reload just a drop-down?
Or can you please suggest me a different way to populate my drop-down, and which works with "reset()"?
Comment: is there any reason you want to reload drop-down list, i mean reloading will load the same data again, right?
Comment: no, reloading the drop-down should add-up the newly entered row from the database. Now am manually refreshing the page to see the new entry within the drop-down.
Comment: so, you can call again the drop-down list populate function again, after ajax success. loadlist(); it should refresh your drop-down, coz it is only one html file with different page sections.
Comment: logically, that's what I understood and did try the same.. but some how... after the ajax call and the loadlist(), it's not showing up :(
By the way, my data is coming from a PHP file. Would that be an issue?
Comment: or, there is an onclick reload page function, try this one? onclick="location.reload(true)"
Comment: hmm that's a good work-around for now i hope. But the screen jumps when reloaded :(
Comment: @yeyene... any idea on how to toggle the flip switch (am using it for Male/Female choosing option in a form) based on the database value?
Comment: of course, check here http://jsfiddle.net/yeyene/hRfwB/1/ ... try to change variable sex value from Male to Female and see effect.
Comment: you are just amazing. I think I need to think more deeper. It looks simple after you gave me the demo on jsfiddle. I tried many other things to do this. (for e.g. I tried to use my loadlist function which did not work - logically it won't :( )
Comment: now, everything is working fine right, glad it works for you.
Comment: @yeyene.. hope you are doing good.. can we refresh a table after an AJAX call? like how we do for a listview?
$('data-role=listview').refresh('listview')
Comment: That will do, please see... http://stackoverflow.com/questions/9334633/how-to-refresh-jquery-table-after-a-row-is-added-dynamically
Comment: @yeyene... thanks for your reply! I've already tried that but the style applies only for my first row.. :( all other rows (out of my 10 rows) look simple HTML. Also, am not able to get this as responsive. It looks good for a computer screen and a mobile screen. It fails for a tablet screen resolution


False Start penalty clarification

Question: In the Super Bowl this year Denver was called for a false start on the very first play of the game. The ref clearly stated the false start happened before the snap.
Why was the play allowed to continue? A false start penalty is a dead ball penalty, correct?
If so, the Broncos should have been penalized 5 yards and kept the ball. No safety allowed.
Answer: Denver was not penalized for a false start; they were penalized for illegal motion. The referee's hand signal is the same for both (hands rotating around each other).
The NFL's official play-by-play reads:

(14:53) (Shotgun) 18-P.Manning Aborted. 66-M.Ramirez FUMBLES at DEN 14, recovered by DEN-27-K.Moreno at DEN -8. 27-K.Moreno tackled in End Zone, SAFETY (56-C.Avril). Penalty on DEN-18-P.Manning, Illegal Motion, declined.

A false start is called when "an offensive player
who has assumed a set position charges or moves in such a way as to simulate the start of a play, or if an offensive player who is in motion makes a sudden movement toward the line of scrimmage." (NFL Rules 7.4.2)
Illegal motion (which is not a dead-ball foul) is called when an offensive player is moving forward at the snap or is never set for one second at any point before the snap (NFL Rules 7.4.7).
Peyton Manning was moving towards the line to call an audible when the ball was snapped; but since he was not simulating a snap, it was an illegal motion and not a false start.

False Start penalty clarification


MongoDB query show all value in array property when reference database

Question: I cannot show all`, if some value are in array property in mongo document. For example, I have some collection users, and such document:
This is collection friend
'list': [
{
  '_id': '123',
  'name':'Charlie',
  'age':50,
},
{
  '_id': '234',
  'name':'Micheal',
  'age':32,
},
{
  '_id': '345',
  'name':'Alice',
  'age':45,
}
]

This is collection seft
'name':'Paul',
  'age':43,
  'friends':
    [
        {  '$ref': 'friend',
           '$id': 123},
        {  '$ref': 'friend',
           '$id': 234},
        {  '$ref': 'friend',
           '$id': 345}
    ],

Now, let's suppose that I want to query "show all friends of Paul" like:
{
  'name':'Paul',
  'age':43,
  'friendsIDs':
  'friends':
    [
        {  '_id': '123',
           'name':'Charlie',
           'age':50 },
        {  '_id': '234',
           'name':'Micheal',
           'age':32},
        {  '_id': '345',
           'name':'Alice',
           'age':45 }
    ]
}

Comment: This needs to be done in your application layer, MongoDB doesn't support join.
Answer: MongoDB doesn't support joins. You can read more about that here.
However, you can manually reproduce the same scenario you described above in MongoDB by using some native JavaScript functions to fill in the friends array with the references and save the modified data to another collection say self_friends.
Let's demonstrate this by using the above schema. Insert the sample data in two collections self and friends:
// Populate self collection
db.self.insert([
    {
        'name':'Paul',
        'age':43,
        'friends':
        [
            {  '$ref': 'friend',
               '$id': 123},
            {  '$ref': 'friend',
               '$id': 234},
            {  '$ref': 'friend',
               '$id': 345}
        ]
    }
]);

// Populate friends collection
db.friends.insert([
    {
      '_id': '123',
      'name':'Charlie',
      'age':50,
    },
    {
      '_id': '234',
      'name':'Micheal',
      'age':32,
    },
    {
      '_id': '345',
      'name':'Alice',
      'age':45,
    }
]);

The following operation will populate another collection self_friends with the desired result:
db.self.find({"name" : "Paul"}).forEach(function(doc){
        var friends = doc.friends.map(function(f){
            //var friend = db.friends.findOne({_id: f["$id"].toString()})
            // Or use @SylvainLeroux's brilliant suggestion
            var friend = db.getCollection(f["$ref"]).findOne({_id: f["$id"].toString()})
            return friend;
        });
        doc.friends = friends;
        db.self_friends.save(doc);
})

Querying the db.self_friends collection with db.self_friends.find() will give the result:
/* 0 */
{
    "_id" : ObjectId("5549f2ff180e849972939047"),
    "name" : "Paul",
    "age" : 43,
    "friends" : [
        {
            "_id" : "123",
            "name" : "Charlie",
            "age" : 50
        },
        {
            "_id" : "234",
            "name" : "Micheal",
            "age" : 32
        },
        {
            "_id" : "345",
            "name" : "Alice",
            "age" : 45
        }
    ]
}

Comment: Given the OP document stores DBRef, _maybe_ you should use something like `db.getCollection(f["$ref"]).findOne({_id: f["$id"].toString()})` -- that being said, I don't think there is any benefit in using DBRef here instead of plain id. Or is it ?
Comment: @SylvainLeroux That's a great suggestion actually, would make much more sense to use the `$ref` key to get the collection with the value. I also would concur it wont be too beneficial to use DBRefs in the case above as the `_id`s are stored as strings in the reference collections.


Differentiating a homogeneous function

Question: I've been working through some problems in my college differential equations textbook, and I've come to one which asks for a proof that if $f(x, y)$ is a homogenous function of degree $n$, then:
$$
x \frac{\partial f}{\partial x} + y \frac{\partial f}{\partial y} = n f
$$
I started with the definition of a homogeneous function:
$$
f(tx, ty) = t^n f(x, y)
$$
To get a factor of $n$ somewhere, the obvious thing to try is to differentiate with respect to $t$:
$$
\begin{align}
\frac{\partial f}{\partial x} \frac{\partial}{\partial t}(tx) + \frac{\partial f}{\partial y} \frac{\partial}{\partial t}(ty) & = n t^{n-1} f(x, y)\\
x \frac{\partial f}{\partial x} + y \frac{\partial f}{\partial y} & = n t^{n-1} f(x, y)
\end{align}
$$
That's almost in the right form except for that pesky factor of $t^{n-1}$.  Where did I go wrong?
Comment: Note that in the left hand side you evaluate $\frac{\partial f}{\partial x}(tx,ty)$. For $t=1$ this is exactly what you want.
Answer: Hint: Fix $(x,y)$ and let $g(t) = f(tx,ty).$ There are two ways to compute $g'(1).$

Differentiating a homogeneous function


What happens if only one runner reaches base on a double steal?

Question: There are two outs, with men on first and third. The one man leaves first and gets caught in a rundown. The other man steals home as a result. The first man gets tagged out, but not before the other run reaches home.
Is the run counted or not, since the one runner reached home first? That is, BEFORE the out? (In the actual play I'm thinking of, Pittsburgh vs. Atlanta, both men reached.)
Do I assume correctly if the man on first made the second (instead of third) out, that the run is counted?
Comment: @Joe. No. My question is does a run count if it is made BEFORE an unforced out?
Comment: Sure, and the answer to your question is exactly the same as in the linked question.  To the point the same rule is quoted.
Answer: If a runner scores before the third out is made on a play such as you describe, the run counts. The runner on first stealing second is not considered a force play, therefore, the run counts.
Rule 5.08(a) states:

One run shall be scored each time a runner legally advances to
  and touches first, second, third and home base before three men
  are put out to end the inning.
EXCEPTION: A run is not scored if the runner
  advances to home base during a play in which the third
  out is made (1) by the batter-runner before he touches
  first base; (2) by any runner being forced out; or (3) by
  a preceding runner who is declared out because he
  failed to touch one of the bases.

The scenario described follows the rule, and does not fall into any of the three exceptions.
Please also note that the rules were reorganized for the 2015 season, so some rules are in different places in the book.