text:
Q: How can I do a swap between two elements belonging to the same polymorphic variable? What is the best method when you need interchange the values in two polymorphic elements? (Using standard fortran 2008).
I'm sending an example (please try don't modify the type variables).
The problems that I have using intel compiler v.19 and gfortran 8.1 in windows are different.
Here a complete example. Look at the subroutine where I have defined the swap procedure. Currently is activate the version that works in GFortran but I have error with intel compiler. If you comment this part and uncomment the lines for ifort, then works for intel and not for gfortran....
    Program Check
   implicit none

   !> Type definitions
   Type :: Refl_Type
      integer,dimension(:), allocatable :: H
      integer                           :: Mult  =0
   End Type Refl_Type

   Type :: RefList_Type
      integer                                     :: Nref
      class(refl_Type), dimension(:), allocatable :: Reflections
   end Type RefList_Type

   Type(RefList_Type)            :: List
   Type(Refl_Type), dimension(3) :: Refl_Ini

   !> Variables
   integer :: i

   !> Init
   Refl_Ini(1)%H=[1, 0, 0]; Refl_Ini(1)%Mult=1
   Refl_Ini(2)%H=[0, 2, 0]; Refl_Ini(2)%Mult=2
   Refl_Ini(3)%H=[0, 0, 3]; Refl_Ini(3)%Mult=3

   List%Nref=3
   List%Reflections=Refl_Ini

   !> Print Step:1
   do i=1, List%Nref
      print '(i3,2x,3i4,2x,i3)', i,List%Reflections(i)%H, List%Reflections(i)%Mult
   end do
   print*,' '
   print*,' '

   !> Swap
   call Swap_Elements_List(List, 1, 3)

   !> Print Step:2
   do i=1, List%Nref
      print '(i3,2x,3i4,2x,i3)', i,List%Reflections(i)%H, List%Reflections(i)%Mult
   end do

Contains

   Subroutine Swap_Elements_List(List, i, j)
      !---- Argument ----!
      type (RefList_Type), intent(in out) :: List
      integer,             intent(in)     :: i,j

      !---- Local Variables ----!
      class(Refl_Type), allocatable :: tmp

      !> IFort
      !tmp=List%reflections(i)
      !List%reflections(i)=List%reflections(j)
      !List%reflections(j)=tmp

      !> Gfortran
      associate(t1 => list%reflections(i), t2 => list%reflections(j), tt => tmp)
         tt=t1
         t1=t2
         t2=tt
      end associate
   End Subroutine Swap_Elements_List

End Program Check

Any suggestion?

A: Compiling the original code with gfortran-8.2 gives
    test.f90:34:6:
           List%reflections(i)=List%reflections(j) !!<---
          1
    Error: Nonallocatable variable must not be polymorphic in
           intrinsic assignment at (1) - check that there is a
           matching specific subroutine for '=' operator

I think this is because List % reflections(i) is not separately allocatable (even though List % reflections itself is allocatable as an array of uniform type). This point seems to be discussed in detail, e.g., in this Q/A page, which suggests two alternative approaches: (A) convince the compiler that all elements will be of the same type; or (B) use an (array) container.

If we use the "container" approach, I think we can use move_alloc() to swap two polymorphic objects (without knowing the dynamic type). For example, a bit modified version of the original code may be
program main
   implicit none

   type :: Refl_t
      integer, allocatable :: H(:)
   endtype

   type, extends(Refl_t) :: ExtRefl_t
      real :: foo
   endtype

   type :: RefList_t
      class(Refl_t), allocatable :: refl
   endtype

   type(RefList_t) :: list( 3 )

   call init()

   print *, "Before:"
   call output()

   call swap( 1, 2 )

   print *, "After:"
   call output()

contains

   subroutine swap( i, j )
       integer, intent(in) :: i, j
       class(Refl_t), allocatable :: tmp

       call move_alloc( from= list( i )% refl, to= tmp             )
       call move_alloc( from= list( j )% refl, to= list( i )% refl )
       call move_alloc( from= tmp,             to= list( j )% refl )
   end
   subroutine init()
       integer i
       do i = 1, 3
           allocate( ExtRefl_t :: list( i ) % refl )

           select type( x => list( i ) % refl )
               type is ( ExtRefl_t )
                   x % H   = [ i, i * 10 ]
                   x % foo = i * 100
           endselect
       enddo
   end
   subroutine output()
       integer i
       do i = 1, 3
           select type( x => list( i ) % refl )
               type is ( ExtRefl_t )
                   print *, "i = ", i, " : H = ", x % H, " foo = ", x % foo
           endselect
       enddo
   end
end program

Result (gfortran-8.2):
 Before:
 i =            1  : H =            1          10  foo =    100.000000
 i =            2  : H =            2          20  foo =    200.000000
 i =            3  : H =            3          30  foo =    300.000000
 After:
 i =            1  : H =            2          20  foo =    200.000000
 i =            2  : H =            1          10  foo =    100.000000
 i =            3  : H =            3          30  foo =    300.000000

I think we could also use polymorphic assignment for the above swap() routine, for example:
   subroutine swap( i, j )
       integer, intent(in) :: i, j
       class(Refl_t), allocatable :: tmp

       tmp              = list( i ) % refl
       list( i ) % refl = list( j ) % refl
       list( j ) % refl = tmp
   end

This compiles with gfortran-8.2, but gives a strange result... (a possible compiler bug?). I guess newer compilers like GCC-9 or Intel Fortran may give an expected result.

On the other hand, if we use a polymorphic array, we may need to use select type explicitly for swapping the two elements. (But I hope there is a different approach...) The code may then look like:
program main
   implicit none

   type :: Refl_t
      integer, allocatable :: H(:)
   endtype

   type, extends(Refl_t) :: ExtRefl_t
      real :: foo
   endtype

   class(Refl_t), allocatable :: refls( : )

   allocate( ExtRefl_t :: refls( 3 ) )
   call init()

   print *, "Before:"
   call output()

   call swap( 1, 2 )

   print *, "After:"
   call output()

contains

   subroutine swap( i, j )
       integer, intent(in) :: i, j

       selecttype ( refls )
           type is ( ExtRefl_t )
               block
                 type(ExtRefl_t) :: tmp

                 tmp        = refls( i )   !<-- assignment of concrete type
                 refls( i ) = refls( j )
                 refls( j ) = tmp
               endblock
           class default
               stop
       endselect
   end
   subroutine init()
       integer i

       select type( refls )
           type is ( ExtRefl_t )
               do i = 1, 3
                   refls( i ) % H   = [ i, i * 10 ]
                   refls( i ) % foo = i * 100
               enddo
       endselect
   end
   subroutine output()
       integer i
       select type( refls )
           type is ( ExtRefl_t )
               do i = 1, 3
                   print *, "i = ", i, " : H = ", refls( i ) % H, &
                            " foo = ", refls( i ) % foo
               enddo
       endselect
   end
end program

(The result is the same as above.)

A: The answer by roygvib summarizes the problem well. If this assignment is to be performed in user's code where the types are known or are known to be from a small set of possible types, one can just protect the assignment by the select type typeguard.
The real problem happens in a generic code that is written without the knowledge of the user's derived types. Therefore it may have no access to possible user-defined assignments. I suggest a possible solution using a callback procedure. Basically, the user defines an assignment or swap procedure which is then called by the library code.
subroutine sub_that_needs_assignments(array, assign)
  class(*) :: array
  interface
    subroutne assign(out, in)
    end subroutine
  end interface

  call assign(array(i), array(i+1))

  !or you can even assign a new elemnt from somewhere else
  ! possibly  protect by same_type_as()
end subroutine

in the user's code
   subroutine assign_my_type(out, in)
     class(*), ... :: out
     class(*), ... :: in

     select type (out)
       type is (my_type)
         select type (in)   ! not always necessary
           type is (in)
             out = in

         end select
      end select
      !add appropriate error checking

  end subroutine


text:
Q: How to process standart html tags in xml file using xslt I have not practiced XML in over a year.
My question is, using the samples below, why my for-each statement is only printing the first paragraph.
If you are wanting to know why my XML is using standard HTML "p" tags that I am trying to put back into "p" tags in my XSL file: the reason is I am batch processing several long writer documents from a word processor into HTML files. There are thousands (maybe tens of thousands) of paragraph tags. I cannot output XML files in any format I can use or manipulate the way I want.
I can however save the HTML file with an XML extension and work with that. I have already converted a few other files, but not tried to for-each the  tags yet.
My XML file
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>

<Library>
    <Books>
        <MyBooks>

            <my_favorite_book>
                <title>the title of my favorite book</title>

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

paragraph 6

paragraph 7

paragraph 8

paragraph 9

           </my_favorite_book>

        </MyBooks>
    </Books>
</Library>

My XSL file
    <?xml version="1.0"?>
    <xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

            <xsl:template match="/">

                                <xsl:value-of select="Library/Books/MyBooks/my_favorite_book/title" />

                    <xsl:for-each select="Library/Books/MyBooks/my_favorite_book">

                            <xsl:value-of select="p" />

                    </xsl:for-each>

        </xsl:template>
    </xsl:stylesheet>

The Web browser output (FireFox 54.0.1 (32-bit))

A:
My question is, using the samples below, why my for-each statement is
  only printing the first paragraph.

Because your for-each,
<xsl:for-each select="Library/Books/MyBooks/my_favorite_book">

is selecting the only my_favorite_book, and your xsl:value-of,
   <xsl:value-of select="p" />

is selecting all of my_favority_book's children only to take the string value of the first such p,
   paragraph 1

The shortest fix to your program would be to loop over the paragraphs,
<xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">

and take the value-of each,
   <xsl:value-of select="." />

or, instead of looping with xsl:for-each, you might use apply-templates instead:
<xsl:apply-templates select="Library/Books/MyBooks/my_favorite_book/p">

if you come to have further pattern matching to do, or copy-of if you don't:
<xsl:copy-of select="Library/Books/MyBooks/my_favorite_book/p">

A: I discovered the answer in another Stack Overflow post that worked.
That is, to change the above code to the code below:
<xsl:for-each select="Library/Books/MyBooks/my_favorite_book/p">

                        <xsl:value-of select="." />

                </xsl:for-each>

Also, while looking at some other projects I did, and reading other posts here, I now recall that using the "template" methods yielded a smoother and more flexible result, so I am going to radically modify my XSL file tomorrow and leave an update here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJS child process PID does not match the real process I'm using windows, and I'm doing this experiment,
console.log( _.process.exec( "mongod --dbpath . --port 8083 --bind_ip 127.0.0.1" ).pid );

The problem is, when I do a tasklist command, the PID from that output points to the command prompt task and not to the mongod.exe task.
Is there a way to get the real PID of the mongod.exe task?

A: That's because mongod is a child process of cmd and tasklist doesn't print child process ids.
Given a parent process id, you can get a list of it's children with a wmi query:
wmic process where (ParentProcessId=CMD_PID) get Caption, ProcessId

Replace CMD_PID with the parent(cmd) process id.

A: I'm looking at this now and thinking that I'll need to run process.pid in the child and signal it back to the parent. The parent then needs to keep track of the number in case the child needs to be killed.
I was hoping this wouldn't be so complicated?


text:
Q: Django EmbeddedField raises ValidationError because of renamed field I've got a Django application with djongo as a database driver. The models are:
class Blog(models.Model):
    _id = models.ObjectIdField()
    name = models.CharField(max_length=100, db_column="Name")
    tagline = models.TextField()

class Entry(models.Model):
    _id = models.ObjectIdField()
    blog = models.EmbeddedField(
        model_container=Blog
    )

When I run this application, I got an error:
File "\.venv\lib\site-packages\djongo\models\fields.py", line 125, in _validate_container
    raise ValidationError(
django.core.exceptions.ValidationError: ['Field "m.Blog.name"  of model container:"<class \'project.m.models.Blog\'>" cannot be named as "name", different from column name "Name"']

I want to keep the name of the field name in my model and database different because the database already exists, and I can't change it. The database uses camelCase for naming fields, whereas in the application, I want to use snake_case.
How to avoid this error?

A: The error you're getting is due to Djongo trying to validate the field name as in the model and Name as created in the database.
You can specify for Djongo to not validate the fields of the model container by setting validate=False in the EmbeddedField.
Modify your Entry model as:
class Entry(models.Model):
    _id = models.ObjectIdField()
    blog = models.EmbeddedField(
        model_container=Blog, validate=False
    )

This should fix your error.

A: you might need to do manage.py makemigrations and manage.py migrate

A: try this:
class Blog(models.Model):
    _id = models.ObjectIdField()
    name = models.CharField(max_length=100, db_column="BlogName")
    tagline = models.TextField()

or this
class Blog(models.Model):
    _id = models.ObjectIdField()
    BlogName = models.CharField(max_length=100, db_column="name")
    tagline = models.TextField()

When you use the "db_colum" parameter, you must choose a different name, even if it is lowercase or uppercase

A: I think it should be db_column instead of bd_column so:
class Blog(models.Model):
    _id = models.ObjectIdField()
    name = models.CharField(max_length=100, db_column="Name")
    tagline = models.TextField()


text:
Q: How do I run South migrations (Django) on a database server? Originally, I've just had servers that have both Django, South and my database installed (web + database server combined). But now, we're moving to a dedicate database server, and a dedicate web app server.
Since the database server doesn't have Django or South installed, how can I run migrations? Or at least, what's the best way to update the database with new schema changes? It's MySQL if that helps.

A: It doesn't matter if the database is running on the same machine as django/South. Wherever your django installation lives has the database configured in its settings. South migrations should work exactly the same.


text:
Q: jQuery- Flickering menubar I would like to develop a menubar where the tabs expand upwards as soon as a user puts the mouse cursor over a tab. Actually it works quite well, despite there is one problem: If the user puts the mouse-cursor over one tab and then moves it above the tab very fast, the tab starts moving up and down very often and very fast which looks like as if it would flicker.
Here is an example of how I implemented it: http://jsfiddle.net/enne87/wLGDG/34/
I hope you know what I mean when I say "Move the cursor over the tab and then upwards". If not, I can show you a video which shows more precisely what i mean.
Btw. here is the javascript-code for the animation:
  $('#primaryMenu ul.menu li:nth-child(1)').hover(
  function () {
      $(this,this).stop(true,true).animate({bottom: '+=55'}, 300, function() {});
  },
  function () {
      $(this,this).stop(true,true).animate({bottom: '-=55'}, 300, function() {});
  }
);

I would be very thankful for help.
Cheers, enne

A: I know this is not fixed code, but here's the problem:
The Problem
You are actually animating the location of the whole li node, which is creating artifacts. To clarify for other readers:

*

*go to the live sample on the fiddle and approach a menu item from underneath. Do NOT move your mouse

*the animation up will complete, but the mouse is now seen to trigger 'leave' and it will start moving back down

*The animation down will complete, but then 'enter' is triggered and it begins up again, in an infinite cycle.

The flickering comes from a more extreme version of this:

*

*approach from beneath the menu. The animation starts to move up

*Move your mouse upwards toward the animating item

As you move the mouse, the upwards "stop" is triggered, sending the element directly to the top of the animation. But then you will re-enter the element again, triggering the animation if it's not already at the top. Moving the mouse upwards while the element is NOT quite yet at the top will trigger the 'leave', sending the element directly to the bottom.
whew
The fix
So, the fix? Instead of animating the location of the menu, devise a way to animate the height such that it's not pushing down but rather up (with the current CSS, simply animating height will expand the gray li downward, not up). This will involve revising the CSS to accomodate that switch. If the design dictates that the whole block needs to stay 200px tall (to give the illusion that it is moving), then the event should be bound to some sort of transparent container instead of the LI.
Unrelated Stuff
In the meantime, there are a few fundamental things wrong with the original code:

*

*Why is the selector $(this,this) for the mouseenter/mouseleave? The second optional selector is a context. Using the same selector for both does not create a context, so you should just use $(this).

*The event doesn't need to be bound twice. They're both li that meet the same description, so you can just have your selector look for:
$('#primaryMenu ul.menu li').hover( /* ... */);

Or if it's actually critical for some reason to specify which li have the event, gang them together:
$('#primaryMenu ul.menu li:nth-child(1), #primaryMenu ul.menu li:nth-child(2)')


text:
Q: "second communication we have sent" or "second communication we had sent"?
This is the second communication we have sent and we are much surprised at receiving no answer.

My book says NO ERROR.
But "we have sent" should be "we had sent", correct me if I'm wrong.

A: This is the second communication we have sent and we are very surprised at receiving no answer.
The sentence is grammatically correct to be in the present.  Look at it he following sentence in the past:
This was the second communication we had sent and we were very surprised at receiving no answer. You use the past perfect to refer to an action that happened before another action in the past.


text:
Q: Why is this small (155 lines-long) Pacman game on Python running so slow? I have already cut everything I could from the main loop. I also optimized collisions for dynamic and static objects, reducing considerably the number of iterations. But it is still slow on his machine. I'll post the entire file for the case someone wants to test it, but you can just jump to the main loop at "while Exit==false:".
import pygame
from pyeuclid import Vector2
from math import sin,cos,pi
from random import random

class Thing:
    def __init__(self,pos):
        self.pos = pos
        things.append(self)
    def update(self): pass
    def draw(self,img): pass
    def collide(self,who): pass

class DynamicThing(Thing):
    def __init__(self,pos):
        Thing.__init__(self,pos)
        self.vel = Vector2(0,0)
        self.lastPos = pos
        self.col = (255,255,0)
        self.r = 12
        dynamic_things.append(self)
    def update(self):
        self.lastPos = self.pos
        self.pos = self.pos + self.vel
    def draw(self,img):
        pygame.draw.circle(img, (0,0,0), [int(n) for n in self.pos], self.r, self.r)
        pygame.draw.circle(img, self.col, [int(n) for n in self.pos], self.r-2, self.r-2)
    def collide(self,obj):
        Thing.collide(self,obj)
        if isinstance(obj,Wall):
            self.pos = self.lastPos

class Wall(Thing):
    def draw(self,img):
        x,y = self.pos.x, self.pos.y
        pygame.draw.rect(img, (90,90,200), (x-16,y-16,32,32), 0)

class Pacman(DynamicThing):
    def __init__(self):
        DynamicThing.__init__(self,Vector2(32*9+16,32*12+16))
        self.col = (255,255,0)
    def update(self):
        DynamicThing.update(self)
        if (keyPressed[pygame.K_LEFT]): self.vel.x = -1
        if (keyPressed[pygame.K_RIGHT]): self.vel.x = 1
        if (keyPressed[pygame.K_DOWN]): self.vel.y = 1
        if (keyPressed[pygame.K_UP]): self.vel.y = -1
        if (self.vel.x==-1 and not keyPressed[pygame.K_LEFT]): self.vel.x = 0
        if (self.vel.x==1 and not keyPressed[pygame.K_RIGHT]): self.vel.x = 0
        if (self.vel.y==1 and not keyPressed[pygame.K_DOWN]): self.vel.y = 0
        if (self.vel.y==-1 and not keyPressed[pygame.K_UP]): self.vel.y = 0
    def collide(self,obj):
        DynamicThing.collide(self,obj)
        if isinstance(obj,Ghost):
            self.pos = Vector2(32*9+16,32*12+16)

class Ghost(DynamicThing):
    def __init__(self):
        DynamicThing.__init__(self,Vector2(32*9+16,32*10+16))
        self.col = (int(random()*255),int(random()*255),int(random()*255))
        self.vel = Vector2(0,-2)
    def update(self):
        DynamicThing.update(self)
        if random()<0.01:
            self.vel = [Vector2(2,0),Vector2(-2,0),Vector2(0,2),Vector2(0,-2)][int(random()*4)]
    def collide(self,obj):
        DynamicThing.collide(self,obj)
        if isinstance(obj,Wall):
            self.vel = [Vector2(2,0),Vector2(-2,0),Vector2(0,2),Vector2(0,-2)][int(random()*4)]

def thingAtPos(pos):
    tile_pos = Vector2(int(pos.x/32),int(pos.y/32))
    return map[tile_pos.y][tile_pos.x]

# initializate stuff
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([32*19,32*22])
points_in_unit_circle_border = [Vector2(cos(float(a)/8*2*pi),sin(float(a)/8*2*pi)) for a in xrange(8)]
things = []
dynamic_things = []
exit = False

map =  [[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
        [1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1],
        [1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1],
        [1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1],
        [1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1],
        [1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1],
        [1,1,1,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
        [1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1],
        [1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1],
        [1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1],
        [1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1],
        [1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
        [1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1],
        [1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1],
        [1,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1],
        [1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1],
        [1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1],
        [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
        [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]

#create pacman, walls, ghosts
pacman = Pacman()
for y in xrange(len(map)):
    for x in xrange(len(map[y])):
        if (map[y][x]==1):
            map[y][x] = Wall(Vector2(x*32+16,y*32+16))
for i in xrange(4):
    Ghost()

while exit==False:
    clock.tick(45)

    screen.fill([255,255,255])
    keyPressed = pygame.key.get_pressed()

    # events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit = True
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            exit = True

    # more ghosts
    if random()<0.001: Ghost()

    # updates e draws
    for thing in things:
        thing.update()
        thing.draw(screen)

    # collisions
    for A in dynamic_things:
        #dynamic vs dynamic
        for B in dynamic_things:
            if A!=B and abs(A.pos-B.pos)<(A.r+B.r):
                A.collide(B)
                B.collide(A)
        #dynamic vs walls
        for circle_point in points_in_unit_circle_border:
            thing_in_a_border = thingAtPos(A.pos+circle_point*12)
            if isinstance(thing_in_a_border,Wall):
                A.collide(thing_in_a_border)

    pygame.display.flip()

pygame.quit ()

A: You are redrawing and fliping the whole screen in every loop. I didn't test your program, but on the pacman I know, there are only 5 moving sprites on the screen, you should try to only blit those every frame (and of course if something else changes, that too). And don't display.flip(), just update the areas of the screen that you changed (that normally speeds up a lot).
Of course you need to stop blanking the screen every frame for that, and there will be much management of what to update. There is some extra support for dirty sprites in pygame http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.DirtySprite that help you with that. Or you could maybe just update all 'active' sprites by blanking the position they where and redrawing them in the new position (and obviously everything that also is in those two areas). Collect the effected rects in a list and pass that to update_rects() instead of flipping the screen. There should be no need in drawing the walls in a pacman game in every frame...

A: Probably not a big source of slowness, but "while exit==False:" requires a little more bytecode to execute than "while not exit:".


text:
Q: INSERT INTO @table, where @table is a variable I have run into a little bit of a problem: I want to create a procedure that inserts some rows in a table specified via parameter. So along the code I have reached this point:
CREATE PROCEDURE my_proc @tableName VARCHAR(30)
AS
    -- ...some code...
    INSERT INTO @tableName VALUES(...some values...)
    -- ...some code...
GO

This doesn't work so maybe I'm missing something.
P.S: I'm working in Microsoft SQL Server Management Studio 2018

A: You can only use variables for constants in a query -- not for identifiers.  So, you need to use dynamic SQL:
declare @sql nvarchar(max);

set @sql = 'insert into [tablename] values ( . . . )';

set @sql = replace(@sql, '[tablename]', quotename(tablename));

exec sp_executesql @sql;

Two points.  First, if you are planning in on passing the table name using a multi-part identifier, then quotename() is not appropriate.
More importantly, passing table names around like this is almost never needed in a relational database.  If you find the need to do this, you likely have a problem with your data model.  I would guess that you have multiple tables with the same structure -- and these should be combined into a single table rather than multiple tables.
To handle quotes strings:
set @sql = 'insert into [tablename] values (''aaa'', ''bbb'', . . . )';

Those are repeated single quotes (''), not double quotes (").


text:
Q: docker containers shutdown continuously I follow the official tutorial of deploying docker services https://docs.docker.com/get-started/part5/#add-a-new-service-and-redeploy, in the first time i tried this the containers was running as expected but after that the containers shutdown and restarting (i notice that using the visualizer service provided by docker )
and when i execute the command :
docker stack ps getstartedlab

NAME                     DESIRED STATE    CURRENT STATE
ERROR
getstartedlab_web.1      Running          Preparing 2 seconds ago
 \_ getstartedlab_web.1  Shutdown         Failed 4 minutes ago
"task: non-zero exit (2)"

i read in this post https://github.com/docker/machine/issues/3747 that the problem came from the firewall that may block the icmp, i tried to ping docker.com and i had 100% loss packet but when i ping google.com it's ok with no loss packets.
the result of docker ps --all is :
CONTAINER ID        IMAGE                             COMMAND             CREATED             STATUS                        PORTS               NAMES
9f67c82da7c7        username/repo:tag                 "python app.py"     2 minutes ago       Exited (2) 2 minutes ago                          getstartedlab_web.2.zcnr0ld9bioy0dffsxmn8zss5
f59e413b0780        username/repo:tag                 "python app.py"     4 minutes ago       Exited (2) 4 minutes ago                          getstartedlab_web.5.ymxgnsf7n8306yr8963xyyljv
9ab631c4057c        username/repo:tag                 "python app.py"     10 minutes ago      Exited (2) 10 minutes ago                         getstartedlab_web.5.zr3gsvgbyxs8c51fiko5h9jxp
bee5816ce1f2        dockersamples/visualizer:stable   "npm start"         15 minutes ago      Up 15 minutes                 8080/tcp            getstartedlab_visualizer.1.oyiqwb5esq6zakcdtiw4txh8a
cadca594f8cd        username/repo:tag                 "python app.py"     24 hours ago        Exited (2) 24 hours ago                           getstartedlab_web.1.zehutsl9cefrccqrj86dz4ap7
576b1a6db0b0        username/repo:tag                 "python app.py"     24 hours ago        Exited (2) 24 hours ago                           getstartedlab_web.5.za9xvxpo5yvl20kha9sjcimmz
2804ebc4fc0c        username/repo:tag                 "python app.py"     24 hours ago        Exited (2) 24 hours ago                           getstartedlab_web.1.zlk42chspvym3jxkzs2nc8k2d
03efb2b04489        dockersamples/visualizer:stable   "npm start"         24 hours ago        Exited (255) 16 minutes ago   8080/tcp            getstartedlab_visualizer.1.qyp4egtu9vcd31kf2jxtzxko3
b85fd1600955        username/repo:tag                 "python app.py"     2 days ago          Exited (2) 2 days ago                             getstartedlab_web.5.kzrj3m5c3jgkuox0ulpszizee

and the
 docker logs 9f67c82da7c7
  python: can't open file 'app.py': [Errno 2] No such file or directory
exuse me for representation of the results of those commands because when i copy past the results the lines breaks, how to copy past and preserve the same displaying ?
can anyone have a fix to this problem ? thanks.


text:
Q: trying to locate the correct file to edit my internal linking anchor tags I am trying to locate the correct file to edit my internal linking anchor tags i.e.<a href=
Can anyone point me to to the correct file? When I view the source code I see about 50 of them but I am not able to locate them in any files for editing????
I have looked in Header, Footer, Functions and many other hooks but could not locate the anchor tags???

A: Please be more specific about what you mean by "internal linking anchor tags".
If it's something like your main logo internal homepage link, it might be hard coded into your header.php file, but if it's a link inside of post content, you would find it in the post editor. So depending on what and where it is, the links could be displayed in a number of different ways.
Update: You can edit your WordPress sites navigation menu's from the Dashboard >> Appearance >> Menu's screen.
Choose the applicable menu from the dropdown select in the "Edit Menus" tab, then you can easily edit existing links, or add more links to your menu. Once saved the changes to your menu will be reflected on your website.

A: If you mean menu links then just do it via Wordpress admin by going to Appearance > Menus. Depending how your theme is setup, the menu options available to you and those that you can create will be different.


text:
Q: Why do we use forms of "have" with past participles to form the present perfect, as in "I have taken"? We use has, had, or have with a past participle to form the present perfect. This contrasts with our use of a single verb for the present simple. We do not say "I taken the test," but instead use the simple past tense took and say "I took the test." For what grammatical reason do we use have, had, or has with a past participle?

A: How the have-perfect came to be
The OED has this to say about the verb to have with regard to its use as an auxiliary for creating perfect tenses when combined with some inflection of the verb have the way that you've asked about:

IV. As an auxiliary verb, used with the past participle of another verb to form the perfect.
The have-perfect in English apparently arose as a reanalysis
  of uses such as I have my work done 'I have my work in a done or finished
  condition' (see sense 7b); the complement done was reinterpreted as part of
  the verb phrase, a process which was reinforced by a lack of fixed word
  order and the possible transposition of object and participle, i.e. I have
  done my work. This development appears to have largely taken place before
  the written record. Even in early Old English, in the majority of examples
  with transitive verbs the past participle is not inflected to agree with
  the object. Despite occasional ambiguity, there are few Old English
  examples in which the past participle must be regarded as a complement
  rather than as part of a perfect construction.
In Old English, the have-perfect is not only established with transitive
  verbs, but also with intransitive verbs expressing action or occurrence,
  while the perfect of intransitive verbs expressing change of state or
  position is usually formed with be (be v.
  16b). From Middle English
  onwards the perfect with have gradually becomes more common in these verbs,
  and is the predominant form by the early 19th cent., except in contexts
  where the focus is on resultant state (for example, she is gone is still
  typically used to express state, while she has gone expresses action; such
  usage is now, however, quite limited). In early Middle English the
  have-perfect also extends to verbs denoting ongoing states or conditions,
  and to the verb to be. Compare discussion in etymology section.

Sense 16b of be covers how be was also historically used as an auxiliary with a past participle to form perfect tenses of intransitive verbs:

*b. In intransitive verbs, forming perfect tenses; in later use chiefly with verbs of motion such as come, go, rise, set, fall, arrive, depart, grow, etc., expressing a condition or state attained at the time of speaking, rather than the action of reaching it, e.g. 'the sun is set', 'our guests are gone', 'Babylon is fallen', 'the children are all grown up'.
Now largely replaced by have following the pattern of transitive verbs: see have v. VI.

An example in (Early) Modern English of using be for a perfect which they provide is from Shakespeare's Comedy of Errors:

These are the parents to these children,
  Which accidentally are met together.

Today we would say have met to form the perfect there.
A smidgen of the discussion alluded to in the etymology section for have is:

Etymology
...
Use as auxiliary.
The development of the periphrastic constructions with past participle
  (the antecedents of the modern present and past perfect) to some extent
  parallels developments in other Germanic and Romance languages, but appears
  at least partly to reflect development within English (compare note at
  branch VI.). Although frequently attested in similar contexts to the later
  present and past perfect, in early use the periphrastic constructions are
  variants of the simple past tense and their use is not fully
  grammaticalized. With transitive verbs in Old English, they are sometimes
  not easy to distinguish from originally related uses in other senses where
  the participial adjective functions as complement (compare not only sense
  7b, but also sense 28a).

The OED has more than 50 dense pages of notes on this verb's historical forms and etymological information before it even
starts talking about its myriad senses and subsenses. Remember too that the past participle was used with be not just with have historically, and that be is a far longer entry than have!
Given all that, I really don't think that we're going to
be able to provide much more than a palimpsest of a full answer here in our format, which does not lend itself to such things.


text:
Q: How to best manage JavaScript dependencies on a project with least hassle I manage few JavaScript ReactJs projects. Two of these projects are rarely updated.
Last week, I updated and deployed these two rarely updated projects (after 14 months) with only two minor changes but the new build had several issues and caused a pain in testing and support.
I fear that yarn install resulted in updating several dependencies (although we have a yarn.lock file) and caused change in behaviour and added issues with it.
Now with this background, I wanted to ask experts here how do they manage their projects that are kept for a long time with no regular updates.
My package.json file looks like:-
    "@babel/cli": "^7.1.2",
    "@babel/core": "^7.1.2",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-google-maps": "^9.4.5",
    "react-google-recaptcha": "^1.0.5",
    "react-helmet": "^5.2.0",
    "react-moment": "^0.7.0",
    "react-router-dom": "^4.2.2",

Some example issues I faced: -
1) React Link router was not building correct link for URLs starting with https://. Found out it was a bug in the React dom version and used link starting with :// to fix.
BUT point is, this feature worked fine for years and broke in a recent build.
Do you use ~ or ^ or just bind to a specific version?
Thanks


text:
Q: Click button after it is visible in Selenium using python I'm trying to emulate a search using Python and Selenium, but recently I faced a problem, when a button is generated but a JS. Here, in the picture below, the button Im t rying to click is "Save..." and it is visible (and clickable) after search is finished. Using code analyzer in Firefox, I found that this button's code is:

   <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button">

     Save...

   </button>

But in this code there are two more buttons with the same text label:

   <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-disabled ui-state-disabled ui-button-text-only" disabled="" role="button">

     Minimize

   </button>
   <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-disabled ui-state-disabled ui-button-text-only" disabled="" role="button">

     Save...

   </button>

I tried to click it using two different pieces of code:
time.sleep(30) #wait for the search to finish
driver.find_element_by_class_name('ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-text-only').click()

And another one:
wait = WebDriverWait(driver, 30)
wait = wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'ui-button.ui-widget.ui-state-default.ui-corner-all.ui-button-text-only')))
wait.click()

But neither of them seems to work. how can I overcome this situation and finally click this button?

A: try the following code:
Using WebDriverWait: (helps to avoid sleep in case of slow loading)
wait = WebDriverWait(driver, 30)
saveButton = wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='pharmit_bottomloaders pharmit_nowrap']/button[2]/span")))
saveButton.click()

Without WebDriverWait:
driver.find_element_by_xpath("//div[@class='pharmit_bottomloaders pharmit_nowrap']/button[2]/span").click()


text:
Q: Two formulations of Lagrangian for Maxwell's equations in the vacuum (revised question) I've started working my way through David Tong's excellent lecture notes in an effort to teach myself QFT and in his first lecture on classical fields he observes that the Lagrangian density for Maxwell's equations in a vacuum:
$$\mathcal{L}=-\frac{1}{2}({\partial_\mu}{A_\nu})({\partial^\nu}{A^\mu})+\frac{1}{2}({\partial_\mu}{A^\mu})^2$$
can also "up to an integration by parts" be written as:
$$\mathcal{L}=-\frac{1}{4}({\partial_\mu}{A_\nu}-{\partial_\nu}{A_\mu})({\partial^\mu}{A^\nu}-{\partial^\nu}{A^\mu})$$
I'm failing to manage to show this. Working in reverse, it's clear that:
$$-\frac{1}{4}({\partial_\mu}{A_\nu}-{\partial_\nu}{A_\mu})({\partial^\mu}{A^\nu}-{\partial^\nu}{A^\mu})\\
=-\frac{1}{2}({\partial_\mu}{A_\nu})({\partial^\nu}{A^\mu})+\frac{1}{2}({\partial_\mu}{A_\nu})({\partial^\nu}{A^\mu})$$
but I can't resolve the second term. I clearly need to brush up my tensor calculus skills - can someone show how to derive this?


text:
Q: Удаление узла в дереве Дана программа, позволяющая: 1)создать N-узловое дерево, вводимое пользователем, 2) вывести это дерево. Как 3) удалить заданный узел дерева?
#include <iostream>

using namespace std;

struct Tree
{
    int id; //индекс
    int level; //уровень в иерархии
    int count_son; //количество сыновей
    struct Tree** son; //массив указателей на сыновей
    struct Tree* parent; //указатель на родителя
    int key; //ключ
};

struct Tree* createTree(struct Tree* node, int id, int level)
{
    node->id = id;
    node->level = level;
    cout << "\nВведите степень узла + его ключ. Текущая позиция: " << node->level << "-" << node->id << "\n";
    cin >> node->count_son >> node->key;
    node->son = new struct Tree* [node->count_son]; //здесь нужно обозначить родительский узел?
    level++;

    for (int i = 0; i < node->count_son; i++)
    {
        node->son[i] = new Tree;
        node->son[i]->id = id + i;
        node->son[i]->level = level;
    }

    for (int i = 0; i < node->count_son; i++)
        createTree(node->son[i], id + i, level);

    return node;
}

void printTree(struct Tree* node)
{
    if (node)
    {
        for (int i = 0; i < node->level; i++) cout << "| ";
        if (node->son != NULL) cout << "[+]";
        cout << "(" << node->level << "-" << node->id << ") = "<< node->key << endl;
        if (node->count_son != 0)
            for (int i = 0; i < node->count_son; i++)
                printTree(node->son[i]);
    }
}
void nodeKill(struct Tree* node, int key)
{
    for (int i = 0; i < node->count_son; i++)
    {
        if (node->key == key)
        {
            node->parent->son[i] = node->son[0]; //Здесь мы "удаляем" наш узел
        }
    }
}

int main()
{
    size_t number; int key; Tree* root;
    setlocale(LC_ALL, "RUS");

    root = new Tree;
    root = createTree(root, 0, 0);
    cout << "\n-----Получившееся дерево-----\n";
    printTree(root);
    cout << "Введите ключ узла, который хотите удалить: ";
    cin >> key;
    nodeKill(root, key);
    cout << "\n-----Дерево с удалённым узлом-----\n";
    printTree(root);
    system("pause");
    return 0;
}


text:
Q: Load multiple files using HTML5 and PHP I am trying to load multiple files using HTML5.
This is my code I found on some site.
In the PHP code it doesn't recognize it as an array.
Am I doing something wrong? Can someone show me a working solution?
Thanks.
index.html
<form action='save.php' method='post' enctype='multipart/form-data'>
<input name="uploads" type="file" multiple="multiple" />
<input type='submit' value="Upload File">
</form>

save.php
function GetFiles() {
        $files = array();
        $fdata = $_FILES["uploads"];
        if (is_array($fdata["name"])) {//This is the problem
                for ($i = 0; $i < count($fdata['name']); ++$i) {
                        $files[] = array(
                            'name' => $fdata['name'][$i],
                            'tmp_name' => $fdata['tmp_name'][$i],
                        );
                }
        } else {
                $files[] = $fdata;
        }

        foreach ($files as $file) {
                // uploaded location of file is $file['tmp_name']
                // original filename of file is $file['file']
        }
}

A: You need to make some sort of array of the name:
<input name="uploads[]" type="file" multiple="multiple" />

Just like you used to do when using checkboxes.

A: form variables that are arrays must be named with a [], otherwise PHP doesn't see it as an array.  So:
<form action='save.php' method='post' enctype='multipart/form-data'>
<input name="uploads[]" type="file" multiple="multiple" />
<input type='submit' value="Upload File">
</form>

should do it.

A: I know this is kind of a old thread but I use this little script to convert the (to me) confusing layout of the $_FILES array to a more readable form. Name_input is whatever name you gave to the Input object in HTML.
for($i=0; $i<count($_FILES['name_input']['name']); $i++) {
    $betterfiles[] = array(
        "name" => $_FILES['name_input']['name'][$i],
        "type" => $_FILES['name_input']['type'][$i],
        "tmp_name" => $_FILES['name_input']['tmp_name'][$i],
        "error" => $_FILES['name_input']['error'][$i],
        "size" => $_FILES['name_input']['size'][$i]
    );
}


text:
Q: Couchbase Lite (Mobile) local database API for Cordova/Ionic app I was wondering if there is any Couchbase Lite Cordova plugin or API to just access and use the database locally on any android/ios mobile device?
I was trying to search in the official documentation. It didn't help!

A: Yes, couchbase-lite-phonegap-plugin is an official ionic plugin for iOS and Android. You can install it in ionic v2+ with:
$ ionic cordova plugin add couchbase-lite-phonegap-plugin
$ npm install --save @ionic-native/couchbase-lite
You won't be able to access Couchbase Lite Native API, which includes N1QL for example, but you can operate local databases with Couchbase Lite REST API.
This plugin basically just gives you an URL to make requests to your local CBLite, allowing you to manage local databases, their documents and views (design docs with JavaScript functions), etc. And you can also start and cancel  push and pull replications with Sync Gateway, each one a continuous or a one-time operation. The replications run in background unassisted, but you can monitor them with the _active_tasks method and get notified of local database changes with the _changes method.
However, for ease of usage, when developing a full featured mobile app, you'll need a wrapper to encapsulate those HTTP REST requests. You'll find some examples in CouchbaseLabs repo.


text:
Q: SizetoFit versus UIViewAutoresizingFlexibleHeight. What is the difference? I had always been told that if I have a UILabel with dynamic text content in it that I should use SizeToFit as that would adjust the UILabel properly. I used sizeToFit but it was messing up my text labels that were on a UITableViewCell after I did a scroll. However on initial screen load, they would appear fine.
After messing with it for a couple of hours I read somewhere that someone else had the same issue and that instead of SizeToFit they used the following two lines:
 cell.message.lineBreakMode = UILineBreakModeWordWrap;
    cell.message.autoresizingMask = UIViewAutoresizingFlexibleHeight;

and it would work. Well I did and my UILabels are perfect. However I am still curious in understanding why so?
so now my code looks like:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MessagesCustomViewCell";
    MessagesCustomViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MessagesCustomViewCell_iPhone" owner:self options:nil];
        cell = [nib objectAtIndex:0];  //you can also loop thru or manually remember positions
    }

    NSArray * discussion = [self.messages objectAtIndex:indexPath.row];

      cell.author.text = [discussion valueForKeyPath:@"author.name"];
      cell.message.text = [discussion valueForKey:@"text"]; //DYNAMIC VARIABLE SIZED TEXT

    cell.message.lineBreakMode = UILineBreakModeWordWrap;
    cell.message.autoresizingMask = UIViewAutoresizingFlexibleHeight;

    return cell;
}

A: sizeToFit
behavior:care about its content over superview's size
send sizeToFit to a UILabel without [yourLabel setNumberOfLines:0] will make the Label as wide as possible to fit it's text. While with [yourLabel setNumberOfLines:0] your label will break it's text to mutiple lines according it's width, but this will make it's height as large as possible to fit in it's text, it does not care about it's superview's bounds.
autoResizingMask
behavior:care about superview's size over its content
If a UIlabel's autoResizingMask is set, once it's superview's bounds is change, it will change it's frame first, then it checks "Can i put more text in my rect?" base on it's relative properties(numberOfLines, font,...).


text:
Q: Apache+mod_ftp - how to set up FTP without altering "/" directory? I have a WAMP on Apache 2.2 configured, up and running, now I have to add FTP functionality to it. Apparently the only solution that's available without compiling is mod_ftp, and good thing the server isn't 2.4, as I've read that precompiled mod_ftp is not compatible with it. So, I've ran into a need of modifying <Directory /> section in httpd.conf file to allow at least a subnet for FTP connection like this:
<Directory />
    Options FollowSymLinks
    AllowOverride AuthConfig
    Order deny,allow
    Allow from <classified>
    Deny from all
</Directory>

The default config is "Deny from all" and no AllowOverride. My question is - is it necessary to fix <Directory /> section for FTP to actually work, and what else can I do in order to leave the default configuration intact?

A: Had to wrap FTP settings in a separate VirtualHost section, and I could place desired settings in <Directory /> section within it to make my FTP server work as intended without loosening security on HTTP part.
<VirtualHost _default_:21>
    <Directory />
        Options FollowSymLinks
        AllowOverride AuthConfig
        Order deny,allow
        Allow from <classified>
        Deny from all
    </Directory>
    ...
</VirtualHost>

Even if I made mistakes in Order, this allowed users to connect and do their work.


text:
Q: Extract ancillary parameters from maximum likelihood model in Stata In Stata while using maximum likelihood (ml) estimation, I can use diparm (in ado file) to display the ancillary (auxillary) parameters. But, when I used ereturn list I didnot see the way to extract these coefficients. Is there something like mat list e(b) for ancillary parameters?
ereturn list

scalars:
               e(rank) =  13
                  e(N) =  6378
                 e(ic) =  17
                  e(k) =  13
               e(k_eq) =  5
               e(k_dv) =  2
          e(converged) =  1
                 e(rc) =  0
          e(k_autoCns) =  0
                 e(ll) =  -7465.044032705097
         e(k_eq_model) =  1
               e(df_m) =  4
               e(chi2) =  65.60818581991281
                  e(p) =  1.91572317062e-13
              e(k_aux) =  2

macros:
                e(cmd) : "mypro"
           e(chi2type) : "Wald"
                e(opt) : "moptimize"
            e(predict) : "ml_p"
                e(vce) : "oim"
               e(user) : "mypro_ll"
           e(crittype) : "log likelihood"
          e(ml_method) : "lf"
    e(singularHmethod) : "hybrid"
          e(technique) : "nr"
              e(which) : "max"
             e(depvar) : "y1 y2"
         e(properties) : "b V"

matrices:
                  e(b) :  1 x 13
                  e(V) :  13 x 13
               e(ilog) :  1 x 20
           e(gradient) :  1 x 13
               e(ml_h) :  1 x 13
           e(ml_scale) :  1 x 13

functions:
             e(sample)

A: The ancillary parameters are typically stored in their own "equation" in the e(b) matrix. See:
M.L. Buis (2011) "Stata tip 97: Getting at $\rho$s and $\sigma$s", The Stata Journal, 11(2), pp. 315-317. http://www.maartenbuis.nl/publications/sigma_rho.html
And: http://www.maartenbuis.nl/wp/p_value_3.html


text:
Q: What does one persist and return the RawValue from the tracker? I am evaluating the Multi-Tracker sample and I want to get hold of the RawValue of the barcode detector once one is available.
I would like to dismiss the Tracker once a valid RawValue has been obtained and use the value elsewhere.
Any suggestions on the items below will be helpful.

*

*How to dismiss the tracker once a detection has been made

*How to hold and pass the RawValue up the the activity. For example, echo it in a Toast
Thanks

A: See the discussion in this thread about passing the RawValue to the activity:
How to capture barcode values using the new Barcode API in Google Play Services?
The tracker is active as long as the associated CameraSource/Detector is active (i.e., the release() method has not been called).  But if you want to avoid receiving updates beyond the initial detection, you could have the tracker suppress sending updates beyond the first one.  For example:
@Override
public void onUpdate(Detector.Detections<Barcode> detectionResults, Barcode item) {
    if (!mFoundCalled) {
        mCallback.onFound(item.rawValue);
        mFoundCalled = true;
    }
    ...
}

A: And you also can use the callback in: onNewItem
@Override
public void onNewItem(int id, Barcode item) {
    mGraphic.setId(id);
    callback.onBarcodeFound(item.rawValue);
}


text:
Q: Fab isnt aligning properly I'm using a view pager. I'm having an issue with aligning the fab to the bottom|endof the screen.
My code for the view is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="40sp"
        android:textStyle="bold"
        tools:text="Words" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="@dimen/activity_horizontal_margin"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:backgroundTint="@color/colorPrimary" />

</RelativeLayout>

and it produces the following output
enter image description here
It gets cropped down.
I think that it might be rendering the screen size for the fragment and ignoring the actual view of the activity that i called it from.
Any one have any thoughts on how to resolve this issue?


text:
Q: Ordenar un QuerySet alguien me puede ayudar a ordenar un queryset  tengo esto:
resultados = transaccional.objects.filter(ordenpaciente_id=pac.id).order_by('examen_id').distinct('examen_id')

Quiero reordenarlo por otro campo de otro modelo, he intentado esto pero no me funciona:
resultados_final = resultados.objects.order_by('examen.grupoExamenes_id')

Esto también he intentado:
resultados = transaccional.objects.filter(ordenpaciente_id=pac.id).order_by('examen.grupoExamenes_id','examen_id',).distinct('examen_id')

Alguien puede ayudarme?

A: Para acceder de un modelo a otros debe utilizar dos guiones bajos (__). A continuación un ejemplo:
Modelos
from django.db import models

class Resultado(models.Model):
    examen = models.ForeignKey(
        Examen,
        related_name='resultados',
        on_delete=models.CASCADE,
    )

class GrupoExamen(models.Model):
    pass

class Examen(models.Model):
    grupo_examen = models.ForeignKey(
        GrupoExamen,
        related_name='examenes',
        on_delete=models.CASCADE,
    )

Consulta
Resultado.objects.order_by('examen__grupo_examen_id', 'examen_id')

Documentación

*

*order_by


text:
Q: mysql database structure (unique id) I think most people had serious problems with inserting a value/data into a database (mysql). When I'm inserting a value into a database, I assign an unique id (INT) for that line. When I query the database, easily I can read/modify/delete that line.
With function for() (in php) I easily can read values/data from the database. The problem occurs when I delete a line (in the middle for example).
E.g:
DB:
ID | column1 | column2 | ... | columnN
--------------------------------------
1 | abcdefgh | asdasda | ... | asdasdN
2 | asdasddd | asdasda | ... | asdasdN
...
N | asdewfew | asddsad | ... | asddsaN

php:
for($i = 0; $i <= $n; $i++){
   $sql = mysql_query("SELECT * FROM db WHERE ID = '$i' ");
   //Code;
}

*$n = last column value from ID

Am I need to reorganize the entire database to have a correct "flow" (1, 2, 3, .. n)? Or am I need to UPDATE the each cell?

A: What you're doing here is unnecessary thanks to AUTO_INCREMENT in mysql. Run this command from PhpMyAdmin (or another DB management system):
ALTER TABLE db MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT;

Now when insert a row into db mysql will assign the ID for you:
INSERT INTO db (id, column1, column2) VALUES(NULL, 'abc', 'def');

SELECT * FROM db;:
+--+-------+-------+
|id|column1|column2|
+--+-------+-------+
|1 |old    |oldrow |
+--+-------+-------+
|2 |abc    |def    | <--- Your newly inserted row, with unique ID
+--+-------+-------+

If you delete a row, it is true that there will be an inconsistency in the order of the ID's, but this is ok. IDs are not intended to denote the numeric position of a row in a table. They are intended to uniquely identify each row so that you can perform actions on it and reference it from other tables with foreign keys.

Also if you need to grab a group of ID's (stored in an array, for example), it is much more efficient to perform one query with an IN statement.
$ids = array(1,2,3,4,5,6);
$in = implode(',', $ids);
mysql_query('SELECT * FROM db WHERE id IN ('.$in.')');

However, if you want all rows just use:
SELECT * FROM dbs;

But be weary of bobby tables.

A: You can select all the rows with query
SELECT * FROM db

and do whatever you want after

A: You can never ensure, that the ids are continous. As you noticed yourself there are gaps after you delete a row, but even for example when you insert rows within a transaction and don't commit it, because something failed and you need to revert the transaction. An ID is an identifier and not row number.
For example if you want to select X items from somewhere (or such) have a look at LIMIT and OFFSET
SELECT * FROM mytable ORDER BY created DESC LIMIT 10 OFFSET 20;

This selects the rows 21 to 30 ordered by their creation time. Note, that I don't use id for ordering, but you cannot rely on it (as mentioned).
If you really want to fetch rows by their ID you definitely need to fetch the IDs first. You may also fetch a range of IDs like
SELECT * FROM mytable WHERE id IN (1,2,3,4);

But don't assume, that you will ever receive 4 rows.

A: Ids are surrogate keys–they are in no way derived from the data in the rest of the columns and their only significance is each row has a unique one. There's no need to change them.
If you need a specific range of rows from the table, use BETWEEN to specify them in the query:
SELECT id, col1, col2, ..., coln
  FROM `table`
  WHERE id BETWEEN ? AND ?
  ORDER BY id

A: You do not have to reorganize the entire database in order to keep the index. But if you feel like it, you'd have to update each cell.
BTW, look at mysql_fetch_array(), it will ease the load on the SQL server.

A: If you need all the rows and all columns for that table use:
$query = mysql_query("SELECT * FROM table_name");

and then loop through each row with a while statement:
while ($row = mysql_fetch_array($query ))
{
       echo $row['column_name'];
}


text:
Q: What's a fast way to check if an item is the most recent version in mongodb? I have a collection of items in mongodb that look like this (I'm using pymongo):
{'type':'_sometype', 'name':'_somename', 'date':datetime, 'incoming':bool}

type and name are not unique across items, so it is possible to have items with the same type and name but differing dates.

The issue:  sometimes I'll need to determine if an item retrieved in some query is the latest version of that item.  What I've been doing is this:
def isLatest(item):
        return not collection.find_one({'date':{'$gt':item['date']},
                                        'type':item['type'],
                                        'name':item['name'],
                                        'incoming':item['incoming']})

Which simply queries mongodb for a matching item that has a more recent value for date.  If such an item is found, this function returns False (because the item passed in is not the latest version).
I call this function many times, once for each item in a given query, and it seems to me like there'd be a much better way of going about this than repeatedly querying for some data.  Unless this looks OK to everybody, in which case I thank you for your evaluation :D
Any thoughts appreciated, thanks in advance,
-S

A: Without knowing any more details about your application than what you've provided, it seems to me it might be better to have a separate collection that only stores the latest version and is indexed by type-name; and a separate collection for historical versions.

A:
I call this function many times, once for each item in a given query, and it seems to me like there'd be a much better way of going about this than repeatedly querying for some data. Unless this looks OK to everybody, in which case I thank you for your evaluation :D

To be honest if you need to keep checking to see if it is the latest, you are going to need to issue queries. That's unavoidable - the act of needing to know necessitates a query.
If querying the database frequently is not bothering you (i.e. causing some other difficulties or complications), then I see nothing wrong. If it is causing problems, it might be the design of the application itself which needs re-examining. Without knowing more about what it is you're trying to achieve, its pretty difficult to say. Personally though, I'd say if everything is looking good, you've probably got nothing to worry about. As always, just make sure your query isn't any less efficient than it needs to be.

A: My advice would be to store an additional field on your items, determining if its the latest or not. Your application would need to update this field everytime it inserts a new item. Depending on how often items are inserted that would be more efficient.


text:
Q: Como seria este codigo de vb en c# Necesito mostrar datos que están en una base de datos. Tengo algo similar hecho en vb.net pero ahora me toca hacerlo en c#
 For i = 0 To dt.Rows.Count - 1
            Dim codigo As Integer = dt.Rows(i).Item("CodDepartamento")

            html.Append("
")
            html.Append("")
            html.Append(dt.Rows(i).Item("CodDepartamento"))
            html.Append("	")

A: Entiendo que la variable dt es un DataTable y html un StringBuilder.
Sería algo así:
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        var codigo = (int) dt.Rows[i]["CodDepartamento"];

        html.Append("
");
        html.Append("");
        html.Append(dt.Rows[i]["CodDepartamento"]);
        html.Append("	");

A: Puedes hacerlo de una manera bastante sencilla:
foreach(DataRow dr in dt.Rows){
    int codigo = Convert.ToInt32(dr["CodDepartamento"]);

    html.Append("
").Append(codigo).Append("	");
}

Esto asumiendo que dt es un DataTable y que html es un StringBuilder.

A: Más que una solucion a tu pregunta es un consejo, existen varias herramientas que tienen la finalidad de hacer la conversión de codigo de VB a C# y viceversa.
Personalmente utilizo esta: http://converter.telerik.com/ pero hay varias..
Es posible que necesites convetir código nuevamente entonces ahí vas a tener una herramienta que lo haga por ti teniendo en cuenta que entiendes la lógica para programar.
Volviendo a tu pregunta el código quedaría de la siguiente manera:
for (int i = 0; i <= dt.Rows.Count - 1; i++) {
    int codigo = dt.Rows(i).Item("CodDepartamento");

    html.Append("
");
    html.Append("");
    html.Append(dt.Rows(i).Item("CodDepartamento"));
    html.Append("	");
}


text:
Q: Getting First argument in form cannot contain nil or be empty while trying to allow users to edit their password I am trying to add a solution to allow users to change their password. I am using devise. And I followed up the third solution from this tutorial.
However after I do everything:
class UsersController < ApplicationController

  before_action :authenticate_user!

  def edit
    @user = current_user
  end

  def update_password
    @user = current_user
    if @user.update_with_password(user_params)
      # Sign in the user by passing validation in case their password changed
      bypass_sign_in(@user)
      redirect_to root_path
    else
      render "edit"
    end
  end

  private

  def user_params
    # NOTE: Using `strong_parameters` gem
    params.require(:user).permit(:password, :password_confirmation, :current_password)
  end
end

in routes.rb
resource :user, only: [:edit] do
  collection do
    patch 'update_password'
  end
end

and in the view:
 <%= form_for(@user, :url => { :action => "update_password" } ) do |f| %>

    <%= f.label :current_password %> (we need your current password to confirm your changes)

    <%= f.password_field :current_password %>

    <%= f.label :password, "Password" %>

    <%= f.password_field :password, :autocomplete => "off"  %>

    <%= f.label :password_confirmation %>

    <%= f.password_field :password_confirmation %>

    <%= f.submit %>

<% end %>

but I get this error First argument in form cannot contain nil or be empty in
= form_for(@user, :url => { :action => 'update_password' } ) do |f|
is there something I have missed? Thanks!


text:
Q: Android sms bot I am trying to make a simple android app. When I send sms hi to my mobile from some number, it should reply hi automatically to me in response. And when I send "How are you", it should reply me How are you.

A: Just a quick Google search on "How to read and send text messages Android" would really help in this situation as there are plenty of resources available.
Assuming you have the basics of the app already built, look at http://codetheory.in/android-sms/ for more information on how to register to deal with messages as well as receive and send them. There are some direct code examples that you could copy&paste into your code and extend. For instance instead of logging the message, you could simply call a function that you create, to send a message back to that number. Hope this helps!


text:
Q: AppEngine "appengine" package always fails with "syscall" or "unsafe" import failure Using the AppEngine 1.9.40 SDK, I can't even import the "appengine" package.
app.yaml:
application: testapp
version: 1
runtime: go
api_version: go1

handlers:
- url: /.*
  script: _go_app

Go code:
package main

import (
    "google.golang.org/appengine"
)

func init() {
    appengine.IsDevAppServer()
}

func main() {
    // This is only here because go-get needs on it.
}

Command-line:
$ GOPATH=$(pwd) goapp serve

Error:
2016/08/01 23:58:02 go-app-builder: Failed parsing input: parser: bad import "unsafe" in src/golang.org/x/net/icmp/helper.go

What can be done to get past this?

A: All code in the application directory tree (the root is the directory containing app.yaml) is compiled in to the app. Appengine rejects code that uses "unsafe".
The fix is to move the offending code out of the application directory tree. Here's one possible way to arrange the code:
$GOPATH
    src
        testapp
            app.yaml
            app.go
        golang.org
            x
                net
                    icmp
                    ... and so on

It's also possible that using package main will cause some trouble. If the above does not work, change the package name.
Appengine apps are not go-gettable. Don't struggle to make them so.
There's more discussion on this topic at https://github.com/golang/gddo/issues/428.


text:
Q: Как запретить Firebase кэшировать фотографии на телефон В приложение есть возможность добавлять фотографии, они отображаются в recyclerview  и по не понятной причине Firebase их сохраняет на устройство. Для чего он это делает, как отключить это? Вес приложения после загрузки 10 фото доходит до 100 мегабайт.
Класс для загрузки записей в базу данных
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_post);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    ButterKnife.bind(this);
    UnderlineSettings();

    storage = FirebaseStorage.getInstance().getReference("uploads");
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == 1 && resultCode == RESULT_OK && data.getData() != null && data != null){

        mImageUri = data.getData();

        Glide.with(getApplicationContext()).load(mImageUri).into(mini);
        mini.setImageURI(mImageUri);
    }
}

@OnClick(R.id.image_select)
public void OpenGallery(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 1);
}
@OnClick(R.id.info_help)
public void Help(){
    new CustomBottomHelperGroup().show(getSupportFragmentManager(),"Dialog");
}
@OnClick(R.id.close_post)
public void ClosePostCreater(){
    finish();
}
@OnClick(R.id.add_post)
public void AddPost(){
    Upload();
    finish();
}

private String getFileExtension(Uri uri) {
    ContentResolver cR = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));
}

private void Upload(){
    if (mImageUri != null) {

        fileReference = storage.child(getFileExtension(mImageUri) + "/" + System.currentTimeMillis());

        mUploadTask = fileReference.putFile(mImageUri).addOnSuccessListener(taskSnapshot ->

                fileReference.getDownloadUrl().addOnCompleteListener(task -> {
                    upload = new Upload(text.getText().toString(), task.getResult().toString(), choose, "0");

                    uploadId = data.push().getKey();
                    data.child(uploadId).setValue(upload);
                })).addOnFailureListener(e -> Toast.makeText(this, "error", Toast.LENGTH_SHORT).show());
    } else {
        Toast.makeText(this, "Не выбрано фото!", Toast.LENGTH_SHORT).show();
    }
}

Адаптер recyclerview

class RecyclerAdapter(val context: Context, private val data: List<Upload>): RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    val uploadCurrent = data[position]
    holder.mainText.text = uploadCurrent.name
    holder.like.text = uploadCurrent.getmLike()
    Glide.with(context).load(uploadCurrent.imageUrl).placeholder(R.drawable.place).centerCrop().into(holder.imageFeed)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view = LayoutInflater.from(context).inflate(R.layout.recycler_content, parent, false)
    return ViewHolder(view, context, data)
}

override fun getItemCount() = data.size

class ViewHolder(view: View, context: Context, data: List<Upload>) : RecyclerView.ViewHolder(view) {

    init {
        view.setOnClickListener{}

        view.delete.setOnClickListener{
            val mDataBaseReg: DatabaseReference = FirebaseDatabase.getInstance().getReference("uploads")
            val mStorage = FirebaseStorage.getInstance()
            val upload: Upload = data[position]
            val selectedKey = upload.code
            val imageRef: StorageReference = mStorage.getReferenceFromUrl(upload.imageUrl)
            imageRef.delete().addOnSuccessListener {
                mDataBaseReg.child(selectedKey).removeValue()
                Toast.makeText(context, "Запись удалена", Toast.LENGTH_SHORT).show()
            }
        }
        view.like.setOnClickListener {

            Toast.makeText(context, "like", Toast.LENGTH_SHORT).show()
        }

        view.ImageFeed.setOnClickListener{

            val intent = Intent(context, ImageViewer::class.java)
            intent.putExtra("image", data[position].imageUrl)
            context.startActivity(intent)
        }
    }

        val mainText: AppCompatTextView = view.findViewById(R.id.MainText)
        val imageFeed: ImageView = view.findViewById(R.id.ImageFeed)
        val like: TextView = view.findViewById(R.id.like_count)
    }
}

Класс для показа записей

@Override
protected void onDestroy() {
    super.onDestroy();
    mDatabaseRef.removeEventListener(mDBListener);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_administrator_feed);
    ButterKnife.bind(this);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    toolbar.setTitle(" ");
    setSupportActionBar(toolbar);
    showDialog();
    UnderlineSettings();
    FirebaseDatabase.getInstance().setPersistenceEnabled(false);

    list = new ArrayList<>();

    RecyclerView recyclerView = findViewById(R.id.recycler);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    SharedPreferences sharedPreferences = getSharedPreferences(MODE, MODE_PRIVATE);
    mode1 = sharedPreferences.getBoolean(MODE, mode1);

    adapter = new RecyclerAdapter(AdministratorFeed.this, list);
    recyclerView.setAdapter(adapter);

    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
    mDatabaseRef.keepSynced(false);

    if(mode1){
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    }else{
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    }
    mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            list.clear();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Upload upload = snapshot.getValue(Upload.class);
                upload.setCode(snapshot.getKey());
                list.add(upload);
            }
            adapter.notifyDataSetChanged();
            all.setTypeface(null, Typeface.BOLD);
            first.setTypeface(null, Typeface.NORMAL);
            second.setTypeface(null, Typeface.NORMAL);
            third.setTypeface(null, Typeface.NORMAL);
            fourth.setTypeface(null, Typeface.NORMAL);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

public void UnderlineSettings(){

    all.setOnClickListener(v -> {
        mDatabaseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Upload upload = snapshot.getValue(Upload.class);
                    upload.setCode(snapshot.getKey());
                    list.add(upload);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        all.setTypeface(null, Typeface.BOLD);
        first.setTypeface(null, Typeface.NORMAL);
        second.setTypeface(null, Typeface.NORMAL);
        third.setTypeface(null, Typeface.NORMAL);
        fourth.setTypeface(null, Typeface.NORMAL);
    });

    first.setOnClickListener(v -> {
        Query query_first = mDatabaseRef.orderByChild("mChoise").equalTo("1");
        query_first.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Upload upload = snapshot.getValue(Upload.class);
                    upload.setCode(snapshot.getKey());
                    list.add(upload);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        all.setTypeface(null, Typeface.NORMAL);
        first.setTypeface(null, Typeface.BOLD);
        second.setTypeface(null, Typeface.NORMAL);
        third.setTypeface(null, Typeface.NORMAL);
        fourth.setTypeface(null, Typeface.NORMAL);
    });

    second.setOnClickListener(v -> {
        Query query_second = mDatabaseRef.orderByChild("mChoise").equalTo("2");
        query_second.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Upload upload = snapshot.getValue(Upload.class);
                    upload.setCode(snapshot.getKey());
                    list.add(upload);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        all.setTypeface(null, Typeface.NORMAL);
        first.setTypeface(null, Typeface.NORMAL);
        second.setTypeface(null, Typeface.BOLD);
        third.setTypeface(null, Typeface.NORMAL);
        fourth.setTypeface(null, Typeface.NORMAL);
    });

    third.setOnClickListener(v -> {
        Query query_third = mDatabaseRef.orderByChild("mChoise").equalTo("3");
        query_third.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Upload upload = snapshot.getValue(Upload.class);
                    upload.setCode(snapshot.getKey());
                    list.add(upload);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        all.setTypeface(null, Typeface.NORMAL);
        first.setTypeface(null, Typeface.NORMAL);
        second.setTypeface(null, Typeface.NORMAL);
        third.setTypeface(null, Typeface.BOLD);
        fourth.setTypeface(null, Typeface.NORMAL);
    });

    fourth.setOnClickListener(v -> {
        Query query_fourth = mDatabaseRef.orderByChild("mChoise").equalTo("4");
        query_fourth.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Upload upload = snapshot.getValue(Upload.class);
                    upload.setCode(snapshot.getKey());
                    list.add(upload);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        all.setTypeface(null, Typeface.NORMAL);
        first.setTypeface(null, Typeface.NORMAL);
        second.setTypeface(null, Typeface.NORMAL);
        third.setTypeface(null, Typeface.NORMAL);
        fourth.setTypeface(null, Typeface.BOLD);
    });
}

A: Нужно сделать
FirebaseDatabase.getInstance().setPersistenceEnabled(false);

потому что firebase по дефолту кэширует данные, чтобы их можно было юзать оффлайн.

A: Мне помог этот метод в glide чтобы не кэшировать данные -
Glide.with(context)
  .load(url)
  .diskCacheStrategy(DiskCacheStrategy.NONE)
  .into(imageView);


text:
Q: Android Market - the only crash reports I get are on Platforms "OTHER" I've an app in the market with a few crash reports of "java.lang.RuntimeException: native typeface cannot be made". This is covered elsewhere on SO and I know where in my code it is. That's not my problem - the problem is finding out which Android version and handset type is causing it. I've never seen this on any handsets the app is tested on, nor does any version of Android on the emulators raise it. The only crash errors I see are these and always on "Platforms OTHER". I'm assuming if a different crash was reported I'd get a better clue regarding the platform - I'd expect to see "8", "11" etc.
It's a paid app. It happens right on first run so the users are cancelling the purchase.
Does anyone know what this platform is please?

A: In my experience, the developer console reports very few of the crashes occurring in your app.
If your app already requests internet permission you can use an error reporting library.
I use ACRA in my app. It's very easy to integrate and you'll be amazed at the number of crashes that don't get reported in the market developer console.

A: The Platforms section displays the device the crash occurs on, not API level.  However, as you've seen, it's very limited.  The only values I've seen besides OTHER are

*

*T-Mobile myTouch 3G

*Nexus One

*Droid

Anything else is lumped in with OTHER.  Obviously, the list of devices it separates out is vastly incomplete and not very helpful.  Until Google improves it, the Platforms sections is essentially useless and I recommend using a third party library to get better information.


text:
Q: q-series related to d(n)=# of divisors of n Let $\sigma_m (n)=\sum_{d|n}d^m$, and $d(n)=\sigma_0(n)$ as stated in the title.
My question is: Does the q-series $f(q)=\sum_{n\ge 1} d(n)q^n$ gives something like a modular form (i.e. with some kind of identity under the action of $SL_2$) when $q=e^{2\pi i z}$?
When $d(n)$ is replaced by $\sigma_{2m-1} (n)$ the q-series gives out Eisenstein series, which are exactly modular forms. One way to obtain such a relation is to use Hecke's converse theorem for the L-function $\zeta(s) \zeta(s-2m+1)$. So I feel natural to think about $\zeta(s)^2$ for properties of $\sum_{n\ge 1} d(n)q^n$.
I tried to modify the argument of Hecke's converse theorem but it does not really give me a neat relation.
Any help will be appreciated. Thanks in advance.

A: The coefficient $d(n)$ is the limit of the $n$-th Hecke eigenvalue of the (nonholomorphic) Eisenstein series $E(z,s)$ as $s\to 1/2$. The limit of the Eisenstein series itself is zero, hence it is more natural to consider the $(\partial/\partial s)E(z,s)$ at $s=1/2$, which is precisely
$$ \sqrt{y}\log y+4\sqrt{y}\sum_{n=1}^\infty d(n)K_0(2\pi ny)\cos(2\pi nx). $$
In short, you have to leave the realm of holomorphic modular forms to find the object you are looking for: $d(n)$ is "morally" the $n$-th Hecke eigenvalue of the Eisenstein series with Laplace eigenvalue $1/4$ (which is zero eventually, so we pass to the derivative). This is another reason why Maass forms are so natural, something that not every arithmetician appreciates!
You can read more about this fascinating story in Iwaniec: Introduction to the spectral theory of automorphic forms. The limit Eisenstein series above is discussed at the end of Chapter 3.


text:
Q: Amazon Cloudfront Cache-Control: no-cache header has no effect after 24 hours I'm hosting a static website in S3 and using Cloudfront to cache files. I've essentially got 3 files with the following headers:

*

*index.html (Cache-Control: no-cache)

*app.js (Cache-Control: max-age=63072000, public)

*style.css (Cache-Control: max-age=63072000, public)

My html file uses query string parameters that get updated every time I update my css or js files. I've configured s3 to pass these parameters through and I've verified that it works to invalidate cached resources. My index.html file looks something like this:
<html>
    <head>
        ...
        <link rel="stylesheet" href="app.css?v=14113e2c764">
    </head>
    <body>
        ...
        <script src="app.js?v=14113e2c764"></script>
    </body>
</html>

It seems to work great as I push updates all day, but when I come in the next morning and push my next change, The index.html file is out of date. Instead of having the correct ?v= parameter, it has the old one! The only way to fix it is to invalidate the html file manually. Then everything works for the rest of the day. The next day I have the same problem again.
What's going on here?

A: Verify that the CloudFront distribution's Minimum TTL is set to 0. If it's set to any other value, CloudFront won't respect the no-cache header and will still cache the file for the Minimum TTL. More details about the caching directives can be found here:
http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
If this doesn't help, try to debug the actual HTTP request for index.html and post the response headers here so we can have a look at them.
Also, instead of using no-cache for the index.html file, you can try using
public, must-revalidate, proxy-revalidate, max-age=0
This will allow CloudFront to store the file on the edge location, but it will force it to revalidate it with the origin with each request. If the file hasn't changed, CloudFront will not need to transfer the file's entire content from the origin. This can speed up the response time, especially for larger files.

A: This is more of a comment, but a bit too long. Hopefully helps others that land here.
Cache busting via query parameter has drawbacks, although perhaps you can combat them all via Cloudfront behaviors. See https://stackoverflow.com/a/24166106/630614. Still, I would recommend unique filenames e.g. app.css?v=14113e2c764 becomes app.14113e2c764.css.
To respond to BradLaney's comment/issue: If you've updated cache-control headers and don't see the changes, it's because the origin item is already cached – invalidate it and you should see the new headers the next time you view the resource.
Regarding race condition when setting cache-control for S3 items, or just setting cache-control in general for an SPA, this is what's working well for my team:
# Sync all files with 1 week cache-control, excluding .html files.
aws s3 sync --cache-control 'max-age=604800' --exclude *.html dist/ s3://$AWS_BUCKET/
# Sync remaining .html files with no cache.
aws s3 sync --cache-control 'no-cache' dist/ s3://$AWS_BUCKET/


text:
Q: Cant Format Seagate Expansion External Drive I bought a new Seagate External Hard drive. I did a format before starting to transfer my files. but during the format the power cut out due to power shortage here in our place. When power comes back I checked my external again. it tells me that the external needs to format but I am not able to format it using the normal format. Disk management freezes when the external is connected, I also tried to format it using diskpart but when I am in the "clean" part my hard drive disconnects. is there someone here experienced the same? how you resolved it. please help. thanks in advance

A: The disk seems to have died out because of the sudden power cut, or perhaps the power
cut was preceded by a power surge that fried some weak component inside the disk.
This is not a normal behavior for a hard disk, that is supposed to be more resilient
to power cuts or small surges.
I would suggest to return the disk as being defective (no need to mention power
problems) and ask for a replacement or reimbursement.
On the other hand, if your house or area is prone to power problems, I would suggest
to put your equipment behind a power-surge protector or even a (costlier) UPS.


text:
Q: Is where a way to track data changes in SQL SERVER 2000? For example, if I execute an UPDATE/INSERT query to change values in a table, can it be tracked on SQL2000?

A: No. Well, yes, if you consider writing your own tracking triggers and / or analysing the logfile to be tracking.
CDC - Change Data Capture - was introduces WAAAAAAAYYYY later than SQL Server 2000... which is ancient and seriously out of support, btw.


text:
Q: Factor and Remainder Theorem Please help me with this exam style question from the IGCSE 2020 Specimen Paper.
The polynomial
$$p(x)=2x^3 -3x^2 +qx+56$$
has $x-2$ as a factor.
Show that $q=-30$.

A: If $x-2$ is a factor, then $p(2)= 2\cdot 2^3 -3 \cdot 2^2 + q\cdot 2 + 56 = 0$.
$$\Rightarrow 2q = -60$$

A: You want $P(2)=0$
What is $ P(2)$ when $ p(x)=2x^3 -3x^2 +qx+56$?
Let $x=2$ and solve for $q$


text:
Q: Question about Hahn Banach Theorem A version of the Hahn-Banach Theorem states that:

Let $Y$ be a subspace of a linear normed space $X$ and $\phi$ be a continuous linear functional on $Y$. Then, there exists a continuous linear functional $\Phi$ on $X$ such that $\Phi(y) = \phi(y)$ for all $y\in Y$ and $\|\Phi \| \leq \|\phi \|$

To beter understand this result, I tried to extend $\phi$ naively as:
Let $\Phi(x) = \phi(x)$  if $y \in Y$ and $\Phi(x) = 0$ otherwise.
What is wrong about my $\Phi$?

A: $\Phi$ is not linear. Take some $y\in Y$ with $\phi(y)\ne 0$ and some $x\in X\setminus Y$. Then $x+y\notin Y$. So $\Phi(x+y)=0$, but $\Phi(x)+\Phi(y)=0+\phi(y)\ne0$.


text:
Q: Using math mode? A MWE:
\documentclass[12pt]{book}
\usepackage{imakeidx}
\usepackage{xcolor}
\usepackage{setspace}
\usepackage{lipsum}
\usepackage[margin=.5in]{geometry}
\usepackage{parskip}
\usepackage{bookmark}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{mathtools}
\usepackage{amsmath}
\usepackage{accents}
\usepackage{bm}
\usepackage{amsfonts}
\usepackage{enumitem}
\usepackage{fancyvrb}
\usepackage[bottom]{footmisc}
\makeindex
\usepackage{hyperref}

\begin{document}

    We know that the \textbf{dual} of $\mathbf{a_1}$ is ${\mathbf{a_1}^\perp}$

    We know that the \textbf{dual} of $\mathbf{a_1}$ is {${\mathbf{a_1}}^\perp$}

\end{document}

Having just learnt to use math mode I have the following problem:
We know that the \textbf{dual} of $\mathbf{a_1}$ is ${\mathbf{a_1}^\perp}$

Results in an error "Mathbf only allowed in math mode". I have tried some variations that give me the error "insert } missing" as follows:
We know that the \textbf{dual} of $\mathbf{a_1}$ is {${\mathbf{a_1}}^\perp$}

I definitely do not understand the placement of the $ signs around math symbols. Any pointers?

A: (too long for a comment, hence posted as an answer)
Some comments and observations:

*

*Not even one of the packages loaded in your preamble is needed to compile the body of the document. Do take some time to figure which packages are really needed to compile your full document.

*The body of the document you've posted actually compiles without errors.

*You may want to give special thought as to whether the subscript term should also appear in bold. The following screenshot displays the results of both types of input for the subscript term.

\documentclass[12pt]{book}
\begin{document}
We know that the \emph{dual} of $\mathbf{a}_1^{}$ is $\mathbf{a}_1^\perp$.

\medskip
We know that the \emph{dual} of $\mathbf{a_1^{}}$ is $\mathbf{a}_{\mathbf{1}}^\perp$.
\end{document}