text:
Q: Angular: routing inside an ng-zorro modal I have an Angular project where I created some components ready for reuse, and they will be created with an NG-ZORRO modal using NzModalService.create(). For example,
// welcome.component.ts
export class WelcomeComponent {
  constructor(private modal: NzModalService) {}

  foo() {
    this.modal.create({
      nzTitle: 'This is a modal',
      nzContent: SharedComponent
    });
  }
}

where WelcomeComponent is one of my major pages and SharedComponent is used as content of the modal created. Each component has its own module as well as a routing module.
Now I want to make some steps guide in a modal like above, and use routing to navigate between steps. And for that, I wrote my code like this:
step-guide.component.html

    Step 1

    Step 2

  <router-outlet name='stepGuide'></router-outlet>

step-guide-routing.module.ts
// imports omitted...

const routes: Routes = [
  { path: 'step1', loadChildren: () => import('../step1/step1.module').then(m => m.Step1Module) },
  { path: 'step2', outlet: 'stepGuide', loadChildren: () => import('../step2/step2.module').then(m => m.Step2Module) }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class StepGuideRoutingModule {}

I tried different ways to make it work, but never succeeded. For the code combination above, when I click Step 1 the modal just disappears and the main window is guided to an empty page. When I click Step 2 nothing happens and the console outputs no error at all. Removing the name from <router-outlet> yields the same result.
I also tried to wrap my route paths with a parent (such as {path: 'welcome', children: ...}) because the modal can be created by clicking a button in a component whose path in app-routing.module is /welcome. And this would cause error like welcome/step1 not matching any route.
The actual problem is, the modal is not hard-coded in HTML and can be created in different components, so I can't bind it to a specific path (which doesn't work, either.) But I hope my routing can work inside the modal wherever it is created. What should I do?
Any ideas would be appreciated.


text:
Q: How to divide map into square grid using ArcGIS Desktop? I want to divide a map in square grid using ArcGIS Desktop.
Is it possible?

A: Create a fishnet using the fishnet tool, then do an intersect procedure. The resulting data set will be a combination of your original data set and the fishnet. You could alternatively use ready-made square grids like the Quarter Degree Grid Cell system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio can't install Android SDK (API level 19 and 21) (missing extra-android-support) After trying to install Android SDK (API level 19 and 21) for Visual Studio via it's updater, I always see the error: screenshot
I reinstalled Visual Studio, JDK and even Windows, but nothing changed.
Than I checked if this "extra-android-support" package exist, and I found that there'are no more that package in Android repository.
You can check it by yourself, if you go to Android SDK folder\tools
C:\Program Files (x86)\Android\android-sdk\tools

And then run next command in cmd
android.bat update sdk -u -a –-filter extra-android-support

Looks like there's no package with this name anymore: screenshot.
But Visual Studio is still trying to install it. Is there anyways how can I use Android SDK for Visual Studio?

A:
But Visual Studio is still trying to install it. Is there anyways how can I use Android SDK for Visual Studio?

You can ignore this error and go ahead use the android SDK for Visual Studio without problem.
If you want to install the latest android SDK Platform or other android tools, you can open the android sdk manager through VS: Tools->Android->Android SDK Manager
Or you can open the android sdk manager directly under C:\Program Files (x86)\Android\android-sdk\SDK Manager.exe(please open it with Administrator).


text:
Q: c pointer to pointer how to iterate through it struct hashLink

{
   KeyType key; /*the key is what you use to look up a hashLink*/
   ValueType value; /*the value stored with the hashLink, an int in our case*/
   struct hashLink *next; /*notice how these are like linked list nodes*/
};

struct hashMap
{
    hashLink ** table; /*array of pointers to hashLinks*/
    int tableSize; /*number of buckets in the table*/
    int count; /*number of hashLinks in the table*/
};

I'm trying to iterate through a hashMap with hashLinks. Is this the correct approach? The hashLinks are in an array and may have more hashLinks linked to them in a linked list. I just do not understand how to work pointers to pointers. tableSize is the amount of elements in the array. At each array position there may be more hashLinks linked to the first there.
for(int i = 0; i < ht->tableSize; i ++)
{
    hashLink *current;

    if (ht->table[i] != 0)
    {
        current = ht->table[i];

        while(current->next !=0)
        {
            hashLink *next;
            next = current->next;
            free(current->key);
            free(current);
            current = next;
        }

        free(current->key);
        free(current);
    }
    else
    {
        continue;
    }

        counter++;
    }
}

A: Yes, this does work, but you end up with a hashtable that contains dangling pointers. Also, as Joachim noted, it works as long as you assume that the values contained in the structs are sane, i.e., tableSize contains the number of entries in table and the hashLinks have been correctly allocated.
Your iteration through the links is fine and correclty frees all the hashLinks in the table. However, consider the state of ht after the iteration. You do not change the values of ht->table[i] at all, so after you leave the loop, the pointers will still be stored in the table. If you want to reuse the table, you should set the pointers to 0 when you do not need them anymore, i.e., add ht->table[i] = 0 somewhere after current = ht->table[i];.
If this method is part of the "destructor" of the table (i.e., some method like hashmap_delete(...)), then you can simply free the hashmap after you finished your iteration, i.e., add free(ht); after the for-loop.

A: Simplified:
for(int i=0; i < ht->tableSize; i++)
{
    hashLink *current;

    while (ht->table[i] != NULL) {
        current = ht->table[i];
        ht->table[i] = current->next;

        free(current->key);
        free(current);
    }
}

It can be further simplified to only one loop, but that is left as an exercise to the reader ...

Note: as a side effect, this will set all the pointers in ht->table[] to NULL; which is good, since after freeing the linked lists they have become stale anyway.


text:
Q: How to host a Java EE website on GlassFish? I have already deployed my web application on GlassFish at http://localhost:8080/Elibrary/.
So how can I configure my server to make "Elibrary" accessible from the Internet?
I know that in ASP we can use IIS to alias the from domain.
Could someone please let me know or point me to some documentation?

A: *

*If you are hosting in your network, then you have to get IP of the machine which is running your app i.e. is your local ip inside ur network. To get your ip, run ifconfig on mac/unix/linux and ipconfig on windows.

*Then go to your router settings. Generally every router has specific ip to access settings from browser like belkin has 'http://192.168.2.1'.

*In your router settings you have to look for 'virtual servers', 'port forwarding' etc. The actual concept is port forwarding but different routers say it differently in the settings. These settings should be in firewall or security sections.

*Once you found the settings, there you will have to tell the inbound port range and map it to the local ip (which we have above) and the outbound port range. It is saying that when ever a request comes on the router on the inbound port range then forward that request to local ip and port range. In your case, the port range will be  to  (for both inbound and outbound). Note that some routers dont have range for ports instead only have one port per entry, so you just have to put .
NOTE: To get the IP for settings of your router, try this site.
I hope this is what you looking for.

A: Nginx or Apache will work will in that scenario, processing virtual hosts and forwarding to an external application. Example for nginx.
Put this in place of the server section in an existing config file, unless using Debian/Ubuntu or other system where the server configurations are split into their own files.
server {
    listen ip:80;
    server_name virtualhostname.tld;

    location "/" {
        proxy_pass http://localhost:8080/;
    };
};

Now http://virtualhostname.tld/Elibrary will work to access your application.
You can add rewiriting to get rid of Elibrary, and you find Apache equivalents of this online.


text:
Q: How can i change the value of a text field in sencha touch? I am scanning the barcode using barcode scanner plugins in phonegap. After getting the value, i want to show this in text field. Below is my text field code:
{
     xtype : 'textfield',
      id : 'barcodetextfield',
     width : 300,
     margin : '0 0 0 10',
     labelWidth : '40%',
     label : 'Enter Barcode'
}

And in the controller, i am trying to set the barcode value in the text field.
window.plugins.barcodeScanner.scan(function(result) {
    this.getBarcodebox.setValue(""+result.text);
 }, function(error) {
     alert("Scanning failed: " + error);
 });

And i put the ref in the controller like below:
barcodebox : '#barcodetextfield',

Here is my whole controller code:::
Ext.define('MyApp.controller.MyController', {
extend : 'Ext.app.Controller',
config : {
    refs : {
        TitlePanel : 'login',
        dashboardpanel : 'dashboard',
        ConsumerSignup : 'consumersignup',
        AddtoWishlog : 'addwishlog',
        wishlogsummary : 'wishlogsummarylist',
        FeedbackSummary : 'feedbacksummarylist',
        ConsumerSignin : 'Consumersignin',
        barcodebox : '#barcodetextfield',
        labelid : 'title'
    },
    views : [ 'TitlePanel', 'dashboardpanel', 'ConsumerSignup',
            'AddtoWishlog', 'wishlogsummary', 'FeedbackSummary',
            'ConsumerSignin' ],

    control : {
        "#LoginBtn" : {
            tap : 'onLoginButtonTap'
        },

        "#wishloghomebutton" : {
            tap : 'onWishlogHomeButtonTap'
        },

        "#feedbacksummaryhomebutton" : {
            tap : 'onFeedbackHomeButtonTap'
        },

        "#wishlogbtn" : {
            tap : 'onWishlogButtonTap'
        },

        "#Feedbackbtn" : {
            tap : 'onFeedbackButtonTap'
        },

        "#signup" : {
            tap : 'onSignupButtonTap'
        },

        "#capturebtn" : {
            tap : 'onCaptureButtonTap'
        },

        "#consumersignuphomebutton" : {
            tap : 'onConsumerSignupHomeButtonTap'
        },

        "#selectphoto" : {
            tap : 'onSelectPhotoButtonTap'
        },

        "#scanbutton" : {
            tap : 'onScanButtonTap'
        }

    }
},

slideLeftTransition : {
    type : 'slide',
    direction : 'left'
},
slideRightTransition : {
    type : 'slide',
    direction : 'right'
},

onLoginButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getDashboardpanel(),
            this.slideLeftTransition);
    // this.getLabelid.setHtml('Dashboard');
},

onWishlogButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getWishlogsummary(),
            this.slideLeftTransition);
},

onFeedbackButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getFeedbackSummary(),
            this.slideLeftTransition);
},

onSignupButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getConsumerSignup(),
            this.slideLeftTransition);
},

onWishlogHomeButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getDashboardpanel(),
            this.slideRightTransition);
},

onFeedbackHomeButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getDashboardpanel(),
            this.slideRightTransition);
},

onConsumerSignupHomeButtonTap : function(button, e, options) {

    Ext.Viewport.setActiveItem(this.getDashboardpanel(),
            this.slideRightTransition);
},

onCaptureButtonTap : function(button, e, options) {
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality : 100,
        destinationType : Camera.DestinationType.FILE_URI
    });

    function onPhotoURISuccess(imageURI) {
        // console.log(imageURI);
        var largeImage = document.getElementById('capturedimage');
        largeImage.style.display = 'block';
        largeImage.src = imageURI;
    }

    function getPhoto(source) {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(onPhotoURISuccess, onFail, {
            quality : 100,
            destinationType : destinationType.FILE_URI,
            sourceType : source
        });
    }
    function onFail(message) {
        alert('It is failed: ' + message);
    }

},

onSelectPhotoButtonTap : function(button, e, options) {
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality : 50,
        destinationType : navigator.camera.DestinationType.FILE_URI,
        sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
    });

    function onPhotoURISuccess(imageURI) {
        // console.log(imageURI);
        var largeImage = document.getElementById('capturedimage');
        largeImage.style.display = 'block';
        largeImage.src = imageURI;
    }

    function getPhoto(source) {
        // Retrieve image file location from specified source
        navigator.camera.getPicture(onPhotoURISuccess, onFail, {
            quality : 100,
            destinationType : destinationType.FILE_URI,
            sourceType : source
        });
    }
    function onFail(message) {
        alert('It is failed: ' + message);
    }
},

onScanButtonTap : function(button, e, options) {
    window.plugins.barcodeScanner.scan(function(result) {
        this.getBarcodebox().setValue(""+result.text);

//          alert("We got a barcode\n" +
//          "Result: " + result.text);
        }, function(error) {
            alert("Scanning failed: " + error);
        });
    }
   });
When i am showing the value in dialog box, it is showing properly. But not able to set in textbox. How i can set the barcode?? Please help.

A: Should:
    this.getBarcodebox.setValue(""+result.text);

Not be a method call?
    this.getBarcodebox().setValue(""+result.text);

This is of course, assuming you have added barcodebox as a ref in your controller:
    refs: {
        barcodebox: '#barcodtext'
    }

Note the typo in the id: #barcodtext (missing 'e') and make sure that this is equal to the value specified with the ref selector.
-- Edit
It look likes that this is out of scope in your callback and thus does not refer to your controller. You could try something as following:
window.plugins.barcodeScanner.scan(function(result) {
    var controller = Ext.app.Application.getController('MyController');
    controller.getBarcodebox.setValue(""+result.text);
}, function(error) {
    alert("Scanning failed: " + error);
});

A: Instead of using barcodebox : '#barcodetextfield', in refs try with getCmp()
var bc = Ext.getCmp('barcodetextfield');

after that bc.setvalue(''+result.text);
I hope this helps..


text:
Q: Is it possible to have a VBA script that will take URLs from hyperlinked images? I have a workbook full of text and image hyperlinks, I've got some code that will deal with the text URLs nicely, however, the image links are presenting a problem as they don't sit in the flow of the page to be able to pull those links. I don't know how VBA treats these as objects, is it possible to target or cycle through them to pull out their URLs?

A: Try this way (I used your code and put some error handling instructions):
Sub test()
    Dim WriteRow As Integer
    WriteRow = 1
    Dim imglink As Shape

'error handling
On Error Resume Next
For Each imglink In Sheets(1).Shapes
    'if any shape doesn't have hyperling we would skip it
    ActiveWorkbook.Sheets(3).Cells(WriteRow, 1).Value = imglink.Hyperlink.Address
    If Err.Number = 0 Then
        WriteRow = WriteRow + 1
    Else
        Err.Clear
    End If
Next
End Sub

I expect that you have an error each time you check Hyperlink for shape which doesn't have one.


text:
Q: Route 53 domain email account account creation without AWS workspace I purchased a domain on route 53 and stood up a LAMP instance on AWS. I need my php running on my instance which I have associated to example.com to send emails.  I do not need to receive email, I just need outgoing email to go out through php from donotreply@example.com, but the php mail() doesn't won't with an AWS hosting configuration. I know I can use AWS workspace to create an email account like "forgotPassword@exapmle.com" but that has a monthly fee.
My question is whether there is a way to send an email from my AWS instance (Simple free tier linux).  For example can I create unix user named "dan" on linux, give it a password, and then dan@example.com will somehow get configured in SES to send emails?  I suspect not since the instance doesn't know its example.com...?
Other hosting environments I have used had this all pre-configured so I would really appreciate any guidance, even if it is just a link to the right documentation.  Success is having my php on AWS send an email, most likely through the SDK/API that is included as part of SES, but somehow getting mail() to just work would be even better!


text:
Q: Segmentation Fault in Socket Programming I am trying to write a simple server-client communication program on C. But I keep getting the error on the server side as soon as a client tries to connect to the server :
Segmentation Fault
The Server side code is :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>

void error(char *);

int main(int argc, char *argv[])
{
int sockfd, newsockfd, n, serv_size, cli_size, port_no, bindfd, readfd, writefd, listenfd;
char sbuffer[256];
char *p;
p = &sbuffer[0];

struct sockaddr_in serv_addr, cli_addr;

if (argc < 2)
    error("No port no. Specified!\n");

//creating sever side socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
    error("Server side listening Socket could not be created!\n");

bzero((char *)&serv_addr, sizeof(serv_addr));
port_no = atoi(argv[1]);
serv_addr.sin_family =  AF_INET;
serv_addr.sin_port = htons(port_no);
serv_addr.sin_addr.s_addr = INADDR_ANY;

//binding socket
bindfd = bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if  (bindfd == -1)
    error("Failed to bind server side socket!\n");

//listening for incoming connections
listenfd = listen(sockfd, 5);
if (listenfd == -1)
    error("Failed to lisen to incoming connections!\n");

serv_size = sizeof(serv_addr);
cli_size = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &serv_size);
if (newsockfd == -1)
    error("Failed to accept connections from client!\n");

printf("Server received connections from %s  \n", (char *)inet_ntoa(cli_addr.sin_addr));
while(1)
{
    bzero(p, sizeof(sbuffer));
    readfd = read(newsockfd, p, sizeof(sbuffer));
    if (readfd == -1)
        error("Sorry. Unable to read message from client!\n");
    printf("Message Received: ");
    puts(sbuffer);

    bzero(p,  sizeof(sbuffer));
    printf("\nEnter Your Message for client: ");
    gets(sbuffer);
    writefd = write(newsockfd, p, sizeof(sbuffer));
    if (writefd == -1)
        error("Sorry. Message Could not be sent to client.\n");
    printf("Congratulations! Message has been sent to client.\n");
}

return 0;
}
void error(char *msg)
{
perror(msg);
exit(1);
}

The Client side code is :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>

void error(char *);
int main(int argc, char *argv[])
{
int sockfd, newsockfd, port_no, n, connectfd, readfd, writefd;
char cbuffer[256];
char *ptr = &cbuffer[0];

struct sockaddr_in serv_addr;
struct hostent *he;

if (argc != 3)
    error("Incomplete arguments!\n");

port_no = atoi(argv[2]);
he = gethostbyname(argv[1]);
if (he == NULL)
    error("No Such Host!\n");

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
    error("Sorry. Socket could not be created!\n");

bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port_no);
serv_addr.sin_addr = *((struct in_addr *)he->h_addr);

connectfd = connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (connectfd == -1)
    error("Sorry. Could not connect to server.\n");

while(1)
{
    bzero(ptr, sizeof(cbuffer));
    printf("\nEnter message for Server: \n");
    gets(cbuffer);
    writefd = write(sockfd, ptr, sizeof(cbuffer));
    if (writefd == -1)
        error("Sorry. Could not send message to Server.");

    printf("Congratulations! Server Successfully Received your message.\n");

    bzero(ptr, sizeof(cbuffer));
    readfd = read(sockfd, ptr, sizeof(cbuffer));
    if (readfd == -1)
        error("Sorry. Message from server could not be read.\n");

    printf("Message Received: ");
    puts(cbuffer);
}
return 0;
}
void error(char *msg)
{
perror(msg);
exit(1);
}

This is my compile time warning while compiling serv.c:
cc -o s serv.c
serv.c: In function 'main':
serv.c:47:52: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

P.S. : I was using Ubuntu 12.04 where I actually wrote these programs and successfully executed the programs. But i recently migrated to Linux Mint 13 Cinnamon. I recompiled the programs. Probably they successfully executed on Mint too. But now it seems to have caught this bug somehow.

A: If you're running on a 64 bit system, your call;
printf("Server received connections from %s  \n",
    (char *)inet_ntoa(cli_addr.sin_addr));

...may break. Since you've not included <arpa/inet.h>, you don't have a definition for inet_ntoa. That will make the compiler assume that it returns an int. Since int is not necessarily 64 bit (actually most machines it seems not to be), it's not long enough to store the char pointer that's returned, so your printf crashes with an invalid string. This happens on (for example) 64 bit MacOS X.
Just plain putting #include <arpa/inet.h> among the includes in the server would fix that problem.
You should also not ignore the difference between int and socklen_t and fix the issue of mixing up cli_size and serv_size, read the already existing comments and answers for more on that.

A: I'd say the issue is the missing prototype for inet_ntoa().
This let's the compiler assume it returns int.
And this make the following line crash the app:
printf("Server received connections from %s  \n", (char *)inet_ntoa(cli_addr.sin_addr));

Having included <arpa/inet.h> the follwing code whould have compiled without warning even with -Wall.
printf("Server received connections from %s  \n", inet_ntoa(cli_addr.sin_addr));


text:
Q: ANTLR Is takes one line of tokens as a single token I'm new to ANTLR and I tried to write a simple parser. I used a valid rules, but when I run the TestRig (grun) with -gui argument on 'var' rule and entered this:
var myVar = 13

the debugger tolds me that: line 1:0 mismatched input 'var myVar = 13' expecting 'var'
I can't get what is wrong with it..
Here's the code:
grammar Leaf;

WS:     (' '|'\t'|'\n'|'\r')+ -> skip;

NUM:    ('0'..'9') ('0'..'9'|'.')*;
CHAR:   ('a'..'z'|'A'..'Z');

ID:     CHAR (CHAR|NUM)*;

BOOL:   ('true'|'false');

STRING: ~('\r'|'\n'|'"')+;

type:   'int'|'byte'|'float'|'double'|'decimal'|'char'|'bool'|'tuple'|'string'|'type';
value:  NUM|BOOL|('[' (value ',')+ ']')|('\'' CHAR '\'')|('"' STRING '"')|('(' (type ',')+ ')')|type;

var:    'var' ID('[]')? (':' type)? '=' (type|value)?;

Thanks for feedback!

A: Lexer rules in ANTLR are greedy. Because of that, the rule STRING:
STRING: ~('\r'|'\n'|'"')+;

consumes your entire input.
What you need to do is remove the double quotes from your value parser rule and include them in your lexer rule:
grammar Leaf;

var
 : 'var' ID ('[' ']')? (':' type)? '=' (type | value)?
 ;

value
 : NUM
 | BOOL
 | '[' value (',' value)* ']'
 | CHAR
 | STRING
 | '(' type (',' type)* ')'
 | type
 ;

type
 : 'int'
 | 'byte'
 | 'float'
 | 'double'
 | 'decimal'
 | 'char'
 | 'bool'
 | 'tuple'
 | 'string'
 | 'type'
 ;

WS     : (' '|'\t'|'\n'|'\r')+ -> skip;

BOOL   : ('true' | 'false');

NUM    : DIGIT+ ('.' DIGIT*)?;

STRING : '"' ~('\r'|'\n'|'"')* '"';

CHAR   : '\'' LETTER '\'';

ID     : LETTER (LETTER | DIGIT)*;

fragment LETTER : [a-zA-Z];
fragment DIGIT  : [0-9];


text:
Q: how to call received data in Serial Port C# i'm newbie in C# serial port...
i have a virtual serial port driver and try this code...
 private string strPortData = null;

    private void okButton_Click(object sender, EventArgs e)
    {
                if (!serialPort1.IsOpen)
                {
                    serialPort1.Open();
                }

                string strPortData= "CMD1";

                serialPort1.WriteLine(strPortData);

    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        textBox1.Text = serialPort1.ReadLine();
    }

but do not serialPort1_DataReceived ever call.
What should i do for call DataReceived?

A: Try creating a new console application with code similar to the following
void Main()
{
    using (SerialPort serialPort1 = new SerialPort("COM1"))
    using (SerialPort serialPort2 = new SerialPort("COM2"))
    {
        serialPort1.DataReceived += (sender, args) => {
            Console.WriteLine("COM1 Received: " + serialPort1.ReadLine());
        };

        serialPort2.DataReceived += (sender, args) => {
            Console.WriteLine("COM2 Received: " + serialPort2.ReadLine());
        };

        serialPort1.Open();
        serialPort2.Open();

        serialPort1.WriteLine("Hello, COM2!");

        Thread.Sleep(200);
    }
}

The above code opens both serial ports, sets up the data received events, and sends data through it. If you run that code you should see "COM2 Received: Hello, COM2!" output.


text:
Q: How to unpack binary data in MatLab the Python way Python has a way to read blocks of binary data and then unpack them from their original encoding into a more accessible form. For example, in some Python code I am using, I use the following code to accomplish this:
    with open(filename, "rb") as binary_file:
        # Read many records at once
        data = binary_file.read(number_of_records*record_size)

    fmt = "8B Q Q 2L 2L 2L 4H 4H 3H2B"
    self.data_array = np.asarray(list(struct.iter_unpack("< " + fmt, data)))

I'd like to know how to do this in Matlab in the same efficient way, without having to read each variable individually.
Is there something in Matlab to do this?

A: One way to do this is to read the data using fread and then convert using typecast.  I'm not familiar with the format you used, but say you have a collection of integers and floats.  You can read them as one large collection of bytes and then covert.
fid = fopen('file.bin', 'rb');
data = fread(fid, 32, '*uint8');
ints = typecast(data(1:8), 'int32');
floats = typecast(data(9:end), 'single');


text:
Q: Swing AWTEventListener listening to 3rd party application Im trying to create tool, which will close popup window in 3rd party application (written in java).
Toolkit.getDefaultToolkit().addAWTEventListener(...);

But with this approach I can only listen to events from windows created in my own application. Is there any way to receive events from other apps? Maybe I should start them from my app?

A: You cannot listen directly to UI elements in other processes... which honestly you should be happy about because it could would open up many software vulnerabilities.
There are two ways I've used to achieve cross application communication. Both require specific (as opposed to built-in) design to work.

*

*Starting the 2nd application in Java via ProcessBuilder (or the old implementations for doing such in System). You can read and write to process in/out/error streams. Of course, the process has got to be set up to also communicate its streams

*Listen on a ServerSocket in one of the applications and connect from the other. When you do this, you need to devise a common port as well as a common communication protocol.

I hope this helps


text:
Q: Setup own DynDNS in VirtualHost I have a server environment within a network that sits behind a dynamic IP.
I as well have a virtual host online where I run Apache 2.4 with a couple of VirtualHosts.
Is it possible to create a VirtualHost (essentially a subdomain) linking to the dynamic IP mentioned above? I guess I have to change the A Record of the DNS settings, right? Is that possible at all?

A: Yes, it is possible to set ServerName in Apache httpd to a DNS name, which A record will change.
If the public IP is configured directly on the server's interface (ie. not on a router in front of it), just remember to bind httpd to the catch-all address (0.0.0.0), not to the domain name, or, even worse, current IP - this will require server restarts on IP change in the former case, or even configuration change in the latter.
But, given how cheap are some VPS plans today (and there're even some free ones available), isn't it more reasonable to use a dedicated service with a static IP?


text:
Q: Space between GroundOverlays using Google Map Android API v2 I have created an off-line map with Google Map Android API v2 (i.e. osmdroid is not an option) using Openstreetmap tiles as GroundOverlays with one minor problem: at zoom level greater than 14 some of the tiles have a 1-3 pixel space between them. Other tiles line up perfectly. It seems random which ones do and do not have spaces between them.
I download the tiles using JTileDownloader, then I fetch the required tiles (using the technique described here) that I downloaded and placed in the device filesystem, then I get the tiles' LatLngBounds, and then I lay them down in a loop as:
groundOverlay = mMap.addGroundOverlay(new GroundOverlayOptions()
                    .image(BitmapDescriptorFactory.fromBitmap(mBitmapImage))
                    .positionFromBounds(tileBoundsArray[i])
                    .transparency((float)0));

I have verified that the lat and long of the tiles should line up. I also verified that all the bitmaps are the same size. I have also tried this particular tileset using the UrlTileProvider and it works fine, so it's nothing wrong with the tiles.  I have been struggling with this for days and would appreciate any suggestions. I have found absolutely nothing anywhere else addressing this issue. Thanks!

A: I finally found the answer to this.  I had to specify the width of the map tile in meters at the tile's latitude (I used the center of the tile). Google maps uses a Mercator projection, which means that the width of the map depends upon the latitude.  You specifiy the width using GoundOverlay.setDimensions(width).  This page gives an explanation on how to calculate the width.


text:
Q: proof of the Cauchy integral formula
$ D=D_{r}(c), r > 0 .$ Show that if $f$ is continuous in $\overline{D}$ and holomorphic in $D$, then for all $z\in D$: $$f(z)=\frac{1}{2\pi i} \int_{\partial D}\frac{f(\zeta)}{\zeta - z} d\zeta$$

I don't understand this question because I don't see how it is different to the special case of the Cauchy Integral formula. I would be very glad if somebody could tell me what the difference is and how to show that it is true.

A: If I understand correctly, $D_r(c)$ is the open ball centered in $c$ with radius $r$? If this is the case, the difference between the two is that above your $c$ is fixed, and in the special case your $c$ "moves" with the ball.
Fix $c$ then; we want to show that for every $z\in D_r(c)$ we have that
$$f(z)=\frac{1}{2\pi i}\int_{\partial D_r(c)}\frac{f(\zeta)}{\zeta-z}d\zeta$$
(we assume that $f$ is holomorphic in the ball).
Well, if we choose $s>0$ such that $D_s(z)\subseteq D_r(c)$, then by the special case we have that
$$f(z)=\frac{1}{2\pi i}\int_{\partial D_s(z)}\frac{f(\zeta)}{\zeta-z}d\zeta,$$
and we see that $\partial D_s(z)$ is homologous to $D_r(c)$. We then have that
$$f(z)=\frac{1}{2\pi i}\int_{\partial D_s(z)}\frac{f(\zeta)}{\zeta-z}d\zeta=\frac{1}{2\pi i}\int_{\partial D_r(c)}\frac{f(\zeta)}{\zeta-z}d\zeta.$$
Does that answer your question? Is that what your question was?
The nice thing about the "general" Cauchy formula is that the curve that we're integrating over no longer depends on the point you want to evaluate.

A: I am not sure what the "usual Cauchy integral formula" is for you but I am assuming it is the following result:
Theorem If $f$ is holomorphic in an open set containing the closure of $D_{r}(c)=\{z\in\mathbb{C}:\left|z-c\right|<r\}$ for some $r>0$ and $c\in\mathbb{C}$, then $f(z)=\frac{1}{2\pi i}\int_{\left|\zeta-c\right|=r} \frac{f(\zeta)}{\zeta - z}d\zeta$ for all $z\in D_{r}(c)$.
Note that the hypothesis of the theorem is that $f$ is holomorphic in an open set containing the closure of $D_{r}(c)$ (in particular, there is a smoothness condition on the restriction of $f$ to the boundary of $D_{r}(c)$), whereas in the result stated in your question, we are only given continuity on the closure of $D_{r}(c)$.
In any case, the general result stated in your question is easy to prove. I will give a hint: fix $z\in D_{r}(c)$ and apply the usual Cauchy integral formula (i.e., the theorem stated above) to conclude that:
$f(z)=\int_{\left|\zeta-c\right|=\epsilon} \frac{f(\zeta)}{\zeta-z}d\zeta$
for all $\epsilon < r$ sufficiently close to $r$. You can now take the limit $\epsilon\to r$ in the above equality and apply the Lebesgue dominated convergence theorem to conclude the proof of the general result. (Please do not forget to verify that the hypothesis of the dominated convergence theorem is satisfied!)
I hope this helps!


text:
Q: Relationship between Stoke's law of sound attenuation and the inverse square law In attempting to find a reference for explaining sound propagation, I came across this article in Wikipedia:
Stokes law(sound attenuation)
What I learnt in high school is that sound is propagated by an inverse square law.
My question is, what (if any) is the relationship between Stoke's law and the inverse square law? Is the inverse square law simply an approximation/generalization of Stoke's law? Or do they in fact have nothing to do with each other?
Lastly, if my assumption that the inverse square law is an approximation of Stoke's law, can anyone point me to a reference?

A: As Chris and leftaroundabout said, these are really independent things.
The $1/r^2$ law comes from the fact that as the energy in the sound wave travels away from its source, it gets spread out over a larger and larger sphere. Since the total energy must remain the same (assuming no dissipation), the amount of energy in each unit of area on the sphere must decrease. The rate it must decrease is $1/r^2$. So this law is really a result of conservation of energy.
The other law says what happens if there is dissipation. Then as the energy travels through the medium (say, air), then some of the energy  in the sound will be lost to heat. The way it works is that after a sound wave has traveled a distance $l_d$, the amplitude of the wave decreases by a factor of $e$.
Putting these two together, we expect intensity $I$ as a function of distance to the source $r$ to have the form $I(r) = I_0 R_0^2 \frac{e^{-2r/l_d}}{r^2}.$ Now why didn't your teachers tell you about this. Well if you calculate $l_d$ according to the formula on wikipedia, you get about six miles. So four sounds that you ordinarilly hear, it is not an important effect.
Now as leftaroundabout said, the attenuation law was derived assuming a plane wave, but I'm fairly certain that you will get the functional form I said for the spherical wave. The decay length might be slightly different, but it will just be an $O(1)$ correction.

A: They do in fact have nothing to do with each other. Inverse-square is a simple conservation-of-energy argument for point sources, i.e. it basically assumes that no absorption takes place anywhere – which is a pretty good approximation for dry air, provided of course there are no solid obstacles anywhere.
Stokes' law is much more specific in that it starts with a plane wave, while inverse-square amounts to a spherical-wave model. Now, any wave looks locally like a plane wave if you zoom in close enough, but Stokes' law only makes sense if you look at an area much larger than the wavelength. Which you can do with a spherical wave, but you need to move out far away from the source, where $r^2$ becomes basically constant1.
For audio applications, Stokes' law is largely irrelevant, because a) you'll hardly get to a proper plane-wave scenario and b) the viscosity of air is so low that the predicted absorption is usually much smaller than any losses at solid boundaries, and to the inverse-square spreading. Where Stokes' law is important is at high frequencies in fluids with significant viscosity, e.g. in medical ultrasonic scans.
Inverse-square itself needs to be handled with care: in lots of applications, reflection plays a significant role, so the spreading is limited and the intensity drops slower than $1/r^2$, or there are solid obstacles between source and observer so the intensity is obviously lower.

1For the purpose of its effect on magnitude only. Of course, the variations in $r$ still act on the phase, where a large offset doesn't play any role.

A: For the fluctuation analisys of sound in ideal fluid over persistent density in 2 dimensions, we can use Green's Theorem. Let's say $k = dI\;ds$ where $I$ is sound intensity and $s$ is orthogonal path line to the vectorial gradient of the sound emission. In fact it may sound complicated but it is very simple, it is the simple representation that the variation of sound's amplitude follow the variation of the section that goes  perpendiculary through. With Green theorem, we can say that the area modulus of the closed loop section is the same as the path's lenght. And so, $dI = k / dA$ where $A$ is the area of the path's loop. We can transpose $dA$ to radial perspective so $dA = r\;dr\;d\theta$, where $r$ is radius and $\theta$ is the angle. Then
$$
A = \int_0^r\int_0^{2\pi} r\;dr\;d\theta=\pi r^2
$$
(do you recognise the formula for the area of a circle!). From there,
$$
I = \frac{k }{\pi r^2}
$$
At this point, $\pi$ can be merged in the constant $k$ so that $I = k / r^2$ where $k$ is a constant relative to some physics proprieties of the fluid medium and so on.
The same logic is applied when we want to get into 3D. The extention of Green theorem (I think this one is more known as Stokes theorem) says that the modulus of the volume of an closed area is the same as the modulus of the area itself. An other way of considering it : Stokes says "hey man, the area is simply the variation of the variation of the looping path orthogonal to the flow that goes  perpendiculary through!". Green hear that and says " dude this is the variation of the area I just found!" Then Stock says "Green stupid geinus I know that! In fact, overall we can say that the modulus of the volume is the same as the modulus of the area perpendicular to the gradient of the flow that goes through it" Finaly in 3D, $dI = k /dV$ were $V$ stands for volume. In spherical perspective,
$$
V= \int_0^r\int_0^{2\pi}\int_{-\pi/2}^{+\pi/2} p^2 \; \sin(\phi)\;dp\;d\theta\;d\phi=\frac{3k}{4\pi r^3}
$$
Same as before, $3/(4\pi)$ can be merged into the constant $k$ so that $I = k / r^3$ were $k>0$  relative to Fluid environnement and some phisical proprieties. But to use it for the measure of power, you must make your observations on a area instead of a single point as the 2D method.
Same calculus apply to any kind of radiation. (Ex: electromagnetic radiation)
To conclude, 2D method of $I= k / r^2$ follows the principe that the sound is spreaded though a circle. And 3D method spead it over a sphere so $I= k / r^3$


text:
Q: simplexml_load_file not a valid URI issue I am trying to read data from an xml file to import to data base.  I am running into an issue loading the file:

parser warning : xmlns: x-schema:#Schema1 not a valid URI

A: Problem is in XML file, not in your code.
You can also try to disable warnings by using
libxml_use_internal_errors(true);


text:
Q: Track root domain & Single Page Application in subfolder I am currently setting up Google Analytics for:

*

*http://example.com (public website advertising the product)

*https://example.com/app (the product, a single page application)

I am using two views to track them. The standard 'All website data' view to encompass the public website and all subfolders (including the single page application) and a separate view for the application itself which contains only application data. In the view for the application I use the filter 'Include only traffic to the subdirectories that begin with /app/' (case insensitive). And within the single page application I log page views like so:
ga('set', 'page', 'p=pageName');
ga('send', 'pageview');

However, I am seeing discrepancies in the 'All website data' view, where there are page loads clearly from within the application recorded as being from the root domain. There are entries for '/p=pageName' and '/app/p=pageName', in other words.
Why is this happening? Do I need to include /app/ in the ga('set') call? Is it related to my filters or that the app is 'https' while the root domain is 'http'? Any hints will be greatly appreciated.

A: For anyone who stumbles on this question: The answer was to prepend /app/ to the ga() calls, as proposed in my original question.
E.g.
ga('set', 'page', '/app/p=pageName');
ga('send', 'pageview');


text:
Q: Getting the RAW camera data on android? I want to work with the bit array of each incoming frame, basically tapping to the YUV format received from the camera sensor for each frame and do some processing on it.
I'm new to java/android and learning as I go so some of my questions are pretty basic but I couldn't find any answers that suites my needs.
Q1: How do I get a bit array of each frame received by the camera sensor? (how do I save the YUV byte stream for further use?)
Q2: How to set that for each new frame received a new data array will be received for processing?
Q3: Do I have to set a preview to do that or could I tap straight to a buffer holding the raw data from the open camera?
Q4: Will a preview slow down the process (of receiving new frames)?
Some further explanations if needed: The idea is to create one way communication with a flickering LED light and a smartphone, by pointing the phones camera to the LED, a real-time process will register the slight changes and decode them to the original sent data. to do so I plan to receive the YUV data for each frame, strip it to the Y part and decide for each frame if the light is on or off.

A: Yes, that's the Camera API. Android 21 and newer support camera2 API which can give you faster response, but this depends on device. I would recommend still to use the deprecated older API if your goal is maximum reach.
Usually, Android camera produces NV21 format, from which it is very easy to extract the 8bpp luminance.
Android requires live preview if you want to capture camera frames. There are quite a few workarounds to keep the preview hidden from the end user, but this is not supported, and any such trick may fail on the next device or on the next system upgrade. But no worry: live preview does not delay your processing speed at all, because it is all done in a separate hardware channel.
All in all, you can expect to receive 30 fps on average device when you use Camera.setPreviewCallbackWithBuffer() and do everything correctly. The high-end devices that have full implementation of camera2 api may deliver higher frame rates. Samsung published their own camera sdk. Use it if you need some special features of Samsung devices.
On a multi-core device, you can offload image processing to a thread pool, but still the frame rate will probably be limited by camera hardware.
Note that you can perform some limited image processing in GPU, applying shaders to the texture that is acquired from camera.

A: Assuming you have done the basics and you have got a camera preview and a Camera object. You can call:
Camera.PreviewCallback callback = new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        //Do your processing here... Use the byte[] called "data"
    }
};

And then:
mCamera.setPreviewCallback(callback);

If Camera.Parameters.setPreviewFormat() is never called, the default format will be NV21, which uses the NV21 encoding format.


text:
Q: CSS grid display in one row 4 columns or 2 rows 2 colums I'm trying to display 4 elements with grid and in a responsive way. What I want to achieve is to have the 4 element or in one row and 4 columns or 2 rows and 2 columns. My solution don't work in all screen width but I don't know how to fix the problem (in some screen width it go in 2 rows 3 columns so the first rows have 3 elements and the second only 1 as show here)
I would appreciate any suggestion that use the grid system!
Thank you in advance

.top-news-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(15rem, 50%), 1fr));
  grid-template-rows: minmax(5rem, auto);
  gap: 1.6rem;
  padding-bottom: 3.2rem;
}

First article in a card style

Second article in a card style

Third article in a card style

Fourth article in a card style


text:
Q: I need a Javascript literal syntax converter/deobfuscation tools I have searched Google for a converter but I did not find anything. Is there any tools available or I must make one to decode my obfuscated JavaScript code ?
I presume there is such a tool but I'm not searching Google with the right keywords.
The code is 3 pages long, this is why I need a tools.
Here is an exemple of the code :
<script>([][(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]()[(!![]+[])[!+[]+!+[]+!+[]]+(+(+[])+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+!+[]+[+[]]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]])(([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+

Thank you

A: This code is fascinating because it seems to use only nine characters ("[]()!+,;" and empty space U+0020) yet has some sophisticated functionality.  It appears to use JavaScript's implicit type conversion to coerce arrays into various primitive types and their string representations and then use the characters from those strings to compose other strings which type out the names of functions which are then called.
Consider the following snippet which evaluates to the array filter function:
([][
   (![]+[])[+[]]               // => "f"
 + ([![]]+[][[]])[+!+[]+[+[]]] // => "i"
 + (![]+[])[!+[]+!+[]]         // => "l"
 + (!![]+[])[+[]]              // => "t"
 + (!![]+[])[!+[]+!+[]+!+[]]   // => "e"
 + (!![]+[])[+!+[]]            // => "r"
]) // => function filter() { /* native code */ }

Reconstructing the code as such is time consuming and error prone, so an automated solution is obviously desirable.  However, the behavior of this code is so tightly bound to the JavaScript runtime that de-obsfucating it seems to require a JS interpreter to evaluate the code.
I haven't been able to find any tools that will work generally with this sort of encoding.  It seems as though you'll have to study the code further and determine any patterns of usage (e.g. reliance on array methods) and figure out how to capture their usage (e.g. by wrapping high-level functions [such as Function.prototype.call]) to trace the code execution for you.

A: This question has already an accepted answer, but I will still post to clear some things up.
When this idea come up, some guy made a generator to encode JavaScript in this way. It is based on doing []["sort"]["call"]()["eval"](/* big blob of code here */). Therefore, you can decode the results of this encoder easily by removing the sort-call-eval part (i.e. the first 1628 bytes). In this case it produces:
if (document.cookie=="6ffe613e2919f074e477a0a80f95d6a1"){ alert("bravo"); }
else{ document.location="http://www.youtube.com/watch?v=oHg5SJYRHA0"; }

(Funny enough the creator of this code was not even able to compress it properly and save a kilobyte)
There is also an explanation of why this code doesn't work in newer browser anymore: They changed Array.prototype.sort so it does not return a reference to window. As far as I remember, this was the only way to get a reference to window, so this code is kind of broken now.


text:
Q: AngularFire how to remove multiple items from array? I am using Firebase and the AngularFire library.  I am looking for a way to remove all items or a range of items from a $firebaseArray object.  I don't see a straightforward way to do it in the documentation.  Is there some way I'm not thinking of other than looping and removing items one by one?  Please tell me that's not the only way!!

A: If there isn't a method in the $firebaseArray that does what you want, you can use the array's $ref() to perform Firebase SDK-style calls. The array content will be synchronized with the changes you make through the ref.
To delete all elements, call remove on the ref itself:
function removeAll(firebaseArray) {
  return firebaseArray.$ref().remove();
}

To remove a range, perform an update in which the keys to be removed are set to null:
function removeRange(firebaseArray, start, end) {
  var keys = {};
  if (end === undefined) {
    end = firebaseArray.length;
  }
  for (var i = start; i < end; ++i) {
    keys[firebaseArray.$keyAt(i)] = null;
  }
  return firebaseArray.$ref().update(keys);
}

Both functions return promises.

A: I couldn't get the firebaseArray.$ref().remove() to work as the remove() function didn't exist on the object when ordered by child, but doing the following seemed to work though:
$firebaseUtils.doRemove(firebaseArray.$ref());


text:
Q: How to use IntentDonationManager.donate(intent:) I just use code like this
IntentDonationManager.shared.donate(intent: AddRopeShortcut())

And intent never appear neither in spotlight nor Siri widget nor Notification Center


text:
Q: SDL 2.0 C++: Polymorphism Vectors, my objects are not loading different images So I'm basically following a book called SDL Game Development by Shaun Mitchell.
I'm current on page 58, where it tells us how to implement polymorphism.
So far what I have down are:
- Create the main code where we do all our rendering updating etc. (Game.cpp and Game.h)
- Create a Texture manager as a singleton (TextureManager.h and TextureManager.cpp)
- Create a GameObject (GameObject.h and GameObject.cpp)
- Create a Player that inherits GameObject (Player.h and Player.cpp)
So my GameObject class basically has 3 methods: load, draw and update.
Load basically loads an image, and I use my TextureManager to do so.
Draw draws it and update just changes it positions and current frame.
I pass the name of the image which is basically the directory, the renderer and the textureID from the Game class where I call them.
Essentially the problem is that I pass in two different directories into a GameObject
and a Player, but it only loads up the last directory I pass in. As in both GameObject and Player becomes the same image.
So I think the problem lies in Game class, Player class or GameObject class.
I create the objects in Game class, and push them in vector at Game.cpp in init function
Where it says
    m_go->load(100, 100, 96, 60, "assets/simba.bmp", "animate",m_pRenderer);
    m_player->load(300, 300, 96, 60, "assets/download.bmp", "animate",m_pRenderer);

GameObject.h
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H

#include <string>
#include <iostream>
#include "SDL_image.h"
#include "TextureManager.h"

class GameObject
{
    public:
        virtual bool load(int x, int y, int width, int height, std::string name, std::string textureID, SDL_Renderer* pRenderer);
        virtual void draw(SDL_Renderer* pRenderer);
        virtual void update();
        virtual void clean();
    protected:
        std::string m_textureID;
        int m_currentFrame;
        int m_currentRow;
        int m_x;
        int m_y;
        int m_width;
        int m_height;
};

#endif // GAMEOBJECT_H

GameObject.cpp
#include "GameObject.h"

bool GameObject::load(int x, int y, int width, int height, std::string name, std::string textureID, SDL_Renderer* pRenderer)
{
    m_x = x;
    m_y = y;
    m_width = width;
    m_height = height;
    m_textureID = textureID;
    m_currentRow = 1;
    m_currentFrame = 1;
    if(!TextureManager::Instance()->load(name, textureID, pRenderer))
    {
        return false;
    }
    return true;
}

void GameObject::draw(SDL_Renderer* pRenderer)
{
    TextureManager::Instance()->drawFrame(m_textureID, m_x, m_y,m_width, m_height, m_currentRow, m_currentFrame, pRenderer);
}

void GameObject::update()
{
    m_x += 1;
    m_currentFrame = int(((SDL_GetTicks() / 100) % 6));
}

void GameObject::clean()
{

}

In my Player class, I do the same thing except I use the methods that are already made in GameObject
Player.h
#ifndef PLAYER_H
#define PLAYER_H

#include "GameObject.h"
class Player : public GameObject
{
    public:
        bool load(int x, int y, int width, int height, std::string name, std::string textureID, SDL_Renderer* pRenderer);
        void draw(SDL_Renderer* pRenderer);
        void update();
        void clean();
};

#endif // PLAYER_H

Player.cpp
#include "Player.h"

bool Player::load(int x, int y, int width, int height, std::string name, std::string textureID, SDL_Renderer* pRenderer)
{
    if(!GameObject::load(x, y, width, height, name, textureID, pRenderer))
    {
        return false;
    }
    return true;
}

void Player::draw(SDL_Renderer* pRenderer)
{
    GameObject::draw(pRenderer);
}

void Player::update()
{
    m_currentFrame = int(((SDL_GetTicks() / 100) % 6));
    m_x -= 1;
}

void Player::clean()
{

}

This is the part where the images doesn't load the same thing happens in Game.cpp
So I basically created a vector that holds GameObjects, it told me to use it so that I could just for loop through it whenever I want to draw objects
Game.h
#ifndef GAME_H
#define GAME_H

#include <SDL.h>
#include <SDL_image.h>
#include <string.h>
#include <iostream>
#include <vector>
#include "TextureManager.h"
#include "Player.h"

class Game
{
    public:
        Game() {}
        ~Game() {}

        bool init(const char* title, int xpos, int ypos, int width, int height, int flags);
        void render();
        void update();
        void handleEvents();
        void clean();

        // a function to access the private running variable
        bool running() { return m_bRunning; }

    private:
        SDL_Window* m_pWindow;
        SDL_Renderer* m_pRenderer;
        int m_currentFrame;
        bool m_bRunning;
        GameObject* m_go;
        GameObject* m_player;
        std::vector<GameObject*> m_gameObjects;

};

#endif

Game.cpp
#include "Game.h"

typedef TextureManager TheTextureManager; // Singleton TextureManager
Game* g_game = 0; // Game Object

bool Game::init(const char* title, int xpos, int ypos, int width,int height, int flags)
{
    // attempt to initialize SDL

    if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        std::cout << "SDL init success\n";
        // init the window
        m_pWindow = SDL_CreateWindow(title, xpos, ypos,width, height, flags);
        if(m_pWindow != 0) // window init success
    {
    std::cout << "window creation success\n";
    m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
    if(m_pRenderer != 0) // renderer init success
    {
        std::cout << "renderer creation success\n";
        SDL_SetRenderDrawColor(m_pRenderer,255,255,255,255);
    }
    else
    {
        std::cout << "renderer init fail\n";
        return false; // renderer init fail
    }
    }
    else
    {
        std::cout << "window init fail\n";
        return false; // window init fail
    }
    }
    else
    {
        std::cout << "SDL init fail\n";
        return false; // SDL init fail
    }
    std::cout << "init success\n";

    m_go = new GameObject();
    m_player = new Player();
    m_go->load(100, 100, 96, 60, "assets/simba.bmp", "animate",m_pRenderer);
    m_player->load(300, 300, 96, 60, "assets/download.bmp", "animate",m_pRenderer);
    m_gameObjects.push_back(m_go);
    m_gameObjects.push_back(m_player);

    m_bRunning = true; // everything inited successfully, start the main loop
    return true;

}

void Game::render()
{
    SDL_RenderClear(m_pRenderer); // clear the renderer to the draw color

    //m_go.draw(m_pRenderer);
    //m_player.draw(m_pRenderer);
    for(std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->draw(m_pRenderer);
    }

    SDL_RenderPresent(m_pRenderer); // draw to the screen
}

void Game::clean()
{
    std::cout << "cleaning game\n";
    SDL_DestroyWindow(m_pWindow);
    SDL_DestroyRenderer(m_pRenderer);
    SDL_Quit();
}

void Game::handleEvents()
{
    SDL_Event event;
    if(SDL_PollEvent(&event))
    {
        switch (event.type)
        {
        case SDL_QUIT:
            m_bRunning = false;
            break;
            default:
            break;
        }
    }
}
void Game::update()
{
    //m_currentFrame = int(((SDL_GetTicks() / 100) % 6));
    //m_go.update();
    //m_player.update();
    for(std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); i++)
    {
        m_gameObjects[i]->update();
    }
}

int main(int argc, char* argv[])
{
    g_game = new Game();
    g_game->init("Chapter 1", 100, 100, 640, 480, 0);
    while(g_game->running())
    {
        g_game->render();
        g_game->handleEvents();
        g_game->update();
        SDL_Delay(10); // add the delay
    }
    g_game->clean();
    return 0;
}

As you can see at the end of the init function, I have m_go load up simba, and m_player load up download. Even though they move in different directions (GameObject moves to the right and Player moves to the left as you can see in the classes in update method).
My program only loads download for both.
I'm not sure if the TextureManager class is related but I'll post it anyway
TextureManager.h
#ifndef TEXTUREMANAGER_H
#define TEXTUREMANAGER_H

#include <SDL.h>
#include <SDL_image.h>
#include <string.h>
#include <iostream>
#include <map>
class TextureManager
{
    public:
        bool load(std::string fileName,std::string id,SDL_Renderer* pRenderer);
        void draw(std::string id, int x, int y, int width, int height, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE);
        void drawFrame(std::string id, int x, int y, int width, int height, int currentRow, int currentFrame, SDL_Renderer* pRenderer, SDL_RendererFlip flip = SDL_FLIP_NONE);
        std::map <std::string, SDL_Texture*> m_textureMap;

        static TextureManager* Instance()
        {
            if(s_pInstance == 0)
            {
                s_pInstance = new TextureManager();
                return s_pInstance;
            }
        return s_pInstance;
        }
        //typedef TextureManager TheTextureManager;
    protected:
    private:
        TextureManager(){}
        static TextureManager* s_pInstance;

};

#endif // TEXTUREMANAGER_H

TextureManager.cpp
#include "TextureManager.h"

TextureManager* TextureManager::s_pInstance = 0;

bool TextureManager::load(std::string fileName, std::string id, SDL_Renderer* pRenderer)
{
    SDL_Surface* pTempSurface = IMG_Load(fileName.c_str());
    if(pTempSurface == 0)
    {
        return false;
    }
    SDL_Texture* pTexture =
    SDL_CreateTextureFromSurface(pRenderer, pTempSurface);
    SDL_FreeSurface(pTempSurface);
    // everything went ok, add the texture to our list
    if(pTexture != 0)
    {
        m_textureMap[id] = pTexture;
        return true;
    }
// reaching here means something went wrong
    return false;
}

void TextureManager::draw(std::string id, int x, int y, int width, int height, SDL_Renderer* pRenderer, SDL_RendererFlip flip)
{
    SDL_Rect srcRect;
    SDL_Rect destRect;

    srcRect.x = 0;
    srcRect.y = 0;
    srcRect.w = destRect.w = width;
    srcRect.h = destRect.h = height;
    destRect.x = x;
    destRect.y = y;
    SDL_RenderCopyEx(pRenderer, m_textureMap[id], &srcRect,
    &destRect, 0, 0, flip);
}

void TextureManager::drawFrame(std::string id, int x, int y, int width, int height, int currentRow, int currentFrame, SDL_Renderer *pRenderer, SDL_RendererFlip flip)
{
    SDL_Rect srcRect;
    SDL_Rect destRect;
    srcRect.x = width * currentFrame;
    srcRect.y = height * (currentRow - 1);
    srcRect.w = destRect.w = width;
    srcRect.h = destRect.h = height;
    destRect.x = x;
    destRect.y = y;
    SDL_RenderCopyEx(pRenderer, m_textureMap[id], &srcRect,
    &destRect, 0, 0, flip);
}

A: You are using "animate" more than once for the textureID - this needs to be unique
Your Code:
m_go->load(100, 100, 96, 60, "assets/simba.bmp", "animate", m_pRenderer);
m_player->load(300, 300, 96, 60, "assets/download.bmp", "animate", m_pRenderer)

What happens is the texture is loaded but it overwrites the existing texture which has the "animate" key in the map. Make them unique and this should resolve your issue.


text:
Q: Python- Get AWS Bucket Key from Path Given that I have something like this:
"s3://folder1/folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv"

How do I parse it out so that I get the Bucket and then the Key as everything minus the last/ with the filename?
I am trying to get the path so that I can list all the files within the path.

A: One way would be to use simple split and join combo:
s3_path = "s3://folder1/folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv"

s3_path_split = s3_path.split('/')

bucket_name = s3_path_split[2]

# 'folder1'

key_name = '/'.join(s3_path_split[3:])

# 'folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7/file_name.csv'

key_name_without_file = '/'.join(s3_path_split[3:-1])

# folder2/folder3/folder4/folder4.5/folder4.6/folder5/folder6/folder7'


text:
Q: CAKEPHP: Filter Issues http://webdesign4.georgianc.on.ca/~100141468/comp2084/todo/clients
PROBLEM: http://webdesign4.georgianc.on.ca/~100141468/comp2084/todo/timesheets/filter2/7
This has to be an issue with a lowercase variable or something, but I just cannot figure it out.
Filter2.ctp

    IDnameHoursclientsedit

<? foreach($Timesheets as $row): ?>

<?=$row['Timesheet']['id']?>

<?=$row['Timesheet']['hours']?>

<a href="../../clients/view/<?=$row['client']['name']?>"><?=$row['client]['name']?>

<a href="edit/<?=$row['Timesheet']['id']?>">Edit

<? endforeach; ?>

Timesheetcontroller filter2
function filter2($Client_id) {
        $this->set('Timesheets',$this->Timesheet->findAllByClientId($Client_id));
    }

A: In this line
<a href="../../clients/view/<?=$row['client']['name']?>"><?=$row['client]['name']?>

You are missing a '. This is producing the syntax error. You will probably also need to capitalize the 'Client' index to get the desired result, as it is the name of a model. It is also likely that the view action in ClientsController expects an id. You can change it to:
<a href="../../clients/view/<?=$row['Client']['id']?>"><?=$row['Client']['name']?>

However, I would suggest not to hardcode the url like that, but have Cake produce the link like so:
<?= $this->Html->link($row['Client']['name'], array('controller' => 'clients', 'action' => 'view', $row['Client']['id']) ?>

See the docs on helpers, as well as the HtmlHelper API.


text:
Q: KML Layer Watermark Removal Hello right now I have a google maps page with KML Layers from multiple online resources. However all of these layers especially those from noaa have giant watermarks that take up large portions of my small map. Is there anyway to remove these watermarks? Is there a paid KML/KMZ weather service I could use that doesn't have watermarks? The feeds I am using now are
     layers[0] = new  google.maps.KmlLayer('http://www.hpc.ncep.noaa.gov/kml/fop/fopbody.kml',
            {preserveViewport: true});

    layers[1] = new google.maps.KmlLayer('http://www.nhc.noaa.gov/gis/forecast/archive/latest_wsp34knt120hr_tenthDeg.kmz',
            {preserveViewport: true});

    layers[2] = new google.maps.KmlLayer('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month_depth_link.kml',
            {preserveViewport: true});

    layers[3] = new google.maps.KmlLayer('http://activefiremaps.fs.fed.us/data/kml/conus_latest_lg_incidents.kml',
            {preserveViewport: true});

    layers[4] = new google.maps.KmlLayer('http://w1.weather.gov/tcig/Tornado.kml?random=115233',
            {preserveViewport: true});


text:
Q: Checking for varification: Proof - continuous function on a compact metric spaces is uniformly continuous As a prep for my exam, I tried to prove all theorems we had during lecture on my own. I tried to prove that every continuous function on a compact metric space is also uniformly continuous. However in my "proof" I don't see me using the compact property of the metric Space, so I assume I error somewhere and that my "proof" is incorrect. I would be very happy, if someone could look over it and point out my mistake.
Let $(X,d)$ be a metric Space and $f$ be a continuous function on $X$.
For a given $ \epsilon $,
we define $T$ as the family of all neighborhoods of all $ x_i \in X, $ that suffice the condition: $ d(x_j, x_i) < { \delta \over 2} \Rightarrow d_Y(f(x_j), f(x_i)) $ for $ x_j \in U_{ \delta \over 2}(x_i) $ - (remind $f$ is continuous)
Now picking any two points $x_m, x_n$ in any neighborhood of $ x_i $ suffices the triangle inequality and one has $d_X(x_m, x_n) \le d_X(x_m, x_i) + d_X(x_i, x_n) < { \delta \over 2} + { \delta \over 2} = \delta \Rightarrow d_Y(f(x_m), f(x_n)) < \epsilon $

A: The continuity of $f$ does not imply the existence of the neighborhoods you choose. Indeed, the $\delta $ should depend on $x_i$. You salvage the proof precisely by noting that by compactness, you can choose a finite subcover, and then choose the smallest $\delta_i$ of the subcover.


text:
Q: Stored Procedure returns nothing This might be a simple fail on my part, but I just can't figure out where or how.
I've been coding a windows service that is doing a bunch of things. One of which is inserting and getting data from a MS Sql 2005 database through stored procedures.
The following code is part of a windows service and now also a windows form, where both produce the same empty result.
    try
        {
            SqlCommand cmd = new SqlCommand("U_RfId_ProductNumberGet", connectionRFID);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            //SqlParameter paramProd = new SqlParameter();
            SqlParameter paramOut = new SqlParameter();
            paramOut.ParameterName = "@ProductInformation";
            paramOut.Direction = System.Data.ParameterDirection.Output;
            paramOut.SqlDbType = System.Data.SqlDbType.VarChar;
            paramOut.Size = 50;
            cmd.Parameters.Add(paramOut);
            cmd.Parameters.AddWithValue("@ProductNumber", content); //content = "1" for testing
            connectionRFID.Open();

            textBox1.Text = (String)paramOut.Value;

            //cmd.Parameters["@ProductInformation"].Value.ToString();
            connectionRFID.Close();
        }
        catch (Exception ex)
        { textBox1.Text = ex.Message;
        connectionRFID.Close();
        }

And then there's the SP the code is calling. I've tried changing it to only return a resultset instead of a scalar output parameter and then the call to the SP works, but I'd prefer to use the scalar values.
CREATE PROCEDURE U_RfId_ProductNumberGet
@ProductInformation     varchar(50) OUTPUT,
@ProductNumber          varchar(8)

AS
BEGIN TRAN
SET NOCOUNT ON;
BEGIN
SELECT @ProductInformation
                = CAST(vareNummer AS varchar(10))
                + '-' + CAST(vareTekst AS varchar(30))
FROM VareNummerVareTekst
WHERE ProductNumber = @ProductNumber
END
COMMIT TRAN

As a side note: If I execute the SP through SQL Management Studio I get a valid result.
Anyone notice what I've forgotten?

A: You forgot to execute the command.
cmd.Execute(); // to get a resultset

or
cmd.ExecuteNonQuery(); // to get output parameters but no resultset

should do it depending on whether or not you want a resultset.

A: you have to use ExecuteNonQuery on command object. SqlCommand Executenonquery
    connectionRFID.Open();
    cmd.ExecuteNonQuery(); // this missing from your code
   textBox1.Text = (String)paramOut.Value;


text:
Q: obtener url de la miniatura de categorías woocommerce tengo la siguiente duda. Estoy haciendo una tienda online con woocommerce y en ella tengo productos, y estos tienen categorías. Pues bien,a la hora de crear la categoría en el back office de wordpress, se añade una imagen/miniatura a esta. Necesito obtener la url de esa imagen. Cualquier función probado hasta ahora como wp_get_attachment_url() o wp_get_attachment_image_src() me devuelven las imagenes de los productos. Yo quiero la miniatura de la categoría (adjunto captura):

Lo único que he conseguido hasta ahora es obtener el parámetro de la URL tag_id, pero este no me sirve de nada a la hora de intentar localizar la imagen...
¿Alguien tiene alguna idea?
Gracias por adelantado.

A: Prueba agregando lo siguiente en tu functions.php
add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
    if ( is_product_category() ){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo '<img src="' . $image . '" alt="' . $cat->name . '" />';
        }
    }
}

Parece que debes tener el gancho woocommerce_archive_description en la plantilla del tema, pero puedes usar cualquier otro gancho, como wp_body_open(); o alguno personalizado.
Fuentes: https://docs.woocommerce.com/document/woocommerce-display-category-image-on-category-archive/


text:
Q: Express promise chain how to send response and end promise chain flow? With the code below i'm getting this error:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client if result === null.
'use strict'

const HttpStatus = require('http-status-codes')
const { handleErr } = require('ciitizen-express-helpers').utils

function updateOrganization(db, stats) {
  return function (req, res) {
    db.organization.findOne({
      where: {
        id: req.params.id
      }
    })
      .then(result => {

        if (result === null) {
          return res.status(HttpStatus.NOT_FOUND).send() <-- IF RESULT IS NULL, I RETURN THIS
        }

        console.log('original result = ', result)

        // Update any fields that were passed in
        if (req.body.name) {
          result.name = req.body.name
        }

        if (req.body.address1) {
          result.address1 = req.body.address1
        }

        if (req.body.address2) {
          result.address2 = req.body.address2
        }

        if (req.body.city) {
          result.city = req.body.city
        }

        if (req.body.state) {
          result.state = req.body.state
        }

        if (req.body.zip) {
          result.zip = req.body.zip
        }

        console.log('new result = ', result)
        return result.save()
      })
      .then(result => {
        console.log('final result = ', result)
        return res.status(HttpStatus.CREATED).send(result) <-- BUT IT'S STILL TRYING TO CALL THIS, HENCE THE CAN'T SEND HEADERS ERROR
      })
      .catch(err => {
        req.log.error(err)
        return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
      })
  }
}

module.exports = updateOrganization

What's the best way to return a response early without continuing through my promise chain flow?

A: Promises chain like that
What you can do is
A) return null AFTER res.status(HttpStatus.NOT_FOUND) (removing the return before that code)
B) in then(result check if result is null, if so, skip the res.status(... code
e.g.
'use strict'

const HttpStatus = require('http-status-codes')
const { handleErr } = require('ciitizen-express-helpers').utils

function updateOrganization(db, stats) {
  return function (req, res) {
    db.organization.findOne({
      where: {
        id: req.params.id
      }
    })
      .then(result => {

        if (result === null) {
          // change A
          res.status(HttpStatus.NOT_FOUND).send();
          return null;
        }
        // snip
        return result.save()
      })
      .then(result => {
        console.log('final result = ', result)
        // change B
        if (result !== null) {
            return res.status(HttpStatus.CREATED).send(result)
        }
      })
      .catch(err => {
        req.log.error(err)
        return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
      })
  }
}

module.exports = updateOrganization

alternatively, keep your existing code until
      .then(result => {
        // change C
        if (!res.headersSent) {
            console.log('final result = ', result)
            return res.status(HttpStatus.CREATED).send(result)
        }
      })

That's probably a "cleaner" fix to be honest

A: Test this:
    function updateOrganization(db, stats) {
  return function (req, res) {
    db.organization.findOne({
      where: {
        id: req.params.id
      }
    })
      .then(result => {

        if (!result) {
          res.status(HttpStatus.NOT_FOUND).end();
          return null;
        }

        console.log('original result = ', result)

        // Update any fields that were passed in
        if (req.body.name) {
          result.name = req.body.name
        }

        if (req.body.address1) {
          result.address1 = req.body.address1
        }

        if (req.body.address2) {
          result.address2 = req.body.address2
        }

        if (req.body.city) {
          result.city = req.body.city;
        }

        if (req.body.state) {
          result.state = req.body.state;
        }

        if (req.body.zip) {
          result.zip = req.body.zip;
        }

        console.log('new result = ', result);
        return result.save();
      })
      .then(result => {
        console.log('final result = ', result);
        if(result) {
            return res.status(HttpStatus.CREATED).json(result)
        }
        return null;

      })
      .catch(err => {
        req.log.error(err);
        return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message);
      })
  }
}


text:
Q: ESC/POS Printing Issue on android device (HiStone HK316) - Xamarin Forms I am working on A xamarin forms app, where i need to implement bluetooth printing. I am successfully able to print on regular iOS and android devices. but on HiStone(hk316) its not printing as it should be

Below is the code i've used for Printing
using (var ms = new MemoryStream())
                {
                    using (var bw = new BinaryWriter(ms))
                    {
                        bw.Write(e.Initialize());
                        bw.Write(e.PrintLine("                             "));

                        bw.Write(e.CenterAlign());
                        bw.Write(e.SetStyles(PrintStyle.Bold));
                        bw.Write(e.PrintLine(GlobalVariables.Instance.Business.Business.BusinessDisplayName));

                        bw.Write(e.PrintLine(GlobalVariables.Instance.Business.Location.LocationName));

                        bw.Write(e.PrintLine(string.Format("{0}, {1}", GlobalVariables.Instance.Business.Location.Address, GlobalVariables.Instance.Business.Location.Zip)));

                        bw.Write(e.PrintLine("Phone: " + GlobalVariables.Instance.Business.Location.Phone.ToFormattedPhone()));
                        bw.Write(e.SetStyles(PrintStyle.None | PrintStyle.FontB));

                        bw.Write(e.PrintLine(string.Format("Payout#: {0}", cashDrawer.InvoiceNumber)));

                        bw.Write(e.SetStyles(PrintStyle.None | PrintStyle.FontB));
                        bw.Write(e.PrintLine(string.Format("Date: {0}   Clerk: {1}", cashDrawer.Dated.ToString("MM/dd/yyyy"), GlobalVariables.Instance.User.DisplayName)));

                        bw.Write(e.PrintLine(string.Format("Station: {0}   Time: {1}", GlobalVariables.Instance.Business.Register.RegisterName, cashDrawer.Dated.ToString("HH:mm:ss"))));
                        bw.Write(e.PrintLine(""));

                        bw.Write(e.LeftAlign());
                        bw.Write(e.SetStyles(PrintStyle.None | PrintStyle.FontB));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine($"Sig:_______________________"));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine(string.Format("Amount (Cash): {0}", cashDrawer.Amount.ToString("C"))));
                        bw.Write(e.PrintLine(string.Format("Reason : {0}", cashDrawer.Reason)));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine("Witness:____________________"));
                        bw.Write(e.PrintLine(""));
                        bw.Write(e.PrintLine(""));

                        bw.Write(AsciiControlChars.GroupSeparator);
                        bw.Write('V');
                        bw.Write((byte)66);
                        bw.Write((byte)3);

                        bw.Flush();

                        ms.Position = 0;
                        var sr = new StreamReader(ms);
                        var str = sr.ReadToEnd();
                        System.Diagnostics.Debug.WriteLine(str);
                        var bytesToPrint = System.Text.Encoding.ASCII.GetBytes(str).ToArray();
                        if (printerType == PrinterType.Bluetooth)
                        {
                            var res = await DependencyService.Get<IBlueToothService>().ConnectAndPrintAsync(bytesToPrint);
                        }
                        else if (printerType == PrinterType.Network)
                        {
                            DependencyService.Get<IPrintService>().PrintOverNetwork(bytesToPrint);
                        }

                        bw.Finish();
                    }
                }

I have used Shiny plugin for bluetooth connection. Thanks


text:
Q: JTable scroll to row issue I have the following method :
public void scrollToVisibleInstructionBlock(JTable table, int rowIndex, int sizeOfBlock) {
    if (!(table.getParent() instanceof JViewport))
        return;
    JViewport viewport = (JViewport) table.getParent();
    Rectangle rect = table.getCellRect(rowIndex, 0, true);
    Point pt = viewport.getViewPosition();
    rect.setLocation(rect.x - pt.x, rect.y - pt.y);
    viewport.scrollRectToVisible(rect);
    table.setRowSelectionInterval(rowIndex, rowIndex + sizeOfBlock - 1);
}

The functionality is nice but not optimal. I input the row to scroll to, it selects sizOfBlock rows and brings them into perception.
The problem is that the rows are always visible at the bottom of the table. For example:

As you can see, the selected row is at the bottom of the table. How could I perhaps bring the selected row to the top or middle?
Thanks

A: JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, 0, true);
Point pt = viewport.getViewPosition();
rect.setLocation(rect.x - pt.x, rect.y - pt.y);
viewport.scrollRectToVisible(rect);

I always use scrollRectTovisible(...) on the component you want to scroll:
Rectangle rect = table.getCellRect(rowIndex, 0, true);
table.scrollRectToVisible(rect);

If the row is below the current viewport position then you will be scrolled to the bottom.
If the row is above the current viewport position then you will be scrolled to the top.
If the rectangle is in the current viewport then no scrolling is done.
Doesn't really help solve your problem, just explains how scrollRectToVisible() works.
You can affect scrolling by increasing the "visible Rectangle" size. For example:
Rectangle rect = table.getCellRect(rowIndex, 0, true);
rect.height = rect.height + (table.getRowHeight() * 4);
table.scrollRectToVisible(rect);

Now the selected row should be 4 lines from the bottom when scrolling down. Doesn't really help when scrolling up as the selected row will be at the top.

How could I perhaps bring the selected row to the middle?

To position the selected row in the middle you would want to play with the viewport position directly to calculate the middle position in the viewport for the selected row:
JViewport viewport = (JViewport) table.getParent();
Rectangle r = table.getCellRect(rowIndex, 0, true);
int extentHeight = viewport.getExtentSize().height;
int viewHeight = viewport.getViewSize().height;

int y = Math.max(0, r.y - ((extentHeight - r.height) / 2));
y = Math.min(y, viewHeight - extentHeight);

viewport.setViewPosition(new Point(0, y));

A: You could just increase the row index when calling getCellRect. After checking the row count of course.
public void scrollToVisibleInstructionBlock(JTable table, int rowIndex, int sizeOfBlock) {
    if (!(table.getParent() instanceof JViewport))
        return;
    JViewport viewport = (JViewport) table.getParent();

    // bottom of selection is 5 rows above bottom of scrollpane
    int delta = 5;
    if ((rowIndex + (sizeOfBlock-1) + delta) >= table.getRowCount())
        delta = 0;
    else
        delta = delta + (sizeOfBlock-1);

    Rectangle rect = table.getCellRect(rowIndex+delta, 0, true);
    Point pt = viewport.getViewPosition();
    rect.setLocation(rect.x - pt.x, rect.y - pt.y);
    viewport.scrollRectToVisible(rect);
    table.setRowSelectionInterval(rowIndex, rowIndex + sizeOfBlock - 1);
}

You should also take into account the sizeOfBlock parameter. And perhaps the size of the scrollpane if you want the selection centered.

A: It's very easy, JTable has scrollRectToVisible method too. If you want, you can try something like this to make scrollpane go to to the bottom if a new record is added
jTable1.getSelectionModel().setSelectionInterval(i, i);
jTable1.scrollRectToVisible(new Rectangle(jTable1.getCellRect(i, 0, true)));

Where i is last added record.
To scroll column replace 2nd parameter of getCellRect with your column index.


text:
Q: PHP beginner with MySQL trouble I am creating a website in which users can log on and review Tablet PC's
On tablet page visitors to the site can see the reviews left by other users. Despite users being able to review 5 tablets, the 'ipad' page for example will only show 'ipad' review. The code can be seen below:
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tt_review WHERE product = 'Apple iPad'");

echo "

";

while($row = mysql_fetch_array($result)) //This function is calling the results variable and displaying them within the rows below
{
echo "
"; //this code tells the page to output the table rows that are defined above
echo "" . $row['name'] . "	";
echo "" . $row['date'] . "	"; //each row is then executed using the table data function
echo "" . $row['product'] . "	";
echo "" . $row['star'] . "	";
echo "" . $row['comment'] . "	";

echo "
";
}
echo "
";

?>

I have a field in my database called 'star' which is the rating the users have gave the tablet. 1, 2, 3, 4 or 5 are the options. I need code that works out the average of the 'star' rating from the 'ipad' page and to display an image based on whatever number it is.
All help is greatly appreciated as I am a newcomer and cant seem to find the answer online.
Thanks
Jonathan

A: Use mysqli to connect to the database. Then you can use the AVG function to calculate average of the column star. Execute the query and fetch the array and then print the average. Then you can use simple switch case or if else to display the image according to the average obtained.
<?php
$db = mysqli_connect("host","user","pass","database");
$query = "SELECT AVG(column_name) FROM table_name";
$result = mysqli_query($db, $query);
$array = mysqli_fetch_row($result);
$average = $array[0];
echo $average;
?>

A: From what I understand you want to calculate the average rating for each tablet. If yes, you can just fetch the star column for the particular tablet from the database and extract it as an array and run a simple for-each loop to calculate the sum and average of the rating for that tablet and based on the average it calculated, an indication can be placed on the screen in the form of images or something else.

A: I'm with the others regarding using 'mysql_*' functions, but I won't go into that here as that is not relevant to your question.
To find the average you add all of the total stars together and divide by the quantity. My suggestion is to first find out how many rows are returned.
$totalStars = count($result);

You also need to know what the sum is of the column. This is done using SUM(column). Like so:
$result = mysql_query("SELECT SUM(star) as TotalStars, name, date, product, star, comment FROM tt_review WHERE product = 'Apple iPad'");

However, you can also add a counter to your code, like so:
$x = 0;
while($row = mysql_fetch_array($result)) {
    $x += $row['star'];
    // your other code
    $x++;
}

Finally, at the end, you can display the average by doing something like:
if ($totalStars != 0 ) {
    $average = $x / $totalStars;
    echo "This product's average stars is " . $average . PHP_EOL;
} else {
    // handle the divide by zero issue
}

When it comes to displaying a particular image, well, you can use a conditional statement or something like:
if ($average > 0 && $average <= 1) {
    echo "";
} else if ($average > 1 && $average <= 1.5) {
    // etc etc etc
}

Hope that helped some.

A: As mentioned, use PDO to connect to the database. Here's how you get the average stars:
$i = 0;
$totalStars = 0;
   while($row = mysql_fetch_array($result))
{
    $totalStars += $row['star'];

    // rest of your code
    $i++;
}
echo 'Average stars = '.($totalStars/$i);

A: As pointed out by others, Mysql has an AVG() function you can use for this exact purpose.
SELECT AVG(star) AS rating FROM tt_review WHERE product = 'Apple iPad' GROUP BY product;

or, to get the star rating for all products you leave off the WHERE
SELECT AVG(star) AS rating FROM tt_review GROUP BY product;

If you just want your rating to be 1,2,3,4, or 5
SELECT ROUND(AVG(star), 0) AS rating FROM tt_review WHERE product = 'Apple iPad' GROUP BY product;

And if you want the rounded number to skew up (a common desire)
SELECT CEILING(AVG(star)) AS rating FROM tt_review WHERE product = 'Apple iPad' GROUP BY product;


text:
Q: trouble in passing select tag values in a rails application new on rails, i am having problem in passing select_tag value(in the view file) to controller.
my view controller file is like
class ProjectStatusController < ApplicationController

  def index
    @projects = Project.find(:all, :select => "name")
  end

  def show
    lookup = params[:project]
    @rows = Project.find_by_lookup(lookup)
  end
end

and view file is like
<% form_tag("project_status", :controller => "ProjectStatus", :action => "show",    :method=>'get' ) do %>
<%= select_tag 'project', options_from_collection_for_select(@projects,"id", "name"),:onchange => "this.form.submit();" %>
<% end %>
<%
if !@rows.nil?
 @rows.each do |row|
end
%>
<%= row[:name] %>
<% end %>

what i basically want to achieve is this - based on the selected value from select tag
i want to display information(on the same view page) of selected item from the database

A: First of all you should write <%= form_tag not <% form_tag
Than, it's strange that your extract for select field id(options_from_collection_for_select(@projects,"id", "name"))
but in method show you search record by field lookup

A: You can use something of this sort to get this issue fixed
     <%= check_box_tag "projectids[]",project.id %>

This would display the checkbox against each entry. And the checkbox is linked to the project object by its id. In the controller method, you will receive the project ids.
Then just directly use the submit tag to pass the parameters to the method.


text:
Q: grafico de varias variables con ggplot tengo una base de datos como la siguiente:

id
choice
pricec1
pricec2
princec3
princec4
princec5
Income

1
1
8
7
8
6
8
20

1
3
8
6
5
6
10
20

1
1
9
8
8
7
8
20

1
4
9
8
10
9
9
20

2
1
8
7
8
6
8
23

2
3
8
6
5
6
11
23

2
1
9
8
7
7
8
23

2
4
9
8
10
9
9
23

y me gustaría hacer un grafico con ggplot que me entregara boxplots de distribucion de precios para cada columna de precios, es decir, que hayan 5 boxplots uno para cada 'pricecn' (siendo n el número) existe alguna forma de hacer eso?

A: Para crear gráficos en ggplot siempre es recomendable reducir el número de columnas agrupando aquellas que representan la misma unidad. Luego para diferenciar entre grupos, se puede ocupar una sola columna en vez de llamar a 5, por ejemplo.
Para este caso, la herramienta para agrupar columnas la incorpora la librería tidyr a través de pivot_longer(). Suponiendo que la tabla tiene por nombre df:
library(dplyr)
library(tidyr)
library(ggplot2)

df %>%
  pivot_longer(-c(id,
                  Income,
                  choice),
               names_to = 'precio',
               values_to = 'valor') %>%
  ggplot(aes(x = precio,
             y = valor)) +
  geom_boxplot()


text:
Q: Why HMS PushKit needs android.permission.REQUEST_INSTALL_PACKAGES Recently I've added HMS PushKit SDK with this gradle code:
implementation "com.huawei.hms:push:5.0.4.302"

After That I've noticed that my application added to the list of apps with access to install apps from unknown source (special permission). I checked the AndroidManifest.xml file of one of this library's dependency (com.huawei.hms.base.availableupdate) and saw that it has this special permission:
<!-- If it is Android 8.0, the targetSdkVersion of the application compilation configuration>=26, please be sure to add the following permissions -->
<uses-permission  android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

So Why PushKit needs this permission? I don't want my app to use this permission. And If I remove it with this code is there gonna be a problem (crash):
<uses-permission
        android:name="android.permission.REQUEST_INSTALL_PACKAGES"
        tools:node="remove"/>

A: UPDATE
If you remove this permission, it will not be affected on Huawei phones,but the HMS Core APK may not be installed on non-Huawei phones.
can it cause to crash in our app because of upgrade failure?--no,Only will make the application cannot be automatically upgraded,have to uninstall and download the new version.

<uses-permission  android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
This permission is used to update the HMS Core and push kit APK. Push kit strongly depends on the HMS Core and push kit APK. If this permission is not granted, applications may fail to be installed, and causing upgrade failures of the HMS and push kit`s APK.
Therefore, this permission is mandatory.

A: android.permission.REQUEST_INSTALL_PACKAGES is a permission that allows a framework or a component on Android, to refer to an external (maven most often) repository, in order to minimise the final installation apk size for the end user by installing source code remotely, instead of packaging it all inside the same apk (for initial download).
Be careful with this permission, because if it is enabled, not on your app, but rather a dependency, it will be rejected. This is because if there are any security issues with your dependency, there is no way for google to pick this up, when you upload the app bundle onto the store. This is because of a remote download of the source code, instead of it being packaged inside the same apk that google can strip.
As a result google will not accept this apk, and it will be rejected (just because google does not know, and has no way of knowing if there is any malicous code being included in the final end user package).
You can try to fork this library, and remove the permission from the manifest, but then you will encounter missing method exceptions.
Your best bet in this case is to find another library that does not install extra source code from a remote maven repository, in order to avoid a google play store rejection.
Looking at this package, it looks like it's an SDK built on top of the Android SDKs. If there is a way for you to get around this, and work directly on the google android sdk, while also making it so the customer does not notice, then that should be fine. At the end of the day the customer does not care how you do it, as long as it works.


text:
Q: React Google Analytics - How to check if initialized? I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).
So, I would like to create a text field in backoffice which value is saved in database.
Then in the front side, I initialize react-ga only if I have a value in database.
To achieve this, I'm trying do this in componentDidUpdate in App.jsx.
I retrieve all my data set in backoffice via :
componentDidMount() {
    // I get my data in this.props.data_admin
    this.props.list_admin();
}

Then in componentDidUpdate(prevProps, prevState) I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :
componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin) {
        // this.props.data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(this.props.data_admin.trackingNumber);
    }
}

But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done.
How can I check if react-ga is already initialized ?
Thanks for your help

A: I think you should not be doing this in componentDidUpdate but in componentDidMount after you have retrieved your data.
Your data retrieval process is an asynchronous call to your backend/database, it should return a Promise that resolves with the data retrieved. You can then initialize react-ga.
componentDidMount() {
    // I am assuming this.props.list_admin() returns your data
    this.props.list_admin().then((data_admin) => {
      if (data_admin) {
        // data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(data_admin.trackingNumber);
      }
    });
}

A: Finally what I did :
I called this.props.list_admin(); in App.jsx constructor and I created a state variable initialized at false :
constructor(props) {
    super(props);

    this.state = {
        googleAnalyticsInitialized: false,
    };

    this.props.list_admin();
}

Then, in componentDidupdate I checked values from this.props.data_admin and if googleAnalyticsInitialized is false. If it is, I initialiaze Google Analytics with the ID received from the call to the API :
componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin && this.props.data_admin.idGoogleAnalytics && !this.state.googleAnalyticsInitialized) {
        ReactGA.initialize(this.props.data_admin.idGoogleAnalytics);
        this.setState({googleAnalyticsInitialized: true});
    }
}

Thanks to @Chukwuemeka Onyenezido who helped me and directed me on the right way.

A: I was hoping to find a better answer than this, but I simply did
try {
    console.log(theObject);
} catch(e) {}

Not very elegant, a bit dirty, I'd like to understand more about what is going on, but this works.
Back Story
I'm trying to access the store in a reducer and importing the store object from the index.js is my current "solution"


text:
Q: reading from text box and passing to another page I want to read text from TextBox and then send it to another page. But on another page I keep geting empty string.
why this doesn't work ?
I have this on page 1:
public string _beseda()
{
    return textBox1.Text;
}

and on page 2 where I should retrieve this string:
private void button1_Click(object sender, RoutedEventArgs e)
{
    Page2 neki = new Page2();
    MessageBox.Show(neki._beseda());
}

A: There's a number of issues. You say you have that _beseda() function on Page1, but you reference Page2() in button1_click(). Additionally, if I assume you meant Page1 in button1_click(), you're creating newPage1 and then you ask it for the text box's text.... so of course it's empty. You haven't put anything in it.
Even if you meant to put Page2 there instead, the problem is still the same.

A: There are two strategies to pass data between pages in windows phone.

*

*Use App.cs

*Pass data as parameter values during navigation

1. Using App.cs
Open up App.cs code behind of App.xaml write:
 // To store Textbox the value
 public string storeValue;

In Page1
 protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        App app = Application.Current  as App;
        app.storeValue = textBox1.Text;
    }

on Page2
 private void button1_Click(object sender, RoutedEventArgs e) {

    App app = Application.Current  as App;
    MessageBox.Show(app.storeValue);
}

2. Passing values as parameters while navigating
Before navigating embed textbox value to the Page Url
    string newUrl = "/Page2.xaml?text="+textBox1.Text;
    NavigationService.Navigate(new Uri(newUrl, UriKind.Relative));

in Page2
    //Temporarily hold the value got from the navigation
    string textBoxValue = "";
    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        //Retrieve the value passed during page navigation
         NavigationContext.QueryString.TryGetValue("text", out textBoxValue)
    }

     private void button1_Click(object sender, RoutedEventArgs e) {

       MessageBox.Show(textBoxValue);
     }

Here are a number of useful links..

*

*How to pass the image value in one xaml page to another xaml page in
windows phone 7?

*How to perform page navigation on Windows
Phone