text:
Q: SQLAlchemy Declarative + relationships across multiple different databases It took me a while, but I figured out how to use SQLAlchemy to model a relationship across two different kinds of databases:
Base = declarative_base()

class Survey(Base):
    __tablename__ = 'SURVEY'

    survey_id = Column("SURVEY_ID", Integer, primary_key=True)
    term_id = Column("TERM_ID", Integer, nullable=False)

    # Because the TERM table is in Oracle, but the SURVEY table is in
    # MySQL, I can't rely on SQLAlchemy's ForeignKey.  Thus,
    # I need to specify the relationship entirely by hand, like so:
    term = relationship("Term",
        primaryjoin="Term.term_id==Survey.term_id",
        foreign_keys=[term_id],
        backref="surveys"
    )

class Term(Base):
    __tablename__ = 'TERM'

    term_id   = Column(Integer, primary_key=True)
    term_name = Column(String(30))
    start_date = Column(Date)
    end_date = Column(Date)

mysql_engine = create_engine(MYSQL)
oracle_engine = create_engine(ORACLE)

Session = scoped_session(sessionmaker(
    binds={
        Term: oracle_engine,
        Survey: mysql_engine
    }
))

if __name__ == "__main__":
    survey = Session.query(Survey).filter_by(survey_id=8).one()
    print survey.term
    print survey.term.surveys

I have to do this because the TERM table is in an Oracle database on which I only have read access, and I'm writing an app that records surveys, taken by students, about that term.
The above works, but it's very fragile when the number of tables climbs up, as the Session needs to specify exactly which mapped classes correspond to which engine.  I would really like to be able to use a different Base to define which tables belong to which engine, instead of binding each table individually.  Like this:
mysql_engine = create_engine(MYSQL)
oracle_engine = create_engine(ORACLE)

MySQLBase = declarative_base(bind=mysql_engine)
OracleBase = declarative_base(bind=oracle_engine)

class Survey(MySQLBase):
    __tablename__ = 'SURVEY'

    survey_id = Column("SURVEY_ID", Integer, primary_key=True)
    term_id = Column("TERM_ID", Integer, nullable=False)

class Term(OracleBase):
    __tablename__ = 'ads_term_v'

    term_id   = Column(Integer, primary_key=True)
    term_name = Column(String(30))
    start_date = Column(Date)
    end_date = Column(Date)

Survey.term = relationship("Term",
    primaryjoin="Term.term_id==Survey.term_id",
    foreign_keys=[Survey.term_id],
    backref="surveys"
)

Session = scoped_session(sessionmaker())

if __name__ == "__main__":
    survey = Session.query(Survey).filter_by(survey_id=8).one()
    print survey.term
    print survey.term.surveys

Unfortunately, this results in the following error when the query runs:
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Survey|SURVEY, expression 'Term.term_id==Survey.term_id' failed to locate a name ("name 'Term' is not defined"). If this is a class name, consider adding this relationship() to the <class '__main__.Survey'> class after both dependent classes have been defined.
even though I did add the relationship() to Survey after Term was defined.
Does anyone have any suggestions?

A: Possibly very late with this reply, but you could have defined the metadata separate from the declarative base and then passed it onto both. ie:
meta = MetaData()
mysql_engine = create_engine(MYSQL)
oracle_engine = create_engine(ORACLE)

MySQLBase = declarative_base(bind=mysql_engine, metadata=meta)
OracleBase = declarative_base(bind=oracle_engine, metadata=meta)

A: You can't. AFAIK there's no single query against two different databases. Also, your Models have to share the same Metadata instance to be used in the same query.
Perhaps you can link the Oracle db to the MySQL db on the DB layer via ODBC, then you'd only talk to MySQL. I have never done this, and I don't know how it works.
You can also query both databases independently and filter and select data on the application layer, whichever is less work.


text:
Q: Nginx Laravel Route as Codeigniter I have a Laravel 5 project, the staffs information can be access from testing.com/staffs, but I want to change the URL to testing.com/test/index.php/staffs, I have tried the Laravel Route group using "test/index.php/", but laravel did not support "dot" in route, How can I do that?
the following is my part of nginx.conf
location / {
        try_files $uri $uri/ /index.php?$args;

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    127.0.0.1:9006;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
        }
    }

A: I think Rickard Smith might Right!! the following are the finally code
location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass    127.0.0.1:9006;
    fastcgi_index index.php;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}

Then you can use Route Group Prefix with "dot" now, Thanks Rickard Smith and shempignon Help!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create multiple environment-specific cdk pipelines from a cdk pipeline? I use trunk-based development to provision aws resources to different environments according to the branches(develop-> dev, release-> prod). Also, I have separated my application code in three different repositories(infra, backend, UI). So I would need multiple pipelines for these deployments to multiple accounts. I am using a cdk-pipeline repository to create these multiple pipelines but having a problem in instantiating these pipelines with empty stacks. A cdk pipeline expects a stage with stacks while calling pipeline.addStage(). How do I include the infra code inside this stage when it exists in a different repository?

A: When using cdk codepipeline you can reference a GitHub repository as the source, an example can be found here: aws_codepipeline_actions


text:
Q: How to keep a groupedby list sorted in Play Framework 2 templates I've got a list of complex objects that I want to display, grouped by one of its attribute in a Play 2 template.
I managed to do it :
@measures.groupBy(_.question.category).map {
    case (category, items) => {
         // Category stuff
         @for(item <- items) {
             // List of items
         }
    }
}

The problem is that the list was sorted in my Java controller, but the keyset of the map that I create is not sorted anymore (I would like to sort the key set using something like _.question.category.order).
Is there a way to have a sorted map on this attribute?
Thanks !

A: What type is measures? Did you try to use a LinkedHashSet? This should keep the elements order in contrast to e.g. a HashSet.


text:
Q: .htaccess not redirecting properly on webhost I have a website http://alburoojschool.org and this is the .htaccess file :
DirectoryIndex home.php index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule home home.php

RewriteRule ^pages/([^\.]+)$ $1.php
RewriteRule ^news-list/([^\.]+)$ news-list.php?id=$1
RewriteRule ^iq-admin/([^\.]+)$ iq-admin/$1.php
RewriteRule ^news/([0-9]+)/([A-Za-z0-9-]+)/?$ latest-news.php?id=$1&post=$2 [NC,L]
RewriteRule ^events-list/([^\.]+)$ events-list.php?id=$1
RewriteRule ^events/([0-9]+)/([A-Za-z0-9-]+)/?$ upcoming-events.php?id=$1&post=$2 [NC,L]

when I click on http://alburoojschool.org/news-list/1, it says it's a redirect loop but works fine on localhost. Please help me.

A: You need to place this line on top of your .htaccess:
Options -MultiViews

Option MultiViews is used by Apache's content negotiation module that runs before mod_rewrite and makes Apache server match extensions of files. So /file can be in URL but it will serve /file.php.

A: I can see a few potential pitfalls but I think this is your main culprit.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule home home.php

You probably want to ensure that home is a complete phrase and redirect relative to the document root like this:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^home/?$ /home.php

With what you've got an URL like /news-list/home will hit that first match and attempt to redirect to /news-list/home.php which, I'm assuming, doesn't exist so it'll attempt to redirect (again) to /news-list/home.php and so on.
You should probably update all your redirects so that they're relative to the docroot.


text:
Q: Better way to check if value is bigger, smaller or equal zero in python I have a function that looks if a value is bigger, smaller or equal zero and depending on the result returns one of three colours. Also if a certain attribute is present it doesn't return one of the three colours but a separate fourth on. I solved it like this:
def set_colour(x, trigger=False):
    if x > 0.0:
        colour = 'green'
    elif x < 0.0:
        colour = 'red'
    else:
        colour = 'black'

    if trigger:
        colour = 'blue'

    return colour

But I don't like it. Is there a better way that is more elegant, efficient and pythonic?
I found this post very interesting but can't use dictionaries since I am not checking for a static value but comparing the value.
Is there a possibility to define a variable for all numbers greater zero to test against in order to use the dictionary solution? Maybe with lambda? I tried some things but didn't get anywhere.
At the moment this solution that I have might be working okay but in future additional colours might be added for values smaller than -1.0, -2.0 or bigger 1.0 or 2.0 etc. and at that point the code will just get longer and longer for something that I feel can be solved more elegantly.
I think I check all relevant posts here so I hope this is not a duplicate.

A: This is the only change I'd make:
def set_colour(x, trigger=False):
    if trigger:
        return 'blue'
    elif x > 0.0:
        return 'green'
    elif x < 0.0:
        return 'red'
    else:
        return 'black'

A: You could use a sign() function and index lookup:
import math
def sign(v):
    return int(math.copysign(1,v))

def set_color(x, trigger=False):
    if trigger: return "blue"
    return ('red', 'black', 'green')[sign(x)+1]

That said, I'm not sure how much "better" this is. "Clever" != "better" in the usual case.
EDIT Alternative which allows you to extend it easily for many color ranges:
colorRanges = (
    # start, color
    (-2, 'red'),
    (0, 'yellow'),
    (1, 'orange'),
)

def set_color(x, trigger=False):
    if trigger: return "blue"
    if x == 0.0: return 'black'

    for start, color in colorRanges:
        if x < start: return color

    return 'green'

This allows you to define color ranges easily but I don't have a good idea to handle the corner cases better.

A: You can use nested conditional expression, like this
def set_colour(x, trigger=False):
    if trigger: return "blue"
    return "green" if x > 0.0 else "red" if x < 0.0 else "black"

assert set_colour(None, True)   == "blue"
assert set_colour(0.0, True)    == "blue"
assert set_colour(0.0, False)   == "black"
assert set_colour(0.01, False)  == "green"
assert set_colour(-0.01, False) == "red"

A: This is quite readable and easy to extend:)
def set_colour(x, trigger=False):
    color = 'black'
    color = 'green' if x > 0.0 else color
    color = 'red' if x < 0.0 else color
    color = 'blue' if trigger else color

    return color

A: You cannot run from the fact that you will need some conditions. However, you can list your conditions in a list, and corresponding colors in another list and then call the conditions. This way, you can separate your conditions form your code somewhat. This is because functions are first class values in Python.
You can do something like this:
conditions =  [
   lambda m: m <  -3,
   lambda m: m >= -3 and m < -2,
   lambda m: m >= -3 and m < -2,
   lambda m: m >= -2 and m <  0,
   lambda m: m ==  0,
   lambda m: m >=  0 and m <  1,
   lambda m: m >= 1 ]

colors = [
   'color1',
   'color2',
   'color3',
   'color4',
   'color5',
   'color6',
   'color7' ]

def colVal(m): return colors[ [c(m) for c in conditions].index(True) ]

Here, colVal(-4) is 'color1', etc ...
This way you can keep appending your conditions list as you wish, and still keep the rest of the code intact. This is an idea with what you can do. However how you want to format your code is up to you. For example, you can do
def set_colour(x, trigger=False):
    if trigger: return 'someColor'
    else: return colVal(x)

Not sure if this is what you want though.


text:
Q: How to get a tree structure ANLTR4 I need to parse config file in form like this
"agent 1"(
"ip"("192.67.4.1"),
"port"("12345"),
"neighbours"(
    "agent 2"(
        "ip"("192.67.4.2"),
        "port"("12345")),
    "agent 3"(
        "ip"("192.67.4.1"),
        "port"("12346"))),
"measurements"(
    "voltage"("4.2V"),
    "power"("7KW")))

What i got so far is grammar(mostly obtained just by trial and error method from few tutorials)
grammar Tree;

compileUnit
    :   group EOF
    ;

group
    :   (node '(' group ')' (',')? )*                # root
    |   node                                         # value
    ;
node
    : STRING                                         # label
    ;

STRING   :   '"'[ a-zA-Z0-9\.]+'"';
WS      :   [ \t\r\n] -> channel(HIDDEN);

and the result of it is tree like this in preview
Tree
I already have functionality to add nodes to my tree in a form(other requirement):

ADD "label 1" "label 2" ... "label n"

So the perfect outcome of parser would be String array like:

*

*"Agent 1" "ip" "192.67.4.1"

*"Agent 1" "port" "12345"

*"Agent 1" "neighbours" "agent 2" "ip" "192.67.4.2"

*"Agent 1" "neighbours" "agent 2" "port" "12345"

*And so on...

But I couldn't get further and implement my parser to obtain such String array. So my question is how to do it? I get that I need to extend something like Parser of BasicListener but couldn't manage this.

A: Solution
First, let's change the named alternative root to:
group
    :   node '(' (group (',')?)+ ')'     # root
    |   node                             # value
    ;

This allows us to track the header (node) of every group. When I refer further to a tree what I mean is config tree structure. Then let's make two definitions:

*

*path - is a string of values collected from tree's root to tree's leaf (e.g. "Agent 1" "neighbours" "agent 2" "ip" "192.67.4.2"),

*partial path - is a path that doesn't end with tree's leaf (an unfinished path, e.g. "Agent 1" "neighbours" "agent 2" "ip").

Now we will write a simple tree listener that will collect paths.
public class TreeToArray extends TreeBaseListener {
    Stack<String> partialPath = new Stack<>();
    public List<String> paths = new ArrayList<>();

    @Override
    public void enterRoot(TreeParser.RootContext ctx) {
        if (partialPath.isEmpty()) {
            // We are in top-root, partial path consists of top-root's name
            partialPath.push(ctx.node().getText());
        } else {
            // We are in one of the sub-roots, partialPath.peek() returns a current partial path
            partialPath.push(partialPath.peek() + " " + ctx.node().getText());
        }
    }

    @Override
    public void enterValue(TreeParser.ValueContext ctx) {
        paths.add(partialPath.peek() + " " + ctx.getText());
    }

    @Override
    public void exitRoot(TreeParser.RootContext ctx) {
        partialPath.pop();
    }
}

The stack partialPath keeps information about currently built partial path. When we visist the main, first root (e.g. "Agent 1") we don't have any partial paths, so we put onto the stack the root's header. Otherwise we retrive a partial path and add to it root's header. When we stumble across value we are at the tree's leaf, we finished the path. We pop() the partial path, then we add to it node value. The result string (the full path) goes into the paths list.


text:
Q: how can I extract values from this dictionary in Python? I have a dictionary like this:
{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}

how can I extract first_name, last_name, id and phone values from this dictionary?

A: Also, assuming your file has new line delimited dictionaries, using below code solved the issue:
import json
fo = open(r"C:\Users\Downloads\test.txt", "r")
for each_line in fo.readlines():
    print(json.loads(json.loads(each_line)['message'])['first_name'])
    print(json.loads(json.loads(each_line)['message'])['last_name'])
    print(json.loads(json.loads(each_line)['message'])['id'])
    print(json.loads(json.loads(each_line)['message'])['phone'])

A: import json

# I have assumed your dictionary like that
data = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}

# The data in "message" need to be loaded on JSON format to access it.
data["message"] = json.loads(data["message"])

# Now, you can print or whatever you want with all the data
print(data["message"]["id"])
print(data["message"]["first_name"])
print(data["message"]["last_name"])
print(data["message"]["phone"])  # There is phone info both in data["message"]["phone"] and data["phone"]. They are identical. You can use whichever you want.

# Optional
# If you want, you can assign data["message"] to a variable.
finalData = data["message"]

# Then you can access the info that you need from finalData
print(finalData["first_name"])

A: You should turn the string into a dictionary using e.g. json.loads. Then extract like from a normal nested dictionary.
Example:
import json
message = mydict["message"]
message_dict = json.loads(message)
message_dict['id']

where mydict is your given input dictionary.
In case your snippet shows the content of a file, you could do the following:
with open(filepath) as file:
    mydict = json.load(file)
message_dict = mydict["message"]
message_dict['id']

A: You can use the below code to extract those values:
import json

str1 = r'{"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}'

print(json.loads(json.loads(str1)['message'])['first_name'])
print(json.loads(json.loads(str1)['message'])['last_name'])
print(json.loads(json.loads(str1)['message'])['id'])
print(json.loads(json.loads(str1)['message'])['phone'])

A: This is another way to do it:
import json

D = {"message":"{\"_\":\"user\",\"pFlags\":{\"contact\":true},\"flags\":2175,\"id\":379951860,\"access_hash\":\"6967195540985199805\",\"first_name\":\"پژوا\",\"last_name\":\"روزبهی\",\"username\":\"mramtd2\",\"phone\":\"989157145632\",\"photo\":{\"_\":\"userProfilePhoto\",\"photo_id\":\"1631880813210609625\",\"photo_small\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476387,\"secret\":\"655623158723369503\"},\"photo_big\":{\"_\":\"fileLocation\",\"dc_id\":4,\"volume_id\":\"448413446\",\"local_id\":476389,\"secret\":\"13993366131879811943\"}},\"status\":{\"_\":\"userStatusOffline\",\"was_online\":1558046876}}","phone":"989157145632","@version":"1","typ":"telegram_contacts","access_hash":"6967195540985199805","id":379951860,"@timestamp":"2020-01-26T13:50:12.793Z","path":"/home/user/mirror_01/users_5d65f610ec18aa615a5f580c.log","username":"mramtd2","type":"redis","flags":2175,"host":"ubuntu","imported_from":"telegram_contacts"}

data = json.loads(D['message'])

for key in ['first_name', 'last_name', 'phone', 'id']:
    print(f'{key} -> {data.get(key, "?")}')


text:
Q: Developing and debugging mem-hogging C# apps I have a C# app that must link with a 32-bit library and also needs to use the maximum amount of memory possible (imaging app); we run the app on XP64 desktops, thus we are using WOW64, targeting builds in Visual Studio for x86 (and doing an editbin /largeaddressaware post-build). We're encountering a few problems:

*

*In the Visual Studio built-in debugger, we can only ever use 2gb of memory (~1.5gb to the app, plus overhead)

*Running from the command line, the app can see 3gb of memory, but Microsoft documents would seem to say we should see 4gb.
Can anyone tell me how to get a WOW64 C# app to see the full 4gb that the platform should be able to give it?
Also, can anyone tell me how to get the Visual Studio (VS 2008, otherwise known as VS90) debugger to obey the /largeaddressaware bit and stop limiting the app memory to 2gb?
I see the same behavior in VS80 and VS90; also no difference between .NET Framework 3.5, 3.0, and 2.0.  Here's a trivial C# program that illustrates the problems; build for x86, editbin /largeaddressaware, then run in built-in debugger versus run from command line to see the difference in memory available to C#.
namespace MemoryAllocTest
{
class Program
{
    static void Main(string[] args)
    {
        const int allocSize = 1024 * 1024;
        List<byte[]> myMem = new List<byte[]>();
        UInt64 totalAlloc = 0;

        while (true)
        {
            myMem.Add(new byte[allocSize]);
            totalAlloc += allocSize;
            Console.WriteLine("{0} allocs: {1}MB total",
             myMem.Count, totalAlloc / (1024 * 1024));
        }
    }
}
}

A:

can anyone tell me how to get the Visual Studio (VS 2008, otherwise known as VS90) debugger to obey the /largeaddressaware bit and stop limiting the app memory to 2gb?

This requires two steps -- both in the project properties:

*

*on the build events tab, setup a postbuild step to run editbin
/largeaware $(TargetPath)

*on the debug tab, un-check the Enable the Visual Studio hosting
process

With these two steps, your sample program was running to 3045MB

A: Thanks to everyone who responded; this site really rocks!
Seems that we really do get to 4gb user space in WOW64, but it seems to me (mildly educated guess) that the garbage collector overhead (or perhaps safety margin) becomes sizeable as the memory allocated by managed code grows.  Running my test app on WOW64 (command line, with LARGEADDRESSAWARE), I get total allocations of 3175MB; running on a WIN32 XP machine with the 4GT parameter set, I get total allocations of 2857MB: so a full gig of additional user-mode memory yields an increase of only ~318MB at the C# app level!
(I have modified my test program to halve the allocation unit size when an allocation fails, and also added calls to strategically force garbage collection in an effort to go a little beyond the limit of what a 'normal' application might be able to grab -- drop a note here if you would like me to post the revised code.)
Anyway, thanks again to everyone; looks like the system is working correctly but the managed environment gets less improvement from the additional gig of memory than may have been expected.

A: From Microsoft:

The virtual address space of processes
  and applications is still limited to 2
  GB unless the /3GB switch is used in
  the Boot.ini file. When the physical
  RAM in the system exceeds 16 GB and
  the /3GB switch is used, the operating
  system will ignore the additional RAM
  until the /3GB switch is removed. This
  is because of the increased size of
  the kernel required to support more
  Page Table Entries. The assumption is
  made that the administrator would
  rather not lose the /3GB functionality
  silently and automatically; therefore,
  this requires the administrator to
  explicitly change this setting.
  The /3GB switch allocates 3 GB of
  virtual address space to an
  application that uses
  IMAGE_FILE_LARGE_ADDRESS_AWARE in the
  process header. This switch allows
  applications to address 1 GB of
  additional virtual address space above
  2 GB.

A: What exact version of .NET are you using? This Connect report is about the same problem (as far as I can tell), seen on .NET 2.0 but fixed in .NET 2.0SP1.
If your x64 machines don't have 2.0SP1 (or later) on, it's worth a try...

A: I built your simple sample app from the post, crashed it and attached WinDbg to it.
!address -summary  will show you the effective user mode address space for the process.
0:003> !address -summary
 TEB fffdd000 in range fffdb000 fffde000
 TEB fffda000 in range fffd8000 fffdb000
 TEB fffd7000 in range fffd5000 fffd8000
 TEB fffaf000 in range fffad000 fffb0000
 ProcessParametrs 004c2b40 in range 004c0000 00535000
 Environment 004c1978 in range 004c0000 00535000

-------------------- Usage SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots) Pct(Busy)   Usage
   e7d2e000 ( 3798200) : 90.56%    98.77%    : RegionUsageIsVAD
   1547b000 (  348652) : 08.31%    00.00%    : RegionUsageFree
    2887000 (   41500) : 00.99%    01.08%    : RegionUsageImage
     3ff000 (    4092) : 00.10%    00.11%    : RegionUsageStack
          0 (       0) : 00.00%    00.00%    : RegionUsageTeb
     1c0000 (    1792) : 00.04%    00.05%    : RegionUsageHeap
          0 (       0) : 00.00%    00.00%    : RegionUsagePageHeap
       1000 (       4) : 00.00%    00.00%    : RegionUsagePeb
          0 (       0) : 00.00%    00.00%    : RegionUsageProcessParametrs
          0 (       0) : 00.00%    00.00%    : RegionUsageEnvironmentBlock
       **Tot: ffff0000 (4194240 KB)** Busy: eab75000 (3845588 KB)

-------------------- Type SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots)  Usage
   1547b000 (  348652) : 08.31%   : <free>
    2aa3000 (   43660) : 01.04%   : MEM_IMAGE
    1f6a000 (   32168) : 00.77%   : MEM_MAPPED
   e6168000 ( 3769760) : 89.88%   : MEM_PRIVATE

-------------------- State SUMMARY --------------------------
    TotSize (      KB)   Pct(Tots)  Usage
   db838000 ( 3596512) : 85.75%   : MEM_COMMIT
   1547b000 (  348652) : 08.31%   : MEM_FREE
    f33d000 (  249076) : 05.94%   : MEM_RESERVE

Largest free region: Base fbfc0000 - Size 03fed000 (65460 KB)

Based on Tot: ffff0000 (4194240 KB) we do have 4GB of effective user mode space.
Also our largest free block is 65,460KB which does imply that we should be able to allocate more memory.

A: Can you post where it implies that you can see all 4 GB?  Ooh, maybe here:
Interesting info at this link

Differences in Addressable Memory
The first thing most developers notice
  is that 64-bit processors provide a
  huge leap in the amount of physical
  and virtual memory that can be
  addressed.
* 32-bit applications on 32-bit platforms can address up to 2 GB
* 32-bit applications built with the /LARGEADDRESSAWARE:YES linker flag

on 32-bit Windows XP or Windows Server
  2003 with the special /3gb boot option
  can address up to 3 GB. This
  constrains the kernel to only 1 GB
  which may cause some drivers and/or
  services to fail.
* 32-bit applications built with the /LARGEADDRESSAWARE:YES linker flag

on 32-bit versions of Windows Vista,
  and on 32-bit versions of Windows
  Server Code Name "Longhorn" operating
  systems, can address memory up to the
  number specified by the boot
  configuration data (BCD) element
  IncreaseUserVa. IncreaseUserVa can
  have a value ranging from 2048, the
  default, to 3072 (which matches the
  amount of memory configured by the
  /3gb boot option on Windows XP). The
  remainder of 4 GB is allocated to the
  kernel and can result in failing
  driver and service configurations.
For more information about BCD, see Boot Configuration Data on MSDN.
* 32-bit applications on 64-bit platforms can address up to 2 GB, or up

to 4 GB with the /LARGEADDRESSAWARE:YES linker flag.
      * 64-bit applications use 43 bits for addressing, which provides 8 TB of
  virtual address for applications and 8
  TB reserved for the kernel.

So yes, it appears you should (on an XP64 target) be able to see 4 GB.


text:
Q: Android ImageViews upon eacht other / fade in fade out I've got two ImageViews and I try to fade out one and fade in another.
The Problem is they should "lay" upon each other.
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="124dp"
android:layout_height="94dp"
android:src="@drawable/dgreen"
android:visibility="visible" />

<ImageView
android:id="@+id/imageView"
android:layout_width="124dp"
android:layout_height="94dp"
android:src="@drawable/blank" />
</RelativeLayout>

Animation animation = AnimationUtils.loadAnimation(this.getApplicationContext(),R.anim.fade_out );
animation.setFillAfter(true);
Animation animation1 = AnimationUtils.loadAnimation(this.getApplicationContext(),R.anim.fade_in );
animation1.setFillAfter(true);
iV.startAnimation(animation);

iV1.startAnimation(animation1);

But the picture below the first imageview does not "glow" through.
Edit:
Here is my Fade in/out code:
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="1000" />

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.1" android:toAlpha="1.0"
android:duration="1000" />

I use alpha transformation.

A: You could use a Framelayout and play with gravity like here and apply a Animation like here


text:
Q: How can I create a queryable alias for a foreign-key field in a Django model? I have a series of models that have fields to be migrated to a FK.
Before
class Sizing(models.Model:
    btu_hour = models.IntegerField()
    flange = models.ForeignKey('parts.Router')

After
class Sizing(models.Model):
    btu_hour = models.IntegerField()
    configuration = models.ForeignKey(Configuration)
    ### WHAT I'D LIKE; alias only ###
    flange = Alias(to='configuration__flange')

class Configuration(models.Model)
    flange = models.ForeignKey('parts.Router')

Assuming I have queries in my views that do lookups on the flange field, how can I create an alias? I have many models that are being restructured in the manner above and would like to use this method so that I don't have to replace every use of that field in views, etc.
Would appreciate any pointers; all info on model aliases I've found only work for same-model fields.

A: The easiest solution would be to create a @property:
class Sizing(models.Model):
    btu_hour = models.IntegerField()
    configuration = models.ForeignKey(Configuration)

    # define the property flange
    @property
    def flange(self):
        return self.configuration.flange

Then, in any of the views if you have a sizing_obj.flange it won't be affected at all.
However, you cannot use it in queryset or filters etc.

A: aliasName = models.ForeignKey(modelName, to_field='fieldName', on_delete=models.CASCADE)

This is the format for aliasing in Django Foreign Key
class Sizing(models.Model):
    btu_hour = models.IntegerField()
    configuration = models.ForeignKey(Configuration)
    ### WHAT I'D LIKE; alias only ###
    flangeNew = models.ForeignKey(Configuration, to_field='flange', on_delete=models.CASCADE)

class Configuration(models.Model)
    flange = models.ForeignKey('parts.Router')

This is the solution of aliasing in new version of Django


text:
Q: Flex Builder 4 cant run or debug I've been working in Flash BUilder 4.0. I installed Flash Builder 4.5, and switched to the workspace I had used for 4.0.  Then we were told to go back to 4.0, and now I can't run or debug.  I can build, but then I have to double click on the .html file to run.  Right clicking doesn't bring up run or debug, and the run and debug icons are not in my toolbar.  Any ideas?  I thought I would check if it is something simple before I reinstall.

A: Create a full backup of your workspace first so you can always go back to the previous situation!
Try removing the hidden .metadata folder from your workspace, remove all your projects from your workspace (but of course not from the disk!).
Restart Flash Builder, open your workspace folder and then reimport them.
If the above does not work, your project might be corrupted.
To fix this, you will have to take a look at your hidden .actionScriptProperties and .project files in your project folder.
Create a new 4.0 project and compare the values of these files to your corrupted project's file. Look especially at the project natures.
If that still doesn't work, remove your workspace, create a new one.
Create a new project and copy all source files of your corrupted project into this project.
Do not copy the .actionScriptProperties and .project files (which is what you get when copying over the whole folder since they are hidden files)
Cheers

A: You can manually add the run/debug-buttons by editing
.metadata\.plugins\org.eclipse.ui.workbench\workbench.xml

First close FB and backup the file!
Then search for <descriptor>-Tag with label="Flash".
Paste the inside the <descriptor>-Tag, maybe after
<alwaysOnActionSet id="org.eclipse.ui.actionSet.openFiles"/>

the following line
<alwaysOnActionSet id="com.adobe.flexbuilder.standalone.launch"/>

Save file and start FB.

A: We have had this problem as well with FlashBuilder 4.5. None of the proposed solution were working. We loose 5 hours to try to solve this, even reinstalling Flash Builder did nothing. That was perfectly strange, as our project perfectly ran on another machine while it was checked out from scratch from same repository on both machines.
Finally got the solution : Go to Users/<yourPCuserName>/AppData/Roaming/Macromedia/Flash Player/Logs
edit the mm.cfg file (it is the debugging setup file for FlashPlayer...)
there should only have two lines :
ErrorReportingEnable=1
TraceOutputFileEnable=1

We did have something like this in it, that was completely blocking FlashPlayer in debugging / run an AIR App.
SuppressDebuggerExceptionDialogs=1
PreloadSWF=C:\Users\<username>\AppData\Roaming\Mozilla\Firefox\Profiles\12l6me0w.default\extensions\flashfirebug@o-minds.com\chrome\content\flashfirebug\flashfirebug.swf

flashfirebug is a Firefox debugger for Flash...
Remove those 2 lines, your apps will start again.

A: I had the same problem, in my case it was the Flash Player (Flash Player Debugger.app on a Mac platform) hanging. Try quitting from the app (if it shows a Force Quit on a Mac it's a good sign) and restarting it.


text:
Q: postgresql statement_timeout behavior To avoid long running queries I want to implement statement_time for certain users.
pgdb=> alter user user1 set statement_timeout=600;
ALTER ROLE
pgdb=> select * from pg_user where usename = 'user1';
  usename  |  usesysid  | usecreatedb | usesuper | userepl | usebypassrls |  passwd  | valuntil |              useconfig
-----------+------------+-------------+----------+---------+--------------+----------+----------+--------------------------------------
 user1 | 2538084332 | f           | f        | f       | f            | ******** |          | {statement_timeout=600}
(1 row)

Logged into PSQL as user1, running very short queries comes back but most of the queries (which will complete in few seconds without statement_timeout limit) are timing out, even though the statement_timeout is set to 180s.
pgdb=> select count(*) from schema.tablea limit 10; -- huge table timeout
ERROR:  canceling statement due to statement timeout
Time: 184.118 ms
imaods=> explain select count(*) from schema.tablea limit 10;
                                                                                QUERY PLAN

-------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------
 Limit  (cost=1906894.11..1906894.12 rows=1 width=8)
   ->  Finalize Aggregate  (cost=1906894.11..1906894.12 rows=1 width=8)
         ->  Gather  (cost=1906893.89..1906894.10 rows=2 width=8)
               Workers Planned: 2
               ->  Partial Aggregate  (cost=1905893.89..1905893.90 rows=1 width=8)
                     ->  Parallel Index Only Scan using idx1 on tablea  (cost=0.57..1828328.86 rows=31026013 width=0)
(6 rows)

pgdb=> select count(*) from tableb;
 count
-------
   260
(1 row)

Time: 0.672 ms
pgdb=> select count(*) from tableb a, tableb b;
 count
-------
 67600
(1 row)
Time: 4.405 ms

pgdb=> select count(*) from tableb a, tableb b, tableb c;  -- timeout
ERROR:  canceling statement due to statement timeout

pgdb=> explain select count(*) from tableb a, tableb b, tableb c;
                                           QUERY PLAN
--------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=264536.10..264536.11 rows=1 width=8)
   ->  Nested Loop  (cost=0.00..220596.10 rows=17576000 width=0)
         ->  Nested Loop  (cost=0.00..878.85 rows=67600 width=0)
               ->  Seq Scan on tableb a  (cost=0.00..16.60 rows=260 width=0)
               ->  Materialize  (cost=0.00..17.90 rows=260 width=0)
                     ->  Seq Scan on tableb b  (cost=0.00..16.60 rows=260 width=0)
         ->  Materialize  (cost=0.00..17.90 rows=260 width=0)
               ->  Seq Scan on tableb c  (cost=0.00..16.60 rows=260 width=0)
(8 rows)

pgdb=> explain analyze select count(*) from tableb a, tableb b, tableb c;
ERROR:  canceling statement due to statement timeout
pgdb=> explain select count(*) from tableb a, tableb b;
                                               QUERY PLAN
--------------------------------------------------------------------------------------------------------
 Aggregate  (cost=1047.85..1047.86 rows=1 width=8)
   ->  Nested Loop  (cost=0.00..878.85 rows=67600 width=0)
         ->  Seq Scan on tableb a  (cost=0.00..16.60 rows=260 width=0)
         ->  Materialize  (cost=0.00..17.90 rows=260 width=0)
               ->  Seq Scan on tableb b  (cost=0.00..16.60 rows=260 width=0)
(5 rows)

pgdb=> explain select count(*) from tableb;
                                        QUERY PLAN
------------------------------------------------------------------------------------------
 Aggregate  (cost=17.25..17.26 rows=1 width=8)
   ->  Seq Scan on tableb  (cost=0.00..16.60 rows=260 width=0)
(2 rows)

Does statement_timeout go by estimated time or by the actual execution time. Going by explain plans, looks like its taking estimated time into consideration and not executing the query if it thinks its estimated time exceeds statement_timeout. Is this expected behavior or am I missing something? My understanding is it should run the query and timeout when the actual execution time exceeds the timeout limit.

A: No, it goes by the actual execution time. The timer starts running when the statement starts executing. How else would you explain that you have for 180 seconds until the query is canceled?
PostgreSQL does not estimate execution time directly. The cost measurements are somewhat artificial, with the rough guideline that 1 corresponds to the time to read one 8kB page from disk during a sequential scan.


text:
Q: Deploy a ASP-project and write the date in a view I want to write the current date in a view or text file when I start the deploy process.
I want to reach :  the deploy-date is visible in a website.
Is this possible?
Thanks

A: You could get the deployment date by reading the last modified date of the assembly.   This will tell you the date the website was built and deployed. Be careful to only read the last modified date once (for performance reasons).
public static class ApplicationSettings
{
    public static DateTime BuildDate { get; private set; }
    static ApplicationSettings()
    {
        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(assembly.Location);
        BuildDate = fileInfo.LastWriteTime;
    }
}

Then in your view you could do:
Build Date: @ApplicationSettings.BuildDate.ToShortDateString()


text:
Q: Issues using NSNumberFormatter? I'm trying to make a label to show the temperature, with a maximum of 3 digits for temperatures over a 100, but I don't want any decimals...
    NSString *longtempstring = [tmp description];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setMaximumFractionDigits:3];
    [formatter setMinimumFractionDigits:0];
    NSString *shorttempstring = [formatter stringForObjectValue:[NSString  stringWithString:longtempstring]];

The code above always returns (null)
Any ideas?

A: You are getting nil because the object you are passing to stringForObjectValue: is not of the type expected.
First of all, don't use stringForObjectValue:. That is a member of the parent class, NSFormatter. NSNumberFormatter has more specific methods that avoid confusion of object types like numberFromString: and stringFromNumber:.
Second, NSNumberFormatter is used to go from number to formatted string or formatted string to number. Not directly from formatted string to formatted string. You will need to use one number formatter to read your original string and produce a number and another to produce a new shorter formatted string from that number.
Of course, you might be able to make the first step (from long string to number) easier by using NSScanner or by taking a substring of your long string (cutting out everything except for the number itself) and then using the NSString method integerValue or doubleValue. A regular expression could also be used to extract the number from the first (longer) string.
The long and short of it is, this is a two step process. The first step (getting a number) can be accomplished any number of ways and a NSNumberFormatter might not be the easiest way. The second step (getting a new shorter string) is what NSNumberFormatter is perfect for.

A: I fixed it by converting the NSString to an NSNumber and only pulling the integer value from the string, thus removing any decimals.
        NSString *longtempstring = [tmp description];
        NSNumber *tempintegervalue = [NSNumber numberWithInteger:[longtempstring integerValue]];
        NSString *shorttempstring = [tempintegervalue stringValue];

A: NSString *longtempstring = [tmp description];

What is the value of longtempstring here? Is it even a number?
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:3];
[formatter setMinimumFractionDigits:0];

Why do you set maximum fraction digits to 3 if you say that you don't want any fraction digits? Fraction digits are what is "after the dot" and you say you don't want any decimals. If you don't want any decimals, minimum and maximum must be set to 0.
NSString *shorttempstring = [formatter stringForObjectValue:[NSString  stringWithString:longtempstring]];

First of all, why are you copying the string? [NSString stringWithString:...] creates a new string that is a copy of the string you provide as argument. Strings are immutable, there is no need to copy them, they won't be modified. If you are afraid that a NSString may in fact be a NSMutableString, after all that is a subclass of NSString and you want to copy it, just copy it by calling [aString copy]. copy is a very smart method here. If the NSString is in fact a mutable string, it will really copy it, so you get an immutable copy. If it is not a mutable string, though, copy just returns the same string with a retain count increased by one (so in that case copy behaves exactly like retain). However, in your case copying makes no sense whatsoever.
And second, what makes you believe, that you can feed a string into a NSNumberFormater? It is called NSNumberFormater because it formats objects of type NSNumber. How is a NSString a NSNumber? It is not called NSStringFormater. If you feed an object of the wrong class to a formater, it will return nil, that's how this method is documented.
If your longtempstring contains a number with fraction, e.g. 12.345, then the correct code would look like this:
NSString * longtempstring = [tmp description];
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
[formatter setMinimumFractionDigits:0];
NSNumber * tempnumber = [NSNumber numberWithDouble:[longtempstring doubleValue]];
NSString * shorttempstring = [formatter stringForObjectValue:tempnumber];

However, if all you want to do is cut off the decimals, that is a horrible way to do it. This can be done much more effective:
double d;
NSString * longtempstring;
NSString * shorttempstring;

longtempstring = @"12.345";
d = [longtempstring doubleValue];
shorttempstring = [NSString stringWithFormat:@"%d", (int)d];

This is much shorter, needs less memory, and is at least three times faster. If you want to round the number (that means everything with a fraction .5 and above is rounded to the next higher value), just round it:
d = round([longtempstring doubleValue]);


text:
Q: Mvvm wpf: update value binding before leaving focus of input element I have this element in my xaml (DevExpress item):
<dxe:ComboBoxEdit IsTextEditable="False" EditValue="{Binding IDTIPOCONN}"
     ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window},Path=DataContext.ttc}"  />

All the binding are correct, and when I change the value, I trigger some event from my ViewModel.
My problem is the update of the value is executed only when I leave the focus of my comboBox. I need, instead, to execute my action when the value is changed, before leaving its foucs.
How can I do it? I need this because selecting one or another from the list, I show to the user some hidden elements.

A: Try for Binding set UpdateSourceTrigger=PropertyChanged:
<dxe:ComboBoxEdit IsTextEditable="False"
                  EditValue="{Binding Path=IDTIPOCONN, UpdateSourceTrigger=PropertyChanged}" ... />

In this case, most likely the default value of UpdateSourceTrigger is LostFocus.


text:
Q: How to align kinect's depth image with color image The image produced by the color and depth sensor on the Kinect are slightly out of alignment. How can I transform them to make them line up?

A: The key to this is the call to 'Runtime.NuiCamera.GetColorPixelCoordinatesFromDepthPixel'
Here is an extension method for the Runtime class.  It returns a WriteableBitmap object.  This WriteableBitmap is automatically updated as new frames come in.  So the usage of it is really simple:
    kinect = new Runtime();
    kinect.Initialize(RuntimeOptions.UseColor | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseDepthAndPlayerIndex);
    kinect.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
    kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
    myImageControl.Source = kinect.CreateLivePlayerRenderer();

and here's the code itself:
public static class RuntimeExtensions
{
   public static WriteableBitmap CreateLivePlayerRenderer(this Runtime runtime)
   {
      if (runtime.DepthStream.Width == 0)
         throw new InvalidOperationException("Either open the depth stream before calling this method or use the overload which takes in the resolution that the depth stream will later be opened with.");
      return runtime.CreateLivePlayerRenderer(runtime.DepthStream.Width, runtime.DepthStream.Height);
   }
   public static WriteableBitmap CreateLivePlayerRenderer(this Runtime runtime, int depthWidth, int depthHeight)
   {
      PlanarImage depthImage = new PlanarImage();
      WriteableBitmap target = new WriteableBitmap(depthWidth, depthHeight, 96, 96, PixelFormats.Bgra32, null);
      var depthRect = new System.Windows.Int32Rect(0, 0, depthWidth, depthHeight);

      runtime.DepthFrameReady += (s, e) =>
            {
                depthImage = e.ImageFrame.Image;
                Debug.Assert(depthImage.Height == depthHeight && depthImage.Width == depthWidth);
            };

      runtime.VideoFrameReady += (s, e) =>
            {
                // don't do anything if we don't yet have a depth image
                if (depthImage.Bits == null) return;

                byte[] color = e.ImageFrame.Image.Bits;

                byte[] output = new byte[depthWidth * depthHeight * 4];

                // loop over each pixel in the depth image
                int outputIndex = 0;
                for (int depthY = 0, depthIndex = 0; depthY < depthHeight; depthY++)
                {
                    for (int depthX = 0; depthX < depthWidth; depthX++, depthIndex += 2)
                    {
                        // combine the 2 bytes of depth data representing this pixel
                        short depthValue = (short)(depthImage.Bits[depthIndex] | (depthImage.Bits[depthIndex + 1] << 8));

                        // extract the id of a tracked player from the first bit of depth data for this pixel
                        int player = depthImage.Bits[depthIndex] & 7;

                        // find a pixel in the color image which matches this coordinate from the depth image
                        int colorX, colorY;
                        runtime.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(
                            e.ImageFrame.Resolution,
                            e.ImageFrame.ViewArea,
                            depthX, depthY, // depth coordinate
                            depthValue,  // depth value
                            out colorX, out colorY);  // color coordinate

                        // ensure that the calculated color location is within the bounds of the image
                        colorX = Math.Max(0, Math.Min(colorX, e.ImageFrame.Image.Width - 1));
                        colorY = Math.Max(0, Math.Min(colorY, e.ImageFrame.Image.Height - 1));

                        output[outputIndex++] = color[(4 * (colorX + (colorY * e.ImageFrame.Image.Width))) + 0];
                        output[outputIndex++] = color[(4 * (colorX + (colorY * e.ImageFrame.Image.Width))) + 1];
                        output[outputIndex++] = color[(4 * (colorX + (colorY * e.ImageFrame.Image.Width))) + 2];
                        output[outputIndex++] = player > 0 ? (byte)255 : (byte)0;
                    }
                }
                target.WritePixels(depthRect, output, depthWidth * PixelFormats.Bgra32.BitsPerPixel / 8, 0);
            };
            return target;
        }
    }

A: One way to do this is to assume that the color and depth images have similar variations in them, and to cross-correlate the two images (or smaller versions of them).

*

*Pre-whiten the images to get at the underlying variations.

*Cross-correlate the pre-whitened images or smaller versions of them.

*The peak position of the cross-correlation will tell you the offset in x and y


text:
Q: How to implement an integration filter on arrays? I have the discrete integration filters:
$$y(n) = Ax(n) + By(n−p) , \text{$A$, $B$ real constants, $p$ positive integer}$$
EDIT: in the initial version of this question I focussed only on the case $A=B=p=1$
I want to apply it on an array representing an impulse signal [1, 0, 0, 0, 0, 0] (assuming $x(n) = y(n) = 0$ for every $n < 0$)
In the imperative style, using Python, I would write:
>>> x = [0]*5
>>> y = [0]*5
>>> impulse = [1]+[0]*5

>>> for i in impulse:
...   x += [i]
...   y += [i+y[-1]]
...

>>> x
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
>>> y
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

How can I obtain the same result with Mathematica? I saw the FoldList and MovingMap functions that had some potential to solve similar problems. But they seem to work only on one list, and I wasn't able to make them use both the $x$ and $y$ lists at the same time.

A: Pardon me if this is wildly off base, but is this useful?
RecurrenceFilter[{{1, 0, -B}, {A}}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}]

{0, 0, 0, 0, 0, A, 0, A B, 0, A B^2, 0}

From the Wolfram Language documentation:

RecurrenceFilter[{α,β},x] gives the response $y$ to the causal input $x$ by solving the recurrence equation:
$$\alpha_1 y_n + ... \alpha_i y_{n-i} = \beta_1 x_n + ... + \beta_j x_{n-j}$$
for $n$ from $1$ to $Length[x]$, where $i$ is $Length[α]$ and $j$ is
  $Length[β]$.

rf[n_, p_] :=
 RecurrenceFilter[{Append[UnitVector[p, 1], -B], {A}}, UnitVector[n + 6, 6]]

rf[5, 2]

rf[8, 3]

{0, 0, 0, 0, 0, A, 0, A B, 0, A B^2, 0}

{0, 0, 0, 0, 0, A, 0, 0, A B, 0, 0, A B^2, 0, 0}

A: x = ConstantArray[0, 5];
y = ConstantArray[0, 5];
impulse = Join[{1}, ConstantArray[0, 5]];
IntegrationFilter[A_, B_, p_, impulse_, xsart_, ystart_] :=
   RecurrenceFilter[
     {Join[{1}, Table[0, p - 1], {-B}], {A}},
      Join[xsart, impulse],
      ystart
   ];

RecurrenceFilter ref : http://reference.wolfram.com/language/ref/RecurrenceFilter.html
IntegrationFilter[1, 0, 1, impulse, x, y]

{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}

IntegrationFilter[1, 1, 1, impulse, x, y]

{0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1}

A: One way to solve this is to use the recursive definition directly along with the initial condition(s):
Clear[y, x]
y[n_] := y[n] = a x[[n]] + b y[n - 1];
y[0] = 0;

To use this, you would need to define x:
x = ConstantArray[0, 20]; x[[3]] = x[[4]] = 1;

To "run" the recursion for the first few entries:
y /@ Range[7]

{0, 0, a, a + a b, b (a + a b), b^2 (a + a b), b^3 (a + a b)}

You can increase the delay (your p parameter) straightforwardly by changing y[n-1] to y[n-2] (for example), but then you also need to add another initial condition (in this case, a value for y[1]). Thanks to @OkkesDulgerci for the simplification.


text:
Q: Count entrances, exits and stayed cars in the parking area I have this dataset with client ID, parking number, starttime and duration.
require(lubridate)
set.seed(1234)
ex <- data.frame(
  client = sample(1:700, 500, replace = T),
  parking = sample(1:5, 1000, replace = T),
  start = sort(as.POSIXct(sample(1377100000:1377230000, 1000), origin = "1960-01-01")),
  duration = format(as.POSIXct(sample(1478130000:1478130000, 1000), origin = "1960-01-01 00:00:00"), "%M:%S")
)

How can I count for each parking for each hour - how many entrances, exits and how many cars are stayed?
Yet I calculate stoptime and add new vector with hours like this:
ex$intime <- format(ex$start, "%Y-%m-%d %H")
ex$outtime <- format(ex$stop, "%Y-%m-%d %H")
dates = seq(ymd_h(min(ex$intime)), ymd_h(max(ex$outtime)), by = "hour")

and count how many cars are in the parking right now:
counts = data.frame(date = dates,
                count = sapply(dates, function(x) sum(x <= ex$parkingStop & x >= ex$parkingStart))

Please help me with counting entraces, exits and stayed cars. Thanks!
The expected output (just for example):
 date                      entrances  exits  stayed
1  2017-04-08 00:00:00     0          0      10
2  2017-04-08 01:00:00    11          1      21
3  2017-04-08 02:00:00     8          4      25
4  2017-04-08 03:00:00     3          1      27
5  2017-04-08 04:00:00     2          7      22
6  2017-04-08 05:00:00     1          2      21
7  2017-04-08 06:00:00     2          9      14
8  2017-04-08 07:00:00     3          7      10
9  2017-04-08 08:00:00     3          12     1
10 2017-04-08 09:00:00    12          2      11
11 2017-04-08 10:00:00    33          23     21
12 2017-04-08 11:00:00    45          22     44

A: Your code is not running, as people noted in the comments, but if I understand you correctly, you are trying to do the following:
require(lubridate)
library(dplyr)

set.seed(1234)
ex <- tibble(
  client = sample(1:700, 1000, replace = T),
  parking = sample(1:5, 1000, replace = T),
  intime = sort(as.POSIXct(sample(1377100000:1377230000, 1000), origin = "1960-01-01")),
  # this will sample durations in M:S format
  dur = format(as.POSIXct(sample(1478130000:1478130000, 1000), origin = "1960-01-01 00:00:00"), "%M:%S")
) %>% mutate(outtime=intime + as.period(ms(dur), unit = "sec"))

ex %>% group_by(date_hours=floor_date(intime, "hour")) %>%
  summarise(entrances = sum(floor_date(intime, "hour") == date_hours)) %>%
  full_join(
    ex %>% group_by(date_hours=floor_date(outtime, "hour")) %>%
      summarise(exits = sum(floor_date(outtime, "hour") == date_hours),
                cars=sum(intime<=date_hours))
  )

So you get similar table out:
Joining, by = "date_hours"
# A tibble: 38 x 4
            date_hours entrances exits  cars
                <dttm>     <int> <int> <int>
 1 2003-08-21 17:00:00         7    NA    NA
 2 2003-08-21 18:00:00        25    21     7
 3 2003-08-21 19:00:00        27    19    11
 4 2003-08-21 20:00:00        23    31    19
 5 2003-08-21 21:00:00        24    25    11
 6 2003-08-21 22:00:00        22    17    10
 7 2003-08-21 23:00:00        30    30    15
 8 2003-08-22 00:00:00        28    27    15
 9 2003-08-22 01:00:00        18    25    16
10 2003-08-22 02:00:00        34    28     9
# ... with 28 more rows


text:
Q: How to center vertically labels in a view I have 4 labels like this in a view:

The view hierarchy like this:

But if one of text in each label is empty, all of other labels should center vertically with the image.
For example: the albumDataLabel.text is empty, then userNameLabel, albumNameLabel, albumLocationLabel should center vertically with the image.
Somethings like this:

So how to do this, please point me to some approaches.

A: *

*Set height constraint for every label and which label have not text
make it's height zero(from outlet of height constraint by setting constant to 0) at runtime.

*Your constraint should be in linear hierarchy like first label's top should be pinned with it's supper view's top and last label's bottom should be pinned with superview's bottom and each and every label's bottom should be pinned with top of below label.

*then you should set height constraint for view that contains all labels with constant (>=) of minimum height(least height of your view).

*and centered vertically that view with your image view.

you can do this kind of setup!!

A: Since your 4 Labels are already in a view, you can set the labels' constraints to pin the first Label to the top, last Label the bottom and spacing in between to zero
Then select the view(withLabels) and your ImageView to align their vertical centers
Do not set a height value constraint for your labels nor the view
When one of your labels have an empty string, the height is automatically set to zero and hence 'hidden' so the view(withLabels) will shrink in height. All can be done in the interface builder, no coding necessary, it is just a matter of autolayout.

A: 1) for your userNameLabel:
userNameLabel.leftAnchor.constraintEqualToAnchor(imageView.rightAnchor, constant: 10).active = true
                userNameLabel.topAnchor.constraintEqualToAnchor(self.topAnchor, constant: 50).active = true
                userNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
                userNameLabel.heightAnchor.constraintEqualToConstant(30).active = true

2) for your albumNameLabel:
albumNameLabel.widthAnchor.constraintEqualToConstant(220).active = true
                albumNameLabel.heightAnchor.constraintEqualToConstant(30).active = true
                albumNameLabel.topAnchor.constraintEqualToAnchor(userNameLabel.bottomAnchor, constant: 5).active = true
                albumNameLabel.leftAnchor.constraintEqualToAnchor(imageView.leftAnchor, constant: 10).active = true

3) remember this:
self.addSubview(userNameLabel)
self.addSubview(albumNameLabel)

And go on in this way to all elements in your View.


text:
Q: What is the wildcards format for TEdit search function in FireDAC Delphi This is my code for searching data using the TEdit component that triggers TFDQuery with parameter:
qryItems.ParamByName('searches').AsString := Format('%%%s%%',[edtSearch.Text]);

If I remove the wildcards (Format('%%%s%%')) format, it works. The wildcards will help me filter the query.
I like the code, its clean, simple, and straight forward. But, I am still not sure if it is correct — it is not returning anything!
My question is:
Does the code above works for query filtering from TEdit.OnChangeTracking event? Otherwise, what is the correct way of doing this?
UPDATE 1:
Heres the code from TFDQuery Editor:
SELECT category.name AS category, item.name, item.description
FROM item
JOIN category ON item.category_id = category.list_id
WHERE item.description LIKE :searches
ORDER BY item.sellable
LIMIT 100

Now, I am trying to access this from this code during runtime but it is not working:
qryItems.ParamByName('searches').AsString := Format('%%%s%%',[edtSearch.Text]);

I think the culprit here is this code Format('%%%s%%',[edtSearch.Text]), I am not getting this right.

A: A short answer is that you want to end up with a parameter assignment like this:
  FDQuery1.Params[0].AsString := '%a%';
  FDQuery1.Open();

assuming the value you want to match in your LIKE expression is simply the letter a.  Or, if you want to use Format, you could do something like this:
  FDQuery1.Params[0].AsString := Format('%%%s%%', [edFilter.Text]);

The reason for the three hash-signs in a row is that the first one 'escapes' the second one in the expression Format evaluates, and the third one, immediately before the 's' combines with it to act as the placeholder for a string as Format constructs its result.
However, given that you are not completely familiar with working with datasets and filtering,
I think you are making this unnecessarily difficult for yourself in at least two respects:

*

*FMX + LiveBindings is not entirely bug free and has some quirks which may well get in your way.

*The syntax for using the LIKE operator, which uses hash-signs (#), clashes with the use
of hash signs for resolving parameters in the Format function.  This, in particular, can be
extremely confusing, especially when you are trying to obtain a syntactically valid
LIKE expression, whether it is for inclusion in the Sql your query uses or in a 'local filter,
i.e. one which uses the Filter + Filtered properties of the FDQuery.
So, I am going to make a suggestion which might possibly be unwelcome initially,
which is to do your exploration
of things like filtering in a VCL application such as the one below.  It will only take a few minutes to set up,
but will probably save you some time and wear and tear on the nervous system compared with
trying to get it right in an FMX + LiveBinding application which is under development.  Here is how:

*

*Create a new VCL application and add these components to it.

    FDConnection1: TFDConnection;
    FDGUIxWaitCursor1: TFDGUIxWaitCursor;
    FDQuery1: TFDQuery;
    DBGrid1: TDBGrid;
    DBNavigator1: TDBNavigator;
    DataSource1: TDataSource;
    edFilter: TEdit;
    btnLocalFilter: TButton;
    btnSqlFilter: TButton;

*Add the code below to the form's file.

*Put a debugger breakpoint on the line
case FilterMode of

and exlore the app's behaviour changing the contents of the edFilter control
and clicking the two buttons, once you've adapted the code to the data you have
available.  Mine uses an Author's table, I can't remember where I got it from
but maybe it was from the Pubs sample database for Sql-Server.
The app shows - as I'm sure you've gathered - that you can filter the data displayed
by your app either server-side by changing the Sql used to retrieve the data or client-side by using
the Filter property of the FDQuery.  So that you can easily see what's going on, the Sql for server-side
filtering is constructed by concatenating the contents of edFilter.Text with the
rest of the Sql, but in real life, you should never do that because of
its exposure to the Sql Injection exploit.
Code
type
  TFilterMode = (fmLocal, fmSql);

type
  TForm1 = class(TForm)
  [...]
  public
    { Public declarations }
    FilterMode : TFilterMode;
  end;
[...]
const
      sOrderBy = ' order by lastname, forename';
      sSql = 'select * from authors';
      sFilteredSql = sSql + ' where lastname like  :lastname%';
      sLocalFilter = 'lastname like ''%%s%%''';

procedure TForm1.OpenFDQuery;
var
  S : String;
begin
  if FDQuery1.Active then FDQuery1.Close;
  FDQuery1.Params.Clear;
  FDQuery1.Filter := '';
  FDQuery1.Filtered := True;
  case FilterMode of
    fmSql : begin
      FDQuery1.Sql.Text := '';
      //  WARNING - don't do this for real - risk of Sql Injection exploit
      //  use a parameterised query instead - see http://docwiki.embarcadero.com/RADStudio/Rio/en/Using_Parameters_in_Queries
      S := 'select * from authors where lastname like ''%' + edFilter.Text + '%''';
      FDQuery1.Sql.Text := S;
    end;
    fmLocal : begin
      FDQuery1.Sql.Text := sSql + sOrderBy;
      S := 'lastname like ''%' + edFilter.Text + '%''';
      FDQuery1.Filter := S;
      FDQuery1.Filtered := True;
    end;
  end;

  FDQuery1.Open;
end;

procedure TForm1.ApplySqlFilter;
begin
  FilterMode := fmLocal;
  OpenFDQuery;
end;

procedure TForm1.ApplyLocalFilter;
begin
  FilterMode := fmLocal;
  OpenFDQuery;
end;

procedure TForm1.btnLocalFilterClick(Sender: TObject);
begin
  ApplyLocalFilter;
end;

procedure TForm1.btnSqlFilterClick(Sender: TObject);
begin
  ApplySqlFilter;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  edFilter.Text := 'a';
end;


text:
Q: Action Script 3. How to prevent lag bugs issues in flash games? How to prevent lag bugs issues in flash games? For example If game have countdown timer 1 minute and player have to catch that much items that possible.
Here are following lag bugs issues:

*

*If items moving (don't have static position) - that higher lag player
have, that slower items move;

*Timer starting count slowly when player have lags (CPU usage 90-100%).

So for example If player without lags can get 100 points, player with slow / bad computer can get 4-6x more, like 400-600.

I think that because It's on client side, but how to move It to server side? Should I insert (and update) countdown time to database? But how to update It on every millisecond?
And how about items position solution? If player have big lags, items moving very very slowly, so easy to click on that, have you any ideas?

A: Moving the functionality to the server side doesn't solve the problem.
Now if there are many players connected to the server, the server will lag and give those players more time to react.
To make your logic independent from lag, do not base it on the screen update.
Because this assumes a constant time between screen updates (or frames)
Instead, make your logic based on the actual time that passed between frames.
Use getTimer to measure how much time passed between the current and the last frame.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html
Of course, your logic should include calculations for what happens in between frames.

A: In order to mostly fix speed issues on the client you need to make all your speed related code based on actual time, not frames. For example:
Here is a fairly typical example code used to move an object based on frames:
// speed = pixels per frame
var xSpeed:Number = 5;
var ySpeed:Number = 5;

addEventListener(Event.ENTER_FRAME, update);

function update(e:Event):void {
    player.x += xSpeed;
    player.y += ySpeed;
}

While this code is simple and good enough for a single client, it is very dependent on the frame rate, and as you know the frame rate is very "elastic" and actual frame rate is heavily influenced by the client CPU speed.
Instead, here is an example where the movement is based on actual elapsed time:
// speed = pixels per second
var xSpeed:Number = 5 * stage.frameRate;
var ySpeed:Number = 5 * stage.frameRate;

var lastTime:int = getTimer();

addEventListener(Event.ENTER_FRAME, update);

function update(e:Event):void {
    var currentTime:int = getTimer();
    var elapsedSeconds:Number = (currentTime - lastTime) / 1000;
    player.x += xSpeed * elapsedSeconds;
    player.y += ySpeed * elapsedSeconds;

    lastTime = currentTime;
}

The crucial part here is that the current time is tracked using getTimer(), and each update moves the player based on the actual elapsed time, not a fixed amount. I set the xSpeed and ySpeed to 5 * stage.frameRate to illustrate how it can be equivelent to the other example, but you don't have to do it that way. The end result is that the second example would have consistent speed of movement regardless of the actual frame rate.


text:
Q: Basic counterexample re: preimages of ideals I'm trying to think of an example of a homomorphism of commutative rings $f:A\rightarrow B$ and ideals $I,J$ of $B$ such that $f^{-1}(I)+f^{-1}(J)$ is not a preimage of any ideal of $B$.  I can't seem to come up with one... anyone know one?
Edit: To clear up some basic facts / head off some mistakes:
As Arturo points out, we can assume $f$ is an inclusion.  Perhaps I should have written the question in terms of inclusions in the first place, but, eh.
No, $f^{-1}(I)+f^{-1}(J)$ is not equal to $f^{-1}(I+J)$ in general.  A counterexample would be the inclusion of $\mathbb{C}$ in $\mathbb{C}[x]$; consider $(x)$ and $(1-x)$.
To show an ideal $K\subseteq A$ is not a preimage of any ideal of $B$, it suffices to show that it's not equal to $f^{-1}(Bf(K))$.

A: Unless I'm missing something, this is the preimage of I+J (I missed something... this is not correct)
If $I,J$ are ideals in $B$ then $f^{-1}(I),f^{-1}(J)\subseteq f^{-1}(I+J)$ so $f^{-1}(I)+f^{-1}(J)\subseteq f^{-1}(I+J)$.
On the other hand, if $x\in f^{-1}(I+J)$ then $f(x)=i+j,\; i\in I,j\in J$. Let $a\in f^{-1}(I)$ such that $f(a)=i$, and $b\in f^{-1}(J),\;f(b)=j$ then $f(a+b)=i+j=f(x)$ so $a+b=x+k$ where $k \in ker(f)$. $ker(f)\subseteq f^{-1}(I)+f^{-1}(J)$ and $a,b\in  f^{-1}(I)+f^{-1}(J)$ so also $x \in f^{-1}(I)+f^{-1}(J)$ and we get that $f^{-1}(I+J)\subseteq f^{-1}(I)+f^{-1}(J)$

ok, another try
let $f:\mathbb{Z}[x]\rightarrow \mathbb{Q}[x]$ be the inclusion function. If $I=(x-3)\mathbb{Q}[x],\; J=x \mathbb{Q}[x]$ then their preimage is $(x-3)\mathbb{Z}[x], \; x\mathbb{Z}[x]$ (I used here Gauss lemma). The sum of the preimages is not all of $\mathbb{Z}[x]$ and it contains 3. If it is in itself a preimage of K then it  $3\in K$ in $\mathbb{Q}[x]$ which is invertible and so this is all of $\mathbb{Q}[x]$ and we get a contradiction.
Hope this one is ok....

A: Let $k$ be field of caracteristic $\neq 2$, $A=k[x,y], B=k[x,y,x^{-1},y^{-1}]$ and take $f:A\hookrightarrow B$ be inclusion. Example for what you want is $I=(x+y)B, J=(x-y)B$.
Then $f^{-1}I=(x+y)A, f^{-1}J=(x-y)A$ and $f^{-1}I+f^{-1}J=(x,y)A$ . Since $(x,y)B=B$,  sum
$f^{-1}I+f^{-1}J$ can not be $f^{-1}$ of ideal in $B$


text:
Q: Python: While is not working with "or" So, I have this:
while cancer[j] != ("l"or"r"or"c")

and it's stopping at the first "l" in the way when it has some r and c in between the string, its acting like there are not "or" and only the "l".
for example my string is this one:
c56r36c20l80c23l180c23l20c55r70

and it returns:
c56r36c20

It stops right at the first "l", skipping the "c" and "r" in the way.

A: It's working properly; it just doesn't work how you think it should:
("l" or "r" or "c")

returns the first nonfalse item (bool(item) is true) on that list, or false if there isn't any. That means it'll return "l".
So your while loop is actually:
while cancer[j] != "l":

What you want, instead, is something like:
while cancer not in ('l', 'r', 'c')

or
while not cancer in ('l', 'r', 'c')

Both are pretty much the same thing.

A: Usually, if one of the expressions in an 'or' statement evaluates to True, the rest of the expression is not evaluated at all. So when the first 'l' is encountered in the string, the while condition will break right there.
You should have something like:
while cancer[j] not in ('l', 'r', 'c'):


text:
Q: ThreadPool. Avoid saturating the server In a test application I pretend that a server only accepts a maximum number of connections simultaneously. For this I use a ThreadPool in the following way:
ThreadSocket client;
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
    while (true) {
            client = new Client(serverSocket.accept());
            executor.execute(client);
    }
} catch (IOException e) {
    System.out.println("IOException: " + e.getMessage());
} finally {
    executor.shutdown();
}
}

The ThreadPool works perfectly but my question is what happens with the creation of thread type objects. The execute method expects to receive an instance already created but I understand that the creation of these instances can collaps the server.
Thank you.

A: Thread type objects are only created when you call Executors.newFixedThreadPool(3);. Then every new request will create Client objects, but they only need to impelment the Runnable interface - those are not new threads (this depends on your implementation, but hope the client doesn't create a new thread itself).
This might help. You should also consider using executor.submit instead of executor.execute.


text:
Q: Using extended properties (attributes) to columns in an SQL table for defining how data should be input later on I have never used SQL. I would like to create a table with different columns. Then I would like to create a program which allows the user to insert entries. For each token of the entry, I would like to retrieve from an attribute of the corresponding column the way this particular part of the data entry should be entered. For example, I will have some data retrieved automatically (e.g. the date and time), some for which I will propose the user to insert the last added value, and some for which I will ask the user to explicitly type the value.
I do not know if "Attribute" is the right term; the attributes that I have available for each column at the moment are "Name", "DataType" and "Description"
I want that my program dynamically adapts to the table columns and to the property of each column, especially because I will have several tables to be filled. So my program would check the table columns with their properties, and interact with the user for the creation of a new entry.
Is there a possibility to add attributes to a column?
Otherwise I will have to encode the information I need for my program in the "Description" field (aka "MS_Description").
I googled terms like "sql add column attribute", but I could only find results concerning how to add a column to a table.


text:
Q: watermarking to video Android using ffmpeg I am using ffmpeg library for water marking in android, somehow it is taking high amount of time (like 5MB video taking 1 minute of time). Let me know if you have any suggestions.
gradle dependency: implementation 'com.writingminds:FFmpegAndroid:0.3.2'
slow code: val command = arrayOf("-i", srcVideo, "-i", watermarkImgPath, "-filter_complex", "overlay=20:20", outPutVideo)


text:
Q: unable to create Jenkins pipeline for UAT environment which is only accessible through VPN i am trying to develop a pipeline for organization's UAT environment.
to access that environment for manual deployments we use VPN (which is not open-vpn),
now i am stuck because i am unable to find any Jenkins plugin which can help my connection to my that UAT environment, or any other solution
please help me out here.


text:
Q: How to manage Spotify access token in express app I'm writing an Express + Typescript application that, among other things, has an API endpoint which allows the user to search for a track. The endpoint receives a track name as a URL parameter, requests an access token from Spotify, uses the access token to query the Spotify Web API for matching tracks, then returns the data in JSON format. My problem is that I'm using the spotify-web-api-node library to interact with the API and so far I've only been able to make it work by requesting a new access token each time the route is accessed. I've tried adding middleware to request the access token elsewhere so it doesn't need to be done in this specific route, but it seemingly executes the route before the middleware, thus executing the API call without first getting the access token. Here is my working solution so far
import { Router, Request, Response, NextFunction } from 'express';
import SpotifyWebApi from 'spotify-web-api-node';

const spotifyRouter = Router();

const spotifyApi: SpotifyWebApi = new SpotifyWebApi({
    clientId: /* My client ID */,
    clientSecret: /* My client secret */
})

spotifyRouter.get('/search/track/:trackName', (req: Request, res: Response) => {
    spotifyApi.clientCredentialsGrant()
    .then(data => spotifyApi.setAccessToken(data.body['access_token']))
    .then(() => { return spotifyApi.searchTracks(req.params.trackName) })
    .then(data => res.json(data.body))
    .catch(error => res.json(error));

})

export default spotifyRouter;

So to reiterate, I'm wondering how I can improve the management of the access token so it doesn't have to get a new one each time the above route is used.
Thanks.
EDIT: I forgot to mention that this is using Spotify's Client Credentials Flow


text:
Q: gdb - optimized value analysis My CPU is arm.How can I figure out the function parameter value if it's optimized out?
For example:
status_t NuPlayer::GenericSource::setDataSource(
        int fd, int64_t offset, int64_t length) {
    resetDataSource();

    mFd = dup(fd);
    mOffset = offset;
    mLength = length;

Above function has 3 parameters, when I try to print the second parameter offset, I will get below result:
Thread 4 "Binder:15082_3" hit Breakpoint 1, android::NuPlayer::GenericSource::setDataSource (this=0xae63bb40, fd=8, offset=<optimized out>, length=9384436) at frameworks/av/media/libmediaplayerservice/nuplayer/GenericSource.cpp:123
123     resetDataSource();
(gdb) x/i $pc
=> 0xb02aaa80 <android::NuPlayer::GenericSource::setDataSource(int, long long, long long)+12>:  blx 0xb0282454 <_ZN7android8NuPlayer13GenericSource15resetDataSourceEv@plt>
(gdb) n
125     mFd = dup(fd);
(gdb) print offset
$1 = <optimized out>
(gdb) p $eax

$2 = void
(gdb) disassemble /m
Dump of assembler code for function android::NuPlayer::GenericSource::setDataSource(int, long long, long long):
122         int fd, int64_t offset, int64_t length) {
   0xb02aaa74 <+0>: push    {r4, r5, r6, r7, lr}
   0xb02aaa76 <+2>: sub sp, #4
   0xb02aaa78 <+4>: mov r4, r3
   0xb02aaa7a <+6>: mov r5, r2
   0xb02aaa7c <+8>: mov r6, r1
   0xb02aaa7e <+10>:    mov r7, r0

123     resetDataSource();
=> 0xb02aaa80 <+12>:    blx 0xb0282454 <_ZN7android8NuPlayer13GenericSource15resetDataSourceEv@plt>

124
125     mFd = dup(fd);
   0xb02aaa84 <+16>:    mov r0, r6
   0xb02aaa86 <+18>:    blx 0xb027e5d8 <dup@plt>
   0xb02aaa8a <+22>:    ldrd    r2, r1, [sp, #24]
   0xb02aaa8e <+26>:    str.w   r0, [r7, #224]  ; 0xe0
   0xb02aaa92 <+30>:    movs    r0, #0

126     mOffset = offset;
   0xb02aaa94 <+32>:    strd    r5, r4, [r7, #232]  ; 0xe8

127     mLength = length;
   0xb02aaa98 <+36>:    strd    r2, r1, [r7, #240]  ; 0xf0

128
129     // delay data source creation to prepareAsync() to avoid blocking
130     // the calling thread in setDataSource for any significant time.
131     return OK;
   0xb02aaa9c <+40>:    add sp, #4
   0xb02aaa9e <+42>:    pop {r4, r5, r6, r7, pc}

End of assembler dump.
(gdb)

I guess it's in some register but the result of $eax is void.

A: Sounds like example code has assigned the parameter variable to local variable already, so print that value will be exactly the same as optimized out parameters.
mOffset = offset;
mLength = length;

A:
I guess it's in some register but the result of $eax is void.

There is no register called eax on ARM.
To know which register the parameter is in, you need to know calling convention.
Looks like you are using 32-bit ARM. From above link:
r0 to r3: used to hold argument values passed to a subroutine

So you should do info registers, verify that r0 == 0xae63bb40, r1 == 8 and find the offset in r2.


text:
Q: Use a VBA function inside a sort macro I maintain an Excel spreadsheet with data in multiple columns that can be sorted in various ways as each user deems useful. I set this up using macros with buttons on the sheets that do the various sorts
A user has requested the ability to sort on a column that has letter-number combinations, but sort by number only. The data is aircraft callsigns that contain 1 to 3 letters followed by 1 to 5 numbers. The user wants to sort by flight number with no regard to the registration letters.
I found a function that accomplishes this called "num()". I would like to use this function without altering the data in the column itself. Here's an example of what I'm shooting for:
Sub sortscenarionum()
'
' sortscenarionum Macro
' Sort Aircraft by FLIGHT NUMBER then RPO TIME
'
    ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear
    ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range( _
        "N11:N159"), SortOn:=num("N11:N159"), Order:=xlAscending, DataOption:= _
        xlSortNormal
    ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range( _
        "I11:I159"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.ActiveSheet.Sort
        .SetRange Range("B11:N159")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    SendKeys "{ESC}"
End Sub

This fails with "Type mismatch". I have also tried SortOn:=num(xlSortValues) with the same negative results. I have no problem with moving the function into the macro itself, but I have no idea how to do that. Here's the function in case it's useful:
Function num(rng As Range) As String
Dim n As Integer
For n = 1 To Len(rng)
If Mid(rng, n, 1) Like "[0-9]" Then
num = num & Mid(rng, n, 1)
End If
Next n
End Function

A: Add a column to be used as a helper; populate then sort on the new column; delete the new column.
Sub sortscenarionum()
    With ActiveWorkbook.ActiveSheet
        .Columns("O").Insert
        With .Range(.Cells(11, "B"), .Cells(.Rows.Count, "N").End(xlUp).Offset(0, 1))
            .Columns(.Columns.Count).Formula = "=numsOnly(N11)"
            .Columns(.Columns.Count).Value = .Columns(.Columns.Count).Value
            .Sort Key1:=.Columns(.Columns.Count), Order1:=xlAscending, _
                  Key2:=.Columns(8), Order2:=xlAscending, _
                  Orientation:=xlTopToBottom, Header:=xlNo
        End With
        .Columns("O").Delete
    End With
End Sub

Function numsOnly(str As String)
    'with rgx as static, it only has to be created once
    Static rgx As Object
    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If
    numsOnly = vbNullString

    With rgx
        .Global = True
        .MultiLine = False
        .Pattern = "[0-9]{1,5}$"
        If .test(str) Then
            numsOnly = CLng(.Execute(str)(0))
        End If
    End With
End Function


text:
Q: How to play speex encoded audio in Flash player? I am able to record sound from microphone, encode it using SPEEX and write into ByteArray. I want to play it back.
If I try using Sound object the audio is messed up.
Speex uses 16kHz for encoding and Sound Object needs 44.1kHz for playing audio. How am I supposed to play this encoded sound.
Please help!!
- Pat

A: Is this a browser or Air based application?
The reason I ask is because Speex is only playable through an FLV container.  It's a one way encode that is made to be streamed through a media player like FMS or Wowza. Here's what you need to do for both cases.
If browser based
There's no way to playing it locally.  You're going to have to stream it to a media server which then returns an FLV file for you to play on the client.
If Air based
You can wrap the speex audio into an FLV container and play it locally.  Use this library to write the FLV locally: http://www.zeropointnine.com/blog/simpleflvwriteras-as3-class-to-create-flvs/


text:
Q: How to terminate a console input request when a new input is requested I need to terminate an existing console input request when a new one is requested. The following code is an attempt to close an existing request using a channel but it does not seem to terminate the input request.
package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strings"
    "time"
)

func main() {
    go Confirm("you are a programmer, aint you?")
    time.Sleep(2 * time.Second)
    Confirm("do you love go?")
}

var cancelChannel chan struct{}

func Confirm(s string) bool {
    //check if channel type holds a value then close the channel to remove previous confirmation input
    if cancelChannel != nil {
        fmt.Println("channel to be closed")
        close(cancelChannel)
    }
    cancelChannel = make(chan struct{})
    reader := bufio.NewReader(os.Stdin)
    for {
        fmt.Printf("%s [y/n]: ", s)

        response, err := reader.ReadString('\n')
        if err != nil {
            log.Fatal(err)
        }

        response = strings.ToLower(strings.TrimSpace(response))

        if response == "y" || response == "yes" {
            return true
        } else if response == "n" || response == "no" {
            return false
        }

        if _, ok := <-cancelChannel; !ok {
            fmt.Println("channel closed")
            return false
        }

    }
}

A: As @JimB mentioned in comment you can't interrupt read on stdin although there is kinda shady trick how you can achieve it. It's possible to duplicate os.Stdin file descriptor using syscall (not recommended) and open it as non blocking file.
package main

import (
    "bytes"
    "context"
    "errors"
    "fmt"
    "io"
    "io/fs"
    "io/ioutil"
    "os"
    "syscall"
    "time"
)

func setNonblock(f *os.File) error {
    c, err := f.SyscallConn()
    if err != nil {
        return err
    }

    var err2 error
    err = c.Control(func(fd uintptr) {
        err2 = syscall.SetNonblock(int(fd), true)
    })
    if err != nil {
        return err
    }
    return err2
}

func nonBlockingFile(f *os.File) (*os.File, error) {
    if err := setNonblock(f); err != nil {
        return nil, err
    }
    fd, err := syscall.Dup(int(f.Fd()))
    if err != nil {
        return nil, err
    }
    f2 := os.NewFile(uintptr(fd), f.Name())
    return f2, nil
}

func read(ctx context.Context, f *os.File) (io.Reader, error) {
    r, err := nonBlockingFile(f)
    if err != nil {
        return nil, err
    }
    go func() {
        defer r.Close()
        <-ctx.Done()
    }()
    buff := bytes.NewBuffer([]byte{})
    for {
        _, err := io.Copy(buff, r)
        if err != nil {
            if errors.Is(err, fs.ErrClosed) {
                break
            }
            panic(err)
        }
    }
    return buff, nil
}

func main() {
    ctx1, cancel := context.WithCancel(context.Background())
    go func() {
        time.Sleep(time.Second * 2)
        cancel()

    }()
    buf1, err := read(ctx1, os.Stdin)
    if err != nil {
        panic(err)
    }
    ctx2, _ := context.WithTimeout(context.Background(), time.Second*2)
    buf2, err := read(ctx2, os.Stdin)

    fmt.Println("buf1")
    fmt.Println(ioutil.ReadAll(buf1))
    fmt.Println("buf2")
    fmt.Println(ioutil.ReadAll(buf2))
}

A: Go on and explore the simplicity offer by go
https://pkg.go.dev/context#WithCancel
You can have a context that returning CancelFunc then you use context.WithCancel.
And execute cancel func if you want to terminate.
This is the good practice way, you can also do a dirty os.Exit(0) in another case.


text:
Q: Browserify errors ending gulp watch task I've got the following setup in my gulpfile.js:
gulp.task('browserify', function() {
    browserify(config.paths.browserifyEntry)
        .transform(reactify)
        .bundle()
        .pipe(source('master.js'))
        .pipe(gulp.dest(config.paths.dist))
        //.pipe(connect.reload());
});

gulp.task('watch', function () {
    gulp.watch(config.paths.components, ['browserify']);
    gulp.watch(config.paths.sassSource, ['sass']);
});

This all works perfectly until I'm writing code that results in a browserify error.  This happens frequently as I'm editing code in one file that is dependent on a change I haven't yet made in another file, browserify errors out.
The problem is that when browserify errors out it ends the watch task.  I would expect that when browserify errors, it simply doesn't finish it's task but that the watch would continue so that when I make other changes that would allow browserify to run successfully it will do so.  It is problematic to be making changes and then to reload the browser and find that it's not working only to find that the watch process ended due to a browserify error when your code was in an erroneous state.
Is there a way to swallow that error so that it doesn't stop the watch process?  Or is there another npm package that watches files and doesn't get tripped up by the browserify error?

A: If you don't handle the error event, the stream will throw. You could handle the event directly:
gulp.task('browserify', function() {
    browserify(config.paths.browserifyEntry)
        .transform(reactify)
        .bundle()
        .on('error', console.error.bind(console))
        .pipe(source('master.js'))
        .pipe(gulp.dest(config.paths.dist));
});

Or you could catch the error after it throws:
process.on('uncaughtException', console.error.bind(console));

A: For Browserify streams you need to call emit in error handler:
gulp.task('browserify', function() {
  browserify(config.paths.browserifyEntry)
  .transform(reactify)
  .bundle()
  .on('error', function (error) {
    console.error(error.toString())
    this.emit('end')
  })
  .pipe(source('master.js'))
  .pipe(gulp.dest(config.paths.dist));
});


text:
Q: Logging Subview Not Returning Correct Subclass At certain points in my application, I am adding a UIView to the keyWindow, and at other points I need to retrieve it in order to manipulate it.
I add the view like such:
self.minimizedView = [[UIViewCustomSubclass alloc] initWithFrame:viewFrame];
[[UIApplication sharedApplication].keyWindow addSubview:self.minimizedView];

Later, in another class, I am attempting to iterate through the subviews of the keyWindow, like this:
for (id subview in [UIApplication sharedApplication].keyWindow.subviews) {
    NSLog(@"VIEW: %@ CLASS %@", [subview description], [subview class]);
}

I am using id here because I want to be typesafe in accessing only the right subview, because I need to move it's frame and I want to be sure I'm only moving the correct one... further to that point, I've subclassed UIView and created the view that I am adding to the keyWindow to be of that type...
Inside the above for loop, I am attempting to ask for isMemberOfClass:
if ([subview isMemberOfClass:[UIViewCustomSubclass class]]) {
    NSLog(@"The Subview %@ of Class %@ Should Be The One We Are Looking For", [subview description], [subview class]);
    // assign subview to iVar etc
}

But this never executes - the subview always logs it's class type to be of UIView (the superclass) but never of the subclass... I've set a breakpoint and inspected the View properties right at the point where I add it to the keyWindow, and it seems to be of the correct subclass type there...
Can anyone spot something that I'm doing wrong?
-- EDIT --
OOPS. I just found one edge case / place in my code where I am allocating the view still as a UIView and not as the subclass - this fixed the problem.


text:
Q: prevent redirection or have RequestDispatcher to link to specific tab We made a jsp and sent data to the database through the use of servlet...
however, it redirects to a blank page,,, I would want to either prevent that redirection or have the RequestDispatcher link to a specified tab on my homepage..
how should I do this?
this is the code inside jsp

Home

Enrollment

Viewing of Grades

A: May I ask what you have tried in your servlet?
If I understand your question:
There are two ways to redirect the user to another page, either by using request.getRequestDispatcher(your_jsp_url).forward(request, response) in doGet(), or by using response.sendRedirect(a_servlet_url) to send to another servlet's doGet()-method.


text:
Q: /dev/i2c is not showing Raspberry Pi4 running on Android I am using AOSP android 11 in the RPi4. I have enabled the i2c in config.txt using the param dtparam=i2c_arm=on.
The i2c is showing in the /sys/bus/i2c/devices/i2c-1 but /dev/i2c is not listing in the dev folder.
I want to access the APDS-9960 sensor in AOSP.
Please suggest some solution.

A: Finally, I got it.
Open the config file bcm2711_defconfig under the kernel path kernel/arpi/arch/arm64/configs and change the config value CONFIG_I2C_CHARDEV=y.
This will enable the dev/i2c.


text:
Q: PHP Arrays. Trouble formatting result array I am working on an API in PHP that sends JSON data in form of an array to an android app. I'm having issues in returning the JSON array in the format;
"sammury" : [
    { "ClientName": "Samuel", "OrdersTaken": 400 },
    { "ClientName": "James", "OrdersTaken": 20 },
    { "ClientName": "Ritah", "OrdersTaken": 9 }
   ]

I'm using a php server online and a mysql database. I have added an image showing how the data that is returned loks like. Any Assistance Will be highly appreciated

A: Here is a simple example for you how to send your desired response.
1) Create your object arrays
2) Push the objects into the data array (you can use loop to push objects to array) and then assign that data array to the response array and convert it to Json.
Please see the working code here
$data = [];

$obj = [
    "ClientName"=> "Samuel",
    "OrdersTaken"=> 400
];

array_push($data, $obj);

$response = [
        "sammury"=> $data
    ];

$json = json_encode($response);

echo $json;


text:
Q: Not sure why I keep getting a NULL value in my array Novice here. I'm having major headaches with trying to get my head around sqlite3.
Every time I try to run this method
-(void)openDB
{
    if (sqlite3_open([[self filePath] UTF8String], &db) != SQLITE_OK)
    {
        sqlite3_close(db);
        NSAssert(0, @"Database failed to open");
    }
    else
    {
        NSLog(@"database opened");
    }

}

So that I can pull data from my database and into a table.
I get this error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -  [NSPlaceholderString initWithUTF8String:]: NULL cString'

Any tips?

A: There is a problem with your filePath. Also, for converting NSStrings to file system compatible C strings, you should use the method fileSystemRepresentation, not UTF8String.


text:
Q: Is there a way to up-size the font with CSS to fit the screen? I'm thinking about improving the front page of the OpenBSD ports web-site, which lists about 71 categories of the ports.
My idea is to use a couple of columns (maybe ul {-moz-columns: 9em;} also with a limit to at most 8 columns at 89em and above, @media (min-width: 89em) {ul {-moz-columns: 8;}}, effectively specifying that there should be at most 8 columns with a minimum width of 9em), and add some padding/margin to each list item listing a port, but on bigger screens, this might occupy too little screen and leave too much empty space.
Is there a way to automatically upsize the font of certain elements, to fill up all the available space, but without effecting the size of some other elements?  For example, I'd like to have the heading and the categories up-sized, but leave all the credits at the bottom of the page in their normal font.  I'm looking for a CSS-only solution.  (I guess I could place in a couple of specific @media rules for a few jumps up a size, but I was curious if there's a more flexible and automated solution.)

A: I think this is what you're looking for: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths
You can you vw (viewport width) or wh (viewport height) where 1 v == 1% of the initial containing block
Example:
 p{
     font-size: 4vw;
 }