text:
Q: Instant Payment Notification (IPN) simulator dose work IPN delivery failed. Unable to connect to the specified URL. Please verify the URL and try again.
i am trying to use my Paypal ipn simulator but every time it gives me this error message, it seems that ipn simulator cant hit the specified URL, even though i am sure the specified URL is correct. any help please
// Connect to database --------------------------------------------------------------------------------------------------

----
    require_once ('../config/cart_api.php');

    // bussines email
    $bussines_email = 'tbuss_1358873839_biz@hotmail.com';

// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST") die ("No Post Variables");

// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
//$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result=$curl_err='';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER , 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);

$req = str_replace("&", "\n", $req);  // Make it a nice list in case we want to email it to ourselves for reporting

// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
    $req .= "\n\nPaypal Verified OK";
    mail("eagleeyes26@hotmail.com", "IPN interaction verified keep going", "$req", "eagleeyes26@hotmail.com" );

} else {
    $req .= "\n\nData NOT verified from Paypal!";
    mail("eagleeyes26@hotmail.com", "IPN interaction not verified", "$req", "eagleeyes26@hotmail.com" );
    exit();
}

/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
1. Make sure that business email returned is your business email
2. Make sure that the transaction�s payment status is �completed�
3. Make sure there are no duplicate txn_id
4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */

// Check Number 1 ------------------------------------------------------------------------------------------------------------
if ($bussines_email != $_POST['receiver_email'])
{
    $message = "Investigate why and how receiver email is wrong. Email = " . $_POST['receiver_email'] . "\n\n\n$req";
    mail("eagleeyes26@hotmail.com", "Receiver Email is incorrect", $message, "From: eagleeyes26@hotmail.com" );
    exit(); // exit script
}

// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
    // Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}
else
    {
        $message = "Payment status is completed = " . $_POST['payment_status'] . "\n\n\n$req";
        mail("eagleeyes26@hotmail.com", "Payment status is completed", $message, "From: eagleeyes26@hotmail.com" );
        exit(); // exit script
    }

A: have you uploaded your files on a free weberver? or free domain? this happened to me, when i tried my ipn script stored on 000webhost, i transfer my files on other webserver, and to my surprise, the ipn simulator sucessfuly sends an ipn to my ipn handler page

A: Paypal IPN simulator does not work for me. I have used two different servers, logged to an external linux server (in an another country) and wgetting handler urls work fine. Using simulator nothing is received and simulator page prints "IPN Delivery Failed:I/O error: Connection timed out; nested exception is java.net.ConnectException: Connection timed out" after a while.
Handler url is tomcat jsp page, using ip and hostname does not help.
https://developer.paypal.com/webapps/developer/applications/ipn_simulator
http://111.222.333.444:8080/testing/paypal_IPN.jsp
http://myserver.com:8080/testing/paypal_IPN.jsp

If calling paypal_IPN.jsp myself in a browser it calls https://www.sandbox.paypal.com/cgi-bin/webscr url with cmd=_notify-validate& param and jsp reads INVALID string reply as was expecting 'cause this was a foodoo transaction anyway.
Test merchant account has IPN enabled, IPN history displayes transactions, tried resending a transaction, all fails. Big showstopper for my Paypal integration test case, cannot go live without able to verify a checkout pipeline.
IPN is enabled in merchant test application but this should not affect IPN simulator anyway. Using POSTFORM classic submit cgibin button goes fine, test visa payment ok, but even then IPN handler url is not invoked. IPN history shows transactions with failed status.
https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_profile-ipn-notify
https://www.sandbox.paypal.com/cgi-bin/webscr


text:
Q: getting updateable time in android How can I get time in android that changes automatically when phone's time change
I use this code but it doesn't update (I use that in a widget)
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
int hour = today.hour;
String hh = Integer.toString(hour);

int minute = today.minute;
String mm = ":" + Integer.toString(minute);

and here is my widget codes
android widget doesn't update

A: use Calendar.getInstance to get the current date and time from the system.

A: To update time every second
final  Calendar c = Calendar.getInstance();

TimerTask task = new TimerTask() {
@Override
public void run() {
     int hh = c.get(Calendar.HOUR);
     int minute = c.get(Calendar.MINUTE);
     String mm = hh+":"+mm; // updated time
    }
};
Timer timer = new Timer("mytimer");
timer.schedule(task ,1000, 1000); //

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get index of selected Ext.form.field.PickerView item? How I can to get index of selected Ext.form.field.PickerView item?
I am trying to use it:
Ext.define('Bind.CL.FormD.view.MyCombo', {
    extend: 'Ext.form.field.Picker',
alias: 'widget.mycombo',

...something code...

this.on('expand', function () {
            var combo = Ext.ComponentQuery.query('mycombo')[0];
            var value = combo.getValue(); //or getRawValue();
        }, this);

But it doesn't work..

A: You can use indexOf() function:
Please Check Fiddle : https://fiddle.sencha.com/#fiddle/1i0o
Ext.application({
name: 'Fiddle',

launch: function() {
    simpsonsStore = Ext.create('Ext.data.Store', {
    storeId : 'simpsonsStore',
    fields : ['id','name', 'email'],
    data : [
        {name : 'Lisa',email : 'lisa@simpsons.com',id:1},
        {name : 'Bart', email : 'bart@simpsons.com',id:2},
        {name : 'Homer', email : 'homer@simpsons.com',id:3},
        {name : 'Marge',email : 'marge@simpsons.com',id:4}
    ]
});

     Ext.create('Ext.form.field.ComboBox', {
        emptyText: "Hello",
        growMax: 10,
        valueField: 'id',
        store:simpsonsStore,
        displayField: 'name',
        editable: false,
        queryMode: 'local',
        renderTo: Ext.getBody(),
        listeners:{
             change:function(combo){
                 console.log(combo.store.indexOf((combo.store.getById(combo.value))));
             }
         }
    });
}
});

A: My solution:
this.on('expand', function () {
        var combo = Ext.ComponentQuery.query('mycombo')[0],
            value = combo.getValue(),
            root = value.store.tree.getRootNode(),
            record = root.childNodes,
            currentValue = combo.getValue().data.Code,
            index = 0;

    Ext.each(record, function(element) {
        var data = element.getData();

        if (data.Code === currentValue) {
            return false;
        }

        index++;
    });


text:
Q: How do I see a list of every cookie (including contents) for any domain in Chrome/Firefox/Safari? I know how to see the list of cookies for the current site, but sometimes I want to see cookies for other sites.
Inside Google Chrome, I can see which sites I have cookies stored for, but I cannot see their contents.
How do I see a list of every cookie (including contents) for any site (domain) in Chrome/Firefox/Safari?


text:
Q: Loader scripts for ARM STR7xx I'm trying to program ARM using Eclipse + CDT + yagarto (gnu toolchain) + OpenOCD. In several sample projects (from yagarto site for example) I found linker scripts (*.ld) where a lot of linking information specified (along with sections definitions). Actually I haven't faced this files before (IAR doesn't need them), and I find them somewhat difficult to understand from a first glance. So my question is can I use one single such script file for my target processor (STR710FZ2T6) with all my projects or I have to get familiar in writing this scripts and write them for each project. If I can use single file for all projects for particular target processor can you please advice where I can find such universal one.

A: My guess is every third person has a different script or solution.  There are a number of problems that have to be solved, different linkers are going to solve those in different ways.  I think GNU has made it way too difficult if not black magic.
For an embedded system you are often going to have a flash or eeprom or some other form of read only memory to boot from.  Like other processors the ARM has a vector table to tell it essentially where the reset code is and interrupt, etc.  So that table has to be in a specific place and you have to tell the linker to put it in that specific place (first).
One of the scripts I like to use is:
MEMORY
{
    bob (RX) : ORIGIN = 0x0000000, LENGTH = 32K
    joe (WAIL) : ORIGIN = 0x2000000, LENGTH = 256K
}

SECTIONS
{
    JANE : { startup.o } >bob
}

I usually use ram and rom as names instead of bob and joe but demonstrating here that it doesnt matter what the names are they are just labels.
Another variation on the theme:
MEMORY
{
    rom(RX)   : ORIGIN = 0x00000000, LENGTH = 0x8000
    ram(WAIL) : ORIGIN = 0x20000000, LENGTH = 0x2000
}

SECTIONS
{
    .text : { *(.text*) } > rom
}

The first one allows you to put the files on the linker command line in any order but you have to have the vector table in the startup.o file.  The latter lets you use whatever filenames but the first file on the linker script needs to have the vector table.
arm-thumb-elf-gcc -Wall $(COPS) vectors.o putget.o blinker2.c -T memmap -o blinker2.elf

Or with ld directly
arm-thumb-elf-ld vectors.o putget.o blinker2.o -T memmap -o blinker2.elf

The RX tells the linker to put read and execute stuff in that memory section and the WAIL is basically everything else.  If you only have one ram for example you can put all the flags RXWAIL on the line that tells where the ram is.  Depending on your loader in that case you can rely on the elf file telling the loader where to branch to to start or you can simply make the entry point the beginning of the binary and the loader can be simpler. The arms (not the cortex-m3) have a branch instruction as the first vector for the reset vector so you can just pretend to build a vector table anyway for a ram solution and will just work.
The are a number of problems with this solution that dont happen to bother me.  I initialize variables in my code, not during declaration.
This
int rx;

int main ( void )
{
  rx = 7;

instead of
int rx=7;

int main ( void )
{

I also never assume that a variable is zero when the code starts I always initialize it to something before I start.  Your startup code plus linker script as a team can work together to make it easier to automate the resetting of the bss code and copying non-zero init data from rom to ram on boot.  (that int rx=7; above requires some code that copies the value 7 from somewhere in rom and writes it to the memory location in ram allocated for the variable rx so that when main() starts the 7 is there.
My boot code is also quite simple as a result of this method:
.globl _start
_start:
    b reset
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang
    b hang

hang : b hang

reset:
    ldr sp,=0x10004000
    bl main
    b hang

You are going to see or read about solutions that allow the startup code and the linker script to work together to not have to hardcode stack pointers, heap space, things like that, again you can put a lot of work into complicated startup code and linker scripts to gain some automation and perhaps save some work, perhaps not.  The automation, if/when working can and will reduce human error and that can be a good thing, also if you are switching chips often or trying to write one bit of code that works in a family of chips you may want this automation as well.
My bottom line is YES you can live with only one linker script for all of your ARM work.  But you have to tailor your work to that script.  You are likely not going to find one script that works with everyones example code.  The more complicated the script the harder it will be to borrow.  Yes, my scripts above can likely be done on the ld command line, but way back when (gcc 2.95) I couldnt get that to work so developed the minimal script above and have been using them ever since.  Had to modify to the second script for some reason but with 4.x.x, certainly 4.4.x I am able to use either one.

A: There is not a universal linker script. These scripts are very important, since they define where in memory (RAM or ROM) the various data and program sections will be placed. There is something equivalent in IAR compilers (xcl files if I remember correctly). You've obviously only used the default ones until now.
There is a nice document about STR7xx called "Using Open Source Tools for STR7xx Cross
Development". You can find a link in yagarto homepage. I recommend that you have a look at it and try to understand how linker files work. There are also some other configuration files that you need to have some understanding of.


text:
Q: Log-In Page Mystery ASP.Net C# I've got a bit of a mystery on my hands and I'm hoping you all can help me figure it out.
I'm creating a log-in page for an Asp.net C# web app. The log-in page is just a simple web form page with two textboxes for inputting username and password (with naming labels), a log-in button, and a hidden message label that is displayed via the back code, if I need it.
The event handler for the log-in button is two parts.
First it queries the database and pulls the fields userName, password, and userAccessLvl, from the table in my DB, where userName and password match the text inputs from the textboxes. Pretty straightforward.
Up to this point, the code works just as it is intended to do.
Now comes the second part.
When the DB is queried and the matching record is found, I have that record populated into a dataset and I set a string variable called AccessLevel to equal the value of the userAccessLvl field from the DB table. I then run a switch statement to evaluate the value.
If the value = "A" (for admin) then the log-in page should redirect the user to the admin page.
If the value = "S" (for standard user) then the log-in page should redirect the user to the customer account page.
In addition, both options will set Session variables called UserName and AccessLevel.
Now here is the mystery. If I attempt to log in with any of the standard user accounts in the DB, then everything works out just fine. However if I attempt to log in as the admin account, then the log-in page simply refreshes and it doesn't redirect me anywhere.
Code for the event handler follows.
Any thoughts? I'm running VS 2015 Community and Access 2010 DB if it matters.
Thanks.
public partial class logIn : System.Web.UI.Page
{
private OleDbConnection connection = new OleDbConnection();
private dsUserLogIn LogInData;
private OleDbDataAdapter sqlDA;
private string AccessLevel;

protected void Page_Load(object sender, EventArgs e)
{
    connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\\Documents\\Visual Studio 2015\\WebSites\\OneStopFurniture\\App_Data\\OneStopFur.accdb";

}

protected void btn_LogIn_Click(object sender, EventArgs e)
{

    sqlDA = new OleDbDataAdapter("SELECT userName, [password], userAccessLvl FROM [userInfo] WHERE userName ='" + txtUserName.Text + "' AND [password] ='" + txtPassword.Text + "'", connection);
    LogInData = new dsUserLogIn();
    sqlDA.Fill(LogInData.userInfo);

    if(LogInData.userInfo.Count == 1)
    {
        lblLogInMessage.Visible = true;
        lblLogInMessage.Text = "Username and Password are correct.";
    }
    else
    {
        lblLogInMessage.Visible = true;
        lblLogInMessage.Text = "Username and Password are not correct.";
    }

    AccessLevel = LogInData.userInfo[0].userAccessLvl.ToString();

    switch (AccessLevel)
    {
        case "A":

            Session["UserName"] = txtUserName.Text;
            Session["AccessLevel"] = "A";
            Response.Redirect("adminArea.aspx");
            break;

        case "S":
            Session["UserName"] = txtUserName.Text;
            Session["AccessLevel"] = "S";
            Response.Redirect("customerAcctArea.aspx");
            break;

        default:
            break;
    }
}

}
EDIT----------------------------------------------------
Ok.
I've set a break in the code to check the value of AccessLevel when the admin record is found. AccessLevel is set to "A"; just like it supposed to.
I also set a break after Session["AccessLevel"] = "A" and checked that value. Again the value is set to "A"; just as intended.
Finally, I checked my web.config file and couldn't find anything restricting access to any pages.
This got me to wondering if the problem might not lay in the Page_Load function of the different account pages, instead of the log-in page. The Page_Load function for both the customer account and the admin pages contain an identical code block
protected void Page_Load(object sender, EventArgs e)
{
    if(Session["AccessLevel"] == null)
    {
        Response.Redirect("login.aspx");
    }
    else
    {
        lblWelcome.Text = "WELCOME BACK " + Session["UserName"];
    }
}

Now again, for the standard user ("S") accounts, everything works fine. It's the admin ("A") accounts that are not working.
A little Google research suggests that ASP.net doesn't like identical code like this on multiple pages and that it can cause unintended functions.
Now the session object appears to be persisting between the pages of the site like it is supposed to, as I've checked other working pages and all attempts to read the current session object match the record of the account that is currently logged in.
Do you think, that since the code blocks on the two pages are identical, that it's possible for the Page_Load code on the admin page to read the session object as null (even though it isn't) and then redirect me back to log-in??
Would creating a separate class file for the code block be a possible work around?
Or would I simply be taking a long way around to get back to the same problem?
Just throwing some ideas out there, trying to wrap my head around this one.
Thanks for any help provided.

A: Besides what other have mentioned about the flaw in design, you have a case for A and S and nothing in the default. What is most likely happening is the A case is never hit and you are going to the default which is why you stay on the same page. Debug to check what your access level is when you think it should be an A.
//set breakpoint here to make sure you get an A
AccessLevel = LogInData.userInfo[0].userAccessLvl.ToString();

    switch (AccessLevel)
    {
        case "A":

            Session["UserName"] = txtUserName.Text;
            Session["AccessLevel"] = "A";
            Response.Redirect("adminArea.aspx");
            break;

        case "S":
            Session["UserName"] = txtUserName.Text;
            Session["AccessLevel"] = "S";
            Response.Redirect("customerAcctArea.aspx");
            break;

        default:
            break; //you are just falling through to here, not redirecting.
    }


text:
Q: Safari doesn't preserve image aspect ratio in flexbox context In this example the "SQUARE" image is 225x225. When its height is scaled to fit the yellow flex container, Chrome maintains its aspect ratio but Safari does not. (Codepen)
Is there a (pure CSS) way to make it work in Safari? (The image size must continue to depend on its parent's height.)
Correct (Chrome):

Incorrect (Safari):

#green {
  display: flex;
  height: 200px;
  width: 300px;
  padding: 20px;
  background: green;
}

#blue {
  flex-grow: 1;
  background: blue;
}

#yellow {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
  background: yellow;
}

img {
  height: 45%;
}

These ideas didn't work: aspect-ratio: 1 / 1, object-fit: scale-down (from this question); align-items: flex-start, object-fit: contain (from this question).


text:
Q: Where to catch exception in WebClient method? I'm developing app which connects to service and consume some JSON data. Consuming works great (JSON.net rocks) but I wonder where I should catch exception error annd show simple MessageBox? Tried in few places but still my app is closing. Or maybe I should do it based on json response which contain error tag? I think that normal error handling could be easier, but have blank spot in my mind now..
Code is below:
private void LoginLoginButton_Click(object sender, System.EventArgs e)
        {
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
            ProgressOverlay.Show();
            GenerateLoginString();
            var w = new SharpGIS.GZipWebClient();

            Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
              .Subscribe(r =>
              {

                  var settings = IsolatedStorageSettings.ApplicationSettings;

                  var deserializedRootObject = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);

                  UserSettings us = new UserSettings()
                  {

                          first_name = deserializedRootObject.user.first_name,
                          last_name = deserializedRootObject.user.last_name,
                          user_id = deserializedRootObject.user_id,

                    };
                    settings.Add("UserSettings", us);
                    settings.Save();
              });
            w.DownloadStringAsync(new Uri(UserUri));
            w.DownloadStringCompleted += new DownloadStringCompletedEventHandler(w_DownloadStringCompleted);

        }

        void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

A: If you mean you want to catch an exception which occurs in your web client call then it should be in the Error property of DownloadStringCompletedEventArgs.
void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if(e.Error != null)
    {
        MessageBox.Show("An error occurred!");
    }
    else
    {
        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
    }
}

A: Solved!
I used try and catch in this case. Works perfect :)


text:
Q: Cocos2d Scrolling game TileMap Collision I have different tile layers that I move at different speeds, my player is fixed in place(horizontally). Now how do I detect that my player is colliding width a tile? How do I know the coordinates of the tiles in the different layers?

A: I figured this out with the help of this tutorial http://paulsonapps.wordpress.com/2010/03/12/tutorial-1-tilemap-with-collision-game-cocos2d/
-(void)handleCollision
{
    for (CCTMXLayer *lr in layers) {
        // Determine the four corners of my player
        int tlXright = floor(player.playerSprite.position.x+player.playerSprite.contentSize.width-lr.position.x);
        int tlXleft = floor(player.playerSprite.position.x-lr.position.x);
        int tlYup = floor(player.playerSprite.position.y+player.playerSprite.contentSize.height);
        int tlYdown = floor(player.playerSprite.position.y);

        //Convert our Map points
        CGPoint nodeSpace1 = [tileMap convertToNodeSpace:ccp(tlXright,tlYdown)];
        pos1X = floor(nodeSpace1.x / tileMap.tileSize.width);
        pos1Y = floor(tileMap.mapSize.height - (nodeSpace1.y / tileMap.tileSize.height));

        CGPoint nodeSpace2 = [tileMap convertToNodeSpace:ccp(tlXright,tlYup)];
        pos2X = floor(nodeSpace2.x / tileMap.tileSize.width);
        pos2Y = floor(tileMap.mapSize.height - (nodeSpace2.y / tileMap.tileSize.height));

        CGPoint nodeSpace3 = [tileMap convertToNodeSpace:ccp(tlXleft,tlYdown)];
        pos3X = floor(nodeSpace3.x / tileMap.tileSize.width);
        pos3Y = floor(tileMap.mapSize.height - (nodeSpace3.y / tileMap.tileSize.height));

        CGPoint nodeSpace4 = [tileMap convertToNodeSpace:ccp(tlXleft,tlYup)];
        pos4X = floor(nodeSpace4.x / tileMap.tileSize.width);
        pos4Y = floor(tileMap.mapSize.height - (nodeSpace4.y / tileMap.tileSize.height));

        unsigned int gid5 = [lr tileGIDAt:ccp(pos1X,pos1Y)];
        unsigned int gid6 = [lr tileGIDAt:ccp(pos2X,pos2Y)];
        unsigned int gid7 = [lr tileGIDAt:ccp(pos3X,pos3Y)];
        unsigned int gid8 = [lr tileGIDAt:ccp(pos4X,pos4Y)];

        //NSLog(@"gid5:%d gid6:%d gid7:%d gid8:%d",gid5,gid6,gid7,gid8);
        / NSLog(@"pos1x:%d pos1y:%d pos4x:%d pos4y:%d",pos1X ,pos1Y,pos4X,pos4Y);
        if (gid5 == 5) {
            [lr removeTileAt:ccp(pos1X,pos1Y)];
        }

        if (gid6 == 5) {
            [lr removeTileAt:ccp(pos2X,pos2Y)];

        }

        if (gid7 == 5) {
            [lr removeTileAt:ccp(pos3X,pos3Y)];
        }

        if (gid8 == 5) {
            [lr removeTileAt:ccp(pos4X,pos4Y)];
        }
    }
}

to know the coordinate of the tile, i subtracted the layer position to the position of the player

int tlXright = floor(player.playerSprite.position.x+player.playerSprite.contentSize.width-lr.position.x);

and converted it like in the tutorial.

CGPoint nodeSpace1 = [tileMap convertToNodeSpace:ccp(tlXright,tlYdown)];
    pos1X = floor(nodeSpace1.x / tileMap.tileSize.width);
    pos1Y = floor(tileMap.mapSize.height - (nodeSpace1.y / tileMap.tileSize.height));

    ...


text:
Q: Trying to remember the name of a book I read in the 90s So this is going to be the worst description in the history of any book description ever, but when I was a young teenager I read a sci fi book that I haven't been able to remember the name or author of since.  It has been like 15 years and I was a kid so my memory of it is so shakey, but I really enjoyed it and would like to find it again.
It started with a man crash landing on a planet where there is a big order of priests that operate keeping peace in the kind of psychic overworld.  He ends up getting sucked into the rescue of one of them and marries her.  Since she's married she can't be part of the order any more but she was some sort of royalty so they just go to live with her twin sister and her husband.  A good deal of the book is in regards to their relationships and him having culture shock, but at the end they fight some kind of big threat with her psychic powers.
It starts out sci fi but reads like a fantasy book.  Anyone who can help it would be greatly appreciated.

A: Sounds like marion zimmer Bradley's Darkover novel

A: It could be The Spell Sword by Marion Zimmer Bradley, part of the Darkover series, (details below) or its sequel The Forbidden Tower.

Callista, a Keeper at Arilinn Tower, has been abducted and confined so that she cannot reach even her twin sister Ellemir telepathically. The only person she can reach is a Terran, Andrew Carr, who has no idea what is going on. His search for his "ghost-girl" crash-lands him in the mountains, an experience he barely survives.
Meanwhile Ellemir has sent for her kinsman, Damon Ridenow, a sorcerer trained at Arilinn, to find and rescue Callista. Damon, however is no swordsman; the person for that job would be the girls' father, who has just been crippled by a Cat-men attack. All three men are needed to rescue Callista, and they will need to harness the magic of the spell sword to succeed.


text:
Q: Bootstrap collapsed navbar showing empty When I click on the hamburger menu in my nicely collapsed bootstrap navbar on my phone, the layout slides to the side as expected, but shows me an empty white (or whatever body background colour I have) bar instead of the navigation. Closer inspection with firebug showed that upon clicking the button, some classes got changed on the navbar-collapsebut it remains tagged as invisible.
I have recompiled Bootstrap from LESS to change the point at which it collapses, but the issue seems persistent even with 'vanilla' bootstrap.
Code:

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-example-2">
        Toggle navigation

      </button>
      De Fijnkost

            Fijne Vleeswaren

            Bereide Gerechten

            Eigen salades

            Kazen & Kaasschotels

            Belegde Broodjes

            Contact

            Nieuws

            Bestel

                Kaasschotel

                Broodjes

Same thing happens on pages without the transparent or navbar-fixed-top class. transparent is added by my CSS. Page is visible on defijnkost.be

A: Your .navbar-collapse is set to display: none !important as far as I can see.
If you set it to display: block in your mobile view media query it should show up just fine.


text:
Q: Filtering PXselector with search I have a custom grid using a custom dac that I have declared. Originally i had a PXselector attribute set to POOrder.orderNbr
With this selector it grabs all POOrders in my grid selector
 [PXDBString(50, IsKey = true, IsUnicode = true, InputMask = "")]
    [PXSelector(typeof(POOrder.orderNbr))]
    [PXUIField(DisplayName = "Po#")]
    public string Po { get; set; }

    public class po : IBqlField { }

But i want the selector to filter POOrders that appear on the Document details->POReceiptLine. I attempted to filter using the Search but only get the lowest value POOrder.ordnbr on the receipt. The images below should illustrate what I mean. I want it to show all POOrder.orderNbr but it's only retrieving the first lowest value order.
[PXDBString(50, IsKey = true, IsUnicode = true, InputMask = "")]
 [PXSelector(typeof(Search<POOrder.orderNbr,Where<POOrder.orderNbr,Equal<Current2<POReceiptLine.pONbr>>>>))]
[PXUIField(DisplayName = "Po#")]
public string Po { get; set; }
  public class po : IBqlField { }

A: I believe it would be much better if you inner join POReceiptLine DAC, and then aggregate associated Purchase Orders to eliminate possible duplicates:
[PXSelector(typeof(Search5<POOrder.orderNbr,
    InnerJoin<POReceiptLine, On<POReceiptLine.pOType, Equal<POOrder.orderType>,
        And<POReceiptLine.pONbr, Equal<POOrder.orderNbr>,
        And<POReceiptLine.receiptNbr, Equal<Current<POReceipt.receiptNbr>>>>>>,
    Aggregate<GroupBy<POOrder.orderType,
        GroupBy<POOrder.orderNbr>>>>))]

A: The main issue in the selector is that you are looking for POOrder where the order Number equals the current Receipt Line. That means that depending the line selected, the value will change but will always yield only one result. The solution would then be to change the condition to be on the Purchase Receipt document instead.
To do so you have two options. Either you search directly POReceiptLine.poNbr, but then your selector will display columns from that table, or you join POOrder to POReceiptLine.

*

*With search on POReceiptLine

[PXSelector(typeof(Search<POReceiptLine.pONbr,
    Where<POReceiptLine.receiptType,
        Equal<Optional<POReceipt.receiptType>>,
    And<POReceiptLine.receiptNbr,
        Equal<Optional<POReceipt.receiptNbr>>>>>), DirtyRead = true)]

*With search on POOrder

[PXSelector(typeof(Search2<POOrder.orderNbr,
        InnerJoin<POReceiptLine, On<POReceiptLine.pOType,
            Equal<POOrder.orderType>,
        And<POReceiptLine.pONbr,
            Equal<POOrder.orderNbr>>>>,
        Where<POReceiptLine.receiptType,
            Equal<Optional<POReceipt.receiptType>>,
        And<POReceiptLine.receiptNbr,
            Equal<Optional<POReceipt.receiptNbr>>>>>))]

Also notice the parameter DirtyRead = true. This parameter will tell the selector to get it's information in the cache and not only from the Database. Because you are selecting something from the same page, you would need to save the whole document before being able to select the record otherwise. Unfortunatly it would not work with the second option because the Join is done at the database level.


text:
Q: How to persist the SelectedValue in a GridView when the rows are updated I have a parent GridView that is bound to an EntityDataSource with a child DetailView.
The child DetailView is bound to the parent by an EntityDataSource, with a ControlParameter as WhereParameter that points to the parent GridView.
When a user selects a row in the GridView, the DetailView is updated with the correct values.
The views are in an UpdatePanel and by entering a value in a TextBox, the user can search through records from the parent GridView. When a user selects a record in the parent view (say row index 1), the child is updated. But if the user starts a search now, the row on index 1 gets a different SelectedValue, so the DetailView is updated.
I want to persist the SelectedValue when a user selects a record.
Can I prevent the GridView SelectedValue from changing, when a user starts a search?

A: I didn't understood ver well, is this helping you?

EnablePersistedSelection="true"

Enable this on GridView


text:
Q: How to fix std::shift_right not functioning properly with 2 element std::vector I am currently working on a Snake game, everything functions as it should except the vector containing the snake body positions. The head of the snake should be the only initial element and after an apple has been eaten a new body part is added along with a trailing tail.
To move the snake body positions so it looks like they are part of the snake I use std::shift_right which works very well except for the first body part added. When the first part is added it is always inside the head/front of the vector. This makes it look like the snake has no growth/parts that follow.
As soon as the second apple is eaten the snake gets a 'tail'. The snake_body vector has now 3 elements while visually only having 2 on the game screen.
One apple has been eaten (snake_body is 2 long) but no tail
 Two apples have been eaten (snake_body is 3 long) but has 1 part following instead of 2
How do I fix this?
(Thankyou in advance)

Related sample code:
std::vector <SDL_Point> snake_body = { SDL_Point(_PLAYER_START_POS) };

void Player::Movement()
{

        switch (active_valid_input)
        {
        case SDLK_UP:

            snake_body.front() = snake_body.front() + _MOVEMENT_UP;
            break;

        case SDLK_DOWN:

            snake_body.front() = snake_body.front() + _MOVEMENT_DOWN;

            break;

        case SDLK_RIGHT:

            snake_body.front() = snake_body.front() + _MOVEMENT_RIGHT;

            break;

        case SDLK_LEFT:

            snake_body.front() = snake_body.front() + _MOVEMENT_LEFT;

            break;

        default:
            break;
        }

    std::shift_right(snake_body.begin(), snake_body.end(), 1);
}

void Player::AddSnakePart() noexcept{

    snake_body.push_back(snake_body.back());

}

A: You need to break up your movement, such that the shift happens between calculating the next head position, and assigning that position to head. At the moment your movement function leaves the head part in a moved-from state.
void Player::Movement()
{
    SDL_Point next_head;
    switch (active_valid_input)
    {
    case SDLK_UP:

        next_head = snake_body.front() + _MOVEMENT_UP;
        break;

    case SDLK_DOWN:

        next_head = snake_body.front() + _MOVEMENT_DOWN;

        break;

    case SDLK_RIGHT:

        next_head = snake_body.front() + _MOVEMENT_RIGHT;

        break;

    case SDLK_LEFT:

        next_head = snake_body.front() + _MOVEMENT_LEFT;

        break;

    default:
        break;
    }

    std::shift_right(snake_body.begin(), snake_body.end(), 1);

    snake_body.front() = next_head;
}

Aside: I would extract that switch into a function:
SDL_Point Player::Direction()
{
    switch (active_valid_input)
    {
        case SDLK_UP: return _MOVEMENT_UP;
        case SDLK_DOWN: return _MOVEMENT_DOWN;
        case SDLK_RIGHT: return _MOVEMENT_RIGHT;
        case SDLK_LEFT: return _MOVEMENT_LEFT;
    }
}

void Player::Movement()
{
    SDL_Point next_head = snake_body.front() + Direction();
    std::shift_right(snake_body.begin(), snake_body.end(), 1);
    snake_body.front() = next_head;
}

A: The issue was a simple matter of when I actually shifted the snake_body vector, I moved the std::shift_right before I applied the change to the front() position, it now functions properly.


text:
Q: SQL Server Space Reclaim We have a sizeable SQL Server 2016 database (running on Windows 2016 Datacenter). A table was growing exponentially due to a bad SQL process.  The bad SQL process has been resolved, but the specific table is still large, and the database instance grabbed a lot of space on the server.  That is, the database instance's physical size is very large.
We need to reduce the physical size and "shrink database" is not recommended by many because of the fragmentation it causes.  To process this while keeping everything on the same server, is the best thing to:

*

*Deal with specific table
a) Create a script that will build a new table and copy records from original table.  But not copy excessive records created by bad SQL process.
b) Then delete the original table and rename the new table.

*Deal with general database
c) Create a script to clone the database schema and use this to create a new database.
d) Then script the data in chunks from the current database to the new database (because data is extensive).
e) Drop the current database and rename the new one.
However, if space is an issue on the server to achieve this, could I:
f) Script the entire database WITH SCHEMA and DATA
g) Drop the current database
h) Use script to rebuild the entire database

A: Delete the extra data out of regular business hours, then shrink the database. Don't overcomplicate things.
Andy Mallon explains how in the post How to shrink a database in 4 easy steps:

*

*First you'll get the file sizes for the databases on your instance, using the sys.database_files system view.

*Then using DBCC SHRINKFILE, you'll shrink each file in question.

*Finally, you'll rebuild all your indexes to ensure any fragmentation is handled.

A: Do you have the space on the server for your #1 option?
If so, then I would do that, making sure all recent activity is in your new table before dropping and renaming. I would definitely try to do it during an outage so that you're not at risk of missing records or errors during the transition, if possible. Also, if the database is in the FULL recovery model, you might consider looping your table inserts with log backups if it will be a large amount of data you are keeping.

A: Here is an alternative I suggest.

*

*DELETE the unwanted records in a chunk (5k, 10k, 20k) not to cause significant blocking.

*Then, take a maintenance window to shrink the database in a chunk to an acceptable size by slowly increasing the chunk size.


text:
Q: Training loss and accuracy remain the same as well as validation accuracy I am trying to train a CNN model with two inputs, but I notice that accuracy for both training and validation remain high and constant. There is probably something wrong with my code. Any help to solve this is welcome.
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Dropout, concatenate
from tensorflow.keras.layers import Embedding, LSTM, GlobalMaxPooling1D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Bidirectional

input_text = Input(shape=(100,), dtype='int32', name='input_text')
meta_input = Input(shape=(2,), name='meta_input')
embedding = Embedding(input_dim=len(tokenizer.word_index) + 1,
                  output_dim=300,
                  input_length=100)(input_text)

lstm = Bidirectional(LSTM(units=128,
                      dropout=0.9,
                      recurrent_dropout=0.9,
                      return_sequences=True),
                 merge_mode='concat')(embedding)
pool = GlobalMaxPooling1D()(lstm)
dropout = Dropout(0.5)(pool)
text_output = Dense(1, activation='sigmoid', name='aux_output')(dropout)

output = concatenate([text_output, meta_input])

output = Dense(n_codes, activation='relu')(output)

main_output = Dense(1, activation='softmax', name='main_output')(output)

model = Model(inputs=[input_text,meta_input], outputs=[output])
optimer = Adam(lr=.001)
model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.summary()
model.fit([X1, X2], [y],
          validation_data=([X_valid1,X_valid2], [y_valid]),
          batch_size=64, epochs=20, verbose=1)

Result:
   training rows: 11416
    validation rows: 2035
    [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
       0   0   0   0   0   0   0   0   0 158]
    Model: "model_6"

Layer (type)                    Output Shape         Param #     Connected to
input_text (InputLayer)         [(None, 100)]        0

embedding_7 (Embedding)         (None, 100, 300)     889500      input_text[0][0]

bidirectional_7 (Bidirectional) (None, 100, 256)     439296      embedding_7[0][0]

global_max_pooling1d_7 (GlobalM (None, 256)          0           bidirectional_7[0][0]

dropout_7 (Dropout)             (None, 256)          0           global_max_pooling1d_7[0][0]

aux_output (Dense)              (None, 1)            257         dropout_7[0][0]

meta_input (InputLayer)         [(None, 2)]          0

concatenate_7 (Concatenate)     (None, 3)            0           aux_output[0][0]
                                                                 meta_input[0][0]

dense_5 (Dense)                 (None, 545)          2180        concatenate_7[0][0]
Total params: 1,331,233
Trainable params: 1,331,233
Non-trainable params: 0

Train on 11416 samples, validate on 2035 samples
Epoch 1/20
11416/11416 [==============================] - 143s 13ms/sample - loss: 0.0254 - accuracy: 0.9982 - val_loss: 0.0236 - val_accuracy: 0.9982
Epoch 2/20
11416/11416 [==============================] - 143s 13ms/sample - loss: 0.0233 - accuracy: 0.9982 - val_loss: 0.0235 - val_accuracy: 0.9982
Epoch 3/20
11416/11416 [==============================] - 150s 13ms/sample - loss: 0.0233 - accuracy: 0.9982 - val_loss: 0.0233 - val_accuracy: 0.9982
Epoch 4/20
11416/11416 [==============================] - 166s 15ms/sample - loss: 0.0232 - accuracy: 0.9982 - val_loss: 0.0234 - val_accuracy: 0.9982
Epoch 5/20
11416/11416 [==============================] - 198s 17ms/sample - loss: 0.0232 - accuracy: 0.9982 - val_loss: 0.0234 - val_accuracy: 0.9982
Epoch 6/20
11416/11416 [==============================] - 236s 21ms/sample - loss: 0.0232 - accuracy: 0.9982 - val_loss: 0.0232 - val_accuracy: 0.9982
Epoch 7/20


text:
Q: Complex-analytic isometry of hyperbolic ball and half-space I'm trying to prove that the $n$-dimensional Poincaré ball and half-space models of hyperbolic space are isometric. Here the Poincaré ball $\mathbb B^n_R$ ($n$-ball of radius $R$) has the Riemannian metric
$$
h^1_R = 4R^4 \frac{(du^1)^2 + \cdots + (du^{n})^2}{\left(R^2 - |u|^2\right)}
$$
and the half-space $\mathbb H^n_R = \left\{\left(x^1, \ldots, x^{n-1}, y \right) : y > 0 \right\}$ has the Riemannian metric
$$
h^2_R = R^2 \frac{\left(dx^1\right)^2 + \cdots + \left(dx^{n-1}\right)^2 + dy^2}{y^2}.
$$
Strategy: Rewriting the coordinates in $\mathbb B^n_R$ as $(u, v)$, with $u \in \mathbb R^{n-1}$ and $v \in \mathbb R$, let $\kappa : \mathbb B^n_R \to \mathbb H^n_R$ be the generalized Cayley transform
$$
\kappa(u,v) = (x,y) = \left( \frac{2R^2 u}{|u|^2 + (v-R)^2}, \: R\frac{R^2 - |u|^2 - v^2}{|u|^2+ (v-R)^2}\right)
$$
This is a diffeomorphism, so we just need to prove it's an isometry, i.e. that $\kappa^* h^2_R = h^1_R$.
What I've tried: My reference text (Lee's "Riemannian Manifolds: An Introduction to Curvature") suggests first proving this for $n=2$ dimensions using the complex differential forms:
$$
h_R^2 = R^2 \frac{dz\, d\overline z}{(\mathrm{Im}\,z)^2} \quad \textrm{and} \quad h_R^1 = 4R^4 \frac{dw \, d\overline w}{\left(R^2 - |w|^2\right)^2}
$$
and using the fact that $F^*\left(dz\,d\overline z\right) = |F'(w)|^2dw\,d\overline w$ for any holomorphic diffeomorphism $F(w) = z$, and then proving it in higher dimensions by conjugating $\kappa$ with a "suitable orthogonal transformation" to reduce it to the $2$-dimensional case. I've succeeded in proving the $n=2$ case, but I'm having trouble with the general case.
EDIT: I've tried two different strategies, both leading to some roadblocks.
Strategy 1: I've managed to show that the differential of $\kappa$ is
$$
d\kappa_{(u,v)} = \left( \begin{array}{cc}
A(u,v) & \mathbf b(u,v) \\
-\mathbf b(u,v)^T & c(u,v)
\end{array}\right)
$$
where $A = A(u,v)$ is a symmetric $(n-1) \times (n-1)$ matrix, $\mathbf b = \mathbf b(u,v)$ is a vector in $\mathbb R^{n-1}$, and $c$ is a function from $\mathbb B^n_R$ to $\mathbb R$. If the matrices $A(u,v)$ are simultaneously diagonalizable, then there's an orthogonal matrix $Q$ that diagonalizes $A$, and I think $Q$ as a map $\mathbb C^n \to \mathbb C^n$ will do what we need to do, although some of the computational details in this case are still a little lost on me. Am I on the right track?
Strategy 2: For each $u \in \mathbb S^{n-1}$ we choose an orthogonal transformation $\tilde Q = \tilde Q_u \in SO(n-1)$ that sends $u$ to $(1,0, \ldots, 0)$. We further assume the mapping $u \mapsto \tilde Q_u : \mathbb S^{n-1} \to SO(n-1)$ is smooth. Then $Q_u := \tilde Q_u \times \mathrm{Id} : \mathbb R^n \to \mathbb R^n$ leaves the $v$-axis invariant and maps the plane $P_u$ containing the origin, $(0,v)$, and $(u,0)$ to the $(u^1, v)$-plane, which we denote $P_0$. (Note $u$ without indices represents a point in $\mathbb R^{n-1}$, whereas its components are $u^i$.) As in the $2$-dimensional case, $\kappa|_{P_0}$ maps $P_0 \cap \mathbb B_R^n$ to $P_0 \cap \mathbb H^n_R$ isometrically, and $\kappa$ maps the plane $P_u$ to itself (since the image of every point in $P_u$ under $\kappa$ is a linear combination of $(u,0) \in \mathbb S^{n-1} \times \{0\}$ and $(0,1)$). In particular, it's straightforward to show that $\kappa = Q_u^{-1} \circ \kappa \circ Q_u$ for every $u \in \mathbb S^{n-1}$. So, since $\kappa$ is a composition of isometries, $\kappa$ itself should be an isometry. But this only shows $\kappa$ is an isometry in each plane through the $v$-axis. How can we improve this to show $\kappa$ is an isometry on $\mathbb B^n_R$?


text:
Q: Any client side haml parser? I'm looking to render my haml code in client side using JavaScript. There are nice haml parsers in server side like Jade or haml.js but I don't know any haml parser/decoder in client side.
Update: Jade that is pretty much haml now supports client side.

A: After some googling I found the "client-side-haml-js" github project. Looks like it should meet your needs:

The clientside-haml-js is a compiler written in CoffeeScript that
  compiles text templates in HAML format into Javascript functions that
  generate HTML. It has been inspired by the server side haml Javascript
  project, and has been written to be feature compatible with Ruby
  server side HAML, supports all major browsers (IE 7+, Firefox 3.6+,
  Chrome 10+, Safari), have minimal runtime dependencies (only
  underscore.js, underscore.string and CoffeeScript if using
  CoffeeScript in your templates).
NOTE: The haml compiler requires a browser with a JSON parser. For
  browsers like IE7, you need to also include a JSON implementation. See
  http://www.json.org/ for more details. A JSON implementation is
  available at https://github.com/douglascrockford/JSON-js.

Example from their github page:
var fn = haml.compileStringToJs("%h1\n  %div\n    %p\n    %span");
var html = fn();

Looks like it also supports a text/haml-template method similar to jquery-templates:
<script type="text/haml-template" id="simple">
%h1
  %div
    %p
    %span
</script>

<script type="text/javascript">
    var fn = haml.compileHaml('simple');
    var html = fn();
</script>


text:
Q: GMAIL: This message has been modified to fit your screen. Tap here to show original I made fixed email template. But When I trying to test it on mobile devices in gmail (and it is happening only in gmail) it is break my layout (looks like it make my layout to fit device width like in responsive emails). There is a message : "This message has been modified to fit your screen. Tap here to show original". Is there any method to prevent this and show the original email at the beginning?

The very same question is already present at this link. But recently two or three days back gmail app is updated and this hack stopped working. Does anyone have any solution ?
Solution:

A: To show original layout need to add to the end of the email this code.

Originale Answer

A: Please add the @class which has display:none property in media query for mobile native app.

In media query add this property:
.display-mobile{display: none !important;}


text:
Q: PHP Facebook Feed with Photo (Graph API: 2.5) i try to post a feed to my wall and link it with a photo (later to the wall of a fan page).
First i post a photo (it works).
I use following parameters for photo:
[endpoint] => /me/photos
[message] => my caption
[source] => URL of the Photo
[no_story] => true

Then i post a feed with the photo to my wall and an exception is thrown.
Graph returned an error: Invalid parameter, code: 100
I use following parameters for feed:
[endpoint] => /me/feed
[message] => My Message
[object_attachment] => The id of the photo

if i remove the parameter "object_attachment" it works. In the documentation it is a valid parameter.
I don't know what i am doing wrong.
The Line of the exception:
 switch ($code) {
            // Login status or token expired, revoked, or invalid
            case 100:
            case 102:
            case 190:
                return new static($response, new FacebookAuthenticationException($message, $code));

I use Graph API Version: 2.5
https://developers.facebook.com/docs/graph-api/reference/v2.5/page/feed#publish
Solutions for my problem:
When i use the Graph Explorer i get followed error:
One or more of the given URLs is not allowed by the Stream post URL security app setting. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains. Read https://developers.facebook.com/docs/facebook-login/security/ to learn more about app settings related to security.
At this Link: https://stackoverflow.com/a/18194474/3303652 i found a solution. Go to the Facebook App. Edit its settings. On the Advanced settings page, disable the "Stream post URL security" option.


text:
Q: Access chrome://flags or chrome://gpu I am using a browser on an embedded system and I would like to check if hardware acceleration flags and so on are enabled. Usually I do this kind of checks by accessing "chrome://flags" or "chrome://gpu".
The browser is a QtWebEngine-based one. when I try to access one of those pages by using location.href I get:
"Not allowed to load local resource: chrome://flags/"
Also I am not able to open them by using an iframe
Can anyone help?
Thanks :)

A: It is not allowed to access local resources from javascript or site content like links.
Chromium issue is referred here
There is one but dangerous work around which I'm not recommending to use : providing --disable-web-security flag through QTWEBENGINE_CHROMIUM_FLAGS environmental var or as argument to the browser you are running. But it will not just allow you to open those urls but will disable lots of security features which I believe is not what you wont.

A: Complementing the answer from j2ko, to check the GPU acceleration flags, you need to:

*

*Set the environment variable with QTWEBENGINE_CHROMIUM_FLAGS=--disable-web-security

*Set the environment variable QTWEBENGINE_REMOTE_DEBUGGING=8080

*Open a Chromium Browser and access the address http://127.0.0.1:8080

*Access the console tab and enter the JavaScript command location.href = "chrome://gpu/"

*The chrome://gpu/ will open on your QT view. In case you extended the QWebEnginePage class, just ensure you not have overwritten the method acceptNavigationRequest() blocking the navigation.

Additionally, you can disable hardware acceleration by setting the QTWEBENGINE_CHROMIUM_FLAGS=--disable-gpu or QTWEBENGINE_CHROMIUM_FLAGS="--disable-web-security --disable-gpu".
Related to:

*

*https://superuser.com/questions/656687/confirm-correctly-working-of-hardware-acceleration-in-chrome-windows-7


text:
Q: Sinatra AJAX redirection, why isn't it working? It goes into the redirected URL controller but doesn't actually execute the redirect. any thoughts? I have included the TML, JS file and Ruby controller file.
controller.rb
get '/' do
  erb :welcome
end

post '/users/create' do
  byebug
  @player1 = User.new(name: params[:player1])
  @player2 = User.new(name: params[:player2])
  if @player1.save && @player2.save
      @race = Race.create
      @user_race = UserRace.create(player1_id: @player1.id, player2_id: @player2.id, race_id: @race.id)
      redirect to "/race/#{@race.id}"
  else
    @player1 = User.find_by_name(params[:player1])
    @player2 = User.find_by_name(params[:player2])
    @race = Race.create
    byebug
    @user_race = UserRace.create(player1_id: @player1.id, player2_id: @player2.id, race_id: @race.id)
    # byebug
      redirect to "/race/#{@race.id}"
  end
end

get '/race/:race_id' do
  @race = Race.find(params[:race_id])
  @user_race = UserRace.find_by_race_id(params[:race_id])
  # byebug
  @player1 = User.find(@user_race.player1_id)
  @player2 = User.find(@user_race.player2_id)
  erb :race
end

put '/race' do
  # byebug
  @race = Race.find(params[:race_id])
  @race.winner = User.find(params[:winner_id])
  @race.loser_index = params[:loser_index]
  @race.save
  redirect to "/winner/#{params[:race_id]}"
end

get '/winner/:race_id' do
  @race = Race.find(params[:race_id])
    byebug
  erb :winner
end

the JS function that is being called.
function parseWinner(player_track, loser_index) {
var race_id = $("#race").data("race-id")
var player1_id = $("#race").data("playerone-id")
var player2_id = $("#race").data("playertwo-id")
if (player_track === $cells1) {
  // debugger
  $.ajax({
    type: "PUT",
    url: "/race",
    data: {"race_id": race_id, "winner_id": player1_id, "loser_index": loser_index, "time_spent": this.time}
  }).done(function(e){
    // e.preventDefault();
    window.location = "/winner/" + race_id
  })
}
else {
  $.ajax({
    type: "PUT",
    url: "/race",
    data: {"race_id": race_id, "winner_id": player2_id, "loser_index": loser_index}
  }).done(function(e){
    // e.preventDefault();
    window.location = "/winner/" + race_id
  })
}

HTML file
<h1 id="race" data-race-id=<%= @race.id %> data-playerone-id=<%= @player1.id %> data-playertwo-id=<%= @player2.id %>>Javascript Racer

  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/style.css">

    <% 20.times do |x| %>

    <% end %>

    <% 20.times do |x| %>

    <% end %>


text:
Q: mapping a distribution to it's parameter domain The K-distribution is a special case of the variance gamma distribution, which in turn is a special case of the generalised hyperbolic distribution. The generalised hyperbolic distribution is a superclass containing the student T's distribution, Laplace distribution, hyperbolic distribution, normal inverse gaussian distribution among others.

How do we recover a simplified form of the K-distribution from an integrating an unknown $1$-parameter distribution $\varphi(s;x)$ over it's support? Does this suggest $\varphi(s,x)$ is a special case of the generalised hyperbolic distribution as well?

Let's write down the $K$ distribution and set this equal to the integral of the unknown distribution:
$$ 2\sqrt{s}K_1(2\sqrt{s})=\int_a^b \varphi(s;x)~dx $$
The LHS is just $f_S(s,1,2)$ see the link above. Also $\varphi(s,x)$ is not normalised.
The integral reminds me of something called an integral transform. I suspect what's happening is that the distribution is being mapped from it's original domain to it's parameter domain, where we obtain a new distribution, in this case the simplified version of the K-distribution.
And now the parameter for the original distribution is the variable for the K-distribution. Does that make sense, and is this useful in any way to have this connection between distributions?


text:
Q: How to Deploy Static html/js App using VSTS Continuous Integration and Azure I'm trying to deploy an Angular app to Azure Web App using VSTS Continuous Integration.
My repository doesn't contain any .sln .pdb, it's just a static web site.
I have define my build to run npm, gulp, but I don't know how to create an artifact without building the the vs solution.
I would also need to create a release task to publish the web site to azure.
Does anybody has a build definition that would work for this deployment?
Thanks

A: You can add "Copy and Publish Build Artifacts" task to copy and publish the deployment files to artifact folder that can be used in "Release Management".
And then you can enable "FTP Deployment" for your Azure Web App and use "FTP Uploader" task to publish the files to Azure.

A: I've solved this a few ways:

*

*Use azure git deploy.  https://azure.microsoft.com/en-us/documentation/articles/web-sites-publish-source-control/  I bake the git credentials into a script, and force commit and publish the site to the azure url.

*Use Publish-WebApplicationWebsite.ps1 from the Azure SDK https://azure.microsoft.com/en-us/documentation/articles/vs-azure-tools-publish-webapplicationwebsite-windows-powershell-script/  I recall handing it a folder, but it appears the current version takes in an MSDeploy package.


text:
Q: Is it reasonable to be concerned an SES object won't be available in S3? I've setup SES Rule in the following way:
Actions:
1) S3: Saves SES object to an S3 bucket
2) Lambda: Triggers my lambda function for email processing
In my testing, I've always been able to retrieve my SES object from the bucket using the messageID in the very first line of code. I'm then able to parse and read it without issue.
My question is, is it reasonable to be concerned that the SES object may not always be immediately available? I'm considering adding error handling incase the object isn't there. Basically to wait 1/2 a second and try again until the lambda times out. But I don't want to complicate the code if this is not a reasonable concern, handled by boto3, ect. Thoughts?

A: In your case, it is best to use only one S3 action configured with a notification on a SNS topic and have your Lambda subscribe to this topic.
Your Lambda will receive a SNS event containing a stringified SES event in the message:
{
    "Records": [
        {
            "EventSource": "aws:sns",
            "EventVersion": "1.0",
            ...
            "Sns": {
                "Type": "Notification",
                "MessageId": "...",
                "TopicArn": "...",
                "Subject": "Amazon SES Email Receipt Notification",
                "Message": "<STRINGIFIED SES EVENT>",
                ...
            }
        }
    ]
}

If you parse the Message, you will get something like this:
{
    "notificationType": "Received",
    "mail": {
        "timestamp": "...",
        "source": "...",
        "messageId": "...",
        "destination": [
           ...
        ],
        "headersTruncated": false,
        "headers": [
            ...
        ],
        "commonHeaders": {
            "returnPath": "...",
            "from": [
                "..."
            ],
            "date": "...",
            "to": [
                ...
            ],
            "messageId": "...",
            "subject": "..."
        }
    },
    "receipt": {
        ...
        "action": {
            "type": "S3",
            "topicArn": "...",
            "bucketName": "<YOUR_BUCKET>",
            "objectKey": "<YOUR_OBJECT_KEY>"
        }
    }
}

where you will find the exact reference to the uploaded object in your bucket (receipt.action.bucketName and receipt.action.objectKey).
With this setup, it reasonable to consider that when your Lambda is triggered the object is available.


text:
Q: Record is only update from API The record which came from Rest API should only update from API, no user can update the record manually.
for(Opportunity guestuser: trigger.new)
{
    id currentuser = guestuser.CreatedById;
                User thisUser = [select Id FROM User where Id =:guestuser.CreatedById];

    id userid=UserInfo.getUserId();
    system.debug('currentuser'+currentuser);
    if(currentuser != userid)
    {
        guestuser.addError('You cannot Update this Application.');
    }
}

A: There are 2 approaches to solve this - Assuming you have a dedicated integration user that the REST API uses.

*

*Using Sharing Rules: Set the OWD of your object to Private, and create a Sharing Rule that shares all the records created/owned by the Integration user with everyone with ReadOnly Access. While records created/owned by everyone other than the Integration user are shared with ReadWrite access.

*Use a trigger: During before or after update, check if the CreatedById's user is your integration user. If yes, check if the current user (UserInfo.getUserId()) is the same one. If not, throw an exception.

A: If I understand you correctly, you're trying to check if the user that is editing the record is:

*

*The API user and that user has created this opportunity (I think?)

*The user is not the API user and the opportunity was created by the API user
Id apiUserId = [SELECT Id FROM User WHERE Name = 'API User'].Id;
Id currentUserId = UserInfo.getUserId();

for(Opportunity opp : Trigger.new){
  if( (currentUserId == apiUserId && opp.CreatedById != apiUserId) ||
      (currentUserId != apiUserId && opp.CreatedById == apiUserId))
  {
     opp.addError('This opportunity can\'t be edited by you.')
  }
}


text:
Q: Proving a statement about $k$-colouring of a graph
Prove that a graph is $k$-colourable iff its edges can be oriented in such a way that the resulting directed graph does not contain a path of length $k$.

It seems to me that the '$\Leftarrow$' implication might be slightly easier to show if we were to consider directed acyclic graphs (then we could assign subsequent colors to vertices as we traverse along a path and do some rearranging when we visit an already coloured vertex)... But I am stuck at finding a valid argument that justifies the implication in either direction, not to mention I am actually interested in a stronger statement.

A: For the forward direction, let the colors be $\{1,2,\ldots, k\}$ and orient each edge to go from the higher color to the lower one.

A: Perhaps you could use the Gallai-Hasse-Roy-Vitaver Theorem.


text:
Q: Fragment not opening with if condition I have an if statement in when i the position 3 is selected that checks a condition of if a particular key has been stored in tinyDB(a form of shared preferences) to open a particular fragment this condition is true(i checked this with the System.out.println(tiny.getString("userSignedIn"); but the fragment does not open. The condition on position 3 in the code. Than you very much
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
        @Override
        public boolean onTabSelected(int position, boolean wasSelected) {
            switch (position){
                case 0:
                    Home home = new Home();
                    doTransation(home);
                    break;
                case 1:
                    Categories categories = new Categories();
                    doTransation(categories);
                    break;
                case 2:
                    MyDownloads myDownloads = new MyDownloads();
                    doTransation(myDownloads);
                    break;
                case 3:
                    if (getUserSignedIn.equals("Sign up Successful")){
                        UserSignedInProfile userSignedInProfile = new UserSignedInProfile();
                        doTransation(userSignedInProfile);
                    }else if (getUserSignedIn.equals("Email address or password not correct")){
                        Profile profile = new Profile();
                        doTransation(profile);
                   }
                   break;
                default:
                     Profile profile = new Profile();
                     doTransation(profile);
                     break;
            }
            return true;
        }
    });

This is the method for doTransation
 private void doTransation(Fragment fragment){
    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    fragmentTransaction.replace(R.id.parentLayout, fragment);
    moreOptions.setImageResource(R.drawable.ic_more);
    moreOptions.setVisibility(View.VISIBLE);
    text_changer.setText(R.string.app_name);
    fragmentTransaction.commit();
}

I have tried the switch statement but it still does not work

A: try
String [] posts = { "1","2","3"};
ArrayAdapter<String> adapter;
switch (position){
case 0:
break;
}

instead of  if&else
or Change the last option to }else(position == 3){
instead of }else if (position == 3){
I think he will succeed

A: So the short answer is, your if comparison isn't evaluating to try when you expect it to. That is because getUserSignedIn does not equal the String value "Sign up Successful". It is likely a typo, we all make them. If that gets you into your if statement (use a debug log or a breakpoint) then let's start checking your Fragment for issues.
But while we are at it, StackOverflow is for learning, and as you can see from your initial comments your code can use some cleaning:
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
    @Override
    public boolean onTabSelected(int position, boolean wasSelected) {

        // This is where we can start, you are instantiating a
        // fragment in your switch statement, so let's start
        // with a fragment variable that we will set in the switch
        // and pass to our method
        Fragment fragment;

        // Now in our switch statement, we simply set our fragment
        switch (position){
            case 0:
                fragment = new Home();
                break;
            case 1:
                fragment = new Categories();
                break;
            case 2:
                fragment = new MyDownloads();
                break;
            case 3:
                if (getUserSignedIn.equals("Sign up Successful")){
                    fragment = new UserSignedInProfile();
                    break; // break here so else goes to default
                }
                /* You don't need this since you are just going
                   to default to the Profile fragment
                else if (getUserSignedIn.equals("Email address or password not correct")){
                }
                */
                // Notice no break here, it is in the if condition
            default:
                fragment = new Profile();
        }

        doTransition(profile);  // I think you mean "Transition"(?)
        return true;
    }
});

Now if you want to get really fancy, and you understand and can read the code clearly, you can get all ternary up in this bad boy. Ternary operators are where you are basically saying [Thing] = (if) ? x : y; but it can be chained into crazy stuff:
Fragment fragment = position == 0 ? new Home() :
    positon == 1 ? new Categories() :
    position == 2 ? new MyDownloads() :
    position == 3 && getUserSignedIn.equals("Sign up Successful") ?
        new UserSignedInProfile() :
    new Profile();

doTransition(fragment);

Let's go even further. Are you ever going to use that fragment variable ever again? No? Why create it?
doTransition(
    position == 0 ? new Home() :
    position == 1 ? new Categories() :
    position == 2 ? new MyDownloads() :
    position == 3 && getUserSignedIn.equals("Sign up Successful") ?
        new UserSignedInProfile() :
    new Profile();
);


text:
Q: Call to undefined method App\User::messages()", exception: "BadMethodCallException I am following this library for chat and i use presence channel in it
composer require beyondcode/laravel-websockets

whenever i send a message console show me this error in my chatcontoller
Call to undefined method App\User::messages()", exception: "BadMethodCallException

my controller
class ChatController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('chats');
    }

    public function fetchMessages()
    {
        return Message::with('user')->get();
    }

    public function sendMessage(Request $request)
    {
        $message = auth()->user()->messages()->create([
            'message' => $request->message
        ]);

        broadcast(new MessageSent($message->load('user')))->toOthers();

        return ['status' => 'success'];
    }

User.php
public function messages()
    {
        return $this->hasMany(Message::class);
    }

Message.php
class Message extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'messages';

    protected $fillable = ['message'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

why my message is not delivering to other user

A: change this line
    $message = auth()->user()->messages()->create([
        'message' => $request->message
    ]);

    $user = User::find(auth()->id);
    $message = $user->messages()->create([
        'message' => $request->message
    ]);

I believe auth()->user();  is different than the User::class


text:
Q: Splitting Output Lists From A Dictionary I have a practice question which is as follows:

My code was as follows:

My Output was as follows:

How can I achieve the same formatting as it asks for in the question with each user on a new line out of its list format. I was able to iterate over val in the second code block but this created a new 'Python Coder(s)' line with Tim and Anne separated.

A: Replace your last for loop with this for loop:
for key,val in programme.items():
    val_to_print = '\n '.join(val)
    print(f"{key} Coder(s) \n {val_to_print}")

Output:
Python Coder(s)
 Anne
 Tim
Java Coder(s)
 Sue


text:
Q: Expand the combobox and its items when it gets focus I want to expand the height of the combobox whenever the combobox gets the Focus.
I have used the following code to expand the combobox height.
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform ScaleX="1" ScaleY="2" />
            </Setter.Value>
        </Setter>
        <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
        <Setter Property="Panel.ZIndex" Value="99999"/>
    </Trigger>
</Style.Triggers>
</Style>

Problem:
When i put the focus on the Combobox first time, the combobox item list opened in normal mode. But if i again click on the combobox then combobx item list opened and also list items height is expanded.
But i want the combobox list items to be expanded even in the first click (focus) also. Also combobox height must be in expanded mode even when i select the item in the Combobox item.
Thanks in advance

A: Is this what you want?
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsDropDownOpen" Value="true" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>


text:
Q: How do I insert rows in a dataframe based on sequence? So I have this dataframe. The columns 'Time' follows a sequence where there are all weeks that fall between the first and the last rows populated in the column. But one of the values i.e. W43-2021 is missing.

How do I insert a new row corresponding to W43-2021 with all the other column values be either same as others or None and 'Values' as 0. Basically like the below dataframe.

I have tried tried below approach to solve this problem.
f = int(df['Time.[Week]'][0][1:3])
l = int(df['Time.[Week]'].iloc[-1][1:3])
check = list(df['Time.[Week]'].str[1:3])
check = list(map(int, check))
c = []
for i in range(f, l+1):
    if i not in check:
        c.append(i)
for week in c:
    temp_df = pd.DataFrame(columns = df.columns)

    temp_df.loc[0, 'Time.[Week]'] = 'W' + str(week) + '-2021'

df.append(temp_df)

This doesn't seem to be the most appropriate way of dealing with the issue as order is getting broken due to appending dataframe at the end and there could be multiple missing rows which could problem later.
What could be a better and more pythonic way of handling this case?
Also find the code to initiate the df if required.
df = pd.DataFrame([[33534,9132,'Current','W41-2021',34],
              [33534,9132,'Current','W42-2021', 45],
              [33534,9132,'Current','W44-2021', 32],
              [33534,9132,'Current','W45-2021', 41],
              [33534,9132,'Current','W46-2021',49]], columns = ['Item', 'Location', 'Version', 'Time', 'Value'])

A: You can use the following:
# build missing values
weeks = df['Time'].str.extract('(?<=W)(\d+)').astype(int)
idx = [f'W{w}-2021' for w in range(weeks.min()[0], weeks.max()[0]+1)]

# add missing values
df2 = df.set_index('Time').reindex(idx).reset_index()

# ffill, except 'Value'
df2 = df2.combine_first(df2.drop(columns='Value').ffill())[df.columns]

output:
>>> df2
      Item  Location  Version      Time  Value
0  33534.0    9132.0  Current  W41-2021   34.0
1  33534.0    9132.0  Current  W42-2021   45.0
2  33534.0    9132.0  Current  W43-2021    NaN
3  33534.0    9132.0  Current  W44-2021   32.0
4  33534.0    9132.0  Current  W45-2021   41.0
5  33534.0    9132.0  Current  W46-2021   49.0

A: Use -
df['week'] = df['Time'].str[1:3].astype(int)
df2 = pd.DataFrame([ i for i in range(week.min(), week.max())], columns=['week']).merge(df, how='outer')
fill_val = df['Time'].iloc[0]
df2['Time'] = df2['Time'].fillna(fill_val[0]+df2['week'].astype(str)+fill_val[3:])
df2 = df2.fillna(0)

Output
   week      Time  Value
0    41  W41-2021   34.0
1    42  W42-2021   45.0
2    43  W43-2021    0.0
3    44  W44-2021   32.0
4    45  W45-2021   41.0
5    46  W46-2021   49.0

A: You can do like that:
Code:
df = pd.DataFrame([[33534,9132,'Current','W41-2021',34],
              [33534,9132,'Current','W42-2021', 45],
              [33534,9132,'Current','W44-2021', 32],
              [33534,9132,'Current','W45-2021', 41],
              [33534,9132,'Current','W46-2021',49]], columns = ['Item', 'Location', 'Version', 'Time', 'Value'])

new_df = df.copy(deep=True)
new_df = new_df.append(pd.DataFrame([[33534,9132,'Current','W43-2021',0]],columns=['Item', 'Location', 'Version', 'Time', 'Value']))
new_df = new_df.sort_values("Time",ascending=True)
print(new_df)

Because the time is ordered you can just append the new value and then sort the values according to the time.
Output:
    Item  Location  Version      Time  Value
0  33534      9132  Current  W41-2021     34
1  33534      9132  Current  W42-2021     45
0  33534      9132  Current  W43-2021      0
2  33534      9132  Current  W44-2021     32
3  33534      9132  Current  W45-2021     41
4  33534      9132  Current  W46-2021     49

A: Option 1 with merge() process any years with actual number of weeks, NOT keep the column type (integer becomes float)
import pandas as pd

df = pd.DataFrame([[33534, 9132, 'Current', 'W41-2021', 34],
                   [33534, 9132, 'Current', 'W42-2021', 45],
                   [33534, 9132, 'Current', 'W44-2021', 32],
                   [33534, 9132, 'Current', 'W45-2021', 41],
                   [33535, 5555, 'Current', 'W44-2022', 132],
                   [33535, 5555, 'Current', 'W45-2022', 141],
                   [33534, 9132, 'Current', 'W46-2021', 49]], columns=['Item', 'Location', 'Version', 'Time', 'Value'])

def yproc(gd):
    year = gd.Time.iloc[0].split('-')[1] # get the year from the group
    # compose a complete sequence like WNN-YYYY from all week numbers in a particular year
    ts = pd.Series([f'W{x+1:02d}-{year}' for x in pd.Series(pd.date_range(f'{year}-01-01',f'{year}-12-31',freq='W')).index],name='Time')
    d = gd.merge(ts, how='outer').sort_values('Time') # merge the df with the sequence
    d['Value'].fillna(0, inplace=True) # fill the values in the added rows
    return d.fillna(method='ffill').fillna(method='bfill') # fill other fields and return

y = df.Time.str.split('-', expand=True)[1] # make a sequence to group by year
df1 = df1 = df.groupby(y, as_index=False, group_keys=False).apply(yproc)  # grop by year and apply the function
print(df1.iloc[40:60,:])

Output:
       Item  Location  Version      Time  Value
0   33534.0    9132.0  Current  W41-2021   34.0
1   33534.0    9132.0  Current  W42-2021   45.0
45  33534.0    9132.0  Current  W43-2021    0.0
2   33534.0    9132.0  Current  W44-2021   32.0
3   33534.0    9132.0  Current  W45-2021   41.0
4   33534.0    9132.0  Current  W46-2021   49.0
46  33534.0    9132.0  Current  W47-2021    0.0
47  33534.0    9132.0  Current  W48-2021    0.0
48  33534.0    9132.0  Current  W49-2021    0.0
49  33534.0    9132.0  Current  W50-2021    0.0
50  33534.0    9132.0  Current  W51-2021    0.0
51  33534.0    9132.0  Current  W52-2021    0.0
2   33535.0    5555.0  Current  W01-2022    0.0
3   33535.0    5555.0  Current  W02-2022    0.0
4   33535.0    5555.0  Current  W03-2022    0.0
5   33535.0    5555.0  Current  W04-2022    0.0
6   33535.0    5555.0  Current  W05-2022    0.0
7   33535.0    5555.0  Current  W06-2022    0.0
8   33535.0    5555.0  Current  W07-2022    0.0
9   33535.0    5555.0  Current  W08-2022    0.0

Option 2 with concat() process any years with actual number of weeks, keep the column type (i.e. integer)
# df = ...

def yproc(gd):
    year = gd.Time.iloc[0].split('-')[1]  # get the year from the group
    # compose a complete sequence like WNN-YYYY from all actual week numbers in a particular year
    ts = pd.Series(
        [f'W{x + 1:02d}-{year}' for x in range(pd.date_range(f'{year}-01-01', f'{year}-12-31', freq='W').size)],
        name='Time')
    repeated = pd.concat([gd.take([0])] * ts.size, ignore_index=True) # replicate one row nth times depend of weeks number
    repeated.Value, repeated.Time = 0, ts # replace Value with 0, Time with ts
    d = pd.concat([gd, repeated]).drop_duplicates(['Time'], keep='first').sort_values('Time')
    return d

y = df.Time.str.split('-', expand=True)[1]  # make a sequence to group by year
df1 = df.groupby(y, as_index=False, group_keys=False).apply(yproc)  # grop by year and apply the function
print(df1.iloc[39:60, :])

     Item  Location  Version      Time  Value
39  33534      9132  Current  W40-2021      0
0   33534      9132  Current  W41-2021     34
1   33534      9132  Current  W42-2021     45
42  33534      9132  Current  W43-2021      0
2   33534      9132  Current  W44-2021     32
3   33534      9132  Current  W45-2021     41
6   33534      9132  Current  W46-2021     49
46  33534      9132  Current  W47-2021      0
...


text:
Q: Issues with webpack.config I created a small project using scrimba.com. It works fine on scrimba's browser, but when I downloaded it and tried to open it on Chrome it doesn't work (or Firefox or GitHub Pages).
The error goes as follows: .../script.pack.js net::ERR_FILE_NOT_FOUND, so I figured it has to do with my script src="script.pack.js", but can't make it work nor did I found a solution. I am new to coding and would appreciate a hand. Below are screenshots of the following files:

*

*index.html

*package.json

*webpack.conf.js


text:
Q: Show $(3,x)$ is a principal ideal in $\mathbb{Z}_{6}[x]$. Since $R[x]/(I)=(R/I)[x]$, and by the Chinese Remainder Theorem,
                $$\mathbb{Z}_6[x]/(3,x)
    \cong \mathbb{Z}_3[x]/(3,x) \times \mathbb{Z}_2[x]/(3,x)
    \cong \mathbb{Z}_3[x]/(f(x)) \times \mathbb{Z}_2[x]/(g(x))
    \cong \mathbb{Z}_3[x] \times \mathbb{Z}_2[x]/(g(x))$$
                since $\mathbb{Z}_2$, $\mathbb{Z}_3$ are fields...
is what I have so far. But I feel like it's trash.
Can anyone help me where to begin?

A: To show that an ideal is principal, you should generally proceed by constructing a generator.
In this case, we can guess that the generator is of the form $a+bx$.  By reducing modulo $2$ and $3$, we can solve for $a$ and $b$: $a+bx$ must generate the ideal $(x)$ in $\mathbb{Z}/3\mathbb{Z}[x]$ and the ideal $(1)$ in $\mathbb{Z}/2\mathbb{Z}[x]$.
Having done this, we have to show that $a+bx \in (3,x)$, and that $3,x\in (a+bx)$.


text:
Q: angular 4 route link activ for parent

{{genre}}

How to apply an active link to a very distant parent link
I want to apply it to

A: problem solved

{{genre}}


text:
Q: UDP source stream on AWS with gst_launch_parse by AWS Kinesis Video Stream SDK C I have one UDP source of video streaming which receives through ffmpeg pipeline.
ffmpeg pipeline
ffmpeg -f h264 -i pipe:0 -tune zerolatency -b 900k -framerate 30 -f h264 udp://0.0.0.0:8280

I want to stream this UDP source to AWS Kinesis Video Stream by using C SDK.
In this samples, have checked kvsWebrtcClientMasterGstSample
i try to make gst pipeline for UDP source to stream on the signaling channel as a master.
Here is the sample pipeline
pipeline = gst_parse_launch(
                    "udpsrc port=8280 ! "
                    "application/x-rtp,media=video,payload=127,encoding-name=H264 ! "
                    "video/x-h264,stream-format=byte-stream,alignment=au,profile=baseline ! appsink sync=TRUE emit-signals=TRUE name=appsink-video", &error);

The sample where i am verifying https://awslabs.github.io/amazon-kinesis-video-streams-webrtc-sdk-js/examples/index.html
It gives an error, it gets connected on the channel but not sending bytes.
Error
2023-02-07 08:23:33 VERBOSE signalingClientGetCurrentState(): Signaling Client Get Current State
[KVS GStreamer Master] sendGstreamerAudioVideo(): Failed to launch gstreamer, operation returned status code: 0x0000000c
no element "udpsrc"2023-02-07 08:23:33 INFO    onSctpInboundPacket(): Unhandled PPID on incoming SCTP message 0
2023-02-07 08:23:33 INFO    onDataChannel(): New DataChannel has been opened kvsDataChannel

2023-02-07 08:23:33 VERBOSE incomingRelayedDataHandler(): Candidate id: RB8BUX8dK
2023-02-07 08:23:33 VERBOSE incomingRelayedDataHandler(): Candidate id: c9naBHPrJ
2023-02-07 08:23:33 VERBOSE lwsWssCallbackRoutine(): WSS callback with reason 8
2023-02-07 08:23:33 DEBUG   socketConnectionClosed(): Close socket 15
2023-02-07 08:23:33 DEBUG   turnConnectionStepState(): TurnConnection state changed from TURN_STATE_CLEAN_UP to TURN_STATE_NEW
2023-02-07 08:23:33 DEBUG   socketConnectionClosed(): Close socket 16
2023-02-07 08:23:33 DEBUG   turnConnectionStepState(): TurnConnection state changed from TURN_STATE_CLEAN_UP to TURN_STATE_NEW
2023-02-07 08:23:34 DEBUG   dtlsSessionChangeState(): DTLS init completed. Time taken 300 ms
2023-02-07 08:23:34 VERBOSE onRtcpSenderReport(): RTCP_PACKET_TYPE_SENDER_REPORT 1511650952 16684651827884982909 rtpTs: 1632938338 17 pkts 13251 bytes
2023-02-07 08:23:34 VERBOSE onRtcpPacket(): unhandled packet type RTCP_PACKET_TYPE_SOURCE_DESCRIPTION
2023-02-07 08:23:34 VERBOSE stepStateMachine(): State Machine - Current state: 0x0000000000000010, Next state: 0x0000000000000010, Current local state retry count [1], Max local state retry count [0], State transition wait time [0] ms
2023-02-07 08:23:35 VERBOSE onRtcpSenderReport(): RTCP_PACKET_TYPE_SENDER_REPORT 1511650952 16684651832982138427 rtpTs: 1633045168 53 pkts 47048 bytes
2023-02-07 08:23:35 VERBOSE onRtcpPacket(): unhandled packet type RTCP_PACKET_TYPE_SOURCE_DESCRIPTION
2023-02-07 08:23:35 VERBOSE stepStateMachine(): State Machine - Current state: 0x0000000000000010, Next state: 0x0000000000000010, Current local state retry count [1], Max local state retry count [0], State transition wait time [0] ms
2023-02-07 08:23:36 VERBOSE onRtcpSenderReport(): RTCP_PACKET_TYPE_SENDER_REPORT 1511650952 16684651837546984288 rtpTs: 1633140838 86 pkts 77038 bytes
2023-02-07 08:23:36 VERBOSE onRtcpPacket(): unhandled packet type RTCP_PACKET_TYPE_SOURCE_DESCRIPTION
2023-02-07 08:23:36 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861389958257661 150818239502962 : 0 packets 0 bytes
2023-02-07 08:23:36 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861389958257661 80436394401579 : 0 packets 0 bytes
2023-02-07 08:23:36 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861390599882826 150818239516407 : 0 packets 0 bytes
2023-02-07 08:23:36 VERBOSE stepStateMachine(): State Machine - Current state: 0x0000000000000010, Next state: 0x0000000000000010, Current local state retry count [1], Max local state retry count [0], State transition wait time [0] ms
2023-02-07 08:23:36 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861390713948567 80436394410025 : 0 packets 0 bytes
2023-02-07 08:23:36 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861391150613597 80436394414905 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861391591668084 150818239537189 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE onRtcpSenderReport(): RTCP_PACKET_TYPE_SENDER_REPORT 1511650952 16684651839893496720 rtpTs: 1633189978 104 pkts 93927 bytes
2023-02-07 08:23:37 VERBOSE onRtcpPacket(): unhandled packet type RTCP_PACKET_TYPE_SOURCE_DESCRIPTION
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861392223986054 150818239550439 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861392265020172 80436394427359 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861393093626737 150818239568663 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861393386603636 80436394439894 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861393854987000 80436394445129 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861393981589751 150818239587270 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 464114683 16684861394525586014 80436394452623 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE rtcpReportsCallback(): sender report 1970552530 16684861394875625848 150818239606004 : 0 packets 0 bytes
2023-02-07 08:23:37 VERBOSE stepStateMachine(): State Machine - Current state: 0x0000000000000010, Next state: 0x0000000000000010, Current local state retry count [1], Max local state retry count [0], State transition wait time [0] ms

what's missing here?


text:
Q: Dynamically add textboxe(s) on webform with attributes.add(onload..) I have searched for similar cases but can't find any that matches mine and I'm not that good with js, jquery and general website flow to figure this out myself.
I'm dynamically adding textboxes like this:
        var nr = new System.Web.UI.HtmlControls.HtmlTableRow();
        var c1 = new System.Web.UI.HtmlControls.HtmlTableCell();
        var c2 = new System.Web.UI.HtmlControls.HtmlTableCell();
        c1.InnerText = Q.Trim(new char[] { '{', '$', '[', ']', '}' }).TrimStart(new char[] { '-' });
        c2.Controls.Add(new TextBox() { ID = "tb_" + c.ToString(), ClientIDMode = System.Web.UI.ClientIDMode.Static });
        var dateControl = c2.Controls[0] as TextBox;
        dateControl.Attributes.Add("autocomplete", "off");
        dateControl.Attributes.Add([event here], "initiateDateControl('"+ dateControl.ID + "')");

Currenty I'm using "onclick" for [event here] but I want onload or something similar.
function initiateDateControl(dateControl) {
    $("#" + dateControl).datepicker({
        dateFormat: "yy-mm-dd",
        changeYear: true
    });
}

That is because onload doesn't work but onclick works. How can I load the jquery-datepicker when the page loads?
I'm not sure if I can add a body because all the controls is inside an asp:Content.

A: A simple workaround will be give a unique CssClass for all the controls like this
c2.Controls.Add(new TextBox() {
    ID = "tb_0",
    CssClass="my_tb",
    ClientIDMode = System.Web.UI.ClientIDMode.Static });

You could then call it on DOM ready like this
$(document).ready(function () {
    $(".my_tb").datepicker({
        dateFormat: "yy-mm-dd",
        changeYear: true
    });
});

Or you could use jQuerys Attribute Starts with Selector
$(document).ready(function () {
    $("input[id^='tb_']").datepicker({
        dateFormat: "yy-mm-dd",
        changeYear: true
    });
});


text:
Q: Windows code signing certificate - what is the reader and cryptographic card for? I was looking at this code signing certificate on Certum:
https://en.sklep.certum.pl/data-safety/code-signing-certificates/open-source-code-signing-930.html
It has two options, either with "reader and cryptographic card" (86 EUR) or without (28 EUR).
I've contacted Certum about it and they say:

From this year Microsoft requires to install code signing certificate on cryptographic card and reader is used to read this card

However I cannot find any information about this on the internet or official Microsoft website (It's possible I'm not searching for the right keywords since the Certum page is translated from Polish).
Is it true that this card and device are absolutely necessary to sign the software? Any idea where I can find information about all this?

A: This might be a late reply, but here's some info in case anybody comes across this post.
CA Security Council:

Stronger protection for private keys: The best practice will be to use
  a FIPS 140-2 Level 2 HSM or equivalent. Studies show that code signing
  attacks are split evenly between issuing to bad publishers and issuing
  to good publishers that unknowingly allow their keys to be
  compromised. That enables an attacker to sign malware stating it was
  published by a legitimate company. Therefore, companies must either
  store keys in hardware they keep on premise hardware, or in a new
  secure cloud-based code signing cloud-based service.

GlobalSign:

Microsoft has announced that they will be adopting the new Minimum
  Requirements for the Issuance and Management of Code Signing
  Certificates issued by the Certificate Authority Security Council
  (CASC). This means, beginning February 1, 2017, Certificate
  Authorities (CAs) will need to meet these requirements in order for
  their certificates to be trusted in Windows platforms.  As such,
  GlobalSign will be making the changes listed below starting January
  30, 2017.
All Code Signing Certificates Will Be Issued with USB tokens

A: I have telephone called Certum and they said it's necessary. You can however go with more expensive option of Open Source Code Signing in Cloud, and they claim you don't need the card and reader then... This is what I'm going for, but I was just as surprised as you that I need some hardware...


text:
Q: How to convert String into JsValue in Play Framework Is it possible at all to convert a String to a JsValue? And how would I do so? I've been trying .asInstanceOf[JsValue] but that doesn't appear to be working
I get the following error:

[ClassCastException: java.lang.String cannot be cast to
  play.api.libs.json.JsValue]

Any ideas?

A: if the string is a representation of a json object, eg:
val jsonString: String = """{"key": "value"}"""
then it can be converted to a value of type JsValue
val jsonObject: JsValue = Json.parse(jsonString)
and you can access the values in the json with path operator
println(jsonObject \ "key")

A: A way to construct JsValue from String is to use the play.api.libs.json.JsString case class.
Namely, JsString("abc") can be used wherever the JsValue representation of "abc" is needed.


text:
Q: PHP Multidimensional Array of Objects Can anyone help me with this little problem please? I need to get (echo) the name, id and link from an array but after hours trying I have not been able, see the array below... Thank you in advanced.
            Array
            (
                [campaigns] => Array
                    (
                        [0] => Campaign Object
                            (
                                [name] => My name 1
                                [id] => 123456789012
                                [link] => 123456789012
                            )

                        [1] => Campaign Object
                            (
                                [name] => My name 2
                                [id] => 123456789012
                                [link] => 123456789012
                            )

                        [2] => Campaign Object
                            (
                                [name] => My name 3
                                [id] => 123456789012
                                [link] => 123456789012
                            )
                    )
            )

A: If you know which campaign you want, you can get it like this:
echo($data['campaigns'][0]->name);
echo($data['campaigns'][0]->id);
echo($data['campaigns'][0]->link);

If you want to loop through all of them, you could do something like this:
foreach ($data['campaigns'] as $item) {
    echo($item->name . "\n");
    echo($item->id . "\n");
    echo($item->link . "\n");
}

This is all a bit of a guess because we don't know what the Campaign class actually looks like - there may be a getName() method that you should be using instead of just accessing the name value directly, for example.

A: foreach ($array['campaigns'] as $key => $value){
    echo "Name: ".$value->name." ID: ".$value->id." Link: ".$value->link."\n";
}

A: Question is a little light on details to debug but have you tried this?
<?php echo $campaigns[0]->name; ?>