text:
Q: How to store values in a function and be printed/modified from another? I'd like to create a function that has different types of enemies in it. But I do not know the amount of enemies, they will be randomly generated. Then, I want to print them out by having an input statement saying press 1 for the first enemy, 2 for the second, etc. So it'd be like, you got 3 zombies, 15 ghosts, etc But, I want it to be created in a way that I can later on add more inputs so that the user can modify it, like 'which type of enemy do you want to add/delete enemies from?. I need help on how to do this, please. Here's what I got so far, if my code can be modified to be simpler, make more sense, in a way I can learn it and understand, that'd be perfect, thanks!
import random
def fillEnemyField():
    print("Here's your first EnemyField")
    zombies = []
    zombies = random.randrange(0, 15)
    trolls = []
    trolls = random.randrange(0, 15)
    vampires = []
    vampires = random.randrange(0, 15)
    ghosts = []
    ghosts = random.randrange(0, 15)

def printEnemyField():
    choice1 = int(input("Press 1 to get a new EnemyField"))
    choice2 = int(input("Press 2 to get a new EnemyField"))
    choice3 = int(input("Press 3 to get a new EnemyField"))
    choice4 = int(input("Press 4 to get a new EnemyField"))
    choice5 = int(input("Press 5 to quit"))
    while choice != 5:
        if choice ==1:
            choice = print(fillEnemyField(zombies))
    ..............................

A: Your function isn't returning anything, you could return a dictionary and from that later choose what value you want, for example:
Also, make sure to update choice in the while loop, or else you will be stuck in the loop forever.
import random
def fillEnemyField():
    print("Here's your first EnemyField")
    return {"zombies": random.randrange(0, 15),
            "trolls": random.randrange(0, 15),
            "vampires": random.randrange(0, 15),
            "ghosts": random.randrange(0, 15)
            }

def printEnemyField():
    print("Press 1 to get a new EnemyField")
    print("Press 2 to get a new EnemyField")
    print("Press 3 to get a new EnemyField")
    print("Press 4 to get a new EnemyField")
    print("Press 5 to quit")
    choice = int(input("Enter a number: "))
    while choice != 5:
        if choice ==1:
            print(fillEnemyField()['zombies'], "zombies in the field")
        choice = int(input("Enter a number: "))

printEnemyField()

Or
What is probily a better option, you can pass the choice in as an argument and then return that choise, for example:
def fillEnemyField(choise):
    print("Here's your first EnemyField")
    options = {"zombies": random.randrange(0, 15),
               "trolls": random.randrange(0, 15),
               "vampires": random.randrange(0, 15),
               "ghosts": random.randrange(0, 15)
               }
    return options[choise]

def printEnemyField():
    ...
    choice = int(input("Enter a number: "))
    while choice != 5:
        if choice == 1:
            print(fillEnemyField('zombies'), "enemies on the field")
        choice = int(input("Enter a number: "))

A: Try this
import random

def fillEnemyField():
      # Define enemy amounts
      zombies = random.randrange(0, 15)
      trolls = random.randrange(0, 15)
      vampires = random.randrange(0, 15)
      ghosts = random.randrange(0, 15)

      # return enemy amounts so you can use them later
      # if you don't care about these names, you could do something like this
      # return [random.randrange(0, 15), random.randrange(0, 15), random.randrange(0, 15), random.randrange(0, 15]
      return [zombies, trolls, vampires, ghosts]

def printEnemyField():
    # when you do something multiple times, it's cleaner to use a loop
    for x in range(4):
        # this is formating a string, here is a great guide on this
        # https://www.digitalocean.com/community/tutorials/how-to-us-string-formatters-in-python-3
        print("Press {} to get a new EnemyField".format(x+1))
    print("Press 5 to quit") # this print is differnt, so we won't use it in the loop

    fields = fillEnemyField() # get all those enemies we worked so hard to make

    choice = int(input()) # get input from the user
    while choice != 5: # we want to quit on 5
        print(fields[choice-1]) # here we print out the ith value of the array, remember to subract 1 because arrays start at 0
        choice = int(input()) # get more input from the user so our loop doesn't just print forever

printEnemyField() # remember to call your functions from somewhere, otherwise it wont get run


text:
Q: How do you Parse this String in Lua "1 2 3 4"? I am brand new to Lua from a pure VB.Net background.  I have a large file of maplines that I need to iterate through.  The data is in the form of:
;XX.XXX  YY.YYY  Name
;
[Airways]
58.50 -12.44 58.21 -13.73
58.21 -13.73 57.89 -15.02
57.89 -15.02 57.54 -16.30
57.54 -16.30 57.17 -17.58
57.17 -17.58 56.76 -18.84
56.76 -18.84 56.33 -20.10
56.33 -20.10 55.87 -21.35
54.33 -25.02 53.77 -26.22
I have tried this but keep getting an error.
local mapLines = {}

local filePath = system.pathForFile( "data.ini", system.DocumentsDirectory )

local file = io.open( filePath, "r" )

if file then
local contents = file:read( "*a" )

--print( "Contents of " .. filePath )
--print( contents )

io.close( file )

local t = display.newText( "Contents of ", 5, 80, nil, 16 );
t:setTextColor( 255, 255, 136, 255 );
local t = display.newText( filePath, 5, 100, nil, 10 );
t:setTextColor( 255, 255, 136, 255 );

local ylast = 130
for line in io.lines(filePath) do
    local t = display.newText( line, 15, ylast, nil, 14 );
    t:setTextColor( 255, 255, 255 );
    ylast = ylast + 20

    n = tonumber(line);
    if n == nil then

        local f = {}
        s = "1 2 3 4"
        for k, v in string.gmatch(s, "(%w+) (%w+)") do
        f[k] = v
          end

local myLine = newLine(tonumber(f[1]), tonumber(f[2]), tonumber(f[3]), tonumber(f[4]))
        table.insert( mapLines, myLine )
    end
  end
end

-- Example of shape drawing func

local function newLine(x,y,x1,y1)

-- need initial segment to start
local Line = display.newLine( x, y, x1, y1 )

Line:setColor( 30, 155, 30, 100 )
Line.width = 3

return Line
end

Runtime:addEventListener( "enterFrame", mapLines )

Any help would be greatly appreciated!
Dave

A: answering the question in the topic:
local string_to_parse = '1 2 3 4'

for s in string_to_parse:gmatch('%d+') do
   print(s)
end

sample code on codepad

redpajama_set_name: RedPajamaStackExchange


text:
Q: Recycler View is Showing Blank Screen after Resuming the activity

   private void loadFrieghtData() {

        progressLoader.startProgress(Frieght_Details.this);

        RequestQueue queue = Volley.newRequestQueue(Frieght_Details.this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, UrlConstant.FRIEGHT_DETAILS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.optString("status");
                            if (status.equals("1")){

                                JSONArray jsonArray = jsonObject.getJSONArray("data");

                                for (int i =0 ; i< jsonArray.length(); i++){

                                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);

                                    dialogPOJO  leftDashboardPOJO = new dialogPOJO(jsonObject1.optString("id"),
                                            jsonObject1.optString("date"), jsonObject1.optString("credit"),
                                            jsonObject1.optString("confirm_status"));

                                    leftDashboardPOJOSList.add(leftDashboardPOJO);

                                }

                                progressLoader.dismissProgress(Frieght_Details.this);
                                millWiseReportRecyclerView.setAdapter(FrieghtAdapterPOJO);
                                FrieghtAdapterPOJO.notifyDataSetChanged();

                                System.out.println("SOMETHING DATA " + response.toString());

                            }else {

                                progressLoader.dismissProgress(Frieght_Details.this);
                                Toast.makeText(Frieght_Details.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();

                            }

                        }catch (JSONException e){
                            progressLoader.dismissProgress(Frieght_Details.this);
                            System.out.println("paramsparamsparams===" + e.toString());

                            Toast.makeText(Frieght_Details.this, e.toString(), Toast.LENGTH_SHORT).show();

                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                progressLoader.dismissProgress(Frieght_Details.this);
                System.out.println("paramsparamsparams===" + error.toString());

                Toast.makeText(Frieght_Details.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                {
                  /*  params.put("user_id", prefManager.getGSTstate());
                    params.put("godown_id", prefManager.getGodownlocation()); */

                    params.put("godown_id", "3");
                    params.put("user_id", "dddd");
                    params.put("vehicle", "2");

                }

                System.out.println("paramsparamsparams===" + params.toString());
                return params;
            }

        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 8,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        queue.add(stringRequest);

    }

This is my Main Method Code
public class FreightAdapter extends RecyclerView.Adapter<FreightAdapter.ViewHolder> {

    private List<dialogPOJO> list_data;
    private Frieght_Details context;
    private PrefManager prefManager;

    public FreightAdapter(List<dialogPOJO> list_data, Frieght_Details context) {
        this.list_data = list_data;
        this.context = context;
        prefManager = new PrefManager(context);
    }

    @Override
    public FreightAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.frieght_wiseadapterlayout,parent,false);
        return new FreightAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(FreightAdapter.ViewHolder holder, int position) {
        final dialogPOJO  lenaDenaPOJO = list_data.get(position);

        if (position %2 == 1){

            holder.linearLayout_data.setBackgroundColor(context.getResources().getColor(R.color.white));

        }else {

            holder.linearLayout_data.setBackgroundColor(context.getResources().getColor(R.color.colorGrey));

        }

        String countString = lenaDenaPOJO.getCount();

        holder.ordernumber.setText( countString );

        holder.ordernumber1.setText( lenaDenaPOJO.getKey());

        String truck_id = lenaDenaPOJO.getReports();
        String vehicle_status = lenaDenaPOJO.getVehicleStatus();

        System.out.println("VEHICLE_VALE " + vehicle_status + " " + truck_id + " " + countString);

        holder.frieght.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                context.callDialogMethod(countString);

            }
        });

        holder.actionOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                context.CallOkStatus(vehicle_status, countString, truck_id);

            }
        });
    }

    @Override
    public int getItemCount() {
        return list_data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView ordernumber, ordernumber1, frieght, actionOK;
        private Button view_Reports;
        private LinearLayout linearLayout_data;

        public ViewHolder(View itemView) {
            super(itemView);

            ordernumber = itemView.findViewById(R.id.pro_name);
            ordernumber1 = itemView.findViewById(R.id.frieght);
            frieght = itemView.findViewById(R.id.total_qty);
            actionOK = itemView.findViewById(R.id.actionOK);

            linearLayout_data = itemView.findViewById(R.id.linearLayout_data);

        }
    }
}

Here are logs

I/System.out: SOMETHING DATA
{"status":1,"data":[{"id":2876,"credit":1500,"confirm_status":1,"date":"01-01-2021"},{"id":2919,"credit":1900,"confirm_status":1,"date":"02-01-2021"},{"id":2933,"credit":2050,"confirm_status":1,"date":"04-01-2021"},{"id":2964,"credit":3500,"confirm_status":1,"date":"05-01-2021"},{"id":3004,"credit":2450,"confirm_status":1,"date":"06-01-2021"}

And This is my Adapter Code I can't understand What is wrong in this.
Please Help me in this case
I have added image for more details,
When I call Activity First Time it works Perfectly But If call onResume method then There is no data added on Recycler view I can't understand what get wrong in my code


text:
Q: How can I find a rare bug that seems to only occur in release builds? I have a fairly large solution that occasionally crashes. Sadly, these crashes appear to only occur in release build. When I attach the debugger upon crashing, I get the message:

"No symbols are loaded for any call
  stack frame. The source code cannot be
  displayed"

This makes it quite hard to find the cause of the crashes. I am using the default release build settings of visual studio 2008, in which 'debug information format' is set to 'Program Database (/Zi)'.
Do you have any tips that might help me find the bug? For example, could I change some settings in my projects so that the crashes might still occur but get more meaningful information in the debugger?
Update: The problem was a very rarely occurring logic error that in itself should not cause a crash, but apparently caused a crash elsewhere. Solving the logic error solved the crashing behavior.
To anyone that came here looking for a resolution of a similar problem: best of luck, you're in for a rough ride. What eventually helped me locate the problem was adding a lot of bounds checks in the code (that I could enable/disable with preprocessor directives) and compiling for linux and running with gdb/valgrind.

A: First ensure you are building symbols (debug info) for release build, and that the debugger can find them (this may require configuring the symbol path—a symbol server would be better).
Second use the Modules view while debugging to confirm you have the symbols loaded.
The simplest way to get the symbols is to put the .pdb files in the same location as the assemblies.
Check out John Robbins blog for many many more details of doing this.

A: If the code crashes after optimisation is applied (as in the default release), it is most likely that your code is in some way flawed and relies on undefined behaviour which changes between the release and debug build.
Try switching off optimisation in the release build to see if the problem goes away (or switch it on in the debug build to see if it occurs).  If it does, you should still aim to find and fix the bug, but you will at least know to be looking for undefined behaviour.
Set the compiler warning level to maximum (/W4) and warnings as errors (/Wx) and fix all warnings (and not simply by casting everything in sight - think about it!).  When optimisation is applied, you may well get warnings that did not occur in the debug build because of the more extensive code analysis that is performed - this is useful static analysis.
You can if you wish switch debugging on in an optimised build, but it is unlikely that you will be able to follow what is going on since the optimiser may re-order code, and remove code and variables.

A: A few reasons why a debug build might not allow a defect to express itself:

*

*Some debug configurations initialize all variables.

*Debug memory allocations and deallocations might be more forgiving of pointer abuse.

*The debug build might execute at a different speed thus masking a race condition.

Since you are using C++ you might consider using a static analysis tool like valgrind to point out possible uninitialized data and pointer mishandling.
Race conditions may be tracked down by adding log output with time stamps.  You first have to narrow down where in your "large solution" the problem occurs by observing what happened just prior to the crash.  Be sure to use a deferred logging mechanism -- one that does the string processing later or in another thread so it doesn't itself impact the timing too much.

A: Sounds to me like that stack frame was blown.  Trivial to do with a buffer overflow, just copy a large string in a small char[] for example.  That wipes out the return address.  The code just keeps running until the return, then bombs when it pops a bad address off the stack.  Or worse, if the address happens to be valid.
The debugger cannot display anything meaningful since it cannot walk the stack to show you how the code got to the crash location.  The actual crash location doesn't tell you anything.
Tuff as nails to debug.  You have to get it reproducible and you need either stepping or tracing to find the last known-good function.  The one that produces the crash after stepping out of it is the one with the bug.  You can actually see the statement that does the damage, the debugger call stack suddenly goes catatonic.  If you can't get a consistent repro then a thorough code review is all that's left.  You can justify the time by calling it a "security review".  Good luck with it.

A: Did you know you can still debug release builds? Just hit F5 (rather than CTRL+F5) to run in debug.
Is it repeatable i.e. are you doing something specific when it goes bang?
If so, set a breakpoint in your code before the crash and hit F5 to run in debug (make sure you're using your release build though). Then step through until your app crashes. I generally find this faster than adding logging and debug print statements.
If not, just running in debug mode will sometimes catch the error and halt on the offending line.
Failing that, Richard and Amar's answers are good :-)

A: An uninitalized variable (pointer perhaps) could also be causing the problem.  Perhaps you should run a static analysis program over your code - CppCheck isn't bad.


text:
Q: Dockerize pt-kill as daemon I am coverting my infra. to containers. I have a couple daemons that right now live in rc.local but I want to do this the docker way
here are the commands:
sudo /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --daemonize --busy-time 30 --kill --print h=db-1,u=master,p=password,P=3306
sudo /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --daemonize --busy-time 30 --kill --print h=db-2,u=master,p=password,P=3306

What is the proper way to do this via docker?

A: AFAIK Percona doesn't provide an official Docker image for the toolkit but, as suggested by @VonC in his answer as well, you could try using the Dockerfile provided in their Github repository, it will give you a base image with the necessary tools installed, including pt-kill. To run pt-kill, you will need to provide the necessary command when running your docker container, or extend the image by including a CMD in your Dockerfile with the necessary information. For reference, I build the aforementioned Dockerfile:
docker build -t local/pt:3.5.0-5.el8 .

And was able to using pt-kill against a local docker based MySQL database running the following command from my terminal:
docker run -d local/pt:3.5.0-5.el8 /usr/bin/pt-kill --match-command Query --victims all --busy-time 5s --print h=172.17.0.2,D=local,u=local,p=local,P=3306

I tested it running the following sentence from MySQL Workbench:
SELECT SLEEP(10)

Which produces the following output from pt-kill:
# 2023-01-01T22:12:33 KILL 16 (Query 5 sec) SELECT SLEEP(10)
LIMIT 0, 1000
# 2023-01-01T22:12:35 KILL 16 (Query 7 sec) SELECT SLEEP(10)
LIMIT 0, 1000
# 2023-01-01T22:12:37 KILL 16 (Query 9 sec) SELECT SLEEP(10)
LIMIT 0, 1000

The way in which this container could be run will depend on your actual infrastructure.
I assume by the existence of the --rds flag in your command that you are connecting to an Amazon RDS instance.
You have many ways for running containers in AWS (see for instance this blog entry, for naming some of them).
In your use case probably the way to go would be using ECS running over EC2 compute instances (the Fargate serverless option doesn't make sense this time), or even EKS, although I think it would be overkill.
You could provision an EC2 instance, install docker, and deploy locally your containers as well, but probably it would a less reliable solution than using ECS.
Just in case, and the same applies if running your containers from an on-premise machine, you will need to launch the containers at startup. In my original answer I stated that in the end you probably will need to use rc.local or systemd to run your container, perhaps by invoking an intermediate shell script, that will launch the actual container using docker run, but thinking about it I realized that the dependency with the docker daemon - it should be running to run your container - could be a problem. Although some kind of automation could be required, consider running your container indicating always or unless-stopped as the --restart policy.
As you suggested, you could use docker-compose for defining both daemons too. The following docker-compose.yaml file could be of help:
version: '3'
x-pt-kill-common:
  &pt-kill-common
  build: .
  restart: always

services:

  pt-kill-db-1:
    <<: *pt-kill-common
    command: /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --busy-time 30 --kill --print h=db-1,u=master,p=password,P=3306

  pt-kill-db-2:
    <<: *pt-kill-common
    command: /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --busy-time 30 --kill --print h=db-2,u=master,p=password,P=3306

We are building the docker image in compose itself: it assumes the existence of the mentioned Percona toolkit Dockerfile in the same directory in which the docker-compose.yaml file is located. You can build the image and publish it to ECR or wherever you see fit and use it in your docker-compose.yaml file as an alternative if you prefer:
version: '3'
x-pt-kill-common:
  &pt-kill-common
  image: aws_account_id.dkr.ecr.region.amazonaws.com/pt:3.5.0-5.el8
  restart: always

services:

  pt-kill-db-1:
    <<: *pt-kill-common
    command: /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --busy-time 30 --kill --print h=db-1,u=master,p=password,P=3306

  pt-kill-db-2:
    <<: *pt-kill-common
    command: /usr/bin/pt-kill --rds --match-command Query --victims all --match-user phppoint --busy-time 30 --kill --print h=db-2,u=master,p=password,P=3306

In order to reuse as much code as possible, the example uses extension fragments, although of course you can repeat the service definition if necessary.
Note as well that we get rid of the --daemonize option in the command definition.
In any case, you will need to configure your security groups to allow communication with the RDS database.
Having said all that, in my opinion, your current solution is a good one: although especially using ECS could be a valid solution, probably provisioning a minimal EC2 instance with the necessary tools installed could be a cheaper and simple option than running them in containers.

A: As mentioned in "How to use Percona Toolkit in a Docker container?", you might need to build your own image, starting from this Dockerfile
The thread mentions The docker image under perconalab (perconalab/percona-toolkit) seems to be the same but isn't.
Maybe perconalab/pmm-client is a better option.


text:
Q: Visual Studio 2017 doesn't show edited/added icon I am connected to 2013 TFS on Visual Studio 2017. Everything is well except I don't see the icons next to the files.
It should have the lock icon on the unedited files, check for edited, and the plus icon for the added files. I don't see any of these icons.
If I edit a file, it shows up on the Pending change. but if I add a new one, I need to manually add it to TFS.
any ideas??

A: Seems you are talking about the icons as below:

If I edit a file, it shows up on the Pending change. but if I add a
new one, I need to manually add it to TFS.

According to your description, this may related to source control binding of the project. Try to unbind/bind the project which may do the trick.
Under File > Source Control > Advanced > Change Source Control.
Another way is editing .csproj file. There is a section missing in the .csproj file that should look something like this:
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>

It only affects the display of the Source Control status in the Solution Explorer as noted you can already perform other source control tasks on the project. It's not much but worth fixing as it's a good visual check that everything is being controlled.
More details you could also take a look at this similar question: No padlock icon for some projects in a source controlled solution


text:
Q: SharePoint Server 2010 to the Cloud (Azure) As part of our implementation of SharePoint 2010 (Server), I am tasked with investigating the option to deploy SharePoint 2010 via the cloud.  Does anyone have the benefits and/or limitations for migrating a SharePoint farm consisting of up to seven servers (initially) to Windows Azure?  If Azure is not the right cloud product, what IaaS provider would be a better fit?
Is there a significant benefit to placing the WFE servers in the cloud pointing back to App Servers on-premises?
I am sure there are plenty of questions I am neglecting, so please be free to offer as much ancillary information as possible.

A: You can't host SharePoint on Azure, and putting the WFEs in the cloud with on-premise SQL would not be workable from a performance stand-point or a supported configuration. If you want a cloud hosting solution and Office365 Enterprise won't fit the bill consider Amazon or Rackspace virtual servers. Make sure you contact Microsoft to validate the licensing required to cover your farm - with cloud hosting it can get tricky.


text:
Q: How can I mount a subdirectory from a hard drive to a separate directory I have this line in fstab
/dev/sda1 /Tera ntfs-3g uid=www-data,gid=www-data,umask=007 0 0

because /Tera/OC has to have permissions 770 but since the drive is NTFS, I can't set it explicitly. Is there a way for me to mount the folder OC on its own with the specified parameters and a different folder with different permissions? I considered splitting the partitions but I'd rather not divide the space.

A: Try adding the following to your fstab:
/Tera/OC /mount/path/for/OC none bind,uid=www-data,gid=www-data,umask=770 0 0


text:
Q: How can I dynamically change the UIID for the commands that go in the toolbar? Currently I am adding the effects to an Image and then I use that as the pressedIcon Image.

A: Try:
Button btn = toolbar.findCommandComponent(cmd);

This will allow you to manipulate the button as you choose (e.g. setUIID etc.).


text: Q: Measuring reverse recovery time of a diode What is the exact formula for reverse recovery time of a diode? I've read a bunch of articles regarding this question, and each of them answers differently -- the time interval between peak negative current and its either 10, 15 or 20% value. What is the precise value of a said percentage?


text:
Q: very interesting use of return keyword in php as we know, return keyword will RETURN some value and exit current function. Mean, that this one used only inside some functions.
BUT, I saw some php-dev's use return keyword outside functions, even in index.php file (in root of web server). What is that mean???? By the way, maybe it's logical to require some file inside function, but this style isnt mine.

A: There's not much more to say than what the docs do.
About the common usage of return:

If called from within a function, the return statement immediately
  ends execution of the current function, and returns its argument as
  the value of the function call. return will also end the execution of
  an eval() statement or script file.

About the less common usage:

If called from the global scope, then execution of the current script
  file is ended. If the current script file was included or required,
  then control is passed back to the calling file. Furthermore, if the
  current script file was included, then the value given to return will
  be returned as the value of the include call. If return is called from
  within the main script file, then script execution ends. If the
  current script file was named by the auto_prepend_file or
  auto_append_file configuration options in php.ini, then that script
  file's execution is ended.

A: Its documented somewhere within the manual
// myFile.php
return array( 'foo' => 'bar');

// somewhere else
$config = include 'myFile.php';
echo $config['foo'];

If you use return in the main scope php will leave the file inclusion and use the value as "return value" of the inclusion (include[_once](), require[_once]()).

A:
BUT, I saw some php-dev's use return keyword outside functions, even
  in index.php file (in root of web server). What is that mean???

You know the common purpose. But what you are asking is used to prevent code injection in php include files. Take a look at this post which explains it:
Prevent Code Injection in PHP include files

While discussing Coding Standards it was not long ago I argued against
  adding ?> at the end of php files. But miqrogroove pointed to me an
  interesting aspect why it actually can make sense to have it and an
  additional return statement at the end of each file: That one (merely
  the return statement) can prevent an attacker to append payload code
  to existing PHP files, for example known include files. The
  countermeasurement is pretty easy, just add a return statement at the
  end of the file. It will end the include "subroutine":

Example:
  /* all the include file's php code */
  return;
?>


text:
Q: Blank screen after rendering text I have opened a window which shows two rects on the screen then using SDL_TTF to show the mouse position on the screen.
The bit I am having hard time understanding is why after rendering text the the two rects before it do not show up.
I am using SDL_RenderFillRect to draw two rects on screen
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, rect1);

SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, rect2);

Code for rendering the text is
// define string with mouse x, y coords
sprintf(someString, "x: %d, y: %d", mouse.x, mouse.y);
SDL_Point textPos = {10, 10};
WriteText(renderer, font, someString, textPos, (SDL_Color){255, 255, 255, 255});
SDL_Surface *fontSurface = TTF_RenderText_Blended(font, someString, COLOR_BLACK); // create font surface
SDL_Texture *fontTexture = SDL_CreateTextureFromSurface(renderer, fontSurface);  // create the texture

// get clip width and height from fontsurface clip rect
SDL_Rect *fontRect = &fontSurface->clip_rect;
fontRect->x = pos.x;
fontRect->y = pos.y;

SDL_RenderCopy(renderer, fontTexture, NULL, fontRect); // copy text to the renderer
// delete surface and texture
SDL_FreeSurface(fontSurface);
SDL_DestroyTexture(fontTexture);

It to shows the mouse positon top left corner of the window. However this makes the rest of the window blank.
To prevent this my work around is having to draw something on the screen after calling SDL_RendererCopy (and weirdly before calling SDL_DestroyTexture too) For example drawing single point
...
SDL_RenderCopy(renderer, fontTexture, NULL, fontRect); // copy text to the renderer

// why is this needed??
SDL_RenderDrawPoint(renderer, 0, 0);

// delete surface and texture
SDL_FreeSurface(fontSurface);
SDL_DestroyTexture(fontTexture); // have to draw a point before this
...

This then shows the two rects rendered before the text
If I set dstRect to NULL when calling SDL_RenderCopy then the text spans the whole window but I can see what was rendered before underneath the text.
Why am I having to draw a point after calling SDL_RenderCopy to stop what was rendered before from not showing up?
NOTE: Link to full source code https://pastebin.com/tRSFT0PV

A: This is a bug in SDL 2.0.10. It's fixed by https://hg.libsdl.org/SDL/rev/6ee12b88beed and this fix will ship with 2.0.11. Sorry about that!


text:
Q: How to disable php language extension (eg. abc.php.fr)? by default apache will load php interpreter with .php extension. Somep\how php interpreter also called with this kind of extension .php.fr . How to disable this language extension?

A: The .fr is being interpreted as French during content negotiation by Apache. This is probably because you have Options +MultiViews and MultiviewsMatch Handlers are both set. Getting rid of either should stop .php.fr from working, but changing this may break other pages. (Assumably, you enabled both for a reason). Also, I'm not completely sure if MultiVideosMatch applies to PHP, but Options +MultiViews definitely does.
If you're trying to make sure people can't upload PHP files and have your webserver execute them, instead of just blacklisting extensions, use php_admin_flag engine off to turn off PHP in that location:
<Location /uploads>
    php_admin_flag engine off
</Location>

A: you can setup the extensions interpreted by Apache on 2 Places.

*

*httpd.conf
AddType application/x-httpd-php .phpx
Will load .phpx files as PHP Scripts

*mime.type
application/x-httpd-php phpx


text:
Q: C++ class with static pointer I don't understand pointers and references very well yet, but I have a class with static methods and variables that will be referenced from main and other classes. I have a variable defined in main() that I want to pass to a variable in this class with static functions. I want those functions to change the value of the variable that is seen in the main() scope.
This is an example of what I am trying to do, but I get compiler errors...
class foo
{
    public:

    static int *myPtr;

    bool somfunction() {
        *myPtr = 1;
        return true;
    }
};

int main()
{
    int flag = 0;
    foo::myPtr = &flag;

    return 0;
}

A: Provide the definition of the static variable outside the class as:
//foo.h
class foo
{
    public:

    static int *myPtr; //its just a declaration, not a definition!

    bool somfunction() {
        *myPtr = 1;
        //where is return statement?
    }
};  //<------------- you also forgot the semicolon

/////////////////////////////////////////////////////////////////
//foo.cpp
#include "foo.h"  //must include this!

int *foo::myPtr; //its a definition

Beside that, you also forgot the semicolon as indicated in the comment above, and somefunction needs to return a bool value.

A: #include <iostream>
using namespace std;

class foo
{
public:

static int *myPtr;

bool somfunction() {
    *myPtr = 1;
    return true;
}
};
//////////////////////////////////////////////////
int* foo::myPtr=new int(5);     //You forgot to initialize a static data member
//////////////////////////////////////////////////
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}


text:
Q: Misunderstanding of class of returned instance from generic method of class called from subclass instance in Java Example:
interface S {}

interface SS extends S {}

abstract class A<T extends S> {
    T get() {…}
}

abstract class B<BT extends SS> extends A<BT> {}

Why does ((B)someInstanceOfB).get() return an object of type S (and we should cast it to SS manually), when the compiler could determine that returned object is at least of type SS?
Why doesn't the compiler make implicit class cast to have clearer code? The code is of version 1.5+ and this is not secret for compiler. (Solved)
Update: Why doesn't the compiler compile B class as it implicitly has method BT get() { return super.get(); } ?
Is this problem solved in Java 1.7+?

A: By casting to B you're using a raw type.
Using a raw type removes all generic information from the object, no matter where it is.
That means that for the raw type B the get method looks like it is returning a S (because that's the erasure (i.e. the actual type used at runtime) of the type parameter T).
To avoid this, never use raw types! They are meant exclusively for backwards compatibility and interaction with legacy code.
Cast to B<? extends SS> instead.
And no: this problem will probably never be "solved" in any future version of Java, as it's non-existing when you use generics correctly.
Regarding Update: no, B does not have a method BT get(). It has a method T get() where T is bound to the type parameter BT which has a lower bound SS. But since all generic type information is discarded when you use a raw type, T will still fall back to the original erasure, which is S.
The rule is quite simple and basically says "when you use a raw type it acts as if the class has no generics at all". The implications, however, are not always obvious, as in this case.

A: You didn't parameterize your instance of B.
Let's say you have the class C implementing SS:
Then, new B<C>().get(); would return an object of type C.
On the new B().get(); line, your IDE must have told you "B is a raw type. References to generic type B should be parameterized.".


text:
Q: lighttpd changing the root folder and the alias don't work Following is my lighttpd.conf file
I changed the root folder and I declared an alias and both don't work.
/localhost/ is still "/var/www/html"
I also added a redirection for the C code
The ".c" redirection works OK.

server.modules = (
 "mod_access",
 "mod_alias",
 "mod_compress",
  "mod_redirect",
            "mod_accesslog",
            "mod_fastcgi",
            "mod_rewrite",
            "mod_auth")

server.document-root        = "/usr/share/phpmyadmin"
server.upload-dirs          = ( "/var/cache/lighttpd/uploads" )
server.errorlog             = "/var/log/lighttpd/error.log"
server.pid-file             = "/var/run/lighttpd.pid"
server.username             = "www-data"
server.groupname            = "www-data"
server.port                 = 80

alias.url = ( "/phpmyadmin/" => "/usr/share/phpmyadmin/" )

fastcgi.debug = 1
fastcgi.server = (
    ".c" => (
    "echo.fcgi.handler" => (
        "socket" => "/tmp/cpp.fcgi.socket",
        "check-local" => "disable",
        "bin-path" => "/home/shlomo/cpp/echo.fcgi",
        "max-procs" => 1
    )
  )

)
index-file.names            = ( "index.php", "index.html", "index.lighttpd.html" )
url.access-deny             = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )

compress.cache-dir          = "/var/cache/lighttpd/compress/"
compress.filetype           = ( "application/javascript", "text/css", "text/html", "text/plain" )

# default listening port for IPv6 falls back to the IPv4 port
## Use ipv6 if available
#include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port
include_shell "/usr/share/lighttpd/create-mime.assign.pl"
include_shell "/usr/share/lighttpd/include-conf-enabled.pl"


text:
Q: AJAX Load More on Custom Post Grid I cant get this to work. I am trying to create a custom post type grid with ajax load more button to show 6 mosts per page in the grid. I can get the posts to show but the Load More button just scrolls to the top of the page like a normal anchor link.
My theme code:

          <?php
    $postsPerPage = 6;
    $args = array(
        'post_type' => 'dslc_projects',
        'posts_per_page' => $postsPerPage,
        'offset' => $offset
    );
    $loop = new WP_Query($args);

    while ($loop->have_posts()) : $loop->the_post();
?>

                <a href="<?php the_permalink() ?>">

<?php the_title() ?>

View project...

<?php
    endwhile; ?>

    <?php echo '
Load More
';
    wp_reset_postdata();
?>

My PHP:
function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");

    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'offset' => $offset
    );

    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post();
       the_content();
    }

    exit;
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

My JS:
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
    var page = 1; // What page we are on.
    var ppp = 6; // Post per page

    $("#more_posts").on("click",function(){ // When btn is pressed.
        $("#more_posts").attr("disabled",true); // Disable the button, temp.
        $.post(ajaxUrl, {
            action:"more_post_ajax",
            offset: (page * ppp) + 1,
            ppp: ppp
        }).success(function(posts){
            page++;
            $(".tabgrid").append(posts); // CHANGE THIS!
            $("#more_posts").attr("disabled",false);
        });

   });

can anyone see what could be wrong here?

A: Your anchor is just a normal anchor and href="#" means scroll to top. Your JS code is trying to add a handler to and element with the id "#more_posts" but your anchor doesn't have an id.
Try replacing your anchor with
Load More


text:
Q: How to call a custom Oracle function returning a value from JPA I have a custom function in oracle returning a number after deleting records. I could get a value in sql_plus such as
call my_function(4) into :out_number;

where out_number is a variable defined as number.
I could verify out_number has a value when I do "PRINT OUT_NUMBER."
My question is how to call this function from JPA.
I've tried like
Query query = em.createNativeQuery("{call my_function(?)}");
query.serParameter(1, 4);
return query.executeUpdate();

and got an error basically my_function is not defined. How can I get a return value as in CALL...INTO on SQL_PLUS?
If this method is not desirable, can someone please recommend any suggestion? JPA is the only option for me at this moment. I could create a stored procedure but I'm not sure if I can get a return value from it since OUT parameters are not supported.
Thanks for your help in advance!

A: I used this to execute native functions in oracle:
Query query = em.createNativeQuery("select my_function(:param) from dual");
query.setParameter("param", 4);
return query.getSingleResult();

A: From https://vladmihalcea.com/how-to-call-oracle-stored-procedures-and-functions-from-hibernate/:
First, we can simply call the Oracle function just like any other SQL query:
BigDecimal commentCount = (BigDecimal) entityManager
    .createNativeQuery(
        "SELECT fn_count_comments(:postId) FROM DUAL"
    )
    .setParameter("postId", 1L)
    .getSingleResult();

Another approach is to call the database function using plain JDBC API:
Session session = entityManager.unwrap( Session.class );

final AtomicReference<Integer> commentCount =
    new AtomicReference<>();

session.doWork( connection -> {
    try (CallableStatement function = connection
            .prepareCall(
                "{ ? = call fn_count_comments(?) }"
            )
        ) {
        function.registerOutParameter( 1, Types.INTEGER );
        function.setInt( 2, 1 );
        function.execute();
        commentCount.set( function.getInt( 1 ) );
    }
} );

A: When using Spring Data JPA / Spring JDBC you can use SimpleJdbcCall for calling functions and procedures.
For such function header:
FUNCTION get_text (p_param IN VARCHAR2) RETURN VARCHAR2

Use this call:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Repository;

@Repository
public class MyRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String callGetTextFunction(String param) {
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
                .withCatalogName("PKG_PACKAGE") //package name
                .withFunctionName("GET_TEXT"); //function name
        SqlParameterSource paramMap = new MapSqlParameterSource()
                .addValue("p_param", param));
        //First parameter is function output parameter type.
        return jdbcCall.executeFunction(String.class, paramMap));
    }

}

A: If you are using EclipseLink you can use a StoredFunctionCall object to call a stored function such as this.
You could also define it as a named query using the @NamedStoredFunctionQuery.

A: It's a quite old question but I have not found here the proper solution...
Here is a code that works in my project:
    EntityManager em;
    String functionName = "NameOfStoredFunction";
    Map<String, Object> arguments = new LinkedHashMap();
    arguments.put("nameOfArgument", "value");
    StoredFunctionCall functionCall = new StoredFunctionCall();
    functionCall.setProcedureName(functionName);
    functionCall.setResult("RESULT", String.class);

    for(String key : arguments.keySet()){
        functionCall.addNamedArgumentValue(key, arguments.get(key));
    }

    ValueReadQuery valQuery = new ValueReadQuery();
    valQuery.setCall(functionCall);

    Query query = ((JpaEntityManager)em.getDelegate()).createQuery(valQuery);

    String call_result = (String)query.getSingleResult();


text:
Q: Certificate pinning not working in Native android Mobilefirst 8.0 app In IOS the certificate pinning is working. But in android certificate pinning is not working.
Below is the code snippet of certificate pinning.
try {
           WLClient wlClient = WLClient.createInstance(context);
          WLClient.getInstance().pinTrustedCertificatePublicKey("ProdCert.cer");

        } catch (Exception e) {
            Log.d("MFPClient",e.toString());
            Toast.makeText(this, e.toString(),Toast.LENGTH_LONG).show();
        } finally {
            try {

                URI url = new URI("/adapters/TestAdapter/getFeed");
                WLResourceRequest request = new WLResourceRequest(url,WLResourceRequest.GET);
                request.send(new WLResponseListener() {
                    @Override
                    public void onSuccess(WLResponse wlResponse) {
                        Log.d("MFPClient",wlResponse.toString());
                        // Toast.makeText(context,wlResponse.toString(),Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onFailure(WLFailResponse wlFailResponse) {
                        Log.d("MFPClient",wlFailResponse.toString());
                        // Toast.makeText(context, wlFailResponse.toString(),Toast.LENGTH_LONG).show();
                    }
                });
            } catch (Exception e) {
                Toast.makeText(this, e.toString(),Toast.LENGTH_LONG);
            }
        }

Below is the Logs at the client side
09-20 20:20:16.460 31459-31459/? I/FtBuild: getRomVersion mRomVer=3.6
09-20 20:20:16.608 31459-31459/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
09-20 20:20:16.623 31459-31459/? D/FEEDBACK: analyticsUrl=null analyticsApiKey=null
09-20 20:20:16.624 31459-31459/? W/FEEDBACK: Failed to invoke feedback mode since Analytic context is null
09-20 20:20:16.637 31459-31459/? D/OpenSSLLib: OpensslErr:Module:12(175:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:175;Function:ASN1_get_object
The above is the logs that is different from the app logs without certificate pinning. Remaining contains the server informations.
In the above code I see a OpensslErr. How to be sure that certificate pinning is happening successfully in native android client side code. There is no exception associated with the logs. That means that, the file is there and it is not invalid cert. But how to be sure that MFP Certificate pinning is successfully happened.
Thanks in advance


text:
Q: Symfony 1.4: Error in dev.php mode. Works in non-dev.php mode I created a module in Symfony 1.4. It works as expected. Nevertheless, when I'm in the dev.php mode, I get a syntax error.
Let's see:
http://honeylumpi.mobi/dev.php/panelparameter
NOTE: panelparameter is the admin-module that I created.

I get:
Parse error: syntax error, unexpected T_STRING in /home/lola/hl/honey-lumpi/cache/cms/dev/modules/autoPanelparameter/actions/actions.class.php on line 66

Now, at line 66 of the  actions.class.php I get:
Warning: stream_get_contents() expects parameter 1 to be resource, null given in  /home/lola/hl/honey-lumpi/lib/model/sitebuilder/PanelParameter.php on line 22

And in line 22 of PanelParameter.php:
/**
 * Returns the serialized value.
 *
 * @return string
 */
public function getSerializedValue ()
{
    $res = parent::getValue();
    $retval = stream_get_contents($res);   <-- This is line 22!
    rewind($res);
    return $retval;
}

I added come echoes, and, in fact, is null. But I don't know why. I believe that that code is auto-generated by Symfony. I don't know how to solve that problem. Again, the module works fine, but in dev.php gives me that error.  I cleared cache, etc.
EDIT:
This is all the code of the /home/lola/hl/honey-lumpi/lib/model/sitebuilder/PanelParameter.php:
<?php

 /**
 * Subclass for representing a row from the 'PanelParameter' table.
 *
 *
 *
 * @package lib.model
 */
 class PanelParameter extends BasePanelParameter
{
    private $condition;

/**
 * Returns the serialized value.
 *
 * @return string
 */
public function getSerializedValue ()
{
    $res = parent::getValue();
    $retval = stream_get_contents($res);
    rewind($res);
    return $retval;
}

/**
 * Sets the value already serialized.
 *
 * @param string $v
 */
public function setSerializedValue ($v)
{
    parent::setValue($v);
}

/**
 * Returns the value of the parameter.
 *
 * @return mixed
 */
public function getValue ()
{
    // get serialized value
    $v = $this->getSerializedValue();

    // unserialize
    $value = @unserialize($v);

    // check for error
    if (false === $value)
    {
        if ('b:0;' != $v)
        {
            if (PHP_VERSION_ID < 50300)
            {
                gxLog::a(__CLASS__, "cannot unserialize parameter #{$this->id} {$this->name} value:{$v}");
                $value = null;
            }
            else
            {
                // try to fix array indexes
                $cb = create_function('$m', 'return "s:".strlen($m[1]).":\"$m[1]\"";');
                $v = preg_replace_callback('/i:([0-9]{12,})/', $cb, $v);
                $value = @unserialize($v);
                if (false === $value)
                {
                    gxLog::a(__CLASS__, "cannot unserialize parameter #{$this->id} {$this->name} value:{$v}");
                    $value = null;
                }
            }
        }
    }

    // return unserialized value
    return $value;
}

/**
 * Sets the value for the parameter.
 *
 * @param mixed $v
 */
public function setValue ($v)
{
    $value = @serialize($v);
    parent::setValue($value);
}

/**
 * Returns the name of the parameter.
 *
 * @return string
 */
public function __toString ()
{
    return $this->getName();
}

/**
 * Returns the condition object.
 *
 * @return gxSiteCondition
 */
public function getCondition ()
{
    if (!isset($this->condition))
    {
        // no condition is true always
        $condition = new gxSiteCondition;

        $cond = parent::getCond();
        if (!is_null($cond))
        {
            // unserialize
            $condition = gxSiteCondition::createFromJson($cond);
        }

        // store
        $this->condition = $condition;
    }

    return $this->condition;
}

/**
 * Sets the condition.
 *
 * @param gxSiteCondition $c
 */
public function setCondition ($c)
{
    if (!($c instanceof gxSiteCondition)) throw new Exception ('parameter is not gxSiteCondition');

    // serialize
    $cond = $c->toJson();

    // store
    $this->condition = $c;

    // store condition
    parent::setCond($cond);
}

/**
 * Checks the condition in the provided context.
 *
 * @param sfContext $context
 */
public function checkCondition (sfContext $context)
{
    // get condition
    $condition = $this->getCondition();

    // evaluate condition
    return $condition ? $condition->evaluate($context) : true;
}

/**
 * Returns true if the provided condition is contained
 * in this object's condition.
 *
 * @param gxBasicCondition $c
 * @return boolean
 */
public function containsCondition (gxSiteCondition $c)
{
    // get condition
    $condition = $this->getCondition();

    // check if contained condition
    return $condition ? $condition->contains($c) : true;
}

/**
 * Set default value for condition if new and not set.
 *
 * @param PropelPDO $con
 * @return int
 */
public function save (PropelPDO $con = null)
{
    if ($this->isNew() && !$this->isColumnModified(PanelParameterPeer::COND))
    {
        $this->setCondition(new gxSiteCondition);
    }

    return parent::save($con);
}

/**
 * Sets contents of passed object to values from current object.
 *
 * If desired, this method can also make copies of all associated (fkey referrers)
 * objects.
 *
 * @param      object $copyObj An object of PanelParameter (or compatible) type.
 * @param      boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
 * @throws     PropelException
 */
public function copyInto($copyObj, $deepCopy = false)
{

    $copyObj->setName($this->name);

    $copyObj->setSerializedValue($this->getSerializedValue());

    $copyObj->setCond($this->cond);

    $copyObj->setPanelId($this->panel_id);

    $copyObj->setNew(true);

    $copyObj->setId(NULL); // this is a pkey column, so set to default value

}
}

A: I didn't know sitebuilder to make symfony website, I don't know what is generated from this tool.
But did you try to rebuild your model ? ./symfony propel:build --all-classes
Is it a generated class from sitebuilder/propel or does it come from the sf1.0 import?


text:
Q: text with unicode escape sequences to unicode in python suppose I have the string
test
'\\u0259'

Note the escaped backslash.
How do I convert it to the respective unicode string?

A: >>> print('test \\u0259'.decode('unicode-escape'))
test ə


text:
Q: Regex mask with varying ignored characters I have a  series of strings which look something like this:
foobar | ABC Some text 123
barfoo | DEF Some te 456

And I want to mask it such that I get the results
ABC123
DEF456

respectively. The text in between will always be a substring Some text which could potentially contain numbers (e.g. S0m3 t3xt or S0m3 t3). It will always be a substring starting from the left, so never me te.
So clearly I need to start the Regex with something like
(?<=| )[A-Z]{3}

which gets me ABC and DEF but I am at a loss of how to effectively concatenate the numbers at the end of the string.
Is there any way to do this with a single expression?

A: See http://regexr.com?375u8
(?<=| )([A-Z]{3}).*(\d{3})

This will give you three characters in the range of A-Z and three numbers in two capturing groups, allowing you to use these groups to concatenate both to your desired output: $1$2
This will even work if your Some text contains three numbers inbetween.
In case you want to replace everything with both of your capturing groups, add .* in front of the regex:
.*(?<=| )([A-Z]{3}).*?(\d{3})

A: Another javascript version
[
 'foobar | ABC Some text 123',
 'barfoo | DEF Some te 456'
].map(function(v) {
  return v.replace(/^.*\| ([A-Z]{3}) .* (\d{3})$/, '$1$2');
})

Gives
["ABC123", "DEF456"]


text:
Q: v-for and computed properties calling methods I'm trying to update some properties on a VueJS object list, but I'm having some glitches.
Here's the HTML:

Total Chats: {{ chats.length }} ({{ unreadCount }} unread)

    <button v-on:click="__addChat(true)">Add a Chat</button>
    <button v-on:click="__makeAllRead">Read All</button>

{{ $data | json }}

                Message {{ chat.id }}
                (UNREAD)

And the Vue code:
var vm = new Vue({

    el: '#el',

    data: {

        nextID : 2,

        chats: {
            '6fc5gh4j3kl_FIRST': {
                id : 1,
                unread : true,
                body : Date(),
            }
        },

    },

    methods: {

        __addChat: function (unread) {

            var chat = {

                id : this.nextID++,
                unread : unread,
                body : Date(),

            };

            this.chats[this.__makeHash()] = chat;

            console.log(this.chats);
        },

        __makeAllRead : function() {

            console.log(Object.keys(this.chats));

            for ( var key in Object.keys(this.chats) ) {

                // if any tests are invalid
                if ( this.chats.hasOwnProperty(key) ) {

                    this.chats[key] = true;

                }

            }

        },

        __countUnread : function() {

            var unread = 0;

            for ( var key in Object.keys(this.chats) ) {

                // if any tests are invalid
                if ( this.chats.hasOwnProperty(key) && this.chats[key].unread ) {

                    unread++;

                }

            }

            return unread;

        },

        __makeHash: function() {
            return '6fc5gh4j3kl1AZ0' + Math.floor((Math.random() * 100) + 1);
        },
    },

    ready: function() {
        this.__addChat(false);
    },

    computed: {
        unreadCount: function () {
            console.log('counting...');
            return this.countUnread();
        }
    }
});

Here's a Fiddle: http://jsfiddle.net/522aw2n5/7/
Things I cannot understand/fix on this code:
1) A computed property using a method to update the count
2) It displays only the object manually created, not the dynamically ones.
3) I cannot make all messages read by clicking a button.
This is Vue 1.0.0 RC2.
Could you, please, tell me what Am I doing wrong?

A: Answered on VueJS's Gitter
HTML

Total Chats: {{ totalChats }} ({{ unreadCount }} unread)

    <button v-on:click="__addChat(true)">Add a Chat</button>
    <button v-on:click="__makeAllRead">Read All</button>

{{ $data | json }}

                {{ chat.id }}
                (UNREAD)

Vue Code
var vm = new Vue({

    el: '#el',

    data: {

        nextID : 2,

        chats: {
            '6fc5gh4j3kl_FIRST': {
                id : 1,
                unread : true,
                body : Date(),
            }
        },

    },

    methods: {

        __addChat: function (unread) {

            var chat = {

                id : this.nextID++,
                unread : unread,
                body : Date(),

            };

            this.$set('chats.' + this.__makeHash(), chat);

        },

        __makeAllRead : function() {

            console.log(Object.keys(this.chats));

            for ( var key in this.chats ) {

                // if any tests are invalid
                if ( this.chats.hasOwnProperty(key) ) {

                    this.chats[key].unread = false;

                }

            }

        },

        __makeHash: function() {
            return 'fc5gh4j3kl1AZ0' + Math.floor((Math.random() * 100) + 1);
        },
    },

    ready: function() {
        this.__addChat(false);
    },

    computed: {
        totalChats: function() {
            var size = 0, key;
            for (key in this.chats) {
                if (this.chats.hasOwnProperty(key)) size++;
            }
            return size;
        },

        unreadCount: function () {

            var unread = 0;

            for ( var key in this.chats ) {

                // if any tests are invalid
                if ( this.chats.hasOwnProperty(key) && this.chats[key].unread ) {

                    unread++;

                }

            }

            return unread;

        }
    }
});


text:
Q: Is it thread safe when adding FiterProvider on objectMapper on perRequest basis in spring mvc? I have following  way of adding Custom Object Mapper.

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.CMSMappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jsonMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

and then in controller I am using
@Autowired
  private ObjectMapper jsonMapper;
in one of the action methods I am
@RequestMapping(produces = "application/json", method = RequestMethod.GET)
public
@ResponseBody
Response get(){
    jsonMapper.setFilters(new SimpleFilterProvider().addFilter(dynamic_per_request));
    return service.get();
}

I am just worried it will not be thread safe. Is it true? If yes how can I make it thread safe?

A: No, you should not handle it that way. You are changing configuration on the fly, but it is quite possible that another request comes by and changes it to something else before first request has actually used the filter.
Instead, you should implement thread-safe FilterProvider that can resolve your filters dynamically, using something like ThreadLocal for passing information you need to pass.


text:
Q: "Unable to simultaneously satisfy constraints." in SWTableViewCell for Xamarin.iOS I am porting SWTableCell (GitHub) to Xamarin.iOS. I already implemented all code in C#, but I still have a problem with constraints.
I am getting this message:
2014-06-23 11:58:59.004 Mark5MobileiOS[1423:70b] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0xe5cd1b0 UIView:0xe5cc310.right == DocumentListViewCell:0xe5c2280.right>",
"<NSLayoutConstraint:0xe5cc370 H:[DocumentListViewCell:0xe5c2280]-(820)-[UIView:0xe5cc310] (LTR)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0xe5cc370 H:[DocumentListViewCell:0xe5c2280]-(820)-[UIView:0xe5cc310](LTR)>

I think I have found constraints that cause this error, but I have to put a larger piece of code so that it makes sense.
    protected void Initialize ()
    {
        _cellScrollView = new SwipeableScrollView ();
        _cellScrollView.TranslatesAutoresizingMaskIntoConstraints = false;
        _cellScrollView.Delegate = new SwipeableScrollViewDelegate (this);
        _cellScrollView.ShowsHorizontalScrollIndicator = false;
        _cellScrollView.ScrollsToTop = false;
        _cellScrollView.ScrollEnabled = true;
        AddSubview (_cellScrollView);

        AddConstraints (new[] {
            NSLayoutConstraint.Create (_cellScrollView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1.0f, 0.0f),
            NSLayoutConstraint.Create (_cellScrollView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, this, NSLayoutAttribute.Bottom, 1.0f, 0.0f),
            NSLayoutConstraint.Create (_cellScrollView, NSLayoutAttribute.Left, NSLayoutRelation.Equal, this, NSLayoutAttribute.Left, 1.0f, 0.0f),
            NSLayoutConstraint.Create (_cellScrollView, NSLayoutAttribute.Right, NSLayoutRelation.Equal, this, NSLayoutAttribute.Right, 1.0f, 0.0f)
        });

        _cellContentView = new UIView ();
        _cellContentView.AddSubview (ContentView);
        _cellScrollView.AddSubview (_cellContentView);

        TapGestureRecognizer = new UITapGestureRecognizer (HandleScrollViewTapped);
        TapGestureRecognizer.CancelsTouchesInView = false;

        _longPressGestureRecognizer = new UILongPressGestureRecognizer (HandleScrollViewLongPressed);
        _longPressGestureRecognizer.CancelsTouchesInView = false;
        _longPressGestureRecognizer.MinimumPressDuration = 0.2f;

        TapGestureRecognizer.Delegate = new SwipeableCellGestureRecognizerDelegate (this, _longPressGestureRecognizer);
        _longPressGestureRecognizer.Delegate = new SwipeableCellGestureRecognizerDelegate (this, _longPressGestureRecognizer);

        _cellScrollView.AddGestureRecognizer (TapGestureRecognizer);
        _cellScrollView.AddGestureRecognizer (_longPressGestureRecognizer);

        // Create the left and right utility button views, as well as vanilla UIViews in which to embed them.  We can manipulate the latter in order to effect clipping according to scroll position.
        // Such an approach is necessary in order for the utility views to sit on top to get taps, as well as allow the backgroundColor (and private UITableViewCellBackgroundView) to work properly.

        _leftUtillityClipView = new UIView ();
        _leftUtillityClipViewConstraint = NSLayoutConstraint.Create (_leftUtillityClipView, NSLayoutAttribute.Right, NSLayoutRelation.Equal, this, NSLayoutAttribute.Left, 1.0f, 0.0f);
        _leftUtilityButtonsView = new SwipeableUtilityButtonView (_leftUtilityButtons, this, HandleUtilityButtonPressed);

        _rightUtilityClipView = new UIView ();
        _rightUtilityClipViewConstraint = NSLayoutConstraint.Create (_rightUtilityClipView, NSLayoutAttribute.Left, NSLayoutRelation.Equal, this, NSLayoutAttribute.Right, 1.0f, 0.0f);
        _rightUtilityButtonsView = new SwipeableUtilityButtonView (_rightUtilityButtons, this, HandleUtilityButtonPressed);

        // Perform common configuration on both sets of utility items (left and right).

        var clipViews = new [] { _leftUtillityClipView, _rightUtilityClipView };
        var clipConstraints = new [] { _leftUtillityClipViewConstraint, _rightUtilityClipViewConstraint };
        var buttonViews = new [] { _leftUtilityButtonsView, _rightUtilityButtonsView };
        var alignmentAttributes = new [] { NSLayoutAttribute.Left, NSLayoutAttribute.Right };

        for (int i = 0; i < 2; ++i) {
            var clipView = clipViews [i];
            var clipConstraint = clipConstraints [i];
            var buttonView = buttonViews [i];
            var alignmentAttribute = alignmentAttributes [i];

            clipView.TranslatesAutoresizingMaskIntoConstraints = false;
            clipView.ClipsToBounds = true;

            AddSubview (clipView);
            AddConstraints (new [] {
                // Pin the clipping view to the appropriate outer edges of the cell.
                NSLayoutConstraint.Create (clipView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1.0f, 0.0f),
                NSLayoutConstraint.Create (clipView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, this, NSLayoutAttribute.Bottom, 1.0f, 0.0f),
/* THIS LINE */         NSLayoutConstraint.Create (clipView, alignmentAttribute, NSLayoutRelation.Equal, this, alignmentAttribute, 1.0f, 0.0f),
/* OR THIS LINE */          clipConstraint,
            });

            clipView.AddSubview (buttonView);
            AddConstraints (new [] {
                // Pin the button view to the appropriate outer edges of its clipping view.
                NSLayoutConstraint.Create (buttonView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, clipView, NSLayoutAttribute.Top, 1.0f, 0.0f),
                NSLayoutConstraint.Create (buttonView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, clipView, NSLayoutAttribute.Bottom, 1.0f, 0.0f),
                NSLayoutConstraint.Create (buttonView, alignmentAttribute, NSLayoutRelation.Equal, clipView, alignmentAttribute, 1.0f, 0.0f),
                // Constrain the maximum button width so that at least a button's worth of contentView is left visible. (The button view will shrink accordingly.)
                NSLayoutConstraint.Create (buttonView, NSLayoutAttribute.Width, NSLayoutRelation.LessThanOrEqual, ContentView, NSLayoutAttribute.Width, 1.0f, -SwipeableUtilityButtonView.UtilityButtonWidthDefault)
            });
        }
    }

When I remove one of the marked lines the message disappears, but code does not work properly.
You can find the original implementation here SWTableViewCell.m - lines 146 and 147.
I tried to translate the code as well as I could and not change the implementation so that I do not get errors like these, but as you can see I failed.
I am really surprised because to me, my implementation and the original implementation looks exactly the same.
Any help would be appreciated.
Once I finish and test my version of SWTableViewCell I will put it on GitHub so others don't have to waste time on this ;)

A: I have found bug in another piece of code, so the snippet above is correct.


text:
Q: Common HTML template for multiple components with added individual code from component In an app there are some differ components, which refer to a common template by using the same url:
@Component({
  selector: 'JG-Percentage',
  templateUrl: '../../../../htmlStructure/htmlBaseTemplate/TemplateVarlist.component.svg',
  styleUrls: ['./Percentage.component.sass']
})

So far so good, also by using angular two-way binding: [(ngModel)]='variable.varLabel'.
But now on some components needs some additional small html code, also with angular two-way binding:    [(ngModel)]='variable.inputStr'.
How to inject this added html code into the common template? Or may two html files can be related together to one component?
Thanks for help.
The example is shown on https://angulartool.de

A:
How to inject this added html code into the common template? ...

You can add *ngIf="isCustom" on the additional HTML and use [(ngModel)] inside as  you wish. Then in all the Typescript component classes using this same HTML template file, you can have the boolean property for isCustom (or whatever variable name). isCustom will be true for the component classes that use the additional HTML and false for those that do not.
If you are using [(ngModel)] directly on the additional HTML and in case Angular complains that you can't use ngModel together with *ngIf (as is the case with *ngFor), you can wrap this additional HTML in an ng-container and add *ngIf there instead.
<ng-container *ngIf="isCustom">
  <div [(ngModel)]="variable.inputStr">additional HTML</div>
</ng-container>

... Or may two html files can be related together to one component?

A Typescript component class can have only one HTML file. Two HTML files can't be linked to the same typescript component class. (Though it is not the case with styles. One component class can have multiple style files).

A: Yes, it is possible to have two html templates for one component by have a additinal child component.
The  child component do nothing more as to extends the Component for which the second template is needed.
The complete code excample with comments is shown on stackblitz and the related extended component is the No.3.
https://stackblitz.com/edit/angular-ivy-7oeube?file=src%2Fapp%2Fapp.component.ts


text:
Q: Is an index on A, B redundant if there is an index on A, B, C? Having years of experience as a DBA, I do believe I know the answer to the question, but I figured it never hurts to check my bases.
Using SQL Server, assuming I have a table which has an index on column A and column B, and a second index on columns A, B, and C, would it be safe to drop the first index, as the second index basically would satisfy queries that would benefit from the first index?

A: Yes, this is a common optimization.  Any query that would benefit from the index on A,B can also benefit just as well from the index on A,B,C.
In the MySQL community, there's even a tool to search your whole schema for redundant indexes:  http://www.percona.com/doc/percona-toolkit/pt-duplicate-key-checker.html
The possible exception case would be if the index on A,B were more compact and used much more frequently, and you wanted to control which index was kept loaded in memory.

A: Much of what I was thinking was written by Jonathan in a previous answer. Uniqueness, faster work, and one other thing I think he missed.
If the first index is made A desc, B asc and second A asc, B asc, C asc, then deleting the first index isn't really a way to go, because the second one isn't a superset of the first one, and your query cannot benefit from the second index if ordering is as written in the first one.
In some cases like when you use the first index, you can order by A desc, B asc (of course) and A asc, B desc, but you can also make a query that will use any part of that index, like Order by A desc.
But a query like order by A asc, B asc, will not be 'covered' by the first index.
So I would add up, you can usually delete the first index, but that depends on your table configuration and your query (and, of course, indexes).

A: It depends, but the answer is often 'Yes, you could drop the index on (A,B)'.
The counter-case (where you would not drop the index on (A,B)) is when the index on (A,B) is a unique index that is enforcing a constraint; then you do not want to drop the index on (A,B).  The index on (A,B,C) could also be unique, but the uniqueness is redundant because the (A,B) combination is unique because of the other index.
But in the absence of such unusual cases (for example, if both (A,B) and (A,B,C) allow duplicate entries), then the (A,B) index is logically redundant.  However, if the column C is 'wide' (a CHAR(100) column perhaps), whereas A and B are small (say INTEGER), then the (A,B) index is more efficient than the (A,B,C) index because you can get more information read per page of the (A,B) index.  So, even though (A,B) is redundant, it may be worth keeping. You also need to consider the volatility of the table; if the table seldom changes, the extra indexes don't matter much; if the table changes a lot, extra indexes slow up modifications to the table.  Whether that's significant is difficult to guess; you probably need to do the performance measurements.

A: I typically would find this "almost" similar index in table that contains historical data. If column C is a date or integer column, be careful. It is most likely used to satisfy the MAX function as in WHERE tblA.C = MAX(tblB.C), which skips the table altogether and utilize an index only access path.

A: The first index covers  queries that look up on A , A,B and the second index can be used to cover queries that look up on A , A,B or A,B,C which is clearly a superset of the first case.
If C is very wide however the index on A,B may still be useful as it can satisfy certain queries with fewer reads.
e.g. if C was a char(800) column the following query may benefit significantly from having the narrower index available.
SELECT a,b
FROM YourTable
ORDER BY a,b


text:
Q: Font consistency throughout Project? Is there a quick and effective way of applying a global Font to be used in a project?
By this I mean I would like to set a specific Font name that all controls in my project will use such as TButton, TEdit, TLabel etc.
Typically setting the Font for the Form rather than a specific control will change all the controls on that Form to the Font specified.
There is a slight issue with this however, if you have manually changed a Font on a specific control, then setting the Font by the Form will no longer update those controls that have previously been changed manually.
Idea 1
I was thinking of using a For loop and iterating through each component on my Forms and setting the Font this way, such as:
procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  with TForm(Self) do
  begin
    for i := 0 to ComponentCount - 1 do
    begin
      if Components[i] is TButton then
      begin
        TButton(Components[i]).Font.Name  := 'MS Sans Serif';
        TButton(Components[i]).Font.Size  := 8;
        TButton(Components[i]).Font.Style := [fsBold];
      end;

      if Components[i] is TLabel then
      begin
        TLabel(Components[i]).Font.Name  := 'MS Sans Serif';
        TLabel(Components[i]).Font.Size  := 8;
        TLabel(Components[i]).Font.Style := [fsBold];
      end;
    end;
  end;
end;

But doing this seems very messy, it will also be a considerable amount of code for a simple task.
Idea 2
I know I could manually change the fonts at design time one by one for each control, but with several forms to go through this could take time and even then I might of missed a control.
Idea 3
Similar to Idea 2, another way could be to view the Form as Text (DFM) and Find and Replace the font that way.

Basically I am going for consistency within my Application, and having one Font used throughout is what I was looking to achieve.
Am I missing something completely obvious here, is what I am trying to do overkill for such a task?

A: As discussed in the comments, the key to this is the ParentFont property. This property is defined at various points in the VCL hierarchy. If you set ParentFont to be True for all components in the chain, then you can change the fonts for the entire application simply by modifying
Application.DefaultFont

By default most components set ParentFont to True and so you have nothing to do. The odd one out though is TForm. A brand new default form has ParentFont set to False. This is somewhat disappointing but I suspect reflects the fact that the original designers of the VCL did not anticipate this and that ParentFont was grafted on relatively late in the development of the VCL.
No matter, in an ideal world, all forms in your application should be derived from a common base class that you control. If that is so then you can simply make the change there, set ParentFont to be True, make sure no explicit font settings are applied to any components on you forms, and you are golden. Control the entire application's fonts through a single property. If you don't have a common base class for your forms, here's an ideal time to add it. If you don't want to do that then you need to set ParentFont for each form.
Other related properties are Screen.MessageFont and Screen.MenuFont. These provide global control over the fonts used in message boxes and menus. However, recent versions of Delphi have handed back to Windows control over the painting of message boxes and menus and so these properties have no effect.

A: The real key, as was mentioned, is to ensure that all your forms descend from your own application base form.
Then, you can view each form and button etc, and review the properties, where any modified font property should be displayed in bold, and is easily identified. Most properties have a "Revert to inherited" menu choice. This should essentially undo any previous selection, without having to go to the text version for editting. (Although it probably does exactly that, deleting any text entry resulting from previous font-setting).
I would definitely want to fix each form once rather than leaving it defined incorrectly and adding more code to fix it at runtime. That change will leave you with a worse problem if you later decide to do something different.

A: If you want to do this runtime, like you describe it in Idea 1, you should consider making it a recursive function, like this:
procedure SetFontProperties(Control: TControl; Name: TFontName; Size: Integer; Styles: TFontStyles);
// Set font properties
var
  Index: Integer;
  Font: TFont;
  AnObject: TObject;
  ChildControl: TControl;
begin
  // Set font properties
  AnObject := GetObjectProp(Control, 'Font', nil);
  if AnObject is TFont then
  begin
    // Set properties
    Font := TFont(AnObject);
    Font.Name  := Name;
    Font.Size  := Size;
    Font.Style := Styles;
  end;

  // Set child font properties
  if Control is TWinControl then
  begin
    // Set
    for Index := 0 to TWinControl(Control).ControlCount - 1 do
    begin
      // Child control
      ChildControl := TWinControl(Control).Controls[Index];

      // Set font properties
      SetFontProperties(ChildControl, Name, Size, Styles);
    end;
  end;
end;

You can then switch fonts for all controls within a form by using it like this:
SetFontProperties(Self, 'Courier', 14, []);

The function will then set the font properties of the form, and the font properties of all child controls on the form, including controls nested within TPanels or other container controls.
However I do agree with you that it's sort of a half messy way of doing it.


text:
Q: Excel file generated from WinForm app via template is sometimes "InVisible" We have a WinForm application that uses VSTO to generate an Excel file from a Template.
Occasionally (frequently) the file opens (because you can use the cursor keys and the formula and cell changes) but it is invisible. Even if you save the file and open it back up, it is still invisible.
The users use Excel 2007 and pretty much all (6 - 8) of our users experience this problem.
The (temporary) fix I have given them is to choose "Arrange All". When this is done, the worksheet pops into view.
I have seen several causes and fixes for this on the web. Everything from using a graphic in the template that was in Excel 2003, but isn't in Excel 2007.
The template is pretty "simple". It has formulas, fonts and colors and that is about it.
The template (and WinForm application) is deployed to the users via Click Once.
Here is the code from the "ThisWorkbook.cs" file:
public string TemplateTableName;
public string TemplateSelectStatement;

private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
    Properties.Settings.Default.myConnectionString = Registry.GetValue("myConnectionString", Properties.Settings.Default.appConnectionString).ToString();
    TemplateTableName = Registry.GetValue("TemplateTableName", string.Empty).ToString();
    TemplateSelectStatement = Registry.GetValue("TemplateSelectStatement", string.Empty).ToString();

    AppLog.ConnectionString = Properties.Settings.Default.myConnectionString;
}

Here is the code from the "Sheet1.cs" file:
private const int StartingDataRow = 4;

private int LastRow;
private int NextAvailableColumn = 18;

DataSet myDS = new DataSet();

Dictionary<string, object[,]> xlsColumnData = new Dictionary<string, object[,]>();

private void Sheet1_Startup(object sender, System.EventArgs e)
{
    try
    {
        if (Globals.ThisWorkbook.TemplateTableName == string.Empty) throw new Exception("TemplateTableName is not set in the registry.");
        if (Globals.ThisWorkbook.TemplateSelectStatement == string.Empty) throw new Exception("TemplateSelectStatement is not set in the registry.");

        Application.ScreenUpdating = false;

        if (Globals.ThisWorkbook.TemplateTableName.Length > 31)
            this.Name = Globals.ThisWorkbook.TemplateTableName.Substring(0, 31);
        else
            this.Name = Globals.ThisWorkbook.TemplateTableName;

        LoadTableData();
        LoadDataArrays();
        BindDataToColumns();
        ApplyFormulas();
        ApplyFormatting();

        this.Range["B4", missing].Select();

        Application.ScreenUpdating = true;

        AppLog.WriteEvent(DateTime.Now, Environment.UserName, Environment.MachineName, Globals.ThisWorkbook.TemplateTableName, TraceEventType.Information, "Creating customer list");

        Globals.ThisWorkbook.RemoveCustomization();
    }
    catch (Exception ex)
    {
        AppLog.Show(ex.Message, "Sheet1_Startup", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, TraceEventType.Error);
    }
    finally
    {
        Application.ScreenUpdating = true;
    }
}

private void LoadTableData()
{
    try
    {
        Application.Cursor = XlMousePointer.xlWait;

        string selectCommandText = Globals.ThisWorkbook.TemplateSelectStatement.Replace("[Bind_Type]", "dbo.GetBindingCodeDescription([Bind_Type]) AS Binding_Description");

        SqlDataAdapter da = new SqlDataAdapter(selectCommandText, Public_No_Holdings.Properties.Settings.Default.myConnectionString);
        da.SelectCommand.CommandTimeout = 60;

        if (da.SelectCommand.Connection.State != ConnectionState.Closed) da.SelectCommand.Connection.Close();
        da.Fill(this.myDS);

        LastRow = (StartingDataRow + this.myDS.Tables[0].Rows.Count) - 1;
    }
    catch (Exception ex)
    {
        AppLog.Show(ex.Message, "Loading Table", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        Application.Cursor = XlMousePointer.xlDefault;
    }
}
private void LoadDataArrays()
{
    System.Data.DataTable dt = this.myDS.Tables[0];

    // insert the data into the object[,]
    object[,] rowData;
    dt.Columns["Imprint"].ColumnName = "Publisher"; //Alias the Imprint dataset column to populate the "Publisher" xls column
    for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
    {
        rowData = new object[dt.Rows.Count, 1];

        for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
        {
            switch (dt.Columns[iCol].ColumnName)
            {
                case "EAN":
                    rowData[iRow, 0] = "'" + dt.Rows[iRow][iCol];
                    break;

                case "IPage_Link":
                    rowData[iRow, 0] = String.Format("=HYPERLINK(\"{0}\", \"{1}\")", dt.Rows[iRow][iCol], "iPage");
                    break;

                default:
                    rowData[iRow, 0] = dt.Rows[iRow][iCol];
                    break;
            }
        }

        xlsColumnData.Add(dt.Columns[iCol].ColumnName, rowData);
    }
}

private void BindDataToColumns()
{
    NamedRange nr;
    Range rng;

    foreach (KeyValuePair<string, object[,]> kvp in xlsColumnData)
    {
        try
        {
            if (this.Controls.Contains(kvp.Key))
            {
                nr = (NamedRange)this.Controls[kvp.Key];

                // Reduce range (remove header rows)
                rng = this.Range[this.Cells[StartingDataRow, nr.Column], this.Cells[LastRow, nr.Column]];
                rng.Value2 = kvp.Value;
            }
            else
            {
                this.Cells[StartingDataRow - 1, NextAvailableColumn].Value2 = kvp.Key;
                rng = this.Range[this.Cells[StartingDataRow, NextAvailableColumn], this.Cells[LastRow, NextAvailableColumn]];
                rng.Value2 = kvp.Value;
                NextAvailableColumn++;
            }
        }
        catch (Exception ex)
        {
            AppLog.Show(ex.Message, "BindDataToColumns - " + kvp.Key, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

}

private void ApplyFormulas()
{
    Range rng;
    int iCol;

    // Book Invoice
    iCol = this.BookInvoice.Column;
    rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
    rng.Select();
    rng.FillDown();

    // Your Cost
    iCol = this.YourCost.Column;
    rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
    rng.Select();
    rng.FillDown();
}

private void ApplyFormatting()
{
    // For some reason Hyperlink columns get reset
    this.IPage_Link.Font.Name = this.EAN.Font.Name;
    this.IPage_Link.Font.Size = this.EAN.Font.Size;

    ((Range)this.Cells[StartingDataRow, 1]).EntireRow.Select();
    Application.ActiveWindow.FreezePanes = true;
}


text:
Q: Encode Images to Video (Mediacodec) I need to encode a series of 10 bitmaps into a video using Mediacodec. I do not want to use FFmpeg or Jcodec because its very slow.
I have searched on the Internet but can't seem to find a fully working sample code that i can modify.
Here is what I've tried:
mMediaCodec = MediaCodec.createEncoderByType("video/avc");
mMediaFormat = MediaFormat.createVideoFormat("video/avc", 320, 240);
mMediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 125000);
mMediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
mMediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,       MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar);
mMediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
mMediaCodec.configure(mMediaFormat, null, null,    MediaCodec.CONFIGURE_FLAG_ENCODE);
mMediaCodec.start();
mInputBuffers = mMediaCodec.getInputBuffers();

 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
 image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); //    image is the bitmap
  byte[] input = byteArrayOutputStream.toByteArray();

  int inputBufferIndex = mMediaCodec.dequeueInputBuffer(-1);
   if (inputBufferIndex >= 0) {
   ByteBuffer inputBuffer = mInputBuffers[inputBufferIndex];
   inputBuffer.clear();
   inputBuffer.put(input);
   mMediaCodec.queueInputBuffer(inputBufferIndex, 0, input.length, 0, 0);
   }

A: Your code example creates an encoder that expects YUV420 image buffers, but you're feeding it PNG compressed data (which btw is just a glorified ZIP file format, not a image representation format).
You should convert each bitmap'z pixels from ARGB to YUV, and feed that buffer to the encoder. Obviously they should match with the frame width and height in the encoder's setup.


text:
Q: Can we write `when`/`then` inside if condition in spock test Can we write when/then inside if condition in spock test? Code looks like this. Here i am trying to control the calling of when and then.
def testMethod(){
    given:
        if(some Condition) {
            when:
                eventOne Occurred
            then:
                assertion based on eventOne
        } else if (some Condition) {
            when:
                eventTwo Occurred
            then:
                assertion based on eventTwo
        } else {
            when:
                eventThree Occurred
            then:
                assertion based on eventThree
        }
    where:
        iteration here.
}

A: What is the purpose of this? The given-when-then approach was designed to make automated tests easier to understand. The example you shown makes reading and understanding your test hard. And I would even bet it wont compile.
Try keeping your tests simple. where is used for providing parameters to your test (parameterized test), e.g.
@Unroll
def "should return #result for parameters(#a,#b)"() {

    when:
        def result = someObject.someMethod(a, b)

    then:
        result == expected

    where:
        a           | b             || expected
        null        | null          || false
        ""          | ""            || false
        "test"      | "foo"         || true
}

The main purpose here is to keep understanding the test logic as simple as possible. If you want to test different combination then you might create separate test method.

A: From the Spock perspective I can't find any restrictions for your specific example. From the readability perspective I don't think it is the best way to use Spock - I agree with answer above.
But please be aware of the following limitation of the Spock labels (from here):

A feature method must have at least one explicit (i.e. labelled) block
  - in fact, the presence of an explicit block is what makes a method a feature method. Blocks divide a method into distinct sections, and
  cannot be nested.

So logically you can think of your example as:

*

*given - is a set-up phase;

*when-then from the first condition;

*when-then from the second condition;

*when-then from the third condition;

*where - describes the data supplies;


text:
Q: If you increase a natural number by the sum of its digits each time from $1$, can you get to $2019\,2019\,2019\,2019$ after a finite number of steps? Stumbled across a question today and to me it makes very little sense and I have no idea as to how one would approach this question and thus solve it, anyone have any ideas? Would be much appreciated.
Question: If you can increase a natural number by the sum of its digits per single move, from the natural $1$, can you get to $2019\,2019\,2019\,2019$ after a finite number of steps?
The only idea I have is that I have heard before that $3$ has some significance with digit sums but I don't know how that links in.
Thanks in advance.

A: Note that $n$ and the the sum of its digits have the same remainder when divided by $3$ (why?). So if we start from $1$, the remainder of the division by $3$ of each term of the sequence would be $1,2,1,2,1,2,1\dots$ which means that we can not obtain any multiple of $3$ such has $2019201920192019$.


text:
Q: stunnel client uses improper SNI when talking to Apache I have stunnel listening on port 80 and acting as a client connecting to Apache listening on port 443. Configuration is below. What I'm finding is that if I attempt to connect to localhost:80 the connection is fine but if I connect to 127.0.0.1:80
When I check Apache's logs it indicates that stunnel is using localhost as the SNI both times, but the HTTP request lists localhost in one case and 127.0.0.1 in another. Is it possible to tell stunnel to either use whatever is in the HTTP request or to somehow configure two clients each with different SNI values?
stunnel.conf:
debug = 7
options = NO_SSLv2

[xmlrpc-httpd]
client = yes
accept = 80
connect = 443

Apache error.log:
[error] Hostname localhost provided via SNI and hostname 127.0.0.1 provided via HTTP are different

Apache access.log:
"GET / HTTP/1.1" 200 2138 "-" "Wget/1.13.4 (linux-gnu)"
"GET / HTTP/1.1" 400 743 "-" "Wget/1.13.4 (linux-gnu)"

wget:
$wget -d localhost
---request begin---
GET / HTTP/1.1
User-Agent: Wget/1.13.4 (linux-gnu)
Accept: */*
Host: localhost
Connection: Keep-Alive

---request end---

$wget -d 127.0.0.1
---request begin---
GET / HTTP/1.1
User-Agent: Wget/1.13.4 (linux-gnu)
Accept: */*
Host: 127.0.0.1
Connection: Keep-Alive

---request end---

edit:
Apache Config
Nothing out of the ordinary, it's just a virtual host listening to 443
<VirtualHost *:443>

A: It looks like you can force this with the client config item:
sni = server_name
http://www.stunnel.org/static/stunnel.html - Search for SNI


text:
Q: In what manner, rotation is 90 degrees here? In the code below, the button with close id, is rotated 90 degrees. But I don't get how that button moved 90 degrees and with respect to what origin. transform-origin: top left; But top left of what element?

body {
  margin: 0;
}

.circle-container {
  position: fixed;
  top: 100px;
  left: 100px;
}

.circle {
  background-color: #ff7979;
  height: 200px;
  width: 200px;
  /*   border-radius: 50%; */
  position: relative;
  transition: transform 0.5s linear;
}

.circle button {
  position: absolute;
  top: 50%;
  left: 50%;
  height: 100px;
  background: transparent;
  border: 0;
  font-size: 26px;
  color: #fff;
}

.circle button:focus {
  outline: none;
}

.circle button#open {
  left: 60%;
}

.circle button#close {
  top: 60%;
  transform: rotate(90deg);
  transform-origin: top left;
}

    <button id="close">

        </button>
    <button id="open">

        </button>

A: Ok, I got it. The top-left is of that button's top-left. I button has been stretched vertically by using height property as well as pushed from the top using absolute positioning. I got confused because, in my mind, I was viewing button element as having an equal size of icon element inside.