text:
Q: Why am I getting "Cannot set headers after they are sent to the client" error in Nodejs? I am getting  Cannot set headers after they are sent to the client error in nodejs and I cant figure out why.the code is given below:I am using mongoose to save data in mongodb.I am trying to save the data and check for a specific condition and return accordingly but the error keeps persisting.
const trendingposts = (req, res) => {
  Post.find({}, function (err, docs) {
    if (docs.length == 0)
       return res.send({message:"No posts"});

    docs.forEach(function (data) {
      var id = data.id;
      var likes = data.likes.length;

      var comments = data.comments.length;
      const date2 = new Date();
      const diffTime = Math.abs(date2 - data.created);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      Post.findByIdAndUpdate(
        id,
        { $inc: { score: (likes * comments) / diffDays } },
        function (errr, doc) {
          if (errr) {
            console.log(err);
          }
        }
      );
    });
  }).exec((err, posts) => {
    if (err) {
      console.log(err);
    }
  });
  var mysort = { score: -1 };
  Post.find({})
    .populate("postedBy")
    .populate("comments.postedBy")
    .populate("comments.incomments.postedBy")
    .populate("comments.likes")
    .sort(mysort)
    .limit(10)
    .exec((er, result) => {

      res.json(result);
    });
};

A: Right here:
Post.find({}, function(err, docs) {
    if (docs.length == 0)
        return res.send({ message: "No posts" });

If you hit that condition of docs.length == 0, then you will send a response to the request.  But, your return is ONLY returning from the Post.find() callback.  It's not returning from your trendingposts() function.
So, meanwhile, that function continues to execute and eventually gets to this code:
var mysort = { score: -1 };
Post.find({})
    .populate("postedBy")
    .populate("comments.postedBy")
    .populate("comments.incomments.postedBy")
    .populate("comments.likes")
    .sort(mysort)
    .limit(10)
    .exec((er, result) => {

        res.json(result);
    });

Where you then send another response to the same request.  That's what triggers the error Cannot set headers after they are sent to the client that you see.

There are many different ways to prevent this, but they are probably all related to how you would generally clean up this function.  The way it is written now, you essentially start two completely separate asynchronous code paths.  Both start with Post.find({}) and go from there.  They each run in parallel and neither has any idea what the other code path is doing.  As such, you have no concrete way to send a response from one, but not both.
So, the way to clean this up is probably to not have two completely separate asynchronous code paths.  You need to coordinate them in some way.  In pretty much all cases here, you will want to switch over to the promise-interface to your database as that will give you a lot more options for managing your control flow.  For example, if for performance reasons, you want to have two parallel asynchronous operations going at once, with promises, you can use Promise.all() or Promise.allSettled() to monitor both and know when they are done and then, with both results in hand, decide which response to send.
Or, if you want to sequence them, you can use async/await to fairly  easily sequence the two operations and then when you do a return, it will actually return from the top-level function and will stop further control flow.
If you want to stick with the callback interface to your database, then you will probably have to nest the second operation into the first option so that you don't start the second operation if you're going to do res.send({ message: "No posts" }).


text:
Q: remove Red boxes in a PDF file I downloaded the Linux Essentials PDF file from LPIC site, the link for which is
https://www.linuxcertification.co.za/sites/default/files/linux-esentials-manual.pdf
I saved the PDF file on my system and opened it using Foxit PDF reader as well as Adobe reader. Now, when viewing the file in Chrome as a PDF, there are no Red boxes visible:

However when I view it in Foxit and Adobe, then these boxes show up:

What is causing this issue?
I tried converting the PDF file to word using online convertors and then converted the Word file to PDF. In most cases, the boxes were removed however the text alignment was distorted and few times even some grammatical error was seen.
I cannot rely on opening the file in Chrome all the time and wish to use either Foxit or Adobe reader to open the file. Any help would be appreciated.

A: As a matter of fact, you can remove the borders, quite easily so because they are not in what makes up the PDF pages themselves. The borders are actually part of the link annotations that allow you to navigate the document. So for removing their appearance one just needs to adjust the appropriate PDF objects.
The document's license doesn't allow derivates to be distributed. So here is a script that uses HexaPDF to remove the borders from the link annotations:
require 'hexapdf'
doc = HexaPDF::Document.open(ARGV[0])
doc.pages.each {|page| page[:Annots]&.each {|a| a = doc.deref(a); a[:C] = nil; a[:Border] = [0, 0, 0]}}
doc.write(ARGV[0] + '.pdf', validate: false)

You need to install HexaPDF (gem install hexapdf, needs a working Ruby 2.4 installation), save this script as a Ruby file, for example remove_borders.rb and then run it like this:
ruby remove_borders.rb path/to/linux-essentials-manual.pdf

The output is a file with the same name but an additional .pdf attached, with the borders of the link annotations removed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Possible ways to call database function in EF Code First Consider I have some code first model in my app and some snippet:
var myQueryable = (IQueryable<MyEntity>dbContext.MyEntitySet;
var myFilteredQueryable = externalService.Filter(myQueryable);

Now, I need to call stored function from database in order to add additional criteria, sth like this:
WHERE MyFunc(MyCol) = 1;

I know, there is no posibility to create own function with EdmFunciton to use it like this:
myFilteredQueryable = myFilteredQueryable.Where(myEnt => MyFunctions.MyFunc(myEnty.MyCol);

It is available in Databse first / Model first.
I know I can run it directly:
var selectedIds = myFilteredQueryable.Select(m => m.Id).ToArray();
var filteredIds = dbContext.Database.ExecuteSqlQuery<int>("SELECT Id FROM MyEntity WHERE MyFunc(MyCol) = 1 AND ID in (" + string.Join(selectedIds, ",") + ")").ToArray();

myFilteredQueryable = myFilteredQueryable.Where(myEnt => filteredIds.Contains(myEnt.Id));

Performance of this solution is not good one.. What are other ways to filter by queryable by function? I am obligated to use Code First and cannot modyify external service.


text:
Q: How to limit the file size in Java I am creating a file in my application and I am keep on writing some content in to this file.
But after my file reaches to some size, let say 100 lines, I want to erase the first line and write the new line to the bottom.
The requirement is my file should be limited, but it should maintain the latest content that I have written in to file.
Please let me know if its possible in Java? Please let me know if there's any alternative to do this.

A:
Please let me know if its possible in Java?

This can't be done in a simple way. You can only truncate the last part of a file. (This is an inherit limit from the underlying file system, and due to the same reasons as to why you can't insert bytes in the middle of a file.)
You can do it manually by:

*

*Figuring out the byte-length, n, of the first line.

*For i = n ... length of file

*

*Write byte at pos i to pos i - n

*Truncate the file to length length of file - n.

Please let me know if there's any alternative to do this.

I suggest you solve it using a cyclic buffer or something similar. Still though, you'd get into trouble if not all lines are equally long, unless you keep the buffer in memory, and dump it to (a cleared) file.

A: This is do-able but could be a very slow process depending on how you implement it. At least keep the 100 lines in memory in a data structure like a Vector so that you don't have to read the file each time, just write it each time you drop the first element and append the new final element.
Another alternative would be to store each line in its own file. Then you just delete a file and make a new one, for each new line after the 100th.
[much later]
Thought of another way, fixed-length records, if your lines are of predictable size. Each line is a space followed by the text followed by spaces to pad out the record, with end-of-line character(s) at the end if desired. Each time you write a record, you prepend it with an asterisk to mark it as the current line, and then index into the previous line (with the modulo operator so it automatically wraps around) and replace that asterisk with a space. An example 10-line logfile would look something like this:
 this happened at that time
 blah blah happened
*this is the current record
 this was the fourth event to occur after startup
 this was the fifth event to occur after startup
 this was the sixth event to occur after startup
 this was the seventh event to occur after startup
 this was the eighth event to occur after startup
 this was the ninth event to occur after startup
 this was the tenth event to occur after startup

This way you only need to open the file, index to the current line (which you know because you're keeping track in your program; otherwise, on restart, loop to find the asterisk), and overwrite it, padding it with spaces to the chosen length. then index back one record and replace the asterisk with a space.

A: I'd use a cyclic buffer. The way I'd implement it with 2 files, and start using the second file if the first one contains 100 lines. Switch back to writing to the first, when that file gets to 100 lines. That way you'll always have 100 to 200 lines total (once you get to at least 100 lines the first time).


text:
Q: How to share connection pool between Amazon-ECS instances I have spring-boot application running on Amazon-ECS. Instances of application are added on the fly using ECS. Now each application has HikariCP for connection-pool. So when I increase instances, connection-pool on each instance is not shared, & that will lead to problem. How do I handle this problem?
So far I've tried creating middle layer which will handle connection-pool & queries will go thru this, but then again this is just another bottleneck, how do I scale up this one? other part is using JNDI for same, which is some-what similar to previous solution.
Or to adjust size of connection-pool on each cluster, but then when instances increase or decrease I'd like this size to adjust as well.
Honestly, I don't have any clue, how folks handle connection-pooling in clustered environment. What could be done to share connection pool, or the question is should be shared at all & if that's the case, how to put limit of number of connections, so that instances wont go thru starvation.

A: The normal practice for connection pools with multiple instances is to manage each one independently.
When you have multiple instances of a Spring Boot application running on ECS, each one needs its own connection pool, and the parameters for that connection pool wouldn't normally vary when the number of instances goes up or down.
In essence, you decide how on the connection pooling parameters that are appropriate for each instance and you make sure the database server can handle the maximum number of connections you expect those settings to result in.


text:
Q: Grails - override message bundle property at runtime Is there a way to override at runtime the value of a property defined in a message bundle?
My grails application contains a property in the messages.properties file:
page1.para1.text=Some text to display to the user

My Config.groovy defines the following config location:
grails.config.locations = [ "file:${userHome}/.myApp/myApp-config.properties" ]

I currently use this approach to override Config.groovy properties (like db connections, etc), but it doesn't seen to apply to message bundle properties.
I was hoping/expecting to just make sure that the myApp-config.properties file contains my new property value, restart the Tomcat server where my app is deployed and it would get picked up and displayed on my page:
page1.para1.text=Some DIFFERENT text to display to the user

Grails docs on Internalization/Message bundles grails i18n doesn't suggest if this is possible or not.
Obviously, I'm trying to achieve this change without the need to recompile and redeliver my Grails application.
Any ideas?
Thanks in advance.

A: When you are already live and don't want to create a new .war file:
I'm not sure, but the .war file can be found unzipped on the server. You might try to replace the message files directly on the server, but a restart of the app might be necessary. But I wouldn't advice doing so.
If you need to often change the message bundles at runtime, I guess it would make sense to store them in the database. But that means that you have to change your code a little bit and redeploy it once. There is a blog entry which describes how to do it: http://graemerocher.blogspot.de/2010/04/reading-i18n-messages-from-database.html
Another SO question handles the case that you want to store changes to the messages in a DB but fall back to the files:
Grails i18n From Database but Default Back To File
hth

A: In theory you should be able to replace the messageSource bean with a ReloadableResourceBundleMessageSource inside Resources.groovy. This way you can not only point it to a new location but also declare how often they should be invalidated as cached values.


text:
Q: Adding string as key in javascript JSON I am trying to update JSON based on user input.
I have an existing JSON array:
 colorDataInitial = {
   "ML1TEST1" : "#120101",
   "ML1TEST2" : "#120101",
   "ML1TEST3" : "#120101",
   "ML1TEST4" : "#120101",
   "ML1TEST5" : "#120101",
  }

And want to update one of these to a new color based on user input:
var roomID = $('#room').val();

But when I attempt to loop through this the dot notation only adds as a new key:
  var arrayLength = roomArray.length;
  for (var i = 0; i < arrayLength; i++) {

    if (roomArray[i] == roomID) {

      var colorDataTest.roomID = "#FF1C1C"

    } else {

      var colorDataTest.roomID = ("ML1TEST" + i);

    }
  }

Output:
ML1TEST1: "#120101"ML1TEST2: "#120101"ML1TEST3: "#120101"ML1TEST4: "#120101"ML1TEST5: "#120101"roomID: "#FF1C1C"

How would I get it to accept the string as the user input?
Thanks for any help

A: You probably need to use:
colorDataTest[roomID]

Instead of:
colorDataTest.roomID

The .roomID method looks for a property named roomID on colorDataTest.
The square bracket looks for a property with the name from the value of roomID, in colorDataTest.
For example:
var myVar = 'aString';

var myObj = {
    aString: 123,
    myVar:   456
}

console.log(myObj[myVar]); // 123
console.log(myObj.myVar);  // 456


text:
Q: swift-custom keyboard on ios 8 I made a custom keyboard using swift.
While doing that, I made vertically. It crashes when I rotate the device to landscape.
Keyboard is also vertical, with the horizontal space of the other so much.
I do not know if any of you have a solution or some advice here.
portrait

landscape


text:
Q: How to select a  on a particular tab clicked? I am designing a tabs of my own for tab navigation I used google api and jquery.
Here my fiddle,
http://jsfiddle.net/raghavendram040/fk7y2d5L/2/
but in fiddle i didnt add google api link.
Here is my js code
google.load("jquery", "1.3.1");
google.setOnLoadCallback(function()
{

$("header ul li a").click(function(e) {
    e.preventDefault();

    $("header ul li a").each(function() {
        $(this).removeClass("active");
    });

    $(this).addClass("active");

            var tabtitle=$(this).attr("title");
    $.show('#tab'+tabtitle);
});
});

Here I am trying is on click of each tag i am trying to display respective div tag. But I cant able to do it. can any one help me in this.

A: Try this : You don't need google api for this. Just include jquery library in your html page as shown below. Put your code inside $(function(){..}); which will ensure that script applies after loading whole DOM structure.
For more information on jQuery visit - JQuery.com
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

$(function()
{
    // Just for demonstration purposes, change the contents/active state using jQuery
    $("header ul li a").click(function(e) {
        e.preventDefault();

        // remove active class from all tabs
        $("header ul li a").removeClass("active");
        // hide all tab div
        $('div[id^="tab"]').hide();

        //add active class to clicked tab
        $(this).addClass("active");

        // show clicked tab content div
        var tabtitle=$(this).attr("title");
        $('#tab'+tabtitle).show();
    });
});

Demo

A: JSFiddle: http://jsfiddle.net/TrueBlueAussie/fk7y2d5L/11/
$(function () {
    // Just for demonstration purposes, change the contents/active state using jQuery
    $("header ul li a").click(function (e) {
        e.preventDefault();

        // Remove the active class from any anchors that have it
        $("header ul li a.active").removeClass("active");

        // Add active to the selected anchor
        $(this).addClass("active");

        var tabtitle = $(this).attr("title");

        // Hide all divs that start with id=tab
        $('#main div[id^=tab]').hide();

        // Show the selected div
        $('#tab' + tabtitle).show();
    });

    // initial hide of all tabs
    $('#main div[id^=tab]').hide();

    // Trigger initial selection
    $('header a.active').trigger('click');

});

A: First of all you need to hide the tabs, lets say that you do so by adding a class tab for all corresponding <div>'s along with the following css
.tab {
  display:none;
}

Then set the initially active tab as visible by applying the class visible given below to it.
div.tab.visible {
  display:block;
}

Now you can use the following JS to make it work:
$("header ul li a").click(function (e) {
  e.preventDefault();

  $(".active").removeClass("active"); // you don't need to iterate over using each
  $(this).addClass("active");

  var tabtitle = $(this).attr("title");
  $("#main div.tab.visible").removeClass("visible"); // hide actve tab
  $('#tab' + tabtitle).addClass("visible"); // show selected tab
});

Updated Fiddle
Side note: I added the missing tab blog and added the corresponding text for the demo

A: Firstly. No need for anything other than just jQuery.
Secondly: Personally, I would default all the tabs to being hidden, and only showing them when the "active" class is on them.
Also, you might want to add some actual class names to the tabs and the tab-content so you have better control. ".tab" for the tabs, and ".tab-content" for the content.
The javascript code is then fairly simple and understandable:
$(function()
{
    $(".tab").click(function(e) {
        e.preventDefault();

        $(".tab.active, .tab-content.active").removeClass("active");

        $(this).addClass("active");
        var tabtitle = $(this).attr("title");
        $('#tab'+tabtitle).addClass("active");
    });
});

JSFiddle with new class names


text:
Q: pygame hold down lkey is delayed im a beginner in pygame, and i dont have any experience in programming,
im using pygame.key.get_pressed() :
import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 400))
pygame.display.set_caption('Hello World!')

green = (0,255,0)
FPS = 60
FpsClock = pygame.time.Clock()
playerY = 200
playerX = 200

while True:
    BG = pygame.draw.rect(DISPLAYSURF,(255, 255,255),(0,0,400,400))
    player = pygame.draw.rect(DISPLAYSURF,(green),(playerX, playerY,20, 20))
    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if keys[pygame.K_z]:
            playerY -= 5
        if keys[pygame.K_s]:
            playerY += 5
        if keys[pygame.K_d]:
            playerX += 5
        if keys[pygame.K_q]:
            playerX -= 5

    pygame.display.update(player)

    pygame.display.update()
    FpsClock.tick(FPS)

when i click one time on s key for example everything works just fine the player moves, but
if i hold down s button there is a delay before the player move's down while im holding the button
(samething for w,a,d)

A: It is a matter of Indentation. You must evaluate the pressed keys in the application loop instead of the event loop:
while True:
    BG = pygame.draw.rect(DISPLAYSURF,(255, 255,255),(0,0,400,400))
    player = pygame.draw.rect(DISPLAYSURF,(green),(playerX, playerY,20, 20))
    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # INDENTATION
    #<--|

    if keys[pygame.K_z]:
        playerY -= 5
    if keys[pygame.K_s]:
        playerY += 5
    if keys[pygame.K_d]:
        playerX += 5
    if keys[pygame.K_q]:
        playerX -= 5

    pygame.display.update(player)
    pygame.display.update()
    FpsClock.tick(FPS)

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False.


text:
Q: How to backup the database from the server to the client computer using asp.net page I have used code C # to write one page of data to back up the .bak file from the server to the client machine. when I tested on my computer is very good. which when connected through another computer by using connectionString web.cofig it reappears errors like this. This one was like before or workaround, please help.

private string _ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        FillDatabases();
        //ReadBackupFiles();
    }
}

private void FillDatabases()
{
    try
    {
        SqlConnection sqlConnection = new SqlConnection();
        sqlConnection.ConnectionString = _ConnectionString;
        sqlConnection.Open();
        string sqlQuery = "SELECT * FROM sys.databases";
        SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
        sqlCommand.CommandType = CommandType.Text;
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
        DataSet dataSet = new DataSet();
        sqlDataAdapter.Fill(dataSet);
        ddlDatabases.DataSource = dataSet.Tables[0];
        ddlDatabases.DataTextField = "name";
        ddlDatabases.DataValueField = "database_id";
        ddlDatabases.DataBind();
    }
    catch (SqlException sqlException)
    {
        lblMessage.Text = sqlException.Message.ToString();
    }
    catch (Exception exception)
    {
        lblMessage.Text = exception.Message.ToString();
    }
}

protected void btnBackup_Click(object sender, EventArgs e)
{
    try
    {
        string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
        string _BackupName = _DatabaseName + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
        SqlConnection sqlConnection = new SqlConnection();
        sqlConnection.ConnectionString = _ConnectionString;
        sqlConnection.Open();
        string sqlQuery = "BACKUP DATABASE " + _DatabaseName + " TO DISK = 'D:\\SQLServerBackups\\" + _BackupName + "' WITH FORMAT, MEDIANAME = 'Z_SQLServerBackups', NAME = '" + _BackupName + "';";
        SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
        sqlCommand.CommandType = CommandType.Text;
        int iRows = sqlCommand.ExecuteNonQuery();
        sqlConnection.Close();
        lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
        ReadBackupFiles();
    }
    catch (SqlException sqlException)
    {
        lblMessage.Text = sqlException.Message.ToString();
    }
    catch (Exception exception)
    {
        lblMessage.Text = exception.Message.ToString();
    }
}

A: What is happening is when you run this program on your computer everything works right because it's setup for your system. If you want to transfer to your system or another computer separate from the server there are a couple of things that might work. You can make a shared drive off the system you want the program to drop the files in, which may or may not work since share folders are treated differently then normal folders/drives. I would write a upload program that connects to a file server and uploads the backup files to there automatically, after the server dumps to a predefined folder that the server has access to. There are some really good file upload libraries available to C# that can automate this process for you. So you can have an asp.net page that puts the backup file like it does for your system currently, and another c# program that is setup to run at a certain time using scheduler and uploads the backup to your desired location remotely from the server.
Hope this makes sense, let me know if you have any questions.
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
Here is the code to have C# upload files automatically for you from a file location. You'll need to setup a ftp server on the computer you want the backups to go to. Otherwise the only way around this is to make the files available for download off the sever in question which means just making the folder visible to the Internet. But I'd go with the ftp options since it's the most flexible.

A: You create backup in online-mode or just have in your server? If you have some files in your server, realize downloading function and that's all what you need.
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename="+file);
Response.TransmitFile(Server.MapPath("~/backups/"+file)); //backup must be located in folder in your application folder, that folder named *backups*
Response.End(); //file is a filename of your backup: e.g. 20151224.bak

If you create backup online and want to send it to user, you have to do next steps (it is just one approach):
1) Make backup and save it into your application folder to some temporary folder
2) Realize download page as I show earlier (user will download it)
3) And as soon as user download that, you will just delete your temporary backup file.
Hope it helps


text:
Q: how to get record of immageable type by id in laravel morph relationship For the Messaging system, I have setup two morph relationships using four tables.
My questions are?

*

*How can I get from a specific Student's message from receives collection?

For example, if Student X and Y send messages to Staff A
when I query Staff A's received messages like:
$staff = \App\Staff::find(1);
$all_message_recieves = $staff->receives;

I got both messages from Student X and Y, but I want only the Student X messages
Tables structure are
tbl_message

id messageable_id, messageable_type, subject, message

1     1              app\staff        msg1     msg1
2     2              app\staff        msg1     msg1
3     1              app\student      msg2     msg2
4     2              app\student      msg2     msg2

tbl_message_receiver

id, message_id , receiveable_id, receiveable_type

1     1            1                 app\student
2     2            2                 app\student
3     3            1                 app\staff
3     4            1                 app\staff

Staff

id name
1   A
2   B

Student

id name
1   X
2   Y

Message.php model
class Message extends Model
{

    public $table = "tbl_message";

    public function messageable()
    {
        return $this->morphTo();
    }
}

Messagereceive.php model
class Messagereceive extends Model
{
    public $table = "tbl_message_receiver";
    public function receiveable()
    {
        return $this->morphTo();
    }

    public function message()
    {
         return $this->hasOne('App\Message');
    }
}

Staff.php model
class Staff extends Model
{

    public function messages()
    {
        return $this->morphMany('App\Message', 'messageable');
    }

    public function receives()
    {
        return $this->morphMany('App\Messagereceive', 'receiveable');
    }
}

Student.php model
class Student extends Model
{

    public function messages()
    {
        return $this->morphMany('App\Message', 'messageable');
    }

    public function receives()
    {
        return $this->morphMany('App\Messagereceive', 'receiveable');
    }
}


text:
Q: Multiplying Gaussians of different dimensions Let $G_1(x, \mu_1, \sigma_1)$ be a 1D Gaussian and $G_2(x, y, \mu_2, \mu_2, \sigma_2)$ be a 2D Gaussian.
What is the product of theses two Gaussians:
$$
G(x, y) = G_1(x, \mu_1, \sigma_1) G_2(x, y, \mu_2, \mu_2, \sigma_2)
$$
I want to find a mean and covariance of the product.
I have tried to write $G_1$ as a degenerate 2D Gaussian with inverse covariance
matrix $\Sigma_1^{-1} = \left( \begin{array}{cc}
\frac{1}{\sigma_1^2} & 0 \\
0 & 0  \end{array} \right)
$
and then use standard multiplication rule to get new mean and variance.
But $\Sigma_1$ is singular and can't invert it.
Any suggestions how to approach this?


text:
Q: PHP json decode breaking when image tag present Here is my json encoded string coming from a db query:
[{"columns":[{"class":"grid","html":"

"}]},{"columns":[{"class":"grid","html":""}]}]

When I go to json_decode in PHP I am getting NULL.
$content = json_decode($json_str); = NULL

I haven't had this issue before.  I am using JSON.stringify when saving the item into the db via ajax like so:
var data = JSON.stringify(html);

Do I have to start treating this differently for some reason?


text:
Q: How to add file extensions based on file type on Linux/Unix? This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee

These files have different original file types such as png, zip, doc, pdf etc.
Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the file command?
Answer:
J.F. Sebastian's script will work for both ouput of the filenames as well as the actual renaming.

A: Following csl's response:

You can use
file -i filename

to get a MIME-type.
  You could potentially lookup the type
  in a list and then append an
  extension. You can find list of
  MIME-types and suggested file
  extensions on the net.

I'd suggest you write a script that takes the output of file -i filename, and returns an extension (split on spaces, find the '/', look up that term in a table file) in your language of choice - a few lines at most. Then you can do something like:
ls | while read f; do mv "$f" "$f".`file -i "$f" | get_extension.py`; done

in bash, or throw that in a bash script. Or make the get_extension script bigger, but that makes it less useful next time you want the relevant extension.
Edit: change from for f in * to ls | while read f because the latter handles filenames with spaces in (a particular nightmare on Windows).

A: Of course, it should be added that deciding on a MIME type just based on file(1) output can be very inaccurate/vague (what's "data" ?) or even completely incorrect...

A: Here's mimetypes' version:
#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.

   `ext` is mime-based.

"""
import fileinput
import mimetypes
import os
import sys
from subprocess import Popen, PIPE

if len(sys.argv) > 1 and sys.argv[1] == '--rename':
    do_rename = True
    del sys.argv[1]
else:
    do_rename = False

for filename in (line.rstrip() for line in fileinput.input()):
    output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
    mime = output.split(';', 1)[0].lower().strip()
    ext = mimetypes.guess_extension(mime, strict=False)
    if ext is None:
        ext = os.path.extsep + 'undefined'
    filename_ext = filename + ext
    print filename_ext
    if do_rename:
       os.rename(filename, filename_ext)

Example:

$ ls *.file? | python add-ext.py --rename
avi.file.avi
djvu.file.undefined
doc.file.dot
gif.file.gif
html.file.html
ico.file.obj
jpg.file.jpe
m3u.file.ksh
mp3.file.mp3
mpg.file.m1v
pdf.file.pdf
pdf.file2.pdf
pdf.file3.pdf
png.file.png
tar.bz2.file.undefined

Following @Phil H's response that follows @csl' response:
#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.

   `ext` is mime-based.
"""
# Mapping of mime-types to extensions is taken form here:
# http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as
mime2exts_list = [
    ["application/andrew-inset","ez"],
    ["application/atom+xml","atom"],
    ["application/mac-binhex40","hqx"],
    ["application/mac-compactpro","cpt"],
    ["application/mathml+xml","mathml"],
    ["application/msword","doc"],
    ["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
    ["application/oda","oda"],
    ["application/ogg","ogg"],
    ["application/pdf","pdf"],
    ["application/postscript","ai","eps","ps"],
    ["application/rdf+xml","rdf"],
    ["application/smil","smi","smil"],
    ["application/srgs","gram"],
    ["application/srgs+xml","grxml"],
    ["application/vnd.adobe.apollo-application-installer-package+zip","air"],
    ["application/vnd.mif","mif"],
    ["application/vnd.mozilla.xul+xml","xul"],
    ["application/vnd.ms-excel","xls"],
    ["application/vnd.ms-powerpoint","ppt"],
    ["application/vnd.rn-realmedia","rm"],
    ["application/vnd.wap.wbxml","wbxml"],
    ["application/vnd.wap.wmlc","wmlc"],
    ["application/vnd.wap.wmlscriptc","wmlsc"],
    ["application/voicexml+xml","vxml"],
    ["application/x-bcpio","bcpio"],
    ["application/x-cdlink","vcd"],
    ["application/x-chess-pgn","pgn"],
    ["application/x-cpio","cpio"],
    ["application/x-csh","csh"],
    ["application/x-director","dcr","dir","dxr"],
    ["application/x-dvi","dvi"],
    ["application/x-futuresplash","spl"],
    ["application/x-gtar","gtar"],
    ["application/x-hdf","hdf"],
    ["application/x-javascript","js"],
    ["application/x-koan","skp","skd","skt","skm"],
    ["application/x-latex","latex"],
    ["application/x-netcdf","nc","cdf"],
    ["application/x-sh","sh"],
    ["application/x-shar","shar"],
    ["application/x-shockwave-flash","swf"],
    ["application/x-stuffit","sit"],
    ["application/x-sv4cpio","sv4cpio"],
    ["application/x-sv4crc","sv4crc"],
    ["application/x-tar","tar"],
    ["application/x-tcl","tcl"],
    ["application/x-tex","tex"],
    ["application/x-texinfo","texinfo","texi"],
    ["application/x-troff","t","tr","roff"],
    ["application/x-troff-man","man"],
    ["application/x-troff-me","me"],
    ["application/x-troff-ms","ms"],
    ["application/x-ustar","ustar"],
    ["application/x-wais-source","src"],
    ["application/xhtml+xml","xhtml","xht"],
    ["application/xml","xml","xsl"],
    ["application/xml-dtd","dtd"],
    ["application/xslt+xml","xslt"],
    ["application/zip","zip"],
    ["audio/basic","au","snd"],
    ["audio/midi","mid","midi","kar"],
    ["audio/mpeg","mp3","mpga","mp2"],
    ["audio/x-aiff","aif","aiff","aifc"],
    ["audio/x-mpegurl","m3u"],
    ["audio/x-pn-realaudio","ram","ra"],
    ["audio/x-wav","wav"],
    ["chemical/x-pdb","pdb"],
    ["chemical/x-xyz","xyz"],
    ["image/bmp","bmp"],
    ["image/cgm","cgm"],
    ["image/gif","gif"],
    ["image/ief","ief"],
    ["image/jpeg","jpg","jpeg","jpe"],
    ["image/png","png"],
    ["image/svg+xml","svg"],
    ["image/tiff","tiff","tif"],
    ["image/vnd.djvu","djvu","djv"],
    ["image/vnd.wap.wbmp","wbmp"],
    ["image/x-cmu-raster","ras"],
    ["image/x-icon","ico"],
    ["image/x-portable-anymap","pnm"],
    ["image/x-portable-bitmap","pbm"],
    ["image/x-portable-graymap","pgm"],
    ["image/x-portable-pixmap","ppm"],
    ["image/x-rgb","rgb"],
    ["image/x-xbitmap","xbm"],
    ["image/x-xpixmap","xpm"],
    ["image/x-xwindowdump","xwd"],
    ["model/iges","igs","iges"],
    ["model/mesh","msh","mesh","silo"],
    ["model/vrml","wrl","vrml"],
    ["text/calendar","ics","ifb"],
    ["text/css","css"],
    ["text/html","html","htm"],
    ["text/plain","txt","asc"],
    ["text/richtext","rtx"],
    ["text/rtf","rtf"],
    ["text/sgml","sgml","sgm"],
    ["text/tab-separated-values","tsv"],
    ["text/vnd.wap.wml","wml"],
    ["text/vnd.wap.wmlscript","wmls"],
    ["text/x-setext","etx"],
    ["video/mpeg","mpg","mpeg","mpe"],
    ["video/quicktime","mov","qt"],
    ["video/vnd.mpegurl","m4u","mxu"],
    ["video/x-flv","flv"],
    ["video/x-msvideo","avi"],
    ["video/x-sgi-movie","movie"],
    ["x-conference/x-cooltalk","ice"]]

#NOTE: take only the first extension
mime2ext = dict(x[:2] for x in mime2exts_list)

if __name__ == '__main__':
    import fileinput, os.path
    from subprocess import Popen, PIPE

    for filename in (line.rstrip() for line in fileinput.input()):
        output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
        mime = output.split(';', 1)[0].lower().strip()
        print filename + os.path.extsep + mime2ext.get(mime, 'undefined')

Here's a snippet for old python's versions (not tested):
#NOTE: take only the first extension
mime2ext = {}
for x in mime2exts_list:
    mime2ext[x[0]] = x[1]

if __name__ == '__main__':
    import os
    import sys

    # this version supports only stdin (part of fileinput.input() functionality)
    lines = sys.stdin.read().split('\n')
    for line in lines:
        filename = line.rstrip()
        output = os.popen('file -bi ' + filename).read()
        mime = output.split(';')[0].lower().strip()
        try: ext = mime2ext[mime]
        except KeyError:
             ext = 'undefined'
        print filename + '.' + ext

It should work on Python 2.3.5 (I guess).

A: You can use
file -i filename

to get a MIME-type.  You could potentially lookup the type in a list and then append an extension.  You can find a list of MIME-types and example file extensions on the net.

A: Agreeing with Keltia, and elaborating some on his answer:
Take care -- some filetypes may be problematic.
JPEG2000, for example.
And others might return too much info given the "file" command without any option tags. The way to avoid this is to use "file -b" for a brief return of information.BZT


text:
Q: Delete button using Fetch API delete i have a question. I am creating simple CRUD application with backend on Java EE and oracle database.
I need to create button to delete object. REST intefrace for delte is .../rest/product/idofproduct
I am using class with Fetch API
class App{

deleteProduct(id){
    return fetch('http://localhost:8080/productdb-0.1/rest/product/'+ id , {
        method: 'delete'
    })
        .then(r=> r.json());
}
}

than i have a fucnction.js where i have
    let deleteApp = new App();
    let remove = document.getElementById('productList');
    remove.addEventListener('submit',function (e) {
        e.preventDefault();
        let id = document.getElementById('delete').getAttribute('data');

    })

I am trying to map it on button inside

            ${product.productName}
            ${product.priceVC} $ / ${product.priceMC} $
            <input id="delete" data="${product.id}"type="submit" value="X Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this item?');">

but its not working, dont know what could be wrong.
Thanks for any advice :)


text:
Q: How to make a level plot with ggplot with same look of the density plot I like the look that the density plot of the ggplot view (Below). I wanna know how make a similar graph using a set of data interpoled (Data: https://www.dropbox.com/s/z8jbz10nnydsqw5/data.txt?dl=0). In other words, i wanna a graph with discrete contour and shaded colors.
I will appreciate your help

For example:
The same plot is possible make with lattice package:
library(ggplot2)
library(lattice)
library(latticeExtra)

data=read.table("data.txt",header = T,sep = ";")
#discrete field
levelplot(var~long+lat,data = data,contour=T)

But, in ggplot i get this result when i apply the density plot:
ggplot(data,aes(x=long,y=lat))+geom_density2d(aes(fill=var))+theme_bw()

I don't wanna make a density plot. I just wanna make a plot that look like the density plot in figure 1.

A: With ggplot I believe you require something like ggplot(dat, aes(long, lat, fill = var)) + geom_raster() and not the geom_density2d function. The default fill function is continuous as shown below. Others can point you to the functions to use discrete colors.

For lattice, you have to provide the colors and the breakpoints to the levelplot function and to the colorkey argument list and to the labels argument list within the colorkey argument. It's not so obvious...but here is an example.
# dat <- read.delim(f, sep = ";")
  myCol <- brewer.pal(11, "RdYlBu")[c(6,8:11)]
  breaks <- seq(min(dat$var), max(dat$var), len = 6)
  levelplot(var ~ long + lat, data = dat,
    at = breaks,
    col.regions = myCol,
    colorkey = list(col = myCol, at = breaks,
      labels = list(at = breaks, labels = round(breaks))
     )
   )


text:
Q: Unable to get value from Json.parse getting undefined value in Angular js MVC I am trying to fetch value from json.parse getting undefined value .
here is code,
var result = JSON.parse(d.data.data);
var name = result["TasksId"];

In result variable i have value in this form:
"{
  "result": [
    {
      "AssignedBy": "724523c9-6d0d-4c69-9ee1-5d17b0271bbc",
      "UserId": "980392bd-96ce-4940-87e7-bb9e8f805f60",
      "Id": 5872,
      "TaskId": 1485
    }
  ]
}"

TaskId exist in it even than i am getting undefined
Hopes for your suggestions
Thanks

A: here, result is an nested object. For accessing the outer key, you have to use either dot notation like result.result or [] notation like result["result"].
The value of result["result"] is an array for which values to be accessed by [index].
result["result"][0]["TaskId"]

A: check your object, It has an array in it
"{
  "result": [
    {
      "AssignedBy": "724523c9-6d0d-4c69-9ee1-5d17b0271bbc",
      "UserId": "980392bd-96ce-4940-87e7-bb9e8f805f60",
      "Id": 5872,
      "TaskId": 1485
    }
  ]
}"

so you must give the proper path(index) to it , so try using result['result'][0]['TaskId']


text:
Q: Problem with calling python script from in excel vba I have a problem calling python scripts from vba in excel, when I run the macro nothing happens!
I don't know exactly where the problem is?
my code in vba:
Option Explicit

Sub Run_python_script()

' declare the variables
Dim objShell As Object

Dim PythonExe, PythonScript As String ' the path of the python file and python script

' create a new shell object
    Set objShell = VBA.CreateObject("Wscript.Shell")

    'provide the file path to the python exe
    PythonExe = """C:\Users\bbbbbb\AppData\Local\Microsoft\WindowsApps\python.exe"""

    'provide the file path to the python script
    PythonScript = """C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.py"""

    'run the python script
    objShell.Run PythonExe & PythonScript
End Sub

I'm using python 3.7 and the jupyter ide
here is my python code :
import pandas as pd
import xlrd

file = r'C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.xlsm'
sheetname='Feuil1'
n=2
df = pd.read_excel(file,skiprows=[*range(n)],index_col=[0])

df_static= df[['CF','VPC','CO','MA','status','Project Naming','Poste','family','ressource']]

wb = xlrd.open_workbook(file)
ws = wb.sheet_by_name(sheetname)

year = ws.cell(0,0).value
month = ws.cell(1,0).value

datetime_cols= pd.to_datetime(df.columns,dayfirst=True,errors='coerce')
out = (df.loc[:,(datetime_cols.year == year) & (datetime_cols.month == month)])

df_merge=pd.concat([df_static,out], axis=1)
df_merge

book = load_workbook(r'C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.xlsm')
writer = pd.ExcelWriter(r'C:\Users\OneDrive\Bureau\test_python\test.xlsm', engine='openpyxl')
writer.book = book

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df_merge.to_excel(writer, "ETP",startcol=0,startrow=6)

writer.save()

my excel sheet 'Feuil1'looks like that :

and when I select the year and the month in cells A1 and A2 , it will generate another sheet called 'ETP' with the selected data.
so by importing the pyrhon script , each time I chose different dates , it will updated automaticaly
thanks in advance for your help

A: You need add some space in your shell execution string,
See my example with you code.
Option Explicit

Sub Run_python_script()
' declare the variables
Dim PythonExe, PythonScript As String ' the path of the python file and python script
    'provide the file path to the python exe
    PythonExe = "C:\Users\bbbbbb\AppData\Local\Microsoft\WindowsApps\python.exe"
    'provide the file path to the python script
    PythonScript = "C:\Users\bbbbbb\OneDrive\Bureau\test_python\test.py"
    'run the python script
    Shell PythonExe & " " & PythonScript, vbNormalFocus
End Sub

I fixed your code, tested it and it worked here.
But there is a problem, in excel you don't write to the 'xlsm' file when the file is open in the excel program. So you will not be able to run directly from the same spreadsheet.
I suggest you modify your python code to pass parameters via the command line, such as file name and directory.
Test this code on the terminal first
Your python code:
import pandas as pd
import xlrd
from openpyxl.reader.excel import load_workbook
from openpyxl import Workbook
file = r'C:\dev\Test.xlsm'
sheetname='Feuil1'
n=2
df = pd.read_excel(file,skiprows=[*range(n)],index_col=[0])

df_static= df[['CF','VPC','CO','MA','status','Project Naming','Poste','family','ressource']]

wb = load_workbook(file, read_only=False, keep_vba=True)
ws = wb.worksheets[0]
year = ws['A1'].value
month = ws['A2'].value

datetime_cols= pd.to_datetime(df.columns,dayfirst=True,errors='coerce')
out = (df.loc[:,(datetime_cols.year == year) & (datetime_cols.month == month)])

df_merge=pd.concat([df_static,out], axis=1)
df_merge

book = wb
writer = pd.ExcelWriter(r'C:\dev\Test.xlsm', engine='openpyxl')
writer.book = book
writer.vba_archive = book.vba_archive

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df_merge.to_excel(writer, "ETP",startcol=0,startrow=6)
writer.save()
input("Test")


text:
Q: Saving state in OpenCTI iframe between page loads We have an in-house OpenCTI adapter that we use with salesforce. It's primary responsibility is to find associated records and pop the results when a new call comes in.
We have a tendency to have Salesforce open in a number of tabs at once. We quickly found that screen popping in all of these windows was not what we desired.
To solve this problem, we added an enable/disable checkbox to our OpenCTI screen. This way, a user can designate one window as the window to allow screen pops in.
The problem we're encountering is that this checkbox loses its value every time the user navigates to a new page (or pops). Our initial thought was to save the checkbox state in the browser localStorage, but we need to somehow make sure that the state saved is local to the current browser window so that the saved checkbox state isn't shared between all open windows.
To do this, it seems that we need a way to identify the current window, but this doesn't seem possible with cross-domain browser restrictions. We are also failing to find any sort of unique identifier that is tied to the current browser window and is passed by Salesforce to our IFRAME or through any of the OpenCTI JS library calls.
Is anyone aware of a solution to this problem? Can it be solved somehow in the APEX domain? Is there a better workaround?


text:
Q: Cannot install apk file from Eclipse Emulator to Note II I am completely new to Android and Java. I am currently taking a course that is introducing me to Android and Eclipse. I am having an issue. Once I have built my app, I can run it through the virtual app, but I cannot install it to my Galaxy Note II phone. I have debugging, mock and unknown sources allowed. Eclipse can see my phone.
Also, I am able to install the apk through explorer. I recently read that the apk should be signed as well. How do I do this and can anyone else help?
[2013-12-10 18:44:47 - Awesome2a] ------------------------------
[2013-12-10 18:44:47 - Awesome2a] Android Launch!
[2013-12-10 18:44:48 - Awesome2a] adb is running normally.
[2013-12-10 18:44:48 - Awesome2a] Performing myapp.awesome2a.MainActivity activity   launch
[2013-12-10 18:44:48 - Awesome2a] Automatic Target Mode: Unable to detect device compatibility. Please select a target device.
[2013-12-10 18:45:14 - Awesome2a] Uploading Awesome2a.apk onto device '42f73302b863bf67'
[2013-12-10 18:45:15 - Awesome2a] Installing Awesome2a.apk...
[2013-12-10 18:45:16 - Awesome2a] Installation failed due to invalid APK file!
[2013-12-10 18:45:16 - Awesome2a] Please check logcat output for more details.
[2013-12-10 18:45:16 - Awesome2a] Launch canceled!

When I take a look at Logcat, I receive this information.
12-10 18:44:00.002: D/STATUSBAR-Clock(3084): onReceive() - ACTION_TIME_TICK
12-10 18:44:00.007: D/STATUSBAR-Clock(3084): onReceive() - ACTION_TIME_TICK
12-10 18:44:00.032: D/ClockAlarmWidgetService(5457): [ClockAlarmWidgetService] onReceive: action = android.intent.action.TIME_TICK
12-10 18:44:00.032: E/ClockAlarmWidget(5457): [AlarmWidgetIdManager] getListItem() : itemIndex=0, widgetID:1
12-10 18:44:00.032: E/ClockAlarmWidget(5457): [AlarmWidgetIdManager] getListItem() : ItemIndex exceed ListItemCount. itemIndex=1
12-10 18:44:00.032: E/ClockAlarmWidget(5457): [AlarmWidgetIdManager] getListItem() : itemIndex=1, widgetID:1
12-10 18:44:00.032: D/ClockAlarmWidget(5457): [ClockAlarmWidgetProvider] fillData() - itemIndex:0, listitemID: 0
12-10 18:44:00.037: D/ClockAlarmDataProvider(5457): getAlarm() - too many same ID alarm data. nCount: 0
12-10 18:44:00.042: D/ClockAlarmWidget(5457): alarmItem = null
12-10 18:44:00.042: D/ClockWidget(2408): refreshTime()
12-10 18:44:00.047: D/ClockWidget(2408): TTS Message = It is 6 : 44 PM, Tuesday, December 10
12-10 18:44:05.727: E/MtpService(3505): In MTPAPP onReceive:android.intent.action.BATTERY_CHANGED
12-10 18:44:05.727: E/MtpService(3505): battPlugged Type : 2
12-10 18:44:05.727: D/BatteryService(2408): update start
12-10 18:44:05.727: D/BatteryService(2408): level:100 scale:100 status:2 health:2 present:true voltage: 4326 temperature: 249 technology: Li-ion AC powered:false USB powered:true icon:17303211 invalid charger:0
12-10 18:44:05.727: D/STATUSBAR-BatteryController(3084): onReceive() - ACTION_BATTERY_CHANGED
12-10 18:44:05.727: D/STATUSBAR-BatteryController(3084): onReceive() - level:100
12-10 18:44:05.727: D/STATUSBAR-BatteryController(3084): onReceive() - plugged:2
12-10 18:44:05.727: D/STATUSBAR-BatteryController(3084): onReceive() - BATTERY_STATUS_CHARGING:
12-10 18:44:05.732: D/STATUSBAR-PhoneStatusBar(3084): ACTION_BATTERY_CHANGED
12-10 18:44:05.732: D/STATUSBAR-PhoneStatusBar(3084): NORMAL_BATTERY
12-10 18:44:05.737: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:23.687: E/Watchdog(2408): !@Sync 28
12-10 18:44:29.682: E/WifiHW(2408): ##################### set firmware type 0 #####################
12-10 18:44:29.682: D/WifiStateMachine(2408): setWifiEnabled : WifiNative.setFwType(0)
12-10 18:44:29.682: V/AlarmManager(2408): waitForAlarm result :4
12-10 18:44:29.682: V/AlarmManager(2408): trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
12-10 18:44:29.682: D/WifiService(2408): startScan: false pid=3965, uid=10019
12-10 18:44:29.687: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:29.697: I/wpa_supplicant(3889): Scan requested (ret=0) - scan timeout 30 seconds
12-10 18:44:29.762: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:33.347: I/wpa_supplicant(3889): nl80211: Received scan results (9 BSSes)
12-10 18:44:33.347: D/Tethering(2408): interfaceLinkStateChanged wlan0, true
12-10 18:44:33.347: D/Tethering(2408): interfaceStatusChanged wlan0, true
12-10 18:44:33.357: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:33.377: D/dalvikvm(3965): GC_CONCURRENT freed 511K, 8% free 13209K/14343K, paused 1ms+1ms, total 14ms
12-10 18:44:33.377: D/dalvikvm(3965): WAIT_FOR_CONCURRENT_GC blocked 8ms
12-10 18:44:33.382: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:33.412: E/WifiHW(2408): ##################### set firmware type 0 #####################
12-10 18:44:33.412: D/WifiStateMachine(2408): setWifiEnabled : WifiNative.setFwType(0)
12-10 18:44:33.417: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:33.467: I/GCoreUlr(3965): Successfully inserted location
12-10 18:44:33.467: I/GCoreUlr(3965): Not calling LocationReportingService, hasMoved: false, elapsed millis: 780030, request: Phone
12-10 18:44:34.682: V/AlarmManager(2408): waitForAlarm result :4
12-10 18:44:41.742: D/BatteryService(2408): update start
12-10 18:44:41.747: E/MtpService(3505): In MTPAPP onReceive:android.intent.action.BATTERY_CHANGED
12-10 18:44:41.747: E/MtpService(3505): battPlugged Type : 2
12-10 18:44:41.747: D/BatteryService(2408): level:100 scale:100 status:2 health:2 present:true voltage: 4326 temperature: 242 technology: Li-ion AC powered:false USB powered:true icon:17303211 invalid charger:0
12-10 18:44:41.747: D/STATUSBAR-BatteryController(3084): onReceive() - ACTION_BATTERY_CHANGED
12-10 18:44:41.747: D/STATUSBAR-BatteryController(3084): onReceive() - level:100
12-10 18:44:41.747: D/STATUSBAR-BatteryController(3084): onReceive() - plugged:2
12-10 18:44:41.747: D/STATUSBAR-BatteryController(3084): onReceive() - BATTERY_STATUS_CHARGING:
12-10 18:44:41.762: W/AlarmManager(2408): FACTORY_ON= 0
12-10 18:44:41.762: D/STATUSBAR-PhoneStatusBar(3084): ACTION_BATTERY_CHANGED
12-10 18:44:41.762: D/STATUSBAR-PhoneStatusBar(3084): NORMAL_BATTERY
12-10 18:44:41.777: D/dalvikvm(3965): GC_CONCURRENT freed 396K, 8% free 13201K/14343K, paused 12ms+1ms, total 27ms
12-10 18:44:53.687: E/Watchdog(2408): !@Sync 29
12-10 18:44:59.997: V/AlarmManager(2408): waitForAlarm result :8
12-10 18:44:59.997: V/AlarmManager(2408): ClockReceiver onReceive() ACTION_TIME_TICK
12-10 18:44:59.997: W/AlarmManager(2408): FACTORY_ON= 0

I have absolutely no clue. Can you help.

A: Hmm, I would suspect that there is something wrong with the project settings or androidmanifest.xml file. In Eclipse's top bar, can you go to Run > Run Configurations, flip over to the "Target" tab and select "Always prompt to pick device" for your current configuration? Just to make sure it's being deployed to the right device. Presuming that doesn't fix it, could you post the android manifest? Also, are you using any libraries or do you have any external dependencies?

A: Usualy if you go to
Project > Unset build automatically

and then,
Proyect > clean

and then, in project explorer:
right click on project name > refresh

and then,
Proyect > build project

Then uninstall from the device any version of the app that you could have, and try to install it again.


text:
Q: Qué reserva ensureCapacity de ArrayList en Polimorfismo tengo este ArrayList:
ArrayList<Cuenta> cuentas = new ArrayList<>();

Tengo varias subclases entre ellas CuentaAhorro y CuentaCorriente. Cuenta es abstracta con dos métodos abstractos que implementan las subclases.
Tengo dos dudas:
Cuando una subclase redefine un método cualquiera, entonces en memoria, que se tiene, dos copias de cada uno de los métodos, uno de la superclase y otro de la subclase redefinido?
Y esto me hace pensar y aquí viene la otra duda, en el ArrayList cuando se hace ensureCapacity que se guarda anticipadamente en memoria, para objetos o instancias de Cuenta o una simple referencia a un objeto de tipo de Cuenta, por que qué sabe a priori de que objeto va a albergar si usamos el polimorfismo y le añadimos una referencia a un objeto de su subclase.
Gracias anticipadas.
Un cordial saludo.

A: En el ArrayList, cuando se hace ensureCapacity(), ¿qué se guarda anticipadamente en memoria?, ¿para objetos o instancias de Cuenta o una simple referencia a un objeto de tipo de Cuenta?
Desde el punto de vista de ArrayList los elementos que está almacenando son todos de tipo Cuenta, aunque en realidad se traten de CuentaAhorro o CuentaCorriente. He ahí la magia del polimorfismo.
Por otro lado, el tamaño en memoria de una referencia es independiente del tamaño real que ocupan en memoria los datos contenidos de una clase (de tipo genérico Object internamente), por lo que ensureCapacity(N) lo único que hace es reservar memoria para un número N de referencias a clases, ya sean de tipo Cuenta o cualquier otro tipo de clase: las referencias ocuparán lo mismo.
Aquí tienes unos enlaces a la implementación para que puedas ver cómo funciona internamente: referencias, ensureCapacity() y la función real de crecimiento grow().


text:
Q: Ruby Savon: Remove Soap Action from Request I'm using Savon::Model in order to send a SOAP request.
The final result I need look like this:
<env:Body>
  <ins0:ValidateCityPostalCodeZipRequest>
    <ins0:Addresses>
      <ins0:ShortAddress>
        <ins0:City>Toronto</v1:City>
        <ins0:Province>ON</v1:Province>
        <ins0:Country>CA</v1:Country>
        <ins0:PostalCode>L4Y1K7</v1:PostalCode>
      </ins0:ShortAddress>
    </ins0:Addresses>
  </ins0:ValidateCityPostalCodeZipRequest>
</env:Body>

My WSDL only contains the operation named:    ValidateCityPostalCodeZip and accepts as parameter a ValidateCityPostalCodeZipRequest object type.
When I'm trying to send the Request like the code:
  validate_city_postal_code_zip do
    soap.header = {
      "ins0:RequestContext" => {
        "ins0:Version" => "1.0",
        "ins0:Language" => "en",
        "ins0:GroupID" => "11",
        "ins0:RequestReference" => "UserRef"
      }
    }
    soap.body = {
      "ins0:Addresses" => {
        "ins0:ShortAddress" => {
          "ins0:City" => city,
          "ins0:Province" => province,
          "ins0:Country" => country,
          "ins0:PostalCode" => postal_code
        }
      }
    }
  end

The formatted SOAP query I obtain is
 <env:Body>
      <wsdl:ValidateCityPostalCodeZip>
           <ins0:Addresses>
                <ins0:ShortAddress>
                     <ins0:City>te</ins0:City>
                     <ins0:Province>te</ins0:Province>
                     <ins0:Country>te</ins0:Country>
                     <ins0:PostalCode>te</ins0:PostalCode>
                </ins0:ShortAddress>
           </ins0:Addresses>
      </wsdl:ValidateCityPostalCodeZip>
 </env:Body>

Which causing an error from the caller, here's an excerpt from the returned message:
SOAP response (status 200):
[...]
<Errors>
    <Error>
        3001116
        <Description>Service Failed</Description>
        <AdditionalInformation i:nil="true"/>
    </Error>
</Errors>

How can it be possible to modify the name of the operation ?
Thanks


text:
Q: How does Apache Zeppelin visualize data from Hbase? Since Apache Zeppelin supports Hbase as an interpreter and can visualize any backend language that's recognized, I wonder if I can use Zeppelin to directly visualize the data from Hbase?
Right now I can only view the data in the Hbase from the zeppelin.
Any suggestions for good alternatives are also welcome. The ultimate goal is to visualize and perform data analytics on a large set of geospatial data.

A:
can visualize any backend language that's recognized

That's not quite true. The tables and chart visualizations generally require a table structure.
The Hbase interpreter is just a proxy into the hbase shell command on that machine that Zeppelin runs on, and doesn't reformat the results into a table for Zeppelin to recognize and format as a graph.
If you want to actually visualize something, I believe the general solution is to install Apache Phoenix and use that as a JDBC interpreter or install Kylin on Hbase and use that interpreter
See Phoenix example here


text:
Q: Deploy a Django project to AWS EB using Docker and nginx Currently, I try to deploy a Django project to AWS EB but I'm facing a lot of problems. I could dockerize the project and deploy it on the AWS elastic beanstalk. But when I try to access the site I always see: 502 Bad Gateway. Locally, the project runs smoothly. I am not really into nginx and I have no idea how to solve this problem.
This is my project structure:

This is my Dockerfile:
# Creating image based on official python3 image
FROM python:3

MAINTAINER Jaron Bardenhagen

# Sets dumping log messages directly to stream instead of buffering
ENV PYTHONUNBUFFERED 1

# Creating and putting configurations
RUN mkdir /config
ADD config/app /config/

# Installing all python dependencies
RUN pip install -r /config/requirements.txt

# Open port 8000 to outside world
EXPOSE 8000

# When container starts, this script will be executed.
# Note that it is NOT executed during building
CMD ["sh", "/config/on-container-start.sh"]

# Creating and putting application inside container
# and setting it to working directory (meaning it is going to be default)
RUN mkdir /app
WORKDIR /app
ADD app /app/

This is my docker-compose file:
# File structure version
version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_DB_PORT: "5432"
      POSTGRES_DB_HOST: "*******"
      POSTGRES_PASSWORD: "*******"
      POSTGRES_USER: Jaron
      POSTGRES_DB: ebdb
  # Build from remote dockerfile
  # Connect local app folder with image folder, so changes will be pushed to image instantly
  # Open port 8000
  app:
    build:
      context: .
      dockerfile: config/app/Dockerfile
    hostname: app
    volumes:
      - ./app:/app
    expose:
      - "8000"
    depends_on:
      - db
  # Web server based on official nginx image
  # Connect external 8000 (which you can access from browser)
  # with internal port 8000(which will be linked to app port 8000 in configs)
  # Connect local nginx configuration with image configuration
  nginx:
    image: nginx
    hostname: nginx
    ports:
      - "8000:8000"
    volumes:
      - ./config/nginx:/etc/nginx/conf.d
    depends_on:
      - app

This is the Dockerrun.aws File:
{
 "AWSEBDockerrunVersion": "1",
 "Image": {
   "Name": "******/******:latest",
   "Update": "true"
 },
 "Ports": [
   {
     "ContainerPort": "8000"
   }
 ]
}

On-container-start.sh file:
# Create migrations based on django models
python manage.py makemigrations

# Migrate created migrations to database
python manage.py migrate
# Start gunicorn server at port 8000 and keep an eye for app code changes
# If changes occur, kill worker and start a new one
gunicorn --reload project.wsgi:application -b 0.0.0.0:8000

And here is the file for the nginx settings (app.conf):
# define group app
upstream app {
  # balancing by ip
  ip_hash;

  # define server app
  server app:8000;
}

# portal
server {

  # all other requests proxies to app
  location / {
    proxy_pass http://app/;
  }

  # only respond to port 8000
  listen 8000;

  # domain localhost
  server_name localhost;
}

I really appreciate any kind of help!

A: *

*First check this question on stack overflow: link to question.
If this doesn't solve your problem try the below suggestion.

*Try to replace the postgress database with RDS and make sure your RDS and EB environment are in the same VPC. I had this problem when I tried to deploy django project on EB.

*Removing Postgress docker image and connecting it with RDS solved my issue.

*For some reason, EB is stopping postgress images.


text:
Q: Связанные списки, сложение цифр На leetcode.com есть задачка на сложение чисел в связанных списках. Посмотрел решение данной задачи и у меня возник вопрос.
Текст задачи:

You are given two non-empty linked lists representing two non-negative
integers.
The digits are stored in reverse order and each of their
nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading
zero, except the number 0 itself.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

Решение:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
      }
    }
}

Сам вопрос:
Зачем мы создаем дополнительные переменные и присваиваем им ссылки на связанный список?
 ListNode p = l1, q = l2, curr = dummyHead;

Ведь мы можем обращаться к next и через переменную l1 и l2. Но в таком случае код работать не будет:
ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
            int carry = 0;
            while (l1 != null || l2 != null) {
                int x = (l1 != null) ? l1.val : 0;
                int y = (l2 != null) ? l2.val : 0;
                int sum = carry + x + y;
                carry = sum / 10;
                dummyHead.next = new ListNode(sum % 10);
                dummyHead = dummyHead.next;
                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }
            if (carry > 0) {
                dummyHead.next = new ListNode(carry);
            }
            return dummyHead.next;
}

A: Без p и q вполне можно обойтись. А без curr обойтись нельзя.dummyHead указывает на начало списка, и именно его next мы возвращаем. А curr указывает на конец списка, на то место, куда мы добавляем очередную цифру результата.


text:
Q: Export Tainted Canvas We render vector shapes along with background map (Open street maps). But we are not able to export this raster map coming from OSM. Is there any way we can export this map. It throws error 'Tainted Canvas cannot be exported'.
Regards,
Pavan

A: OpenStreep Maps images come without CORS approval (Cross Origin Resource Sharing).
Documentation of CORS enabled image says:
"Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error."
You can try to use the tilePath property to set an image url that points to a server that allows CORS, i.e. its Access-Control-Allow-Origin header allows the resource to be shared with a given origin.
//Initialization
$("#map").igMap({
backgroundContent: {
    type: "bing",
    key: "abcdefghijk123456",
    tilePath: "http://www.example.com/tiles/"
}});


text:
Q: Is it possible to upgrade a second generation iPod Touch to iOS 4.3? Suddenly a lot of my apps are not working on my iPod Touch 2nd gen.  Many of these are telling me that I need iOS 4.3 for them to work.
I've tried updating software in iTunes - but it says my current version 4.2 is the latest and there are no updates to install.
Any ideas?
Please answer
Thanks

A: According to the incredibly useful iOS support matrix v 2.0 (Winter 2012) done by Empirical Magic, the end of the line is running iOS 4.2.1 on an iPod touch (2nd generation).

Apps that target 4.3 or newer are just not going to run on that device unless the developers re-add support for that OS. Since the code set for that device is ARMv6 you can expect more and more apps to be dropping support as time goes by. Thankfully, what you have should keep running indefinitely, but updates will taper off.


text:
Q: Functions $u \in C^{0,1/2}(\mathbb{R}^n)$ satisfy $\|u\|_{C^0(\mathbb{R}^n)} < \infty$ In solving problem sheets for my upcoming functional analysis $2$ exam I encountered the following statement:

Functions $u \in C^{0,1/2}(\mathbb{R}^n)$ satisfy $\|u\|_{C^0(\mathbb{R}^n)} < \infty$.

Here $C^{0,\alpha}(\mathbb{R}^n)$ denotes the space of Hölder continuous functions for $0 < \alpha \leq 1$, i.e. $$C^{0,\alpha} := \{f \in C^0(\mathbb{R}^n) : [f]_{C^{0,\alpha}} < \infty\}$$ where $$[f]_{C^{}0,\alpha} := \sup_{x,y \in \mathbb{R}^n,x\neq y} \frac{|f(x) - f(y)|}{|x - y|^\alpha}$$
What I tried: $$\|u\|_{C^0} = \sup_{x \in \mathbb{R}^n} |u(x)| \leq \sup_{x \in \mathbb{R}^n}|u(x) - u(y)| + |u(y)| \leq\sup_{x \in \mathbb{R}^n}|x - y|^{1/2} [u]_{C^{0,1/2}}+ |u(y)|$$ which does not help much


text:
Q: Sync Files from folder to another using windows task scheduler I was trying to sync files from folder to another automatically,
I managed to do this using windows 10 task scheduler ,
I used a PowerShell code given by someone, then I run it every 5 min,
I wonder if there is any other way to make the task runs every time a file is added to the source folder to avoid running the task every 5 min.

A: yes there is. you can use the FileSystemWatcher. a sample script can be found in the technet gallery: https://gallery.technet.microsoft.com/scriptcenter/Powershell-FileSystemWatche-dfd7084b


text:
Q: Get PostgreSQL resultset column types without executing query using psycopg2 Given an arbitrary PostgreSQL query, e.g. SELECT * FROM (...) AS T, how can I get resultset column names and types WITHOUT actually executing the query using psycopg2 Python3 library?
I saw JDBC solution using getMetaData(), but I cannot figure out how to get that same information in psycopg2.
PreparedStatement pstmt = con.prepareStatement("select ... ");
ResultSetMetaData meta = pstmt.getMetaData();
for (int i=1; i <= meta.getColumnCount(); i++) { ... }

A: As far as I understand, that's not possible without executing(running cur.execute())
But, If you want a Postgres solution using a function that can be used by Psycopg2 as a query, you may use this solution. As you were expecting, this will not execute your query, it simply creates a temporary View which allows us to query it's metadata using the catalog information_schema.columns
CREATE OR REPLACE function define_query(query text)
  RETURNS TABLE( column_name text,data_type text)
LANGUAGE plpgsql AS
$$
DECLARE
v_view_n TEXT := 'temp_view$';
BEGIN
       EXECUTE format( 'CREATE OR REPLACE TEMP VIEW  %I AS %s', v_view_n,query);
       RETURN QUERY  select i.column_name::text, i.data_type ::text
           from information_schema.columns i where i.table_name = v_view_n;
END $$;

Once you've got this function, you can get the definition of any query by simply calling this function and not executing it.
knayak=# select * from define_query('select 1::int as a,''TWO''::text as b');
 column_name | data_type
-------------+-----------
 a           | integer
 b           | text
(2 rows)

A: I think you have to execute something at least.
If you don't want any rows returned, you can query like select * from XXX where false. This query will return types of columns to client with 0 rows.


text:
Q: temp folder in Macos under root? I'm eriting a MacOS script that need to run under admin rights (under 'sudo'). Script needs a temp folder in order to keep some temp files. Unfortunately, there is no 'TMPDIR' under root! If i run 'env' i see TMPDIR with a nice temp path. If i run 'sudo env' i don't see TMPDIR :(. Is it any way to obtain correct "temp folder" path under root?

A: In general, you're supposed to create temp files using the library-provided functions and use the filenames and/or handles provided. On mac, the mktemp(1) command with the "-d" option should do what you want.

NAME
       mktemp -- make temporary filename (unique)
SYNOPSIS
       mktemp [-dqtu] [-p directory] [template]
DESCRIPTION
       The mktemp utility takes the given filename template and overwrites
  a
       portion of it to create a unique filename.  The template may be any
  file-
       name with some number of `Xs' appended to it, for example
       /tmp/tfile.XXXXXXXXXX.  If no template is specified a default of
       tmp.XXXXXXXXXX is used and the -t flag is implied (see below).

A: If there's a $TMPDIR, use it. Otherwise use /tmp (it should exist on Mac too).


text:
Q: How to report a bug to sharepoint 2013 team? I have found a bug in sharepoint 2013 and i want to know whether it is already reported, if not, want to raise a bug on it. But i don't find any door opened for it, can any one help?

A: Try using microsoft sharepoint support.


text:
Q: MySQL stored procedure value of variable returns to null after loop ends Here is my simplified, the value of rent_ids string returns to null after the loop. I already know that the loop is working properly and that the value of rent_ids changes with every itiration.
BEGIN

DECLARE rent_ids VARCHAR(265);
DECLARE tmp_rent_id int;
create temporary table due_rent_ids (rent_id int);
SET rent_ids = "";

set @test = "Insert into due_rent_ids (rent_id) select unit_id from tbl_rent";

PREPARE stmt1 FROM @test;

EXECUTE stmt1;

BEGIN

        DECLARE cur1 CURSOR for select rent_id from due_rent_ids;
        OPEN cur1;

        read_loop: LOOP
            FETCH cur1 INTO tmp_rent_id;

            IF rent_ids = "" THEN
              SET rent_ids = tmp_rent_id;
            ELSE
              SET rent_ids = concat(rent_ids, ", ", tmp_rent_id);
            END IF;

        END LOOP;

        CLOSE cur1;

 END;

 select * from tbl_unit where unit_id in (rent_ids);

 DEALLOCATE PREPARE stmt1;
END

A: You're doing this all wrong. You can't put a comma-separated string in IN (...), the commas have to be in the actual SQL code.
The right way to do this is:
SELECT *
FROM tbl_unit
WHERE unit_id IN (SELECT rent_id FROM due_rent_ids)

Or:
SELECT t1.*
FROM tbl_unit AS t1
JOIN due_rent_ids AS t2 ON t1.unit_id = t2.rent_id

The second form tends to perform better in MySQL.


text:
Q: How to fix "No FileSystem for scheme: gs" in pyspark? I am trying to read a json file from a google bucket into a pyspark dataframe on a local spark machine.  Here's the code:
import pandas as pd
import numpy as np

from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession, SQLContext

conf = SparkConf().setAll([('spark.executor.memory', '16g'),
                        ('spark.executor.cores','4'),
                         ('spark.cores.max','4')]).setMaster('local[*]')

spark = (SparkSession.
              builder.
              config(conf=conf).
              getOrCreate())

sc = spark.sparkContext

import glob
import bz2
import json
import pickle

bucket_path = "gs://<SOME_PATH>/"
client = storage.Client(project='<SOME_PROJECT>')
bucket = client.get_bucket ('<SOME_PATH>')
blobs = bucket.list_blobs()

theframes = []

for blob in blobs:
    print(blob.name)
    testspark = spark.read.json(bucket_path + blob.name).cache()
    theframes.append(testspark)

It's reading files from the bucket fine (I can see the print out from blob.name), but then crashes like this:
 Traceback (most recent call last):
 File "test_code.py", line 66, in <module>
   testspark = spark.read.json(bucket_path + blob.name).cache()
 File "/home/anaconda3/envs/py37base/lib/python3.6/site-packages/pyspark/sql/readwriter.py", line 274, in json
return self._df(self._jreader.json(self._spark._sc._jvm.PythonUtils.toSeq(path)))
 File "/home/anaconda3/envs/py37base/lib/python3.6/site-packages/py4j/java_gateway.py", line 1257, in __call__
answer, self.gateway_client, self.target_id, self.name)
 File "/home/anaconda3/envs/py37base/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
return f(*a, **kw)
 File "/home/anaconda3/envs/py37base/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value
format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o51.json.
: java.io.IOException: No FileSystem for scheme: gs

I've seen this type of error discussed on stackoverflow, but most solutions seem to be in Scala while I have pyspark, and/or involve messing with core-site.xml, which I've done to no effect.
I am using spark 2.4.1 and python 3.6.7.
Help would be much appreciated!

A: Some config params are required to recognize "gs" as a distributed filesystem.
Use this setting for google cloud storage connector, gcs-connector-hadoop2-latest.jar
spark = SparkSession \
        .builder \
        .config("spark.jars", "/path/to/gcs-connector-hadoop2-latest.jar") \
        .getOrCreate()

Other configs that can be set from pyspark
spark._jsc.hadoopConfiguration().set('fs.gs.impl', 'com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem')
# This is required if you are using service account and set true,
spark._jsc.hadoopConfiguration().set('fs.gs.auth.service.account.enable', 'true')
spark._jsc.hadoopConfiguration().set('google.cloud.auth.service.account.json.keyfile', "/path/to/keyfile")
# Following are required if you are using oAuth
spark._jsc.hadoopConfiguration().set('fs.gs.auth.client.id', 'YOUR_OAUTH_CLIENT_ID')
spark._jsc.hadoopConfiguration().set('fs.gs.auth.client.secret', 'OAUTH_SECRET')

Alternatively you can set up these configs in core-site.xml or spark-defaults.conf.
Hadoop Configuration on Command Line
You can also use spark.hadoop-prefixed configuration properties to set things up when pyspark (or spark-submit in general), e.g.
--conf spark.hadoop.fs.gs.impl=com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem


text:
Q: how to do many2one domain filter? i have one calendar.event inherited module there i wanted to make domain filter based on location i.e Asset location again 'asset_catg_id' will filter from 'asset_catg_id' its working fine
from openerp.osv import fields, osv # its cal.event class inherited
class calendar_event(osv.osv):

    _inherit = "calendar.event"
    _rec_name = 'number'

    _columns = {
            'number' : fields.char('Meeting ID',readonly=1),
            #'place' : fields.many2one('stock.location','Substation Location',),

            'place' : fields.many2one('asset.parentlocation','Substation Location',),
            #'location' : fields.selection(STATUS_SELECTION,'Location',  default='Board A'),
            'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',),
             'area_id' : fields.many2one('asset.name','Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True),
            'assetmodelid_add' : fields.many2many('agile.portfolio1','agile_portfolio1_rel','super_id','agile_portfolio1_id','Asset Model Code',),
            'folio_num' : fields.many2many('asset.asset','asset_asset_rel','super_id','asset_asset_id','Folio Num',),
            #'folio_num' : fields.related('folio_num','folio_num',string='Folio Num',relation='asset.asset', type='many2one')
            }

    _defaults = {
                'number' : lambda self,cr,uid,context={}:self.pool.get('ir.sequence').get(cr,uid,'calendar.event'),
                }

class asset_asset(osv.osv): #asset inherited
    _inherit = "asset.asset"
    #_name = "asset_asset"
    _rec_name= "folio_num"
    _columns = {
        'name': fields.char('Asset Name', size=64),
        'asset_catg_id' : fields.many2one('asset.catg', 'Asset Catg Selection',select=True, required=True),
               'area_id' : fields.many2one('asset.name', 'Asset Name Selection', domain="[('asset_catg_id', '=', asset_catg_id)]", select=True, required=True),
        'assetmodelid_add' : fields.many2one('agile.portfolio1','Asset Model Code',domain="[('area_id', '=', area_id)]",),
        'folio_num' : fields.char('Folio No', readonly=1),
        'asse_line':fields.one2many('asset.line','emp_id','Name Plate'),
        'asse_line2':fields.one2many('asset.part','emp_id1','Parts'),
               # 'assed_modelid':fields.many2one('agile.portfolio1','Asset Model ID',select=True, required=True),
        'quantity': fields.char('Quantity',size=64),
        'uom': fields.char('Uinit of Measure',size=64),
        'model_no' : fields.char('Model', size=64),
        'place': fields.many2one('asset.parentlocation', 'Location'),
        #'asset_id':fields.many2one('agile.portfolio','Asset ID'),

    }
class asset_parentlocation(osv.osv):
    _name="asset.parentlocation"
    _rec_name="location_name"
    _columns = {
        'location_name' : fields.char('Asset Location', required=True),
        'parent_location' : fields.many2one('asset.parentlocation','Parent Location'),}

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if not ids:
            return []
        reads = self.read(cr, uid, ids, ['location_name','parent_location'], context=context)
        res = []
        for record in reads:
            name = record['location_name']
            if record['parent_location']:enter code here
                name = record['parent_location'][1]+' / '+name
            res.append((record['id'], name))
        return res


text:
Q: Azure attributes show URLs instead of friendly names in SimpleSAMLphp I am new to SAML and Azure but I need to integrate my PHP web application with Azure and I do not understand how the Azure name attributes (claims?) are working with simpleSAMLphp.
Problem 1 - attributes from Azure are hard to read
This is a returned dataset from Azure - the attributes are named as HTTP URLs:

I can somehow view the purpose of each attribute in the URL but is there a way to show a shorter and more friendly name? Is the friendly names something that should be provided by our Azure team or is there a standard translation that can be done?
Problem 2 - I cannot read all Azure provided attributes/claims
I have been told by our Azure team that they have provided me with more attributes than what is visible in the above picture - e.g. our organization, title and more and they have sent this picture as a proof to me:

This seems to be a weird mix of URLs and friendly names/descriptions but I seem not able to read all Azure attributes from simpleSAMLphp!? Do I need to read the (extra?) attributes in another way than $azure->getAttributes();?
What I have tried
I have (among others) used this guide for setting up simpleSAMLphp, https://www.lewisroberts.com/2015/09/05/single-sign-on-to-azure-ad-using-simplesamlphp/ and that guide refers to the below setup, which I have included in \config\authsources.php:
'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',
'simplesaml.nameidattribute' => 'eduPersonTargetedID',

But to be honest then it confuses me, if this is relevant or not.
I have also viewed How do I map attributes returned by an IDP to friendly names inSimpleSAMLphp? which gets close to my problem but I did not get any closer to a solution.
Any hints or help would really be appreciated :-) My guess is that it is not possible to get friendly names/claims and that our Azure team will need to fix the missing attributes/claims but I do not have any solid evidence for proving this.

A: After more time spent on this and some trial-and-error from our IT department then everything has now been fixed.
It WAS in fact a faulty Azure configuration that did not send the attributes and the weird names/claims could also easily be "translated" by Azure in to short meaningful and friendly names.
This is what I wanted from the beginning:

It still show the weird names for tenantid etc. but I don't care for that as I do not use that. I assume this is some standard attributes being sent from Azure.
The Azure "claims" now looks like this:

Also it was not mentioned by our IT guys but even if they state that it has been fixed then please await for some time before testing as it will take some time from applying the change until it is effective in Azure. At least I noticed it could take 15-30 minutes for adding new attributes though the change of attribute names was done almost instantly.


text:
Q: JavaScript getElementById returns null I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:

 1

 2

 3

 4

next

JS:
var counter = 1;
var button = document.getElementById('next');

button.addEventListener("click",function(){
    var currentDiv = document.getElementById('div-'+counter);
    currentDiv.remove();
    var nextDiv = document.getElementById('div-'+counter+1);
    alert(nextDiv); // why does it return null
    alert('div-'+counter+1); // while this doesn't?
    nextQuestion.style.display = "block";
    counter++;
},true);

A: Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));

The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo

A: This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1

This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this     'div-'+(counter+1)

A: What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.

A: Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');

button.addEventListener("click",function(){
    var currentDiv = document.getElementById('div-'+counter);
    currentDiv.remove();
    var nextDiv = document.getElementById('div-'+Number(counter+1));
    alert(nextDiv); // why does it return null
    alert('div-'+Number(counter+1)); // while this doesn't?
    nextQuestion.style.display = "block";
    counter++;
},true);

A: it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle

A: Here is your answer:

 1

 2

 3

 4

next

A: To solve this kind of returning "null" values by getElementById("").

you can use script inside the body instead of head  it will return the html element.

const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

sample text


text:
Q: L2tpIPsecVpnControlDaemon critical error I am currently trying to use l2tp-ipsec-vpn in my ubuntu machine.
I followed a guide from tuxfamily to install it.
Unfortanely, when I start the system, I got a window with the following error:
A critical error occurred:
L2tpIPsecVpnControlDaemon is not started

Any throughts how to fix it?


text:
Q: Allow temporary pinning or hiding of answers in a given thread I would like the ability to pin an interesting answer on screen when I go to look at more answers (or to hide the uninteresting answers). Granted, I could open multiple browser windows or tabs but this isn't so convenient for comparing two answers.
This would be useful when say comparing opposing views or suggestions, or creating a reference sheet before going away to try them and see what works.

A: I doubt the developers want to spend time implementing features already offered by both the browser and the operating system.


text:
Q: Tweet from authenticated logged in twitter user I have a web app where people can log in through Twitter and by doing so authenticate the app to tweet on their behalf, I want to do this.
But the problem is that I cannot find any endpoints in the twitter API that would facilitate this,
I'm able to tweet from my own app using the Twitter npm package but I can't find a parameter to pass something like a user ID to tweet from a different twitter account using my App.
Do you maybe need the OAUTH token and secret to do this?

A: The solution is to have people sign in on your web page and get their tokenSecret and token from the login, put those in the place where the access_token_key and access_token_secret usually go when tweeting and send a regular statuses/update/ POST request.


text:
Q: Find all $x$ such that $11\mid 3x+7$ I found this question in Beachy and Blair: Abstract algebra book, they even have a solution to this but its not satisfactory for me. They only say "$x\equiv 5 \pmod{11}$ ". Which one can "feel" simply by trial and error. I would like to know what is the proper approach. Thank you in advance!

A: We need $3x+7\equiv 0\pmod{11}$
Add 4 to both sides:
$$3x+11\equiv 4\pmod{11}$$
reduce:
$$3x \equiv 4\pmod{11}$$
multiply both sides by a number to make the coefficient on the left equivalent to $1$. In this case, $4$ works:
$$12x\equiv 16\pmod{11}$$
reduce:
$$x\equiv 5\pmod{11}$$
Does that work for you?

A: ${\rm mod}\ 11\!:\,\ 3x\equiv -7\equiv 4\iff x\equiv \overbrace{\dfrac{\color{#c00}4}3\equiv \dfrac{\color{#c00}{15}}3}^{\large \color{#c00}{4\  \equiv\ 15}}\equiv 5$
Remark $ $ More generally we can use the extended Euclidean algorithm (esp. simple in fractional form) to invert $3$ modulo $11$. But for small numbers other methods are often simpler, e.g. adding $\pm\rm modulus$ to make the division exact (e.g. above we added $11$ to $\color{#c00}4$ to make it divisible by $3)$
Beware $\ $ Modular fraction arithmetic is well-defined only for fractions with denominator coprime to the modulus. See here for further discussion.

A: It's simpler to use  congruences: $11\mid 3x+7$ means $3x+7\equiv 0 \mod11$, or
$$3x\equiv -7\equiv 4\mod4,$$
so all we have to do is finding the inverse of $3$ mod. $11$.
This comes with a Bézout's relation obetween $3$ and $11$:
$4\cdot 3-11=1$, thus $4\cdot 3\equiv 1\mod 11$, therefore
$$4\cdot 3x\equiv 4^2\iff x\equiv 5\mod11.$$

A: $11\mid 3x+7$ is the same thing as saying there exists an integer $y$ such that $3x + 7 = 11y$.
Trying $y=0, 1$ and finally $y=2$, we find that $x=5$ and $y=2$ is a solution. So we consider solutions of the form $x = 5+u$ and $y=2+v$.
\begin{align}
   3x + 7 &= 11y \\
   3(5+u) + 7 &= 11(2+v) \\
   15 + 3u + 7 &= 22 + 11v \\
   3u + 22 &= 11v + 22 \\
   3u &= 11v \\
   3 &\mid 11v \\
   3 &\mid v
\end{align}
So $v = 3t$ and $y=2+3t$ for some integer $t$. The "for some" part is a problem. It suggests that, sometimes, $y=2+3t$ may not be a solution. It is very easy to show $y=2+3t$ is always going to be a solution.
Start with $3x+7=11y$ and let $y = 2+3t$.
\begin{align}
   3x+7 &= 11y \\
   3x + 7 &= 11(2+3t) \\
   3x + 7 &= 22 + 33t \\
   3x &= 33t + 15 \\
   x &= 11t + 5
\end{align}
But, of course, saying $x = 11t+5$ for any integer $t$ means that $x \equiv 5 \pmod{11}$.

A: We need to find all integers $x$ such that
$3x = 11y - 7$ for some integers $y$
$3x = 11(y-2) -7 + 22 = 11(y-2) + 15$ and we get $3x - 15 = 11(y-2)$.
So $11 \mid (3x - 15)$ which can be written $11 \mid 3(x-5)$. $\gcd(3,11) = 1$ and by Euclid's Lemma $11 \mid (x-5)$ then $x = 11t+5$ ($t$ integer) are all the integers such that $3x+7$ is divisible by $11$.

A: We need $$3x+7=11y\iff11y-3x=7(12-11)\iff11(y+7)=3(x+28)$$
$\implies\dfrac{3(x+28)}{11}=y+7$ which is an integer
$\iff11|3(x+28)\iff11|(x+28)$ as $(3,11)=1$
$\implies x\equiv-28\pmod{11}\equiv-28+33$

A: According to you $$3x+7\equiv 0 \pmod{11}$$ $$3x\equiv -7\pmod{11}$$ $$3x\equiv 4\pmod{11} $$ $$3x+11y=4$$
Note that $$3(4)+11(-1)=1$$ which can be deduced by Bezout's identity
Multiplying throughout by $4$ $$3(16)+11(-4)=4$$ which gives $$x=16$$ $$x\equiv 16\pmod{11}$$ $$x\equiv 5\pmod{11}$$
Not so impressive solution but an easier approach to solve this


text:
Q: How to create functions in Fortran? I'm sure the solution to this is extremely basic, but I'm having a hard time figuring out how to use functions in Fortran. I have the following simple program:
  PROGRAM main
    IMPLICIT NONE
    INTEGER :: a,b
    a = 3
    b = 5
    PRINT *,funct(a,b)
  END PROGRAM

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION

I've tried several variations of this, including assigning a data type before FUNCTION, assigning the result of funct to another variable in the main program and printing that variable, and moving the FUNCTION block above the PROGRAM block. None of these worked. With the current program I get an error on line 6 (the line with the PRINT statement):
Error: Return type mismatch of function 'funct' (UNKNOWN/INTEGER(4))
Error: Function 'funct' has no IMPLICIT type

From all of the guides I've tried, I seem to be doing it right; at least one of the variations, or a combination of some of them, should have worked. How do I need to change this code to use the function?

A: Simply putting the function in the file will not make it accessible to the main program.
Traditionally, you could simply declare a function as external and the compiler would simply expect to find a suitable declaration at compile-time.
Modern Fortran organizes code and data in "modules". For your purpose, however, it is simpler to "contain" the function within the scope of the main program as follows:
PROGRAM main
  IMPLICIT NONE
  INTEGER :: a,b
  a = 3
  b = 5
  PRINT *,funct(a,b)

CONTAINS

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION funct
END PROGRAM main

A: A simpler solution can be the following code
 PROGRAM main
    IMPLICIT NONE
    INTEGER :: a,b, funct
    a = 3
    b = 5
    PRINT *,funct(a,b)
  END PROGRAM

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION

where the only difference is in the third line, where I have declared funct as an integer. It compiles and it prints 8 as result.


text:
Q: How to include internal jar files in android library I am trying to download and run an existing android studio project and currently I am getting the error:
error: package com.google.gson does not exist
The java file that needs gson is in the main app section. The gson-2.8.1.jar file is in a client library inside of a libs folder.
So the file structure looks a little like:
project_root
 |-- app/
 |   |-- src/
 |       |-- main/
 |           |-- java/
 |               |-- com.company.stuff/
 |                   |-- controller
 |                       |-- fileThatUsesGson.java
 |-- client/
     |-- libs/
         |-- gson-2.8.1.jar

The app build.gradle shows:
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(path: ':client')
}

The client build.gradle shows:
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/gson-2.8.1.jar')
}

This does seem to be an older project. I had to change compile to implementation which seems like it might be part of the problem but I can't seem to figure out how to add those .jar files.
Any help would be appreciated. Thanks!

A: Expanding on Mr.AF's answer:
In the app build.gradle file I added
dependencies {
    implementation files('../client/libs/gson-2.8.1.jar')
}

sync project with gradle files and make project
Original
File ->Project Structure ->App-> dependencies -> + ->add library


text:
Q: Persisting ZonedDateTime to mysql database using JPA I have a column created_at in mysql database with datatype TIMESTAMP. Through JPA, I was persisting a variable of type java.uti.Calendar to column created_at. Now I want to change the datatype from Calendar to ZonedDateTime and I did. When I save the java object to mysql database, it is throwing the error
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '\xAC\xED\x00\x05sr\x00\x0Djava.time.Ser\x95]\x84\xBA\x1B"H\xB2\x0C\x00\x00xpw\x15\x06\x00\x00\x07\xE1\x09\x0A\x0C\x109)l\xDB\xC0' for column 'u_created_at' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3971)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy97.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 159 common frames omitted

How to solve this issue. I am thinking of converting ZonedDateTime back to Calendar and then save it. Will it work or is there a better way of doing.
Thank you