text:
Q: Hexadecimal valued string to varbinary SQL Server 2008 I have a string with a hexadecimal value, as an example, like so: "AD5829FC..." which is a varbinary I took and saved in hexadecimal to a text file. The thing is, I need to get this back to a varbinary by running an insert query through C# and SQL Server 2008.
How do I get it back to its original format. I am currently using a SQL CAST like so:
CAST('HEX VALUE' AS varbinary(MAX))

NOTE: I need to save it to the text file like I just showed it so that the CSV doesn't get any \n or comma characters from a sequence in the hexadecimal

A: Here is example of T-SQL code to convert your string back to varbinary(max)
declare @hexstring varchar(max)='abcedf012439112200AABBCCFF';
set @hexstring = '0x'+@hexstring;
select CONVERT(varbinary(max), @hexstring, 1);

A: There is no built-in function to do this. Writing a streaming function in C# to do it would be trivial (read 2 chars, emit a byte). You can either use a SQLCLR function to do it inside the engine, or you can do it in the client side. IF the input is large is arguably better to do it in the client side to avoid memory overload.
Here's an example of streaming conversion (no omptimizations, but highlights the important of not converting a string into a byte[]):
namespace hex2bin
{
    class Program
    {
        public static void hex2bin(TextReader sin, BinaryWriter sout)
        {
            char[] block = new char[2];
            bool eof = false;
            do
            {
                int chars = sin.ReadBlock(block, 0, 2);
                switch (chars)
                {
                    case 0:
                        eof = true;
                        break;
                    case 1:
                        // Input is odd length, invalid case
                        throw new Exception("Invalid input");
                    case 2:
                        string sblock = new String(block);
                        byte b = Convert.ToByte(sblock, 16);
                        sout.Write(b);
                        break;
                }
            } while (!eof);

        }

        static void Main(string[] args)
        {
            using (StringReader sr = new StringReader("AD5829FC"))
            {
                using (BinaryWriter bw = new BinaryWriter(new MemoryStream()))
                {
                    hex2bin(sr, bw);
                }
            }
        }
    }
}

A: If I understand correctly you want to convert every 2 characters to a byte, this can be achieved using the already answered question.
Convert hex string to byte array also How to Convert Hex String to Byte[]
Hope it helps.


text:
Q: MySql status order by I have a query in messages table and i want them to be sorted by the status of the message. Those that have status like 'unread' and the recent ones must comes first.
How should i do the order by clause in which those unread will be on top as well as among those unread, those that comes last will be on top?
This is my code
   select message_id,sender,penname,dp,message,TIMEDIFF(now(),date_sent) as date,status
   from message_log,user
   where recepient = 11 and sender = user_id

A: Use the order by clause:
select message_id,sender,penname,dp,message,TIMEDIFF(now(),date_sent) as date,status
from message_log,user
where recepient = 11 and sender = user_id
order by status = 'unread' desc,
      date_sent desc;

This puts all the "unread" ones at the top, in date descending order.  Then the rest of the messages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to treat member of Num typeclass as an Int This is a function I'm trying to write:
missingNumber :: (Num a) => [a] -> a
missingNumber list = (sum refList) - (sum list)
  where refList = [1..n]
        n = length list

Given a list of numbers, I want to sum them and compare them to a known list to see if any are missing. This code seems straightforward, but when I run it I get this (rather verbose) error:
Could not deduce (a ~ Int)
from the context (Num a)
  bound by the type signature for missingNumber :: Num a => [a] -> a
  at missingnumber.hs:1:18-36
  `a' is a rigid type variable bound by
      the type signature for missingNumber :: Num a => [a] -> a
      at missingnumber.hs:1:18
Expected type: [a]
  Actual type: [Int]
In the first argument of `sum', namely `refList'
In the first argument of `(-)', namely `(sum refList)'
In the expression: (sum refList) - (sum list)

I'm guessing this is happening because n in [1..n] must be an instance of the Enum type class in order to be iterated over in sequence. But (assuming I'm correct), how do I cast a as two types? Also... shouldn't Int be a member of the Num class?

A: as you asked this should work:
missing :: (Num a, Foldable t) => t a -> a
missing xs = fromIntegral (sum [1..length xs + 1]) - sum xs

but only if your list of numbers is just missing one number in [1..m] for some m

your version don't work because you claim
missingNumber :: (Num a) => [a] -> a

and then it needs to work for all Num a - for example Double - but then you will mix Int with Double (for example) - which you cannot do
fromIntegral saves you here because it will bring back your Int into any Num a you might have there (it's fromIntegral :: (Integral c, Num d) => c -> d - here you have c ~ Int and d ~ a - where ~ means type-equality)


text:
Q: Avoid the problem with recurring tasks I am looking to find a work around and solution of the problem  "Error: You cannot reassign a recurring task occurrence." as I'm assigned to transfer many tasks and most of them are recurring.
Could you please suggest and help me find an appropriate solution.

A: My recommendation would be to clone your list of recurring Tasks, assign the desired new owner to the cloned Tasks, then insert your cloned list as new Tasks, then set the RecurrenceEndDateOnly of the existing recurring Tasks to Today() and finally update that existing list of recurring Tasks. That should allow those tasks to come to a conclusion at the same time while creating replacements that will belong to the new owner you want them assigned to.
From the Object Reference:

*

*When you change the value of RecurrenceEndDateOnly to an earlier date (for example, from January 20th to January
  10th), all open task occurrences in the series with the ActivityDate value greater than the new end date value are deleted.
  Other open and closed task occurrences in the series are not affected.

You'll also want to be aware of this behavior:

*

*When you change the RecurrenceStartDateOnly field or the recurrence pattern, all open tasks occurrences in the
  series are deleted and new open task occurrences are created based on the new recurrence pattern. The recurrence pattern
  is determined by the following fields: RecurrenceType, RecurrenceTimeZoneSidKey, RecurrenceInterval,
  RecurrenceDayOfWeekMask, RecurrenceDayOfMonth, RecurrenceInstance, and RecurrenceMonthOfYear.

Because of the above, unless you want to calculate the correct new start date (because of the recurrences that have likely happened since the original start), I would be very cautious of resetting the RecurrenceStartDateOnly field when you insert the new Tasks as it likely won't be Today(). Yet, that would also be the proper way to do it.


text:
Q: How can I sort my JSON file by nested value? So I have a JSON file that looks like this:
{
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

And I want it to be sorted by "val," so that it looks like this:
{
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

How would I go about doing this?

A: Try this:
data = {
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

data = sorted(data.items(), key=lambda x: x[1]["val"], reverse=True)

print(data)
# [('PlayerB', {'val': 1000, 'level': 1}), ('PlayerA', {'val': 200, 'level': 1}), ('PlayerC', {'val': 30, 'level': 1})]


text:
Q: Installing sagemath binaries in Ubuntu 20.10 flatpack chromium and jupyter notebook As mentioned in other posts the sagemath package is only available in the LTE releases.The binary release 9.2 seems to work mostly. Part of the reason I'm asking my question is to document what I did to get the terminal version running.
So I downloaded sage-9.2-Ubuntu_20.04-x86_64.tar.bz2 from one of the mirrors and unpacked it into my desired directory. Running ./sage results in the following error
/usr/bin/env: 'python': No such file or directory

I found this simple way to get this working without a recompile:
sudo apt install python-is-python3

./sage now runs in the terminal but running
./sage -n jupyter

results in the error Access to the file was denied when loading file:///home/user/.local/share/jupyter/runtime/nbserver-111854-open.html
The notebook is active if I copy & paste into firefox. Clearly this is a problem with the flatpack "jail" that chromium lives in.
Personally, I'd rather not switch my default browser for the system to firefox and I would like to accomplish the following:

*

*Have a command to run the sage jupyter notebook directly in firefox or bypass the flatpack restrictions in chromium.

*Add a sage command to my gnome launcher


text:
Q: Use cases for overriding save method in Django Suppose I have a ModelForm and want to save the form. I know that we can override save method in django in the forms and models python code. But I want to know when exactly we should use saving forms in views, override save in forms and override save in models?

A: There's no right answer.
All you can do is choosing case by case:
Forms:
Specific methods will be used specifically when model is saved using this form.
Models:
Method will (almost) be used when saving models.
A third way you don't mention is Signals.


text:
Q: Why Java graphicsenvironment can and cannot update unplug monitor changes? I'm using java graphics environment to detect monitor changes, it can detect correctly when unplugged an extended monitor ( run with a simple class ).
But in my company project. It can't update monitor correctly when I unplugged an extended monitor ( it show correctly when I ran applet with 2 monitors first times). When I unplugged and ran it again, it showed 2 devices with wrong devices in the second data. ( I use latest jre 8 both )
I found this is the same issue with me.
How to listen to graphic environment or device changes in java
GraphicalEnvironment does not update screen devices after switching off second screen
So I don't understand why it can and it can't when update plugged monitors.
I try with declare new instance. But my company project was down when re-login.
Could you give me any solution.
Simple code for detect
GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();

enter code here


text:
Q: How to run pylint on hg commit? How to run pylint on hg commit ?
I've seen https://github.com/sebdah/git-pylint-commit-hook but I've also seen comments that I should be using a "Continuous Build System". In the context of a small side project I'm not sure what that means ? I'm assuming Jenkins, etc but that seems way over the top ? I would use git-pylint-commit-hook but I'm getting errors from when it tries to popen pylint and it all feels like a lot of pain.

A: OK I've worked this out.
Setup Paver so it does the commit and before doing the actual commit will run pylint and stop the commit if the results from pylint aren't what they should be.


text:
Q: Reverse DNS lookup in Python If I have an IP address like 2001:4860:4860::8888
How can I get the fully qualified domain in the format foo.ip6.arpa ?
EDIT: Both the solutions so far give me google-public-dns-a.google.com - maybe Reverse DNS was the wrong name. For this I'd expect the output to be something like 8.8.8.8.0...etc.ip6.arpa

A: IPy provides methods for what you want:
>>> from IPy import IP
>>> ip = IP('127.0.0.1')
>>> ip.reverseName()
'1.0.0.127.in-addr.arpa.'

Works for both IPv4 and IPv6, although the original IPy has a few bugs for IPv6. I created a fork with some extensions and fixes at https://github.com/steffann/python-ipy which you can use as long as the fixes haven't been merged back into the original code.
Update:
You can of course also use the getnameinfo function in built-in socket module:
>>> import socket
>>> socket.getnameinfo(('2001:4860:4860::8888', 0), 0)
('google-public-dns-a.google.com', '0')
>>> socket.getnameinfo(('127.0.0.1', 0), 0)
('localhost', '0')

You need to provide a host+port tuple, but you can provide 0 for the port, and you'll get the hostname back.

A: using dnspython.
from dns import resolver,reversename
addr=reversename.from_address("2001:4860:4860::8888")
str(resolver.query(addr,"PTR")[0])


text:
Q: Javascript Delete A Specific Row I'm trying to get a script to delete a table row.
var i = 1;

function addURL() {
    var tr = document.createElement('tr');
    tr.setAttribute("id", "url_row_" + ++i);
    var td = tr.appendChild(document.createElement('td'));
    td.style.valign = 'middle';

    td = tr.appendChild(document.createElement('td'));
    var input = td.appendChild(document.createElement('input'));
    input.name = 'url[]';
    input.type = 'text';
    input.size = '40'
    var node = document.getElementById('myTable').tBodies[0];
    node.insertBefore(tr, node.children[3]);

    var link = document.createElement("a");
    link.setAttribute("href", "");
    link.setAttribute("style", "text-decoration: none;");
    link.setAttribute("onClick", "removeURL('');return false;");
    td = tr.appendChild(document.createElement('td'));
    td=td.appendChild(link)
    td.appendChild(document.createTextNode('-'));
}

function removeURL(divNum) {
    var d = document.getElementById('myTable').tBodies[0];
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
}

This can produce as many url_row_(number) text fields as I want. I just don't know how to delete those rows.
I know doing
link.setAttribute("onClick", "removeURL('url_row_2');return false;");

will delete url_row_2, but what can I put at url_row_2 that will grab whatever id that the row is or what is the correct code to do this?

A: To do it that way, you would use string concatenation to concatenate i into the handler string to target the given tr.
link.setAttribute("onclick", "removeURL('url_row_" + i + "');return false;");

A: Don't use setAttribute for event listeners. Have a look at the Introduction to event handling at quirksmode.org, and especially on the simple event registration model. Also, you can just use the information from the event object to identify the row to remove:
function clickHandler(event) {
    var anchor = this; // == event.targetElement
    var tr = anchor.parentNode.parentNode;
    tr.parentNode.removeChild(tr);
    event.preventDefault(); // do not follow the href
}

function addURL() {
    …

    var link = document.createElement("a");
    link.setAttribute("href", "#");
    link.setAttribute("style", "text-decoration: none;");
    link.onclick = clickHandler;
    td = tr.appendChild(document.createElement('td'));
    td.appendChild(link)
    link.appendChild(document.createTextNode('-'));
}


text:
Q: Multiple Regions in Customer Registration Form We need to add a US/Canada <option> element before region_id to select US or Canada in the Registration Form, and change the region_id <option> element based on if the user selects either using javascript. Here is the current template, which looks similar to the magento default:

    <?php echo $this->__('State/Province') ?> *
    <select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" class="validate-select" style="display:none;">
       <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
    </select>

    <input type="text" id="region" name="region" value="<?php echo $this->htmlEscape($this->getRegion()) ?>" title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />

In the Admin panel under System -> Configuration -> General, Countries allowed are United States and Canada. If I can pull these both separately into a javascript array then switching them will be much easier. How can I accomplish this?
Edit: Just had an idea for this, is it possible to detect if the visitor is in US/Canada based on $_SERVER environment variables to auto select a region to populate State/Providence once and not involve javascript?

A: Yes there is mod_geoip2 for apache to get the location from the ip:
http://dev.maxmind.com/geoip/mod_geoip2

A: Here is my extension which allows GeoIP integration on Magento level
https://github.com/tim-bezhashvyly/geoip


text:
Q: Ajax - Notice : Undefined index when using $_GET in PHP I'm creating for a school assignment a sort of social media platform. I've created a simple chat tool. Each friend relation has a single conversation.
The problem is that when I reload all the chat messages using Ajax, I can't use the $_GET method to get the conversation id which I saved in the url. Without this id I can't use the function in my Chat class.
I'm sorry if some code is written in Dutch.
The url looks like this chat.php?gesprek_id=1. Gesprek or Conversation Id is like I said saved in the url. After the Ajax request I receive the notice:

'Notice: Undefined index: gesprek_id in ...'

It refers to the $_GET method in php.
My code:
Chat Class:
public function getNewMessages($gesprekId){
    $conn = Db::getInstance();
    $stm = $conn->prepare("SELECT * from chat WHERE gesprek_id = :gesprek_id AND tijd > :tijd");
    $stm->bindValue(":gesprek_id", $gesprekId, PDO::PARAM_STR);
    $stm->bindValue(":tijd", $_SERVER['REQUEST_TIME'], PDO::PARAM_STR);
    $stm->execute();
    $res = $stm->fetchAll();
    return $res;
}

Php for Ajax
<?php
header('Content-Type: application/json');

include_once('../classes/Db.php');
include_once('../classes/Chat.php');

session_start();

$gesprekId = $_GET['gesprek_id'];

$chat = new \Kvm\Chat();
$newMessages = $chat->getNewMessages($gesprekId);
?>

<?php foreach ($newMessages as $message): ?>
    <?php $profile = $chat->getUserMessage($message['user_id']); ?>
        <?php if ($message['user_id'] == $_SESSION['user_id']): ?>

                    <img class="profileSmall" src="<?php echo $profile['avatar']; ?>"/>

<?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?>

<?php echo $message['message'] ?>

    <?php else: ?>

                <img class="profileSmall src="<?php echo $profile['avatar']; ?>"/>

<?php echo $profile['firstname'] . ' ' . $profile['lastname']; ?>

<?php echo $message['message'] ?>

    <?php endif; ?>
<?php endforeach; ?>

Edit in Ajax (added a few lines to find the correct 'gesprek_id' with the solution of the $_GET issue)
Ajax/Jquery:
$(document).ready(function () {

function loadchat() {
    var messageList = $('#allMessages');
    var gesprekId = $('.message').attr('data-gesprekId');
    $(messageList).load('ajax/newChat.php?gesprek_id='+gesprekId);
}
setInterval(loadchat, 50000);
loadchat();
});

I hope that my question is clear.
It's also my first question asked in Stackoverflow so I'm sorry if something is not well described. (and sorry if I made some errors in English ;) )
Thank you by advance.

A: Change your call to
$(messageList).load('ajax/newChat.php?gesprek_id=abc');

It should start working.
Basically, you're trying to make a GET request to newChat.php . You're trying to access the same parameter in PHP. Since, there are no GET parameters, GET is throwing a warning.
But, in this load function. you're not sending any GET parameters. Hence, the change to gesprek_id=abc.
About doing a polling repeatedly, You need to rewrite the setInterval function better.
setInterval(function() {
      // Do something every 5 seconds
      loadchat();
}, 5000);

I'm not sure if this is the ideal way. Something feels a little odd here. But, I would think, there will be better ways of doing this. Anyhow, I've rewritten the setInterval call for you.


text:
Q: Error in drupal-commons installation i´ve got drupal 7 installed on my pc running on localhost from Acquia Dev stack. Now i tried to installed Drupal-Commonns, but i got this error when the Install Profile stage is running:
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows.
Path:
.......
siteChoose site color paletteEnter Homepage welcome textCreate the first groupFinished
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dc.watchdog' doesn't exist

what might it be?
thanks

A: You need to enable Database logging module.
This module will create watchdog table.
After that this error will go away.
Hope this will help. :)


text:
Q: EF migrations: creating DbContext instance Is it possible to "tell" migration how to create MyDbContext instance? By default it uses a public parameterless constructor and searches for the connection string in AppConfig with the same as MyDbContext class. Can I tell somehow configure migration to use some factory method to create MyDbContext instance, which it will use to to the migration?

A: I don't know how to make migration uses a parameterless constructor of the DbContext, but I would use my configuration class and my Initializer to inject some connection string for example. Maybe it can help you.
public class MyDbInitializer : IDatabaseInitializer<MyDbContext>
{
    private readonly DbMigrationsConfiguration _configuration;

    public MyDbInitializer(string connection)
    {
        _configuration = new Configuration(connection);
    }

    public void InitializeDatabase(MyDbContext context)
    {
        if (!context.Database.Exists())
        {
            context.Database.Create();
        }
        else
        {
            var migrator = new DbMigrator(_configuration);
            if (migrator.GetPendingMigrations().Any())
                migrator.Update();
        }
    }
}

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration(string connectionString)
    {
        this.TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo(connectionString);
        AutomaticMigrationsEnabled = true;
        ContextKey = "MyProj.Models.MyDbContext";
    }
}

public MyDbContext()
{

}

public MyDbContext(string connection)
{
   Database.SetInitializer(new MyDbInitializer(connection));
}

A: You can create a class that implements the IDbContextFactory<MyDbContext> interface and that contains your custom code for creating an instance of MyDbContext.
Design-time tools as well as migrations tools will auto-discover this class (if it is palced in the same assembly as your DbContext) and will use it to initialize the MyDbContext.
public class MigrationsContextFactory : IDbContextFactory<MyDbContext> {
    public MyDbContext Create() {
        return new MyDbContext(connectionString, someOtherSettings);
    }
}

See documentation for reference.


text:
Q: Braintree form error: ncaught TypeError: FormNapper requires an HTMLFormElement element or the id string of one - Magento 2.1 We have Magento 2.1 installed and we are completing the integration with Braintree, everything seems to be working fine, however, on latest version of Chrome shows this error:

braintree-2.17.6.min.js:4 Uncaught TypeError: FormNapper requires an HTMLFormElement element or the id string of one.

I have contacted Braintree but they said their hosted forms doesn't have this issue and that is something in Magento.
Anyone had this issue?


text:
Q: pgfplot height setting does not work when scale only axis is off I have the following plot, but no matter what I choose the height to be, it has no effect on the plot height. The only way it works is when I use scale only axis option, but I do not want that. What gives?
\begin{tikzpicture}
\begin{axis}[width=3cm,
height=6cm,
footnotesize,
xmin=1,
xmax=15,
xlabel={X},
xmajorgrids,
ymin=0.2,
ymax=1.2,
ylabel={Y},
ymajorgrids,
axis background/.style={fill=white},
legend style={legend cell align=left,at={(axis cs:0.,0.2)},anchor=south}
]
\addplot [color=mycolor1c,dashed,mark size=5pt,mark=x,mark options={solid}]
table[row sep=crcr, y expr=\thisrow{Y}*.5]{%
    X    Y\\
    1   1.98396947369363\\
    2   1.86736194644617\\
    3   1.39672685380491\\
    4   1.81801351792524\\
    5   1.65800541448776\\
    6   1.72124859501669\\
    7   1.95053632111296\\
    8   1.5953158074501\\
    9   2.20484922246232\\
    10  2.06660239159798\\
    11  1.15700938093597\\
    12  1.70354273363983\\
    13  1.97071496027903\\
    14  1.5377824362414\\
    15  1.34852389652374\\
};
\addlegendentry{1};

\addplot [color=mycolor3c,solid,mark size=3.0pt,mark=o,mark options={solid}]
table[row sep=crcr, y expr=\thisrow{Y}*.5]{%
    X    Y\\
    1   1.98396947369363\\
    2   1.87985797050402\\
    3   1.81018984587384\\
    4   1.45668153706335\\
    5   1.45662344223124\\
    6   1.42321790298663\\
    7   1.58846550051792\\
    8   1.7261014576169\\
    9   1.84497235618249\\
    10  1.83868784206141\\
    11  1.91262415124094\\
    12  1.87950764557444\\
    13  1.16064983693758\\
    14  1.28630813303169\\
    15  0.729867599135851\\
};
\addlegendentry{2};

\addplot [color=mycolor2c,solid,mark size=3.0pt,mark=*,mark options={solid}]
table[row sep=crcr, y expr=\thisrow{Y}*.5]{%
    X    Y\\
    1   1.98396947369363\\
    2   1.58099605261815\\
    3   1.25697492063651\\
    4   1.46582314712387\\
    5   1.3939586089965\\
    6   1.32595119844705\\
    7   1.41440624648194\\
    8   1.53386555109464\\
    9   1.7654715541107\\
    10  1.54694708739791\\
    11  1.53904078916298\\
    12  1.66515096650716\\
    13  1.09210648149942\\
    14  1.2047294527546\\
    15  0.647646671362433\\
};
\addlegendentry{3};
\end{axis}
\end{tikzpicture}%

A: Torbjørn T.'s answer worked for me:

Switch the order of the options. The footnotesize key sets (among
  other things height, so your definition of height is overwritten. With
  footnotesize,height=3cm, 3cm should be the one that's used. – Torbjørn
  T. Sep 9 at 21:10


text:
Q: Codeship cloning another repository from one repository I have created a repository on the codeship and push my code on that repository. I have another repository which is dependent on the this repository.When i am trying to create the build it is going to clone the   another repository.I am getting access denied error.I can not add two codeship key to one project.
Can anyone please help me out for this issue?
Thank you.

A: do you have a build url that you could share here? Sounds like you'll need to add the CodeShip project's public ssh key to the additional repositories -- https://documentation.codeship.com/basic/builds-and-configuration/access-to-other-repositories


text:
Q: How to implement the conditional probability for each pixel? I have asked a 'very broad' question yesterday link about build conditional random field based energy function from images. I got negative feedback from the comments and I think I should modify the question and make it more specific.
Here I have got bunch of images with a cow on the grass and some sky at the background. I want to segment the cow from the grass and sky (a toy problem only).
I firstly over-segment the images using some super-pixel method, and I have got the ground truth of labels of my 10 training images. Here is an example,

Then I pass these super-pixel patches to some filter to get texture features and saved them into feature vectors for cow (c), grass (g) and sky (s)
My question is how to using Matlab to implement the conditional probabilities of these three classes?
Like P(X_i|C_c), P(X_i|C_g) and P(X_i|C_s)? X_i are each super-pixel, C_x are the three classes.
I think some webpage mentioned about using Matlab hist function. Not sure how and why to do that. Please give me some basic applicable hints not complicated papers. Thanks a lot. A.


text:
Q: What's the most clean and pythonic way to load data from one of two file paths? Why can't I catch two of the same Exceptions? I have two potential file-paths where my application can read specific data from. If one fails, I want it to read from the other.
My intuitive attempt to do so was with try...except clauses, having something as below:
# Try the first file path
try:
    file = open(possible_path_1)
    content = file.read()

# File is not in first location, try the second
except IOError:
    file = open(possible_path_2)
    content = file.read()

# Could not read from either location, throw custom CriticalException
except IOError:
    raise CriticalException("Could not read the file!")

However, this does not seem to work as intuitively expected. The second IOError is never caught. Why is this the case? Is there any "clean" way to read from one file path or the other without having to manually check os.path.exists(filepath) and os.path.isfile(filepath)?

A: Here's an alternative, but not sure if it is "prettier":
for path in paths:
    try:
        file = open(path)
        content = file.read()
    # File is not in first location, try the second
    except IOError:
        continue
    break
else: # for-else gets executed if break never happens
    raise CriticalException("Could not read the file!")

Assuming you have all your possible paths in some container, paths
Although honestly, I simply wouldn't use exception handling here, I think this is much clearer (and of course, I would use pathlib not os.path:
from pathlib import Path

for path in map(Path, paths):
    if path.exists():
        content = path.read_text()
        break
else:
    raise CriticalException("Could not read the file!")


text:
Q: How to use a max of 4GB of memory on ElasticSearch? I am trying to optimize the use of memory in Elastic Search to use max 4GB on a macOS. I know the following code works on Windows, but when I run it on Mac it doesn't work:
./elasticsearch -Xmx4g -Xms4g

When running it on Mac it says the following message:
ERROR: Parameter [-Xmx4g]does not start with --

I have tried to run it without "-" and still does not work.
Any ideas on how to run it on Mac?

A: Try using this command instead
ES_JAVA_OPTS="-Xms4g -Xmx4g" ./bin/elasticsearch

or use the jvm.options file mentioned here
Source: https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html


text:
Q: Difference DNX and .NET Core I couldn't find any answer online so I try it here: What is the difference between the DNX (.NET Execution Environment) and the .NET Core?
I know that the DNX is the SDK and also used to execute code and the .NET Core contains the CoreFX (Libraries) and the CoreCLR (the common language runtime).
But I still don't get what it is precisely about between DNX and the .NET Core.

A: My understanding is that .NET Core is the core Common Language Runtime and various .NET libraries used in .NET applications. This would be things like Microsoft.AspNet.Server.Kestrel, Microsoft.AspNet.Mvc, Microsoft.AspNet.Tooling.Razor, etc.).
DNX is the .NET executioner, which is responsible for running your .NET application. Basically, you would install one or more DNX (clr, coreclr, mono) versions. Then you would build your application and type something like dnx run or dnx web from the command-line to run your application.
There is also DNVM (the .NET version manager), which is the tool used to maintain (install, upgrade, uninstall, etc.) versions of DNX. You would do this by entering commands like dnvm upgrade, dnvm install <dnx_version>, dnvm uninstall <dnx_version>, dnvm use <dnx_version>, etc.
And then there is DNU (the .NET Utilities manager), which manages the dependencies your application relies on located in your project.json file every time you add/remove new dependencies in your project.json file, dnu restore would need to be run in order to update the dependencies your application relies before running dnx run or dnx web.
I've heard that dnx, dnvm, dnu will all be under dotnet soon as .NET 5 is now being called .NET Core 1.0


text:
Q: Adding all elements of an array except the element at index with O(n) complexity This is what i came thru a problem in some coding test.
problem statement was like that we have to add all the elements of an array except the element at the index. subtraction operator cannot be used here and complexity should be O(n).
like
arr={3,7,8,4,9}
then result array will be... sum={28,24,23,27,22}
i have think a lot over it. but still missing something. some hint or pseudo code will be appreciable.
Concluded:
if there is not any other reasonable answer to this then achieving subtraction by any mean could be possible solution. i have concluded it with using -1*arr[i] or complexity will be O(n2).
Edit: Above conclusion is not correct.

A: Since the complexity of O(2n) = O(n), you can use one loop to calculate the entire sum.
Then a second loop after wards and set the value at the index as
arr[i] = totalSum-arr[i]
Edit: woops, did forget that you can't use subtraction.
But hey, subtraction is equivalent to an addition with the two's complement, LOL.
Edit: Here is the solution in python2
arr = [3,7,8,4,9]
sum = 0
for elem in arr:
    sum += elem

for i in xrange(len(arr)):
    elem = arr[i]
    elem = ~elem + 1
    arr[i] = sum + elem

print arr

Output
./bla.py
[28, 24, 23, 27, 22]

A: A simple O(n) approach that uses only addition (and no "cheats" like -1*elem or ~elem + 1 to simulate subtraction) is to do two passes:

*

*Create the result array sum.

*In a "forward" pass from index 0 to index n−1, set each element of sum to the sum of all "previous" elements in arr:
int sumOfAllPrevious = 0;
for (int i = 0; i < n; ++i) {
  sum[i] = sumOfAllPrevious;
  sumOfAllPrevious += arr[i];
}

*In a "reverse" pass from index n−1 to index 0, augment each element of sum with the sum of all "later" elements in arr:
int sumOfAllLater = 0;
for (int i = n - 1; i >= 0; --i) {
  sum[i] += sumOfAllLater;
  sumOfAllLater += arr[i];
}

A: package assignments;

import java.util.Arrays;
import java.util.Scanner;

public class sumOfArrayExceptItself {

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        int n,i,j, sum=0,m=0;
        n=sc.nextInt();
        int arr[]=new int[n];
        int arr1[]=new int[n];
        for (i=0;i<n;i++) {
            arr[i]=sc.nextInt();
        }
        for(i=0;i<n;i++) {
            for(j=0;j<n;j++) {
                sum=sum+arr[j];
            }
            int a = sum-arr[i];
            arr1[i]=a;
            sum=0;
        }
        System.out.println(Arrays.toString(arr1).replace("[", " ").replace("]", " ").replace(","," "));
    }

}


text:
Q: Where do I put this javascript code? I'm using jQuery UI for the first time, and I'm going to create a datetimepicker control for a DOB field.
Here is how the view looks:
    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<StronglyTypedHelpers.Models.Person>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Index

    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>

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

                <%: Html.TextBoxFor(model => model.Name) %>
                <%: Html.ValidationMessageFor(model => model.Name) %>

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

                <%: Html.TextBoxFor(model => model.Age) %>
                <%: Html.ValidationMessageFor(model => model.Age) %>

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

                <%: Html.TextBoxFor(model => model.DOB, String.Format("{0:g}", Model.DOB)) %>
                <%: Html.ValidationMessageFor(model => model.DOB) %>

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

                <%: Html.CheckBoxFor(model => model.Married) %>
                <%: Html.ValidationMessageFor(model => model.Married) %>

                <input type="submit" value="Save" />

        </fieldset>

    <% } %>

        <%: Html.ActionLink("Back to List", "Index") %>

</asp:Content>

Now the UI documentation says to use this code:
$('#date').datepicker();

Where do I put that?
Here is the link to what I'm reading:
http://learn.jquery.com/jquery-ui/getting-started/

A: This should work... just put this anywhere you have HTML

yeah, the problem is that you don't have a jquery declaration... thats why you do $({ })
you can also do this which is the more universal way:

this you should be able to put anywhere, but its probably best in the head bit of your html.

A: You can put it at the end of the document, like this:
.
.
.

Or, if you have the jquery.js and jquery-ui.js called in the head of the page, just add

just before the  tag

A: you cant put javascript in your title. you must put it in your content
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Index

  ...

the document.ready is like the old javascript windows.onload, only, the document.ready fires more early, and doesnt wait for images to be loaded :)


text:
Q: Proof of Newton's Binomial Theorem I have two issues with my proof, which I will present below. Recall Newton's Binomial Theorem:
$$(1+x)^t=1+\binom{t}{1}x+\cdot\cdot\cdot=\sum_{k=0}^\infty \binom{t}{k} x^k$$
By cleverly letting $$f(x)=\sum_{k=0}^\infty \binom{t}{k} x^k,$$
we have
$$f'(x)=\sum_{k=1}^\infty \binom{t}{k} k x^{k-1}$$
Claim: $(1+x)f'(x)=tf(x)$
First problem: I would have not been able to come up with this relation had I not assumed that $f(x)=(1+x)^t$
Proof of Claim: Compare coefficients of $x^j$
For the left hand side $(1+x)f'(x)$, we have
\begin{align*}
\binom{t}{j+1}(1+j)+\binom{t}{j}j=&j\left(\binom{t}{j}+\binom{t}{j+1}\right)+\binom{t}{j+1}\\
=&j\binom{t+1}{j+1}+\binom{t}{j+1}\\
=&\dfrac{t!t(j+1)}{(t-j)!(j+1)!}=\dfrac{t\cdot t!}{(t-j)!j!}\\
=&t\binom{t}{j}
\end{align*}
where the second inequality follows from Pascal's Triangle.
For the right hand side $tf(x)$, we have $t\binom{t}{j}$.
Second Problem: I am not quite sure if comparing coefficients is rigorous enough when proving these theorems. If I show that the degrees of the two polynomials are equal, would that be sufficient?

A: I imagine the issue is to prove the given identity for $t\in\mathbb{R}\setminus\mathbb{N}$, otherwise induction is enough.
By definition of real exponentiation, for any $|x|<1$ we have
$$(1+x)^t = \exp\left(t\log(1+x)\right) = \exp\left(t\sum_{k\geq 1}\frac{(-1)^{k-1}}{k}x^k\right) \tag{1}$$
hence the LHS is an analytic function in a neighbourhood of $x=0$, and
$$ (1+x)^t = 1+\sum_{m\geq 1}c_m x^m\tag{2} $$
where
$$ c_m = \frac{1}{2\pi}\int_{-\pi}^{\pi}(1+e^{i\theta})^t e^{-mi\theta}\,d\theta \tag{3} $$
by Cauchy's integral formula, but also
$$\begin{eqnarray*} c_m &=& [x^m] \left(e^{tx}\cdot e^{-tx^2/2}\cdot e^{tx^3/3}\cdots e^{(-1)^{m-1}x^m/m}\right)\\&=&(-1)^m [x^m] \left(e^{-tx}\cdot e^{-tx^2/2}\cdot e^{-tx^3/3}\cdots e^{-tx^m/m}\right)\end{eqnarray*}\tag{4} $$
due to $(1)$. It follows that
$$ c_m = \sum_{a_1+2a_2+\ldots+ma_m=m}\frac{(-t)^{a_1+a_2+\ldots+a_m}}{a_1! 2^{a_2}a_2! \cdots m^{a_m}a_m!} \tag{5} $$
and now I leave to you to understand the relation between $\binom{t}{k}$ and the RHS of $(5)$.
It may be useful to recall a few facts about exponential generating functions.

A simpler approach is to notice that both $f(x)=(1+x)^t$ and $g(x)=\sum_{k\geq 0}\binom{t}{k}x^k$ are solutions of the differential equation
$$(1+x)\cdot h'(x) = t\cdot h(x) $$
such that $h(0)=1$. $f\equiv g$ hence follows from the Cauchy-Lipschitz theorem.

A: The  combinatorial  proof  starts  from the  unique  factorization  of
permutations into disjoint cycles which gives the species
$$\mathfrak{P}(\mathcal{U}\mathfrak{C}(\mathcal{Z}))$$
with bivariate EGF $$G(z, u) = \exp\left(u\log\frac{1}{1-z}\right)$$
which yields the Stirling numbers of the first kind
$$\left[n\atop k\right]
= n! [z^n] \frac{1}{k!} \left(\log\frac{1}{1-z}\right)^k.$$
We thus have
$$n! [z^n] G(z, u)
= \sum_{k=1}^n \left[n\atop k\right] u^k.$$
Therefore
$$n! [z^n] G(z, u) = n! (-1)^n [z^n] G(-z, u) =
u(u+1)(u+2)\cdots(u+n-1).$$
Hence
$$n! (-1)^n [z^n] G(-z, -u) = (-1)^n u(u-1)(u-2)\cdots(u-(n-1))$$
and finally
$$n! [z^n] \exp\left(-u\log\frac{1}{1+z}\right)
\\ = n! [z^n] \exp(u\log(1+z)) = u(u-1)(u-2)\cdots(u-(n-1))$$
so that
$$[z^n] \exp(u\log(1+z)) =
\frac{1}{n!} u(u-1)(u-2)\cdots(u-(n-1))
= {u\choose n}.$$


text:
Q: How to re-use the calling result of a java collection's stream, so we don't do same work twice? I know that once a Collection's stream actions of collect/forEach/min/max, the stream is closed and no longer valid for further function call.
My question is, how to avoid "duplicate stream operations" so that we can do different stream actions on same collection without duplicate computation?
E.g.
    public static void main(String[] args) {
        List<Integer> ls = new ArrayList<>(Arrays.asList( 11, 9, 7, 11, 24, 13, 37, 16 ));
        Stream<Integer> s1 = ls.stream().filter(x -> x > 10).sorted().distinct().limit(4).skip(2);
        s1.forEach(System.out::println);

        // java.lang.IllegalStateException: stream has already been operated upon or closed
        System.out.println(s1.max((x, y) -> x < y ? y : x).get()); // s1 is no longer useable.
    }

Well, I know in order to get s1.max I have to construct the Stream again like :
Stream<Integer> sAnother = ls.stream().filter(x -> x > 10).sorted().distinct().limit(4).skip(2);

This works, but seems doing redundant work for the 2nd time. I hope that we can use this calling sequence, and make it executed once and only once:
filter(x -> x > 10).sorted().distinct().limit(4).skip(2)

and then:
(1) Do the forEach to print elements.
(2) Calculate the max element.
Not having to construct and compute the whole stream process twice.
Is there a way to achieve this? Thanks.

A: A Stream can be consumed only once and there is nothing you can do about it.
However, what you can do is collect it i.e. to the List (stream.toList()) and then use that list for further execution - in your case creating two new streams that would do different job.

A: *

*You should distinct() before sorting() to avoid to sort double values which you throw away anyway.

*You could save your processed values in a collecten of your choice. I would recommend you a List (keep in mind that this List is unmodifiable) and if you need to work with streams from there, which i can't see from your code yet, then you could create new streams out of it. But i recommend you to do the following:
public static void main(String[] args) {
    List<Integer> ls = new ArrayList<>(Arrays.asList( 11, 9, 7, 11, 24, 13, 37, 16 ));
    List<Integer> s1 = ls.stream().filter(x -> x > 10).distinct().sorted().limit(4).skip(2).toList();

    Integer max = null;
    for (Integer integer : s1) {
        if (max == null || integer.compareTo(max) > 0) {
            max = integer;
        }
        System.out.println(integer);
    }
    System.out.println(max);
}


text:
Q: Visual Studio Code Does Not Comment-out Empty Lines Visual Studio Code Does Not Comment-out Empty Lines

I've searched everywhere for a solution to this issue but couldn't find anything, and it's been bugging me for months now.
Basically what happens is that VS Code ignores empty lines when you tell it to comment out multiple lines of code.
So for example, let's say I highlighted all the code below and told VS Code to comment it out:
package com.mycompany.app;

public class MyApp {
    public static void main(String[] args) {
        SayHello();
    }

    static void SayHello() {
        System.out.println("Hello!");
    }
}

What I expected to get:
// package com.mycompany.app;
//
// public class MyApp {
//     public static void main(String[] args) {
//         SayHello();
//     }
//
//     static void SayHello() {
//         System.out.println("Hello!");
//     }
// }

What I got instead:
// package com.mycompany.app;

// public class MyApp {
//     public static void main(String[] args) {
//         SayHello();
//     }

//     static void SayHello() {
//         System.out.println("Hello!");
//     }
// }

I've only experienced this with Java and Golang so far, but I assume this happens for all other languages inside VS Code too.
The reason I want my comments to stay connected to each other is so I know which lines I commented out together in case I need to uncomment them back.
I am also aware of the Shift + Alt + A shortcut, but that typically uses Block Comments (which I don't like using), and I only want Line Comments.
Is there a setting I'm missing? Because I tried searching within VS Code and couldn't find anything either.
Any help would be greatly appreciated.

A: A new VS Code setting has been added that resolves this issue:
"editor.comments.ignoreEmptyLines": false

Unfortunately, it is only tagged as "insiders-released" despite being included in Stable versions of VS Code.
Hopefully, this issue gets addressed in future versions.

A: An option to have empty lines commented out is coming to v1.48. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_48.md#thank-you and https://github.com/microsoft/vscode/pull/93160
New setting:
Editor > Comments: Ignore Empty Lines default is true (will ignore)
[editor.comments.includeEmptyLines]
In Insiders' Build already v1.48.

A: Multi-line Editing seems to be the only alternative solution so far.
Press and hold the Alt key and press either Up or Down so your cursor expands to multiple lines. Then just add // manually.
It isn't very intuitive, but it works. Hopefully, the VS Code team will address this issue someday.
UPDATE: This feature has now been added to the VS Code backlog! (https://github.com/microsoft/vscode/issues/88480)


text:
Q: Which action is executing as a strongly typed object I would love to be able to get some strongly typed way of knowing which action is executing.
To clarify im doing AOP where I only allow access to a given action if the user has rights for that action.
The problem with using a string for determining which rule to check for, is that if some developer renames an action, I wont get a compile error telling me that my rule is broken.
Any ideas??

A: Develop an attribute that performs your check.  Apply the attribute, with any necessary options, to the actions that you want to protect.  Write unit tests that check that the actions in question exist and are decorated with your attribute (with the proper options).  In your attribute you needn't know what action is executing, just whether the current user passes the tests as configured by your attribute's options.
I have a couple of different attributes that I've derived from AuthorizeAttribute that do exactly this sort of thing.
 public class RequiresEmailAttribute : AuthorizeAttribute
 {
      ... implements the logic to test whether the current user
      ... has an email address and redirects to error view if no
      ... email address is found
 }

 [RequiresEmail]
 public ActionResult SendEmail( string to )
 {
    ....
 }


text:
Q: Why is a .mp3 passed as an integer? Maybe this is a really dumb question, but I went through a part of the R.java file. There I saw a mp3 file of my raw folder. It was named:
public static final int sound01=0x7f040000;
Why is a sound file passed as an integer? Is that just that they give the file a number, and then Android uses that number as a reference?
Thanks in advance!

A: This is just like any other reference that you access through R (e.g. R.string.x, R.dimen.x). You can access your files in raw through R.raw.x (so in this case, R.raw.sound01). The integer is just a guaranteed unique identifier for that particular resource.


text:
Q: BigQuery Equivalent of "CREATE TABLE my_table (LIKE your_table)" I want to create a table which schema is exactly the same as another table. In other SQL engines, I think I was able to use "CREATE TABLE my_table (LIKE your_table)" or some variations.
I couldn't find the equivalent in BigQuery yet. Is this possible in some fashion?

A: Use this form:
CREATE TABLE dataset.new_table AS
SELECT *
FROM dataset.existing_table
LIMIT 0

This creates a new table with the same schema as the old one, and there is no cost due to the LIMIT 0.
Note that this does not preserve partitioning, table description, etc., however. Another option is to use the CLI (or API), making a copy of the table and then overwriting its contents, e.g.:
$ bq cp dataset.existing_table dataset.new_table
$ bq query --use_legacy_sql --replace --destination_table=dataset.new_table \
    "SELECT * FROM dataset.new_table LIMIT 0;"

Now the new table has the same structure and attributes as the original did.

A: To create a partitioned and/or clustered table the syntax would be:
CREATE TABLE project.dataset.clustered_table
 PARTITION BY DATE(created_time)
 CLUSTER BY
   account_id
 AS SELECT * FROM project.dataset.example_table LIMIT 0


text:
Q: Obtener objeto usando SELECT JSON_EXTRACT de MYSQL tengo el siguiente json guardado en una tabla:

[{"lesson_id": 1, "name": "Lesson 1"}, {"lesson_id": 2, "name": "Lesson 2"}, {"lesson_id": 3, "name": "Lesson 3"}]

Lo que necesito es ver si en este JSON esta un objeto determinado por ejemplo: "lesson_id" : 2,
Si esta en este json que me regrese solo ese objeto

{"lesson_id": 2, "name": "Lesson 2"}

Tengo algo así, pero no logro encontrar la forma de que me regrese solo ese objeto
La consulta que estoy usando esta así.
SELECT JSON_EXTRACT(lessons_viewed, '$[**saber esto mediante el lesson_id**]')
AS object
FROM clients WHERE JSON_EXTRACT(lessons_viewed,
'$[**saber esto mediante el lesson_id**].lesson_id') = 2

Pero necesito ver la forma que me mande el objeto de forma dinámica, haciendo que busque en todos los objetos y me regrese solo ese objeto del JSON
Gracias por su atención

A: Puedes intentar:
SELECT
    test.id,
    JSON_EXTRACT(prueba.json_list, CONCAT('$.list[', ind.ind, ']')),
    ind.ind
FROM
    prueba
CROSS JOIN
    (SELECT 0 AS ind UNION ALL SELECT 1 AS ind UNION ALL SELECT 2 AS ind) ind
WHERE
    JSON_LENGTH(json_list, "$.list") > ind.ind
    AND JSON_EXTRACT(json_list, CONCAT('$.list[', ind.ind, '].type')) = "color";


text:
Q: Select max query returning all the rows in a table in Apache Hive I am querying my data using this query

SELECT date_col,max(rate) FROM crypto group by date_col ;

I am expecting a single row but it is returning all the rows in the table. What is the mistake in this query?

A: You'll get one row per date_col because you're grouping by it. If you just want the maximum rate then just do SELECT max(rate) FROM crypto;.
If you want to get the date_col for that record too then:
SELECT
  date_col,
  rate
FROM crypto
WHERE rate = (SELECT MAX(rate) FROM crypto)


text:
Q: Position: sticky polyfill for angular 2 Are there any polyfill available for angular 2 position:sticky. I have been able to find a few, but most of them are jquery based, there seem to be no implementation available for angular 2:
https://github.com/wilddeer/stickyfill
I need to know the sample usage with angular 2,
for Javascript it is as follows:
var stickyElements = document.getElementsByClassName('sticky');

for (var i = stickyElements.length - 1; i >= 0; i--) {
    Stickyfill.add(stickyElements[i]);
}

A: I added it as a directive on angular 1.4 and npm package "stickyfilljs":"^2.0.3"
import { Directive, ElementRef } from '@angular/core';
import * as Stickyfill from 'stickyfilljs';

@Directive({
  selector: '[StickyPolyfill]'
})
export class StickyPolyfillDirective {

  constructor(private elementRef: ElementRef) { }

  ngAfterViewInit() {
    Stickyfill.addOne(this.elementRef.nativeElement);
  }
}

And in the component I have:
<div class="top-bar-container stickyMenu" StickyPolyfill>

Don't forget to include sticky in CSS:
  .stickyMenu {
    position: -webkit-sticky;
    position: -moz-sticky;
    position: -o-sticky;
    position: -ms-sticky;
    position: sticky;
    top: 0px;
  }

A: It has nothing to do with Angular. What you are looking for is a Polyfill to handle something not implemented in a browser, this is not directly linked with jQuery or Angular, it's only linked to your browser.
The one you linked is good, just add it to your build process or to your assets array if you are using Angular-CLI.
You can use it just by declaring the variable as any element, add this to the start of one of your ts file:
    declare var Stickyfill: any;


text:
Q: Launchd 'Invalid Property List' I was hoping someone could point out where I might be going wrong with a launchctl script I'm trying to write and launch.
The intention is to run a python script I've managed to get working, everyday at 3.15am. (the computer it's going to run on is on 24/7 but if there is a way to incorporate this into it's everyday running that would be great in the event the computer shuts down or needs to be interrupted.)
When I attempt to load the file I get the return message below:
jace@Jaces-Mac-Pro ~ % launchctl load /Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist
/Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist: Invalid property list
jace@Jaces-Mac-Pro ~ %

According to the tutorial I'm following and a few pages online I've reviewed I should have laid everything out correctly but feel I'm missing something.
If someone could point out my mistake and offer a solution I'd really appreciate it!
Am totally new to this file type and the writing of, but feel it'll be what i need to get the job done.
The file I'm trying to run is the below -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.launch.phoneconfig</string>
       <key>ProgramArgument</key>
    <array>
        <string>/usr/local/bin/python3</string>
        <string>/Users/jace/Desktop/Filing_Cabinet/Python_Folder/Selenium_Projects/my_phone_config01.py</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key
        <integer>3</integer>
        <key>Minute</key>
        <integer>15</integer>
    </dict>
</dict>
</plist>1

P.s
I tried putting the file in my mac's launch Daemon folder but can't seem to locate it in the Library, only 'LaunchAgents' folder can be found. Don't know if this effects anything but let me know if there's more information I could provide to get this running.
Thank you for your time.
I was hoping the code to load and run at the designated time and be returned with the other .plist files when I enter 'launchctl list' into terminal.
Update from comment
(Thanks for pointing this out @Chepner)
Running 'putil -lint' allowed me to see an error in script. Example of result.
Before, w/error:
jace@Jaces-Mac-Pro LaunchAgents % plutil /Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist
/Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist: Encountered unexpected character < on line 17 while looking for close tag

After, once fixed:
jace@Jaces-Mac-Pro LaunchAgents % plutil -lint /Users/jace/Desktop/Filing_Cabinet/LaunchD_Folder/launch_phoneconfig/com.launchd.phoneconfig.plist
/Users/jace/Desktop/Filing_Cabinet/LaunchD_Folder/launch_phoneconfig/com.launchd.phoneconfig.plist: OK

Tried running code again but results are as shown -
jace@Jaces-Mac-Pro LaunchAgents % launchctl load /Users/jace/Desktop/Filing_Cabinet/LaunchD_Folder/launch_phoneconfig/com.launchd.phoneconfig.plist
/Users/jace/Desktop/Filing_Cabinet/LaunchD_Folder/launch_phoneconfig/com.launchd.phoneconfig.plist: Invalid or missing Program/ProgramArguments
jace@Jaces-Mac-Pro LaunchAgents %

Update from Answer
Thank you for the suggestion @Chepner.
Adjusting the line to separate the program and program argument seems to have gotten everything to say 'ok'. Technically this answers my question!
Only problem now is that it doesn't actually run, I can run the python script it's meant to run just fine but can't seem to get it to run via this method. Any suggestions or links I can review to help figure this out?
Thank you for your time in helping me! :)
Last login: Wed Nov 30 14:44:29 on console
jace@Jaces-Mac-Pro ~ % plutil /Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist

/Users/jace/Library/LaunchAgents/com.launchd.phoneconfig.plist: OK

jace@Jaces-Mac-Pro ~ % launchctl list
PID Status  Label
-   0   com.launch.phoneconfig (removed the other items that would be returned to show clearly it loaded)
jace@Jaces-Mac-Pro ~ %

A: I think the problem is that you are trying to specify an entire command line as program arguments, rather than specifying the program name separately from its arguments.
<dict>
    <key>Label</key>
      <string>com.launch.phoneconfig</string>
    <key>Program</key>
      <string>/usr/local/bin/python3</string>
    <key>ProgramArgument</key>
      <array>
        <string>/Users/jace/Desktop/Filing_Cabinet/Python_Folder/Selenium_Projects/my_phone_config01.py</string>
      </array>
    <key>RunAtLoad</key>
      <true/>
    <key>StartCalendarInterval</key>
      <dict>
        <key>Hour</key
        <integer>3</integer>
        <key>Minute</key>
        <integer>15</integer>
      </dict>
</dict>

If this is the case, the runtime error could be more specific (Program is missing, so it could just say so instead of implying that there is a problem with ProgramArguments as well).


text:
Q: Get apache.commons.cli.CommandLine as String I get an Object of type apache.commons.cli.CommandLine passed. Somehow there is no toString() method (org.apache.commons.exec.CommandLine does have a toString() method).
Is it possible to get the original command line as a String?

A: No, it's not possible to get the original input arguments back from the CommandLine object. The CommandLine object only stores what the parser parsed from your input argument list.
If you really want the exact argument list you provided the parser save a reference to the String[] you passed in to the Parser.


text:
Q: Nested Form for Devise Account Types I have Devise set up to create Accounts, which are linked to Businesses and Personnel. I'm trying to find a way to include the personnel info and the business info when you sign up for a new account. Is there a way to expand the new registration form? I also want it to change depending on which radio button is active (Personnel by default). I think a nested form is the way to go, but honestly I have no idea how to go about it.
The Business model and the Personnel model both have this line...
app/models/Business.rb & app/models/Personnel.rb
has_one :account, as :accountable

and the Account model looks like this...
app/models/Account.rb
class Account < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :accountable, polymorphic: true

  ACCOUNT_TYPES=["SuperAccount","Chamber","Personnel", "Business"]
  attr_accessor :type
end

Here's how I set up the registrations controller in case it helps.
app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    build_resource(sign_up_params)
    if (resource.type=="Personnel")
      resource.accountable = Personnel.new
      SignupNotifierMailer.personnel(@account).deliver
    elsif(resource.type =="Business")
      resource.accountable = Business.new
      SignupNotifierMailer.business(@account).deliver
    end
    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

  def destroy
    @account.accountable.destroy!
    super
  end

  protected

    def after_sign_up_path_for(resource)
      if (resource.type == 'Personnel')
        edit_personnel_path(current_account.accountable_id)
      elsif (resource.type == 'Business')
        edit_business_path(current_account.accountable_id)
      else
        super
      end
    end
end

And finally, here's the view that I want to change.
app/views/devise/registrations/new.html.erb

Sign Up

<%= simple_nested_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

    <%= f.input :email, required: true, autofocus: true %>
    <%= f.input :password, required: true, hint: ("#{@minimum_password_length}
        characters minimum" if @minimum_password_length) %>
    <%= f.input :password_confirmation, required: true %>
    <%= f.input :type, required: true, as: :radio_buttons, label: "Type of Account",
            collection: Account::ACCOUNT_TYPES.drop(2), checked: 'Personnel' %>

    <%= f.button :submit, "Sign Up" %>

<% end %>

A: You should use accepts_nested_attributes_for :accountable in your Account model, then you should be able to pass those on through to devise in the call to build_resource.
In your HTML form, you should use a nested form, which will generate form field names like account[accountable][name]=Foobar and that will be passed through to your model. You may need to include an accountable_type key and ensure it is within an acceptable range of options in the controller.
There is some information on the Devise readme that describes how to filter these parameters in the controller using strong parameters.
https://github.com/plataformatec/devise#strong-parameters


text:
Q: Convert recursive lists to dynamic data.frame in R I need to build a function that traverses lists and sublists recursively and then convert to data.frame. Let's say I have a list like that
from <- list(id="12345678", name="Gabriele")
message <- "The quick fox"
comments <- list(list(name="Mickey", comment="Hello world!"), list(name="Donald", message="World...hello!"))

big.list <- list(from, message, comments)

I need to convert it in the form of a data.frame with this schema
from_id, from_name, message, comments_name, comments_message

(in other words, flattening the sublists)
The problem is that I don't know in advance which fields I have in the lists and which I've not (for example, some posts may miss the comments section altogether).

A: Below is a quick trial. If big.list has names, they can be taken as column names.
The inner do.call() flattens the sub-list while the outer one converts into a data frame.
lst1 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox",
             comments = list(list(name="Mickey", comment="Hello world!"),
                            list(name="Donald", message="World...hello!")))
lst2 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox",
             comments = list(list(name="Mickey", comment="Hello world!")))
lst3 <- list(from = list(id="12345678", name="Gabriele"),message = "The quick fox")

df1 <- do.call(data.frame, do.call(c, lst1))
df2 <- do.call(data.frame, do.call(c, lst2))
df3 <- do.call(data.frame, do.call(c, lst3))

df1
#from.id from.name       message comments1.name comments1.comment comments2.name comments2.message
#1 12345678  Gabriele The quick fox         Mickey      Hello world!         Donald    World...hello!

df2
#from.id from.name       message comments.name comments.comment
#1 12345678  Gabriele The quick fox        Mickey     Hello world!

df3
#from.id from.name       message
#1 12345678  Gabriele The quick fox

@ Gabriele B
Below is clumsy but working solution. Others may post a better one.
from <- list(id="12345678", name="Gabriele")
message <- "The quick fox"
comments <- list(list(name="Mickey", comment="Hello world!"), list(name="Donald", message="World...hello!"))
big.list <- list(from = from, message = message, comments = comments)
big.list1 <- list(from = from, message = message)

join <- function(lst) {
  if(length(lst$comments) < 1) {
    bnd <- data.frame(id = unlist(lst$from)[1], name = unlist(lst$from)[2], lst$message)
    bnd$cmt.name <- "na"
    bnd$comment <- "na"
    bnd
  } else {
    bnd <- do.call(rbind, lapply(1:length(lst$comments), function(x) {
      id <- unlist(lst$from)[1]
      name <- unlist(lst$from)[2]
      data.frame(id = id, name = name, lst$message)
    }))
    bnd <- cbind(bnd, do.call(rbind, lst$comments))
    names(bnd) <- c("id", "name", "message", "cmt.name", "comment")
    bnd
  }
}

join(big.list)
#id     name       message cmt.name        comment
#id  12345678 Gabriele The quick fox   Mickey   Hello world!
#id1 12345678 Gabriele The quick fox   Donald World...hello!

join(big.list1)
#id     name   lst.message cmt.name comment
#id 12345678 Gabriele The quick fox       na      na


text:
Q: NaNs warning en ZAP model Intentando construir un modelo inflado a ceros R me devuelve el siguiente mensaje:

Warning message: In sqrt(diag(object$vcov)) : NaNs produced

Que básicamente supone que la mayoría de mis estadísticos aparecen como Na. Las recomendaciones que leo en otros foros son re escalar las variables numéricas. Lo he hecho y pese a que mejora, siguen apareciendo Na que me impiden interpretar nada o seguir modelando.
tabla <- read.table("Dataset_pulido-basura.csv", sep=";", dec=".", header=T, na.strings="NA")
f1<- formula(presencias ~ distancia|distancia+habitat+ganado)
Zap1 <- hurdle(f1, dist = "poisson",link = "logit", data = tabla)

A: Sin los datos es difícil hacer un análisis, lo que si puedo decirte es que el problema se produce por algún valor en los regresores que terminan produciendo que la diagonal de la matriz de varianza/covarianza del modelo tenga algún valor en negativo. Esto lo puedes verificar de la siguiente forma:
diag(Zap1$vcov)

si hay algún valor negativo eso confirmaría esta teoría, ya que en definitiva se esta haciendo una raiz cuadrada de un negativo, lo que termina produciendo un NaN.
La solución del problema está en analizar en detalle los datos con los que alimentas el modelo, o como te decía, en definitiva se trata de un Warning, por lo que si el mismo no tiene consecuencias sobre lo esperado, bien podrías ignorarlo mediante:
options(warn=-1)


text:
Q: Having problem to desctructure my data on React The upcomingWork contains my apis data. What I want here is to insert this as an array to display it on my calendar, below are the example of structured data I want.
Actually, the upcomingWork contains a lot of attributes but I just want to get those three attributes to display on my calendar.
const data = upcomingWork.map(u => u.id && u.title && u.created_at);

Example of array that I want to create from data.
  const events = [
    {
      id: 1,
      title: 'My event',
      start: new Date(2020, 4, 8, 10, 0),
      end: new Date(2020, 4, 8, 14, 0),
    },
  ];

A: The map that you have will simply set every value to either true if all values are truey or false if any of them are falsey. if you want to extract those 3 values just change the map to this:
const data = upcomingWork.map(({id, title, created_at}) => ({id, title, created_at}))

A: Whatever you returned is not going to give you any desired data.
I think you misunderstood the map method of Array.
Instead you should use map like:
const data = upcomingWork.map(u => {
             const {id, title, created_at} = u;
                 return {
                   id,
                   title,
                   created_at
                 }
              });

A: const data = upcomingWork.map(u => {
    return { id: u.id, title: u.title };
});

A: Your upcomingWork.map doesn't create an object at all, so it has no chance of creating the expected data. Instead, you can map appropriate properties of the u object to the new keys in a new object you create.
const events = upcomingWork.map(u => ({
    id: u.id,
    title: u.title,
    start: u.created_at,
    end: u.end    //change the u.end to whatever property you have in your data
}));

(the new object has to be wrapped in () to ensure JS interprets it as a value, not a function body)


text:
Q: Wordcount in a field (all and unique) - is there a more elegant/optimal way? Answering this question,
Given this table (constructed from the question):
CREATE TABLE wordcount (id SERIAL NOT NULL PRIMARY KEY, description TEXT NOT NULL);

INSERT INTO wordcount (description) VALUES ('What a great day');
INSERT INTO wordcount (description) VALUES ('This is a product. It is useful');

produce this result:
     id  | word_count | unique_word_count |  Description
---------+------------+-------------------+---------------
     1   |  4         | 4                 | What a great day
     2   |  7         | 6                 | This is a product. It is useful

I gave the (correct) answer, which you can find here.
However in a comment, the OP then asked a further question - what if the string in question was  ['a', ' ', ' ', 'b'] and my solution broke down completely - for starters, the string wouldn't even INSERT into the table.
So, the question now is, how does one deal with strings like this - i.e. with apostrophes, square brackets &c. I'm going to give my own answer and also offer a bonus for a more elegant solution.
Solutions with multiple options will be highly prized as will those which show evidence of "thinking outside the box" (sorry for the cliché - but it fits here! :-) ). I'm also going to give a detailed explanation of my reasoning - that will earn kudos also! Options which mention other servers will also gain merit. Obviously, I can only award the bonus to one person, but I will upvote all decent answers.
I can only offer a bonus in two days - so I'll post my answer and will offer the bonus (+100) when I'm allowed to. Also, any solutions which deal with strings which my own can't deal with - haven't exhaustively tested yet.

A: First step obviously is to create the table and data (as per the question mentioned):
CREATE TABLE wordcount (id SERIAL NOT NULL PRIMARY KEY, description TEXT NOT NULL);

INSERT INTO wordcount (description) VALUES ($$What a great day$$);
INSERT INTO wordcount (description) VALUES ($$This is a product. It is useful$$);
INSERT INTO wordcount (description) VALUES ($$['a', ' ', ' ', 'b']$$);

The first "lifesaver" was the dollar quoting ($$) - a really neat
PostgreSQL feature. I was really floundering before I came across
this - couldn't even get the data into the table (trying
backslashes, double quotes &c.)
My final SQL looks like this (fiddle here):
WITH cte1 AS
(
  SELECT id,
    UNNEST(STRING_TO_ARRAY(REGEXP_REPLACE(
    REGEXP_SPLIT_TO_TABLE(description, ','), '[^\w\s]', '', 'g'), ' ')) as "word",
    description
  FROM wordcount
)
SELECT id,
       COUNT(word),
       COUNT(DISTINCT(word)),
       description
FROM cte1
WHERE LENGTH(word) > 0
GROUP BY id, description
ORDER BY id;

Result:
id  Word_count  Distinct_count  description
 1           4               4    What a great day
 2           7               6    This is a product. It is useful
 3           2               2    ['a', ' ', ' ', 'b']

Logic explained:
I decided not to bother with capitalisation - i.e. "It" and "it" are different words in this case - if this is an issue, the simple addition of an UPPER() function would solve that - it's not core to the question.
Step 1:
SELECT id, REGEXP_SPLIT_TO_TABLE(description, ',') FROM wordcount;
-- Keeping the id field helps clarity, even if superfluous.

Result:
id  regexp_split_to_table
1   What a great day
2   This is a product. It is useful
3   ['a'
3    ' '
3    ' '
3    'b']

Step 2 (remove all non-space, non-alpha)
SELECT id, REGEXP_REPLACE(REGEXP_SPLIT_TO_TABLE(description, ','), '[^a-zA-Z\s]', '', 'g')
FROM wordcount;

-- Remove all non-alpha, non-spaces. Otherwise the words "product" and "product." would
-- be counted as different! Again, keeping the id field makes things clearer,
-- even if not strictly necessary for purists

Result:
id  regexp_replace
1   What a great day
2   This is a product It is useful
3   a
3
3
3    b

Step 3 (put the strings into an array):
SELECT id, STRING_TO_ARRAY(REGEXP_REPLACE(
          REGEXP_SPLIT_TO_TABLE(description, ','), '[^\w\s]', '', 'g'), ' ')
FROM wordcount;
--              id again - not strictly necessary at this step.

Result:
id  string_to_array
1   {What,a,great,day}
2   {This,is,a,product,It,is,useful}
3   {a}
3   {"","",""}
3   {"","",""}
3   {"",b}

Finally, the answer itself - UNNEST and then select those words LENGTH > 0 grouping by id and description.
i.e. SELECT the necessary from the following cte (Common Table Expression) - the cte isn't strictly necessary - I could have used the UNNEST... throughout my final query, but that would have been horrible to read and debug. It's the reason Common Table Expressions were invented!
WITH cte1 AS
(
  SELECT id,
    UNNEST(STRING_TO_ARRAY(REGEXP_REPLACE(
    REGEXP_SPLIT_TO_TABLE(description, ','), '[^\w\s]', '', 'g'), ' ')) as "word",
    description
  FROM wordcount
)
SELECT blah... (see above)

A: As to your solution: smart and with a solid explanation. But what about these cases: '', NULL, '"§$%', '-'? No words. The count should be 0 - but your solution drops these rows altogether.
Also, any solution first and foremost depends on the exact definition of "word", which can vary wildly ...
Regular expression based string processing
Similar to your solution, with some alternative suggestions:
SELECT id
     , COALESCE(cardinality(arr), 0) AS word_count
     , unique_word_count
     , description
FROM  (
   SELECT *
        , string_to_array(trim(regexp_replace(description, '\W+', ' ', 'g')), ' ') AS arr
   FROM   wordcount
   ) a
LEFT   JOIN LATERAL (
   SELECT count(DISTINCT elem) AS unique_word_count
   FROM   unnest(arr) elem
   ) b ON true;

db<>fiddle here (extended test case)
The core is regexp_replace(description, '\W+', ' ', 'g') to replace all substrings of non-word characters with a single space. See Regular Expression Class-shorthand Escapes. This removes all noise early in the game.
Followed up by cheap trim() to remove leading/trailing spaces, and string_to_array() to convert the prepared string to an array.
Get word_count from the array directly. Again: cheap.
The unique_word_count from a LATERAL subquery with count(DISTINCT ...). That part may or may not be slower than a total unnest / aggregate. It's a bit simpler.
The COALESCE in the outer SELECT takes care of NULL input (the original question did not mention a NOT NULL constraint). Optional, in case you need 0 instead of NULL.
Or (faster in a quick test with short strings):
SELECT id
     , count(*) AS word_count
     , count(DISTINCT elem) AS unique_word_count
     , description
FROM  (
   SELECT id, description
        , unnest(string_to_array(trim(regexp_replace(description, '\W+', ' ', 'g')), ' ')) AS elem
   FROM   wordcount
   ) sub
GROUP  BY id, description;

This drops rows with 0 words like your answer does.
(Ab-)using text search parser
Using the text search function ts_parse() is simpler. May or may not be faster. But first study the various tokens identified by the the text search parser and see what matches your definition of "word":
SELECT * FROM ts_token_type('default')

For only "ASCII Words":
(Unlike above, the underscore (_) is not treated as word character here):
SELECT w.id
     , count(*) AS word_count
     , count(DISTINCT token) AS unique_word_count
     , w.description
FROM   wordcount w, ts_parse('default', w.description) t
WHERE  t.tokid = 1 -- 'asciiword'
GROUP  BY w.id;

To keep _ from separating  words, use simple replace() first:
SELECT w.id
     , count(*) AS word_count
     , count(DISTINCT token) AS unique_word_count
     , w.description
FROM   wordcount w, ts_parse('default', replace(w.description, '_', 'x')) t
WHERE  t.tokid = 1 -- 'asciiword'
GROUP  BY w.id;

Again, to keep all rows:
SELECT w.id
     , count(token) AS word_count
     , count(DISTINCT token) AS unique_word_count
     , w.description
FROM   wordcount w
LEFT   JOIN LATERAL (
   SELECT t.token
   FROM   ts_parse('default', w.description) t
   WHERE  t.tokid = 1 -- 'asciiword'
   ) t ON true
GROUP  BY w.id;

db<>fiddle here
Related:

*

*Efficient merging (removing duplicates) of arrays

*How do I select arrays that are not empty?

*What is the difference between LATERAL and a subquery in PostgreSQL?


text:
Q: JScrollPane acts funny inside of a JOptionsPane I have tried to add a scroll view to a JOptionsPane, so that the information window can handle more text. It does add a scroll pane to the window. However, it acts funny on scrolling. The first visible text is shown clearly, but when you start scrolling, the text parts will overlap each other, until the text area is all black.
Do you have an explanation of how this can be and maybe a solution to the problem?
My code looks like this:
public void showInfoNoTranslation(String info) {
    frame.requestFocusInWindow();

    // create a JTextArea
    JTextArea textArea = new JTextArea(info, 6, 25);
    textArea.setEditable(false);
    textArea.setBackground(new Color(255, 255, 255, 0));
    textArea.setBorder(BorderFactory.createEmptyBorder());
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    // if (textArea.getLineCount() > 5) {
    JScrollPane scrollPane = new JScrollPane(textArea);
    JOptionPane.showMessageDialog(_frame, scrollPane, "title", JOptionPane.INFORMATION_MESSAGE);
}

A: Call textArea.setOpaque(false); instead of setting it's background-color to fully transparent and it will work.

From the docs:
public void setOpaque(boolean isOpaque)

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

The default value of this property is false for JComponent. However, the default value for this property on most standard JComponent subclasses (such as JButton and JTree) is look-and-feel dependent.


text:
Q: Include pdf file with existing bookmarks I need to include several papers (PDF files) in the end of my thesis.
The PDF files already have bookmarks, and my thesis has bookmarks as well.
Is there some way to include the bookmarks of the included PDF files in the thesis, or are the PDF files only inserted as pictures?
Many thanks in advance!


text:
Q: Possible bug with Z3: Z3 is not able to prove a theorem in Topology I am trying to prove with Z3 the theorem in general topology given at
TPTP-Topology
I am translating the code given there using the following Z3-SMT-LIB code
;; File     : TOP001-2 : TPTP v6.0.0. Released v1.0.0.
;; Domain   : Topology
;; Problem  : Topology generated by a basis forms a topological space, part 1

(declare-sort S)
(declare-sort Q)
(declare-sort P)

(declare-fun elemcoll (S Q) Bool)
(declare-fun elemset (P S) Bool)
(declare-fun unionmemb (Q) S)

(declare-fun f1 (Q P) S)

(declare-fun f11 (Q S) P)
(declare-fun basis (S Q) Bool)
(declare-fun Subset (S S) Bool)
(declare-fun topbasis (Q) Q)

;; union of members axiom 1.
(assert (forall ((U P) (Vf Q)) (or (not (elemset U (unionmemb Vf)))
                                    (elemset U (f1 Vf U) ) )   ))
;; union of members axiom 2.

(assert (forall ((U P) (Vf Q)) (or (not (elemset U (unionmemb Vf)))
                                   (elemcoll (f1 Vf U) Vf ) )   ))

;; basis for topology, axiom 28

(assert (forall ((X S) (Vf Q)) (or (not (basis X Vf)) (= (unionmemb Vf) X )  )   ))

;; Topology generated by a basis, axiom 40.

(assert (forall ((Vf Q) (U S)) (or (elemcoll U (topbasis Vf))
                               (elemset (f11 Vf U) U))   ))

;; Set theory, axiom 7.

(assert (forall ((X S) (Y Q)) (or (not (elemcoll X Y)) (Subset X (unionmemb Y) ) )  ))

;; Set theory, axiom 8.
(assert (forall ((X S) (Y S) (U P)) (or (not (Subset X Y)) (not (elemset U X))
                                                                (elemset U Y)     )))

;; Set theory, axiom 9.
(assert (forall ((X S)) (Subset X X )  ))

;; Set theory, axiom 10.
(assert (forall ((X S) (Y S) (Z S)) (or (not (= X Y)) (not (Subset Z X)) (Subset Z Y) )  ))

;; Set theory, axiom 11.
(assert (forall ((X S) (Y S) (Z S)) (or (not (= X Y)) (not (Subset X Z)) (Subset Y Z) )  ))

(check-sat)

(push)
(declare-fun cx () S)
(declare-fun f () Q)
(assert (basis cx f))
(assert (not (elemcoll cx (topbasis f))))
(check-sat)
(pop)

(push)
(assert (basis cx f))
(assert (elemcoll cx (topbasis f)))
(check-sat)
(pop)

The corresponding output is
sat
sat
sat

Please run this example online here
The first sat is correct; but the second sat is wrong, it must be unsat. In other words, Z3 is saying that the theorem and its negation are true simultaneously.
Please let me know what happens in this case.  Many thanks.  All the best.

A: It is possible that both a formula and the negation of the formula is consistent with respect to a background theory T. In particular, when T is not complete, then there are sentences that are neither consequences of T nor inconsistent with T. In your case the theory T is the set of topology axioms.
You can use the command (get-model) to obtain a model that satisfies the axioms and the sentence.


text:
Q: Tablesorter - Sorting pair of tables with same order? I'm using Tablesorter and ZURB Responsive Table. The responsive table will break the tables into two: One to store sticky column (won't move) and the second one will be horizontally scrollable.
The problem is: since it is separate table, sorting one of them won't sort the other.
Here's the JSFiddle. If you click the <th> on the right-side, it will only short the right-table and vice versa.
Any easy solution for this? Or must I write custom-made tablesorter?
Notes: Try minimizing the JSFiddle Result window to see the responsive table


text:
Q: How to create a k sorted array using algorithm based on quicksort The question is, how to "tweak" the simple and basic version of the QuickSort algorithm, to have it produce a nearly-sorted array instead of a fully-sorted array, given a certain k?
Any help or direction will be appreciated!

A: The simplest way - don't make recursive calls for slices with right-left<k (in case of recursive implementation) and don't put similar pieces onto stack in case of iterative implementation.


text:
Q: affine sets in $\mathbb{R}^2$ I was trying to visualize all affine sets in $\mathbb{R}^2$.
I started with single points. All points are affine sets of cardinality one.
Now I thought of adding another point to the context. The set of two points is not affine. But the affine hull is a line through these points which is an affine set.
Now, I thought of adding a point which is not in the line . The union of line and the new point is not affine. The affine hull cor this union set is $\mathbb{R}^2$.

So the affine sets are {singleton points ,lines, $\mathbb{R}^2$}

Is this right?


text:
Q: Agregar EntityFramework a Proyecto C# con BD Firebird en VisualStudio 2019 Quisiera de su ayuda para saber si alguno de ustedes, ha tenido detalle o le ha pasado que no puede crear el entorno de EntityFramework en el proyecto ya que no encuentra otro Proveedor de datos .NET Framework, no se como se podría agregar el proveedor de Firebird ya que la información que encuentro no es tan correcta o precisa. cabe mencionar que lo intente por medio del asistente y también por medio del Administrador de paquete.(adjunto Capturas)
Espero y puedan orientarme, saludos.


text:
Q: Summing nested arrays of different length in python I have the arrays p1 and p2 where they each look like
array([  1.00000000e+00,   4.00000000e+00,   8.90000000e+01,
         1.00000000e+00,   3.94090600e-06,   2.22958010e-02,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00])

and
array([  1.00000000e+00,   4.00000000e+00,   8.90000000e+01,
         1.00000000e+00,   3.94090600e-06,   2.87729900e-03,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00])

So p2 is longer than p1. Note the numbers themselves are unimportant.
They are in the list
p = [p1,p2]

I would like to sum them such that the extra values in p2 are truncated. I thought I could do
sum(p[:][0:10])

But this produces an operand error. Actually I'm really unsure if I even understand what the sum function is trying to do in this instance. I know it works in the instance that p1 and p2 are the same length though.
Basically I want the result that
p[0][0:10]+p[1][0:10]

gives, which is
array([  2.00000000e+00,   8.00000000e+00,   1.78000000e+02,
         2.00000000e+00,   7.88181200e-06,   2.51731000e-02,
         0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00])

I had come up with a workaround but it's disgusting and I feel like there is probably a way to get the sum function to do this.

A: You can't use sum to do that directly. sum basically just iterate over a list and total up the elements like
def sum(iterables):
  total = 0
  for elem in iterables: total += elem
  return total

You can use list comprehension to achieve your goal as below
# Find out the minimum length of list inside p to truncate excess elements
truncated_len = min([len(list) for list in p])
# Sum up each elements
result = [sum([p[j][i] for j in range(len(p))]) for i in range(truncated_len)]
print(result)


text:
Q: How to show toast in second java file? I have been reading this forum for days and I have found no answer to my problem.
I'm having problem with getting java.lang.NullPointerException when I try to show Toast.
In my android application I have MyWorkActivity.java which is main activity and Statistika.java intended to calculate some statistics based on data from my database.
Inside class MyWorkActivity (public class MyWorkActivity extends Activity implements OnClickListener) i have menu item statistika.
When I press on that item I want to show layout Statistika.xml with data from statistika.java like this:
public class MyWorkActivity extends Activity implements OnClickListener
{
    //Menu item statistika
    else if(item.getItemId()==R.id.statistika)
    {
        //Layout statistika.xml
         setContentView(R.layout.statistika);

         Statistika nova_statistika = new Statistika();
         nova_statistika.rsatiDanasJuceMjesec(sDatumZaPrikaz);
    }
}

But I have been receiving java.lang.NullPointerException on dbJuceDanas = this.openOrCreateDatabase(DatabaseInfo.IME_BAZE, MODE_PRIVATE,null); so I have commented database part and tried only Toast but I still get java.lang.NullPointerException.
This is my Statistika.java:
public class Statistika extends Activity
{
 public void rsatiDanasJuceMjesec (String sDatumZaRacunanje)
   {
      Toast.makeText(getBaseContext(), "Toast is working! ", Toast.LENGTH_LONG).show();

    //Računanje radnih sati za prikazani dan
//      SQLiteDatabase dbJuceDanas = null;
//      dbJuceDanas = this.openOrCreateDatabase(DatabaseInfo.IME_BAZE, MODE_PRIVATE,null);
//
//      //Filtriranje rekordseta po datumu
//      Cursor cJuceDanas = dbJuceDanas.rawQuery("SELECT * FROM " + DatabaseInfo.IME_TABELE + " WHERE " + DatabaseInfo.DATUM + " LIKE '%" + MyWorkActivity.sDatumZaPrikaz + "'", null);
//
//      if (cJuceDanas !=null && cJuceDanas.getCount() > 0)
//      {
//          //Ako postoje upisi za datum trenutnog upisa
//          int Column4 = cJuceDanas.getColumnIndex("r_vrijeme");
//
//          //Sumiranje svih radnih vremena od danas
//          fRVDanas=Float.valueOf(0);
//          do
//          {
//              cJuceDanas.moveToFirst();
//              fRVDanas=fRVDanas+cJuceDanas.getFloat(Column4);
//
//          }while (cJuceDanas.moveToNext());
//      }
    }
}

This is LogCat:
04-25 12:33:15.020: E/AndroidRuntime(927): FATAL EXCEPTION: main
04-25 12:33:15.020: E/AndroidRuntime(927): java.lang.NullPointerException
04-25 12:33:15.020: E/AndroidRuntime(927):  at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
04-25 12:33:15.020: E/AndroidRuntime(927):  at android.widget.Toast.<init>(Toast.java:89)
04-25 12:33:15.020: E/AndroidRuntime(927):  at android.widget.Toast.makeText(Toast.java:231)
04-25 12:33:15.020: E/AndroidRuntime(927):  at myWork.amicus.ba.Statistika.rsatiDanasJuceMjesec(Statistika.java:69)
04-25 12:33:15.020: E/AndroidRuntime(927):  at myWork.amicus.ba.MyWorkActivity.onOptionsItemSelected(MyWorkActivity.java:3028)
04-25 12:33:15.020: E/AndroidRuntime(927):  at android.app.Activity.onMenuItemSelected(Activity.java:2205)
04-25 12:33:15.020: E/AndroidRuntime(927):  at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:748)

I have tried following:
Toast.makeText(this, "Toast is working! ", Toast.LENGTH_LONG).show();

Toast.makeText(Statistika.this, "Toast is working! ", Toast.LENGTH_LONG).show();

and many other combinations but it doesn't work.
As I can understand, problem is with context.
What do I need to do to be able to show Toast message and access database from Statistika.java?

A: Try this code

public class MyWorkActivity extends Activity implements OnClickListener
{
    //Menu item statistika
    else if(item.getItemId()==R.id.statistika)
    {
        //Layout statistika.xml
         setContentView(R.layout.statistika);

         Statistika nova_statistika = new Statistika(MyWorkActivity.this);
         nova_statistika.rsatiDanasJuceMjesec(sDatumZaPrikaz);
    }
}

public class Statistika extends Activity
{

Context context;

    public Statistika(MyWorkActivity mainActivity) {
        // TODO Auto-generated constructor stub

        context = mainActivity;
    }

 public void rsatiDanasJuceMjesec (String sDatumZaRacunanje)
   {
      Toast.makeText(context, "Toast is working! ", Toast.LENGTH_LONG).show();
}

}


text:
Q: Select Master Data From Table Based on Categories From Multiple Tables I have Tables Like
1) User Which Holds The Master Data Like

User ID   Name    OtherColumns
1         Banshi   Nothing
2         Banshi2  Nothing
3         Banshi3  Nothing

2)Second Table "Friends" Holds Data Like

ID    UserID     FriendID    FriendCategory
1       1          2             2
2       2          1             2
3       4          1             2
4       1          4             2

3)Third Table "Subscribers" Holds Data Like

ID    SubscribersID  SubscribToID    FriendCategory
1       1              3                  3
2       1              4                  3

4)Fourth Table "FriendCategory" Like

ID      Name
2       Friends
3       Subscribers

5)Fifth Table "Posts" Contains Data Like

PostID   UserID  Post
1         2      Hello Dear Post By Banshi2
2         3      Hello Dear  Post By Banshi3
3         4     Hello Dear  Post By Banshi4

Now Being User 1 i Need Data Like
A) I need Data if Posted By My Friends
B) I need Data if Posted By i am Subscribed to
c) If User is My Friend Subscribed as Well Then it Must Show Friend not i am Subscribed
My Data Something Like

UserID      Name        Post                          Category
2          Banshi2    Hello Dear Post By Banshi2     Friends
3          Banshi3    Hello Dear Post By Banshi3     I Am Subcriber
4          Banshi4    Hello Dear Post By Banshi4     Friends

Please Suugest Me How to Get Such a Out put in Sql Server 2008
Thanks in Advance
Banshi

A: Am not sure can you try this and let me know,
select u.userid,u.name,p.post,f.name from
User u join Friends fr on u.userid=fr.userid
join FriendCategory f on fr.FriendID=f.id
join Posts p on u.userid=p.userid
order by u.userid;

A: For getting data if posted by friends
SELECT
  u.UserID, u.Name , p.Post , fc.Name
FROM
  users as u,
  FriendCategory as fc,
  Subscribers as s,
  Friends as f,
  Posts as p
WHERE
  f.UserID=1
  and fc.id=f.FriendCategory
  and p.UserID = f.FriendID
group by fc.Name

You can do it similarly for getting data to i am subscribedto .

c) If User is My Friend Subscribed as Well Then it Must Show Friend
  not i am Subscribed

Well, i didn't get what you were trying to say here .


text:
Q: How can I fix JSON Duplicate Key? I've never programed anything before and have no experience :) I'm using a program which I get from github and now I have to make a json settings file for it.
basicly, I'll pick fix(ASMAP or BARPE) and runway(35L or 36) and the program should give me the right "dep"/"nap" and "cfl" for these settings. But there are more than one possible cfl and runway for a fix which is causing me duplicate key warning. can anybody help me about how to overcome this problem? I'll share just a little part of the code for you to see the structure:
"ASMAP": {"cfl": 5000, "rwys": {"35L": {"dep": "ASMAP3D", "nap": "ASMAP3R"},"35R":{"dep":"ASMAP3D", "nap": "ASMAP3R"}}},
"ASMAP": {"cfl": 8000, "rwys": {"36": {"dep": "ASMAP3E", "nap": "ASMAP3S"}}},
"BARPE": {"cfl": 5000, "rwys": {"35L": {"dep": "BARPE3D"}, "35R": {"dep": "BARPE3D"}}},
"BARPE": {"cfl": 8000, "rwys": {"36": {"dep": "BARPE3E"}}},

A: It looks like you are using the wrong data structure.
A hashmap's (what you are using) keys must be unique. You have multiple keys that are not unique:
{
 "ASMAP": { ... }
 "ASMAP": { ... } <- this is the same key as above
}

To help you thinking about it, the reason why they must be unique is because when you attempt to access a value by key, if the keys are not unique, then the hashmap doesn't know which value you are trying to access.
So, you could use a different data structure like this:
{
 "ASMAP": [
   {"cfl": 5000, "rwys": {"35L": {"dep": "ASMAP3D", "nap": "ASMAP3R"},"35R":{"dep":"ASMAP3D", "nap": "ASMAP3R"}}},
   {"cfl": 8000, "rwys": {"36": {"dep": "ASMAP3E", "nap": "ASMAP3S"}}}
 ],
 "BARPE": [ ... ]
}

Now, ASMAP and BARPE are unique keys, and their values contain a list.


text:
Q: In iOS apps, is Bundle Id or SKU visible to customers When creating a new app, I had to choose a Bundle Id and SKU in iTunes Connect.
Are those in any way visible to the end user?
I am pretty sure that they are not visible in the "normal" scenarios (e.g. AppStore, installed apps, etc.), but what about when you make a backup of the apps on your computer or some other advanced scenario?

A: Bundle ID can be found with dev tools or something like iExplorer. SKU is not visible anywhere.