text:
Q: How can I implement Frame Pacing into an android games app I'm an amateur app developer and have been tuning one of my projects to improve performance by reducing overdraw, removing unnecessary code and ensuring screen updates only occur when necessary.  My app works well and there are no bugs that I'm aware of but when I profile the GPU rendering I get good results with the exception of occasional unexplained spikes in the GPU profile display. I've been investigating Frame Pacing without any success. My main testing is done using a Samsung GS4 device and the problem I'm struggling with is the consistency of the GPU rendering.  On most occasions the animation of the token moving to the new position is smooth and I can't see any problems but intermittently the animation seems to be jumpy.
The GooglePlay pre-launch report on some devices is indicating VSync errors / Slow Ui Thread and Slow Draw commands across a small set of devices, most devices in the pre-launch report do not report the same performance errors.
I've searched you tube and googled as much as I can for any help to implement Frame Pacing (Swappy) and I've downloaded the Android Developer "games/sdk". I'm finding it difficult to follow the developer Frame Pacing guidelines and I've been unable to find a Frame Pacing example that I can understand.
https://developer.android.com/games/sdk/frame-pacing/opengl/update-build-settings
I'm using Android Studio at version 4.0.1 with Gradle 6.1.1, my code is Java and includes the following dependencies which are not being referenced by my app and I suspect these dependencies  hold the answers to the performance problems in my app.
// To use the Android Frame Pacing library

implementation "androidx.gaming:gaming-frame-pacing:1.5.0-alpha01"

// To use the Android Performance Tuner

implementation "androidx.gaming:gaming-performance-tuner:1.0.0-alpha01"

I'm hoping that I don't need to learn C/C++ or convert my code to Unity as I'm just getting comfortable with Java.
Any help or advice / examples to help implement Swappy for Open GL into my app would be appreciated.

A: Will here, from the Android Games Team at Google.
The Android Game SDK is a solution for C/C++ and Unity games only, so it won't help you with frame pacing in a Java app, I'm afraid.
We suggest looking at the Firebase Performance Monitoring tool:
https://firebase.google.com/docs/perf-mon/screen-traces
This will hopefully give you insights as to where and why your frame jank is occurring.
Best regards.


text:
Q: json_encode must cast object as array Currently I need to build an API to output as json format, and what I currently do (as example) is the following:
$array=array();
$array['firstname']="John";
$array['lastname']="Doe";
$array['cities']=array();
$array['cities']['name']=array("London","Brighton");
$array['cities']['population']=array("12000000","500000");
echo json_encode($array);

The output is:

{"firstname":"John","lastname":"Doe","cities":{"name":["London","Brighton"],"population":["12000000","500000"]}}

However I was told that this is incorrect, and the output needs to be

{"firstname":"John","lastname":"Doe","cities":[{"name":["London","Brighton"],"population":["12000000","500000"]}]}

(note the square brackets in the output). The reason was claimed that cities itself needs to be specified as an array since $array['cities'] is an array.
My questions are:
1) Is it custom to add square brackets in these cases to indicate it is an array?
2) How can I change my php code in order to have these square-brackets in the output?
help appreciated
Thanks
Patrick

A: It's here
$array=array();
$array['firstname']="John";
$array['lastname']="Doe";
$array['cities']=array();
$array['cities'][]=array(
                        'name'=>array("London","Brighton"),
                        'population'=>array("12000000","500000")
                   );
echo json_encode($array);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failed to validate OAuth signature and token twitter integration ios GTM-OAuth I am using following code to handle twitter integration in my Application.
- (IBAction)signInWithTwitter:(id)sender {
NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"];
NSURL *accessURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"];
NSURL *authorizeURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/authorize"];
NSString *scope = @"http://api.twitter.com/";

GTMOAuthAuthentication *auth = [self authForTwitter];
[auth setCallback:@"http://www.noop.com/OAuthCallback"];

GTMOAuthViewControllerTouch *viewController;
viewController = [[GTMOAuthViewControllerTouch alloc] initWithScope:scope
                                                             language:nil
                                                      requestTokenURL:requestURL
                                                    authorizeTokenURL:authorizeURL
                                                       accessTokenURL:accessURL
                                                       authentication:auth
                                                       appServiceName:@"CK12: Twitter"
                                                             delegate:self
                                                     finishedSelector:@selector(viewController:finishedWithAuth:error:)];
}

- (GTMOAuthAuthentication *)authForTwitter {

GTMOAuthAuthentication *auth = [[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
                                                     consumerKey:TWITTER_CONSUMER_KEY
                                                      privateKey:TWITTER_CONSUMER_SECRET];

[auth setServiceProvider:@"Twitter"];

return auth;
}

My problem is, if I am changing device time i.e making it 1 hour late, then I am getting following error:
Error Domain=com.google.HTTPStatus Code=401 and error message is : failed to validate oauth signature and token .

So can anybody please suggest how to solve this. if system time is wrong then also I want to make it work .

A: Finally I got solution for this . . . .
One of the reason we get this error "Failed to validate OAuth signature and token"
when system time is wrong . Because OAuth request carry system timestamp parameters with it , so when device time is not within the 5 minutes of twitter server time  .we get "Failed to validate OAuth signature and token" .
There are two ways to make it work , if the device time is even wrong .
1.make HTTP HEAD request to an endpoint on api.twitter.com -- you'll get a Date HTTP header in the response that indicates the current time understood by Twitter. You would then convert this to epoch time and adjust your oauth_timestamp values by a determined offset.
2.There's a small iOS library named ios-ntp link: http://code.google.com/p/ios-ntp . use this to get the current Accurate time .
After that i just set the timestamp of OAuth object in the following method
- (GTMOAuthAuthentication *)authForTwitter
{
GTMOAuthAuthentication *auth = [[GTMOAuthAuthentication alloc]
            initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
            consumerKey:TWITTER_CONSUMER_KEY
            privateKey:TWITTER_CONSUMER_SECRET];
[auth setServiceProvider:@"Twitter"];
NSDate * currentdate = //GET ACCURATE DATE HERE ;
[auth setTimestamp:[NSString stringWithFormat:@"%f",[currentdate timeIntervalSince1970]]];
return auth;
}

that's it . . .Happy Coding :)


text:
Q: Laravel - I deleted a migrate class manually and created it again. Now Migrate won't work I created a migrate class for laravel using:
php artisan make:migration mymigrationclass

Then I deleted it manually. Then I created it again using the same name.
After that I tried to refresh my database by using:
php artisan migrate:refresh

But now I get the error:
 Cannot declare class mymigrationclass, because the name is already in use

Probably because I deleted it manually before.
What should I do now?

A: Also, make sure you remove it from your migrations table in db.

A: Use command
composer dump-autoload


text:
Q: What is the performance impact of writing C# code in views which can also be written in controller/ business? I have done so to avoid extra View Model mappings in Business class.
Example:
public class PatientInfoBusiness
{
    public List<PatientInfo> GetPatientInfo()
    {
        IPatientInfoService proxy = new VRFactory().GetPatientInfoServiceProxy();
        var piData= proxy.GetPatientInfoSectionData();

        //var patientInfoVM= new List<patientInfoVM>();
        //piData.ForEach( a => patientInfoVM.Add(
        //                                                          new patientInfoVM
        //                                                          {
        //                                                              AcknowledgedUserName = a.AcknowledgedUserName,
        //                                                              Description = a.Description,
        //                                                              PriorityCode = a.PriorityCode,
        //                                                              Status = a.Status
        //                                                          }
        //                                        )
        //                );

        return piData;
    }
}

Shifted the commented code in the above Business to View, looping through and displaying in HTML. This way no need of patientInfoVM View Model. But I am skipping the business layer altogether and binding the entity from service layer directly in view!

A: I don't think the Maintainability vs Performance shouldn't be the question here. It's all about time. The less time you need to develop/read/modify your solution, the better. Therefore you need to split your solution in layers. If something changes in the data-layer, you shouldn't have to modify your gui-layer.
Pre-optimalizations should not be done. But there are a few tricks to write your code more efficient.
You might return an IEnumerable<patientInfoVM>. This will create the patientInfoVM lazy. This will only create the item when iterated.
public class PatientInfoBusiness
{
    public IEnumerable<PatientInfo> GetPatientInfo()
    {
        IPatientInfoService proxy = new VRFactory().GetPatientInfoServiceProxy();
        var piData= proxy.GetPatientInfoSectionData();

        return piData.Select(a => new patientInfoVM
        {
          AcknowledgedUserName = a.AcknowledgedUserName,
          Description = a.Description,
          PriorityCode = a.PriorityCode,
          Status = a.Status
        });
    }
}

If you iterate the result only ones, you can just use it like this:
foreach(var patientInfo in GetPatientInfo())
{
    // do something.
}

But if you need to use the results more than ones, you should persist the items:
var patientInfoList = GetPatientInfo().ToArray();

foreach(var patientInfo in patientInfoList)
{
    // do something.
}

foreach(var patientInfo in patientInfoList)
{
    // do something.
}

A: Without any hard metrics I can only offer my opinion, but in lieu of other, more analytics-driven responses, here it is.
I would say yes, putting your business logic in a separate layer will cause slightly more overhead and therefore worse performance. Then again I would also say that I could squeeze more performance if I wrote in raw machine code, but that would be crazy. So here are my reasons why the slightly worse performance is worth it:

*

*maintenance of data-access code mixed in throughout your views will become a nightmare - you will end up re-writing the same access boilerplate code many times over (as you can't reuse the query logic in other views)

*views are typically JIT-compiled (unless you switch that off), and often the intellisense doesn't fully catch up with what you are doing, so you can leak compile-time bugs through to runtime

*debugging through views sucks - it just does

*mixing of your presentation code and your business logic is generally a "bad idea" - mainly because the two concerns become far too intermingled

*you are using a List<> in your example, which is a lower-performance convenience structure: so it's OK for that, why not for MVC?

*how do you error-handle in your view? Are you catching exceptions and outputting different markup? How does that translate into display templates, partial views and other such things?

Anyway, that's all my opinion: just ask yourself why you are using this framework, and what that last drop of performance might cost you in other ways. But the decision is up to you.


text:
Q: How to imply swin transformer to arbitrary image size? ( tensorflow, keras ) I am studying about image swin transformer(https://openaccess.thecvf.com/content/ICCV2021/papers/Liu_Swin_Transformer_Hierarchical_Vision_Transformer_Using_Shifted_Windows_ICCV_2021_paper.pdf) ,
and mainly try to follow swinIR(https://arxiv.org/pdf/2108.10257.pdf) that make super-resolution-ed image using swin transformer.
However, The examples and code I found only describes in the case that the image has fixed size(224 x 224 x 3 e.g.) And I cannot understand how the transformer block is adjusted for arbitrary sized image inputs. I am mainly referring the author's github https://github.com/JingyunLiang/SwinIR/blob/main/models/network_swinir.py
Please somebody tell me how and thank you very much .


text:
Q: How to go from one view to another in MVC3 I am still learning and not sure how to do this, I have in  my controller:
[HttpGet]
public ActionResult Detail(int userId)
{
  var user = ZincService.GetUserForId(userId);
  UserDetailViewModel userDetail = new UserDetailViewModel();
  userDetail.UserId = userId;
  userDetail.Email = user.Email;
  userDetail.Firstname = user.Firstname;
  userDetail.Surname = user.Surname;
  return View(userDetail);
}

[HttpGet]
public ActionResult ChangeEmailAddress()
{
  return View();
}

In my Detail view:

     <%: Html.LabelFor(model => model.Email)%>

             <%: Model.Email  %>
             <%: Model.UserId %>

             <%: Html.ActionLink("Change Email Address",  "ChangeEmailAddress", "User", new { area = "Admin", @id = Model.UserId, @email = Model.Email, @name = Model.Firstname }, 0) %>

             <%: Html.ValidationMessageFor(model => model.Email)%>

I just want to go from here in the view to another view(ChangeEmailAddress) where the user can actually change his email from old to new?
Thanks

A: Why did you put 0 as last argument of the ActionLink? It should be null.
<%= Html.ActionLink(
    "Change Email Address",
    "ChangeEmailAddress",
    "User",
    new {
        area = "Admin",
        id = Model.UserId,
        email = Model.Email,
        name = Model.Firstname
    },
    null
) %>

Now your ChangeEmailAddress action could take the model as parameter:
[HttpGet]
public ActionResult ChangeEmailAddress(UserDetailViewModel user)
{
    return View(user);
}

Then you should define the corresponding ChangeEmailAddress.aspx view which will be rendered by this controller action and strongly typed to your view model.
But a better approach is to send only the user id in the request and then retrieve the actual user object using this id:
<%= Html.ActionLink(
    "Change Email Address",
    "ChangeEmailAddress",
    "User",
    new {
        area = "Admin",
        id = Model.UserId,
    },
    null
) %>

and then:
[HttpGet]
public ActionResult ChangeEmailAddress(int id)
{
    // retrieve the user object using the id
    ...
}


text:
Q: Stuck in programming with winBGIm with C I recently discovered winBGIm libraries, and I find it very useful to learn to code, so I started creating something to get some practice but I got stuck with my program.
The program should show a little ball and two rectangles approaching to the ball itself, and the player can move the ball up and down simply by pressing a button on the keyboard. Initially, I wrote everything in the main to make it fast, but since this is terrible I divided the program into functions.
First of all, even when everything was together, the getch function seemed to not work, because, while it should wipe the input buffer for the kbhit function, it made the ball not move at all, while the mere kbhit function worked, but obvioulsy the ball continued going up even when you stopped pressing a key. I used the same procedure in another text-only program and it worked very well, so I don't know where the problem is.
The second and most important problem is that, after splitting the program into functions, it became static, since the main loop which would make the graphic move stops at the end of the first iteration. It only restarts working when I delete the cleardevice function at the end of the loop and I disable the duble buffering in the initwindow function, but I can't understand the relationship between these things.
Finally, when I set a new background color, if it is not 0 (black), the window remains completely black.
I hope someone can help me.
Best regards, Giacomo.
#include <graphics.h>
#include <time.h>
#include <stdio.h>

int rettangoli(int b);
void bird(int x_default, int y_default);

void bird();

int main() {
    int a=640;
    int b=480;
    int x_default=150;
    int y_default=400;
    int verifica=0;
    srand(time(NULL));
    initwindow(a, b, "BGI", 0, 0, true, true);
    setbkcolor(0);
    while(1) {
        bird(x_default, y_default);
        verifica=rettangoli(b);
        if(verifica==1) {
            outtextxy(0, 0, "HAI PERSO");
            outtextxy(0,20, "PREMERE UN TASTO PER CONTINUARE");
            break;
        }
        delay(50);
        while(kbhit()) {
            getch();
        }
        swapbuffers();
        cleardevice();
    }
    delay(350);
    getch();
    closegraph();
    return 0;
}

void bird(int x_default, int y_default) {
    static int x_pos=x_default;
    static int y_pos=y_default;
    if(kbhit()) {
        if(y_pos-16>0)
            y_pos=y_pos-5;
        circle(x_pos, y_pos, 16);
        setfillstyle(SOLID_FILL, YELLOW);
        floodfill(x_pos, y_pos, 15);
    }
    else {
        while(y_pos<400)
            y_pos=y_pos+15;
        circle(x_pos, y_pos, 16);
        setfillstyle(SOLID_FILL, YELLOW);
        floodfill(x_pos, y_pos, 15);
    }
    return;
}

int rettangoli(int b) {
    static int x_rett=615;
    int verifica=0;
    int contatore;
    int altezza;
    if(x_rett==615)
        altezza=rand()%(b-60)+1;
    rectangle(x_rett, 0, x_rett+25, altezza);
    rectangle(x_rett, altezza+60, x_rett+25, 480);
    setfillstyle(SOLID_FILL, GREEN);
    floodfill(x_rett+1, 1, 15);
    floodfill(x_rett+1, 479, 15);
    for(contatore=0;contatore<altezza && x_rett>100;contatore++) {
        if(getpixel(x_rett-1, contatore)!=getbkcolor())
            verifica=1;
    }
    for(contatore=altezza+60;contatore<b && x_rett>100;contatore++) {
        if(getpixel(x_rett-1, contatore)!=getbkcolor())
            verifica=1;
    }
    for(contatore=0;contatore<15;contatore++) {
        if(getpixel(contatore, altezza)!=getbkcolor())
            verifica=1;
    }
    for(contatore=0;contatore<15;contatore++) {
        if(getpixel(contatore, altezza+60)!=getbkcolor())
            verifica=1;
    }
    x_rett=x_rett-5;
    printf("%i", x_rett);
    return verifica;
}

A: Nevermind, I solved the problem on my own. There was an incompatibility issue between Windows 8 x64 and Codeblocks-EP, and I think there is a general incompatibility between winBGIm and x64 systems.
I created a virtual machine using Vmware Player and Windows XP x86 and now everything is fine.


text:
Q: Forcing autocomplete to lose focus after selecting from suggestions Very basic stuff, but I can't get my head around it.
After calling:
<script type="text/javascript">
    $(function() {
        $("#aspecinput").autocomplete({
            source: "search.php",
            minLength: 2
        });
    });
</script>

I'd like autocomplete to lose focus immediately, after the selection gets in the field because I have an onblur event on my search window that needs to run to adjust the selected data. Right now, I have to lose focus by clicking anywhere within the webpage obviously, to lose focus from the search textfield. How can I achieve the results?
Much appreciated!

A: instead of loosing focus you can do this, make use of change function
$('#aspecinput').change(function(){
    //fire search click
    //or fire function to do search
});

or try this make use of 'select' function
$('#aspecinput').autocomplete({
    'select':function(){
        $('#aspecinput').blur();
    }
});


text:
Q: Maclaurin series stuck at finding $L_n$ I need to develop Maclaurin serie of $f(x)=\frac{1}{(1-x)^2}$
I found all the derivative, and all the zero values for the derivatives. I come up with that :
$\frac{1}{(1-x)^2}=1+2x+\frac{6}{2!}x^2+\frac{24}{3!}x^3+\frac{120}{4!}x^4+...+\frac{?}{(n-1)!}x^{n-1} + ...$
Now I want to determinate $L_n=\frac{f^{n-1}(0)}{(n-1)!}x^{n-1}$
And this is where I'm stuck. How can I calculate $L_n$ ?

A: When calculating successive derivatives, sometimes it is more illuminating to not simplify out the entire calculation:  $$\begin{align*} f(x) &= (1-x)^{-2}, \\ f'(x) &= 2(1-x)^{-3}, \\ f''(x) &= 2(3)(1-x)^{-4}, \\ f'''(x) &= 2(3)(4)(1-x)^{-5}, \\ f^{(4)}(x) &= 2(3)(4)(5)(1-x)^{-6}, \\ &\vdots \\ f^{(n)}(x) &= \ldots. \end{align*}$$  Does the pattern seem more evident now?

A: Start from the geometric series $$\frac{1}{1-x}=\sum\limits_{n=0}^{\infty}{x^{n}} $$
add differentiate it:$$
\frac{d}{dx}{\left(\frac{1}{1-x} \right)}=\frac{1}{(1-x)^2}=\sum\limits_{n=1}^{\infty}{nx^{n-1}}.$$

A: $$\frac{ 1 }{ 1-x }=1+x+x^2+x^3+x^4+x^5+...\\\frac{ 1 }{ 1-x }\frac{ 1 }{ 1-x }=\\(1+x+x^2+x^3+x^4+x^5+...)(1+x+x^2+x^3+x^4+x^5+...)\\\\=1+(x+x)+(x^2+x^2+xx)+(x^3+x^3+x^2x+xx^2)+...=\\\\1+2x+3x^2+4x^3+5x^4+6x^5+... $$


text:
Q: Correctly reading HttpRequest body asynchronously in NetCore web app I am trying to get POST request body as string in C#. I wrote this:
    protected async Task<string> readBodyAsync(HttpRequest req)
    {
        // turns out this is always false...
        if(req.Body.CanSeek)
            req.Body.Seek(0, SeekOrigin.Begin);
        // string buffer
        string str = "";
        // I wouldn't expect to have to do this in 2017
        byte[] buffer = new byte[255];
        int offset = 0;
        int lastLen = 0;
        // On second iteration, CanRead is true but ReadAsync throws System.ArgumentException
        while ( req.Body.CanRead && (lastLen = await req.Body.ReadAsync(buffer, offset, buffer.Length))!=0)
        {
            offset += lastLen;
            // This also adds all the \0 characters from the byte buffer, instead of treating like
            // normal C string
            str += System.Text.Encoding.UTF8.GetString(buffer);
        }
        // This never executes due to the System.ArgumentException
        return str;
    }

The issues:

*

*On second iteration, req.Body.CanRead is true, but calling read causes System.ArgumentException

*All is read on first iteration already. Not only that, System.Text.Encoding.UTF8.GetString adds all remaining zeroes from the buffer to the string.

I handle the request like this:
    app.Run(async (context) =>
    {
        if(context.Request.Method.ToLower() == "post" && context.Request.Path.ToString().EndsWith("/ajax"))
        {
            string requestText = await readBodyAsync(context.Request);
            /// Parsing of the JSON in requestText should be here
               // but I can't get that text
            await context.Response.WriteAsync("{data: \"AJAX TEST\"}");
        }
        else
        {
            await context.Response.WriteAsync("Hello World! And go away. Invalid request.");
        }
    });

A: Apparently there's a more elegant way that also works:
    protected async Task<string> readBodyAsync(HttpRequest req)
    {
        StreamReader r = new StreamReader(req.Body);
        return await r.ReadToEndAsync();
    }

A:     private async Task<string> StreamToStringAsync(HttpRequest request)
    {
        using (var sr = new StreamReader(request.Body))
        {
            return await sr.ReadToEndAsync();
        }
    }

A: var body = await new StreamReader(req.Body).ReadToEndAsync();


text:
Q: Cant upload file Failed to load resource: the server responded with a status of 503 i have problem here that when i upload files in my upload script give me this error
Failed to load resource: the server responded with a status of 503 ()
i don't know why give me this error , sometimes i can upload successfully
iam using php , jquery , ajax
any help in this Error ?
Image For Problem

A: You should check the error.log file on your server which would give you (and us) more information - from just that screenshot we can only guess what's happening


text:
Q: How do I print a string with a printer? I'm writing an application that need to print some information that would came from a DataGridView, I already have the string I'd like to print, I just don't know how. I found some stuff on the web that said I'd need to use a PrintDocument object and a PrintDialog.
Lets suppose I have 3 strings and I want to print to each one in one line (line 1, 2 and 3),but the first must be in bold and using the Arial font.
The output (on the paper) would be:
string 1 (in bold and using the Arial font)

string 2

string 3

EDIT: (asked by abelenky)
The Code:
    private void PrintCoupon()
    {
        string text = "Coupon\n";

        foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows)
        {
            foreach (DataGridViewCell dgvCell in dgvRow.Cells)
            {
                text += dgvCell.Value.ToString() + "  ";
            }

            text += "\n";
        }

        MessageBox.Show(text);
        // I should print the coupon here
    }

So how do I do that using C#?
Thanks.

A: for printing strings on a paper you should draw them first on a PrintDocument using GDI+ in c#
in a Winform add PrintDocument tool to your project , and double click on it to access the PrintPage event handler of it ,
assuming you already have s1,s2 and s3 as String Variables  ,
in the PrintPage event handler we use :
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    Font f1 = new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel);
    Font f2 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
    Font f3 = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
    e.Graphics.DrawString(s1, f1, Brushes.Black, new Point(10, 10));
    e.Graphics.DrawString(s2, f2, Brushes.Black, new Point(10, 40));
    e.Graphics.DrawString(s3, f3, Brushes.Black, new Point(10, 60));
}

and whenever you wanted to print the document :
printDocument1.Print();

you may also consider using a PrintPreviewDialog to see what's going on before printing the document

A: Try this ..
using System.Drawing;

private void printButton_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
            (this.pd_PrintPage);
pd.Print();
}

// The PrintPage event is raised for each page to be printed.
void pd_PrintPage(Object* /*sender*/, PrintPageEventArgs* ev)
{
Font myFont = new Font( "m_svoboda", 14, FontStyle.Underline, GraphicsUnit.Point );

float lineHeight = myFont.GetHeight( e.Graphics ) + 4;

float yLineTop = e.MarginBounds.Top;

string text = "Coupon\n";

foreach (DataGridViewRow dgvRow in dataGridViewCarrinho.Rows)
    {
        foreach (DataGridViewCell dgvCell in dgvRow.Cells)
        {
            text += dgvCell.Value.ToString() + "  ";
        }

        text += "\n";
    }

    //MessageBox.Show(text);
    // I should print the coupon here
    e.Graphics.DrawString( text, myFont, Brushes.Black,
    new PointF( e.MarginBounds.Left, yLineTop ) );

    yLineTop += lineHeight;

}


text:
Q: Boost spirit can handle Postscript/PDF like languages? I noticed that Boost spirit offers some limits, in a question here on SO there is an user asking for help about boost spirit and the other user who gave the answer specified that boost spirit works well with statements and not with "generic text" ( I'm sorry if I don't recall it correctly ).
Now I would like to think about Postscript and PDF in terms of tokens and simplify my approach to this formats this way, the problem is that the PDF is kind of a mix between a markup language and a programming language with jumps and tables in it, and I can't think about something similar when considering the most popular file formats like XML, C++ code and others languages and formats.
There is also another fact: I can't really find people that had some kind of experience with boost::spirit wiriting a pdf parser or writer, so I'm asking, boost::spirit it's capable of parsing a PDF file and output the elements as tokens ?

A: Although this has nothing to do with Boost, let me assure you that the parsing of PDF (and PostScript) are about as trivial as you could want.  Let's say that you have a scanner object that returns a series of tokens.  The token types you will get from the scanner are:

*

*String

*Dict begin (<<)

*Dict End (>>)

*Name (/whatever)

*Number

*Hex array

*Left Angle (<)

*Right Angle (>)

*Array begin ([)

*Array end (])

*Procedure begin ({)

*Procedure end (})

*Comment (%foo)

*Word

My scanner is a finite-state automata with states for Start, Comment, String, HexArray, Token, DictEnd, and Done.
The way you parse PDF is not by parsing it, but by executing it.  Given these tokens, my "parser" looks like this (in C#):
while (true) {
    MLPdfToken = scanner.GetToken();
    if (token == null)
        return MachineExit.EndOfFile;
    PdfObject obj = PdfObject.FromToken(token);
    PdfProcedure proc = obj as PdfProcedure;

    if (proc != null)
    {
        if (IsExecuting())
        {
            if (token.Type == PdfTokenType.RBrace)
                proc.Execute(this);
            else
                Push(obj);
        }
        else {
            proc.Execute(this);
        }
        if (proc.IsTerminal)
            return Machine.ParseComplete;
    }
    else {
        Push(obj);
    }
}

I'll also add that if you give every PdfObject an Execute() method such that the base class implementation is machine.Push(this) and IsTerminal that returns false, the REPL gets easier:
while (true) {
    MLPdfToken = scanner.GetToken();
    if (token == null)
        return MachineExit.EndOfFile;
    PdfObject obj = PdfObject.FromToken(token);

    if (IsExecuting())
    {
        if (token.Type == PdfTokenType.RBrace)
           obj.Execute(this);
        else
           Push(obj);
    }
    else {
        obj.Execute(this);
        if (obj.IsTerminal)
            return Machine.ParseComplete;
    }
}

There's more support in Machine - Machine has a Stack of PdfObject and a few methods for accessing it (Push, Pop, Mark, CountToMark, Index, Dup, Swap), as well as ExecProcBegin and ExecProcEnd.
Beyond that, it's very light.  The only thing that is slightly odd is that PdfObject.FromToken takes a token and if it is a primitive type (number, string, name, hex, bool) returns a corresponding PdfObject.  Otherwise, it takes the given token and looks in a "proc set" dictionary of procedure names associated with PdfProcedure objects.  So when you encounter the token << that gets looked up in a the proc set and comes up with this code:
void DictBegin(PdfMachine machine)
{
    machine.Push(new PdfMark(PdfMarkType.Dictionary));
}

So << really means "mark the stack as the start of a dictionary. >> gets more interesting:
void DictEnd(PdfMachine machine)
{
    PdfDict dict = new PdfDict();
    // PopThroughMark pops the entire stack up to the first matching mark,
    // throws an exception if it fails.
    PdfObject[] arr = machine.PopThroughMark(PdfMarkType.Dictionary);
    if ((arr.Length & 1) != 0)
        throw new PdfException("dictionaries need an even number of objects.");
    for (int i=0; i < arr.Length; i += 2)
    {
        PdfObject key = arr[i], val = arr[i + 1];
        if (key.Type != PdfObjectType.Name)
            throw new PdfException("dictionaries need a /name for the key.");
        dict.put((PdfName)key, val);
    }
    machine.Push(dict);
}

So >> Pops up to the nearest dictionary mark into an array then puts each pair into the dictionary.  Now, I could have done this without allocating the array.  I could just pop pairs, putting them into the dictionary until I either hit the mark, fail to get a name or underflow the stack.
The important takeaway is that there really isn't any syntax in PDF, nor is there any in PostScript.  At least not so much as you'd notice.  The only real Syntax (and the read-eval-(push) loop shows it) is '}'.
So when you this is a PDF 14 0 obj << /Type /Annot /SubType /Square >> endobj what your really seeing is a series of procedures:

*

*Push 14

*Push 0

*Execute obj (Pop two numbers and push a "definition" object).

*Execute dictionary begin

*Push /Type

*Push /Annot

*Push /SubType

*Push /Square

*Execute dictionary end

*Execute endobj (pop the top object and then get (not pop) the next one.  If the second is a definition, set its "value" to the first object, else throw).

Since "endobj" is terminal, parsing ends and the top of the stack is the result.
So when you are asked to look up object 14 in the PDF, the cross-reference table tells you where to seek to, you make a new Machine with the stream pointer at that location and run it.  If the top of the stack is a "definition" object, you've succeeded.
About now you should be nodding but not trusting me, since you're thinking about PDF streams, which look like this:
<< [/key value]* >> stream ...raw data... endstream endobj

Again, there is no syntax.  The proc stream looks at the top of the stack, which should be a PdfDict.  If it is, it consumes characters until the next newline (scanner does this), stores the current file position in the stream as data start, reads the stream length from the dict (which may cause another Machine to get newed up), and skips past the end of stream and pushes the new stream object on the stack.  endstream is a no-op.  The only difference between a PdfDict and a PdfStream is that a PdfStream has a start position and a bool saying that it's a stream, otherwise I dual-purpose the object.
PostScript is almost identical except that the execution environment is a little more complex.  For example, you need several stacks in your machine: a parameter stack, a dictionary stack, and an execution stack.  From there, you more or less just bind your tokenizer into the set of primitive procedures as well as the word exec, and then most of your interpreter is written in PS itself.
If you're talking about boost, you're looking at C++, which means that you can't be as fast and loose with memory as I am, so you'll want to either use smart pointers or figure out where you scope is and be careful to dispose objects instead of blithely throwing them away, but that's just the normal C++ stuff.
Currently, I make PDF tools for my company in .NET, but in a former life I worked on Acrobat versions 1-4, and most of what I described is exactly what Acrobat did under the hood (well, more or less - it was C, not C++, but it's the same approach).
With respect to the xref table (or xref stream), you read that first - the spec tells you that if you jump to EOF and scan back, you find the start of the xref table.  You parse that (which is a CS 101 assignment), parse the trailer, seek to the /Prev if any and repeat until no more /Prev entries.  That gives you a complete xref for looking up objects.
As for writing - there are a number of approaches that you can take.  The most obvious one is that when an object is meant to be referenced, you create a new reference object by assigning the newest available xref entry to it.  Whenever objects refer to other objects for writing, they ask if these objects are referenced.  If they are, they write the reference (ie, 14 0 R).  When it comes time to write a referenced object, you get the current stream pointer and store it in the xref, then write <objnum> <generation> obj <object contents> endobj.  For example, my code to write a dictionary looks like this:
public override ToStream(PdfStreamingContext context)
{
    if (context.HasReference(this)) // is object referenced in xref
    {
        PdfUtils.WriteObjectDefinitionBegin(this, context);
    }
    context.Writer.Indent();
    context.Writer.WriteLine("<<");
    WriteContents(context);
    context.Writer.Exdent();
    context.Writer.Writeline(">>");
    if (context.HasReference(this))
    {
        PdfUtils.WriteObjectDefinitionEnd(this, context);
    }
}

I've chopped out some chaff so you can see the wheat underneath.  The context is an object that holds a new xref table as well as an object for writing to streams that automagically handles appropriate newline discipline, indentation, line wrapping, and so on.
What you should see is that the basics here are straight forward, if not trivial.  And now's when you should be asking yourself the question, "if it's trivial, how come there isn't more (serious) competition for Acrobat in the market?  The answer is that even though it's trivial, it's still easy to write PDFs that aren't spec compliant and Acrobat handles most of those.  The real challenge is to be able to honor the spec and make sure that you include all required values in a dictionary and that they are in range and semantically correct.  Hell, even the date time format--which is pretty well-specified--is a mound of special case code in my library to manage where other people have screwed it up royally.  Being able to generate consistently correct PDF is hard and consuming the garbage in the sea of PDFs in the world is harder.
I could (and probably should) write a book about how to do this.  While a lot of the fringe code is grubby, the overall structure can be very pretty.
tl;dr - If you're thinking of a recursive descent parser for PDF, you're thinking too hard.  All you need is a tokenizer and a simple REPL.


text:
Q: Why doesn't my custom mouse cursor load after restart? I have created a new personal preferences profile in Windows 7 which cycles my background pictures from a custom folder location and changed my mouse cursor.  When I save this profile and activate it, everything runs as it should.  My problem is when I restart my computer, my mouse cursor is back to the default but my custom background setting is still active.  I have to reopen my preferences and click on my profile to activate it.  Why doesn't my OS load my cursor automatically ?
Things to note:

*

*I am using a logitech G500.

*OS: Windows 7 (happened within multiple OS builds)

*I have tried:

*

*Deleting & reinstalling mouse driver

*Creating new profiles

*multiple mouses

*different cursors

*removed logitech services from the start up

How can I resolve this issue?

A: I found that custom profiles are set as 'Themes' and the referenced cursors only happen at save or reload.
To fix this:  make a copy of the referenced cursors and paste them into the C:\Windows\Cursor folder to be called upon start up.  Then re-find the cursors stored in that windows cursor location (default location themes look at - regardless if you change them manually)

A: The solution of copying custom cursors inside Windows\Cursor folder works. But I found that it also works if you copy them to other system folders outside Windows, like ProgramData. Finally, I found that the background problem is another.
Windows stores cursor configuration in Registry under key:
HKEY_CURRENT_USER\Control Panel\Cursors

If your custom cursor file is located inside any folder under your profile, Windows rewrites its path using %UserProfile% variable. It seems that this is the offending part. If you go to that registry key and manually rewrite those full paths without using %UserProfile% variable, custom cursors will load normally at startup, wherever the files are located.
It's still a bug, but at least it's a cleaner workaround than copying files into Windows folders.

A: I researched a lot and found this:

*

*Copy this into file explorer: C:\Windows\Cursor

*Drag your own cursor into the folder, and it should stay after restart.


text:
Q: Excel VBA runtime error 1004 I'm trying to write a macro to paste special formulas but keep getting a runtime error 1004 "PasteSpecial method of Range class failed".
This macro comes directly from using the "Record Macro" provided by Excel.
Sub paste_formulas()
  Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
         SkipBlanks:=False, Transpose:=False
End Sub

Here is the sequence of events:

*

*Manually select a range of cells in CSV file A and copy (CTRL+C).

*Switch to the XLS file B and select the cell were I want the copied data pasted.

*Press Macros and run personal.xlsm!paste_formulas

That's when I get the error. Why does this work manually when I copy/paste-special formulas, but fail in the macro?
Note: I need this to work in the above sequence regardless of the selected range that I copy (will vary from time to time), and regardless of the location I paste formulas to (will also vary from time to time). In other words, hardcoding a fixed range for copy and/or paste won't work for me.
Thanks in advance for any help understanding why my code isn't working or providing a work-around.

A: The reason is very simple, When you copy from the CSV and then in your workbook, click on Macros in the Developer Toolbar, Excel clears the clipboard.
Excel has this habit of clearing the clipboard when you click on Developer | Macros. To demonstrate this, copy the cells from the same workbook. You will see the ant like border around the cells. Now in the same workbook, click on Developer | Macros. The Ant like borders will disappear :)

Set a shortcut key for your macro and use that. it will work :)


text:
Q: How to mutate an element from the DOM and then return it to its original state in JavaScript? I've made a function which cycles through the DOM of a targeted are (via id) to create a rollover functionality.
My problem lies within the rollOver/rollOut function. For some reason the environment where I run this script seems to mess with the srcset attribute.
This is the original:
function rollOver(elem) {
  (document.getElementById(elem).srcset =
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-hover-" +
    elem.slice(6) +
    ".jpg?$staticlink$"),
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-2x-hover-" +
    elem.slice(6) +
    ".jpg?$staticlink$ 2x";
}

function rollOut(elem) {
  (document.getElementById(elem).srcset =
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-" +
    elem.slice(6) +
    ".jpg?$staticlink$"),
    "https://staging.elizabetharden.pfsweb.demandware.net/on/demandware.static/-/Sites-JuicyCoutureBeauty-Library/default/dw685f8968/images/home-page/desktop/eyes-on-you-desktop-2x-" +
    elem.slice(6) +
    ".jpg?$staticlink$ 2x";
}

rollOver:
path/to/image/eyes-on-you-desktop-hover-" + elem.slice(6) + ".jpg?$staticlink$"

rollOut:
path/to/image/eyes-on-you-desktop-" + elem.slice(6) +".jpg $staticlink$"

The elem variable comes from here...
document.addEventListener("DOMContentLoaded", function (event) {
  var rollOverCollectionA = document
    .getElementById("roll-over-collection-b")
    .getElementsByClassName("rollover");
  rollOverCollectionA = Array.prototype.slice.apply(rollOverCollectionA);

  var l = rollOverCollectionA.length;
  for (let i = 0; i < l; i++) {
    on("mouseover", `#${rollOverCollectionA[i].id}`, function () {
      rollOver(rollOverCollectionA[i].id);
    });
    on("mouseout", `#${rollOverCollectionA[i].id}`, function () {
      rollOut(rollOverCollectionA[i].id);
    });
  }
});

and its just the #id value on the elem which gets sliced to coincide with the element which is receiving focus.
I tried something like this:
  function rollOver(id, elem ) {
    elem.srcset = elem.srcset.splice(174, 0, '-hover');
    elem.srcset = elem.srcset.splice(362, 0, 'hover-')
    document.getElementById(id).srcset = elem.srcset;
  }

  function rollOut(id, elem) {
    document.getElementById(id).srcset = elem.srcset;
  }

But what that does is continually add 'hover to the elem.srcset/string !
UPDATE
This is a working demo.
UPDATE
This is an example of what is happening.

The rollover appends hover to the non-hover state, but then the next time you hover the src now has `xxx-1-hover-hover.jpg
Any help would be appreciated!


text:
Q: new operator overwriting an existing object I have a custom FastStack class, implemented as a fixed size array and an index into that array.
In my copy constructor, I allocate the array and then assign each object from the copy's array into the new array. There's some refcounting in the objects on the stack, hence assignment is used rather than a simple copy.
The problem is that when allocating the array, it sometimes overwrites part of the other stack's array. As can be expected, this leads to eventual segmentation faults when that data is dereferenced.
class FastStack {
private:
    int m_size, m_ptr;
    ObjectRef* m_stack;

public:
    FastStack(int size) : m_size(size), m_ptr(-1) {
        m_stack = new ObjectRef[m_size];
    }

    FastStack(const FastStack& copy) : m_size(copy.m_size), m_ptr(copy.m_ptr) {
        long a = (long)copy.m_stack[0];

        m_stack = new ObjectRef[m_size];

        if ((long)copy.m_stack[0] != a)
            fprintf(stderr, "\nWe have a serious problem!\n\n");

        for (int i = 0; i <= m_ptr; i++)
            m_stack[i] = copy.m_stack[i];
    }

    ~FastStack() {
        delete[] m_stack;
    }
};

class ObjectRef {
private:
    DataObj* m_obj;

public:
    ObjectRef() : m_obj(0) { }

    ObjectRef(DataObj* obj) : m_obj(obj) {
        if (m_obj) m_obj->addRef();
    }

    ObjectRef(const ObjectRef& obj) : m_obj(obj.m_obj) {
        if (m_obj) m_obj->addRef();
    }

    ~ObjectRef() {
        if (m_obj) m_obj->delRef();
    }

    ObjectRef& operator=(DataObj* obj) {
        if (obj) obj->addRef();
        if (m_obj) m_obj->delRef();
        m_obj = obj;
        return *this;
    }

    ObjectRef& operator=(const ObjectRef& obj) {
        if (obj.m_obj) obj.m_obj->addRef();
        if (m_obj) m_obj->delRef();
        m_obj = obj.m_obj;
        return *this;
    }
};

I see that "We have a serious problem!" line shortly before a segfault, and stepping through it with gdb I can see that one of the ObjectRefs created by new has the same address as the other stack's array.
My first instinct is to say that new should never be allocating memory that is already in use, but that clearly seems to be the case here and I am at a complete loss as to what can be done.
Added: At the time that I see this happen, m_size = 2 and m_ptr = 0.
The full code for this program is on github at https://github.com/dvpdiner2/pycdc but is quite convoluted and difficult to follow.

A: Sometimes new is known to give memory that has been already allocated to other objects and when that happens good C++ code must repeat the allocation in the hope of having memory not shared with others...
NO!
new is ok, your program is buggy. Write this one hundred times on the blackboard.
new will never give you memory that has been given to someone else BUT if you did anything bad before (i.e. accessing out of the limits, dereferencing a pointer once the object it was pointing to has been deallocated, used an invalidated iterator and jillions of other possible "UB" violations) then new gains a special permit and can do whatever it likes, including making daemons appearing out of your nosrils.
Your code appears highly suspect but I don't see anything that is for sure an error (too much code is hidden, for example what exactly is an ObjRef and how it is declared). From what I see however I'm almost sure you did something wrong before getting to that new allocation because there many violations of good C++ practices (for example the shown class has a constructor and a copy constructor, but no assignment operator nor a destructor).
The biggest problem with the shown code however is that looks like an half-backed and buggy attempt of mimicking a subset of what a plain std::vector would do. To say exactly what is(are) the problem(s) however requires more context... this is bad code but could be legal depending on how other code has been written. It's also evident that even this small piece of code has been altered and reduced as there are no methods to access anything, no friends and data members are private (so it's basically impossible to do anything with those objects).

A: In a loop you iterate from 0 to m_ptr:
for (int i = 0; i <= m_ptr; i++)
    m_stack[i] = copy.m_stack[i];

But, your array m_stack contains m_size elements (assuming that you initialized them).
EDIT: The only way (I could see) to overlap m_stack and copy.m_stack is if placement new operator is used. But, according to posted source, you didn't do it.

A: What you should do is use a std::vector to manage the memory, and just keep the index (m_ptr) managed explicitly by you. This will solve all these problems.
However, I seriously can't see what the hell is wrong with your code. Consider yourself an optimizer, and take a quick pass, focusing just on a and copy.m_stack[0].
long a = (long)copy.m_stack[0];

m_stack = new ObjectRef[m_size];

if ((long)copy.m_stack[0] != a)

long a = (long)copy.m_stack[0];

if ((long)copy.m_stack[0] != a)

if (copy.m_stack[0] != copy.m_stack[0])

If that condition is true, then you must have corrupted your heap, and possibly but less likely the stack. Heap corruption can bite in apparently completely unrelated code to the code at fault. Either that, or you're screwing with threads and not telling us about it. (and getting it wrong).
Of course, you're missing several other important functions, like operator= and destructor, but hey- none of which you would have to implement yourself if you used a vector.

A: It seems to me like the most likely culprit is actually the input to the copy constructor.
However, I will say that this code doesn't do nearly enough validation and the way it is constructed is going to make it hard to detect a bug or misuse until it crashes at some point down the road. A class written in this manner will produce hard to find bugs, as you're seeing now.
Simple things you should do at minimum:
 1. Handle new throwing an exception
 2. Check the bounds before you index into an array, even if you're just using m_stack[0]
 3. Check that the input to the copy constructor is valid (aka initialized)
Oh, and the easiest way to track down memory errors like this is just to valgrind it. It's surprisingly good at flushing out memory issues quickly, even thought that's not its stated goal.
Also this would be super simple to debug if you included a working chunk of code that isolated the problem in it's simplest reproducible form.

A: You can replace the entire code posted by this:
class FastStack {
public:

protected:
    std::vector<boost::shared_ptr<DataObj> > m_Stack;
};

(and if you need to add a constructor that makes sure that the vector has preallocated its memory).
When you are doing unnecessary work like you are doing here by implementing classes that someone else has already done better ("someone else" are in this case smart people, smarter than most of us) it is likely that you add more problems than you solve.
std::vector is going to be a far better collection than your allocated array and boost::shared_ptr (or tr1::shared_ptr or std::shared_ptr if you are using a tr1/c++0x-compatible compiler) is doing exactly what your ObjectRef class is doing (but better). From your code it appears as if DataObj contains its own refcount, which you can also scrap if you use shared_ptrs instead.
Use the tools that are available - the less code you have to write, the less chance you have of writing bugs... If you replace your code with the above and are still seeing problems, your error is somewhere else.

A: May it be that your code works with multiple threads?
Since new never ever returns memory that is already allocated the only way that you get the check message is that another threads is doing something to the copy instance.
This suspicion is also raised by the fact that it only happens from time to time. This is typically for multi-threading bugs (as they need a special timing to happen that only occur from time to time).


text:
Q: What is the analogy between the Hilbert function and L-functions? In his book Projective Varieties and Modular Forms, M. Eichler uses the notation $L(\lambda, M)$ for the Hilbert function of a finite graded $R=k[x_0, \dots, x_n]$-module $M$. So, $L(\lambda, M) = \dim_k M_\lambda$. By the classical theorem of Hilbert, $L(\lambda, M)$ coincides with a numerical polynomial for large $\lambda$.
On p.27 of his book Eichler writes an equation which amounts to
$$L(\lambda + \mu, M) = L(\lambda, M \otimes \mathcal O(\mu))$$
Of course, this is absolutely self-evident because tensoring with $\mathcal O(\mu)$ only shifts the degree by $\mu$.
This is very much analogous to the equation
$$L(s + \mu, V) = L(s, V\otimes \mathbf Q_{\ell}(\mu)),$$
where $V$ is a geometric representation over $\mathbf Q$.
On p.43, Eichler states in the following form a generalization of Riemann-Roch and Serre dualiy:

Theorem of Duality. Let $n>1$. For a finite, reflexive, and quasifree $R$-module $M$ the following equations hold $(i=1, \dots, n-1)$: $$L(\lambda, \text{Ext}_R^i(M, R)) = L(-\lambda -2n -2, \text{Ext}_R^{n-i}(M_*, R)).$$

This looks suspiciously like a functional equation relating the  $L$-functions of $H^i_{et}(X, \mathbf Q_\ell)$ and $H^{2n-i}_{et}(X, \mathbf Q_\ell)$, for a variety of dimension $n$ over $\mathbf Q$.
What is going on here? Where does this similarity comes from? Eichler says nothing of it, but the suggestive notation is probably deliberate...


text:
Q: Encontrar y devolver listas que estan en una matriz necesito ayuda con esto, dada dos matrices:
a = [[bogota, cundinamarca,13013,0,0,0,0], [cartagena,bolivar,12002,1,1,1,1], [leticia,amazonas,140012,0,0,0,0]]

b = [[bogota,cundinamarca,13013], [cartagena,bolivar,12002]]

como hago para crear una nueva matriz "c" que dada la matriz b, busque en la matriz principal "a"
las que tengan los mismos elementos en los indices  0, 1 y 2, y las agregue a "c", es decir que c sea asi:
c = [[bogota, cundinamarca,13013,0,0,0,0], [cartagena,bolivar,12002,1,1,1,1]]

pd. La matriz principal "a" es mucho mas grande que la matriz "b"

A: Lo puedes hacer con in ciclo for o de forma mas optima con una comprensión de lista, donde recorreremos la lista a y comprobaremos si su elemento esta en la lista b
a = [["bogota", "cundinamarca",13013,0,0,0,0], ["cartagena","bolivar",12002,1,1,1,1], ["leticia","amazonas",140012,0,0,0,0]]
b = [["bogota","cundinamarca",13013], ["cartagena","bolivar",12002]]

c = [y for y in a if y[:3] in b]

Utilizamos la notación de slice para solo verificar los 3 primeros elementos, puesto que la lista b contiene [bogota,cundinamarca,13013] y la lista a contienen muchos mas [bogota, cundinamarca,13013,0,0,0,0]
resultado
[['bogota', 'cundinamarca', 13013, 0, 0, 0, 0],
 ['cartagena', 'bolivar', 12002, 1, 1, 1, 1]]

con ciclo for tradicional
c = []
for y in a:
    if y[:3] in b:
        c.append(y[:3])

print(c)

Por lo que veo en los comentarios, quieres que mantenga el orden, en ese caso puedes utilizar la siguiente comprensión de lista.
a = [["bogota", "cundinamarca",13013,0,0,0,0], ["cartagena","bolivar",12002,1,1,1,1], ["leticia","amazonas",140012,0,0,0,0]]
#cambie el orden para que veas que se mantiene
b = [["cartagena","bolivar",12002],["bogota","cundinamarca",13013]]

#almacenamos x que es el dato de la lista a
c = [x for y in b for x in a if y == x[:3]]

Es necesario recorre la lista a por que solo hay coincidencia hasta ciertos elementos (los primmeros 3)
resultado
[['cartagena', 'bolivar', 12002, 1, 1, 1, 1],
 ['bogota', 'cundinamarca', 13013, 0, 0, 0, 0]]


text:
Q: ServiceWorker refresh the page that loads the work I would like to benefits from offline capabilities, so I m making sure to cache on install the page it self and other assets like css and js
self.addEventListener('install', function (event) {
    event.waitUntil(caches.open(cacheName).then(cache => cache.addAll([
        "/",
        self.location.href
    ])));

    self.skipWaiting();
});

as install will be run only once for the worker, how can I make sure that those assets get refreshed on every run or at least from time to time?

A: You can achieve this also by defining a new cache name each time you deploy a new version of your website:
//change cache name with each deploy
var staticCacheName = 'NewWithEachDeploy';

self.addEventListener('install', function (event) {
  event.waitUntil(
    caches.open(staticCacheName).then(function (cache) {
      return cache.addAll([
        'index.html',
        '...'
      ]);
    })
  );
});

Then on activate you delete all the old caches.
self.addEventListener('activate', function (event) {
    event.waitUntil(caches.keys().then(function (keyList) {
        return Promise.all(keyList.map(function (cacheKey) {
            //delete all caches which do not equal with the current cache name (staticCacheName)
            if (cacheKey !== staticCacheName) {
                console.log('[ServiceWorker] Removing old cache', cacheKey);
                return caches.delete(key);
            }
        }));
    }));
});

This way you make sure all resources are updated at once. Otherwise you can get in trouble. For example your cached html is updated to the newest version but the JS file is still old and this constellation probably does not play well together.

A: While implementing cache expiration using vanilla JS can be bit challenging, you can try using Workbox by Google. It has this concept of cache expiration.
A super basic example:
const cacheExpirationPlugin = new workbox.cacheExpiration.CacheExpirationPlugin({
  maxEntries: 50,
  maxAgeSeconds: 24 * 60 * 60
});

You could read more about it here.


text:
Q: JSON cortado ao enviar por post com AJAX estou usando o Angular para fazer um cadastro no banco de dados, eu pego os dados dos meus inputs coloco em um objeto e transformo em um JSON e mando por post, mas acontece que o meu JSON é cortado e não faço a minima idéia de o por que.
 var meuJson = angular.toJson(meuObjeto);
 $http({
   method: 'POST',
   url: 'http://url/arquivo.php',
   data: {
     'data': meuJson
   }
 })
 .success(function (data){
    console.log(data);
  })

Meu JSON está aparecendo assim.
[
  {
    "uuid":"56456456456456456456465456"
  },
  {
    "store_name":"",
    "store_email":"",
    "store_facebook":"",
    "contact_name":"Juca",
    "contact_email":"email@gmail.com",
    "contact_facebook":"http://localho

Eu dei um console.log() com o Json quando eu pego ele e mostro, depois eu mostro a resposta, vejam a imagem que fica melhor de entender:

A: Ainda não tenho permissões para fazer comentários, então postarei uma alternativa mesmo assim: bem, eu já tive problemas similares com transferências cortadas, e um dos principais problemas nesse caso é a codificação dos caracteres. Por algum motivo que desconheço, quando a codificação do texto enviada é diferente da codificação esperada pelo servidor em determinados casos ele corta a string a partir de um caractere que ele não pode interpretar - eu acho.
Para verificar a codificação do texto que está sendo enviado utilize o método mb_detect_encoding. Se a codificação do JSON recebida for diferente da esperada tente forçar a conversão pelo PHP, ou então definindo o charset da página que está enviando JSON.
Convertendo com o PHP:
$charset = mb_detect_encoding($_POST['data']);
$json = mb_convert_encoding($_POST['data'], "UTF-8", $encoding);

Convertendo com o HTML: http://www.w3c.br/cursos/html5/conteudo/capitulo3.html


text:
Q: Cache Addressing: Length of Index, Block offset, Byte offset & Tag? Let's say I know the following values:
W = Word length (= 32 bits)
S = Cache size in words
B = Block size in words
M = Main memory size in words

How do I calculate how many bits are needed for:
- Index
- Block offset
- Byte offset
- Tag

a) in Direct Mapped Cache
b) in Fully Associative Cache?

A: The address may be split up into the following parts:
[ tag | index | block or line offset | byte offset ]

Number of byte offset bits
0 for word-addressable memory, log2(bytes per word) for byte addressable memory
Number of block or line offset bits
log2(words per line)
Number of index bits
log2(CS), where CS is the number of cache sets.

*

*For Fully Associative, CS is 1. Since log2(1) is 0, there are no
index bits.

*For Direct Mapped, CS is equal to CL, the number of cache lines, so the number of index bits is log2(CS) === log2(CL).

*For n-way Associative CS = CL ÷ n: log2(CL ÷ n) index bits.

How many cache lines you have got can be calculated by dividing the cache size by the block size = S/B (assuming they both do not include the size for tag and valid bits).
Number of tag bits
Length of address minus number of bits used for offset(s) and index. The Length of the the addresses can be calculated using the size of the main memory, as e.g. any byte needs to be addressed, if it's a byte addressable memory.
Source: http://babbage.cs.qc.edu/courses/cs343/cache_parameters.xhtml


text:
Q: Regex to return the value starting at the first number and ending at the bracket I am getting a return value of "_sahi._div(\"1.0[4]\")" and I only need the 1.0 number. Is there any way to create a regex that returns the first number and every character after that until the [ ?

A: Try this regex:
[\d\.]+(?=\[)

Demo


text:
Q: Delphi - Authorization TIdHttp fails over HTTP proxy I'm using Delphi XE 6 and TIdHttp component(Indy 10.6.0.5122) and trying to consume a SOAP service - http://www.webservicex.net/globalweather.asmx over a http proxy (CCProxy - http://www.youngzsoft.net/ccproxy/). The issue is that at the first attempt to connect to the webservice I receive an "Unauthorized" respone:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Unauthorized ...

IP Address: xxx.xxx.xxx.:61295

MAC Address:

Server Time: 2014-11-18 14:19:00

Auth Result:

I've linked an IdSSLIOHandlerSocketOpenSSL and IdLogDebug1 components to IdHttp in order to debug the issue.
Logs of the operations performed
***********************IdSSLIOHandlerSocketOpenSSL1Status
Connecting to xxx.xxx.xxx.xxx.

***********************IdLogDebug1Send
POST http://www.webservicex.net/globalweather.asmx HTTP/1.1
Content-Type: text/xml; charset=utf-8
Content-Length: 388
SOAPAction: http://www.webserviceX.NET/GetCitiesByCountry
Host: www.webservicex.net
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

***********************IdLogDebug1Send
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetCitiesByCountry xmlns="http://www.webserviceX.NET">
      <CountryName>Romania</CountryName>
    </GetCitiesByCountry>
  </soap:Body>
</soap:Envelope>

***********************IdLogDebug1Receive
HTTP/1.0 407 Unauthorized
Server: Proxy
Proxy-Authenticate: Basic realm="CCProxy Authorization"
Cache-control: no-cache

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Unauthorized ...

IP Address: xxx.xxx.xxx.xxx:61295

MAC Address:

Server Time: 2014-11-18 14:19:00

Auth Result:

***********************IdSSLIOHandlerSocketOpenSSL1Status
Disconnected.

Now, what is interesting is that if I'm trying again to call the webservice everything works correctly. Log of the operations:
***********************IdSSLIOHandlerSocketOpenSSL1Status
Connecting to xxx.xxx.xxx.xxx.

***********************IdLogDebug1Send
POST http://www.webservicex.net/globalweather.asmx HTTP/1.1
Content-Type: text/xml; charset=utf-8
Content-Length: 388
SOAPAction: http://www.webserviceX.NET/GetCitiesByCountry
Host: www.webservicex.net
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)
Proxy-Authorization: Basic YW1ibzphbWJvIQ==

***********************IdLogDebug1Send
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetCitiesByCountry xmlns="http://www.webserviceX.NET">
      <CountryName>Romania</CountryName>
    </GetCitiesByCountry>
  </soap:Body>
</soap:Envelope>

***********************IdLogDebug1Receive
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 2456

***********************IdLogDebug1Receive
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 18 Nov 2014 12:26:21 GMT

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET"><GetCitiesByCountryResult><NewDataSet>
  <Table>
    <Country>Romania</Country>
    <City>Arad</City>
  </Table>
  <Table>
    <Country>Romania</Country>
    <City>Bacau</City>
  </Table>
  ......

And the response it's correct.
Code of the application
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, Soap.SOAPHTTPTrans,
  IdAuthentication, IdHeaderList, IdIntercept, IdLogBase, IdLogDebug,
  IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL
  ,IdGlobal;

type
  TForm1 = class(TForm)
    IdHTTP1: TIdHTTP;
    Button1: TButton;
    HTTPReqResp1: THTTPReqResp;
    Memo1: TMemo;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
    IdLogDebug1: TIdLogDebug;
    Memo2: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure IdHTTP1ProxyAuthorization(Sender: TObject;
      Authentication: TIdAuthentication; var Handled: Boolean);
    procedure IdSSLIOHandlerSocketOpenSSL1StatusInfo(const AMsg: string);
    procedure IdSSLIOHandlerSocketOpenSSL1Status(ASender: TObject;
      const AStatus: TIdStatus; const AStatusText: string);
    procedure IdLogDebug1Receive(ASender: TIdConnectionIntercept;
      var ABuffer: TIdBytes);
    procedure IdLogDebug1Send(ASender: TIdConnectionIntercept;
      var ABuffer: TIdBytes);
    procedure IdHTTP1Authorization(Sender: TObject;
      Authentication: TIdAuthentication; var Handled: Boolean);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  postData: TMemoryStream;
begin
  postData := TMemoryStream.Create;
  try
    Memo1.Lines.Clear;
    postData.LoadFromFile('..\..\soap1.1.txt');
    IdHTTP1.Request.ContentType := 'text/xml';
    IdHTTP1.Request.Charset := 'utf-8';
    IdHTTP1.Request.CustomHeaders.Values['SOAPAction'] := 'http://www.webserviceX.NET/GetCitiesByCountry';
    IdHTTP1.ProtocolVersion := pv1_1;
    IdHTTP1.HTTPOptions := IdHTTP1.HTTPOptions + [hoKeepOrigProtocol];
    Memo1.Lines.Text := IdHTTP1.Post('http://www.webservicex.net/globalweather.asmx', postData);
  finally
    postData.Free;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 with IdHTTP1.ProxyParams do
  begin
    ProxyServer := 'xxx.xxx.xxx.xxx';
    ProxyPort := 808;
    ProxyUsername := 'User-001';
    ProxyPassword := 'User-001!';
  end;

end;

procedure TForm1.IdHTTP1Authorization(Sender: TObject;
  Authentication: TIdAuthentication; var Handled: Boolean);
begin
//
  Authentication.Username := 'User-001';
  Authentication.Password := 'User-001!';
end;

procedure TForm1.IdHTTP1ProxyAuthorization(Sender: TObject;
  Authentication: TIdAuthentication; var Handled: Boolean);
begin
//
// Authentication.Username := 'User-001';
// Authentication.Password := 'User-001!';
// Handled := true;
end;

procedure TForm1.IdLogDebug1Receive(ASender: TIdConnectionIntercept;
  var ABuffer: TIdBytes);
begin
 Memo2.Lines.Add(#13#10+'***********************IdLogDebug1Receive '+#13#10+BytesToString(ABuffer))
end;

procedure TForm1.IdLogDebug1Send(ASender: TIdConnectionIntercept;
  var ABuffer: TIdBytes);
begin
 Memo2.Lines.Add(#13#10+'***********************IdLogDebug1Send '+#13#10+BytesToString(ABuffer))
end;

procedure TForm1.IdSSLIOHandlerSocketOpenSSL1Status(ASender: TObject;
  const AStatus: TIdStatus; const AStatusText: string);
begin
Memo2.Lines.Add(#13#10+'***********************IdSSLIOHandlerSocketOpenSSL1Status '+#13#10+AStatusText)
end;

procedure TForm1.IdSSLIOHandlerSocketOpenSSL1StatusInfo(const AMsg: string);
begin
Memo2.Lines.Add(#13#10+'***********************IdSSLIOHandlerSocketOpenSSL1StatusInfo '+#13#10+AMsg)
end;

end.

How should I make the authentication in order to work from the first attempt?
PS : I've already read this question - Authorization failure TIdHTTP over HTTPS.
ANSWER : based on the indications of Remy Lebeau problem was solved by setting up the

OnProxySelectAuthorization

event and add the hoInProcessAuth to the

IdHTTP1.HTTPOptions

A: Make sure you have added the IdAuthentication unit to your uses clause so TIdHTTP can process Proxy-Authorization headers in a 407 reply, and also make sure you have a TIdHTTP.OnProxyAuthorization event handler assigned (even if it just returns Handled:=True) otherwise TIdHTTP will not attempt proxy authorization while processing a 407 reply, even though you have provided a username/password in the TIdHTTP.ProxyParams property.
What is most likely happening is that the TIdHTTP.ProxyParams.Authentication property is initially nil during the first request, and gets filled in with a TIdBasicAuthentication object while processing the 407 reply, but a missing OnProxyAuthorization event handler causes TIdHTTP to skip authorization, and then the TIdHTTP.ProxyParams.Authentication property is not nil anymore when the second request is made, so it attempts authorization at that time.
Skipping proxy authorization if the TIdHTTP.OnProxyAuthorization event is not assigned appears to be a bug, IMHO.  By comparison, the TIdHTTP.OnAuthorization event can be unassigned as long as a non-empty value is assigned to the TIdHTTP.Request.Password property.  I have now updated TIdHTTP with similar logic for the OnProxyAuthorization event regarding the TIdHTTP.ProxyParams.Password property.
So, either update to the latest SVN snapshot, or just assign a TIdHTTP.OnProxyAuthorization event handler, then you should be OK:
procedure TForm1.IdHTTP1ProxyAuthorization(Sender: TObject; Authentication: TIdAuthentication; var Handled: Boolean);
begin
  // prompt the user for username/password (optional) and store them
  // in the Authentication.Username and Authentication.Password
  // properties, respectively. By default, they are initialized with
  // the current values of the ProxyParams.UserName and
  // ProxyParams.Password properties...
  Handled := True;
end;


text:
Q: how to start video track which is opened using getUserMedia I am trying to create a toggle button on video track of getUserMedia
toggleVideo = () => {
  let { video } = this.state;
  video = !video
  let camera = document.getElementById("camera");
  this.videoStream.getTracks().forEach(track => {
    console.log('999 :: track value', track)
    track.readyState == 'live' && track.kind === 'video' &&
      track.stop()
  })
  video === false && camera.src = "";
};
<video id="camera"></video>

using this way i am able to stop the video track but how can i restart the video track.


text:
Q: SharedPreferences.Editor not being updated after initial commit I'ma a bit confused here. I'm trying to change the value of an EditTextPreference, but it is not updated in the view. (This is in a PreferenceActivity)
Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  addPreferencesFromResource(R.xml.modify_instrument_preferences);

  // Set default values
  SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
  SharedPreferences.Editor editor = customSharedPreference.edit();
  modifying = getObjectWithName(); //Some object with a name;

  editor.putString("namePref", modifying.getName());
  editor.commit();
  android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}

My printlns print out valid information, and the commit() returns true, but on clicking the EditTextPreference, it displays the old value. If I rotate the screen, causing the onCreate to get run again, the EditTextPreference has the right value.
So perplexing. Why isn't this change being updated in the UI?
Edit:
I'm not sure why the above isn't working, but I managed to change it just by doing:
  EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
  namePref.setText("the text");

That updated the view everytime.

A: Although I know there are some constructs in place for PreferenceActivities to keep track of this info themselves, it doesn't seem to be well documented. I have found that adding an onPreferenceChangeListener to the preference will allow you to make those edits as soon as the preference is changed.


text:
Q: Ubuntu 14.04 live cd while booting asks for username and password (Installing in Virtual Box) Guys i am trying to install Ubuntu 14.04 in my virtual box, but it repeatedly asks for username and password. Not able to solve this problem, None of my ubuntu .iso asked this before installation.. pls help..

A: Update (after comments):
It's always a good rule to check if the download was finished in the proper way.
The iso images are released with a checksum code for this purpose available from the same page of the downloads In this case from here.

Those are the MD5SUM for the relative files
dccff28314d9ae4ed262cfc6f35e5153 *ubuntu-14.04-desktop-amd64.iso
c4d4d037d7d0a05e8f526d18aa25fb5e *ubuntu-14.04-desktop-i386.iso
01545fa976c8367b4f0d59169ac4866c *ubuntu-14.04-server-amd64.iso
08d25bf879e353686a974b7b14ae7d81 *ubuntu-14.04-server-i386.iso
b31731ea6cdbebe1d02f8193db420886 *wubi.exe

If you downloaded a ready to use ubuntu image for virtualbox usually the passwords are
Active user account(s) (username/password): ubuntu/reverse

If you downloaded from another source you should refer to the download page.
Note that you can always install in virtualbox a ready image and after upgrade it
sudo apt-get update
sudo apt-get upgrade

or
sudo apt-get dist-upgrade

In the past there was some livecd for which the username was ubuntu (or lubuntu...) with no password.

A: At last i solved the real problem i got, i placed the downloaded .iso in my torrent folder and started the bitorrent using this link-> "http://www.ubuntu.com/download/alternative-downloads".
->It was at 99.9%, remaining 0.1% got completed and now its works like a charm.


text:
Q: Golang decrypt array Byte Xtea ECB algorithm I have an input byte array:
60614e680e705d0fefcf7ac8102c4452
ecb0c85768f2f2dc52415c43a36712f0
31c9037dafd31f01ecb0c85768f2f2dc
7b00be7e5a15fee1e78c63c58c2c6861
fef9a1c4130a354c846448512e6a97ce
4a9005690d1e3808f065c957538e1bac
87e7228322ab39a6900146786840dc0b
c536ad6afb6e4e3267fb045dd9c7e670
f1c2d2ac1fcc71ad06b7b194de4031f4
046744610aafa7b92fd3f392c3a5eeb1
474ffa60c0587e68ecb0c85768f2f2dc
2a88827461b41c99b2539b6bfdcd4325
be3ced59be7b594addb3366e076f6e47
0cc41df1eb3a8d93c99eb7bdad5a474c
33659653762910d0ecb0c85768f2f2dc
ecb0c85768f2f2dc82e715e7952a79c4
660074ccc50741cab5eabb873ae706b4
c8b008128df0af80fece91741fc5f641
1145aab35ac9f6e0f8a937baed012d00
c3be705a5e8c3440ddc1cd4e0051cccc

The algorithm by which they were encrypted XTEA ECB. I try to use the library for decryption "golang.org/x/crypto/xtea".
package main

import (
    "golang.org/x/crypto/xtea"
    "fmt"
)

func main() {
    // encripte data
    test :=[]byte{
            0x60, 0x61, 0x4e, 0x68, 0x0e, 0x70, 0x5d, 0x0f, 0xef, 0xcf, 0x7a, 0xc8, 0x10, 0x2c, 0x44, 0x52,
            0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc, 0x52, 0x41, 0x5c, 0x43, 0xa3, 0x67, 0x12, 0xf0,
            0x31, 0xc9, 0x03, 0x7d, 0xaf, 0xd3, 0x1f, 0x01, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0x7b, 0x00, 0xbe, 0x7e, 0x5a, 0x15, 0xfe, 0xe1, 0xe7, 0x8c, 0x63, 0xc5, 0x8c, 0x2c, 0x68, 0x61,
            0xfe, 0xf9, 0xa1, 0xc4, 0x13, 0x0a, 0x35, 0x4c, 0x84, 0x64, 0x48, 0x51, 0x2e, 0x6a, 0x97, 0xce,
            0x4a, 0x90, 0x05, 0x69, 0x0d, 0x1e, 0x38, 0x08, 0xf0, 0x65, 0xc9, 0x57, 0x53, 0x8e, 0x1b, 0xac,
            0x87, 0xe7, 0x22, 0x83, 0x22, 0xab, 0x39, 0xa6, 0x90, 0x01, 0x46, 0x78, 0x68, 0x40, 0xdc, 0x0b,
            0xc5, 0x36, 0xad, 0x6a, 0xfb, 0x6e, 0x4e, 0x32, 0x67, 0xfb, 0x04, 0x5d, 0xd9, 0xc7, 0xe6, 0x70,
            0xf1, 0xc2, 0xd2, 0xac, 0x1f, 0xcc, 0x71, 0xad, 0x06, 0xb7, 0xb1, 0x94, 0xde, 0x40, 0x31, 0xf4,
            0x04, 0x67, 0x44, 0x61, 0x0a, 0xaf, 0xa7, 0xb9, 0x2f, 0xd3, 0xf3, 0x92, 0xc3, 0xa5, 0xee, 0xb1,
            0x47, 0x4f, 0xfa, 0x60, 0xc0, 0x58, 0x7e, 0x68, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0x2a, 0x88, 0x82, 0x74, 0x61, 0xb4, 0x1c, 0x99, 0xb2, 0x53, 0x9b, 0x6b, 0xfd, 0xcd, 0x43, 0x25,
            0xbe, 0x3c, 0xed, 0x59, 0xbe, 0x7b, 0x59, 0x4a, 0xdd, 0xb3, 0x36, 0x6e, 0x07, 0x6f, 0x6e, 0x47,
            0x0c, 0xc4, 0x1d, 0xf1, 0xeb, 0x3a, 0x8d, 0x93, 0xc9, 0x9e, 0xb7, 0xbd, 0xad, 0x5a, 0x47, 0x4c,
            0x33, 0x65, 0x96, 0x53, 0x76, 0x29, 0x10, 0xd0, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc, 0x82, 0xe7, 0x15, 0xe7, 0x95, 0x2a, 0x79, 0xc4,
            0x66, 0x00, 0x74, 0xcc, 0xc5, 0x07, 0x41, 0xca, 0xb5, 0xea, 0xbb, 0x87, 0x3a, 0xe7, 0x06, 0xb4,
            0xc8, 0xb0, 0x08, 0x12, 0x8d, 0xf0, 0xaf, 0x80, 0xfe, 0xce, 0x91, 0x74, 0x1f, 0xc5, 0xf6, 0x41,
            0x11, 0x45, 0xaa, 0xb3, 0x5a, 0xc9, 0xf6, 0xe0, 0xf8, 0xa9, 0x37, 0xba, 0xed, 0x01, 0x2d, 0x00,
            0xc3, 0xbe, 0x70, 0x5a, 0x5e, 0x8c, 0x34, 0x40, 0xdd, 0xc1, 0xcd, 0x4e, 0x00, 0x51, 0xcc, 0xcc,
            }
    // key
    key := []byte("yuyuyuyuopopopop")
    c, _ := xtea.NewCipher(key)
    myout := make([]byte, len(test))
    // decrypte
    c.Decrypt(myout, test)

    fmt.Println(myout)
}

My results do not coincide with what should be the result. Maybe I'm not using the library correctly? Or was it wrong with the data type? I'm new to the golang. The array that should be output:
09300004100e00000104f47795590210
0000000000000000616161615d5d5d5d
09150000000000000000000000000000
000000000000000d1052545530322e30
312e3030303200000012040000000013
040000000014046161616115045d5d5d
5d1604010e00001704010e0000180401
0e00001904010e00001a04010e00001b
04010e00001c04010e00001d04010e00
001e01001f0100200100210100240100
25113235303032000000000000000000
0000002604ef1400002704930d00002d
01022e02e0012f05ffffffff00300103
3101003301003404050100003d20342e
3132382e323400000000000000000000
00000000000000000000000000004401
184f04960d0000500400000000570460
ea0000580422060000590460ea00005a
04e01500005b01005c01025d01005e01
005f010360010361010262010400011b

A: Maybe someone will come in handy. The library "golang.org/x/crypto/xtea" does not include the XTEA algorithm with the ECB model because of its insecurity, therefore I wrote my own version:
package main

import (
    "fmt"
    "encoding/hex"
    "encoding/binary"
)

func main() {
    original := []byte{
            0x60, 0x61, 0x4e, 0x68, 0x0e, 0x70, 0x5d, 0x0f, 0xef, 0xcf, 0x7a, 0xc8, 0x10, 0x2c, 0x44, 0x52,
            0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc, 0x52, 0x41, 0x5c, 0x43, 0xa3, 0x67, 0x12, 0xf0,
            0x31, 0xc9, 0x03, 0x7d, 0xaf, 0xd3, 0x1f, 0x01, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0x7b, 0x00, 0xbe, 0x7e, 0x5a, 0x15, 0xfe, 0xe1, 0xe7, 0x8c, 0x63, 0xc5, 0x8c, 0x2c, 0x68, 0x61,
            0xfe, 0xf9, 0xa1, 0xc4, 0x13, 0x0a, 0x35, 0x4c, 0x84, 0x64, 0x48, 0x51, 0x2e, 0x6a, 0x97, 0xce,
            0x4a, 0x90, 0x05, 0x69, 0x0d, 0x1e, 0x38, 0x08, 0xf0, 0x65, 0xc9, 0x57, 0x53, 0x8e, 0x1b, 0xac,
            0x87, 0xe7, 0x22, 0x83, 0x22, 0xab, 0x39, 0xa6, 0x90, 0x01, 0x46, 0x78, 0x68, 0x40, 0xdc, 0x0b,
            0xc5, 0x36, 0xad, 0x6a, 0xfb, 0x6e, 0x4e, 0x32, 0x67, 0xfb, 0x04, 0x5d, 0xd9, 0xc7, 0xe6, 0x70,
            0xf1, 0xc2, 0xd2, 0xac, 0x1f, 0xcc, 0x71, 0xad, 0x06, 0xb7, 0xb1, 0x94, 0xde, 0x40, 0x31, 0xf4,
            0x04, 0x67, 0x44, 0x61, 0x0a, 0xaf, 0xa7, 0xb9, 0x2f, 0xd3, 0xf3, 0x92, 0xc3, 0xa5, 0xee, 0xb1,
            0x47, 0x4f, 0xfa, 0x60, 0xc0, 0x58, 0x7e, 0x68, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0x2a, 0x88, 0x82, 0x74, 0x61, 0xb4, 0x1c, 0x99, 0xb2, 0x53, 0x9b, 0x6b, 0xfd, 0xcd, 0x43, 0x25,
            0xbe, 0x3c, 0xed, 0x59, 0xbe, 0x7b, 0x59, 0x4a, 0xdd, 0xb3, 0x36, 0x6e, 0x07, 0x6f, 0x6e, 0x47,
            0x0c, 0xc4, 0x1d, 0xf1, 0xeb, 0x3a, 0x8d, 0x93, 0xc9, 0x9e, 0xb7, 0xbd, 0xad, 0x5a, 0x47, 0x4c,
            0x33, 0x65, 0x96, 0x53, 0x76, 0x29, 0x10, 0xd0, 0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc,
            0xec, 0xb0, 0xc8, 0x57, 0x68, 0xf2, 0xf2, 0xdc, 0x82, 0xe7, 0x15, 0xe7, 0x95, 0x2a, 0x79, 0xc4,
            0x66, 0x00, 0x74, 0xcc, 0xc5, 0x07, 0x41, 0xca, 0xb5, 0xea, 0xbb, 0x87, 0x3a, 0xe7, 0x06, 0xb4,
            0xc8, 0xb0, 0x08, 0x12, 0x8d, 0xf0, 0xaf, 0x80, 0xfe, 0xce, 0x91, 0x74, 0x1f, 0xc5, 0xf6, 0x41,
            0x11, 0x45, 0xaa, 0xb3, 0x5a, 0xc9, 0xf6, 0xe0, 0xf8, 0xa9, 0x37, 0xba, 0xed, 0x01, 0x2d, 0x00,
            0xc3, 0xbe, 0x70, 0x5a, 0x5e, 0x8c, 0x34, 0x40, 0xdd, 0xc1, 0xcd, 0x4e, 0x00, 0x51, 0xcc, 0xcc}

    testKey := []byte("yuyuyuyuopopopop")
    block := make([]byte, 8)
    for i := 0; i< len(original)/8; i++ {
        block = decrypt(testKey , original[(i*8):((i+1)*8)], 32)
        fmt.Println(hex.Dump(block))
    }
}

func decrypt(key []byte, block []byte, rounds uint32) ([]byte){
    var k [4]uint32
    var i uint32
    end := make([]byte, 8)
    v0 := binary.LittleEndian.Uint32(block[:4])
    v1 := binary.LittleEndian.Uint32(block[4:])

    k[0] = binary.LittleEndian.Uint32(key[:4])
    k[1] = binary.LittleEndian.Uint32(key[4:8])
    k[2] = binary.LittleEndian.Uint32(key[8:12])
    k[3] = binary.LittleEndian.Uint32(key[12:])

    delta := binary.LittleEndian.Uint32([]byte{0xb9, 0x79, 0x37, 0x9e})
    mask := binary.LittleEndian.Uint32([]byte{0xff, 0xff, 0xff, 0xff})

    sum := (delta * rounds) & mask

    for i=0; i<rounds; i++ {
        v1 = (v1 - (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
            sum = (sum - delta) & mask
            v0 = (v0 - (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
    }

    binary.LittleEndian.PutUint32(end[:4], v0)
    binary.LittleEndian.PutUint32(end[4:], v1)

    return end
}


text:
Q: Display flex and vertical align middle, without moving content side by side? Let's say I have this aligned item to the center, but I don't want the side by side stacking. I want the About us header to be left justified above the paragraph and not side by side. Is there a way to align this content to the center but, still use flex box as its means of adjusting?
So it should like like...
About Us
Paragraph.

and not like...
About us Paragraph

Can flex box do this without moving the content beside one another? I know that's kind of the purpose of flex box.

.list {
  float:left;
  height: 250px;
  background-color: blue;
  width: 50%;
  margin: 15px;
}

.about {
  display: flex;
  align-items: center;
  height: 250px;
]

About Us text

Some text here

A: Change the direction to column:

.list {
  float:left;
  height: 250px;
  background-color: blue;
  width: 50%;
  margin: 15px;
}

.about {
  display: flex;
  flex-direction:column;
  justify-content: center;
  height: 250px;
]

About Us text

Some text here


text:
Q: How to get URL of web-service method in android? I have to write XML to my SD card for that I want to get input-Stream but to establish this how can I get URL when I call any method from android?
For instance I want to download all login details containing 10,000 records when I call it from android that method is called but how to get URL so that I can establish connection and get Input Stream to write to file...Please help me on this below is my code
public void DownloadFiles(){

    try {
        URL url = new URL("http://192.168.0.10/INIFARM/fieldbook/webservice1.asmx?wsdl");
        URLConnection conexion = url.openConnection();
        conexion.connect();
        int lenghtOfFile = conexion.getContentLength();
        InputStream is = url.openStream();
        File testDirectory = new File("/data/data/com.example.androidwebservice/");
        if (!testDirectory.exists()) {
            testDirectory.mkdir();
        }
        FileOutputStream fos = new FileOutputStream(testDirectory + "/response.xml");
        byte data[] = new byte[1024];
        int count = 0;
        long total = 0;
        int progress = 0;
        while ((count = is.read(data)) != -1) {
            total += count;
            int progress_temp = (int) total * 100 / lenghtOfFile;
            if (progress_temp % 10 == 0 && progress != progress_temp) {
                progress = progress_temp;
            }
            fos.write(data, 0, count);
        }
        is.close();
        fos.close();
        Log.v(TAG, "File is Downloaded Successfully");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

A: You mean the URL to call? Your web server admin needs to create a REST API for this and tell you the url so that your app can consume the data by querying this API.


text:
Q: Add authenticated user id by filter to java servlet I have an authentication filter that authorize REST call by JWT Token. I already implemented the authentication through JWT and the JWT validation by a Filter. How can I pass the user id coming from the JWT to the servlet in the filter process?

A: Usually this is done with an HttpServletRequestWrapper. It's an object that allows you to add or override methods on the standard HttpServletRequest.
Within your filter, wrap the original HttpServletRequest with your own RequestWrapper and then send your RequestWrapper to the servlet instead of the original HttpServletRequest.
For example, here's a simple RequestWrapper to pass an authenticated userId:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class AuthenticatedRequest extends HttpServletRequestWrapper {

    private int userId;

    public AuthenticatedRequest(HttpServletRequest req, int userId) {
        super(req);
        this.userId = userId;
    }

    public int getUserId() {
        return userId;
    }

}

Wrap the original request in your authentication filter before forwarding to your servlet chain:
// in filter class
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
    throws ServletException {

    int userId;

    // do something to get your authentication data (userId)
    // ...
    // wrap the original request with the "AuthenticatedRequest"
    AuthenticatedRequest authRequest = new AuthenticatedRequest(req, userId);

    // forward the AuthenticatedRequest to the servlet
    chain.doFilter(authRequest, res);

}

The Servlet can then use your new wrapped request methods to access the auth data:
// in servlet class
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
    // this request object is actually your own AuthenticatedRequest wrapper
    int userId = req.getUserId();

This and this cover some more implementation details.


text:
Q: Passing a parameter to npm start from mocha I have written test cases for my nodejs application using mocha and supertest. But my nodejs application is having an argument to start development environment and production environment as e.g, npm start -- development, npm start -- production. But from my mocha & supertest  application ,how can i start  the server for two different environments. I am giving as below
var server = supertest.agent("https://XXXXXX:3050")

so how can i cover test case fro both the environments

A: You should be able to just pass in additional arguments and use process.argv from the file invoked by the npm start command. This will return an array that you can then take the index of the argument, i.e. process.argv[indexOfArgument].
Or, in the case you've specified, you may want to use environment variables, i.e. $ NODE_ENV=development npm start, and then in your respective files something like:
if (process.env.NODE_ENV === 'development') {
    // do something
}


text:
Q: Calculate the arithmetic mean of a random variable Suppose that the results of a measurement (of let's say the number of citizens of a town, which is modeled by the random variable $X$) are given as follows:

Out of 4000 towns:
a) 500 have less than 10000 citizens;
b) 1500 have between 10000 and 100000 citizens;
c) 1500 have between 100000 and 1000000 citizens;
d) 500 have more than 1000000 citizens

My question is: how would I be able to calculate the average number of citizens per town (i.e. $\bar X$)?

A: The usual way to estimate the mean is to take the midpoint of each class as the representative value for each class (however inaccurate the estimate is then likely to be) simply because you have no more accurate information.
So we would take $5000$ as the value for the first class, $55000$ for the second class, and so on, and work out an estimate from there, i.e.  $$\bar{X}\simeq\frac{500\times5000+1500\times55000+...}{4000}$$


text:
Q: Force execution of CMake install directive I have a CMakeLists.txt where I copy files in a specific order but the execution order seems random:
#First Installation
   install(DIRECTORY ${SIT_AW_FIRST_WORKSPACE_DIR}/ DESTINATION ${WS_DESTINATION_DIR})

#Second Installation that should overwrite a subset of files
   install(DIRECTORY ${SIT_AW_SECOND_WORKSPACE_DIR}/ DESTINATION ${WS_DESTINATION_DIR})

Output :

-- Installing: /opt/FOO/share/baz/xml/Login.xml

-- Up-to-date: /opt/FOO/share/baz/xml/Login.xml

The second file will not overwrite the first because they have the same timestamp and the same name, but they have different size. Is there a way to force the copy?

A: I think you may have better success by using the PATTERN and EXCLUDE options instead of trying to overwrite one file with another.  You could try something like this:
#First Installation
install(DIRECTORY ${SIT_AW_FIRST_WORKSPACE_DIR}/ DESTINATION ${WS_DESTINATION_DIR}
        PATTERN "Login.xml" EXCLUDE)

#Second Installation that should overwrite a subset of files
install(DIRECTORY ${SIT_AW_SECOND_WORKSPACE_DIR}/ DESTINATION ${WS_DESTINATION_DIR})

You can read the CMake docs here with the specifics here:  https://cmake.org/cmake/help/v3.18/command/install.html#installing-directories


text:
Q: Cast char* to std::vector Is there a fast (CPU) way to cast a char array into a std::vector<char>?
My function looks like this:
void someFunction(char* data, int size)
{
    // Now here I need to make the std::vector<char>
    // using the data and size.
}

A: The general rule with STL containers is that they make copies of their contents. With C++11, there are special ways of moving elements into a container (for example, the emplace_back() member function of std::vector), but in your example, the elements are char objects, so you are still going to copy each of the size char objects.
Think of a std::vector as a wrapper of a pointer to an array together with the length of the array. The closest equivalent of "casting a char * to a std::vector<char>" is to swap out the vector's pointer and length with a given pointer and length however the length is specified (two possibilities are a pointer to one past the end element or a size_t value). There is no standard member function of std::vector that you can use to swap its internal data with a given pointer and length.
This is for good reason, though. std::vector implements ownership semantics for every element that it contains. Its underlying array is allocated with some allocator (the second template parameter), which is std::allocator by default. If you were allowed to swap out the internal members, then you would need to ensure that the same set of heap allocation routines were used. Also, your STL implementation would need to fix the method of storing "length" of the vector rather than leaving this detail unspecified. In the world of OOP, specifying more details than necessary is generally frowned upon because it can lead to higher coupling.
But, assume that such a member function exists for your STL implementation. In your example, you simply do not know how data was allocated, so you could inadvertently give a std::vector a pointer to heap memory that was not allocated with the expected allocator. For example, data could have been allocated with malloc whereas the vector could be freeing the memory with delete. Using mismatched allocation and deallocation routines leads to Undefined Behavior. You might require that someFunction() only accept data allocated with a particular allocation routine, but this is specifying more details than necessary again.
Hopefully I have made my case that a std::vector member function that swaps out the internal data members is not a good idea. If you really need a std::vector<char> from data and size, you should construct one with:
std::vector<char> vec(data, data + size);

A: You can't "cast" anything here, but you can easily construct a vector from the C string:
std::vector<char> v(data, data + size);

This will create a copy though.


text:
Q: Returning value from eventListener callback My program contains 2 functions, one to fetch a random joke from https://api.chucknorris.io/ and the other to display the joke on a webpage.
I think the problem lies in returning "joke.value" from the anon function in the event listener. I can return a value without using the event listener but I want to know how to achieve it using it if possible.
    <script>
    // function fetches joke onclick
    const generateJoke = () => {

        let button = document.querySelector("button");

        button.addEventListener("click", async () => {
            try{
                const response = await fetch("https://api.chucknorris.io/jokes/random");
                const joke = await response.json();
                return joke.value;
            }
            catch (error){
                console.error(error);
            }
        })
    // call print function to display joke content to the page

       printJoke(joke.value);
    }

    const printJoke = async (joke) => {

        let jokeList = document.getElementById("jokeDisplay");
        let jokeItem = document.createElement("p");

        jokeItem.innerHTML = joke;

        jokeList.appendChild(jokeItem);
    }

    </script>

When my code runs nothing happens when I click the button.

A: You don't need the generateJoke function. Also if you put printJoke(joke.value) inside the try your code will work.
let button = document.querySelector(".button-item");
        button.style.color ='red';
        button.addEventListener("click", async () => {
            try{
                const response = await fetch("https://api.chucknorris.io/jokes/random");
                const joke = await response.json();
                console.log(joke);
                printJoke(joke.value);
            }
            catch (error){
                console.error(error);
            }
        })


text:
Q: Quantum computing Grover's Algorithm Question:-
How much does exploiting quantum computing actually speed up computing? (We know that it hassome effect, because of Grover's algorithm, but how much? Does BQP=P?)
What I know
I understand Grover's Algorithm but solving this question seems to be a tough.
Source of Grover's Algorithm:-
https://en.m.wikipedia.org/wiki/Grover%27s_algorithm
Is there any way to solve this?

A: Well, using a classical naive search algorithm where you look at one entry after the other in a register, it would take on average N/2 calls before you find the result you are looking for.  Grover's algorithm would, assuming you have a register of all entries in a superposition state already prepared, only take square root of N calls on average.  For large registers, this is a huge gain.
What the story doesn't tell is that the preparation of the register is costly.  Everytime you call Grover's algorithm, you "consume" the entire register.  Therefore, Grover's algorithm's real cost would be square root of N * (cost of preparation of the register).  Sadly, the preparation of the quantum register (superposition of state of all entries in the register) scales with N.  Therefore, Grover's algorithm might not provide an actual gain to the classical search algorithm!
It remains to be seen if there are efficient ways to prepare the quantum register.  If one could find a O(sqrt(N)) way to prepare it, it would, at the very least, be as efficient as the classical search algorithm.

A: The observations by @Exeko on the computational cost of Grover's algorithm based Search Operations is quite valid and important concern when it is implemented out of the box. However, the cost of preparation and cost of information retrieval from the quantum register can be minimised by introducing a quantum bloom filter with verifiable random functions. Quantum Bloom Filter will help us to eliminate false positives in the register. Hence we don't need to consume the entire register every time. We have implemented Grover's algorithm in IBM Q last year with an additional Quantum Bloom Filter with a full adder circuit. This could help us to achieve quadratic speed-up in the end to end search performance.