Q:

C++ Concepts - Concept in the requires parenthesis causes 2 conflicting error messages

I've worked hard this morning to understand concepts a bit more (still a newbie), and I've stumbled to something strange.
I wanted to understand how good concepts work with Lambda functions, I've tried toying around with them a lot.
Lets start with this code (that works!):
#include <concepts>
#include <stdio.h>

template <typename T>
concept Integral =
requires(T n)
{
    { n } -> std::convertible_to<int>;
};

template <typename Operation>
concept CalculatorOperation =
requires(Operation&& op, int a, int b)
{
    { op(a, b) } -> Integral;
};

template <CalculatorOperation Operation>
static inline constexpr Integral auto Calculator(const Integral auto First,
                                                 const Integral auto Second)
{
    return Operation{}(First, Second);
}

int main()
{
    static constexpr auto Multiply = [](const Integral auto First,
                                        const Integral auto Second)
                       { return First * Second; };
    return Calculator<decltype(Multiply)>(15, 18);
}

I created an Integral concept that (just for dummy's sake) is satisfied if a type is convertible to int.
I've created a calculator operation concept that accepts a lambda, two ints, and makes sure the operation returns an Integral.
I decided that I want the int in the concept to turn into an Integral, since I don't want only int's to be accepted to the operation (I want all integral types).
So I changed
requires(Operation&& op, int a, int b)

to
requires(Operation&& op, Integral&& a, Integral&& b)

Not only did this not work for me, I actually got 2 conflicting error messages (on GCC 10.1):
<source>:13:30: error: placeholder type not allowed in this context

<source>:13:30: error: expected 'auto' or 'decltype(auto)' after 'Integral'

   13 |     requires(Operation&& op, Integral&& a, Integral&& b)

I ran this using GodBolt's website Compiler Explorer.
Whats going on here? Is there an actual way to do this?

A:

First off, by doing this:
requires(Operation&& op, Integral&& a, Integral&& b)

you probably actually meant this:
requires(Operation op, Integral auto a, Integral auto b)

that is, to use the type-constraint auto form of a placeholder type specifier.
However, auto parameters produce function templates, and the auto placeholder is an equivalent of an actual invented type template parameter of that function template, thus it can appear only in contexts where type deduction from an initializer takes place, and that means that:
void foo(auto x);

is an equivalent of:
template <typename T>
void foo(T x);

Similarly,
void bar(Integral auto x);

is an equivalent of:
template <Integral T>
void bar(T x);

Such transformation is not applicable to a requires expression, i.e., there's no initializer whose type could be deduced, and so one cannot use an auto placeholder in the parameter declaration of a requirement parameter list. These parameters, as the standard says, "are only used as notation for the purpose of defining requirements." So instead, you need to explicitly specify all template arguments that are needed for the concept to work, e.g.:
template <typename Operation, typename Lhs, typename Rhs>
concept CalculatorOperation = requires(Operation op, Lhs a, Rhs b)
{
    { op(a, b) } -> Integral;
};

template <typename Operation>
constexpr Integral auto Calculator(Integral auto first, Integral auto second)
    requires CalculatorOperation<Operation, decltype(first), decltype(second)>
{
    return Operation{}(first, second);
}

Also note that I removed && from each of the parameter declarations in the requirement parameter list. The whole requires expression is an unevaluated context, and no arguments are actually passed.


Q:

Ghostscript, Duplex print same side twice when NumCopies is bigger than 1

I using the command :
 -q -dBATCH -dNOPAUSE -dNODISPLAY -dPDFFitPage \
 -c  "mark /BitsPerPixel  1  \
           /NoCancel true \
           /NumCopies 2 \
           /Duplex true \
           /OutputFile (%printer%Ricoh c2051)  \
           /UserSettings << /DocumentName  (Arquivo Teste) \
                            /MaxResolution 500  >>  \
      (mswinpr2)finddevice putdeviceprops setdevice"   -f  "C:\Test123.pdf"

The PDF file have 3 pages, when I set the NumCopies 2 for example, the result is 3 pages :

page 1 = the text of page one, in both sides;
page 2 = the text of page two, in both sides;
page 3 = the text of page three, in both sides;

But when I set just one copy the result is 2 pages:

page 1 : the text of page one and in the other side the text of page 2
page 2 : the text of page three and the other side blank .

like Duplex are supposed to be.
Anyone knows how this happened ?

A:

Its a consequence of the way mswinpr2 works, it doesn't care about you setting /Duplex true because the device is not a duplexing device (your printer obviously is, but that's not the same thing). In fact the majority of the command line will have no effect on teh output.
When you set NumCopies, it prints each page 'NumCopies' times to the printer so if your printer is set to do duplexing then it prints the first copy of page 1 on the first side, then the second copy of page 1 on the second side (ie the back of page 1) then the first copy of page 2 on the third side (the front of page 2) and so on.
You cannot achieve multiple collated copies using the mswinpr2 device.
The command line you have set suggests that you have the PostScript option for your printer, you could instead use the ps2write device to convert the PDF to PostScript and send the PostScript to the printer, the latest version of Ghostscript allows for the injection of device-specific options into the output PostScript so you could easily add NumCopies and Duplex there, assuming your printer has sufficient memory to do duplexing and NumCopies at the same time.


Q:

Add layer on top of existing SWF in Flash Pro

A project I'm involved in has a specific requirement where a layer must be added on top of an existing SWF. The SWF is created by converting a PDF using SWFTools pdf2swf. This layer will be used to add interactive elements like videos or sound on top of the existing text content in the SWF.
My problem is, when I try to import the SWF into Flash Pro, it sort of breaks up and it's not possible to see the SWF or its elements correctly.
I've tried making the SWF a MovieClip symbol after importing and called its play() and gotoAndPlay(i) methods to no avail. Using an external SWF with a loader works, but the SWF should be internal so the whole project can be compiled to iOS and Android in one go.
Are there any other methods I could use to interact with a SWF and make it work inside my FLA project?

A:

Your problem is not in Flash but the way you're transforming the pdf to swf. The default parameters of pdf2swf will export the swf for a previous version of Flash, 6 to be exact. So you need to explicitly set the flash version when converting to a later version so that you can import it in your timeline (assuming u're using AS3).
Use this config option:
    -T , --flashversion num        Set Flash Version in the SWF header to num.
View this for more information:
http://wiki.swftools.org/index.php?title=Pdf2swf
http://wiki.swftools.org/index.php?title=Pdf2swf_-s_parameters


Q:

How to force an android device to stay alive while the application is running

I need to force the android device to stay alive while the application is running. There any way to do this ?
I read here : Is there a way to force an android device to stay awake? about this, I tried to do this but probably I don't know to use correctly a Service.
This is the code I use :
public class WakeLockService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onCreate() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
    wl.acquire();
}
@Override
public void onDestroy() {
    wl.release();
}

and in the first Activity of my Application, I put this :
Intent s = new Intent(this, WakeLockService.class);
startService(s);

Is it correct what I'm doing? Anyone can help me to do this ?
Thanks in advance.

A:

If you want the device to stay awake while it displays an activity of your app, you have to set the flag FLAG_KEEP_SCREEN_ON when creating the activity:
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // Unlock the device if locked
    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); // Turn screen on if off
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keep screen on
    .....
}

Add the permission WAKE_LOCK in the manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />

EDIT After seeing your last comment: yes, you need a service: note that the device will go to sleep anyway, but your service can continue to run if you make it clear to the user (you have to display a notification) and declare it STICKY:
public class yourservice extends Service
{
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //The intent to launch when the user clicks the expanded notification
        /////////////////////////////////////////////////////////////////////
        Intent forPendingIntent = new Intent(this, si.test.app.activities.activity.class);
        forPendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, forPendingIntent, 0);

        Notification notification = new Notification(R.drawable.icon, "testapp", System.currentTimeMillis());
        notification.setLatestEventInfo(this, "testApp", "testApp is running", pendIntent);

        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground (R.string.app_name, notification);
        return START_STICKY;
    }
    ...
}


Q:

Nested (Condition) ? true:false statements in JavaScript

In the following code snippet,
var paintMode = data.hasOwnProperty('regions') ?
        'regions' : data.hasOwnProperty('vpcs') ?
        'vpcs' : data.hasOwnProperty('zones') ?
        'zones' : data.hasOwnProperty('subnets') ?
        'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null;

I've used a deeply nested (condition) ? true : false -- is this acceptable? is it optimized? If its bad is there an alternative?
It is used inside a recursive function which does a few SVG operations, here's the function snippet if you are curious.
function paintGroups(data) {
    var paintMode = data.hasOwnProperty('regions') ? 'regions' : data.hasOwnProperty('vpcs') ? 'vpcs' : data.hasOwnProperty('zones') ? 'zones' : data.hasOwnProperty('subnets') ? 'subnets' : data.hasOwnProperty('clusters') ? 'clusters' : null,
        depth = data[paintMode].length,
        i,
        Shape; //= raphealObj.rect();

    // Register stacking order
    // Paint a shape with styles based on paintMode
    // Store its id & Label for other ops.

    if(paintMode) {
        for(i = 0; i < depth; i++) {
            paintGroups(data[paintMode][i]);
        }
    }

    // to reverse the order of paint - place your statements here
}

A:

Generally speaking using binary operations should be faster than conditional statements with branching because of branch prediction, caching, yada yada yada. But your code is fine. I like the && || but it's just a preference and not based on anything empirical.
var data = {a: 1, b: 2, c: 3};
var result = data.x ||
    data.y && "y" ||
    data.z && "z" ||
    data.w && "w" ||
    null;

I didn't feel like typing .hasOwnProperty.
EDIT After actually looking at your code
var paintMode = data.regions || data.vpcs || data.zones || data.subnets || data.clusters || null;
if(paintNode) {
    for(var i=0; i<paintMode.length; i++)
        paintGroups(paintMode[i]);
}


Q:

Regular Expression to find querystring portion of a hyperlink

I'm pretty new to regular expressions, but I'm sure a regex would give me something much more elegant than anything I could do with string methods.
I've got a hyperlink in the form of:
hello

I want to yank out just the querystring portion.  Also, what's a good reference for .net regular expressions (sheepish grin)? I find the MSDN reference very hard to follow.

A:

the following code will extract the query string
string html = "hello";
Match m = Regex.Match(html, "]+href=\".*?\\?(.*?)\">");
string querystring = m.Groups[1].ToString();

regex explained:
take only strings starting with <a href="
between the a and href there can be other attributes, spaces, it ignores them
make a group of the the url, from the first question mark to the ending quotes - this is your query string


Q:

Crosstab Report With Dynamic Columns in PRD

i want to create a crosstab report in PRD but with dynamic columns based on report filter
For example i want to generate summary purchase report based on selected date
Sample of table :
Date    Purchase No Total Value
1-Jan   PO001    $10.00
5-Jan   PO002    $20.00
7-Jan   PO003    $30.00
7-Jan   PO004    $40.00
20-Jan  PO005    $50.00
22-Jan  PO006    $60.00
22-Jan  PO007    $70.00
25-Jan  PO008    $10.00
30-Jan  PO009    $20.00

So if my filter is from 1 Jan to 15 Jan then my report should looks like this:
Description              1-Jan      5-Jan      7-Jan
Purchase total value     $10.00      $20.00      $70.00

Then if my filter is from 1 Jan to 30 Jan it will looks like :
Description              1-Jan      5-Jan      7-Jan      20-Jan     22-Jan     25-Jan    30-Jan
Purchase total value     $10.00      $20.00      $70.00      $50.00      $130.00     $10.00      $20.00

Any idea how to create this on PRD ?
currently i have PRD 3.9 & 5.0

A:

To answer my own question, refer to link below
http://www.youtube.com/watch?v=o_J3nkFRgpI
But crosstab can only works well in version 4.0 above.
I tried on my version 3.9 it doesn't work well. The aggregation is not working.


Q:

How to divide two Prometheus Counters

I have two metrics, Counters to be precise, lets say they are called

NumberOfVisitors
NumberOfLogins

In grafana I would like to plot is the number-of-logins divided by the number of visitors (or the other way around) over time. So I tried
rate(NumberOfLogins) / rate(NumberOfVisitors)

but this results in an error

Error executing query: invalid parameter 'query': parse error at char
  46: expected type range vector in call to function "rate", got instant
  vector

I'm not sure what all that means. Hopefully something like this is possible. Any help would be appreciated

A:

The rate function expect a range vector, for example:
rate(NumberOfLogins[5m])

That means to calcualte the rate within the last 5 minutes at each time point. You can change the 5m to other time range.
Therefore this would fit you need:
rate(NumberOfLogins[5m]) / rate(NumberOfVisitors[5m])


Q:

How can I replace \xA0 (or Non-ASCII) chars in a string to ' '?

I have an excel file with numerous Non-ASCII characters which I would like to replace with the space character.
This text is to be entered into a MySQL database, and it will not import with these characters in the strings. I get a HY000 Incorrect string value when trying to post the row.

A:

If the set of Non-Ascii characters is fixed you could use:
NewString := StringReplace(OriginalString,#1#4,' ',[rfReplaceAll])

where #1#4 is the non-ascii characters you want to have replaced.
Here is some docs on it's use.
You could also do this.
function StripNonAlpha(aInput : String) : String;
var
 I : Integer;
begin
 result := aInput;
 for I := 1 to length(result) do
 begin
   if not CharInSet(result[I],['A'..'Z','a'..'z']) then
      result[I] := ' ';
 end;
end;

Then you can change Set in CharInSet to the acceptable characters.


Q:

What is the meaning of this phrase "Someone has less authority than you "?

A sidekick might be a work assistant, a best friend, or even a devoted dog that follows you to school every day. Sometimes this word signifies an imbalance of power, though; if you say, “This is my sidekick, Sarah," it implies that       . "

A:

Authority means:
noun
 1. the power or right to give orders, make decisions, and enforce obedience.

The paragraph in your question talks about a "sidekick".  This is a person that usually helps a "superhero".  Therefore, the phrase "Someone has less authority than you" means that the other person (e.g 'Someone', 'sidekick', 'Sarah', etc) has less power that you.


Q:

MySQL table JOIN with ordering by averages

First off, I am not very good with MySQL yet, so go easy on me. I am not even sure how to word my question.
I have two tables; one table contains information about links, the other ratings of each link made by users. Essentially, I just need to be able to order the links table by rating average.
TABLES:
links

link_id  PK int autoincrement
url  varchar
title  varchar
description  text
rating decimal

link_ratings

link_rating_id PK int autoincrement
link_id FK int
user_id FK int
rating decimal

What I need is when someone adds a link rating to a link (new link_ratings entry) or updates their current rating, all of the ratings for that link are averaged and updated on the rating column in links. OR Can I scrap the rating column in the links table entirely and use a JOIN?
If so, how would I go about doing the JOIN. If not, how do I make TRIGGER that would accomplish this for me?
I haven't been able to find much information, most likely due to my lack of SQL knowledge, of how to even start this.
Any help is appreciated. Thanks.

A:

You don't need to persist the rating average in the links table. I am calculating it below, and this should perform reasonably well:
select l.link_id,
    l.url,
    l.title,
    l.description,
    lra.AvgRating
from links l
left outer join (
    select link_id, avg(rating) as AvgRating
    from link_ratings
    group by link_id
) lra on l.link_id = lra.link_id
order by lra.AvgRating desc


Q:

Replace "&" (ampersand) with ";" (semicolon) in URL

I know what you will going to tell me, but for learning purpose I need to know how to change the & in URL with ; using PHP.
For Example:
I have a URL like
http://example.com/index.php?show=products&index=20&page=5

It will become
http://example.com/index.php?show=products;index=20;page=5

I saw this on ESPN Cricinfo like they use it for their stats, commentary, like this page uses it.
As I think, we use $_GET['...'] to get values from URL in PHP, but this method may use some other string functions.
I already said, if you know how then tell me how. It is only for learning purpose.

A:

Set this option globally inside the php.ini file:
arg_separator.input = ";"

or locally for your current script execution with ini_set:
ini_set('arg_separator.input', ';');

From the docs:

arg_separator.input string
List of separator(s) used by PHP to parse input URLs into variables.

The option can receive a character set of possible separators, so if you need to make PHP parsing arguments both with semicolon and ampersand as a separator, set it equal to ;&.
Additionally arg_separator.output can be used to separate arguments in PHP generated URLs.
REF: http://www.php.net/manual/en/ini.core.php#ini.arg-separator.input


Q:

Having issues with javascript compiling

I have an application Javascript file that is showing an error in the console section of VS Studio Code, it keeps saying: app.js: The parser expected to find a '}' to match the '{' token here. and the console will not compile.
Based on my code, would you be able to tell me where I need to close in my braces? I think I might be confused.
Here is my app.js code:
const express = require('express');
const app = express();
const bodyParser  = require('body-parser');
const mongoose = require('mongoose');
//specify where to find the schema
const Item = require('./models/item')
// connect and display the status
mongoose.connect('mongodb://localhost:27017/items', { useNewUrlParser: true })
  .then(() => { console.log("connected"); })
  .catch(() => { console.log("error connecting"); });

// use the following code on any request that matches the specified mount path
app.use((req, res, next) => {
   console.log('This line is always called');
   res.setHeader('Access-Control-Allow-Origin', '*'); //can connect from any host
   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS'); //allowable methods
   res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');
   next();
});
app.get('/items', (req, res, next) => {
  //call mongoose method find (MongoDB db.Students.find())
  Item.find()
    //if data is returned, send data as a response
    .then(data => res.status(200).json(data))
    //if error, send internal server error
    .catch(err => {
    console.log('Error: ${err}');
    res.status(500).json(err);
});

  // parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// serve incoming post requests to /items
app.post('/items', (req, res, next) => {
    const items = req.body;
    console.log(items.itemName + " " + items.servings);
    //sent an acknowledgment back to caller
    res.status(201).json('Post successful');
  });

//to use this middleware in other parts of the application
module.exports=app;

A:

Your app.get('/items' function is not closed. Try this.

app.get('/items', (req, res, next) => {
  //call mongoose method find (MongoDB db.Students.find())
  Item.find()
    //if data is returned, send data as a response
    .then(data => res.status(200).json(data))
    //if error, send internal server error
    .catch(err => {
      console.log('Error: ${err}');
      res.status(500).json(err);
    });
});

But in the future, please just use an IDE of some sorts. Even just dumping your code into JSFiddle will highlight this for you.


Q:

makefile: execute one target from another target plus additional commands

I have a makefile with something like the following targets:

install:
    do a whole bunch of stuff to install

dist: install
    cp README.txt $(INSTALL_DIR)
    zip $(INSTALL_DIR)

I am trying to not repeat the commands from target install and make dist execute install first before executing its own commands.
Calling make dist does indeed execute all commands from target install but then just stops and it does not execute its own commands, e.g. the cp.
Am I missing something?

A:

try to add this line in your makefile
.PHONY : install dist


Q:

How to get PUT and DELETE parameters from HTTPRequest in SilverStripe?

There are getVars(), postVars() and requestVars() methods in HTTPRequest.
They returns parameters from GET and POST requests.
But how can I get parameters from PUT and DELETE requests?
I know that there is a 'body' property somewhere in HTTPRequest. It contains PUT params in query string or something similar.
To use this property I need to parse 'body' field.
Is there a way to get these parameters with comfortable way, like for GET and POST?

A:

You need to do it the old school way.
parse_str($request->getBody(), $params);
$foo = $params['Foo'];

Keep in mind the second parameter of parse_str is a reference, so no need to define that variable before invoking the function call.


Q:

Can I use relative fast queries in the SitecoreQuery attribute?

I have a working installation of Sitecore 7 + Glass Mapper 3 which I am looking to optimize.
An example of my code is:
[SitecoreQuery(".//*[@@templateid = '{011EC776-D9F3-4D73-8D8D-E454417E7574}']",
                                                               IsRelative = true)]
IEnumerable<ItineraryLine> Itinerary { get; set; }

I was hoping to use FastQuery but I get the error:

End of string expected at position 4

I gave the following solution a try this involves slotting in to the getLookupSourceItems pipeline - but I don't think this is the right pipeline as it doesn't trigger in debug.
Is there another pipeline (if at all) that Glass uses in this scenario? Is there a different way I can solve my goal of speeding this up?
If I wasn't using attributes but extension methods I could do this manually and use *[@@id=''] to set the root node, but I was hoping to avoid this if possible.

A:

When using the IsRelative setting to true GMS pushes the query throught Axes SelectItem. Sitecore does not allow fast query for Axes selects, e.g.:
Item.Axes.SelectItems("fast:./*");

See documentation here page 3:
http://www.iosh.co.uk/~/media/using%20sitecore%20fast%20query001.ashx
However GMS being awesome allows us to solve this another way, you can put placeholders in your query that GMS will expand. Removing the IsRelative property and using the {path}
placeholder allows the same result:
[SitecoreQuery("fast:{path}//*[@@templateid = '{011EC776-D9F3-4D73-8D8D-E454417E7574}']")]
IEnumerable<ItineraryLine> Itinerary { get; set; }

The path placeholder will be expanded to the full path of the current item being mapped.


Q:

Multiplying 3D matrix

I was wondering if it is possible to multiply a 3D matrix (say a cube $n\times n\times n$) to a matrix of dimension $n\times 1$? If yes, then how. Maybe you can suggest some resources which I can read to do this. Thanks!

A:

If you view the $n\times n\times n$ object as $n$ different $n\times n$ matrices, then you can apply each one to the $n\times 1$ vector, yielding $n$ different $n\times1$ vectors, which could be viewed as a $n\times n$ matrix.
This won't have interesting multiplication properties though beyond those that come from the regular matrix-vector multiplication.

A:

Multiplication of regular matrices arises from their interpretation as linear transformations. For a square matrix you get a map $T:V\to V$ (after having chosen a basis for $V$.) Since the domain and range of $T$ are the same, you can compose linear transformations, and this gives you matrix multiplication.
A cubical matrix can correspond to a linear map $V\to V\otimes V$ or $V\otimes V\to V$ (or a number of other possibilities such as $V\otimes V\otimes V\to \mathbb R$). (As Milind points out, this type of thing is called a tensor, and the different possibilities correspond to different placement of the indices up or down on the tensor, $t^i_{jk}, t^{ij}_k, t_{ijk}$, etc.
An $n\times 1$ matrix can represent a map from $V$ to $\mathbb R$. So if you think of the 3D array as a map from $V\otimes V\to V$, then you can compose it with the map $V\to\mathbb R$. The resulting map is a map $V\otimes V\to \mathbb R$, which can be thought of as an $n\times n$ matrix.


Q:

Why is the length of address of variable only 6 digits in hex code although my machine is 64 bit?

When I tried printing out address of variable in C to my standard output in hexadecimal format, I got a 6 digit answer to my surprise. Since, I work on a 64 bit machine, I expected to have a 16 digit long address since 2^{64} = 16^{16} but instead the address was just 6 digits long.
Code for reference:
#include<stdio.h>

int square();

int x;

int main(){
    scanf("%d",&x);
    printf("%d\n",square());
    printf("\naddress of x is %x",&x);
    return 0;
}

int square(){
    return x*x;
}

The output was:
address of x is 407970

A:

First of all printf("\naddress of x is %x",&x); is incorrect. %x expects an unsigned int.
The correct format specifier to print address is %p (more here):
printf("\naddress of x is %p",&x);

//To be more precise cast to void*, see @Gerhardh's comment below
printf("\naddress of x is %p", (void*)&x);

Why is the length of address of variable only 6 digits in hex code although my machine is 64 bit?

unsigned long x = 10;
printf("%lu", x); //prints 10

x is 10 in the above example. Does it mean x is now 8 bit wide? No. Similarly there is a range of addresses starting from 0, the address doesn't have to be big enough to be represented as full 64 bit always. You can assume it to be 0x00407970 in your case.

Side note: The following will have undefined behaviour if the value of x is large. Just enter 123123 as input and see what happens
int square(){
    return x*x;
}


Q:

Constructor/destructor defined by trait is not being called

How can I launch constructor and destructor defined by trait along with the class' constructor and destructor as well. For example,
trait Audit
{
    public function __construct()
    {
        parent::__construct(); // Doesn't work...

        $this->_name = __CLASS__;

        $this->AuditAction('Started');
    }

    public function __destruct()
    {
        parent::__destruct(); // Doesn't work...

        $this->AuditAction('Ended');

        echo $this->_log;
    }

    public function AuditAction($n)
    {
        $this->_log .= $this->GetCurrentTimeStamp() . ' ' . $this->_name . ": $n" . PHP_EOL;
    }

    private function GetCurrentTimeStamp()
    {
        return (new DateTime())->format('[Y-m-d H:i:s]');
    }

    private $_name, $_log = '';
}

class C
{
    use Audit;

    public function __construct()
    {

    }

    public function __destruct()
    {

    }
}

$c = new C();
I should get couple of lines of text but I get none since class C's constructor is explicitly called instead. Is there a way to achieve this?

A:

The constructor and destructor of C will have precedence over the trait constructor and destructor when the class is composed:

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.

Source: http://php.net/traits
In other words, remove the empty constructor and destructor from C and the trait's constructor and destructor will be used. There is no way to make this work with both, C and the traits, constructor and destructor, because traits do not work like regular inheritance.
In general, I would advise against giving Traits their own constructors or destructors because you cannot instantiate Traits. You instantiate from a class having a Trait and that class should be in control. Consider adding an onCreate() or onDestroy() method to the trait instead and call these from the appropriate magic methods on C. You could achieve the same by aliasing the traits __construct in C, but I think this waters down semantics.

A:

Addition to Aeremdir's answer: inherited constructors from base class and multiple traits...
<?php
  trait T1 {
    public function __construct() {
      $this->someval |= 0b0001;
      echo "T1::__construct() done\n";
    }
  }

  trait T2 {
    public function __construct() {
      $this->someval |= 0b0010;
      echo "T2::__construct() done\n";
    }
  }

  class C1 {
    protected $someval;

    public function __construct() {
      $this->someval = 0b10000000;
      echo "C1::__construct() done\n";
    }
  }

  class C2 extends C1 {
    use T1, T2 {
      T1::__construct as private T1__construct;
      T2::__construct as private T2__construct;
    }

    public function __construct() {
      parent::__construct();
      $this->T1__construct();
      $this->T2__construct();

      $this->someval |= 0b00100000;
      echo "C2::__construct() done\n";
    }

    public function someval() {
      $str = base_convert($this->someval, 10, 2);
      $len = strlen($str);
      if($len < 8)
          $str = str_repeat('0', 8 - $len) . $str;

      return '0b' . $str;
    }
  }

  $v1 = new C2();
  echo $v1->someval();
?>

under PHP 7.0.5 this code results in...

C1::__construct() done
  T1::__construct() done
  T2::__construct() done
  C2::__construct() done
  0b10100011


Q:

Bind Text to size

How can i bind a Text property from a textBox to a Width of a panel?
I tried:
   panel1.DataBindings.Add("Text", textBox3, "Size.Width");

but it raises exception
Object does not match target type.

EDIT: I want to change the width of panel, as text in textbox is changed.

A:

Try this:
void MakeBind()
{
     Binding bind = new Binding("Width", textBox3, "Text");
     bind.Format += new ConvertEventHandler(bind_Format);
     panel1.DataBindings.Add(bind);
}
void bind_Format(object sender, ConvertEventArgs e)
{
     int i = 0;
     int.TryParse((string)e.Value, out i);
     e.Value = i;
}

You also should know, that you can't directly change Size.Width, because of Size is a property, which returns value type, which you can't change this way. Only to set new Size with new Width.


Q:

Ways of writing $n=2a+b$ with $a$ and $b$ are non-negative integers

For a non-negative number $n$, let $r_n$ be the number of ways of writing
$n = a + 2b$, where $a$ and $b$ are non-negative integers.
For example,
$5 = 1  \cdot 5 + 2 \cdot  0 = 3 \cdot  1 + 1 \cdot  2 = 1 \cdot  1 + 2 \cdot  2$,
so $r_5 = 3$.
My question is I have found the rule that:
$r_0=r_1=1$,
$r_2=r_3=2$,
$r_4=r_5=3$,
$r_6=r_7=4$,
......
$r_{n-1}=r_{n}=\frac{n+1}{2}$ where $n$ is odd.
But how can we prove this rule?

A:

Note that $a$ is determined by $n$ and $b$ via $a=n-2b$, so $r_n$ is the number of valid choices for $b$. Since $a$ and $b$ must be nonnegative, we get $b\geq 0$ and $n-2b\geq 0$, so $\frac n2\geq b \geq 0$. If $n=2k$ or $2k+1$, then the only integer values $b$ can take are $0, 1, \ldots, k$ so there are $k+1$ choices. In particular, in the case $n=2k+1$, $$k+1=\frac{n-1+2}{2}=\frac{n+1}{2}$$ which is exactly the formula you found.


Q:

How to display the value get from .val()

I have this code here but it doesn't work... I have a text input where user can key in any number. When user click on ADD, it will add a new row to the table. when click on REMOVE, that row will be remove.
I want to keep track of the index and it is working. However I need to keep track of the number the user input as well, then I can remove that row with that number. However, I can't get the textInput to be displayed on the table... not sure what's the right way to display that. Please help.
 var index=1;
 textInput = $('#outputTextInput').val();

 $('#outputAdd').click(function(){
                   index++;
                   $('#status_table tr:last').after('
'+index+'	type_row_'+textInput+'	num row '+index+'
');
                });
  $('#outputRemove').click(function(){

                    $('#status_table').find("#output_newrow_'+textInput+'").remove();
               });

A:

Replace this:
$('#status_table').find("#output_newrow_'+textInput+'").remove();

With this:
$('#status_table').find("#output_newrow_" + textInput).remove();

and try again!


Q:

What is the use of hello_view.ex in Phoenix

I was reading the 'Programming Phoenix' book to create my first MVC simple routing project. In the book, it says to create a 'hello_view.ex', and it's under the view section in MVC. But there is already a view in templates. This feels very confusing.
Also, they told me to put hello_world.html inside 'hello' folder in templates. Can I change this folder name? Why can't I rename it? In 'hello_controller.ex', it says 'hello_world.html', not 'hello/hello_world.html'

A:

Phoenix views aren't HTML templates with embedded programming language like html.erb, but the names are similar to the ones in Django, where view means code for displaying data and template means actual HTML with embedded Elixir code (and they have extension eex).
According to the official guide for Phoenix Framework, short info about views:

They also act as a presentation layer for raw data from the controller, preparing it for use in a template. Functions which perform this transformation should go in a view.

Check this out:
Ruby on Rails flow:
router.rb -> Controller (-> Model) -> view in html.erb
Django flow:
urls.py -> View (act like Controller) -> Template
Phoenix flow:
endpoint (in lib) -> router (in web) -> Controller -> View -> Template
The Phoenix flow seems to be longer, but it's not. The biggest advantage for you:
You have explicit control over the middleware!
Remember that- framework does the magic for you, but explicitly. You exactly see what macros and other stuff are called.
Edit
Check out the stuff that's imported when using use in your code.
In your controller you're using Phoenix.Controller stuff, which provides you render function.
You call render with conn, template and assigns parameters. In deps/phoenix/lib/phoenix/controller.ex you have this render
function stored and in the private function do_render line:
view = Map.get(conn.private, :phoenix_view) ||
        raise "a view module was not specified, set one with put_view/2"

Gets your View name from the current connection.
And few lines later uses it:
Phoenix.View.render_to_iodata(view, template, Map.put(conn.assigns, :conn, conn))

This call uses internally render in deps/phoenix/lib/phoenix/view.ex
and then render_within, but the name of the folder is set in __using__
use Phoenix.Template, Phoenix.View.__template_options__(__MODULE__, unquote(opts))

which calls __template__options where following lines are placed:
    module
    |> Module.split()
    |> Enum.take(1)
    |> Module.concat()

which does the Hello from Hello.PageView or whatever the name is.
Edit2
About changing default view in controller (info from Phoenix documentation):

By default, Controllers render templates in a view with a similar name
  to the   controller. For example, MyApp.UserController will render
  templates inside   the MyApp.UserView. This information can be
  changed any time by using   render/3, render/4 or the put_view/2
  function:

  def show(conn, _params) do
    render(conn, MyApp.SpecialView, :show, message: "Hello")
  end

  def show(conn, _params) do
    conn
    |> put_view(MyApp.SpecialView)
    |> render(:show, message: "Hello")
  end


Q:

How to create customize popup using absolute layout?

Is there a way to use absolute layout as a customize pop-up? I am trying to create a customize popup. Is this possible?
<StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BackgroundColor="Yellow">
    //Elements here
</StackLayout>
<AbsoluteLayout StyleClass="dialogbox" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
   //Popup here
</AbsoluteLayout>

A:

You can achieve that with AbsoluteLayout and add a fade animation. Here is running GIF.

There is code.
      <StackLayout>

    <Button
        x:Name="btn"
        Text="click"
        />

    <ContentView x:Name="popupLoginView" BackgroundColor="#C0808080" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
        <AbsoluteLayout  VerticalOptions="Center" HorizontalOptions="Center">
            <StackLayout Orientation="Vertical" HeightRequest="200" WidthRequest="300" BackgroundColor="White">
                <Entry Margin="20,20,20,10" Placeholder="Enter Username"></Entry>
                <Entry Margin="20,0,20,0" Placeholder="Enter Password"></Entry>
                <Button Margin="20,0,20,0" Text="Login"></Button>

            </StackLayout>
        </AbsoluteLayout>
    </ContentView>
</StackLayout>

In xamarin forms, you can add fade animation to view. There is animation code.
 public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
      btn.Clicked += Btn_Clicked;
    }

    private async void Btn_Clicked(object sender, EventArgs e)
    {

        if (popupLoginView.IsVisible==true)
        {
            btn.IsEnabled = false;
              await popupLoginView.FadeTo(0,2000);
            await Task.Delay(2000);
            popupLoginView.Opacity = 0;
            popupLoginView.IsVisible = false;

            btn.IsEnabled = true;
            return;

        }
        if (popupLoginView.IsVisible == false)
        {

            if (popupLoginView.Opacity==1)
            {
                popupLoginView.Opacity = 0;
            }

            popupLoginView.IsVisible = true;
            btn.IsEnabled = false;
            await popupLoginView.FadeTo(1, 2000);
              await Task.Delay(2000);
            btn.IsEnabled = true;
            popupLoginView.Opacity = 1;
            return;

        }

    }
}

There is article about fade animation.
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/animation/simple#fading
If you want to achieve it with Rg.Plugins.Popup and add the animation, you can refer to this article, it will add some animations.
https://www.c-sharpcorner.com/article/learn-about-xamarin-forms-animation-with-popuppage/


Q:

Could not find com.android.tools.build:gradle:4.3.3

Error :
Could not find com.android.tools.build:gradle:4.3.3.
Searched in the following locations:
  - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.3.3/gradle-4.3.3.pom
  - https://jcenter.bintray.com/com/android/tools/build/gradle/4.3.3/gradle-4.3.3.pom
  - https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/4.3.3/gradle-4.3.3.pom
Required by:
    project :

build.gradle(Project):
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.3.3"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(app):
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.blogger"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

}

This is while Trying to connect to fire base .(Add Firebase to your Android app)
https://console.firebase.google.com
Kindly help I have downloaded google-services.json and synced it as well  and it gives this error.

A:

The version 4.3.3 of the android gradle plugin doesn't exist.
Use:
classpath "com.android.tools.build:gradle:4.0.1"

Don't confuse it with the google play services plugin:
classpath 'com.google.gms:google-services:4.3.3'


Q:

How to create a horizontal scroll bar when shrinking the window

If I have a content area with a width of 1225px how do I make it so that when you shrink the page to less than that width a horizontal scroll bar appears so that that center content will always be visible (at least have the option for scrolling)?  Would it involve using fixed or absolute positioning?
In this site, you can see when you shrink the page, the horizontal scroll bar appears:  http://www.websitecodetutorials.com/
I don't know if it helps, but here is some of my code:

Pathfinder is Temporarily Unavailable

I used a CSS reset.  Here is some of my CSS:
.bar {
    background-color:#365C8C;
    height:30px;
    width:auto;
    position:relative;
    padding:0 0 0 0;
    margin:0 0 0 0;
    overflow-x:hidden;
}

body {
    position:relative;
    padding:0 0 0 0;
    margin:0 0 0 0;
    overflow-x:hidden;
    height:100%;
    width:100%;
    background-color:#ADCCEB;
    /*background-color:black;*/
    /*background: url(background.png);*
    /*background-size:100%;*/
}

.bold {
    font-weight:bold;
}

.contentcontainer {
    width:825px;
    height:870px;
    margin-left:auto;
    margin-right:auto;
    margin-top:0px;
    padding-top:0px;
    /*background-color:red;*/
}

.extcontentcontainer {
    width:825px;
    height:645px;
    margin-left:auto;
    margin-right:auto;
    margin-top:0px;
    padding-top:0px;
    /*background-color:red;*/
}

img.fullbackground {
    position:absolute;
    z-index:-1;
    top:0;
    left:0;
    width:100%;
    height:100%;
    padding: 0 0 0 0;
    margin: 0 0 0 0;
}

img.extfullbackground {
    position:absolute;
    z-index:-1;
    top:0;
    left:0;
    width:100%;
    height:100%;
    padding: 0 0 0 0;
    margin: 0 0 0 0;
}

A:

You may try adding this property to the body tag:
overflow-x:auto;


Q:

Intellij GUI Designer doesn't generate $$$setupUI$$$ method

I'm working on something in Intellij-ScalaPlugin and I want to modify something in the Settings Panel. I changed the text from an existing label and after compiling the project the $$$setupUI$$$ method is unchanged.

I'm trying to change the text from the label shown in this image, but after compilation the $$$setupUI$$$ method is not changed.

What can I do in order to fix this problem?

A:

Configure GUI Designer to generate source code instead of instrumenting binary classes:

For this specific plug-in project you will also need to disable Use SBT shell for build and import option.


Q:

How can I still use Borderlayout constant with a panel that is not a different Layout manager?

How am I able to use Borderlayout.EAST on a panel for this particular case with a panel that has a different layout, which is a BoxLayout layout manager? Don't the panel itself has to be able a BorderLayout manager in order for it to be able to use BorderLayout.CONSTANT?
 JPanel jp1 = new JPanel();
 jp1.setLayout(new BoxLayout(jp1, BoxLayout.X_AXIS));
 JPanel jp2 = new JPanel(new GridLayout());
 jp1.add(jp2, BorderLayout.EAST); //This worked even though jp1 is a BoxLayout, how did it use BorderLayout?

A:

This can be a little convoluted. When you add() a Component to a Container, addImpl() handles the request. An original LayoutManager like BorderLayout understands constants like BorderLayout.EAST, which has the String value "East". A newer LayoutManager2 like BoxLayout never sees the unused constraint. In particular,

If the current layout manager implements LayoutManager2, then LayoutManager2.addLayoutComponent(Component,Object) is invoked on it. If the current layout manager does not implement LayoutManager2, and constraints is a String, then LayoutManager.addLayoutComponent(String,Component) is invoked on it.

Addendum: BoxLayout implements both LayoutManager and LayoutManager2. Although BoxLayout must provide both variations of addLayoutComponent(),  the method is "Not used by this class." In effect, the BorderLayout.EAST constraint is ignored.
void    addLayoutComponent(Component comp, Object constraints)
        Not used by this class.
void    addLayoutComponent(String name, Component comp)
        Not used by this class.


Q:

How can I use same JAXB class to marshall and unmarshall into different namespaces?

Note: this is with Java 7.  Also, I am not using JAXB to generate anything from a schema.  I only/merely want to use JAXB to deserialize pieces of existing SOAP messages.  So the JAXB beans are "hand-written".
I am trying to deserialize the following XML with JAXB.  I do not have access to it as a string.  Rather, I am getting it as an org.w3c.dom.Element object:
<SynchInfo xmlns="urn:InitronSOAPService">
    <HandshakeInfo>
        <dnsName>foo.bar</dnsName>
        <ip>1.2.3.4</ip>
        <id>TheId</id>
        <key>SomeKey</key>
        <version>1.0</version>
    </HandshakeInfo>
</SynchInfo>

But I would also like to marshall HandshakeInfo instances into a SOAPBody that is part of a message belonging to a different namespace.
I first tried to write a HandshakeInfo class that didn't mention namespaces at all:
@XmlRootElement(name = "HandshakeInfo")
@XmlAccessorType(XmlAccessType.NONE)
final private static class HandshakeInfo
{
    private String version;
    private String id;
    private String key;
    private String ip;
    private String dnsName;

    public String getVersion() {
        return version;
    }

    @XmlElement(name = "version")
    public void setVersion(String version) {
        this.version = version;
    }

    public String getId() {
        return id;
    }

    @XmlElement(name = "id")
    public void setId(String id) {
        this.id = id;
    }

    public String getKey() {
        return key;
    }

    @XmlElement(name = "key")
    public void setKey(String key) {
        this.key = key;
    }

    public String getIp() {
        return ip;
    }

    @XmlElement(name = "ip")
    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getDnsName() {
        return dnsName;
    }

    @XmlElement(name = "dnsName")
    public void setDnsName(String dnsName) {
        this.dnsName = dnsName;
    }
}

But when I used that to try to deserialize the Element object containing the HandshakeInfo element, I got the following exception:
javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:InitronSOAPService", local:"HandshakeInfo"). Expected elements are <{}HandshakeInfo>
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)
...

So then I tried adding , namespace="urn:InitronSOAPService" to all the element and attribute (in this case none) annotations in the class.  (Or, alternatively, used an @XmlSchema annotation in a package-info.java file.)  That worked for deserializing that element in that namespace.
But when I tried to use the class to serialize into a different namespace I (not entirely unexpectedly) get stuff like this:
<SomeMessage xmlns="urn:differentNamespace">
    <ns5:HandshakeInfo xmlns:ns5="urn:InitronSOAPService">
        <ns5:dnsName>foo.bar</ns5:dnsName>
        <ns5:ip>1.2.3.4</ns5:ip>
        <ns5:id>TheId</ns5:id>
        <ns5:key>SomeKey</ns5:key>
        <ns5:version>1.0</ns5:version>
    </ns5:HandshakeInfo>
</SomeMessage>

That's not what I want.  I want the serialized thing to be part of the urn:differentNamespace.
So is there any way to use the same JAXB class in multiple namespaces?  Or am I stuck with having to multiple copies of classes with each one annotated to be in the appropriate namespace?
I have seen some tricks using filters, etc. but those tricks seem to be assuming the XML is being read from or written to a stream or a file.  Again, for unmarshalling I am working with org.w3c.dom.Element objects and for marshalling I am working with SOAPBody objects.

A:

I see the following options:

Use MOXy XML Bindings and move mappings out of annotations into XML resources. You could then define and load different resources for different namespaces.
Use XSLT to preprocess XML prior to unmarshalling/postprocess after marshalling. Remapping namespaces is a trivial task in XSLT.
Use a custom AnnotationReader for JAXB RI to "fake" namespace read from annotations. You just have to adjust the namespace read from the package, should not be too hard.

AnnotationReader solution is a bit "hacky", also ties you to JAXB RI. XML bindings would require you to rewrite your annotations in XML form and will tie you to MOXy (I think). XSLT is quite elegant but will make the processing slower. And you'll have to hack into the processing chain with your XSLT.
All the options have pros and cons, you have to carefully consider them for your specific case.


Q:

How to use local-storage

So I have this game and I would like to have a save function. Here is my code below:
function SaveData() {
  localStorage.setItem('save', score);
  localStorage.setItem('save', btoa(JSON.stringify(score)));
}
function LoadData() {
  score = window.localStorage.getItem('save');
  document.getElementById('demo').innerHTML = score;
}
window.onload = function()  {
LoadData();
}

When it loads it does not use the storage or it says Not a Number (NaN)

A:

Ok, so let's assume you have a DOM element in which you display the score, and start with that.
So, the first time the user will arrive on the game, the score will be "0" (you will probably have something to calculate it and that's not the scope of this answer, let's focus on the load and save parts for now.
I'll write the save function in this way:
function SaveData(score) {
  localStorage.setItem('save', btoa(score));
}

While, the load function could be like:
function LoadData() {
  var score = window.localStorage.getItem('save');
  if (score === null){
    score = 0;
  }else{
    score = atob(score);
  }
  document.getElementById('demo').innerHTML = score;
}

I've used the btoa an atob, but they are unnecessary to save just a number, but since you used them I suppose there will be a reason, I deleted the JSON.stringyfy (and not added the parse) because that's totally unnecessary and could be trivial, because you will end up with an object (or an error)


Q:

Is it possible to sort an array in O(n) if there are only elements from 1 to n?

Let's say the comparison of elements in array takes O(n), is it possible to sort the array in O(n) when it has elements starting from 1 to n?
We need to create an algorithm like that but don't know if it's even possible. I could think of one in O(n^2).
I'm not asking for the algorithm, will take my time to create one but need to know if it's possible at all.

A:

It is definitely possible to do so, you simply create an array with counters and count the number of times element i occurs, since the elements range from 1 to n, you know this counter has length n.
Next there is the generate step, where you simply generate ki elements i if you have encountered ki such elements.
Example code in Java:
int[] data = {5,1,2,4,5,1,2,3};

//assuming data contains only values from 1 to n (included) with n the length
public static int[] sort_int_limited (int[] data) {
    int n = data.length;
    int[] counters = new int[data.length];

    //counter phase
    for(int i = 0; i < n; i++) {
        counters[data[i]-1]++;
    }

    //generate phase
    int k = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < counters[i]; j++) {
            data[k++] = i+1;
        }
    }

    return data;
}

jDoodle demo
As @Aivaen says in his/her comment, this algorithm is called counting sort.


Q:

printf of a size_t variable with lld, ld and d type identifiers

I wrote this tiny code:
#include <stdio.h>
int main() {
    size_t temp;
    temp = 100;

    printf("lld=%lld, ld=%ld, u=%u\n", temp, temp, temp);

    return 0;
}

I am running this on a i386 GNU/Linux machine with gcc version 4.1.1 20070105 (Red Hat 4.1.1-52). This is the output that I got:
lld=429496729700, ld=100, u=7993461

I can understand that the first (lld) was printed as garbage because the printf tries to print 8 bytes (for signed long long as signified by lld) when only 4 bytes are available from variable temp.
But, I fail to understand why the last identifier, u is getting printed as garbage - whereas, in my understanding this is the closest applicable identifier for size_t.
Here I have assumed that size_t is unsigned int (which is signed 4 bytes for my i386).
Now, I did a little tweaking with the printf line:
...
printf("ld=%ld, u=%u, lld=%lld\n", temp, temp, temp);
...

and I have a perfectly fine answer (except the lld part).
ld=100, u=100, lld=34331653576851556

Can someone please help me in understanding what exactly am I missing here?
Thanks a lot for any help!
[side note: I tried switching optimization using gcc -O[0,2] tag on/off without any difference in the observation.]

A:

That's because what you've pushed on the stack is three 32-bit values and your format string tries to use four of them or, more accurately, one 64-bit value and two 32-bit values.
In the first case, the lld sucks up two 32-bit values, the ld sucks up the third one and the u gets whatever happens to be on the stack after that, which could really be anything.
When you change the order of the format specifiers in the string, it works differently because the ld sucks up the first 32-bit value, the u sucks up the second and the lld sucks up the third plus whatever happens to be on the stack after that. That's why you're getting different values, it's a data alignment/availability issue.
You can see this in action with the first value. 429496729700 is equal to (4294967296 + 1) * 100, i.e., (232+1)*100. Your code snippet
printf("lld=%lld, ld=%ld, u=%u\n", temp, temp, temp);

actually has the following effect:
What you pass     Stack     What printf() uses
-------------     -----     ------------------
                 +-----+
100              | 100 | \
                 +-----+  = 64-bit value for %lld.
100              | 100 | /
                 +-----+
100              | 100 |    32-bit value for %ld.
                 +-----+
                 | ?   |    32-bit value for %u (could be anything).
                 +-----+

In the second case
printf("ld=%ld, u=%u, lld=%lld\n", temp, temp, temp);

the following occurs:
What you pass     Stack     What printf() uses
-------------     -----     ------------------
                 +-----+
100              | 100 |    32-bit value for %ld.
                 +-----+
100              | 100 |    32-bit value for %u.
                 +-----+
100              | 100 | \
                 +-----+  = 64-bit value for %lld (could be anything).
                 | ?   | /
                 +-----+

A:

Your code aptly demonstrates Undefined Behavior. Note that in case of variadic arguments no type checking is done for parameters. This is when an explicit cast becomes necessary. In fact the following should therefore be used:
 printf("lld=%lld, ld=%ld, u=%u\n",
         (unsigned long long)temp,
         (unsigned long)temp,
         (unsigned int)temp);

As an aside remember the specifier for size_t is z. So:
 printf("zd=%zd\n", temp);


Q:

How to scroll up in GridView that is in a BottomSheetDialog?

I created a BottomSheetDialog that has a GridView in it. When the BottomSheetDialog is opened, you can scroll down normally. Doing so makes the BottomSheetDialog expand to full screen and scroll down in GridView normally.
However when user tries to scroll up; instead of scrolling up in GridView, BottomSheetDialog shrinks and closes.
What I want is being able to scroll up and down in GridView without BottomSheetDialog changing sizes.
How to do it?
My Code:
final BottomSheetDialog dialog = new BottomSheetDialog(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.grid, null);
dialog.setContentView(view);

grid.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <GridView
        android:background="#FFFFFF"
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:horizontalSpacing="4dp"
        android:verticalSpacing="4dp"
        android:gravity="center"
        />

</LinearLayout>

A:

Solved:
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(final DialogInterface dialog) {
                    BottomSheetDialog d = (BottomSheetDialog) dialog;
                    FrameLayout bottomSheet = (FrameLayout) d.findViewById(android.support.design.R.id.design_bottom_sheet);
                    // Right here!
                    final BottomSheetBehavior behaviour = BottomSheetBehavior.from(bottomSheet);
                    behaviour.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                        @Override
                        public void onStateChanged(@NonNull View bottomSheet, int newState) {
                            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                                dialog.dismiss();
                            }

                            if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                                ((BottomSheetBehavior) behaviour).setState(BottomSheetBehavior.STATE_EXPANDED);
                            }
                        }

                        @Override
                        public void onSlide(@NonNull View bottomSheet, float slideOffset) {

                        }
                    });
                }
            });


Q:

Php design patterns

Ok, i'd like to firstly make you notice that i have looked for "php mvc design patterns" and so and i haven't really found what i was looking for; still now, writing my question, i cannot find any related and so specific question as i am going to ask. But i know i'm probably wrong, anyway consider this question and a question pack that could be usefull togheter.
Question

I was wondering how we should consider the design patterns. I mean: What are they? Are they simply binaries that help us designing consistent application? Are they so used? Why?
Where could i find a list about every design patterns on the web? Or at least the 5-10 most used design patterns?
Do Phpbb, Wordpress or Joomla (that i know pretty well) use a design pattern? If yes, which?
I googled MCV PHP and found about 3 italian articles and read about 5 of the first pages ranked and i didn't understand pretty much nothing. They were conflicting and seemed to me confusing. I did understand that it is usefull to separate business login, script and view (?) but i didn't got anything else. I am probably stupid or something but where could i find a nice and official (means written by the Gang of Four or someone who actually know what he is talking about) mvc tutorial or documentation related to php?
Are there simple examples about design patterns and how they are better then (normal) writing styles? Are there simple examples about a mvc or other design pattern? For example a simple blog written with a design pattern?

Tips
I'd prefer free solution first. I don't like frameworks, so please don't refer to them even if (i know) they have mvc and other valid design patterns and benefits. I still don't like them. Thanks
Notice
I'll choose my accepted answer after tomorrow, so, please, take your time to answer.

A:

What are they?

Design patterns are language-agnostic blueprint solutions for common problems. They are not downloadable code or readymade implementations, but a theoretical approach you can implement/translate into working solutions.
Design Patterns also allow for easier communication between developers who know patterns, because when developer A says: this is a Factory, developer B will know what is meant.

Where could i find a list about every design patterns on the web? Or at least the 5-10 most used design patterns?

GOF patterns with examples in various languages
Fowler's POEAA
StackOverflow has plenty results
Five common PHP design patterns
Five more PHP design patterns
Design Patterns in PHP (with examples)

There is also a recommendable book called PHP Design Patterns (german only) for which you can download the code samples at http://www.phpdesignpatterns.de/auflage-2/#beispiele

Do phpbb, wordpress or joomla (that i know pretty well) use a design pattern? If yes, then which?

Probably, but listing each and every pattern an application uses is rather pointless. Some patterns are tiny, some are more complex. You dont use them to use them, but to solve problems.
Let me stress that: you dont use them to use them. They are not some sort of status symbol. You dont want to amass them. You even don't have to implement them by the book. Use them where appropriate with every variation required to solve a concrete problem in your application.

I googled MCV PHP and found about 3 italian articles and read about 5 of the first pages ranked and i didn't understand pretty much nothing. They were conflicting and seemed to me confusing. I did understand that it is usefull to separate business login, script and view (?) but i didn't got anything.

MVC is not a GOF pattern. It is listed in POEAA but it's way older than that. The MVC you usually see on the web has nothing to do with the "classic" MVC because there is the internet between view and the other two.
Basically, there is not much to know about MVC. It's very simple pattern. The idea is to split a UI into three distinct roles. The model is all your business logic. Your controller handles any requests from the view and delegates to the model. Your view displays the model. You should be able to replace the controller and views without having to touch your model.

Are there simple examples about design patterns and how they are better then (normal) writing styles?

Plenty. See the links above for some examples. If they are not clear enough, have a look around StackOverflow searching for their names.

A:

You would probably get better results googling for MVC PHP instead of MCV PHP.
Design patterns can be applied to all object oriented languages so you might be best advised
to look into THE design pattern book and into Object Oriented Programming with PHP.
There also is an article series on DZone about practical PHP patterns.


Q:

Does IoC with constructor injection in asp.net mvc controllers waste resources?

I'm not sure if its just me, but I get the feeling that constructor injection used in ASP.NET MVC controllers is causing unnecessary resource consumption.
Components that's not being used for a particular web request still needs to be created when controllers are created. It's like buying booth milk and juice when I'm thirsty for milk and then I just throw away the juice.
Compare these examples of constructor injection and service locator for controller to clarify my concern.
Constructor Injection, booth deps are created but only one is used.
public class MyController : Controller
{
    private readonly IDep1 _dep1;
    private readonly IDep2 _dep2;

    public MyController(IDep1 dep1, IDep2 dep2)
    {
        _dep1 = dep1;
        _dep2 = dep2;
    }

    public ActionResult Index()
    {
        _dep1.MakeStuff();
        return View();
    }
    public ActionResult PageTwo()
    {
        _dep2.MakeStuff();
        return View();
    }
}

Service Locator, each dep are created only when its being used.
public class MyController : Controller
{
    public ActionResult Index()
    {
        var dep1 = ServiceLocator.Resolve<IDep1>();
        dep1.MakeStuff();
        return View();
    }
    public ActionResult PageTwo()
    {
        var dep2 = ServiceLocator.Resolve<IDep2>();
        dep2.MakeStuff();
        return View();
    }
}

PLEASE NOTE that an IoC container (which is beneficial for many reasons) can still be used for the Service Locator pattern. I do not want this to be a discussion around IoC and container frameworks neither other benefits from constructor injection (clear visibilty of dependencies etc). It's the constructor injection pattern and how it wastes resources in ASP.NET MVC controller situations that is my concern.
I guess the main question here is:
Is Service Locator a better solution performance wise for the above scenario (ASP.NET MVC controllers) ?

A:

If the object creation is your bottleneck you are in either a very good situation (everything else works like a charm so the < 1 ms operations count) or in a very bad one (your constructors are doing some heavy lifting - which they are not supposed to).
Mark Seemann already covered the subject here:
http://blog.ploeh.dk/2011/03/04/Composeobjectgraphswithconfidence/

In many cases that's a performance hit you'll have to take because you
  need those classes anyway, but sometimes you might be concerned with
  taking this performance hit too early. However, I make the claim that
  in the vast majority of cases, this concern is irrelevant.

And supplied a possible solution if it still matters to you (deferred branches).


Q:

Need rock garden plant and layout guidance

I am converting a small fountain and pond into a rock garden. Space to work with is about 2' x 4'. So far, I have Anouk Lavender in the top-left corner, Blue Star Juniper in the bottom-right corner and Cooper's Ice Plant in the lower-left corner. I just purchased a rosemary, Angelina Stonecrop and Blue Spruce Sedum (seen in middle photo's foreground), but I'm unsure of where to place them, if at all. It a high sunlight location in zone 7A and gets quite hot in the summer. Bonus points for evergreen plant suggestions.

A:

I'm sorry to tell you that your blue star juniper will more than fill that space on its own - the lavender won't take up much room widthways, but the Delosperma (ice plant) would also fill up most of area, so really, there isn't room for anything else. I suggest you remove the blue star juniper altogether - it will spread all over the plant behind it where its planted now and is altogether too large for such a small area. When choosing plants, checking their eventual spread as well as height prior to planting is important.
Blue spruce sedum will spread up to 12 inches all round; rosemary will be a large shrub, 6 x 6 feet, so you can see that area is way too small for all these plants. Hopefully, you can find somewhere else for most of them.
Rock plants are usually much, much smaller subjects - Armeria maritima, for example, is an evergreen perennial with grass like foliage and bright pink flowers in spring, but it doesn't get much bigger than 4-6 inches wide. Others, like Euphorbia myrsinites, get about 6 inches tall with a spread of around 10 inches, whereas Iberis sempervirens can spread up to 2 feet - these three are evergreen. Some guidance can be found at Rock gardens: plants.

A:

I have a bit of a hill in the back yard.Was very hard to mow,mostly mowed the dirt.The area gets sun all afternoon and can get very dry.I hauled a bunch of rocks,different sizes shapes and colors and tried to create what they call a "rocky outcrop" almost like a waterfall effect.Filled it all in with river rock and planted Candytuft and Blue Festuca,the Candytuft will bloom this spring and the Festuca lasts all the way till winter.They propagate very quickly so their filling in nicely. The book I referenced is by H.Lincoln Foster, Rock Gardening.I have taken pictures of my rock garden would like to post them for the site, need help!


Q:

Counting uppercase and lowercase characters of String and appending count to the character

I am trying to print the output of a String to find the count of uppercase and lowercase in it.
E.g. if string = "AaaBBbCc",
I need the output as : "A1a2B2b1C1c1".
I.E. count of uppercase 'A' then count of lowercase 'a', appending with the characters.
Below is the code snippet till where I have done. Can any one suggest how it goes.
I know code is not up-to the mark :(
public static void main(String[] args) {
    String str = "AaaBBbCc";
    int upperCount=0;
    int lowerCount=0;

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if(ch>='A' && ch<='Z'){
             upperCount++;
             System.out.println("Uppercase letter is : "+ch+upperCount);

    }
     if(ch>='a' && ch<='z'){
        lowerCount++;
        System.out.println("Lower case letter is : "+ch+lowerCount);
    }
}
    System.out.println("upper count is :"+upperCount+" & lower count is: "+lowerCount);

}

A:

What you are trying to accomplish here is called Run-length encoding. This is sometimes referred to as a form of lossless data compression in which the length of a continuous character is appended to a single instance of that character. Here is a modified version from RosettaCode that should do the trick for you:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {

    public static String encode(String source) {
        StringBuffer dest = new StringBuffer();
        for (int i = 0; i < source.length(); i++) {
            int runLength = 1;
            while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
                runLength++;
                i++;
            }
            /* We will swap these so they fit your format of [Letter][Count]
            dest.append(runLength);
            dest.append(source.charAt(i));
            */
            dest.append(source.charAt(i));
            dest.append(runLength);
        }
        return dest.toString();
    }

    public static void main(String[] args) {
        String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
        System.out.println(encode(example));
    }
}


Q:

Calling member functions of an object stored in a vector

This may sound like a newbie question. How do I call a member function of an object stored in a vector ? Supposedly, I have this class:
class A {
public:
void foo() {
std::cout << "Hello World"; }
};

Then I store some objects in a vector:
std::vector<A*> objects;
A* b;
A* c;
A* d;

objects.push_back(b);
objects.push_back(c);
objects.push_back(d);

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this ? At first I thought I could just do something like this:
objects[2].foo();

But it seems that I can't do it like this.

A:

std::vector::operator[] returns a reference to the object in std::vector. As your objects stores a pointer to A, you should call it:
objects[2]->foo();

Now I want to create a loop, in which every object stored in the vector would call it's own foo() function. How should I do this

The easiest loop is:
for (int i=0; i<objects.size(); ++i)
{
   objects[i]->foo();
}

use C++11 for loop:
for(auto ep : objects)
{
    ep->foo();
}

Or for_each(need to write a small lambda though)
for_each(objects.begin(), objects.end(), [](A* ep){ep->foo(); });

Side note:
    In practice you'd better store value in STL container.
std::vector<A> objects;
for(auto e : objects)
{
    ep.foo();    // call member function by "."
}

If you want to store pointer with STL container, better use smart pointer, e.g.
#include <memory>
std::vector<std::unique_ptr<A> > objects;

objects.push_back(new A());
objects.push_back(new A());
objects.clear(); // all dynamically allocated pointer elements will be de-allocated automatically

A:

You can do this:
std::vector<A> objects;
A b;
A c;
A d;

objects.push_back(b);
objects.push_back(c);
objects.push_back(d);

objects[2].foo();

Please be a bit more specific about the exact error.  I suspect maybe the whole problem was trying to reference a pointer to an object with "." instead of "->".
But yes, in general:
1) You can save an object, or a pointer to an object, in any STL container
2) You can call any public method of that object upon accessing it from the container.


Q:

Shell - Execute imagemagic for all files in directory and store result

I need to execute next imagemagick command
convert some_image.jpeg logo: -fuzz 0% -negate -threshold 0 -negate -format "%[fx:100*mean]" info:

for all jpeg images inside some directory. The command above will return the percentage number (like 95.922983.4128). I need to compare that number to some threshold (say 98%) and if the percentage is greater than the threshold - move file to another directory.
Currently what I have is:
for filename in /writeData/TAX1040/*.jpeg; do
    white=$(convert $(filename) logo: -fuzz 0% -negate -threshold 0 -negate -format "%[fx:100*mean]")
    echo -n "$white"
done

And I have a missing an image filename error.
Thanks to @oliv I have a working script:
#!/usr/bin/env bash
mkdir -p /writeData/TAX1040/blank

for filename in /writeData/TAX1040/*.jpeg; do
    white=`convert $filename logo: -fuzz 0% -negate -threshold 0 -negate -format "%[fx:100*mean]" info:`

    p=${white:0:2}

    if [ "$p" -ge 98 ]; then
        echo "Percentage of white in file $filename is $p"
        echo "Moving file $filename to blank directory"
        mv "$filename" /writeData/TAX1040/blank
    fi
done

A:

The file must be used with "$filename" instead of $(filename) that actually executes the command filename (which is likely to fail).
Assuming that you convert command line is correct, you can then perform your check on the value like this:
threshold=98
for filename in /writeData/TAX1040/*.jpeg; do
  white=$(convert "$filename" logo: -fuzz 0% -negate -threshold 0 -negate -format "%[fx:100*mean]")
  if(( white > threshold )); then
     mv "$filename" /to/another/path
done

Note that in a arithmetic expression ((...)) you don't need to use the $ for the expansion.


Q:

Add background image to window.rootViewController or window directly?

I have a set of table views which the user can switch between using a tab bar controller, each table view has the same background.
Rather than have each table display the same background image I instead can do either of these:
[myDelegate.window addSubview: theUIImageView];

or
[myDelegate.window.rootViewController addSubview:theUIImageView];

Both work, should one be used rather than the other and why?
I have a similar question for displaying an activity indicator.
Thanks

A:

I think the principle is that the window should have one root view controller at the top of the tree, so I would maintain that. Other rulesets are available!


Q:

json serializing linq result in c#

I have some code that returns linq result (I even tried to add ToList())
I see the collection OK

but when I get out of the function body,
another abstraction layer is added

at the end ewhen I return the client the result
it gets:
"{ apps = System.Collections.Generic.List1[\u003c\u003ef__AnonymousType14[System.String,System.String,\u003c\u003ef__AnonymousType0`4[System.String,System.String,System.String,System.String],System.Object]], Status = succeeded }"
How can I serialize the linq result properly?
Update
Beforehand, it used to work without calling JSON()
    public object GetAppsData()
    {

        var appsData = new List<AppData>();
        using (IDataReader dr = DatabaseFactory.CreateDatabase().ExecuteReader("usp_AppsData_GetAll"))
        {

            while (dr.Read())
            {
                appsData.Add(new AppData()
                {
                    AppGuid = (Guid)dr["AppGuid"],
                    AppName = (string)dr["AppName"],
                    ClientAppID = dr["ClientAppID"] == DBNull.Value ? null : (string)dr["ClientAppID"],
                    Url = dr["Url"] == DBNull.Value ? null : (string)dr["Url"],
                    DisplayName = dr["DisplayName"] == DBNull.Value ? null : (string)dr["DisplayName"],
                    AppDesc = dr["AppDesc"] == DBNull.Value ? null : (string)dr["AppDesc"],
                    PrivacyPolicyUrl = dr["PrivacyPolicyUrl"] == DBNull.Value ? null : (string)dr["PrivacyPolicyUrl"],
                    TermsOfUseUrl = dr["TermsOfUseUrl"] == DBNull.Value ? null : (string)dr["TermsOfUseUrl"],
                    //Platform = dr["Platform"] == DBNull.Value ? null : (string)dr["Platform"],
                    //MaxVersion = dr["MaxVersion"] == DBNull.Value ? null : (string)dr["MaxVersion"],
                    LocalizationKey = dr["LocalizationKey"] == DBNull.Value ? null : (string)dr["LocalizationKey"],
                    Compatibility = dr["Compatibility"] == DBNull.Value ? null : jss.Deserialize<object>((string)dr["Compatibility"])

                });

            }
        }

        var appsDataJson = appsData.Select(GenerateAppsDataClientResponse);

        return new { apps = appsDataJson, Status = "succeeded" };
    }

    private object GenerateAppsDataClientResponse(AppData a)
    {
        object result;
        if (a.Compatibility == null)
        {
            result = new
            {
                id = a.ClientAppID,
                url = a.Url,
                optionsDialog = new
                {
                    displayName = a.DisplayName,
                    appDesc = a.AppDesc,
                    privacyPolicyUrl = a.PrivacyPolicyUrl,
                    termsOfUseUrl = a.TermsOfUseUrl
                }
            };
        }
        else
        {
            // this line throws NullReferenceException
            result = new
            {
                id = a.ClientAppID,
                url = a.Url,
                optionsDialog = new
                {
                    displayName = a.DisplayName,
                    appDesc = a.AppDesc,
                    privacyPolicyUrl = a.PrivacyPolicyUrl,
                    termsOfUseUrl = a.TermsOfUseUrl
                },
                compatibility = a.Compatibility
            };
        }
        return result;
    }
}

and
    [HttpGet]
    public ActionResult GetAppsData()
    {
        try
        {
           AppsDataManager appsData = new AppsDataManager();
           object adr =  appsData.GetAppsData();
           return this.JsonpOptional(adr);
        }
        catch (Exception ex)
        {
            Log.Application.Error("ClientDataController.GetSettings", ex);
            return this.JsonpOptional(new { Status = "failed", Reason = ex.Message });
        }
    }

A:

The cryptic datatype you see in the debugger is just the classname of the anonymous class you return with the new keyword.
Your main problem is, that you have to return a JsonResult and not the plain object. And don't forget to specify JsonRequestBehavior.AllowGet. Otherwise you will get an exception when returning JSON Data to a HTTP GET request:
return Json(new { apps = appsDataJson, Status = "succeeded" },
                 JsonRequestBehavior.AllowGet);


Q:

AttributeError: type object 'Global' has no attribute 'cursor'

I am getting below error while running the below database query in pyodbc.
Query
DECLARE  @TempTable Table (Flag int)
DECLARE @intFlag INT
DECLARE @intFlag1 VARCHAR(50);
SET NOCOUNT ON
SET @intFlag1 = 'foo'
SET @intFlag=(select a.fooID from foo a
where a.fooName=@intFlag1)
INSERT INTO @TempTable SELECT @intFlag
WHILE (@intFlag >=0)
BEGIN
 set @intFlag=(select a.basefooId from foo a
 join foo b on a.basefooId=b.fooID
 where a.fooID=@intFlag)
 INSERT INTO @TempTable SELECT @intFlag
 END
 SELECt * from @TempTable

The above query works fine in sql server.
Database
connection = pyodbc.connect(super().database_config())
        Global.connection = connection.cursor()
result = list(Global.connection.execute(query))

Error:
while Global.cursor.nextset():  # NB: This always skips the first resultset
AttributeError: type object 'Global' has no attribute 'cursor'

Note: I am aware that, many of such questions are already asked and answered in the same forum but apparently my fix based on those guidance has not yielded expected results. May be I am wrong in implementing. Can someone throw a light as to how to fix it?

A:

Issue resolved after keeping SET NOCOUNT ON on top of the query in pyodbc.


Q:

Why do I have to use utf8_decode before I insert an already UTF8 string in mysql?

I am running into a problem, that I managed to fix by simply trying different options, but I don't understand why it works, it does not make sense to me...
Here it is, I receive UTF8 encoded JSON from Facebook, my table is in utf8_general_ci and my DB connection is UTF8 encoded too.
If I don't do anything special, the string is inserted as

FabiÃ©n

but if I utf8_decode it before inserting it is inserted as

Fabién

When I call mb_detect_encoding on my string, it returns UTF8.
Can anyone explain why I have to use utf8_decode for it to work? Or better, what to do to fix my code so I don't have to call utf8_decode?
Thanks in advance.

A:

Found the problem, you have to execute the command "SET NAMES utf8" after establishing the connection to the DB with PDO. I am using an older version of PHP (5.3.6), and charset=utf8 is ignored in the connection string...
See this question: PHP PDO: charset, set names?


Q:

Why is it considered a good practice to isolate data management in a microservice?

I have seen proponents of isolating data management and storage into microservices in a way that each microservice has its own data store (at least in a logical sense). Hence, joins and aggregations are made in the application layer.
Why is this better than using, for example, a relational database where different microservices can connect to? By doing it this way, we leverage the capabilities of the database to do joins and the likes and we can also use views to separate concerns and roles, getting the best of both worlds. If the database system is deployed with high-availability in mind, it is not a probable point of failure.
What am I missing?

A:

A big advantage that a Microservices architecture has is that each service can be safely developed, tested and deployed independently. Having services share a database undermines this as it allows subtle changes in one service to introduce failures in other services, e.g.

One service might start writing data in an unexpected format into columns read by another service
Services might start locking records in a slightly different way, causing performance issues or even deadlocks in other services

Because of the difficulty in making sure that a given change doesn't impact another user of a database verifying changes becomes more complicated and deployments of "independent" services often become interconnected (e.g. changes need to be deployed in specific orders otherwise testing is invalidated). In addition schema changes also become substantially harder as it is difficult to identify what services could be impacted by a given change.
Having services communicate using REST APIs or message queues helps keep services independent as automated test suites can more easily verify that changes are backwards compatible, and services can safely make otherwise breaking changes without impacting other services, e.g. by introducing new API / endpoint versions.


Q:

How to do databinding with two ObservableCollection?

I have 2 models, 2 views, and 1 viewmodel.
Basically I want to load the data from a GTSLocation object into a ListItem, but also add two more values from a GTSWorkingSite object that has the same Working Site Guid as the GTSLocation object have.
The item fooA from ObservableCollection＜GTSLocation＞:
WorkingSiteId : "A-A-A-A"
Longitude: 60
Latitude: 120

The item fooB from ObservableCollection＜GTSLocation＞:
WorkingSiteId : null
Longitude: 70
Latitude: 130

The item barA from ObservableCollection＜GTSWorkingSite＞:
Id: "A-A-A-A"
Name: "WacDonald's"
Description: "A Fastfood resturaunt."

The listitem for fooA:
WorkingSiteName: "WacDonald's"
WorkingSiteDescription: "A Fastfood resturaunt."
Longitude: 60
Latitude: 120

The listitem for fooB:
WorkingSiteName: "Unknown Place"
WorkingSiteDescription: "No info to provide"
Longitude: 70
Latitude: 130

I can only come up with the solution that is to create another model which contain all the properties I want. Actually is it the only way to go? There must be a more elegant way I guess?
To add up, the reason I have two ObservableCollection is because GTSWorkingSite is also used on the other view (WorkingSiteView.xaml) seperately.
◎Model
    public class GTSLocation
    {
        public string WorkingSiteId {get;set;} //GUID
        public double Longitude {get;set;}
        public double Latitude {get;set;}
        public DateTime Timestamp {get;set;}
    }
    public class GTSWorkingSite
    {
        public string Id {get;set;} //GUID
        public string Name {get;set;}
        public string Description {get;set;}
    }

◎ViewModel
    public class GeneralViewModel : INotifyPropertyChanged
    {
        //Assume these two collection filled with data
        public ObservableCollection<GTSLocation> UserLocations { get; set; }
        public ObservableCollection<GTSWorkingSite> WorkingSites { get; set; }
        //Ignored the rest of the code...
    }

◎View: UserItemsPage.xaml
   <ListView ItemsSource="{Binding UserLocations}">
   <ListView.ItemTemplate>
       <DataTemplate>
           <ViewCell>
               <Grid>
                   <Grid.RowDefinitions>
                       <RowDefinition Height="1*" />
                       <RowDefinition Height="1*" />
                       <RowDefinition Height="1*" />
                   </Grid.RowDefinitions>
                   <Grid.ColumnDefinitions>
                       <ColumnDefinition Width="100" />
                       <ColumnDefinition Width="1*" />
                       <ColumnDefinition Width="2*" />
                   </Grid.ColumnDefinitions>
                   <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" />
                   <Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding WorkingSiteName}" />
                   <Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding WorkingSiteDescription}" />
                   <Label Grid.Row="2" Grid.Column="1" Text="{Binding Longitude}" />
                   <Label Grid.Row="2" Grid.Column="2" Text="{Timestamp}" HorizontalTextAlignment="End" />
               </Grid>
           </ViewCell>
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

If this is a bad design from the very begining, I am willing to refactor my code, if anyone could give me suggestion.

A:

It's pretty bad because you rely on string (or whatever GUID) mapping between the two classes. If you don't want to create a third model but can refactor current model and if GTSLocation has a 1-1 mapping with GTSWorkingSite anyway then i think you could just do:
1) Refactor the model so that GTSLocation knows about the fact it has a GTSWotkingSite:
public class GTSLocation
{
    public string WorkingSiteId {get;set;} //GUID
    public double Longitude {get;set;}
    public double Latitude {get;set;}
    public DateTime Timestamp {get;set;}
    //New property -> We will use it in the binding!
    public GTSWorkingSite WorkingSite {get;set;}
}
public class GTSWorkingSite
{
    public string Id {get;set;} //GUID
    public string Name {get;set;}
    public string Description {get;set;}
}

2) Then in your XAML it becomes easy to retrieve the info when populated correctly (note the binding ["."] slight change using the new added WorkingSite property):
<ListView ItemsSource="{Binding UserLocations}">
   <ListView.ItemTemplate>
       <DataTemplate>
           <ViewCell>
               <Grid>
                   <Grid.RowDefinitions>
                       <RowDefinition Height="1*" />
                       <RowDefinition Height="1*" />
                       <RowDefinition Height="1*" />
                   </Grid.RowDefinitions>
                   <Grid.ColumnDefinitions>
                       <ColumnDefinition Width="100" />
                       <ColumnDefinition Width="1*" />
                       <ColumnDefinition Width="2*" />
                   </Grid.ColumnDefinitions>
                   <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" />
                   <Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding WorkingSite.Name}" />
                   <Label Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding WorkingSite.Description}" />
                   <Label Grid.Row="2" Grid.Column="1" Text="{Binding Longitude}" />
                   <Label Grid.Row="2" Grid.Column="2" Text="{Timestamp}" HorizontalTextAlignment="End" />
               </Grid>
           </ViewCell>
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

Hope it helps and happy coding!


Q:

Maximum volume of tetrahedron with given face areas

Everyone knows Heron formula for the area of a triangle as a function of its sides. Moving to three dimensions, what is the maximum volume of a tetrahedron with given four face areas $a$, $b$, $c$, and $d$?
Obviously, this is an optimization problem. For example, with $a=b=c=d=1$ one can construct a tetrahedron with any volume between zero and $\frac{2\sqrt2}{3\sqrt{3\sqrt3}}$. The latter is the volume of the regular tetrahedron with side 1, and it is this tetrahedron that gives the maximum volume (from symmetry considerations). The zero volume is presented by any degenerate tetrahedron (such as the "tetrahedrons" with vertices given by
$$
A=(0,0,0),\quad B=(2,0,0),\quad C=(1+e,1,0),\quad D=(1-e,-1,0),
$$
for any real $e$, all have four faces 1 and volume zero).
A degenerate tetrahedron can not be constructed for given face areas when $S_1\not=S_2+S_3+S_4$ and $S_1+S_2\not=S_3+S_4$ for any assignment of $a,b,c,d$ to $S_1,S_2,S_3,S_4$. Then a complementary problem is what is the minimum volume of a tetrahedron with given four faces $a$, $b$, $c$, and $d$?
The "maximum" problem somewhat resembles "What is the maximum area of the quadrilateral given by its sides $a$, $b$, $c$, and $d$?", for which Brahmagupta's formula gives the solution. See also this question, and you can find numerous other pieces of study of this planar problem in the Internet. In this  problem one can intuitively guess that the four vertices of the maximum area quadrilateral should live on a circle, and then proceed with the derivation and proof of the formula. For the maximum volume of tetrahedron, what intuitive guess can be made?
I suspect the maximum volume is obtained together with the maximum sum of the six digedral angles at the six edges of the tetrahedron. In the above example, the sum is $2\pi\approx6.28$ for the degenerate tetrahedra and $6\cdot2\arcsin\frac1{\sqrt3}\approx7.39$ for the regular tetrahedron. To support this intuition, the volume is given by any of the six identities like this one:
$$
3V\cdot AB=2c d\sin AB_\angle,
$$
where $c$ is the area of the face opposing vertex $C$, and $AB_\angle$ is the dihedral angle at edge $AB$, so all the dihedral angles should be maximized.
From this guess on, the radius of the circumscribed sphere should be minimized, perhaps. I can not prove this guess, but it concords with the expression of the area of a triangle given by its sides: $S=4abc/R$ (if finding the area of the triangle by its sides were an optimization problem, then you would minimize the circumcircle).
The problem was originally given to me by Ernst D. Krupnikov, who claims its closed form solution is cumbersome and difficult to derive without a help of a computer algebra system. Here is a particular case of the problem you may find amusing to solve: what is the maximum volume of the tetrahedron with face areas 120, 150, 160, 250?

A:

Given four face-areas, the tetrahedron of maximum volume is the one in which opposite edges are perpendicular.

(I call these "perfect" tetrahedra, although they are called "orthocentric" in the literature.)
You can find a proof of this in the 1975 Pacific Journal of Mathematics article "The Orthocentric Simplex as an Extreme Simplex (PDF)" by Leon Gerber. (As the title suggests, the results apply to arbitrary-dimensional figures, not merely three-dimensional tetrahedra.) The argument takes a few pages, but involves fairly elementary vector techniques, with a touch of calculus.
In my own note, "Heron-like Hedronometric Results for Tetrahedral Volume (PDF)", I show that the volume of a perfect tetrahedron with face areas $W$, $X$, $Y$, $Z$ is given by what I call the "Heron Quartic":
$$\begin{align}
0 = 27 U^4 &+ U^3 \left( s_\star s_1 + 8(4 s_1 s_2 - 27 s_3) \right) \\
&- U^2 \left( s_\star^2 s_2 + 12 s_\star(3 s_1 s_3-28 s_4) - 48(9 s_3^2-16 s_2 s_4) \right) \\
&+ U\phantom{^3} \left(s_\star^3 s_3+40 s_\star s_1 s_4-576 s_\star s_3 s_4 + 1536 s_1 s_4^2 \right) \\
&- \phantom{U^3} s_4 ( s_\star^2 - 64 s_4)^2
\end{align}$$
where $U = 81 V^4$, and the $s_i$ are symmetric polynomials in the squares of the face-areas ( $w=W^2$, etc):
$$s_1 := w+x+y+z \qquad s_2 := w x + w y + w z + x y + x z + y z$$
$$s_3 := w x y+w x z+w y z+ x y z \qquad s_4 := w x y z$$
$$s_\star := 4s_2 - s^2 = - w^2-x^2-y^2-z^2+2wx+2wy+2wz+2xy+2xz+2yz$$
In the case where $W^2 = X^2 + Y^2 + Z^2$, the polynomial factors as
$$0 = (U - 4 X^2 Y^2 Z^2) (\ldots\text{extraneous cubic}\ldots)$$
so that
$$9 V^2 = 2 XYZ$$
as mentioned in this answer. The maximizing figure is a "right-corner tetrahedron", with $\cos A = \cos B = \cos C = 0$. (Note: In general, a tetrahedron satisfying $W^2=X^2+Y^2+Z^2$ isn't necessarily a right-corner tetrahedron, but a perfect one must be.) Your "amusing" example falls into this category (with $W = 250$), so that
$$9 V^2 = 2\cdot 120\cdot 150 \cdot 160 \qquad\to\qquad V = 800$$

BTW: Although the Heron Quartic is guaranteed (by the Descartes Rule of Signs) to have a positive root $U$, it's actually possible for it to have as many as three of them. I haven't been able to prove that there's an unambiguous choice corresponding to the given tetrahedron's volume. Even so, it's possible to prove that perfect volume is at least "locally" maximal using a few hedronometric relations, giving an alternative to Gerber's vector-based approach. We simply optimize the hedronometric volume formula ...
$$\begin{align}
81 V^4 &= H^2 J^2 K^2 - 2 ( W X - Y Z )( W Y - Z X )( W Z - X Y ) \\
&-H^2 ( W X - Y Z)^2 - J^2 ( W Y - Z X)^2 - K^2 ( W Z - X Y )^2
\end{align}$$
(where $H$, $J$, $K$ are the tetrahedron's pseudofaces), subject to the sum-of-squares identity ...
$$W^2 + X^2 + Y^2 + Z^2 = H^2 + J^2 + K^2$$
... finding that stationary points (more-specifically, local maxima) must correspond to perfect tetrahedra.  See my "Heron-like Results" note for details.


Q:

Makefile DEFAULT_GOAL variable

This is an example of use of DEFAULT_GOAL Variable:
ifeq ($(.DEFAULT_GOAL),)
  $(warning no default goal is set)
endif

.PHONY: foo
foo: ; @echo $@

$(warning default goal is $(.DEFAULT_GOAL))

# Reset the default goal.
.DEFAULT_GOAL :=

.PHONY: bar
bar: ; @echo $@

$(warning default goal is $(.DEFAULT_GOAL))

# Set our own.
.DEFAULT_GOAL := foo

The output is:

no default goal is set
default goal is foo
default goal is bar
foo

I stuck up understanding that what is the flow of the echo and $(warning ) function i.e. when $(warning ) function is called the echo $@ output is suppressed and last output of echo $@ is displayed. Because there is 2 echo statement and 3 $(warning ) function call but only one target id printed by echo the last one foo . Why others are not printed and why the last value is printed as foo why not bar?

A:

The warnings and assignments happen as make reads the Makefile.  Only then does it begin to decide which of the rules to execute.  The other echo statements are never executed because it only makes the default goal at that point, which is foo.