text:
Q: ERROR s4s-att-not-allowed: Attribute 'type' cannot appear in element 'element' I have an XML file that I need to read and it looks similar to this:
<container time="">
<level1 id="1:0:0" name="Some Name">level1 Description
    <level2 id="1:1:0" name="Some Name">level2 Description
        <level3 id="1:1:1" name="Some Name">level3 Description</level3>
        <level3 id="1:1:2" name="Some Name">level3 Description</level3>
    </level2>
</level1>

At build time I am using xjc to generate my classes for me.
<javac includeantruntime="false" srcdir="${build.dir}/configuration_src"
  destdir="${build.dir}/generated_jars"
  classpathref="example.jars"
  debug="on">
  <include name="**"/>
</javac>

The problem I am running into is the fact that <level1> has a description but it also has 0 to many <level2>.  How do I setup my schema so that the description gets taken care of?
<xs:schema targetNamespace="http://example.com/container" xmlns="http://example.com/container" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="container">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="level1" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
</xs:element>
<xs:element name="level1">
    <xs:complexType>
        <xs:sequence>
          <xs:element ref="level2" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:attribute name="id" type="xs:string"></xs:attribute>
        <xs:attribute name="name" type="xs:string"></xs:attribute>
    </xs:complexType>
</xs:element>
<xs:element name="level2">
    <xs:complexType>
        <xs:sequence>
          <xs:element ref="level3" minOccurs="0" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:attribute name="id" type="xs:string"></xs:attribute>
        <xs:attribute name="name" type="xs:string"></xs:attribute>
    </xs:complexType>
</xs:element>
<xs:element name="level3">
    <xs:complexType>
        <xs:attribute name="id" type="xs:string"></xs:attribute>
        <xs:attribute name="name" type="xs:string"></xs:attribute>
    </xs:complexType>
</xs:element>

When I try to add a type="xs:string" to any of my <xs:element> for example
<xs:element ref="level1" minOccurs="0" maxOccurs="unbounded" type="xs:string"/>
It complains [ERROR] s4s-att-not-allowed: Attribute 'type' cannot appear in element 'element'.

A: The error is that you can't have @ref and @type on the same <xs:element> element.
An <xs:element> can either be an element declaration, in which case it has an @name attribute and can also have an @type attribute; or it's a reference to an element declaration, in which case it has an @ref attribute and no @type. The type belongs on the element declaration; if you're referring to an element declared elsewhere, then the type goes with that element declaration, not with the reference.
The level3 element is a complex type with simple content. The way you declare it is typically
<xs:element name="level3">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="id" type="xs:string"></xs:attribute>
        <xs:attribute name="name" type="xs:string"></xs:attribute>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

The level1 and level2 elements are more difficult. They have both text node and element node children. The only way you can describe this in XSD is with "mixed content" types, but mixed content types are designed primarily for narrative text documents, and they can't constrain where the text goes or what form it takes. It might look like this:
<xs:element name="level2">
  <xs:complexType mixed="true">
    <xs:sequence>
      <xs:element ref="level3" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:string"></xs:attribute>
    <xs:attribute name="name" type="xs:string"></xs:attribute>
  </xs:complexType>
</xs:element>


text:
Q: Matlab: Creating duplicate edges in graph I want to have duplicate edges or even more edges if required, between to vertices.
The normal graph command does not allow and gives error that duplicate edges are not allowed, same thing happens for digraph as well.
Does anyone know of any way or trick to do this?
Let's say as an example I want matlab to draw below graph:
G = graph([1 1 3],[2 2 5])
plot(G)

A: This is not possible with the MATLAB class graph. Graphs that allow multiple edges between two nodes are typically called multi-graphs or similar, and are less commonly used.
You could work around this by adding a Weight variable that is larger if it represents several edges:
G = graph([1 3], [2 5], [2 1]);

This could then be used to plot the edge with a thicker line:
plot(G, 'LineWidth', G.Edges.Weight);

Other workarounds may be possible, depending on what you want to do with this graph.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No image is displaying In the below code i have placed a ascx file and javascript .It will display a textbox with image but it is not showing image for clicking the image for date picker pls help me to solve the issue.
js:
<script type="text/javascript">
    $(function () {
        $("#txtDate").datepicker({
            showOn: "button",
            buttonImage: "calendar.png",
            buttonImageOnly: true
        });
    });
</script>

asp.net:

A: You need a path to your image or include the image in the directory where your page is here is a jsfiddle sample
$(function () {
    $("#txtDate").datepicker({
        showOn: "button",
        buttonImage: "http://png.findicons.com/files/icons/2166/oxygen/48/kontact_date.png",
        buttonImageOnly: true
    });
});

Edit :
First of all see the source code if your textbox id changes, if so you got two option to either set it to ClientIDMode="static" or change the script to get the ClientID of textbox control:
$(function () {
        $("#<%=txtDate.ClientID%>").datepicker({
            showOn: "button",
            buttonImage: "http://png.findicons.com/files/icons/2166/oxygen/48/kontact_date.png",
            buttonImageOnly: true
        });
    });

A: The problem could be the path of the buttonImage.
Make sure the path is correct means it should be in the same directory where the your .aspx page is.
Other wise change the path of the image.
Suppose that you page is in the root directory and images in the image directory the the path should be
buttonImage:"/image/to/calendar.png"

Also it could be the problem with the ID of you text box you can use ClientId as follows
 $("#<%=txtDate.ClientID%>").datepicker({
 ...

A: JQuery for datePicker
 $(document).ready(function() {
        $("#datefield").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            showOn: 'button',
                buttonImage: "http://www.cphlibrary.org/images/events/calendar.jpg",
            buttonImageOnly: true
        });
    });

HTML
<input type="text" id="datefield" />

Working fiddle
To make this Work you have to include Jquery 1.8.3 and jqueryui/1.10.3/jquery-ui.min.js


text:
Q: Loading SSIS Package Programmatically in C# I'm loading a ssis package from my application which works fine.  However, what I'm trying to work out and failing miserably is that the package executes in 1 second (which is great) but the loading of the package takes 9 seconds.
Working locally in visual studio 2015 connecting remotely to a SQL Server 2014 instance.
The package is being loaded in a business object behind an async web api call from a console application.
Heres the code (standard stuff)...
Application application = new Application();
DTSExecResult result;
DTSPackageEventListener eventListener = new DTSPackageEventListener();

packageLocation = request.packageLocation;

//using (Package package = application.LoadPackage(packageLocation, eventListener)) // 9 seconds to load
using (Package package = application.LoadFromDtsServer(@"File System\<PACKAGENAME>", @"<SERVERNAME>", eventListener)) // 9 seconds to load
{
.
.
.

Does anyone have any tips? Any help/guidance would be much appreciated.
Simon.

A: This is normal, dtsx file is an xml file and the DtsRuntime library need to deserialize the file to load it as dot net class. Also there are some validation that are done on package loading.


text:
Q: Adding url parameters to UI component mass action I have a ui component with a listing of products in magento 2.2, with a mass action function implemented.  however when it submits, i need it to also pass over a parameters from the query string.
example listing url: https://mymagentostore.com/admin/wishlist/projects/additem/wishlist_id/1234/
here is my mass action:
<massaction name="listing_massaction" >
        <action name="additem">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="type" xsi:type="string">additem</item>
                    <item name="label" xsi:type="string" translate="true">Add Selected Items to Project</item>
                    <item name="url" xsi:type="url" path="wishlist/project/saveitems"/>
                    <item name="confirm" xsi:type="array">
                        <item name="title" xsi:type="string" translate="true">Add Item</item>
                        <item name="message" xsi:type="string" translate="true">Are you sure you want to add selected item(s) to this projects?</item>
                    </item>
                </item>
            </argument>
        </action>
    </massaction>

I need to find a way to pass wishlist_id=1234 also when the mass action is submitted.

A: 1) Add class to attribute to action, and replace url item with urlPath:
<massaction name="listing_massaction" >
    <action name="additem" class="Vendor\Module\Ui\Component\Action\AddItem">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">additem</item>
                <item name="label" xsi:type="string" translate="true">Add Selected Items to Project</item>
                <item name="urlPath" xsi:type="string">wishlist/project/saveitems</item>
                <item name="confirm" xsi:type="array">
                    <item name="title" xsi:type="string" translate="true">Add Item</item>
                    <item name="message" xsi:type="string" translate="true">Are you sure you want to add selected item(s) to this projects?</item>
                </item>
            </item>
        </argument>
    </action>
</massaction>

2) Create class extending the action component and implement the prepare method. There you can set the URL basing on the param from request (or from anywhere else).
namespace Vendor\Module\Ui\Component\Action;

class AddItem extends \Magento\Ui\Component\Action
{

    protected $urlBuilder;
    protected $request;

    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\UrlInterface $urlBuilder,
        array $components = array(),
        array $data = array(),
        $actions = null
    ) {
        parent::__construct($context, $components, $data, $actions);

        $this->urlBuilder = $urlBuilder;
        $this->request = $request;
    }

    public function prepare()
    {
        parent::prepare();

        $config = $this->getConfiguration();

        $params = array('wishlist_id' => $this->request->getParam('wishlist_id');

        $config['url'] = $this->urlBuilder->getUrl($config['urlPath'], $params);

        $this->setData('config', $config);
    }
}


text:
Q: Regex matching comma-separated list of values, trailing comma not allowed I want to match:

*

*aaa

*aaa,bbb

*aaa,bbb,ccc

But not a list with a trailing comma. My current regex:
(\w{3},?)+

also matches lists with trailing commas (aaa,bbb,). I was thinking I could also do:
(\w{3})(,\w{3})*

but that is rather ugly. My real regex is not matching 3-letter-words, but something bigger, and repeating the regex is ugly. How can this be fixed?

A: You can give a name to your big regex in PCRE like:
(?<big>[a-zA-Z0-9]+)

Everything after the ?<name> will be recorded with the name given.
Called Regular Expression Subroutines
So, repeats (?&name) become easy:
^(?<big>[a-zA-Z0-9]+)(,(?&big))*$

Test it Online
So, matching an IP, for example, becomes simpler:
^(?<ip>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.(?&ip)){3}$

Test it OnLine.
Use it with grep as:
grep -P '^(?<ip>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.(?&ip)){3}$'

A: If using perl or PCRE regexps, you can avoid repetition by using things like (?1) to refer to the regexp in the first capture group:
grep -Px '(?:(\w{3}),)*(?1)'

Which would match on any non-empty comma separated list of 3 character words. Change to:
grep -Px '(?:(?:(\w{3}),)*(?1))?'

To allow an empty list.

A: Please use - ^((([a-zA-Z0-9]){1,45},){2}([a-zA-Z0-9]){1,45})$
Here, I have set max word size to 45, as longest word in English is 45 characters, can be changed as per requirement

A: The regex as simple as: [^,]$ answers the question.
Thanks to @Hkoof for their comment!


text:
Q: JavaScript Onkeyup expiry date How can i set onkeyup to output this format  00/00 instead 00/00/0000
<input type="text" onkeyup="
    var v = this.value;
    if (v.match(/^\d{2}$/) !== null) {
        this.value = v + '/';
    } else if (v.match(/^\d{2}\/\d{2}$/) !== null) {
        this.value = v + '/';
   }">

A: You could add maxlength="5"
<input type="text" maxlength="5" onkeyup="
    var v = this.value;
    this.value = v
      .replace(/^(\d{2})(?:\/?)(\d{1,2})$/, `$1/$2`)
      .replace(/^(\d{2})\/$/, '$1');
   ">

I also improved your regex to use replace and remove the / automatically


text:
Q: Evaluating the derivative of a polynomial Let $f(x) = x^{2n} - x^{2n-1} + \cdots + x^4 - x^3 + x^2 - ax + b$
We wish to compute $f'(1)$. The way I did this was to differentiate term by term, and then pair the terms of the form $-(2m + 1)x^{2m} + (2m) x^{2m-1}$ to get $-1$ summed $n-1$ times to get a $1-n$ term. Considering the first and last terms, we see that $2n$ and $-a$ contribute a term. So we get $f'(1) = n+1-a$
My book just states that $f'(1) = n-1+2-a$. They might have a quicker way than my reasoning, and I am not sure where the $+2$ comes from. Does anyone see how the book did it?

A: They are just pairing neighboring terms the opposite way from you, namely $$(2k)1^{2k-1}-(2k-1)1^{2k-2}=2k-(2k-1)=1$$ There are $n-1$ full pairs, and $2-a$ is the derivative of $x^2-ax$.

A: If $f(x) = x^{2n} - x^{2n-1} + \cdots + x^4 - x^3 + x^2 - ax + b$,
$f(x) = x^{2n} - x^{2n-1} + \cdots + x^4 - x^3 + x^2 - x + 1 + x - 1 - ax + b$,
so $f(x) = \frac{x^{2n+1}+1}{x+1} + x - 1 - ax + b
= \frac{x^{2n+1}+1}{x+1} + x(1-a) - 1 + b$.
Differentiating,
$f'(x) = \frac{(2n+1)x^{2n}(x+1)-(x^{2n+1}+1)}{(x+1)^2} + 1-a
= \frac{2nx^{2n+1}+(2n+1)x^{2n}-1}{(x+1)^2} + 1-a$.
Setting $x=1$,
$f'(1) = \frac{2n+(2n+1)-1}{4}+1-a
=n+1-a$.
At no extra charge,
$f(1) = \frac{1+1}{1+1} + (1-a) - 1 + b
= 1 - a + b$
(which you can see from cancellation,
but it's nice to have a check).


text:
Q: Median of Medians using blocks of 3 - why is it not linearic? I understand why, in worst case, where T is the running time of the algorithm, that using the median of medians algorithm with blocks of size three gives a recurrence relation of

T(n) = T(2n / 3) + T(n / 3) + O(n)

The Wikipedia article for the median-of-medians algorithm says that with blocks of size three the runtime is not O(n) because it still needs to check all n elements. I don't quite understand this explanation, and in my homework it says I need to show it by induction.
How would I show that median-of-medians takes time Ω(n log n) in this case?

A: Since this is a homework problem I'm going to let you figure out a rigorous proof of this result on your own, but it might be helpful to think about this one by looking at the shape of the recursion tree, which will be something like this:
                      n                         Total work: n
      2n/3                        n/3           Total work: n
4n/9        2n/9             2n/9      n/9      Total work: n

Essentially, each node's children collectively will do the exact same amount of work as the node itself, so if you sum up the work done across the layers, you should see roughly linear work done per level. It won't be exactly linear work per level because eventually the smaller call starts to bottom out, but for the top layers you'll see this pattern hold.
You can formalize this by induction by guessing that the runtime is something of the form cn log n, possibly with some lower-order terms added in, but (IMHO) it's more important and instructive to see where the runtime comes from than it is to be able to prove it inductively.

A: If we add the fractional parts of T(2n/3) and T(n/3), get T(n). Then, using the Master theorem, we have n^(log_(b)(a)) = n^(log_(1)(1)) = n. We also have f(n) = O(n). So n^(log_(b)(a)) = O(n) = Theta(f(n)), thus Case 2 of the Master theorem applies. Thus T(n) = Theta(n^(log_(b)(a)) * log(n)) = Theta(n*log(n)).


text:
Q: Dual boot mode (Legacy/efi) for external HDD I have an external HDD that I have used for backup for many years.
It has been formated MBR and gpt; and had partitions copied to it in both modes. Recently I discovered that if legacy mode is active, it will boot the legacy install. if legacy is inactive it will boot the efi install.
I assume this effect is reproducible. however, since I stumbled on it by accident, I don't know what I did to cause it.
Thus, my question is: What steps do I do to make a HDD boot both modes? I'm making a diagnostic/recovery/install drive. will there be any limitations on grub booting other partitions? (most will be FAT32 for copies of diag disks)

A: You need bootloaders for both modes.

*

*The BIOS bootloader is the MBR in the head of the drive plus extra code in the rest of the first mibibyte of a drive with an MSDOS partition table and the content of a small partition with the flag bios_grub in a drive with a GPT.

*The UEFI bootloader is the EFI partition and its content (a partition with a FAT partition table and a boot flag).
The following links provide detailed descriptions.

*

*help.ubuntu.com/community/Installation/UEFI-and-BIOS/stable-alternative

*help.ubuntu.com/community/mkusb/persistent#Partitions

*help.ubuntu.com/community/DiskSpace


text:
Q: What do you call this type of graph?
I am not sure what these types of graph are called, but they remind me of trees, except there is no root, or at least I don't see it. So is there a name for graphs that look like this? I imagine there are several different way to classify it. The more answers, the better.

A: This is called a brainstorming diagram or mind map:
https://datavizcatalogue.com/methods/brainstorm.html
They are used to classify ideas related to the original subject.
It can be thought of as a style of tree diagram where the root is the subject, branches are topics, and leaves are ideas.


text:
Q: how to run xcode 5 project on iphone 5 with ios 7.0.2 Can any one tell me how can I rum my xcode project on real iphone 5 with ios 7 installed without developers account

A: There is no possible way of doing what you want to do without an Apple Developer Account and a registration of the iOS Developer Program.

*

*Make an Apple Developer Account.

*Sign up for iOS Developer Programme.

*Create a Provisioning Profile for your device.

*Run your
app on the device.

That is if you are attempting to run your app in a regular device.
I believe there are ways to achieve this if your device is jailbroken, however I advise you to refrain from doing so.


text:
Q: Как написать скрипт, выводящий периодически в складывающем окне слова на английском и его перевод и затем закрывающий его? Изучаю по немного js и наткнулся на такое странное задание, с одной стороны интересное, с другой не понятное.

Написать скрипт, выводящий периодически в складывающем окне слова на
  английском и его перевод и затем закрывающий его.

Вопрос таков:

*

*Как это понять?

*Как это сделать?

A: Я сделал вот так)

var notransl = ["Яблоко", "Привет", "Пока", "Слово", "Мир", "Машина"];
var transl = ["Apple", "Hello", "Bye", "Word", "World", "Machine"];

function call() {
  popup = window.open("trnsl.html");
  setTimeout(wait, 8000);
}

function caller() {
  setInterval(call, 12000);
}

function wait() {
  popup.close();
}

function showMessage() {
  var x = Math.round(Math.random() * (notransl.length - 1));
  var y = Math.round(Math.random() * (notransl.length - 1));
  if (x == y) {
    y = Math.round(Math.random() * (notransl.length - 1));
  }
  document.write('
' + notransl[x] + " - " + transl[x]);
  document.write('
' + notransl[y] + " - " + transl[y]);
}
html, body{
 width: 100%;
 height:  100%;
}


text:
Q: Classifying data into known patterns with accord.net Let me begin by saying that my knowledge about machine learning is very, very limited. But I guess I could use my situation to learn it.
My problem domain evolves 18 well-known patterns. Those patterns are assigned to users once they get created in the system, by the order they come in.
The focus now is to import user data from a different system and the pattern information is not included in it. The patterns exist to make sure every user gets a job schedule. For the users being imported, I'll have to figure what their pattern is by observing their schedule. It's important to note that it's very common for their current schedule to not meet any known pattern entirely, so what I have to do is to find the most likely known pattern.
Reading through Accord's classification classifiers I thought Sequence classification could be a good fit for the problem so I tried to use it, as follows:
class Program
{
    static void Main(string[] args)
    {
        int[][] inputs =
        {
            new[] {1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1}, //pattern 1
            new[] {1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1}, //pattern 2
            new[] {1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3}, //pattern 3
            new[] {3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3}, //pattern 4
            new[] {3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3}, //pattern 5
            new[] {3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3}, //pattern 6
            new[] {3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3}, //pattern 7
            new[] {3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1}, //pattern 8
            new[] {1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1}, //pattern 9
            new[] {1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1}, //pattern 10
            new[] {1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1}, //pattern 11
            new[] {1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2}, //pattern 12
            new[] {2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2}, //pattern 13
            new[] {2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2, 2}, //pattern 14
            new[] {2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2, 2}, //pattern 15
            new[] {2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 2}, //pattern 16
            new[] {2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1}, //pattern 17
            new[] {1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1} //pattern 18
        };

        int[] outputs =
        {
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15,
            16,
            17
        };

        int[][] actualData =
        {
            new[] {3,3,1,1,1,1,2,2,2,2,2,1,1,1,1,3,3,3} // should be pattern 5
        };

        // Create the Hidden Conditional Random Field using a set of discrete features
        var function = new MarkovDiscreteFunction(states: 3, symbols: 3, outputClasses: 18);
        var classifier = new HiddenConditionalRandomField<int>(function);

        // Create a learning algorithm
        var teacher = new HiddenResilientGradientLearning<int>(classifier)
        {
            MaxIterations = 1000
        };

        // Run the algorithm and learn the models
        teacher.Learn(inputs, outputs);

        // Compute the classifier answers for the given inputs
        int[] answers = classifier.Decide(actualData);

        foreach (var answer in answers)
        {
            Console.WriteLine(answer);
        }
    }
}

I expected the output to be pattern 5 as they are an exact match, but that was not the case. I tried to train the model with more inputs by repeating the patterns an associating the input to the correct pattern. The actual data consist in more than 18 values. But it didn't help it match it, actually made it "worse".
In my ideal situation, the program would be able to always guess the known patterns right and find best candidates in data that don't match them. Have I chosen the wrong path here?

A: The example code threw an exception with Accord 3.8. If you change the following line it will execute and predict the correct class after 18 iterations:
var function = new MarkovDiscreteFunction(states: 18, symbols: 18, outputClasses: 18)


text:
Q: No-GUI automatic console screen off when idle I'm searching and searching and having a hell of a time finding out how to set a workstation install with the GUI disabled, to blank the screen automatically after being idle for a bit.
Anything to do with gsettings and xset won't work - there is no GUI.
I did find this useful command in another post -
setterm --blank 1

but that's a CLI command, you have to log in and run it, and apparently putting it in startup scripts or whatever doesn't work.
I want the system to boot, and if no one touches the keyboard, I want the screen to turn off after a bit.
It can't be as hard as searching is making it seem!
As is, it stays on forever.  I've got the system set to stay awake when the lid is closed (it's a laptop), and the screen stays on, forever ... I didn't realize this and wouldn't be surprised if I actually burned-in the screen last night leaving top up for 12+ hours :-(
Any help would be greatly appreciated!

A: Alright, found an answer while researching the fairly unrelated "How do I change the console resolution" question ...
consoleblank=seconds

needs to be added to the
GRUB_CMDLINE_LINUX=""

line in /etc/defaults/grub, then sudo update-grub, then reboot.


text:
Q: Angular: Add dynamic html component Using php REST, I am getting html in json from php server.
I used to simply use innerhtml to display the html in angular.
However, I need to add the html component to the angular component instead
main.ts
import { my_component } from './my_component';

@Component({
    selector: 'page-main_page',
    templateUrl: 'main_page.html'
})
export class main_page {
    data: any;

constructor(public mine: my_component ){

};

    ngOnInit(){
        this.getDynamicREST().then((res)=>{

          //where res is "
Test
"

          //????

        })
    };

}

my_component.ts
import { Component } from '@angular/core';

@Component({
    selector: 'my_component ',
    template: '????' // HTML json goes here
})

export class my_component {
   data: any;
}

How would I achieve this so that I can fetch angular components dynamically and add them to the my_component.ts template?
Any help will be much appreciated.
Thank you.


text:
Q: csv to php: accented letters? I have a page with a part in php that converts a .csv table to html. However, I have a problem with accented letters. Indeed, these are not shown even if the page is set with
meta http-equiv="Content-Type" content="text/html; charset=utf-8"

and the csv file is encoded in utf-8.
The other parts not processed by the php show the accented letters with no problem.
Should I add a string in the php to convert them?
Thank you so much,
Stefano

A: You can tried this, and let me know if your problem is resolved:
$string = (isUtf8($string))? $string : utf8_encode($string);

function isUtf8 ($string)
{
    //regex modified from http://www.w3.org/International/questions/qa-forms-utf-8.en.php
    return preg_match('%^(?:
          [\x09\x0A\x0D\x20-\x7E]           # ASCII
        | [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
        |  \xE0[\xA0-\xBF][\x80-\xBF]       # excluding overlongs
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
        |  \xED[\x80-\x9F][\x80-\xBF]       # excluding surrogates
        |  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        | [\xF1-\xF3][\x80-\xBF]{3}         # planes 4-15
        |  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
    )*$%xs', $string);
}

A: You can put all your return in the following PHP function:
string utf8_encode ( string $data )

You can include all your text without problem.
Font: http://www.php.net/manual/en/function.utf8-encode.php


text:
Q: Code keeps skipping input step I recently started using Java,and I need to start on a big project,but I'm getting weird issues in my code which looks like this:
    import java.util.Scanner;
public class Sifre {

    public static void main(String[] args) {
        Scanner unos = new Scanner(System.in);
        System.out.println("Unesite broj sifara:");
        int bsif = unos.nextInt();
        String sifre[] = new String [bsif];
        String imena[] = new String [bsif];
        int i,z;
        for (i = 0;i<bsif;i++)
        {
            System.out.println("Unesite sifru broj " + (i+1));
            sifre[i] = unos.nextLine();
        }
        for (z=0;z<bsif;z++)
        {
            System.out.println(sifre[z]);
        }
    }

}

Every time I run the code,It skips the first input step and continues to work normally even if the counter starts with more than 0.Here is the output,tell me what is wrong(I know the code isnt perfect,but its my first time posting after 3 months of Java)
> Unesite broj sifara:

>>3

>Unesite sifru broj 1

>Unesite sifru broj 2
>>first

>Unesite sifru broj 3
>>second
>
>first
>
>second

A: Add input.nextLine() after
int bsif = unos.nextInt();


text:
Q: How to merge two columns and re-arrange data in a specific order? New to python. I need to merge CA1 with CA2 and CB1 with CB2 and re-arrange the data with a specific order shown in the example.
Dataset

CA1
CB1
CA2
CB2

1
A
1.1
B
1.2

2
C
1.3
D
1.4

3
E
1.5
F
1.6

4
G
1.7
H
1.8

Needed as

CA1
CB1

1
A
1.1

2
B
1.2

3
C
1.3

4
D
1.4

5
E
1.5

6
F
1.6

7
G
1.7

8
H
1.8

A: Just stack the column pairs and create DataFrame out of them:
>>> pd.DataFrame({'CA1': df[['CA1', 'CA2']].stack().values,
              'CB1': df[['CB1', 'CB2']].stack().values})
  CA1  CB1
0   A  1.1
1   B  1.2
2   C  1.3
3   D  1.4
4   E  1.5
5   F  1.6
6   G  1.7
7   H  1.8

A: Split your dataframe into 2 parts, and concatenate them vertically. Then sort columns individually:
first = df[['CA1', 'CB1']]
second = df[['CA2', 'CB2']].set_axis(['CA1', 'CB1'], axis=1)

result = pd.concat([first, second], axis=0, ignore_index=True)
for col in result:
    result[col] = result[col].sort_values(ignore_index=True)

Result:
  CA1  CB1
0   A  1.1
1   B  1.2
2   C  1.3
3   D  1.4
4   E  1.5
5   F  1.6
6   G  1.7
7   H  1.8

A: Check Below Code using - Numpy
import pandas as pd
import numpy as np

df = pd.DataFrame({'CA1':['A','C','E','G'],'CB1':[1.1,1.3,1.5,1.7],'CA2':['B','D','F','H'], 'CB2':[1.2,1.4,1.6,1.8]})

pd.DataFrame(np.vstack([df[['CA1','CB1']].values,df[['CA2','CB2']].values]), columns=['CA1','CB1']).sort_values('CA1')

Output:

A: One option is with pivot_longer from pyjanitor:
# pip install pyjanitor
import pandas as pd
import janitor

df.pivot_longer(
    index = None,
    names_to = ('CA1', 'CB1'),
    names_pattern = ['CA', 'CB'],
    sort_by_appearance=True)

  CA1  CB1
0   A  1.1
1   B  1.2
2   C  1.3
3   D  1.4
4   E  1.5
5   F  1.6
6   G  1.7
7   H  1.8

A: ### Assuming your dataframe is called df
df = pd.DataFrame.from_records([{
    'CA1': 'A', 'CB1': 1.1, 'CA2': 'B', 'CB2': 1.2},
    {'CA1': 'C', 'CB1': 1.3, 'CA2': 'D', 'CB2': 1.4},
    {'CA1': 'E', 'CB1': 1.5, 'CA2': 'F', 'CB2': 1.6},
    {'CA1': 'G', 'CB1': 1.7, 'CA2': 'H', 'CB2': 1.8}])
# Make new dataframe with extra columns and rename the headers to match
df2 = df[['CA2', 'CB2']].rename(columns={
    'CA2': 'CA1', 'CB2': 'CB1'}
    )
# Drop the extra columns from your initial dataframe
df.drop(columns=['CA2','CB2'], inplace=True)
# Concat the dataframes
# ignore index so your index continues naturally rather than resetting
df = pd.concat([df, df2], ignore_index=True)
### Sort your dataframe by CA1 first, then CB1
df.sort_values(by=['CA1', 'CB1'], inplace=True, ignore_index=True)
print(df)


text:
Q: Does the django_address module provide a way to seed the initial country data? I'm using Django 2.0, Python 3.7, and MySql 5.  I recently installed the django_address module.  I noticed when I ran my initial migration based on my models.py file ...
from django.db import models

from address.models import AddressField
from phonenumber_field.modelfields import PhoneNumberField

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    class Meta:
        unique_together = ("name",)

class Coop(models.Model):
    type = models.ForeignKey(CoopType, on_delete=None)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

It created some address tables, including ...
mysql> show create table address_country;
+-----------------+---------------------------------------------------+
| Table           | Create Table                                      |
+-----------------+---------------------------------------------------+
| address_country | CREATE TABLE `address_country` (                  |
|                 |   `id` int(11) NOT NULL AUTO_INCREMENT,           |
|                 |   `name` varchar(40) COLLATE utf8_bin NOT NULL,   |
|                 |   `code` varchar(2) COLLATE utf8_bin NOT NULL,    |
|                 |   PRIMARY KEY (`id`),                             |
|                 |   UNIQUE KEY `name` (`name`)                      |
|                 | ) ENGINE=InnoDB                                   |
|                 | DEFAULT CHARSET=utf8 COLLATE=utf8_bin             |
+-----------------+---------------------------------------------------+

However, this table has no data in it.  Is there a way to obtain seed data for the table generated by the module or do I need to dig it up on my own?

A: You can generate the countries yourself pretty easily with the pycountry package.
Since the code field on the Country model that is created has a maximum length of two characters then you'll want to use the alpha_2 code.
I usually use a custom management command for this sort of thing. Maybe add a check to see if any objects have already been created then handle as you'd like.
Usage from the shell python manage.py create_countries
from address.models import Country
from pycountry import countries
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Initialize Country model'

    def handle(self, *args, **kwargs):
        create_countries = [
            Country(name=country.name[:40], code=country.alpha_2)
            for country in countries
        ]
        Country.objects.bulk_create(create_countries)
        self.stdout.write(f'Created {len(countries)} countries.\n')

If the production server isn't running Python/Django then you could use pycountry to create a CSV file with the relevant data. Assuming you're using PostgreSQL then you could use the COPY FROM command to populate the database.
import csv
from pycountry import countries

with open('countries.csv', mode='w') as countries_file:
    # specify delimiter because some countries have a comma
    writer = csv.writer(countries_file, delimiter='\t')
    writer.writerow(['id', 'name', 'code'])
    writer.writerows([
        [index + 1, country.name, country.alpha_2]
        for index, country in enumerate(countries)
    ])

A: As discussed above you need to add the actual data yourselves. You will need to prep it and do a one time upload. If you are looking for only country data, this is a good source. There is also a django app called django-countries which lets you have a lot more data and controls including flags, ISO codes etc. Another database with 3 letter codes is the IBAN list. Hope that helps.

A: You could use django-countries and include a CountryField in your model. This includes support for both models and a choice field for forms.
Since this is built in you could include this in your model just fine without having to worry about seeding a table.

A: I'd suggest you write a simple management command that imports data from pycountry into your address models (approach borrowed from here). pycountry is a wrapper around the ISO standard list of countries - i.e., it's about as canonical a list of countries as you're going to get.
A management command to populate all the countries into your Country model would look something like this:
import pycountry
from django.core.management.base import BaseCommand, CommandError

from address.models import Country

class Command(BaseCommand):
    help = "Populates address.Country with data from pycountry."

    def handle(self, *args, **options):
        countries = [
            Country(
                code=country.alpha_2,
                name=country.name[:40],  # NOTE - concat to 40 chars because of limit on the model field
            )
            for country in pycountry.countries
        ]

        Country.objects.bulk_create(countries)
        self.stdout.write("Successfully added %s countries." % len(countries))

This will populate your model with the ISO list of countries.
One caveat here is that the address.Country.name field is limited to 40 characters (which seems like a questionable design decision to me, along with the decision not to make country codes unique - ISO 2-letter codes definitely are unique), so the script above truncates the name to fit. If this is a problem for you I suggest you set up your own address models, borrowing from django-address and raising the character limit.

A: Simple is better. By the django doc, you can create a data migration: https://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations
Assume the app name of your models.py is coops, do something like this:
First:

*

*pip install django-countries (I prefer pipenv install) https://github.com/SmileyChris/django-countries
Second:

*

*Add django_countries to INSTALLED_APPS
Third:

*

*Make an empty migration file: python manage.py makemigrations --empty coops
Forth:

*

*Edit the migration file, for example: vi coops/migrations/0002_auto_20200205_0421.py

*file content:

# Generated by Django 2.2 on 2020-02-05 04:21

from django.db import migrations

def init_countries(apps, schema_editor):
    from django_countries import countries
    from address.models import Country
    countries = [
        Country(code=code, name=name) for code, name in countries
    ]
    Country.objects.bulk_create(countries)

class Migration(migrations.Migration):

    dependencies = [
        ('coops', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(init_countries),
    ]

Fifth:

*

*run python manage.py migrate
After migrate address_country table should have data as follows:
In [1]: from address.models import *

In [2]: Country.objects.all()
Out[2]: <QuerySet [<Country: Afghanistan>, <Country: Albania>, <Country: Algeria>, <Country: American Samoa>, <Country: Andorra>, <Country: Angola>, <Country: Anguilla>, <Country: Antarctica>, <Country: Antigua and Barbuda>, <Country: Argentina>, <Country: Armenia>, <Country: Aruba>, <Country: Australia>, <Country: Austria>, <Country: Azerbaijan>, <Country: Bahamas>, <Country: Bahrain>, <Country: Bangladesh>, <Country: Barbados>, <Country: Belarus>, '...(remaining elements truncated)...']>

In [3]: Country.objects.all().count()
Out[3]: 249


text:
Q: Is there a way to configure firebase.json file to serve different html files based on screen size? I have a website configured through Firebase Hosting. I'm using adaptive web design technique to serve a different html file for desktop vs. mobile devices. Essentially, I have two different html files, that are responsive, but I wanted to serve one on desktop and one on mobile. Is there a way to configure the firebase.json file to do this? Right now, I just have my website serving the index.html file, which is the desktop version. To get to the mobile version, I must add the "mobile.html" at the end of the url.
Here's my json file currently.
{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

A: Firebase Hosting doesn't provide a way to detect the type or size of mobile device for the purpose of serving content.
True responsive design is implemented as one set of HTML and CSS that renders correctly for any size and orientation of screen.  I strongly suggest that you look into how to implement that correctly (hint: use screen size media rules in CSS) rather than depending on the device identifying its capabilities through an HTTP request.  I'm sure you can find lots of great tutorials and examples of that using a web search.


text:
Q: Build OpenCV with contrib modules and Java wrapper I'm trying to build OpenCV on my Windows 7 machine. To include the contrib modules I have added the OPENCV_EXTRA_MODULES_PATH in CMake-gui. The opencv-300.jar and opencv-300.dll have been created but I can not find the Java classes to use the extra modules. Am I missing an option in the make configuration? Is it possible to use these extra modules from Java?

A: i've the same problem and i resolved in this way. I imagine that you had downloaded from contrib repo the specific version match with the opencv version if you want to build. So go in  directory and enter, for example, face module directory; in this directory there is a file called CMakeLists.txt that you have to edit. This file should be like this:
set(the_description "Face recognition etc")
ocv_define_module(face opencv_core opencv_imgproc opencv_objdetect WRAP python)
# NOTE: objdetect module is needed for one of the samples

If you want to have the org.opencv.face package in your opencv-3xx.jar library you have to modify the 2nd line of the file in this way:
ocv_define_module(face opencv_core opencv_imgproc opencv_objdetect WRAP python java)

Then you have to compile opencv as depicted in the Readme.md of the contrib repo https://github.com/itseez/opencv_contrib
Obviously the same thing is valid for all the contrib modules if you want to add to your opencv-3xx.jar library.
I hope that this solution works for you, bye!


text:
Q: Why hashcode in Java do not use long to store hash value? Java use int result = result * 31 + C to compute hash value. Just curious why 31 was chosen.
As stated in Effective Java:
The value 31 was chosen because of it's an odd prime. If it were even and the multiplication overflowed, information would be lost. Because multiplication by 2 is equivalent shifting.
for overflowing, why long type can not be used? Is it a trade-off about hash collision and memory usages?

A: The most common usage of hashCode() is to compute the index of the bucket into which to add an element/key to a HashSet/HashMap` (or lookup an existing element/key). That index  happens to be an array index.
Array indices can only be int, so it would be meaningless for hashCode() to return long. You would have to convert that long to an int anyway.


text:
Q: Sinon: how to create a stub that resolves multiple calls It seems straightforward to create a stub that returns different values on repeated calls:
Possible to stub method twice within a single test to return different results?
But, I how does one do this with an async method that resolves on multiple calls?
sinon(module, "myFunction")
  .resolves('a')
  .resolves('b')

To be clear, in the fragment above, the second resolves overwrites the first, so it always returns 'b'.   I'd like the behavior where 'myFunction' first resolves 'a' and then resolves 'b'.

A: Here's the solution:
sinon(module, "myFunction")
  .onFirstCall().resolves('a')
  .onSecondCall().resolves('b')


text:
Q: HTML5 Video Autoplay In Slider Issue I've integrated the JW HTML5 player into my jQuery Cycle slider. The problem is if I set the video to autoplay it plays when the page loads and not when that slide comes into view - which is what happens with Flash videos. Is there a way to prevent HTML5 videos from playing until their slide is shown?
This is the code I'm using:
 <video id="video-'.$video_name.'" width="'.$width.'" height="'.$height.'" poster="'.get_bloginfo('template_directory') .'/lib/scripts/timthumb.php?src='.$image.'&h='.$height.'&w='.$width.'&zc=1" controls="controls">
    <source src="'.$html5_1.'" type="video/mp4" />
    <source src="'.$html5_1.'" type="video/webm" />
    <source src="'.$html5_2.'" type="video/ogg" />
</video>

<script>
    jwplayer("video-'.$video_name.'").setup({
        file: "'.$url.'",
        image: "'.get_bloginfo('template_directory') .'/lib/scripts/timthumb.php?src='.$image.'&h='.$height.'&w='.$width.'&zc=1",
        icons: "'.$icons.'",
        autostart: "'.$autostart.'",
        stretching: "'.$stretching.'",
        controlbar: "'.$controlbar.'",
        skin: "'.$skin.'",
        screencolor: "white",
        height: '.$height.',
        width: '.$width.',
        players: [';
        if($fallback == "flash") {
            $out .= '{type: "html5"}, {type: "flash", src: "'.get_bloginfo("template_directory").'/lib/scripts/mediaplayer/player.swf"}';
        } elseif($fallback == "html5") {
            $out .= '{type: "flash", src: "'.get_bloginfo("template_directory").'/lib/scripts/mediaplayer/player.swf"}, { type: "html5" },';
        }
        $out .= ']
    });
</script>';

A: set video tag Attribute preload="auto"
preload attribute Specifies if and how the author thinks the video should be loaded when the page loads. default value of preload is none you can set it to the metadata or auto

A: See this opera dev article:
http://dev.opera.com/articles/view/introduction-html5-video/
You can tie the play() function into your js to start the video when that slide loads.


text:
Q: Compare date time in SQL Timestamp with XMLGregorianCalendar and ignoring seconds in JAVA I tried converting SQL Timestamp to XMLGregorianCalendar and then compare with other XMLGregorianCalendar, but the problem is if I put DatatypeConstants.FIELD_UNDEFINED for seconds and milliseconds while converting am getting "Invalid set of fields set for XMLGregorianCalendar"
Any suggestion please
Thanks in advance

A: Without having more information you could do the check in a couple ways.
1) Convert the two dates to Calendar instances and Zero out the time then simply run compareto
2) Get the Calendar instances and manually check Year to Year , Day to Day and finally Month to Month
public class DateCheck
{

  public static void main(String[] args)
  {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(new Date());
    try
    {
      XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
      Timestamp timeStamp = new Timestamp(System.currentTimeMillis());

      System.out.println("Are dates equal using manual check : " + manualDateCheck(timeStamp, xmlGregorianCalendar));

      Calendar timeStampCalendar = Calendar.getInstance();
      timeStampCalendar.setTime(timeStamp);
      System.out.println("Are dates equal using calendar check : " + calendarCheck(timeStampCalendar, xmlGregorianCalendar.toGregorianCalendar()));

    }
    catch (DatatypeConfigurationException e)
    {
      e.printStackTrace();
    }
  }

  public static boolean manualDateCheck(Timestamp timestamp, XMLGregorianCalendar xmlGregorianCalendar)
  {
    Calendar cal = xmlGregorianCalendar.toGregorianCalendar();
    Calendar otherCal = Calendar.getInstance();
    otherCal.setTime(timestamp);
    if (cal.get(Calendar.YEAR) != otherCal.get(Calendar.YEAR))
    {
      return false;
    }
    if (cal.get(Calendar.MONTH) != otherCal.get(Calendar.MONTH))
    {
      return false;
    }
    if (cal.get(Calendar.DATE) != otherCal.get(Calendar.DATE))
    {
      return false;
    }
    if (cal.get(Calendar.HOUR) != otherCal.get(Calendar.HOUR))
    {
      return false;
    }
    if (cal.get(Calendar.MINUTE) != otherCal.get(Calendar.MINUTE))
    {
      return false;
    }
    return true;
  }

  public static boolean calendarCheck(Calendar calendar1, Calendar calendar2)
  {
    return zeroCalendar(calendar1).compareTo(zeroCalendar(calendar2)) == 0;
  }

  public static Calendar zeroCalendar(Calendar calendar)
  {
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar;
  }
}

A: Thanks Kenneth,
calenderCheck is simpler and I will use that.. :) but I after trying many way I did in other way as below.
please correct me if the below one is not,
public class TestMain {

  public static void main(String[] args) throws DatatypeConfigurationException{

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(new Date());
    XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
    String sqlTimestamp = dateFormat.format(timeStamp);

    Timestamp xmlToSqlTimestamp = new Timestamp(xmlGregorianCalendar.toGregorianCalendar().getTimeInMillis());
    String xmlTimestamp = dateFormat.format(xmlToSqlTimestamp);
    System.out.println(timeStamp+" : "+xmlGregorianCalendar);
    System.out.println(sqlTimestamp+" : "+xmlTimestamp);

    System.out.println("Time stamps are equal : "+sqlTimestamp.equalsIgnoreCase(xmlTimestamp));
  }
}


text:
Q: SharePoint online certifcation path? Alright so I am asking broad question here and please correct me if I am not posting this in the right exchange.
I have worked and been developing on SharePoint 2013/16 on prem. for quite a few years now and I am trying to transition my career to Office 365. I have a few questions.
1) Are there any certification paths I should follow for SharePoint online?
2) Are there any boot camps/course out there that would help prepare a company for a transition from 2013/2016 to SharePoint online?
3) What are some major headache's during a transition from on-prem to online.

A: You could find all microsoft certifications here: https://www.microsoft.com/en-us/learning/browse-all-certifications.aspx
For more details for sharepoint certification, please refer to this article:https://www.scnsoft.com/blog/sharepoint-certifications
Microsoft 365 certification exam and traning:https://www.microsoft.com/en-us/learning/microsoft-365-exams.aspx
I think the biggest difference between SharePoitn 2013/2016 and SharePoint online is SharePoint online using modern experience. Please read this article to know about modern experience in SP online: https://support.office.com/en-us/article/sharepoint-classic-and-modern-experiences-5725c103-505d-4a6e-9350-300d3ec7d73f


text:
Q: could not find artifact while running maven build in jenkins While building the maven application in jenkins i get the following error
    [ERROR] Artifact: com.envoisolutions.sxc:sxc-runtime:jar:0.7.3-osgi has no file.
org.apache.maven.artifact.resolver.ArtifactNotFoundException: Could not find artifact com.envoisolutions.sxc:sxc-runtime:jar:0.7.3-osgi in central (http://repo.maven.apache.org/maven2)

org.apache.maven.artifact.resolver.ArtifactNotFoundException: Could not find artifact xpp3:xpp3_min:jar:1.1.3.4.O-osgi in central (http://repo.maven.apache.org/maven2)

Try downloading the file manually from the project website.

Then, install it using the command:
    mvn install:install-file -DgroupId=xpp3 -DartifactId=xpp3_min -Dversion=1.1.3.4.O-osgi -Dpackaging=jar -Dfile=/path/to/file

Alternatively, if you host your own repository you can deploy the file there:
    mvn deploy:deploy-file -DgroupId=xpp3 -DartifactId=xpp3_min -Dversion=1.1.3.4.O-osgi -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

  xpp3:xpp3_min:jar:1.1.3.4.O-osgi

from the specified remote repositories:
  central (http://repo.maven.apache.org/maven2, releases=true, snapshots=false),
  codehaus-releases (http://repository.codehaus.org/, releases=true, snapshots=true),
  java.net (http://download.java.net/maven/2/, releases=true, snapshots=true),
  central (http://repo.maven.apache.org/maven2, releases=true, snapshots=false)

Is there any way to restrict the search of maven to few repos ?

A: This artifact seems to be very old.
I found it in this Maven repository :
https://teamcity-systeme.lip6.fr/nexus/content/groups/public
Add this repo to your Maven's pom.


text:
Q: jpa composite primary key table not returning values I am new JPA and I am facing exceptions when I retrieve the values from composite primiary key table.
Exception Description:
Problem compiling [select t from ASSIGN_TASK_EMPLOYEE t].
    [14, 34] The abstract schema type 'ASSIGN_TASK_EMPLOYEE' is unknown.
        at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)

Following are my code
@Entity
        @Table(name = "ASSIGN_TASK_EMPLOYEE")
        //@IdClass(AssignTaskEmployeePk.class)
        public class AssignTaskEmployee implements Serializable {

            @EmbeddedId
            private AssignTaskEmployeePk assignTaskEmployeePk;

            public AssignTaskEmployeePk getAssignTaskEmployeePk() {
                return assignTaskEmployeePk;
            }

            public void setAssignTaskEmployeePk(AssignTaskEmployeePk assignTaskEmployeePk) {
                this.assignTaskEmployeePk = assignTaskEmployeePk;
            }

        }

       @Embeddable
        public class AssignTaskEmployeePk  {

            private String employeeId;
            private String taskId;
            public AssignTaskEmployeePk() {
            }

            @Override
            public boolean equals(Object obj) {
                // TODO Auto-generated method stub

                if (obj instanceof AssignTaskEmployeePk) {

                    AssignTaskEmployeePk employeePk = (AssignTaskEmployeePk) obj;
                    if (!employeePk.getEmployeeId().equals(this.employeeId)) {
                        return false;
                    }
                    else if (!employeePk.getTaskId().equals(this.taskId)) {
                        return false;
                    }

                }
                else {
                    return false;
                }

                return false;

            }

            @Override
            public int hashCode() {
                return employeeId.hashCode() + taskId.hashCode() ;
            }

            public String getEmployeeId() {
                return employeeId;
            }

            public void setEmployeeId(String employeeId) {
                this.employeeId = employeeId;
            }

            public String getTaskId() {
                return taskId;
            }

            public void setTaskId(String taskId) {
                this.taskId = taskId;
            }

            }

I have added four values in the databases for composite primary key ASSIGN_TASK_EMPLOYEE (table) which PK table
EMP_ID   TASKID
1         2
2         4
3         5
4         6

Now I would like to get the tasks assigned to emp_id 1
For that I wrote the query below:This would supposed to return list of AssignTaskEmployee object.
entityManager.createQuery("select t from ASSIGN_TASK_EMPLOYEE t").getResultList()

When I execute this query, I am getting the following exception
Exception Description:

Problem compiling [select t from ASSIGN_TASK_EMPLOYEE t].
            [14, 34] The abstract schema type 'ASSIGN_TASK_EMPLOYEE' is unknown.
                at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)

A: JPQL should use entities names, default are the name of the class. AssignTaskEmployee
It should be
entityManager.createQuery("select t from AssignTaskEmployee  t").getResultList()

The above will be return all the records in table ASSIGN_TASK_EMPLOYEE.
If you want to retrieve a specific record with JPQL you should use WHERE statement as it follows:
    Query query =  entityManager.createQuery("select t from AssignTaskEmployee t WHERE
t.assignTaskEmployeePk.employeeId = :employeeId and t.assignTaskEmployeePk.taskId = :taskId")

query.setParameter("employeeId", 1);
query.setParameter("taskId",1);

query.getSingleResult()  //As expected to have only one record.

Read this to query over EmbeddedId


text:
Q: trying to upgrade a web service to work with new end point 2010 I have an old web service that is located on a Windows 2003 server and we are getting ready to upgrade the box to Windows 2012. When I regenerate the vb file using the latest wsdl.exe, the new file that is generated does not compile and play well with others, I get hundreds of syntax errors on all "Partial" Classes, I compare the file to the old vb file that was being used and I don't even know if the new one has all the same attributes being called from my legacy program. This program was created originally 10 years ago and if they used an .xsd schema file when generating the final file, I have no idea. Has anyone ran into this issue before? How can I do some forensic work when I don't have any idea how the original vb file got generated? FYI the vb.net program that uses the web service uses it to build menu items based on Reports available and is based on the SSRS ReportServer.
Server Error in '/XXX.Edv.Web' Application.
Object reference not set to an instance of an object.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 288:                    Dim oItemsManagement() As CatalogItem = Application.Item("MANAGEMENTREPORTS")
Line 289:
Line 290:                    If oItemsManagement.Length > 0 Then
Line 291:                        Dim oManagementItem As MenuItem = New MenuItem
Line 292:                        oManagementItem = New MenuItem


text:
Q: scipy sparse matrix division I have been trying to divide a python scipy sparse matrix by a vector sum of its rows. Here is my code
sparse_mat = bsr_matrix((l_data, (l_row, l_col)), dtype=float)
sparse_mat = sparse_mat / (sparse_mat.sum(axis = 1)[:,None])

However, it throws an error no matter how I try it
sparse_mat = sparse_mat / (sparse_mat.sum(axis = 1)[:,None])
File "/usr/lib/python2.7/dist-packages/scipy/sparse/base.py", line 381, in __div__
return self.__truediv__(other)
File "/usr/lib/python2.7/dist-packages/scipy/sparse/compressed.py", line 427, in __truediv__
raise NotImplementedError
NotImplementedError

Anyone with an idea of where I am going wrong?

A: You can circumvent the problem by creating a sparse diagonal matrix from the reciprocals of your row sums and then multiplying it with your matrix. In the product the diagonal matrix goes left and your matrix goes right.
Example:
>>> a
array([[0, 9, 0, 0, 1, 0],
       [2, 0, 5, 0, 0, 9],
       [0, 2, 0, 0, 0, 0],
       [2, 0, 0, 0, 0, 0],
       [0, 9, 5, 3, 0, 7],
       [1, 0, 0, 8, 9, 0]])
>>> b = sparse.bsr_matrix(a)
>>>
>>> c = sparse.diags(1/b.sum(axis=1).A.ravel())
>>> # on older scipy versions the offsets parameter (default 0)
... # is a required argument, thus
... # c = sparse.diags(1/b.sum(axis=1).A.ravel(), 0)
...
>>> a/a.sum(axis=1, keepdims=True)
array([[ 0.        ,  0.9       ,  0.        ,  0.        ,  0.1       ,  0.        ],
       [ 0.125     ,  0.        ,  0.3125    ,  0.        ,  0.        ,  0.5625    ],
       [ 0.        ,  1.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 1.        ,  0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.375     ,  0.20833333,  0.125     ,  0.        ,  0.29166667],
       [ 0.05555556,  0.        ,  0.        ,  0.44444444,  0.5       ,  0.        ]])
>>> (c @ b).todense() # on Python < 3.5 replace c @ b with c.dot(b)
matrix([[ 0.        ,  0.9       ,  0.        ,  0.        ,  0.1       ,  0.        ],
        [ 0.125     ,  0.        ,  0.3125    ,  0.        ,  0.        ,  0.5625    ],
        [ 0.        ,  1.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 1.        ,  0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
        [ 0.        ,  0.375     ,  0.20833333,  0.125     ,  0.        ,  0.29166667],
        [ 0.05555556,  0.        ,  0.        ,  0.44444444,  0.5       ,  0.        ]])

A: Something funny is going on.  I have no problem performing the element division.  I wonder if it's a Py2 issue.  I'm using Py3.
In [1022]: A=sparse.bsr_matrix([[2,4],[1,2]])
In [1023]: A
Out[1023]:
<2x2 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements (blocksize = 2x2) in Block Sparse Row format>
In [1024]: A.A
Out[1024]:
array([[2, 4],
       [1, 2]], dtype=int32)
In [1025]: A.sum(axis=1)
Out[1025]:
matrix([[6],
        [3]], dtype=int32)
In [1026]: A/A.sum(axis=1)
Out[1026]:
matrix([[ 0.33333333,  0.66666667],
        [ 0.33333333,  0.66666667]])

or to try the other example:
In [1027]: b=sparse.bsr_matrix([[0, 9, 0, 0, 1, 0],
      ...:        [2, 0, 5, 0, 0, 9],
      ...:        [0, 2, 0, 0, 0, 0],
      ...:        [2, 0, 0, 0, 0, 0],
      ...:        [0, 9, 5, 3, 0, 7],
      ...:        [1, 0, 0, 8, 9, 0]])
In [1028]: b
Out[1028]:
<6x6 sparse matrix of type '<class 'numpy.int32'>'
    with 14 stored elements (blocksize = 1x1) in Block Sparse Row format>
In [1029]: b.sum(axis=1)
Out[1029]:
matrix([[10],
        [16],
        [ 2],
        [ 2],
        [24],
        [18]], dtype=int32)
In [1030]: b/b.sum(axis=1)
Out[1030]:
matrix([[ 0.        ,  0.9       ,  0.        ,  0.        ,  0.1       , 0.        ],
        [ 0.125     ,  0.        ,  0.3125    ,  0.        ,  0.        , 0.5625    ],
 ....
        [ 0.05555556,  0.        ,  0.        ,  0.44444444,  0.5       ,     0.        ]])

The result of this sparse/dense is also dense, where as the c*b (c is the sparse diagonal) is sparse.
In [1039]: c*b
Out[1039]:
<6x6 sparse matrix of type '<class 'numpy.float64'>'
    with 14 stored elements in Compressed Sparse Row format>

The sparse sum is a dense matrix. It is 2d, so there's no need to expand it dimensions.  In fact if I try that I get an error:
In [1031]: A/(A.sum(axis=1)[:,None])
....
ValueError: shape too large to be a matrix.

A: Per this message, to keep the matrix sparse, you access the data values and use the (nonzero) indices:
sums = np.asarray(A.sum(axis=1)).squeeze()  # this is dense
A.data /= sums[A.nonzero()[0]]

If dividing by the nonzero row mean instead of the sum, one can
nnz = A.getnnz(axis=1)  # this is also dense
means = sums / nnz
A.data /= means[A.nonzero()[0]]


text:
Q: NSArray handled as NSDictionary I am doing an HTTP call to my web server via objective-c app. The server returned json usually looks like this:
{
  "name": "test",
  "surname": "test",
}

but sometimes, when I am requesting a list of something, I get the JSON like this:
[
  { "name": "test" },
  { "name": "test" },
]

Now, I am handling the returned object as NSDictionary this way:
NSDictionary *results = [http doRequestWithData:@{ @"tag": @"whatever" } atUrl:@"/search"]
NSLog(@"%@", results);

I have omitted the implementation of doRequestWithData for simplicity, because the interesting  part of it is that when I do an NSLog of data, I get the following:
(
        {
        "_id" = 5353c332339a5ea32e000008;
        content = "i am the first search result";
    },
        {
        "_id" = 5353c32b339a5ea32e000007;
        content = "I am the second";
    },
        {
        "_id" = 5353c31c339a5ea32e000006;
        content = "third";
    },
)

Can anyone explain how this can happen? The returned data is an NSDictionary, but from the console it seems just like an array, as I cannot see the keys!

UPDATE: I am using NSJSONSerialization in my http class to serialize the object. The docs say it may return either a dict or an array based on the data. but the problem is that I am clearly defining it as NSDictionary! Shouldn't this at least throw and error?
This is what I am using in my http class to define the returned nsdictionary:
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return responseDict;

A: Unlike Java (and similar languages), there is no runtime type checking in Obj-C.
If your method returns a NSArray and you store it into a NSDictionary, it's not a problem for Obj-C. Until you try to call a method which is not defined for NSArray (e.g. objectForKey:).
Usually, such problems should be cought at compile time, however
+[NSJSONSerialization JSONObjectWithData:...] returns an id (it can return either NSArray or NSDictionary) and id is compatible with any type.

A: Your best bet is to do your own type checking on returned value using isKindOfClass:.
NSData *data = ...;

NSError *__autoreleasing jsonError;
NSDictionary *dictionary = data ? [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError] : nil;

if (jsonError || ![dictionary isKindOfClass:[NSDictionary class]])
    dictionary = nil;

You may want to do more handling than this, but this at least ensures you'll never access the wrong object type.


text:
Q: Any free alternatives to missing sync on OS X (for Palm OS HotSync)? I have a device (Alphasmart Dana) that requires Palm OS HotSync manager, but it's no longer supported by 10.6.

A: The only thing that I have been able to come arcorss, besides confirming your issue, is the software mentioned in that KB articled linked there.  The Missing Sync, no, it is not free, however, it is designed to sync up the Palm OS to the Macintosh computer, even to version 10.6.
iSync, built into Mac, unfortunately will not do it without the Palm Desktop, and the latest versions of both the desktop and hotsync manager just are not going to work with 10.6.
Wish i could give you better news, but that is all I have been able to find thus far.

A: try syncmate - it is apparently a free alternative to the missing sync. Unfortunately, I don't have that phone or OSX to try it out on, but it's worth a shot, I think


text:
Q: mysqli_query single query gerenating PHP fatal error: Allowed memory size exhausted I have a Mysql table (named "base") with 3 million records, which is composed of only 3 int(10) fields.

When I try to run this simple query $result = mysqli_query($db, 'SELECT * FROM base'), php shows the error:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted
  (tried to allocate 10485768 bytes) in C:\xampp\htdocs\combina.php on
  line 17

I think mysqli_query should not load all the table records into memory, right?
So why the memory overflow?
I'm using XAMPP installation on Windows 10, PHP 7.2.
Here is the code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comb";

$db = mysqli_connect($servername, $username, $password, $dbname);
if (!$db) {
    die("Falha na conexão: " . mysqli_connect_error());
}
$result = mysqli_query($db, 'SELECT * FROM base');

A: I researched and realized that the mysqli_query command actually loads ALL records into RAM. That is, for large tables, it will actually generate a memory limitation.
The solution I found was to use the combination of mysqli_real_query (which will activate the query without loading all the records in RAM, mysqli_use_result (which will return the resulting object not buffered ) and finally mysqli_fetch_row which will read the result line by line.
In this way the solution to the presented problem would be more or less:
$db = mysqli_connect($servername, $username, $password, $dbname);
mysqli_real_query($db, 'SELECT * FROM base');
$result = mysqli_use_result($db);
while ($row = mysqli_fetch_row($result)) {
    ...


text: Q: How to log information from multiple threads into different files in python? I am trying to log the different clients information in different files in python. ex client 1,client 2,client 3 in their specific files but in client 1 file all the information is coming 1,2,3 in client 2 file 2,3 information is coming.


text:
Q: Convert pandas dataframe into dictionary with keys one column and values the other Assuming I have a pandas DF as follows:
mydf=pd.DataFrame([{'sectionId':'f0910b98','xml':'<p/p>'},{'sectionId':'f0345b98','xml':'<a/a>'}])
mydf.set_index('sectionId', inplace=True)

I would like to get a dicctionary out of it as follwos:
{'f0910b98':'<p/p>', 'f0345b98':'<a/a>'}

I tried the following:
mydf.to_dict()
mydf.to_dict('records')

And it is not what I am looking for.
I am looking for the correct way to use to_dict()
Note: I know I can get the two columns into two lists and pack them in a dict like in:
mydict = dict(zip(mydf.sectionId, mydf.xml))

but I am looking for a pandas straight direct method (if there is one)

A: You could transpose your dataframe and then to_dict it and select the first item (the xml now-index).
mydf.T.to_dict(orient='records')[0]

returns
{'f0910b98': '<p/p>', 'f0345b98': '<a/a>'}


text:
Q: issue with apostrophes and double quotes in Javascript I'm having trouble adding in a variable into the following line of JavaScript:
 row.insertCell(0).innerHTML = "

"

how do I add in the password variable I'm getting confused with apostrophes and double quotes
I think it needs to put the value in-between apostrophes but this clashes with what's already there?

A: Try this:  row.insertCell(0).innerHTML = "

"

A: you can try escape quotes with backslashes like this
row.insertCell(0).innerHTML = "

"

A: Try this example:
 var Password ='sample';

 document.getElementById("id1").value= '

';

 alert(document.getElementById("id1").value);

This is called Escaping. Use backslash() for the character which you want to escape.


text:
Q: XML and XSD mistake i need help to solve my error with this code of XML and XSD, please if u can check it and tell me a solution of why it doesn't works am gona be your slave
this is my XSD code:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="clients">
<xs:complexType>
  <xs:sequence>
    <xs:element name="client" type="xs:string" maxOccurs="unbounded"/>
  <xs:complexType>
             <xs:sequence>
             <xs:element name="llinatge" type="xs:string"/>
             <xs:element name="edat" type="xs:decimal"/>
             <xs:element name="data_naixement" type="xs:date"/>
             <xs:element name="email" type="xs:string"/>
             <xs:element name="telefon" type="xs:decimal"/>
             </xs:sequence>
                <xs:attribute name="poblacio" type="xs:string" use="required"/>
                <xs:attribute name="codi" type="xs:string" use="required"/>
       </xs:complexType>
    </xs:sequence>
  </xs:complexType>
  </xs:element>
  </xs:schema>

This is my XML code:
<?xml version="1.0" ?>
<clients
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="clients.xsd">

   <client codi="001">
   <llinatge>Alomar</llinatge>
   <edat>30</edat>
  <data_naixement poblacio="Palma de Mallorca">3-10-1989</data_naixement>
      <email>alomar@gmail.com</email>
  <telefon>600898989</telefon>

  </client>
   <client codi="002">
      <llinatge>Pérez</llinatge>
      <edat>47</edat>
      <data_naixement poblacio="Ciutadella">3-10-1975</data_naixement>
      <email>alomar@gmail.com</email>
  <telefon>600898989</telefon>

   </client>
</clients>

A: Based upon the XML shown and what you have attempted in your XSD, I would recommend something like this:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="clients">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="client" maxOccurs="unbounded" >
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="llinatge" type="xs:string"/>
                            <xs:element name="edat" type="xs:decimal"/>
                            <xs:element name="data_naixement">
                                <xs:complexType>
                                    <xs:simpleContent>
                                        <xs:extension base="xs:string">
                                            <xs:attribute name="poblacio" type="xs:string" use="required"/>
                                        </xs:extension>
                                    </xs:simpleContent>
                                </xs:complexType>
                            </xs:element>
                            <xs:element name="email" type="xs:string"/>
                            <xs:element name="telefon" type="xs:decimal"/>
                        </xs:sequence>
                        <xs:attribute name="codi" type="xs:string" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Note that for the data_naixement I have it extending xs:string instead of xs:date, since those date values are not in the correct format YYYY-MM-DD. You could either assert some pattern restriction or correct the date format and change the type, depending upon what you are really expecting those values to be.


text:
Q: Excel Using Structured Reference Assume a table named: TableA
Item     ColA     ColB    ColC       ColD
RowA     10       no      30         40
RW_Start 11       yes     31         41
RowC     12       no      32         42
RW_End   13       yes     33         43
RowE     14       no      34         44

I would like to use structured reference as follows:
=COUNTIF(TableA[[ColB][RW_End]:[ColB][RW_Start]],"Yes")

I tried this versoin:
=ROWS(Regions[TableA[[ColB][RW_End]:[ColB][RW_Start]]])

and this version:
=ROWS(TableA[[ColB][RW_End]:[ColB][RW_Start]])

and other permutations, but nothing works throwing a formula error, rather than returning 2 and 3 respectively.
What am I entering wrong?

A: Based on the comment by @Scott Craner, the answer is:
=COUNTIF(INDEX(TableA[ColB],MATCH("RW_End", TableA[Item], 0)):INDEX(TableA[ColB],MATCH("RW_Start", TableA[Item], 0)), "yes")


text:
Q: sybase command to find out the duplicate value in a coulmn in sybase I have a table named tarty which consistss of variious filels
CREATE TABLE tarty  (
    aer_id      int NOT NULL,
    iewtwr      int NOT NULL,
    )

Can you please advise what will be the sybase command as i want to check that
aer_id should not have the same value
that is i want that if aer_id have the dame value in the table then it should be get listed out please
advise the sybase command for that

A: There is nothing Sybase-specific about the following query, this is standard SQL:
select aer_id, count(*) as nr_of_times
from tarty
group by aer_id
having count(*) > 1

If you want to guarantee uniqueness, declare the column as 'unique' so that a constraint will apply.


text:
Q: How to add markers to leaflet map with tabletop.js? I'm using this quite nice guide to add markers from a Google sheet to a basic leaflet.js map:
https://rdrn.me/leaflet-maps-google-sheets/
The problem is, using these code snippets here i get all the data logged and returned in the console, but none of the points appear on the map itself.
This is probably some really basic JavaScript issue that i'm not able to see. Sorry, still learning.
Here's a jfiddle, linking to a demo sheets with one marker point
https://jsfiddle.net/xfs19cz7/1/
with the map part:
function init() {
    Tabletop.init({
        key: '*url to gsheets here*',
        callback: myFunction,
        simpleSheet: true
    })
}

window.addEventListener('DOMContentLoaded', init)

function myFunction(data, tabletop) {
    console.log(data);
}

var map = L.map('map-div').setView([64.6220498,25.5689638], 5);
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Basemap (c) OpenStreetMap',
        minZoom: 5,
        maxZoom: 18
    });
basemap.addTo(map);

function addPoints(data, tabletop) {
    for (var row in data) {
        var marker = L.marker([
            data[row].Latitude,
            data[row].Longitude
        ]).addTo(map);
        marker.bindPopup('' + data[row].Info + '');
    }
}

This should add one point to a basic map. Now actually the map is not at all rendered, and no marker shows up. I can't find any issues in the code making the map show up blank, but there probably are some.
The marker from gsheets is however logged in the console, i suspect there is something missing in my code relating to really basic javascript functions / looping / sloppy syntax.
Also tried the init() and addPoints(data, tabletop) parts to a map i had where the map with the same basemap link, which rendereded OK. Adding this still left the map rendering, but no markers showed up. Again, the gsheets was loaded as an array of objects.
Could anyone point me to this, probably very basic, issue in the code?
edit:
callback: myFunction,

line above needs to be changed to
callback: addPoints,

also, init function needs to be called and position set to absolute. Thanks for the working fiddle in answer marked as correct below.

A: Fixes

*

*Try setting map position absolute

*calling the init() function

Working fiddle


text:
Q: Redirect a subdomain AND pages to a domain? Years ago, someone setup a subdomain or alias on our site and some pages, but we've had some problems clearing them out and need all old, broken references redirected to our home page.
While our site is "example.com" the subdomain is "www2.example.com" even though we can't find "www2" listed on the host cpanel subdomains, not in the .htaccess, alias etc. I did find a CNAME record and redirected it to to our home page (example.com).
However, there are lingering pages, such as www2.example.com/page1 that get redirected to example.com/page1 and a 404 error instead of going to the home page at example.com.
So I added this to the .htaccess file, but it does not seem to be working:
# www2 redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www2.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com [R=301,L]
</IfModule>

Thoughts?

A: Based on the standard cPanel setup, each sub-domain will have its own folder at main public directory("/public_html/www2").  So, you need to redirect every file from that sub domain/folder to main domain/folder.
Your final .htaccess file would be this simple config:
//301 Redirect Entire Directory
RedirectMatch 301 /www2(.*) //$1

Hope it helps!


text:
Q: Trying to convert ivy artifacts into maven - missing artifact exception for the pom, even though it is there Not sure if I'm going about this the right way, but I have some artifacts that I'm trying to convert to maven using ivy ant tasks and push into my maven repo.
the component in question is mystuff.services.common.
First I make the pom...
    <ivy:makepom ivyfile="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/ivy-mystuff.services.common.xml" pomfile="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/poms/mystuff.services.common.pom">
        <mapping conf="default" scope="compile"/>
        <mapping conf="runtime" scope="runtime"/>
    </ivy:makepom>

Then a little hackery - I insert an artifact element in the ivy file using xml task.  This works ok...
    <xmltask source="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/ivy-${resolved.revision}.xml" dest="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/ivy-${resolved.revision}.xml">
        <insert path="/ivy-module/publications" >
            <![CDATA[
               <artifact name="mystuff.services.common" type="pom"/>
            ]]>
        </insert>
    </xmltask>

Then I resolve/deliver/publish, as per various docs I've seen on how to do this.
    <ivy:resolve file="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/ivy-${resolved.revision}.xml"/>
    <!--<echoproperties/>-->
    <ivy:deliver conf="*" delivertarget="recursive-deliver"/>
    <ivy:publish resolver="myrepo-publish" publishivy="false" overwrite="true">
        <artifacts pattern="lib/myorg/[module]/[type]s/[artifact].[ext]"/>
    </ivy:publish>

And the error I get:
build.xml:235: impossible to publish artifacts for
  myorg#mystuff.services.common;1.0.1: java.io.IOException: missing artifact
  myorg#mystuff.services.common;1.0.1!mystuff.services.common.pom

If I leave out the pom from the artifacts in the ivy file, the other artifacts just publish fine.
What am I doing wrong?
This is what the ivy file looks like after inserting the pom entry for artifacts
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="../../ivy-doc.xsl"?>
<ivy-module version="1.0">

  <info organisation="myorg" module="mystuff.services.common" revision="1.0.1" status="integration" publication="20130206204156"/>

  <configurations>
    <conf name="default"/>
    <conf name="compile" extends="default"/>
  </configurations>

  <publications>
    <artifact name="services.common" type="jar" conf="compile"/>
    <artifact name="services.common~test" type="jar" conf="compile"/>

    <artifact name="services.common" type="javadoc-zip" ext="zip" conf="compile"/>
    <artifact name="services.common~test" type="javadoc-zip" ext="zip" conf="compile"/>

    <artifact name="services.common" type="src-zip" ext="zip" conf="compile"/>
    <artifact name="services.common~test" type="src-zip" ext="zip" conf="compile"/>

    <artifact name="com.myorg.mystuffservices.common" type="osgi-module" ext="jar" conf="compile"/>
    <artifact name="services.common" type="pom"/>
  </publications>

  <dependencies>
    <dependency org="org.testng" name="testng" rev="5.11" conf="compile->compile-15"/>
  </dependencies>

</ivy-module>

A: Your publish does not have an artifact pattern that finds the pom generated by your "makepom" task.
Either change the location or alternatively add an extra artifacts tag to your publish task:
<ivy:publish resolver="myrepo-publish" publishivy="false" overwrite="true">
    <artifacts pattern="lib/myorg/[module]/[type]s/[artifact].[ext]"/>
    <artifacts pattern="${ivy.lib.dir}/ivy/cache/myorg/mystuff.services.common/poms/mystuff.services.common.pom"/>
</ivy:publish>

I also don't understand why you're inserting a POM entry into you ivy file. Why don't you just list in your publications section?
For a detailed example see:

*

*how to publish 3rdparty artifacts with ivy and nexus


text:
Q: how to create thread in rails model using rubyinline and c I want to create two classes as follows:
class User < ActiveRecord::Base
  def self.some_method(array = ['name1', 'name2']) # a string array
    ...
  end
end

class ThreadCreator
  builder.c '
  void function do_with_threads(how_many, **array)
    create how_many threads, and pass each one slice of **array, example a = array[0], a = array[1] etc
    each thread calls: User.some_method(a)
  end
  '
end
e = ThreadCreator.new
e.do_with_threads(3, [
 ['name1'],
 ['name2', 'name3'],
 ['name4']
 ])

Now, how can i implement the details of the do_with_threads method call, so that it creates 3 threads, each thread calls User.some_method, the first thread calling it with ['name1'], the second thread with ['name2', 'name3'] and the third thread with ['name3'], so that code User.some_method(array= []) is executed with the threading asindicated above?


text:
Q: How can I use semaphore to describe precedence graph?
How can I Use semaphores to describe the synchronization of the eight processes in the general
precedence graph above?

A:    p1        p2        p3        p4        p5        p6        p7        p8
=============================================================================
    .         .         .         .         .        .         .          .
  work        .         .         .         .        .         .          .
    |         .         .         .         .        .         .          .
V(s1, 3)    P(s1)       .         .       P(s1)      .        P(s1)       .
    x         |         .         .         |        .          |         .
            work        .         .         |        .          |         .
              |         .         .         |        .          |         .
          V(s2, 2)    P(s2)     P(s2)      work      .          |         .
              x         |         |         |        .          |         .
                        |       work        |        .         work       .
                        |         |         |        .          |         .
                      work    V(s3, 1)   V(s3, 1)   P(s3)       |         .
                        |         x         x       P(s3)       |         .
                        |                             |         |         .
                        |                           work        |         .
                        |                             |         |         .
                    V(s4, 1)                      V(s4, 1)   V(s4, 1)    P(s4)
                        x                             x         x        P(s4)
                                                                         P(s4)
                                                                           |
                                                                         work
                                                                           |
                                                                           x


text:
Q: Color indicator for page rating fraction decimal value at Jekyll pages Every articles of my site based on Jekyll are rated with some formula and have values in fraction decimals from 0.0 either 179.87 and further more. Here is sample of the including in layout

#{{ page.shortname }} {% include
indexmod.html %}
is an Indexmod of the "{{
page.title }}"
 at the {{
site.title }}
{{ site.time |
date_to_long_string }}

that displays on the random page sample an article rating some value (here 179.87) in fraction decimal value. I want to generate and include with a color indicator that getting a hex color value from any fraction decimal value and look like correspondent-color-dot (see below)


text:
Q: C Programming data input error I'm writing this to get student information (full name, id and gpa for the last 3 trimester, so I used structures and a for loop to plug in the information however, after 1st excution of the for loop (which means at student 2) my 1st and 2nd input are shown on screen together. How could I prevent this from happening in a simple and easy way to understand? ( P.S: I already tried to put getchar(); at the end of the for loop and it worked, however; I'm not supposed to use it 'cause we haven't learnt in class)
The part of the c program where my error happens:
 #include <stdio.h>

struct Student {
  char name[30];
  int id;
  float gpa[3];
};

float averageGPA ( struct Student [] );

int main()
{
  int i;
  float average;
  struct Student studentlist[10];
  i=0;

  for (i; i<10; i++)
  {
     printf("\nEnter the Student %d full name: ", i+1);
     fgets(studentlist[i].name, 30, stdin);
     printf("Enter the Student %d ID: ", i+1);
     scanf("\n %d", &studentlist[i].id);
     printf("Enter the Student %d GPA for the 1st trimester: ", i+1);
     scanf("%f", &studentlist[i].gpa[0]);
     printf("Enter the Student %d GPA for the 2nd trimester: ", i+1);
     scanf("%f", &studentlist[i].gpa[1]);
     printf("Enter the Student %d GPA for the 3rd trimester: ", i+1);
     scanf("%f", &studentlist[i].gpa[2]);
  }

  average = averageGPA(studentlist);

  printf("\n\nThe average GPA is %.2f", average);

  return 0;
}

float averageGPA (struct Student studentlist[])
{
  int i;
  float total = 0.0, average = 0.0;
  for (i=0; i<10; i++)
  {
    total =  studentlist[i].gpa[0] + studentlist[i].gpa[1] + studentlist[i].gpa[2];
  }

  average = total / 30 ;
  return average;
}

Computer output:
Enter the Student 1 full name: mm

Enter the Student 1 ID: 12

Enter the Student 1 GPA for the 1st trimester: 3

Enter the Student 1 GPA for the 2nd trimester: 4

Enter the Student 1 GPA for the 3rd trimester: 3

Enter the Student 2 full name: Enter the Student 2 ID: <<<<< Here is the problem!!

A: Try eating the newline after the last scanf:
scanf("%f ", &studentlist[i].gpa[2]);
         ^

This is very much like your getchar solution. It's actually superior to getchar, since it only discards whitespace.

A: But you have to use getchar() to discard the newline character that is still in the input buffer after your last scanf("%f"), which according to given format converts a float and leave in the buffer all other chars.
If you can't use getchar(), use another fgets() at the end of the loop.. but of course getchar() would be better
Edit for explanation: whenever you type on your keyboard characters go in a input buffer waiting to be processed by your application. getchar() just "consumes" one character from this buffer (returning it), waiting for a valid char if the buffer is empty. scanf("%f") only "consumes" characters resulting in a float. So, when you type "5.12<enter>", scanf reads and removes from buffer "5.12" leaving "<enter>". So the next fgets() already finds a newline in the buffer and returns immediately; that's why you should use getchar(): ignoring its returning value you successfully discard "<enter>" from the buffer. Finally, please note that if in the buffer there is only "<enter>", scanf("%f") discards it (since it cannot be converted in a float) and waits for another input blocking application.
One last note: input stream is buffered by your OS default policy, in the sense that application does not receive any character until you type "<enter>".

A: Use scanf in following way to read the student name:
scanf(" %[^\n]",studentlist[i].name);

The first space in the format specifier is important. It negates the newline from previous input. The format, by the way, instructs to read until a newline (\n) is encountered.
[Edit: Adding explanation on request]
The format specifier for accepting a string is %s. But it allows you to enter non-whitespace characters only. The alternative way is to specify the characters that are acceptable (or not acceptable, based on the scenario) within square brackets.
Within square brackets, you can specify individual characters, or ranges, or combination of these. To specify characters to be excluded, precede with a caret (^) symbol.
So, %[a-z] would mean any character between a and z (both included) will be accepted
In your case, we need every character other than the newline to be accepted. So we come up with the specifier %[^\n]
You will get more info on these specifiers from the web. Here's one link for convenience: http://beej.us/guide/bgc/output/html/multipage/scanf.html
The space in the beginning actually 'consumes' any preceding white space left over from previous input. You can refer the answer here for a detailed explanation: scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?

A: I would just say no to scanf(). Use fgets() for all input fields and convert to numeric with atoi() and atof().


text:
Q: How to run Amplify's uploadFile function within a dart isolate? My application has a function that allows to upload videos and other large files to Amazon S3 buckets via Amplify storage. The below function works as expected and uploads a file to my S3 bucket:
  Future<String> uploadFile({File? file, String path = "", String fileName = "", String fileExtension = ""}) async {
try {
  final key = path+fileName+'.'+fileExtension;
  final result = await Amplify.Storage.uploadFile(
    local: file!,
    key: key,
  );
  return result.key;
} catch (e) {
  throw e;
} }

However, given the size of some of these files, the time required to upload can be large and I want to avoid that my users have to wait until the file is completely uploaded. Therefore I want to run the above function in a dart Isolate, so that the file can continue uploading while my user Navigates to different screens of the app.
I tried to achieve this with the below function:
  static uploadFileIsolate(List<dynamic> args) async {
try {
  SendPort responsePort = args[0];
  File file = args[1];
  String path = args[2];
  String fileName = args[3];
  String fileExtension = args[4];
  final key = path+fileName+'.'+fileExtension;

  final result = await Amplify.Storage.uploadFile(
    local: file,
    key: key,
  );
  Isolate.exit(responsePort, result);

} catch (e) {
  throw e;
} }

Which I call like this from my main function:
        final p = ReceivePort();
        Isolate.spawn(uploadFileIsolate, [p.sendPort, file, path, fileName, fileExtension]);

This is not working and throws the below error:
[VERBOSE-2:dart_isolate.cc(1111)] Unhandled exception:
RangeError (index): Invalid value: Valid value range is empty: 0
#0      DatabaseService.uploadFileIsolate (package:mastory/services/database_service.dart:202:7)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:17)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

After reading this issue it makes me think that the error comes from the fact that Amplify is not configured in the 'isolated' environment.
So my question is: How can I make Amplify's uploadFile function work in an Isolate?
Or, if that is not possible, how can I make sure that the uploadFile function continues until completion while allowing my user to Navigate to other screens in my app?


text:
Q: Reducing voltage in power supply with diodes Hello there i am building a variable power supply as a summer project. I have ordered some parts, and want to begin building it. I start with the transformer power supply:
I've ordered a transformer (230 V - 36 V) and i expected it to give a output voltage of 36 V peak (silly me), and then found out the output will be in RMS, i. e. an peak outout of 50,92 V. I can work with this, but the capacitors i've orderes is only rated at 50 V, so this will give me some smoking problems i guess. The rectifying diodes will give a voltage drop of minimum 0,6 V, which is not quite enough to go under 50 V.
Is it possible to just use two diodes extra? As seen in the simulation:

The diodes added is of course D5 and D6. Their only purpose is to lower the voltage, to under 50 V. This will theoretical be enough.
But will i need to go lower in voltage, as the overhead on the WV of the capacitor is too small?
And is the "extra diodes" way even a viable way of doing this?

A: As a rule of thumb, it is always desirable to select capacitors which are 1.5 times (2times is even better) the desired voltage. So, in short, the answer is NO. Theoretically(ideally) it should, but practically it will be a bad design. An Even slight increase in input voltage or any small variation in the circuit than ideal and you might see the circuit smoked.

A: What is important for the capacitor selection is the rms current it can accept and at what temperature. This is the major cause of failures in power supplies as manufacturers often select cheap capacitors which quickly overheat due to poor characteristics (high equivalent series resistance or ESR). Current ratings are usually given for a 120-Hz ripple so you should find the adequate information in the data-sheet if you operate from a 60-Hz network. So from your simulation results, extract the rms current in worst case (max output current and min input voltage for instance) and base your capacitor selection including some derating factor (safety margin). Then, voltage is of course important but not as sensitive as reported by some of the answers. A capacitor can operate close to its max voltage without problems. For instance, you can find 420-V bulk capacitors in hi-volume PFC-based adapters in which the nominal output voltage is 390 V (7% derating). However, using diodes to reduce the peak by a few volts is not reasonable especially considering a voltage drop depending on the absorbed current plus variations in the input voltage (+/- 15% in Europe). If you are stuck with the caps you have and providing they can accept the current, the best is to stack them in series and add equilibrium resistances so that they equally share the voltage. This is often done in hi-volume power supplies.

A:
this will give me some smoking problems i guess.

No point in guessing. Capacitor ratings are magic and it wouldn't explode just because the voltage is a tiny bit off when unloaded
Yes you can use more diodes to further reduce the voltage on the capacitor but it isn't the best solution

A: No, adding a few diodes to drop the voltage is not a good idea.
At best, you'd be running the electrolytic capacitors right at their maximum voltage.  That is not a good strategy.  It will decrease their lifetime, and it will still leave you vulnerable to voltage spikes or a little higher than usual line voltage.
You should aim for running electrolytic capacitors at around 75% of their rated voltage most of the time.  Then it's OK for spikes to occasionally go up to the rated voltage, but never above it.
Do it right.  Get the right transformer, or get the right capacitors.