text:
Q: how to use collide direct for multiple sprites #sprites

import random, sys, time, math, pygame
from pygame.locals import *
from pygame import mixer # Load the required library

FPS = 30 # frames per second to update the screen
fpsClock = pygame.time.Clock()
WINWIDTH = 1500 # width of the program's window, in pixels
WINHEIGHT = 1000 # height in pixels
HALF_WINWIDTH = int(WINWIDTH / 2)
HALF_WINHEIGHT = int(WINHEIGHT / 2)

moveX,moveY=0,0
move2X,move2Y=0,0

GRASSCOLOR = (24, 255, 0)
WHITE = (255, 255, 255)
PURPLE = (128, 0, 128)
RED = (255, 0, 0)
pygame.init()

global FPSCLOCK, DISPLAYSURF, self
DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
pygame.display.set_icon(pygame.image.load('god.png'))
pygame.display.set_caption('Smash Bros Melee')
BASICFONT = pygame.font.Font('freesansbold.ttf', 32)

class Sprite:
    def __init__(self,x,y):

        self.x=x
        self.y=y
        self.width=50
        self.height=50
        self.i0= pygame.image.load('ryanrenolds.jpeg')

        self.timeTarget=10
        self.timeNum=0
        self.currentImage=0

    def render(self):

            DISPLAYSURF.blit(self.i0, (self.x, self.y))

player=Sprite(0,0)

class Sprite2:
    def __init__(self,x,y):

        self.x=x
        self.y=y
        self.width=50
        self.height=50
        self.i0= pygame.image.load('ArkhamKnight.png')
        self.i1= pygame.image.load('Black-Panther.png')
        self.timeTarget=10
        self.timeNum=0
        self.currentImage=0

    def update(self):

        self.timeNum+=1

        if (self.timeNum==self.timeTarget):

            if (self.currentImage==0):
                self.currentImage+=1
            else:
                self.currentImage=0
            self.timeNum=0
        self.render()

    def render(self):

        if(self.currentImage==0):
            DISPLAYSURF.blit(self.i0, (self.x, self.y))

        else:
            DISPLAYSURF.blit(self.i1, (self.x, self.y))

player2=Sprite2(200,300)

def checkCollision(Sprite, Sprite2):
  col = Sprite.rect.colliderect(Sprite2.rect)
  if col == True:
    sys.exit()

while True:

        for event in pygame.event.get():

                if event.type == KEYUP:
                    if event.key == K_a:
                       moveX = moveX - 0
                    elif event.key == K_d:
                       moveX == False
                    elif event.key == K_w:
                       moveY == False
                    elif event.key == K_s:
                       moveY == False

                if (event.type==pygame.KEYDOWN):
                   if (event.key==pygame.K_a):
                      moveX = moveX - 5
                   elif (event.key==pygame.K_d):
                       moveX = moveX + 5
                   elif (event.key==pygame.K_w):
                       moveY = moveY - 5
                   elif (event.key==pygame.K_s):
                       moveY = moveY + 5
                   elif (event.key==pygame.K_ESCAPE):
                       pygame.quit()
                       sys.exit()

                if event.type == KEYUP:
                    if event.key == K_LEFT:
                       move2X = move2X - 0
                    elif event.key == K_RIGHT:
                        move2X == False
                    elif event.key == K_UP:
                        move2Y == False
                    elif event.key == K_DOWN:
                        move2Y == False

                if (event.type==pygame.KEYDOWN):
                    if (event.key==pygame.K_LEFT):
                        move2X = move2X - 5
                    elif (event.key==pygame.K_RIGHT):
                        move2X = move2X + 5
                    elif (event.key==pygame.K_UP):
                        move2Y = move2Y - 5
                    elif (event.key==pygame.K_DOWN):
                        move2Y = move2Y + 5
                    elif (event.key==pygame.K_o):
                        player=Sprite(0,0)
                        player2=Sprite2(200,300)
                    elif (event.key==pygame.K_ESCAPE):
                        pygame.quit()
                        sys.exit()

         DISPLAYSURF.fill(PURPLE)
         player.x+=moveX
         player.y+=moveY
         player2.x+=move2X
         player2.y+=move2Y
         player.render()
         player2.update()
         checkCollision(Sprite, Sprite2)
         pygame.display.update()
         fpsClock.tick(FPS)

 pygame.quit()
 sys.exit()

how do i get to wear my sprites will collide my collide direct code asks for three arguements when i used self in the parameters but when i took self out it says that class Sprite has no attribute 'rect'
This the error i keep getting how do i fix this to where my game works to where my sprites will exit the game if they collide with each other
Traceback (most recent call last):
  File "C:\Python27\Sprites\sprites.py", line 159, in
    checkCollision(Sprite, Sprite2)
  File "C:\Python27\Sprites\sprites.py", line 88, in checkCollision
    col = Sprite.rect.colliderect(Sprite2.rect)
AttributeError: class Sprite has no attribute 'rect'

A: You don't have the attribute rect in your Sprite class, which is causing this problem. You also need an attribute rect in your Sprite2 class. You can do this by using the get_rect() method.
You can do this in your Sprite class by entering this in the __init__(self)
self.rect = self.i0.get_rect()

And for the Sprite2 class you can do this (because displayed image can change, put this in the update().)
if self.currentImage == 0:
    self.rect = self.i0.get_rect()
elif self.currentImage == 1:
    self.rect = self.i1.get_rect()

I hope this helps.


text:
Q: Why do I have to cherry-pick when performing reviews in iOS? Starting about 2 days ago, something seems terribly wrong with the various review screens. And this for any SE site, using an iOS device (running 9.3.5), and browser either Safari or Dolphin. No idea so far how it looks like in the most recent iOS version. Looking at similar review pages on a Win PC seems to work fine.
Here is a screenprint of a sample of such review screen:

Long story short:

*

*Any of the typical review actions (like flag, upvote, downvote, edit) are all disabled, so that the I'm done button always remains disabled, so either you use No Action Needed, or Skip to move on to the next review (if any).

*Surprisingly, for sites that have audit reviews enabled, this issue does not occur for such audit reviews. I.e. those special reviews can be processed as normal (though you recognize those types of reviews right away of course, great ...).

Is this intended to be like this, or is it rather some issue that needs to be fixed?
Notes:

*

*Not sure if it is related, but the All time review counter (the 3,453 in the screenprint above) doesn't get updated either in between 2 reviews, so if you'd click No Action Needed and the next review is shown, that counter didn't get updated either. If however you'd use the Review button (upper right in the screenprint), to just move on to the next review without any review action for the current review, then that counter does get refreshed to the then current value of it.

*While waiting for those disabled options to become enabled again, the only serious review actions appear to be to cherry-pick (*) the 'No Action Needed' reviews, and 'Skip' the reviews of posts that otherwise I'd want to flag, edit, vote, etc.

(*) It's the time of the year around here:

redpajama_set_name: RedPajamaStackExchange


text:
Q: strings not outputing before program is paused I have started making a text game and at the start the user takes a test which is then graded and the user is told how well they did. I want to pause the program to make it look like it has to take time to grade but it will not output the string I want and will go straight to pausing the program.
whenever I comment out the thread sleeping, the string will output but whenever I put it back into the program, I will go back to pausing before the string can output even though the string outputting is before the program pauses.
#include <iostream>
using namespace std;
int main(){
  char questionAnswer;
  int randomAnswer;
  string testAnswers, testKey;
   //create test answers
    for(int answer = 0; answer < 5; answer++){
      randomAnswer = rand()%4+1;
      switch(randomAnswer){
        case 1:
          testKey += 'A';
          break;
        case 2:
          testKey += 'B';
          break;
        case 3:
          testKey += 'C';
          break;
        case 4:
          testKey += 'D';
          break;
      }
    }
   //start test
    for(int question = 0; question < 5; question++){
      cout << "Question " << question+1 << ":\t";
      cin >> questionAnswer;
      while(toupper(questionAnswer) != 'A' && toupper(questionAnswer) != 'B' && toupper(questionAnswer) != 'C' && toupper(questionAnswer) != 'D'){
        cout << "\nInput Valid Answer:\t";
        cin >> questionAnswer;
      }
      testAnswers += toupper(questionAnswer);
      cout << endl;
    }
    cout << "\nGrading...";
    //pause fo dramatic effect
    this_thread::sleep_for(5s);
    cout << "Student Answers:\t" << testAnswers << endl;
    cout << "Test Answers:\t" << testKey << endl;
}

A: That is because standard output is buffered. If you flush the output before pausing, it should work.
cout << "\nGrading..." << flush;
this_thread::sleep_for(5s);

A: Use a \n at the end of the string, it solves the problem.
cout << "\nGrading...\n";


text:
Q: radio button submission in javascript returns the first value hello every body i have a code that submits a few text inputs along with a radio box together the problem is that all text inputs are submitted correct but the radio button sends the first value
here is my html code:
<form  action="process.php" method="POST">

        لینک بنر
        <input type="url" class="form-control" name="name" placeholder="http://example.com">

        تعداد کل کلیک
        <input type="number" class="form-control" name="email" placeholder="15000">

        تعداد کلیک روزانه
        <input type="number" class="form-control" name="superheroAlias" placeholder="حداقل 1000">

        <input type="radio"  name="position" value="head" >

        <input type="radio" name="position" value="right" >

        <input type="radio" name="position" value="left"  >

    <button type="submit" class="btn btn-success">Submit </button>

</form>

and my js file that processes this code is :
$(document).ready(function() {

// process the form
$('form').submit(function(event) {

    $('.form-group').removeClass('has-error'); // remove the error class
    $('.help-block').remove(); // remove the error text

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val(),
        'position'          : $('input[name=position]:checked').val()
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'process.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })

A: 1) try to add event.preventDefault(); inside form submit event on top
2) set var formData = $('form').serialize();
this code works perfectly :
    <form  action="" method="POST">

        لینک بنر
        <input type="url" class="form-control" name="name" placeholder="http://example.com">

        تعداد کل کلیک
        <input type="number" class="form-control" name="email" placeholder="15000">

        تعداد کلیک روزانه
        <input type="number" class="form-control" name="superheroAlias" placeholder="حداقل 1000">

        <input type="radio"  name="position" value="head" />
        <input type="radio" name="position" value="right" />
        <input type="radio" name="position" value="left"  />
    <button type="submit" class="btn btn-success">Submit </button>
</form>


text:
Q: Can't access derived class method from pointer of type base class I should specify that I'm a bit new to OOP.
 I'm tying to make a vector of type pointer to Person that has a method GetName() and access a method GetSpg() from my Player class that derives Person. I get an error "GetSpg() is not a member of Person". My question would be: is there any way to access both functions from the vector so that if it points to a Person to not show that method but if it is to do so?
Here is my code:
#ifndef _PERSON_H
#define _PERSON_H

#include <iostream>
#include <algorithm>

typedef std::pair<std::string, std::string> StrPair;

class Person :private StrPair
{

  public:
    Person(const std::string& fn = "none", const std::string& sn = "none")         :StrPair(fn,sn){};
    virtual void Update(const std::string& fn, const std::string& sn){ StrPair::first = fn; StrPair::second = sn; };
    virtual const StrPair& GetName(){ return (const StrPair&)(*this); };
};
#endif

typedef std::pair<int, int> IntPair;

class Jucator: public Person, private IntPair
{
    std::string tip;
    int spg;
    int average;

  public:
    Jucator(const std::string& fn = "none", const std::string& sn = "none",
        const std::string& t = "", const int& _spg = 0, const int& _avr = 0,
        const int& _g = 0, const int& _r = 0) :Person(fn, sn),tip(t),spg(_spg),average(_avr),IntPair(_g,_r){};
    virtual void Update(const std::string& fn, const std::string& sn, const std::string& t, const int& _spg, const int& _avr,
        const int& _g, const int& _r){
    Person::Update(fn, sn); tip = t; spg = _spg; average = _avr; IntPair::first = _g; IntPair::second = _r;
};

virtual const int& GetSpg(){ return spg; };

A: You can't.
A pointer of type Person can only be used to access data/addresses(functions) that are part of the Person object. The compiler simply has no way of knowing what all classes could be deriving from Person and hence which operations are legal.
Have a look at Dynamic casting. MSDN Reference | Tutorial
In brief:
Player* pPlayer = dynamic_cast<Player*>(pPerson);
if (pPlayer) {
  //Use the pointer like a player pointer
  //Note: You can only call player functions from pPlayer, not pPerson
} else {
  //Use the pointer like a person pointer
}

Note that this casting is a runtime operation. At compile time, the compiler sees you using the Player pointer to access Player code, which it is happy to allow!
Disclaimer: I found your code tough to follow, so consider this an answer to your question in text

A: The problem you're facing is very similar to the classic animal/cat/dog example. The basic idea is you have a base class - Animal - and two classes that derive from it - Cat and Dog.
class Animal {
    public:
    Animal() {}
    virtual ~Animal() {}
};

class Dog : public Animal {
    public:
    Dog() : Animal() {}

    void bark() { std::cout << "Woof" << std::endl; }

    ~Dog() {}
}

class Cat : public Animal() {
    public:
    Cat() : Animal() {}

    void meow() { std::cout << "Meow" << std::endl; }

    ~Cat() {}
}

Now, if you declare a Cat or a Dog object, it's pretty obvious that  you can call either bark() or meow(); but if you declare an Animal object, there's no way of knowing whether it's a Cat or a Dog, so you can't call either method.
In your case, you have Person as the base class and Player as the derived. You may further derive Person and have a new class, NonPlayer, so that Person would play the same role as Animal, and Player and NonPlayer would be Cat and Dog respectively.
If you really need to access Player methods from pointers to Person objects, you need to cast the Person* to Player* before. However, you need to be sure before that the pointer inside is a Player*. If it isn't, you'll most likely get a compilation error.

A: There are concepts of upcasting and downcasting which are essential to understand your problem. You can use the concept of dynimc_cast, this Link would be helpful to understand.


text:
Q: Custom header control/footer of Transfer in Ant Design library I have the following Table Transfer control with antd design.
I would like to add a list box select on the top where I could filter by Groups. Currently this is what I have but it looks like there are too many header items (groups filter, item count - 1135 Document Types, Search here text box.
I would like to consolidate the three items with some custom header control. Any ideas? This might be an overkill.
Or
How about moving the Document Types count to the bottom?
Only Doucment Groups and Search here would show up as the header. 1135 Document Types would be the footer. This is a sandbox. I need help with moving the
https://codesandbox.io/s/7uc1g?file=/index.js


text:
Q: ASPNET Core: Wrong Value for ContentRootPath I have an ASP.NET core application with the following configurations:
public Startup(IHostingEnvironment hostingEnvironment)
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(hostingEnvironment.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}

When I publish the application and run it using the dotnet MyApp.dll inside the application directory, it runs with no problems. When I execute the the command dotnet /dir1/dir2/MyApp.dll, it fails to load the appsettings.json file. I did a little digging and found out that the ContentRootPath is set to the directory I'm running the dotnet command from and not the actual directory of the application. Can anyone tell me how to fix this issue?

A: I have the same problem. I often store my code in a /src folder which contains multiple projects. So from the CLI I would like to do the following:
cd /c/code/repo
dotnet restore /src/solution.sln
dotnet build /src/solution.sln
dotnet run /src/project/project.csproj

The first 2 work no problem but the CLI for .NET Core 2.0 does not recognize .SetBasePath(env.ContentRootPath) as the path where the project is being built to. Instead it uses the current path I am in on the CLI.
This results in:
Unhandled Exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\code\repo\appsettings.json'.

The only way I can get it to work is if I go the that directory:
cd /src/project
dotnet run project.csproj

Which is fine but if I want to rebuild the solution then I need to navigate back to /src where my .sln is located which is very annoying.
Seems like a bug in the CLI.

A: If you are having this issue when debugging within VS Code this can be caused by incorrect configuration in the .vscode\launch.json file
you need to make sure the "cwd" parameter for your build points at your project - so in this case it would need to be:
"cwd": "${workspaceFolder}/src/project"

Then the hostingEnvironment.ContentRootPath value will be correct when running Startup.

A: Similar to Adrian Massey. I had a project launching from VS with the wrong working directory, but only when using IIS.
I deleted all .vs files and reorganized and saved my sln file so that the projects were in alphabetical order.
I was looking for any bad references or other anomalies. After saving, a forced reload occurred.
Now my project no longer picks up the working directory of another project.

A: I came across a scenario where if you have similar folder names it sets the ContentRootPath of the wrong project.
i.e.
foo.api/foo.api.csproj
or
bar.api/bar.api.csproj
would show the ContentRootPath for the project:
api/api.csproj so it loaded an appsettings file, just not the right one.
To fix, I renamed the project folders without the '.' separators


text:
Q: Regex function to delete all numbers and punctuation except a specified expression? I have a string in Python:
string = "Hello I am a 21 !string. In section 3.2.F.1.2 we covered 1topic X. On the oth1er hand, in section 1.2.F.1.1 we covered Y. Lastly, in section F.3.2 we 23 covered Z."

I need to remove the random numbers and punctuation from the text such that:
"a 21 !string" --------> "...a string..." and...
"covered 1 topic x." ---------> "covered topic"
My final string should then be:
filtered = "hello i am a string in section 3.2.F.1.2 we covered topic x on the other hand in section 1.2.F.1.1 we covered y lastly in section 1.1.F.3.2 we covered z"

...such that the codes "3.2.F.1.2", "1.2.F.1.1", and "1.1.F.3.2" were not affected by this.
I was able to generate a regex expression to specify the codes with:
regex_codes = "[\d\.]{1,4}F[\.\d]{1,4}"

all_nums_punct = "[0-9 _.,!"'/$]*"

What I cannot figure out is how to "select and remove all numbers and punctuation (all_nums_punct) except these codes (regex_code) pattern".
I tried using a "negative lookahead" pattern to ignore everything that starts with my codes from a previous stackOverflow article, but my selection is not selecting anything.

A: Using the regex package from the PyPI repository:
import regex

string = "Hello I am a 21 !string. In section 3.2.F.1.2 we covered 1topic X. On the oth1er hand, in section 1.2.F.1.1 we covered Y. Lastly, in section 1.1.F.3.2 we 23 covered Z."
string = regex.sub(r'''[\d\.]{1,4}F[\.\d]{1,4}(*SKIP)(*FAIL)|[0-9_.,!"'/$]''', '', string)
print(string)

Prints:
Hello I am a  string In section F we covered topic X On the other hand in section F we covered Y Lastly in section F we  covered Z

We match either your  regex_codes expression or one of your all_nums_punct characters (without the space character). If we match the regex_codes expression, we skip over those characters and fail the test and try the second alternative.
The results will have possibly multiple contiguous space characters. You will need a second replace operation to replace these with a single space:
import regex

string = "Hello I am a 21 !string. In section 3.2.F.1.2 we covered 1topic X. On the oth1er hand, in section 1.2.F.1.1 we covered Y. Lastly, in section 1.1.F.3.2 we 23 covered Z."
string = regex.sub(r'''[\d\.]{1,4}F[\.\d]{1,4}(*SKIP)(*FAIL)|[0-9_.,!"'/$]''', '', string)
string = regex.sub(r' +', ' ', string)
print(string)

Prints:
Hello I am a string In section 3.2.F.1.2 we covered topic X On the other hand in section 1.2.F.1.1 we covered Y Lastly in section 1.1.F.3.2 we covered Z

Update
I will try to answer the question you posed to @WiktorStribiżew concerning how his solution below worked:
re.sub(r"""([.\d]{1,4}F[.\d]{1,4})|[0-9_.,!"'/$]'""", '\1', $string)

Whatever the regular expression matches will be replaced by '\1', which specifies the value of capture group 1. If the regular expression matches a regex_codes, then capture group 1 will be set to what ever it matches and the matched string will be replaced with itself and nothing is modified. However, if the regular expression matches one of the characters you wish to delete, then capture group 1 will be empty and the matched string will be replaced by an empty string. This method does not require the regex package. This method, too, will leave contiguous spaces, which you will probably want to remove as I have indicated.


text:
Q: Can you write in dynamodb at the same time from parallel or asynchronous functions while being in a free layer? execution without parallel functions: time = x
execution with 4 parallel functions: time = x / 4
When the code attached with 4 parallel functions is executed, the total time is not divided for 4, but is maintained.
my question is:
Does Dynamodb support parallel function table writes?
def patronfanin_out(event, context):
    for i in range(4):
        x= list #aqui envio una lista nueva para cada función
        response = lambda_client.invoke(
        FunctionName="tesis-aws-patrones-dev-workers",
        InvocationType='Event',
        Payload=json.dumps(x)
      )

def workers(event, context):
  table = boto3.resource('dynamodb').Table('patron2')
  rowsFinal = event['list']
  for row in rowsFinal:
    table.put_item(Item={
        'id': str(uuid.uuid4()),
        'serie': row[0],
        'rank': row[1],
        'discipline': row[2],
        'sex': row[3],
        'salary': row[4]
        })
  response = {
      "statusCode": 200,
      "params" : rowsFinal
  }
  return response

I wish that the total execution time of the function will decrease considerably, since I am using 4 parallel functions.
total execution time: x
total execution time wish: x/4

A:   for row in rowsFinal:
    table.put_item(Item={
        'id': str(uuid.uuid4()),
        'serie': row[0],
        'rank': row[1],
        'discipline': row[2],
        'sex': row[3],
        'salary': row[4]
        })

This doesn't seem to run in parallel, but in an iterative way
EDIT
invoke, as stated in https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.invoke is synchronous, it waits for the response.
Use invoke_async https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.invoke_async and they will run in parallel.
EDIT 2
Instead of table.put_item use batch_write_item()
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.batch_write_item
And group them by max 25 items or 16MB total https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html


text:
Q: MySQL returns same result multiple times even with Distinct Here is sql
        SELECT DISTINCT
            t1.`name` team1_name,
            t1.id team1_id,
            t2.id team2_id,
            t2.`name` team2_name,
            sc.`name_en` sportCatname,
            c.title championshipTitle,
            e.date eventDate,
            e.id eventId,
            e.title,
        FROM
            `Event` e,
            `SportCategory` sc,
            `Championship` c,
            `Team` t1,
            `Team` t2
        WHERE
            e.top = 1
        AND t1.id = e.team1ID
        AND t2.id = e.team2ID
AND sc.id = c.sportCategoryID

Tried with JOIN also. No way. It returns corrects rows but, in result set I have same row 2 times. What am I doing wrong?

A: There is no relationship for SportCategory and  Championship in the where clause. This is the reason for having duplicate results.
You should provide the relationship in the where clause.

A: Can you check if any column has a special characters that are not in other rows?


text:
Q: Is redirection of events a good practice in C#? If true, who should be the 'sender'? I am now refactoring a code written by someone else and I have found a construct that I have mixed feelings about. There is a ListView-like control and each of its items can raise 'DialogOpened' event. However, it may be cumbersome to register external event handlers to each of the items (and the items may be added or removed dynamically!). For that reason there is a single event in the ListView-like control and it is named 'ItemDialogOpened'. It sounds all reasonable for me, but there are two issues:

*

*There is a method 'OnItemDialogOpened' in the ListView-like control raising the single event, but this method is not called directly. Instead, it is registered as an event handler to 'DialogOpened' event of each item. It that ok? I am asking, because I was unable to find anything similar to it in the MSDN.

*If such event redirection is ok, then who should be the sender of that final, single event? Now, in the code I am working with it is the original sender - the item. However, I think (but I am not sure about it), that now the sender should be changed to the ListView-like control. Am I right?

A: For 2 - it is a little bit open to interpretation. Generally you would expect the sender to be the thing you subscribed to; any other information should be conveyed via the args - but there are exceptions, where (for example) the individual item comes through as the sender.
The important thing is to document it clearly.

A: For 1: This approach does not fully fit into standard flow pattern. From my point of view you must hide your own implementation logic in private method (this method will be end-point for each item DialogOpened event), and then this method will call protected virtual method OnItemDialogOpened. In this case listview can be inherited, communication logic will be transparent and more ms-like, and subscriber will work without casting (because casting is hidden in your private method). Something like that:
private void DialogOpenedHandler(object sender, EventArgs e)
{
    OnItemDialogOpened(new ItemEventArgs((YourItemClass)sender);
}

protected virtual OnItemDialogOpened(ItemEventArgs e)
{
    // call event here
}


text:
Q: SSL self signed certificate not working on ipad / iphone We use IIS 7 and self signed certificates for our internal sites. All works perfect on windows PCs, laptops and from the server itself. the request https:// server/folder resolves correctly.
However, when we try to connect using an ipad or iphone, the page cannot be displayed. Chrome on iOS says "Page cannot be displayed" and Safari simply shows a blank page.
Is there any settings we need to change from the server side in order to make this work?


text:
Q: A network-related or instance-specific error occurred while establishing a connection to SQL Server in Azure I have a ASP NET MVC web application and in the solution I'm running two apps that are connected to the same database. Both are published on Azure and I also have a Azure SQL Server and database connected. The first app is running fine with fetching data and login etc. The second app however runs but when I need data from the database it gives the following error:

I found a solution on StackOverflow to add ASPNETCORE_ENVIRONMENT with value Development to get a better understanding of the error. Now when I run the specific view in the app this error pops up:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SNI_PN11, error: 26 - Error Locating Server/Instance Specified)
I can't seem to find a solution for this. Both apps have the same connection string to Azure and the first app runs fine. Hope somebody can help!


text:
Q: (JPA/JPQL) how to query TIMESTAMPDIFF in now() function? how to use this query? help me
problem that max(FUNCTION('TIMESTAMPDIFF', 'SECOND',
  startAt, endAt)))
startAt and endAt is LocalDateTime!
@Query(nativeQuery = false, value = """
  select new com.entity.repository.MyDto(category, max(FUNCTION('TIMESTAMPDIFF', 'SECOND',
  sendStartAt, sendEndAt)))
  from ReportHistory where eventAt >= :startAt
""")
fun findAllByStatistic(startAt: LocalDateTime): List<MyDto>?

data class MyDto(
        val category : String ?= null,
        val max : Long ?= null
)

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.stream.Stream com.entity.repository.MyDto.findAllByStatistic(java.time.LocalDateTime)!
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:93)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.(SimpleJpaQuery.java:63)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:76)
    at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:56)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:139)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:206)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:79)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lookupQuery(RepositoryFactorySupport.java:566)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery$1(RepositoryFactorySupport.java:559)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Collections$UnmodifiableCollection$1.forEachRemaining(Collections.java:1049)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:561)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$new$0(RepositoryFactorySupport.java:551)
    at java.util.Optional.map(Optional.java:215)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.(RepositoryFactorySupport.java:551)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:324)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297)
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:211)
    at org.springframework.data.util.Lazy.get(Lazy.java:94)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:300)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
    ... 30 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.hibernate.hql.internal.NameGenerator.generateColumnNames(NameGenerator.java:27)
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.generateColumnNames(SessionFactoryHelper.java:434)
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeColumnNames(SelectClause.java:270)
    at org.hibernate.hql.internal.ast.tree.SelectClause.finishInitialization(SelectClause.java:260)
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:255)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:1018)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:786)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:677)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:271)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:191)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143)
    at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:119)
    at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:595)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:704)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
    at com.sun.proxy.$Proxy112.createQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
    ... 59 common frames omitted

A: There is not registerFunction('TIMESTAMPDIFF') in org.hibernate.dialect.MySQLDialect.
So you cant use it in jpa.
you can use unix_timestamp() instead.
(function('unix_timestamp', sendStartAt)-function('unix_timestamp', sendEndAt))/60


text:
Q: Finding Direction of Angular Velocity Suppose I have a 3D rigid object on which some external forces act at various points located on it. The resulting motion would, in general, be the translation of center of mass plus rotation about the axis passing through Center of Mass. Velocity of center of mass can be easily found from summing external forces, so I have information about 'translational part'. I need to find the direction of Angular velocity or the direction of axis of rotation,
 assuming I know only about the location on the body where external forces act.
Suppose I find the torque about the center of mass (I chose COM because it simplifies the equations, no need to add pseudo torques).
But the direction of torque doesn't always point towards the axis of rotation (if it does then a nice proof using vectors would be a great help because I haven't been able to prove it), only the component of torque along the axis is proportional to magnitude of Angular acceleration, but that doesn't help because I want to know the direction of axis itself.
Finding angular momentum won't help either because angular momentum vector doesn't always point in the direction of angular velocity.
So if I know about the forces acting on the rigid body then how to predict the direction of rotational axis?
Basically knowing the direction of rotational axis passing through COM is important as once known I can simply take the component of net torque (about COM) along the axis to find angular acceleration and to fully analyze the motion.

A: The sum of torques on the center of mass $\vec{\tau}_C$ will let you know the direction of the angular acceleration $\vec{\alpha}$, by solving the Euler equations of motion $$ \vec{\tau}_C = \mathbf{I}_C \vec{\alpha} + \vec{\omega} \times \mathbf{I}_C \vec{\omega} $$
The result depends on the current angular momentum vector $$\vec{L}_C = \mathbf{I}_C \vec{\omega}$$
Note that the 3×3 mass moment of inertia tensor is calculated from the body  $\mathbf{I}_{\rm body}$ using the 3×3 rotation matrix $\mathbf{R}$ that transforms from local directions to world directions, as follows
$$ \mathbf{I}_C = \mathbf{R}\, \mathbf{I}_{\rm body} \mathbf{R}^\top $$
As far as the future angular velocity $\vec{\omega}$, you have to integrate the rotational acceleration over time to find the result. Remember a force does to result with velocity, but with acceleration. And acceleration over time results in velocity. Similarly for rotational dynamics.

A: Have you come across Inertia Tensors? If I've understood your question, then maybe take a look at how these work: 3D Rigid Body Dynamics:  The Inertia Tensor.
These govern the mathematics of the direction of angular momentum and angular velocity.

A: In general, the vector sum of the external torques equals dL/dt, the rate of change of the angular momentum vector.  If your object is starting at rest, the instantaneous axis of rotation would be in the direction of dL/dt.  Otherwise it would be in the direction of L, which may be changing with time. Note: a torque relative to the center of mass is given by R x F (vector product).


text:
Q: What is the use cases for Azure file storage? I'm using Azure file storage and there was a huge number of files uploaded. A single file will be 250kb in size and there will be 7000 files in a directory.
So when the user request I need to get the data from 100 files in a single call.
At first, I was accessing the files using native file IO methods after mounting the fileshare in the Azure VM. But it was slow due to file IO. Then I changed the native file IO to Azure Rest API and it was slightly fast.
So does this Azure file storage suits for my requirement or do I need to consider no-sql storages?
What was the exact use cases for file storage?

A: In my experience the usecase for an azure VM/disk space is aligned to scenarios related the execution of your program (say a config file or a limited number of resources).
If you want to upload a lot of data you should look into azure blob storage. Depending on your scenario it might be more cost effective
Microsoft also has some documentation what to use when here
https://docs.microsoft.com/en-us/azure/storage/storage-decide-blobs-files-disks
and of course the pricing
https://azure.microsoft.com/en-us/pricing/details/storage/blobs/

A: storage-decide-blobs-files-disks

You want to "lift and shift" an application to the cloud which already
  uses the native file system APIs to share data between it and other
  applications running in Azure.


text:
Q: (Node.js) Splitting JS class into modules I have a class "Firebase" in which I write all the functions (that involve this service) used in my server side.
At first, the code was pretty clean and clear, as there were not a lot of functions in this class. Now, the class is super giant (more than 100 functions not very short). This is why I have decided to divide the class into modules (maybe not correct) to improve the clarity and organization of the project.
Something like this:
/* eslint-disable no-empty */
const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Lazy initialization of the admin SDK
try {
     const googleCloudServiceAccount = require("../../utils/json/googleCloudServiceAccount.json");
     admin.initializeApp({
       credential: admin.credential.cert(googleCloudServiceAccount),
       databaseURL: URL,
       storageBucket: BUCKET,
     });
} catch (e) {}

class Firebase {
  constructor() {
    Object.assign(this, {
      auth: admin.auth(),
      firestore: admin.firestore(),
      storage: admin.storage(),
    });
  }
}

Object.assign(Firebase.prototype, {
  /* Methods */
});

module.exports = Firebase;

What I have in mind is to organize the code in modules like "firebase-auth.js", "firebase-storage.js", "firebase-firestore.js"... and finally, require all the modules methods (or something better, because it can be a really long list of imports) and assign them to my Firebase class prototype.
My question is: If in the methods of the modules I need to use Firebase.firestore, Firebase.auth... (which are members of the Firebase class), should I create an instance of the class in each module?
Any ideas?
Thank you.

A: try this, is not best but works as expectly
create a file with functions in export module like:
module.exports = function (app, dbConnection, firebase) {
       exampleFirebaseFunction(){
       }
}

and in your main file you call it as:
require('./routes/firebase-routes.js')(app, dbConnection, firebase);


text:
Q: Why MX libraries are in my SWF? I have a pure AS3 project. I use Ant to build it. Here is a part of my ant script:
<target name="mxmlc">
    <exec executable="${flex.home}/${mxmlc}" failonerror="true">
        <arg line="-compiler.include-libraries=${lib}"/>
        <arg line="-compiler.incremental=false"/>
        <arg line="-compiler.optimize=true"/>
        <arg line="-debug=false"/>
        <arg line="-default-background-color=0x${background.color}"/>
        <arg line="-default-frame-rate=60"/>
        <arg line="-default-size 800 600"/>
        <arg line="-static-link-runtime-shared-libraries=true"/>
        <arg line="-source-path='${src}'"/>
        <arg line="'${basedir}/${src}/${src.file}'"/>
        <arg line="-o=${bin}/${output.file}"/>
        <arg line="-use-network=true"/>
    </exec>
</target>

The problem is that my resulting SWF is really big. When I checked what is inside I saw that it has mx.* libs from Flex. Why it is like this? How to kick mx.* from my SWF?
p.s. In my code I don't use anything from mx.* library.

A: Even though your code doesn't import any mx.* classes directly, some of the classes you do import might have imports of their own. Are you using any of the built-in Flash, Flex or Spark components, for example?
Anyway, I wouldn't worry about the mx.* imports, but rather check the assets you are using:

*

*Components (Can you do without some and replace them with your own, simpler implementations?)

*Fonts

*Images

*Movies

*Sounds

These are usually responsible for bloating your SWFs, and adjusting image quality, or reducing the number of characters in an embedded font, for example, can greatly reduce your file size.


text:
Q: Format table cells according to datatype using Jinja2/Bootstrap I'm trying to automate a manual task where, every day, a colleague logs in to various systems, cuts/pastes chunks of data into an email, and then sends it to a group of people. I'm using Jinja2 for the template engine, and Bootstrap to make it look beautiful. Here's what's been done so far: https://gist.github.com/alexwoolford/ac342289bb90c5dda524
Some of the columns are percentages, some are counts, and some are dollars. For percentages, I'd like to multiply the value by 100, round to two decimal places, and add a percent sign (e.g. 0.34567 would be displayed as 34.57%). For counts, I'd like to comma separate the thousands (e.g. 1234567 would be displayed as 1,234,567). For dollars, I'd like to add a dollar sign, round to the nearest whole integer, and comma separate the thousands (e.g. 2345.67 would be displayed as $2,346).
Ideally, I'd like to simply add a class to the table cells in the template like this:
{{ row.some_percent_val }}
{{ row.some_count }}
{{ row.some_dollar_value }}

What would I need to do to the Jinja2 template to format the columns correctly?

A: css is not going to give you what you want. You'll need to use the jinja filter system.  Some of the built filters like format can probably get you most of the way there.  But you may need to create some custom ones.  For example you could do this to get a nice dollar display:
{{ "${:,.2f}" | format (row.some_dollar_value)}}

if you prefer,  you can use all the built in python methods on the string variable:
{{ "${:,.2f}".format (row.some_dollar_value)}}

Documentation for creating your own custom filters can be found here:
http://jinja.pocoo.org/docs/dev/api/#custom-filters


text:
Q: Proof that a sequence decreases past a certain point
I would like to try to prove that the sequence
  $$
\frac{\sqrt{6}^{x}}{x!}
$$
  for $x=0, 1, 2, \cdots$, is strictly decreasing when $x\geq 2$.

It appears to be the case after listing out a few terms. Here's my attempt at a proof:
To the contrary, suppose $\frac{\sqrt{6}^{x}}{x!} \leq \frac{\sqrt{6}^{x+1}}{(x+1)!}$ for $x \geq 2$. Then we have
\begin{align*}
\begin{split}
&\frac{x\text{ln}\sqrt{6}}{x!} \leq \frac{(x+1)\text{ln}\sqrt{6}}{(x+1)!}\\
&\Rightarrow \frac{1}{(x-1)!} \leq \frac{1}{x!}\\
&\Rightarrow \frac{x!}{(x-1)!} \leq 1\\
&\Rightarrow x \leq 1.
\end{split}
\end{align*}
But this contradicts our assumption on $x$, so the inequality above must in fact be ">". Thus the sequence is strictly decreasing for $x \geq 2$.
Any corrects/input appreciated.

A: The given sequence IS strictly decreasing for $x\geq 2$. If we follow your approach in a correct way, we find that the inequality
$$\frac{\sqrt{6}^{x}}{x!} > \frac{\sqrt{6}^{x+1}}{(x+1)!},$$ is equivalent to
$$\frac{(x+1)!}{x!} > \frac{\sqrt{6}^{x+1}}{\sqrt{6}^{x}}$$
which reduces to
$$x+1> \sqrt{6}$$
which is satisfied when $x> \sqrt{6}-1\approx 1.449$.
P.S. Note that $\sqrt{6}^{x}=\exp(x\ln(\sqrt{6}))$ (not $x\ln(\sqrt{6})$).


text:
Q: can $f$ twice differentiable on $(0, 1)$ and continous on $[0,1]$ have a derivative discontinuous on $[0,1]$ As I wrote in the title can the first derivative of $f$ be discontinous on $[0,1]$ given
$f(x): [0,1] \rightarrow \mathcal{R}$ twice differentiable on $(0,1)$ and continuous on $[0,1]$?
My idea is to use a function like:
$$f(x) = \begin{cases} \displaystyle x\sin\frac1x & \text{if } x \neq 0, \\
0 & \text{if } x = 0.\end{cases}$$
Which is continuous, differentiable on $(0,1)$ and it does not have a derivative in $0$ (which I understand means tha the derivative is discontinuous).
I am not sure if it is twice differentiable though.

A: With your $f$, $f' = sin(1/x) - (1/x)cos(1/x)$, which is a composition of differentiable functions on $(0,1)$, so yes this function satisfies all your conditions.


text:
Q: App routing providers not found angular 2 - inject a service before canactivate() I am trying to inject services in my angular 2 applications however the service is undefined when i call canactivate() in angular/router . How can i inject a service before canactivate() is called.
enter image description here
app.routing.ts
const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        canActivate: ['AuthGuardService']
    },
    {
        path: 'login',
        component: LoginComponent,
        outlet: 'popup'
    },
    // otherwise redirect to home
    {path: '**', redirectTo: ''}
];

export const appRoutingProviders: any[] = [
    {provide: "AuthGuardService", useValue: AuthGuardService}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

auth.guard.service.ts
import {Injectable, Inject} from '@angular/core';
import {AuthService} from "./auth.service";
import {Router, CanActivate} from "@angular/router";
import {Observable} from "rxjs";

@Injectable()
export class AuthGuardService  implements CanActivate {

  constructor(@Inject(AuthService) private auth, @Inject(Router)  private router) {
  }
  canActivate() : Observable<boolean> | boolean{

    if(this.auth.loggedIn()) {

      return true;
    }
    this.router.navigate([{outlets: {popup: 'login'}}]);
    return false;
  }
}

app.module.ts
@NgModule({
    declarations: [],
    imports: [ routing    ]
    providers: [
        appRoutingProviders,
        ...AUTH_PROVIDERS,
        AuthService,
        AuthGuardService,
        HttpService,
        {
            provide: AuthHttp,
            useFactory: AuthHttpServiceFactory,
            deps: [Http, RequestOptions]
        },
        IndicesEffectsService,
        DialogServiceService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

A: you'll need to expose your routes as a module
try this:
const appRoutes: Routes =
[
    {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuardService] // <- no quotes
    },
    {
        path: 'login',
        component: LoginComponent,
        outlet: 'popup'
    },
    // otherwise redirect to home
    {path: '**', redirectTo: ''}
];
@NgModule
({
  imports:   [ RouterModule.forRoot(appRoutes)],
  exports:   [ RouterModule],
  providers: [ AuthGuardService ] // <- provide guard
})
export class AppRoutingModule {}

then in your AppModule
@NgModule({
    declarations: [],
    imports: [ AppRoutingModule ] // <- import module here
    providers: [
        appRoutingProviders,
        ...AUTH_PROVIDERS,
        AuthService,
        // AuthGuardService, // <- no need for this
        HttpService,
        {
            provide: AuthHttp,
            useFactory: AuthHttpServiceFactory,
            deps: [Http, RequestOptions]
        },
        IndicesEffectsService,
        DialogServiceService
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}


text:
Q: Prevent webpack from rebuilding unless sources have changed I use webpack as a bundler AND task runner.
I don't want it to rebuild bundles if sources haven't changed:

*

*when run in watch mode, it caches to memory, and won't rebuild unless necessary

*BUT as a pure task runner (no watch mode), it rebuilds on every run
How do I prevent it from rebuilding every time? It takes longer, and thrashes my SSD drive.

A: I found the answer:
cache: {
  type: 'filesystem',
},

But sometimes I use webpack in watch mode, so I want to use memory instead. So I did this:
module.exports = (env, argv) {

  // ...

  cache: function () {
    return argv.env.WEBPACK_WATCH ? { type: 'memory' } : { type: 'filesystem' };
  }(),

}

So when in watch mode it will use memory, and when used as a pure task runner (not watching) it will cache to disk.
And in both cases webpack will avoid rebuilding if source files haven't changed.


text:
Q: Maintain scroll position of gridview inside a div I have a Master Page which contain a Script Manager.In a child page i have a scrollable gridview with checkbox and some textboxes
    <div id="grdScr" style ="width:130%;  overflow:auto" align="center" >
        <asp:GridView ID="dgvBill" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" ForeColor="Black" GridLines="Horizontal" PageSize="100"
            Width="150%">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="True"
                            oncheckedchanged="chkSelect_CheckedChanged" />
                        <asp:Label ID="lblVendCd" runat="server" Text='<%# Eval("vend_cd") %>'
                            Visible="false"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Bill date">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("bill_dt") %>'></asp:Label>
                        <asp:Label ID="lbltrid" runat="server" Text='<%# Eval("tr_id") %>'
                            Visible="False"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Bill no">
                    <ItemTemplate>
                        <asp:Label ID="lblBillNO" runat="server" Text='<%# Eval("bill_no") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Vendor">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("vend_nm") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Supplier">
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Eval("supplier") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Driver">
                    <ItemTemplate>
                        <asp:Label ID="Label5" runat="server" Text='<%# Eval("driver") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Vechicle Type">
                    <ItemTemplate>
                        <asp:Label ID="Label6" runat="server" Text='<%# Eval("comm_nm") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Vehicle No">
                    <ItemTemplate>
                        <asp:Label ID="Label7" runat="server" Text='<%# Eval("veh_no") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Payable Amount">
                    <ItemTemplate>
                        <asp:Label ID="Label8" runat="server" Text='<%# Eval("payable") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cash">
                    <ItemTemplate>
                        <asp:TextBox ID="txtCashGrid" runat="server" AutoPostBack="True"
                            Enabled="False" ontextchanged="txtCashGrid_TextChanged"
                            style="text-align: right" Width="75px" onkeypress="return isNumberKey(event)">0.00</asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cheque">
                    <ItemTemplate>
                        <asp:TextBox ID="txtChequeGrid" runat="server" AutoPostBack="True"
                            Enabled="False" ontextchanged="txtChequeGrid_TextChanged"
                            style="text-align: right" Width="75px" onkeypress="return isNumberKey(event)">0.00</asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Bank">
                    <ItemTemplate>
                        <asp:TextBox ID="txtBankNameGrid" runat="server" Width="174px"
                            AutoPostBack="True" ontextchanged="txtBankNameGrid_TextChanged"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cheque No">
                    <ItemTemplate>
                        <asp:TextBox ID="txtChqNoGrid" runat="server" Width="75px" AutoPostBack="True"
                            ontextchanged="txtChqNoGrid_TextChanged"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cheque Date">
                    <ItemTemplate>
                        <asp:TextBox ID="txtChDateGrid" runat="server" AutoPostBack="True"
                            EnableTheming="True" Width="97px"
                            ontextchanged="txtChDateGrid_TextChanged"></asp:TextBox>
                        <cc1:TextBoxWatermarkExtender ID="txtChDateGrid_TextBoxWatermarkExtender"
                            runat="server" Enabled="True" TargetControlID="txtChDateGrid"
                            WatermarkText="dd-MMM-yyyy">
                        </cc1:TextBoxWatermarkExtender>
                        <cc1:CalendarExtender ID="txtChDateGrid_CalendarExtender" runat="server"
                            Enabled="True" Format="dd-MMM-yyyy" TargetControlID="txtChDateGrid">
                        </cc1:CalendarExtender>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White"
                HorizontalAlign="Center" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"
                HorizontalAlign="Center" />
            <AlternatingRowStyle BackColor="#CCCCCC" HorizontalAlign="Center" />
            <RowStyle HorizontalAlign="Center" />
        </asp:GridView>
    </div>

My gridview is inside an update panel. The textboxes are doing some mathematical calculations in side the gridview in their TextChange Event and autopostback is true for them.
Whenever I am pressing tab for moving the cursor to the next textbox the page gets postbacked and the scroll position is not maintained. How will I solve this?


text:
Q: sshfs and emacs on OS X; file has changed since last visited or saved I am trying to use sshfs (2.2.0) and macfuse (2.0.3) along with emacs (23.2.1).
Many times when I try to save a file that I am editing from the remote file system I get the error:
file.txt has changed since last visited or saved; save anyway?

Occasionally I then get the error:
file.txt is write-protected; save anyway?

Are there any options I can use when mounting the file system that would make this work without the errors?  I have tried turning caching off (-o cache=N) which made the error show up every time I tried to save a file.


text:
Q: Text Size for Different Resolution Density Just Using XML How do we change the textSize based on Resolution density?
I have found several ways on SO, but all of them usng java code to do that.
I however need a java free approach because I have someplaces where I set a textSize on XML and some on Java code.
In xml, I do this
        android:textSize="@dimen/FONT_SIZE_SMALL"

however sometimes I need to set it via java code.
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.FONT_SIZE_SMALL);

Any ideas please?  is it doable?

A: Use textSize in sp unit in xml. It will adjust to all resolutions.
Hope this helps.
UPDATE
Please also refer to Text size with different resolution which proposes some scaling factors for different resolutions.

A: You can declare sizes with the <dimen> tag in dimens.xml in resolution specific values folder.
eg
<dimen name="my_text_view_size">12sp</dimen>

You can have multiple value files for different resolutions and can assign different values for the same constant for each resolution. then assign the constant to textsize.
check this for more details
https://stackoverflow.com/a/16910589/3329488


text:
Q: Using permalinks with parameters I am trying to make a custom web app with wordpress. I have a page, Person with URL http://www.domainname.com/person. In that page, i have a shortcode. This shortcode is going to extract a get parameter from the URL such as http://www.domainname.com/person?id=5. The problem is that when clicking on URL like http://www.domainname.com/person?id=5, wordpress is complaining that the page does exist when the page http://www.domainname.com/person exist. How can I solve this ?

A: id is already used by WordPress, it's a query variable and a reserved name. If you put ?id=5 on the end of a URL, you're asking for the post with ID 5.
Instead, have you considered using a person post type? This would give you an archive, add/edit screen, admin listings, templates, individual person templates, URL paths, etc all for free No need to create a page and a page template, just use single-person.php and archive-person.php


text:
Q: Why are the storm troopers in The Force Awakens not the original clones? In the new Star Wars movie there is a black stormtrooper, but I thought that all stormtroopers were clones. I have tried to look this up but with no success.
Why are clones no longer used as stormtroopers?

A: You're confusing Clonetroopers and Stormtroopers.
Clonetroopers were used by the Republic during the Clone Wars, and were all genetic clones of Jango Fett.
The Empire used Stormtroopers, which were made up, at least in part, of non-clones. This is explicitly shown during the show Star Wars: Rebels, where we see recruits working towards becoming Stormtroopers.
See also:

*

*Why Did the Empire Discontinue the Clone Trooper Program?

*Are the Empire (or First Order) not using clones any more? If not, why?

A: In Star Wars Rebels Season 2, the initial encounter with Captain Rex had him remarking that the Emperor had retired the clones. Stormtroopers are now fully birth-born recruits. 13 years would have passed before the first batch of clones was commanded to execute Order 66, another 19 years before the Battle of Yavin, 3 years from then to the Battle of Endor and then 30 years to The Force Awakens. Considering accelerated ageing, the first batch of clones would be 130 years old by then. The Fett clones would all be dead.
As for the reason why clones aren't used anymore? They are expensive. And the original clones weren't willing executors of Order 66 - they are loyal to the Jedi and the Republic but inhibitor chips overrode their natural loyalties. They were then released (Kanan mentioned clones later telling him they had chips in them, that they had no choice. This indicates he encountered clones who snapped out of it and are no longer willing to go on a Jedi killing spree) from control and are clearly traumatic and unhappy over what they were tricked into doing. Not a good idea to keep these kind of guys around to rule your new Empire.
By the time of The Force Awakens, the First Order has access to less resources than before. Cloning had indeed been considered as an option for how to raise a new army of stormtroopers, but ultimately the decision was made to kidnap babies and raise them in a brainwashed environment instead. Not using clones was a conscious decision of the First Order.


text:
Q: Array assignment Snake Working in a business environment, I don't really get to code or use the good old console anymore. My work is repetitive and thus not really challenging.
I decided to challenge myself by writing a snake game in a C# console; and boy did it make my brain work. I never have to think this hard on a day-to-day basis, but I felt like my programming skills weren't getting any better.
I have a problem though. The basic approach I took was to create a snake class and a food class. The snake class uses an array to store all coordinates and then a drawing class decides what coords to draw on-screen.
The problem is that as you move the snake, the array fills up (maxsize is 250 for performance), so when I reach the end of the array I want to copy the last few coords to a temp array, flush the original array and copy the temp coords back to the main array.
The problem I have is copying x coords back to the original array. I decided to do it manually to test but this solution always makes my poor snake leave behind one of its segments on the screen when it shouldn't be there.
How would I go about doing this programmatically?
spoints[4, 0] = stemp[249, 0];
spoints[4, 1] = stemp[249, 1];
spoints[4, 2] = stemp[249, 2];

spoints[3, 0] = stemp[248, 0];
spoints[3, 1] = stemp[248, 1];
spoints[3, 2] = stemp[248, 2];

spoints[2, 0] = stemp[247, 0];
spoints[2, 1] = stemp[247, 1];
spoints[2, 2] = stemp[247, 2];

spoints[1, 0] = stemp[246, 0];
spoints[1, 1] = stemp[246, 1];
spoints[1, 2] = stemp[246, 2];

spoints[0, 0] = stemp[245, 0];
spoints[0, 1] = stemp[245, 1];
spoints[0, 2] = stemp[245, 2];

I really don't mind posting the whole game here if someone really wants to dig into the code.

A: It sounds like an array is the wrong data type for your purposes. Consider using a List instead, since it allows for more flexibility when moving entries around.

A: Have you thought about as you add a new coordinate to the 'front' of the array, removing the one at the 'back' as you go.  So basically, a sort of FIFO type collection?!  You could use a Queue in C#.  Have a look at this article and see if it helps any?!  http://www.dotnetperls.com/queue.
Cheers,
Chris.

A: Consider using an array for 'general points' not drawing points, create another class called something like SnakePart so your Snake class has manageable parts.
You could also create a custom array class so in each part of the grid you would only have a value hasSnakePart and manipulate that.


text:
Q: Pygame Rect center can't overwrite Rect's left In the code below I add a center and before it a top and a left attribute to the self.rect (this is only for learning and understanding pygame behavior). When I add the top attribute it seems that the top will be overwritten by the center, but having a left before center comes changes the x position of the block. Can any one explain why the left doesn't get overwritten by center?
import pygame
pygame.init()

screen=pygame.display.set_mode((500,500))

class Block(pygame.sprite.Sprite):

    def __init__(self):
        super(Block, self).__init__()
        self.image=pygame.Surface((50,50))
        self.image.fill((0,0,200))
        self.rect=self.image.get_rect(top=400,center=(0,0))
        #this will obviously be overwritten by center, but not the following, why?
        #self.rect=self.image.get_rect(left=400,center=(0,0))

b=Block()
blockGrp=pygame.sprite.Group()
blockGrp.add(b)
print blockGrp

while 1:
    pygame.time.wait(50)
    for e in pygame.event.get():
        if e.type==pygame.QUIT:
            pygame.quit()

    blockGrp.draw(screen)

    pygame.display.flip()

A: The keywords you use when you call the get_rect function are, in the end, passed as a dict to the function.
The Rect class* then iterates over this dict and calls the appropriate setter function.
Now note that the order of the items in the dict is not the same order you used when creating that dict.
For example, try running the following code in your python interpreter:
>>> {"top": 400, "center": (0, 0)}
{'top': 400, 'center': (0, 0)}
>>> {"left": 400, "center": (0, 0)}
{'center': (0, 0), 'left': 400}
>>>

As you can see, when you use ...get_rect(left=400,center=(0,0)), a dict like {'center': (0, 0), 'left': 400} is created (this is an implementation detail that may change depending on the python interpreter you use).
So, first center will be set, then left will be set.
Now if you use ...get_rect(top=400,center=(0,0)), a dict like {'top': 400, 'center': (0, 0)} will be generated, and top will be set first, then center will be set.
For more information about how dict works internally, look at this great answer.

That being said, if you want to set multiple attributes that collide with each other, (like top and center e.g.), you should call the setter manually, e.g.
self.rect = self.image.get_rect(center=(0,0))
self.rect.top = 400

* it's not really a Rect class, since it's implemented in C, so it's a C function that does the work in the end.


text:
Q: CDK AppSync DynamoDB Resolver Query with Expression and Expression Values I am frustrated that there is nothing in the documentation about how to achieve this. In Cloudformation I can do the following:
rExampleResolver:
  Type: "AWS::AppSync::Resolver"
  Properties:
    ApiId: !GetAtt rGraphQLApi.ApiId
    TypeName: "Items"
    FieldName: "getItems"
    DataSourceName: !GetAtt rTableDataSource.Name
    RequestMappingTemplate: |
      {
        "version" : "2017-02-28",
        "operation" : "Query",
        "query" : {
            "expression": "itemId = :itemId",
            "expressionValues" : {
                ":conversationId" : {
                    "S" : "${context.source.itemId}"
                }
            }
        },
        "index": "itemId-index"
      }
    ResponseMappingTemplate: |
      $util.toJson($context.result.items)

I'm trying to do the exact same thing in CDK V2 with the following code:
const resolver = tableDataSource.createResolver({
  typeName: 'Query',
  fieldName: 'getItems',
  requestMappingTemplate: appsync.MappingTemplate.dynamoDbQuery(
        KeyCondition.eq('itemId', ':itemId'),
        'itemId-index',
  ),
  responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(),
});

Where am I supposed to provide the expressionValues?


text:
Q: Geolocation country and city? I'm trying to to use someone's example code to get the country and city, but...something seems to be wrong. Meaning, no error, but also no alerts() pop up. It must be something really simple, but...so far I haven't managed to figure it out. See http://triparound.org/temptest.php
Thanks!

A: Ah, really weird, simple thing, type="text/javascript" instead of type="javascript" was required.


text:
Q: Unable to obtain Proper Stack Trace after running the dump file with WinDbg We are having exception thrown on Production that causes the w3wp process to crash. To figure out the faulted code, we configured the Debug Diag that is creating dump file when exception occur. Then we are trying to run the dump file with WinDbg to obtain the Stack Trace to figure out the faulted code but this is what we are experiencing after opening the dump file and running the required commands.

As you can see in the image above, it's not giving the stack trace after running the commands, I'm not sure what I'm missing
UPDATE
After running a command twice as suggested in the comments, I'm able to get the stack trace. But seems like there is no faulted code pointed out in the stack instead there is a long list of underlying framework in the stack. Below is the snapshot for the start of stack. Not sure how to identify the error. Any suggestion or I may need to open separate Question for this?


text:
Q: When boiling water, why does the water level decrease? When boiling water, the level of water decreases and will disappear after a while. I guess this has something to do with the condensation of water vapour into the visible white "steam" or "cloud". What is above the "cloud"? Does the water molecules just escape? I thought they would go back to liquid water through condensation? I'm confused.

A: when you boil water, you convert it into water vapor, which leaves the pot and mixes with the atmosphere. If you boil the pot long enough, eventually all the water in it is converted to vapor and leaves. the pot is then empty.


text:
Q: ios - can't embed a screen inside a scrollview (my first attempt) I am using a storyboard, and I have one screen where all the elements do not fit into the 3.5 inch screen.
What I am trying to do is put the screen that I want to use in focus, go to Editor --> EmbedIn --> But the scroll-view option is disabled.
Is there something that I am not doing correctly? What is the correct way to make my screen scrollable?
Thanks!

A: Command + Click on the objects you want embedded in the scroll view, then do a Editor -> Embed In -> Scroll view and it should be enabled.  My guess is you have the highest level view selected (or nothing at all selected), which you can't do because that view needs to stay on top.


text:
Q: Drupal: How to remove login to make site passwordless for users? I want to remove the login page from a Drupal site so that the site is open and public-facing.  Only the admin would need to login.  Does anyone know how this can be accomplished?

A: You can't remove the login page, because the administrators will need one to login.
You could, however, give anonymous users access to whatever you like. So that you don't have to be logged in the use any feature of the site. If users are to create content or do other stuff, you will need for them to login, so that you can tell them apart.
Edit
To configure the access control, you'll have to go to admin/user/permissions, where you can select which permissions anonymous users (and other user roles) should have.

A: I looked through permissions, but nothing helped me to make the main site page available instead of the login page.
Open Features (site.org/features), change Site settings -> Site work mode from Only private access to Open access (moderated registration) (sorry, the names were translated back from Russian).
This has solved my problem. I made private access to the site before and forgot about that. I wanted to disable new users registration (because of mass spam). This can be done through admin/user/settings -> Only site administrators can create new user accounts. [I use Drupal 6, but Drupal 7 works same with this setting]. [UPDATE: it seems, at least for my somewhat outdated setup, that these two Drupal options contradict each other, when I allow only administrators to add users, the private mode turns on automatically :( ]

A: Drupal 7
You do not need to remove the login page to make the site open and public facing. Any browser to your site would be given an anonymous user role by default. So any content that is visible to the anonymous role (which can be altered by going to admin/user/permissions) and published can be seen. As long as your website is not in maintenance mode.
If your looking to move the login block that is on the front page of most new Drupal installations you'll have to go to admin/structure/blocks and change the setting there.


text:
Q: U-SQL extract a column based on its ordinal position I'm experimenting with Azure Data Lake, and trying to consume a bunch of data files.
The files are CSVs.  The folder structure looks like:
/jobhistory/(AccountId)/(JobId)/*.csv

In the CSV files, the 6th column is the username.
What I'd like to do is extract out the account id, the job id, and the username (then, in the interests of experimentation, do some aggregates on this data).
Following an online tutorial, I wrote something like this:
DECLARE @file_set_path = "/jobhistory/{AccountId}/{JobId}/{FileName}.csv";

@metadata =
    EXTRACT AccountId int,
            JobId string,
            FileName string,
            UserName string
    FROM @file_set_path
    USING Extractors.Csv();

Now, the problem (I think) I have is that the UserName field is the 6th column in the csv files, but there are no header rows in the files.
How would I assign UserName to the 6th column in the files?
Also, please let me know if I'm totally going down a wrong path here; this is very different from what I'm used to.

A: The built-in CSV extractor is a positional extractor. That means you have to specify all columns (even those you are not interested in) in the extract schema.
So you would write something like (assuming username is the 6th col and you have 10 cols):
DECLARE @file_set_path = "/jobhistory/{AccountId}/{JobId}/{FileName}.csv";

@metadata =
  EXTRACT AccountId int,
          JobId string,
          FileName string,
          c1 string, c2 string, c3 string, c4 string, c5 string,
          UserName string,
          c7 string, c8 string, c9 string
  FROM @file_set_path
  USING Extractors.Csv();

@metadata =
  SELECT AccountId,
          JobId,
          FileName,
          UserName
  FROM @metadata;

Note that the SELECT projection will be pushed into the EXTRACT so it will not do the full column processing for the columns that you do not select.
If you know that the 6th column is the column you are interested in, you could also write a custom extractor to skip the other columns. However the trade-off of running a custom extractor compared to a built-in one may not be worth it.
(Also note that you can use the ADL Tooling to create the EXTRACT expression (without the virtual columns), so you do not need to do it by hand:
https://github.com/Azure/AzureDataLake/blob/master/docs/Release_Notes/2017/2017_Summer/USQL_Release_Notes_2017_Summer.md#adl-tools-for-visualstudio-now-helps-you-generate-the-u-sql-extract-statement


text:
Q: How can I get the stream I processed in cv2 into the tkinter window? I have a frame that pops up from a raspberry pi broadcasting its signal over the network. The camera feed opens and runs fine in the frame I have opening with cv2 in line 37. However, I am trying to show the camera feed in tkinter as you can see by line 42 and on.
To summarize in short: I need to display the camera feed in tkinter.
Any help is greatly appreciated.
import io
import socket
import struct
import cv2
import numpy as np
from PIL import Image
import tkinter as tk
global image
# Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means
# all interfaces)
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 5001))
server_socket.listen(0)

# Accept a single connection and make a file-like object out of it
connection = server_socket.accept()[0].makefile('rb')

while True:
        # Read the length of the image as a 32-bit unsigned int. If the
        # length is zero, quit the loop
        image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
        if not image_len:
            break
        # Construct a stream to hold the image data and read the image
        # data from the connection
        global image
        image_stream = io.BytesIO()
        image_stream.write(connection.read(image_len))
        # Rewind the stream, open it as an image with opencv and do some
        # processing on it
        image_stream.seek(0)
        image = Image.open(image_stream)

        data = np.frombuffer(image_stream.getvalue(), dtype=np.uint8)
        imagedisp = cv2.imdecode(data, 1)

        cv2.imshow("Frame",imagedisp)
        cv2.waitKey(1)  #imshow will not output an image if you do not use waitKey
         #cleanup windows

root = tk.Tk()

image = Image.fromarray(image)
photo = ImageTk.PhotoImage(image2)  # it has to be after `tk.Tk()`

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(side='left', fill='both', expand=True)

canvas.create_image((0,0), image2=photo, anchor='nw')

description = tk.Label(root, text="Place for description")
description.pack(side='right')

# - start -

update_frame() # update it first time

root.mainloop() # start program - this loop runs all time

a few changes have been made from what I understand of @TheLizzard. It still does not pull up the page. These are the changes:
from tkinter import *
from PIL import ImageTk, Image
import cv2

import io
import socket
import struct
import numpy as np

# Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means
# all interfaces)
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 5001))
server_socket.listen(0)

# Accept a single connection and make a file-like object out of it
connection = server_socket.accept()[0].makefile('rb')
try:
    while True:
            # Read the length of the image as a 32-bit unsigned int. If the
            # length is zero, quit the loop
            image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
            if not image_len:
                break
            # Construct a stream to hold the image data and read the image
            # data from the connection
            image_stream = io.BytesIO()
            image_stream.write(connection.read(image_len))
            # Rewind the stream, open it as an image with opencv and do some
            # processing on it
            image_stream.seek(0)
            image = Image.open(image_stream)

            data = np.fromstring(image_stream.getvalue(), dtype=np.uint8)
            imagedisp = cv2.imdecode(data, 1)

             #cleanup windows
finally:
    connection.close()
    server_socket.close()

root = Tk()
# Create a frame
app = Frame(root, bg="white")
app.grid()
# Create a label in the frame
lmain = Label(app)
lmain.grid()

# Capture from camera
cap = cv2.VideoCapture(0)

# function for video streaming
def video_stream():
    _, frame = cap.read()
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(1, video_stream)

video_stream()
root.mainloop()

Client Side:
import io
import socket
import struct
import time
import picamera

# Connect a client socket to my_server:8000 (change my_server to the
# hostname of your server)
client_socket = socket.socket()
client_socket.connect(('192.168.1.000', 5001))

# Make a file-like object out of the connection
connection = client_socket.makefile('wb')
try:
    with picamera.PiCamera() as camera:
        camera.resolution = (320, 240)
        # Start a preview and let the camera warm up for 2 seconds
        camera.start_preview()
        time.sleep(1)

        # Note the start time and construct a stream to hold image data
        # temporarily (we could write it directly to connection but in this
        # case we want to find out the size of each capture first to keep
        # our protocol simple)
        start = time.time()
        stream = io.BytesIO()
        for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True):
            # Write the length of the capture to the stream and flush to
            # ensure it actually gets sent
            connection.write(struct.pack('<L', stream.tell()))
            connection.flush()

            # Rewind the stream and send the image data over the wire
            stream.seek(0)
            connection.write(stream.read())

            # Reset the stream for the next capture
            stream.seek(0)
            stream.truncate()
    # Write a length of zero to the stream to signal we're done
    connection.write(struct.pack('<L', 0))
finally:
    connection.close()
    client_socket.close()

A: This is example which start socket server in thread and next display tkinter.
At start tkinter display empty image and every 100ms replaces it with current image (which still is empty).
When client connects then server replace image so automatically tkinter display it in window.
When client disconnects then server again put empty image.
Window has `Button to save current screen in file - it shows that window doesn't freeze.
When you close window then it stops server. Problem is that accept() is blocking thread and I use daemon=True to kill thread when program stop running.
import io
import socket
import struct
import tkinter as tk
from PIL import Image, ImageTk
#import cv2
#import numpy as np
import threading
import datetime  # screenshot filename

def server():
    global image
    global server_socket

    print('Start Server')

    # Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means
    # all interfaces)
    server_socket = socket.socket()
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # solution for '[Error 89] Address already in use'. Use before bind()
    server_socket.bind(('0.0.0.0', 5001))
    server_socket.listen(0)

    while server_running:
        print('Waiting for client')
        # Accept a single connection and make a file-like object out of it
        conn, addr = server_socket.accept()
        connection = conn.makefile('rb')
        print('Connected:', addr)

        while client_running:  # to stop it from TK
                # Read the length of the image as a 32-bit unsigned int. If the
                # length is zero, quit the loop
                image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
                if not image_len:
                    break

                # Construct a stream to hold the image data and read the image
                # data from the connection

                image_stream = io.BytesIO()
                image_stream.write(connection.read(image_len))
                # Rewind the stream, open it as an image with opencv and do some
                # processing on it
                image_stream.seek(0)
                image = Image.open(image_stream)

                #data = np.frombuffer(image_stream.getvalue(), dtype=np.uint8)
                #imagedisp = cv2.imdecode(data, 1)

                #cv2.imshow("Frame",imagedisp)
                #cv2.waitKey(1)  #imshow will not output an image if you do not use waitKey
                #cleanup windows

        image = empty_image.copy()
        connection.close()
        conn.close()
        print('Disconnected')

# ---

def update_frame():
    # replace image on Canvas
    global photo

    photo = ImageTk.PhotoImage(image)
    canvas.itemconfig(photo_id, image=photo)

    root.after(100, update_frame)  # repeate after 100ms

def screenshot():
    filename = datetime.datetime.now().strftime('%Y.%m.%d-%H.%M.%S.jpg')
    image.save(filename)
    print('Saved:', filename)

# ---

client_running = True
server_running = True

# empty image to set at start and when client disconnets
empty_image = Image.new('RGB', (320, 240))

# empty image at start
image = empty_image.copy()

t = threading.Thread(target=server)
t.daemon = True  # use daemon to stop thread when accept() wait for client
t.start()

print('Start GUI')
root = tk.Tk()

# create empty object on canvas
photo = ImageTk.PhotoImage(image)

canvas = tk.Canvas(root, width=photo.width(), height=photo.height())
canvas.pack(fill='both', expand=True)

# set object and get ID to update it later
photo_id = canvas.create_image((0,0), image=photo, anchor='nw')

button = tk.Button(root, text='Exit', command=root.destroy)
button.pack()

button = tk.Button(root, text='Screenshot', command=screenshot)
button.pack()

# - start -

update_frame() # update it first time

root.mainloop() # start program - this loop runs all time
print('Stop GUI')

# - end -

# stop loops in thread (and stop server)
client_running = False
server_running = False

print('Stop Server')
server_socket.close()

# don't wait - accept() is blocking thread - use daemon
#t.join()


text:
Q: OS X - How can I share a folder with Windows users (SMB) without sharing my entire user directory? I'd like to be able to just have the single shared folder appear in Windows explorer, but somehow the folder + my users home folder (which essentially allows you into the whole machine) is visible.

A: In System Preferences -> Sharing -> File Sharing, choose the folder that you want to share. In that list, there should not be an entire users folder. In Windows, connect to your computer as a Guest, which will allow you to see what is publicly available. Do not log in with your username. If you connect with your username, you will see your entire home folder.


text:
Q: Can one manufacturer's uefi updater/flasher (.exe) be used for other manufacturers' devices? https://www.reddit.com/r/SteamDeck/comments/tyuu84/comment/i3vfve2/
According to this comment, it is okay to "grab a Lenovo uefi update pack" and extract the .exe uefi flasher from it, then use the said .exe flasher to flash firmware for the steam deck.
Any problems if doing something like this?

A: Sometimes, at your own risk.
Most hardware manufacturers don't build their own UEFIs, but license them from companies specialized in creating UEFIs and customize them for a particular product. Different hardware based on the same UEFI platform will likely share the flashing software.
In this particular case it seems that both Steam Deck and some Lenovo hardware are based on Insyde H2O UEFI.
By following this procedure you're taking the responsibility for any problems. They won't be covered by the warranty.
UEFIs themselves aren't interchangeable, with very rare exceptions, and even then patches will be required.


text:
Q: Redshift: error: Maximum column length exceeds 255 code This error is incurred by the following row in create table sentence.
movie_title VARCHAR encode text255,

the default VARCHAR length in Redshift is 256, and 256>255, so

Unable to execute this query or statement
ERROR: ----------------------------------------------- error: Maximum
  column length exceeds 255 code: 8001 context: Limit is due to use of
  text255 encoding query: 0 location: column.cpp:167 process: padbmaster
  [pid=9637] -----------------------------------------------

The error goes away if I change text255 to text32k,
But as far as I have understood, the text255 compression does not work in this way.

It use one byte (255) to dictionary encode the text in columns, any
  words that are not represented in the dictionary are stored
  uncompressed

reference: http://docs.aws.amazon.com/redshift/latest/dg/c_Text255_encoding.html
shouldn't cause this problem. How can I explain this error ?

A: Looks like there is another limitation which each word size for compression must be less than 255 bytes. The column size to apply text255 might be restricted in connection with this.
Actually I can set text255 encoding to varchar(255), like movie_title VARCHAR(255) encode text255.


text:
Q: jPane Scroll on two divs - Problems I am having problems adding jpanel in my web.
I have two divs with the same class, where  I want to add the scroll, but in the first visit to the web, it shows only 1 div with scroll.
When I refresh the web, it shows both. (Except in Chrome, where it never shows)
All needed libraries are added, and divs have the class tag.
Here comes the code:
$(function()
{
    $('.scrollCh').jScrollPane();
});

Thank you.

A: Well that is very strange, but did you try to add the reinitialize option? like
    var settings = {
      autoReinitialise: true
    };

    $('.scrollCh').jScrollPane(settings);


text:
Q: Dynamically load information to Twitter Bootstrap modal Problem:
I would like to transfer by using jQuery a value in an link-attribute to PHP/SQL query.
HTML code:
HTML

PHP code:

      <button class="close" data-dismiss="modal">×</button>

Title

        <?php
            $query = "SELECT * FROM table WHERE id = ID FROM JQUERY HERE";
            $result = mysql_query($query) or die ('Error (' . mysql_errno() . ') ' . mysql_error());
        ?>

      Close

Scenario:
When the user clicks the link-element that has data-toggle="modal" then jQuery should take the value of the id-attribute (which is 1 in this case) and send it to the SQL-query so that the SQL query would look like:
$query = "SELECT * FROM table WHERE id = 1";

jQuery code:
$("a[data-toggle=modal]").click(function(){
    var essay_id = $(this).attr('id');
    //Find $essay set it to essay_id in PHP
    //Alternatively create a $_SESSION['EID'] here
});

Question:
How do I use jQuery to set a variable ($essay) in PHP? or how can I create a session variable in PHP through jQuery?

A: Final solution
HTML code:

      <button class="close" data-dismiss="modal">×</button>

Title

      Close

jQuery code:
$("a[data-toggle=modal]").click(function()
{
    var essay_id = $(this).attr('id');

    $.ajax({
        cache: false,
        type: 'POST',
        url: 'backend.php',
        data: 'EID='+essay_id,
        success: function(data)
        {
            $('#myModal').show();
            $('#modalContent').show().html(data);
        }
    });
});

A: here is the solution ,
click

use a div on your modal body , like this

                    // here you can show your output dynamically

now put data into the .something with ajax calling .please check http://api.jquery.com/jQuery.ajax/ to know more about jquery ajax.
   $(function(){

   $('.push').click(function(){
      var essay_id = $(this).attr('id');

       $.ajax({
          type : 'post',
           url : 'your_url.php', // in here you should put your query
          data :  'post_id='+ essay_id, // here you pass your id via ajax .
                     // in php you should use $_POST['post_id'] to get this value
       success : function(r)
           {
              // now you can show output in your modal
              $('#mymodal').show();  // put your modal id
             $('.something').show().html(r);
           }
    });

});

   });

A: *

*Get ID with jQuery

*Pass it to some script via AJAX

*Get your results back and do with them what you please

http://api.jquery.com/jQuery.ajax/


text:
Q: CodeIgniter "status":false,"error":"Unknown method" I'm trying to create a REST service with codeigniter. I have installed RestController.
In my controller (Person):
    public function createUser(){
                $user = array(
                'fiscalcode' => $this->input->post('fiscalcode'),
                'name' => $this->input->post('name'),
                'surname' => $this->input->post('surname'),
                'email' => $this->input->post('email'));
                $data = $this->person_model->post_user($user);
                $this->response($data);
    }

While in my model (Person_model)
public function post_user($user){
            $this->fiscalcode = $user['fiscalcode'];
            $this->name = $user['name'];
            $this->surname = $user['surname'];
            $this->email = $user['email'];
if($this->db->insert('Persons', $this)){
                return 'Utente registrato';
            }
}

I have tried to use Postman to try if the insert works, I pass values in the body  form-data and I receive this error:

{"status":false,"error":"Unknown method"}

In postman I have done a post to index.php/Person/createUser
Can you explain where is the error?

A: In codeigniter REST controller there is a naming convention when creating get or post methods. Use _post post-fix with method name for post and _get for get method, and use $this->post('keyname') to get the post data.
POST Method
public function createUser_post(){
            $user = array(
            'fiscalcode' => $this->post('fiscalcode'),
            'name' => $this->post('name'),
            'surname' => $this->post('surname'),
            'email' => $this->post('email'));
            $data = $this->person_model->post_user($user);
            $this->response($data, 200);
}

A: Use
public function post_user($user){
    if($this->db->insert('Persons', $user)) {
           return 'Utente registrato';
    }
}

Instead of
public function post_user($user){
            $this->fiscalcode = $user['fiscalcode'];
            $this->name = $user['name'];
            $this->surname = $user['surname'];
            $this->email = $user['email'];
if($this->db->insert('Persons', $this)){
                return 'Utente registrato';
            }
}

$this->db->insert('Persons', $this), $this variable not only contain fiscalcode,name,email. but its also contain the method, and its not an array


text:
Q: How to solve "A RenderFlex overflowed by 19 pixels on the right."? I have a page as below, and I got error A RenderFlex overflowed by 19 pixels on the right., I tried to add Expanded or SixedBox before Row or Column, but same result, what I can do? then I want know how can I show three dot in this case when text overflowed?
Widget build(BuildContext context) {
  return Scaffold(
    body: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      child: ListView(
        children: [
          ListTile(
             Row(
              children: [
                Padding(padding: const EdgeInsets.only(right: 10.0), child: Column()),
                Column(),
              ],
            ),
          ),
        ],
      ),
    ),
  );
}

A: I found the result what I wondered as below:
Widget build(BuildContext context) {
  return Scaffold(
    body: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10.0),
      child: ListView(
        children: [
          ListTile(
             Row(
              children: [
                Padding(padding: const EdgeInsets.only(right: 10.0), child: Column()),
                Expanded(
                 child: Column([
                      Row(Expanded(
                        child: Text()),
                   ),
                 ]),
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  );
}