text:
Q: + Operator for Dates in JavaScript The plus-operator ('+') seems to have multiple functions for Date-type objects in javascript. The following input gives different output for +t:
var t = new Date();
console.log('the date is '+t);
console.log(+t);

More confusing for me is that it doesn't convert to millseconds here:
console.log(t+5);

And especially:
console.log(5+t);

Since:
console.log(+t+5);

I'm surprised it treats the fives as strings, and that '+t' semantically different between +t+5 and t+5.
Is there a reference where I can find what operators have what impact on Date objects? That way I can get some confidence that the multiplicity of behaviors for + is implemented the same in each browser.
Quick fiddle: http://jsfiddle.net/yqQv7/

A: +new Date() is the same as Number(new Date()). It simply converts to a number using type conversion.

A: Here's an important notice regarding + (an addition operator) in the standard:

No hint is provided in the calls to ToPrimitive [when type-coercing an object]. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given.

And that's what happens when you attempt to evaluate new Date() + 5 expression. The left operand should become a String, not a Number - and toString is called, not valueOf.
On the contrary, this...
+new Date() + 5
... explicitly sets the left operand's type to Number (by calling valueOf method, which in case of Date returns that milliseconds' value). This is done before evaluating binary plus operation, because unary plus precedence is higher.

As a sidenote, the order of operands in + operation doesn't matter in JS: t + 5 and 5 + t are equivalent. And if t is a String (or type-coerced to a String), + will be treated as a concatenation operator, not an addition one.

A: The unary '+' operator (+x) is just a way to convert an expression into a number. All other combinations are either implicit number or string conversions. There is no special overloading of the '+' operator for Date.
The closest thing to a complete reference about how exactly Javascript operators work is the ECMAScript standard:
http://www.ecma-international.org/publications/standards/Ecma-262.htm
For a less complicated overview, you might want to have a look at the Mozilla reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference#Operators


text:
Q: What does sorting a list of lists in python mean for the following example: >> L = [[9, 1], [3, 4]]

>> sorted(L, key=lambda x:x[0])

[[3,4], [9,1]]

The above will sort the list according to the first element, meaning that the list with the smallest first element will appear first.
However, what does the following mean?
>> L = [[9, 1], [3, 4]]

>> sorted(L, key=lambda x:(x[0], x[1]))

[[3,4], [9,1]]

Or even
>> L = [[9, 1], [3, 4]]

>> sorted(L, key=lambda x:(x[0], x[1], x[0]))

[[3,4], [9,1]]

I'm not sure what keys mean when they have more than one item.

A: Hope this makes it clear:
>>> L
[[9, 1], [3, 4], [3, 2], [9, 0]]
>>> sorted(L, key=lambda x:(x[0], x[1]))
[[3, 2], [3, 4], [9, 0], [9, 1]]

Sort by first and then second element of the sublist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Library layouts using main app drawables I have an app that needs to be branded for a couple of different companies.
So basically, the functionality stays the same but each company has their own colours and logos.
I've been able to do this by having a library that contains pretty much everything, including the layouts, and then each company app is a separate application that contains all of the drawables (images) for that company, and it links to the library.
The problem is that I currently have to keep a set of the drawables with the library, even though those images will never be used. If I remove them, the library project gets the dreaded big red X on the layouts.
Is there a way to tell the library that the drawables are in the main app?
Or is it ok to leave that set of drawables - will they automatically be excluded from the built apk if the main app already has them?
Thanks,
-Nico


text: Q: Is there any MQTT client specifically for Xamarin forms? I have searched a lot about MQTT client for xamarin forms, but I am unable to get a bit of information about it. When I tried to install the MQTT client in the Nuget package of .net framework it shows an error saying "The .Net framework does not support the version of MQTT client".


text:
Q: moving trig function from the exponent? Is there a form of $e^{\sin(x)}$ that does not have trig functions in the exponent?  I've seen the "Euler Identity" form and looked into series expansions.  (thanks for the answers -- sorry I didn't give background earlier.)  I'm curious if there was something computationally faster than sin() then exp().

A: You could use this
$$
e^{\sin(x)} = e^{\frac{1}{2i}(e^{ix} - e^{-ix})}
$$
But I doubt that's what you're looking for.  A common trick in situations like this is to use the taylor series.  So you could try
$$
e^{\sin(x)} = e^{x-x^3/6 + x^5/120 - \cdots}
$$
or
$$
e^{\sin(x)} = 1 + \sin(x) + \sin^2(x)/2 + \sin^{3}(x)/6 + \cdots
$$


text:
Q: How we can perform different actions in single HTML form for changing url dynamically in django? HTML Template
<form action="" method="post">
    ...
    ...
    <input type="submit" name="Next" value="Next"/>
    <input type="submit" name="Cancel" value="Cancel"/>
</form>

I want to navigate on different pages by click this buttons. Specifically in django environment.

A: Usually your form should only have one submit button. You could have cancel button in an anchor tag and that has an href to the page you want to bring them too. Something like

  <form>
     ...fields...
    <button type="default">Cancel</button>
    <button type="submit">Save</button>

  </form>

You could also use javascript to perform these actions.


text:
Q: CPP Visual Studio 2017 "CLR Form"... Label wont take my string? I want my label object to display a string or an integer, but I can't seem to find the problem
"System::Windows::Forms::Label::Text::set" cannot be called with the given argument list

argument types are (std::string)
Function type is System::Windows::Forms::Label^

Scroll to the very end of my program to see what I'm talking about
#pragma once
#include <string>
#include <sstream>
#include <stdio.h>
#include <iostream>

int result;

namespace PraythisWorksOMG {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button1;
    private: System::Windows::Forms::TextBox^  textBox1;
    private: System::Windows::Forms::TextBox^  textBox2;
    private: System::Windows::Forms::TextBox^  textBox3;
    private: System::Windows::Forms::Label^  label1;
    protected:

    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->textBox2 = (gcnew System::Windows::Forms::TextBox());
            this->textBox3 = (gcnew System::Windows::Forms::TextBox());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->SuspendLayout();
            //
            // button1
            //
            this->button1->Location = System::Drawing::Point(74, 102);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(98, 34);
            this->button1->TabIndex = 0;
            this->button1->Text = L"button1";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
            //
            // textBox1
            //
            this->textBox1->Location = System::Drawing::Point(74, 169);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(100, 22);
            this->textBox1->TabIndex = 1;
            //
            // textBox2
            //
            this->textBox2->Location = System::Drawing::Point(74, 12);
            this->textBox2->Name = L"textBox2";
            this->textBox2->Size = System::Drawing::Size(100, 22);
            this->textBox2->TabIndex = 2;
            //
            // textBox3
            //
            this->textBox3->Location = System::Drawing::Point(74, 58);
            this->textBox3->Name = L"textBox3";
            this->textBox3->Size = System::Drawing::Size(100, 22);
            this->textBox3->TabIndex = 3;
            //
            // label1
            //
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(88, 212);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(46, 17);
            this->label1->TabIndex = 4;
            this->label1->Text = L"label1";
            //
            // MyForm
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(282, 253);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->textBox3);
            this->Controls->Add(this->textBox2);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->button1);
            this->Name = L"MyForm";
            this->Text = L"MyForm";
            this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void MyForm_Load(System::Object^  sender, System::EventArgs^  e) {
    }
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
    {

        int number;
        int radix;
        try
        {
            number = Convert::ToInt32(textBox1->Text);
            radix = Convert::ToInt32(textBox2->Text);
        }
        catch (...) // catch all Convert errors
        {

            MessageBox::Show("this isn't string");

        }
        if (radix < 2 || radix > 36)
        {
            MessageBox::Show("must be integers!");
        }
        else
        {
            do // conversion algorithm
            {
                char digit = number % radix;
                number /= radix;
                if (digit > 9) // for letters
                {
                    digit += 7; // add bias
                }
                digit += 0x30; // convert to ASCII
                result = digit + result;
            } while (number != 0);
        }

        std::string test = "test";
        label1->Text = "Test";
        label1->Text = test;

    }
    };
}

A: You have to convert your std::string to System::String. You can do it with:
label1->Text = gcnew System::String(test.c_str());

A: .NET classes do not interact with std::string, an unmanaged C++ standard library type.
It's looking for a System::String.
You generally don't want std::string in your managed code.
By the way, C++/CLI is on its way out. Why not use some lovely C# for this project?


text:
Q: I keep getting an "Unsupported Media Type" error using RestTemplate So I am having trouble with REST (which I am a beginner at). I would like to PUT a multipart form to a certain URL. I had accomplished this with Jersey from an example I found on the web, unfortunately in my project I am supposed to use the spring framework web client. Below is my working Jersey Code.
// setup properties
String publishUrl = "http://localhost:8080/url/to/rest/api";
File schemaFile = new File("myfile.xml");
String catalogName = "myFileName";

FileInputStream inputStream = new FileInputStream(schemaFile);
String jndiName = "myJNDI";
boolean overwrite = true;
boolean enableXmla = true;

//set up multi part form.
FormDataMultiPart part = new FormDataMultiPart()
        .field("uploadAnalysis", inputStream, MediaType.MULTIPART_FORM_DATA_TYPE)
        .field("catalogName", catalogName, MediaType.MULTIPART_FORM_DATA_TYPE)
        .field("Datasource", jndiName, MediaType.MULTIPART_FORM_DATA_TYPE)
        .field("overwrite", overwrite ? "true" : "false", MediaType.MULTIPART_FORM_DATA_TYPE)
        .field("xmlaEnabledFlag", enableXmla ? "true" : "false", MediaType.MULTIPART_FORM_DATA_TYPE)
        .field("parameters", "Datasource=" + jndiName, MediaType.MULTIPART_FORM_DATA_TYPE);

// If the import service needs the file name do the following.
part.getField("uploadAnalysis").setContentDisposition(FormDataContentDisposition.name("uploadAnalysis").fileName(schemaFile.getName()).build());

//set up client and create web resource
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("Admin", "password"));

WebResource resource = client.resource(publishUrl);
ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).put(ClientResponse.class, part);

System.out.println(response.getStatus());

This works fine. So now I have tried to transcribe this over to work with the spring web client. The following is my current code
//setup properties
String publishUrl = "http://localhost:8080/url/to/rest/api";
File schemaFile = new File("myFile.xml");
String catalogName = "myFileName";
String jndiName = "myJNDI";
boolean overwrite = true;
boolean enableXmla = true;

//setup form
MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
form.add("uploadAnalysis", new FileSystemResource(schemaFile));
form.add("catalogName", catalogName);
form.add("Datasource", jndiName);
form.add("overwrite", overwrite ? "true" : "false");
form.add("xmlaEnabledFlag", enableXmla ? "true" : "false");
form.add("parameters", "Datasource=" + jndiName);

//Set up credentials
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("Admin", "password"));

//set up http client
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

//create client request factory using httpcient
HttpComponentsClientHttpRequestFactory fact = new HttpComponentsClientHttpRequestFactory(httpclient);

//create rest template
RestTemplate rt = new RestTemplate(fact);

//create http headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

//use put method.
rt.put(publishUrl, headers, form);

This code does not work, I always get the following error:
 WARN  26-04 14:57:11,988 - PUT request for "http://localhost:8080/url/to/rest/api" resulted in 415 (Unsupported Media Type); invoking error handler

I am a bit confused by this because in Jersey I set the MediaType to "MULTIPART_FORM_DATA_TYPE" and in Spring I set it to "MULTIPART_FORM_DATA" so I am not sure why this would give me a unsupported media type. Any ideas would be helpful.
Edit
So I changed my code to not use the .put() method as I was using it wrong, the changes look like this.
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(form, headers);

    ResponseEntity<String> response = rt.exchange(publishUrl, HttpMethod.PUT, entity, String.class);

However, after making these changes I am getting a no response error
org.springframework.web.client.ResourceAccessException: I/O error on PUT request for "http://localhost:8080/url/to/rest/api":localhost:8080 failed to respond; nested exception is org.apache.http.NoHttpResponseException: localhost:8080 failed to respond
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:543)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:489)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:431)

The odd thing is the that the file is uploaded to the server, however I dont get any response from the server. Is there some type of header I have to set to get a response or something? When using Jersey I would get a response every time, so I am wondering if there was something pre-configured in jersey that I am unaware of.

A: You're using RestTemplate#put(...) incorrectly. The 3rd argument is meant to be a Map of URI variables. Instead use one of the RestTemplate#exchange(..) methods where you can pass an HttpEntity with the appropriate headers.


text:
Q: How to find a specific month by entering the number of the month and the year as integers? I have homework that involves the user entering 2 integers (The month & The year) and I was wondering how to do that, I have searched a little in the calendar class documentation but I didn't find what I was searching for.
The main thing I'm tring to do is to print a calendar like the one in Windows where the only input I get from the user is the number of the month and year, I need to find a way to find weather the month is 31, 30, 29 or 28 days and the day in which that month started.
http://lifehacker.com/assets/2006/06/vista-windows-calendar.jpg this is what I want to do but as text without printing the days from other months .

A: You could use java.util.Date for this:
int month = 3 ; // Input
int year = 2012 ; // Input
Date date = new Date() ;
date.setMonth(month) ;
date.setYear(year) ;

But since Date is deprecated, you would have to use java.util.Calendar instead. The equivalent functions are:
Calendar.set(Calendar.MONTH, month) ;
Calendar.set(Calendar.YEAR, year) ;

A: Since this is homework, I'm not spilling out all the beans. You have to figure out the rest.
Without knowing what have you tried or what do you mean by finding a month, I think you want to obtain a Date object based in a year and a month.
The Calendar class was a right start. First of all, you should obtain an instance with the getInstance() method, considering the set(int field, int value) method in particular to set both the year and the month of that calendar.
If you're wondering how do you know which field you're setting, try the different constant values defined by Calendar itself (by convention, those are named in uppercase, just for you to find them).
In the end you just need to obtain that Date, through the getTime() method.
EDIT
Following the Calendar class approach and by using set, you can come up with the month you're searching.
Use methods such as getActualMaximum(int field) with Calendar.DAY_OF_MONTH. That's practically one of the answers. The other one is similar and I'm leaving it up to you.
Hint: Create a calendar and play with the fields, try setting the day of the month to 1 (the first day) and the current month to the one you need to get information from.

A: Have a look at DateFormatSymbols. This has methods to retrieve the months. You can then use the index postion in the array (the month number) to get the month
   String[] months = new DateFormatSymbols(Locale.getDefault()).getMonths();
   System.out.println(months[0]);
   System.out.println(months[11]);

As it's homework I'll let you work out why [0] gives Januaray and [11] gives December

A: import java.util.Calendar;
import java.text.SimpleDateFormat;

class PrintCalendar {
    public static void main(String args[]) {
        Calendar c = Calendar.getInstance();

        int month = 3;
        int year = 2011;

        c.set(year, month, 1); // Set c's time to first day of specified month/year

        // Day of week (by numerical index) can also be obtained programmatically with c.get(Calendar.DAY_OF_WEEK)
        System.out.println("First day of month falls on a " + new SimpleDateFormat("EEEE").format(c.getTime()));
        // "Actual maximum" means the maximum in the current timeframe; that is, it will return 29 for a February in a leap year
        System.out.println("Month has " + c.getActualMaximum(Calendar.DAY_OF_MONTH) + " days");
    }
}


text:
Q: Escape key, arrow keys, etc not working in remote shell to server, but work on server's local shell Note, I am running these systems on VMWare Player.
Referencing this Arrow keys, tab-complete not working, it seems I should check to be sure my remote shell is running bash. My session is bash according to
echo $0
bash

Yet my arrow keys and escape key still print the following respectively
^[[D^[[A^[[B^[[C^[
Why are the key mappings so wonky?
Note: Bash and SSH version on server are a bit old (see comments). Client is up to date.
UPDATE:
I logged into the actual machine and the escape keys etc are working. It's just that when I connect with the remote shell they fail to work.

A: From your previous question  we know that you're dealing with an older Ubuntu system and bash 3.2 version.
Some of the shells don't come with readline library support (see my related question about this), which is what causes the control characters to show up on screen. Good example of that is Korn shell and Dash. I couldn't find whether or not bash 3.2 comes with readline library support. I'll ask around to make sure.
However, based on the output of locate readline.so you provided in the comments, it seems like your bash indeed is missing that library. Here's output of the same command from my system with bash 4.3.
$ locate readline.so
/lib/x86_64-linux-gnu/libreadline.so.5
/lib/x86_64-linux-gnu/libreadline.so.5.2
/lib/x86_64-linux-gnu/libreadline.so.6
/lib/x86_64-linux-gnu/libreadline.so.6.3

You could attempt to run set enable-keypad on but I doubt this will have any effect without readline library present.
The obvious solution would be to upgrade bash, but since you need this system for infosec studies, i assume you might want to keep it as is.

I've asked a related question on unix.stackexchange.com. You can check if bash uses readline with nm command , as shown in Thomas's answer


text:
Q: Index out of bounds exception when traversing InMultiPart object I am getting exception on my restService's file upload method. I am using Websphere application Server (8.5.x) and apache wink library (version 1.4).
You can find the sample code below.
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/uploadBigg/")
@Produces("application/json")
@javax.ws.rs.POST
public Response uploadDocument3(@Context HttpServletRequest request, @FormParam("channel") String channel,
        @FormParam("customerId") String customerId, @FormParam("userName") String userName,
        @FormParam("FileName") String fileName, InMultiPart inMP

) {
     while(inMP.hasNext()) {
         inMP.next();
     }

    return null;
}

And you can find exception details below. Thanks in advance
[21.11.2018 06:18:27:027 EET] 0000008e ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: An exception was thrown by one of the service methods of the servlet [tr.test.Application] in application [winktest2EAR]. Exception created : [java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -8216
    at java.lang.System.arraycopy(Native Method)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.shiftBuff(MultiPartParser.java:85)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.fetch(MultiPartParser.java:228)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.verifyByteReadyForRead(MultiPartParser.java:210)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.digestBoundary(MultiPartParser.java:149)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.nextPart(MultiPartParser.java:110)
    at org.apache.wink.common.model.multipart.InMultiPart.hasNext(InMultiPart.java:83)
    at tr.test.Service.uploadDocument3(Service.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:508)
    at org.apache.wink.server.internal.handlers.InvokeMethodHandler.handleRequest(InvokeMethodHandler.java:63)
    at org.apache.wink.server.handlers.AbstractHandler.handleRequest(AbstractHandler.java:33)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.CreateInvocationParametersHandler.handleRequest(CreateInvocationParametersHandler.java:54)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleSubResourceMethod(FindResourceMethodHandler.java:188)
    at org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleRequest(FindResourceMethodHandler.java:110)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.FindRootResourceHandler.handleRequest(FindRootResourceHandler.java:95)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.HeadMethodHandler.handleRequest(HeadMethodHandler.java:53)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.OptionsMethodWADLHandler.handleRequest(OptionsMethodWADLHandler.java:51)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.SearchResultHandler.handleRequest(SearchResultHandler.java:33)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.log.ResourceInvocation.handleRequest(ResourceInvocation.java:92)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.log.Requests.handleRequest(Requests.java:76)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.handlers.AbstractHandlersChain.run(AbstractHandlersChain.java:60)
    at org.apache.wink.server.internal.RequestProcessor.handleRequestWithoutFaultBarrier(RequestProcessor.java:207)
    at org.apache.wink.server.internal.RequestProcessor.handleRequest(RequestProcessor.java:154)
    at org.apache.wink.server.internal.servlet.RestServlet.service(RestServlet.java:124)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3980)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1016)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
]
[21.11.2018 06:18:27:045 EET] 0000008e LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
[21.11.2018 06:18:27:051 EET] 0000008e webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[tr.test.Application]: java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -8216
    at java.lang.System.arraycopy(Native Method)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.shiftBuff(MultiPartParser.java:85)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.fetch(MultiPartParser.java:228)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.verifyByteReadyForRead(MultiPartParser.java:210)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.digestBoundary(MultiPartParser.java:149)
    at org.apache.wink.common.internal.providers.multipart.MultiPartParser.nextPart(MultiPartParser.java:110)
    at org.apache.wink.common.model.multipart.InMultiPart.hasNext(InMultiPart.java:83)
    at tr.test.Service.uploadDocument3(Service.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:508)
    at org.apache.wink.server.internal.handlers.InvokeMethodHandler.handleRequest(InvokeMethodHandler.java:63)
    at org.apache.wink.server.handlers.AbstractHandler.handleRequest(AbstractHandler.java:33)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.CreateInvocationParametersHandler.handleRequest(CreateInvocationParametersHandler.java:54)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleSubResourceMethod(FindResourceMethodHandler.java:188)
    at org.apache.wink.server.internal.handlers.FindResourceMethodHandler.handleRequest(FindResourceMethodHandler.java:110)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.FindRootResourceHandler.handleRequest(FindRootResourceHandler.java:95)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.HeadMethodHandler.handleRequest(HeadMethodHandler.java:53)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.OptionsMethodWADLHandler.handleRequest(OptionsMethodWADLHandler.java:51)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.handlers.SearchResultHandler.handleRequest(SearchResultHandler.java:33)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.log.ResourceInvocation.handleRequest(ResourceInvocation.java:92)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.internal.log.Requests.handleRequest(Requests.java:76)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:26)
    at org.apache.wink.server.handlers.RequestHandlersChain.handle(RequestHandlersChain.java:22)
    at org.apache.wink.server.handlers.AbstractHandlersChain.doChain(AbstractHandlersChain.java:75)
    at org.apache.wink.server.handlers.AbstractHandlersChain.run(AbstractHandlersChain.java:60)
    at org.apache.wink.server.internal.RequestProcessor.handleRequestWithoutFaultBarrier(RequestProcessor.java:207)
    at org.apache.wink.server.internal.RequestProcessor.handleRequest(RequestProcessor.java:154)
    at org.apache.wink.server.internal.servlet.RestServlet.service(RestServlet.java:124)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3980)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1016)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)

A: I'm thinking that maybe you can't use InMultiPart and @FormParam together. That you might have to loop through each part manually if you use InMultiPart.
In case it's helpful, here's my write-up of when I implemented the same capability:
https://www.ibm.com/developerworks/community/blogs/Dougclectica/entry/JAX_RS_in_WebSphere_to_upload_files
Which also links to the official WebSphere page on this topic:
https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.multiplatform.doc/ae/twbs_jaxrs_multipart_formdata_from_html.html


text:
Q: For two standard uniform RVs is there a way to find the $E[|U_1-U_2|]$ using the linearity rule, ie $E[X+Y] =E[X] + E[Y]$? The answer is $\frac{1}{3}$ and I know how to get it by either:

*

*finding $f_{|U_1-U_2|}(a) = 2 -2a$ and doing the expected value formula

*or by calculating $\int \int |x-y| dxdy$
It looks like $E[|U_1-U_2|] \neq E[|U_1|]-E[|U_2|]$ since the LHS is $\frac{1}{3}$ and the RHS is $0$.
My questions

*

*What about the absolute value screws up the linearity of expected values?

*Is there a way to solve this problem using linearity of expectations?

A: "What about the absolute value screws up the linearity of expected values?" This issue has nothing fundamental to do with expected values at all; it's just a property of how numbers behave, and in particular how absolute values do not play nicely with $+$ or $-$. Note, for instance, that $|5 - 7| \neq |5| - |7|$.
"Is there a way to solve this problem using linearity of expectations?" Not an easy one, no. The best you can do is break this up into cases; consider one case where $U_1 > U_2$, and another where $U_2 > U_1$. You will quickly notice that this strongly resembles your direct calculation via double integral.
It's not the linearity of expected values that's burning you here, as they are indeed always linear; it's the (non)-linearity of absolute values.

A: I'll write $\operatorname{abs}(x)$ for $|x|$ because mixed vertical bars for absolute values and conditional probabilities get rather confusing. We have
\begin{eqnarray*}
E[\operatorname{abs}(U_1-U_2)]
&=&
\frac12E[\operatorname{abs}(U_1-U_2)\mid U_1\gt U_2]
+
\frac12E[\operatorname{abs}(U_1-U_2)\mid U_1\le U_2]
\\
&=&
\frac12E[U_1-U_2\mid U_1\gt U_2]
+
\frac12E[U_2-U_1\mid U_1\le U_2]
\\
&=&
\frac12\left(E[U_1\mid U_1\gt U_2]-E[U_2\mid U_1\gt U_2]\right)
\\&&+
\frac12\left(E[U_2\mid U_1\le U_2]-E[U_1\mid U_1\le U_2]\right)
\;,
\\
&=&
E[U_1\mid U_1\gt U_2]-E[U_2\mid U_1\gt U_2]
\\
&=&
E[U_1\mid U_1\gt U_2]-(1-E[U_1\mid U_1\gt U_2])
\\
&=&
2E[U_1\mid U_1\gt U_2]-1\;,
\end{eqnarray*}
where the equalities are respectively due to the law of total probability, the definition of the absolute value, the linearity of expectation, symmetry considerations, again symmetry consideration, and finally simple algebra.
Now you just need a nice way to find $E[U_1\mid U_1\gt U_2]$ :-)


text:
Q: Laravel 5.5 scopes definition I'm trying to make a scopes configuration. The scopes are build in the follow schema:
module:submodule:action

Also, I defined on boot section
Passport::tokensCan($scopes);

However, I got the following error when I'm trying to generate a token using oauth2 with Passport:
The requested scope is invalid, unknown, or malformed

A: The problem was method tokensCan receive an array, the keys must be the scopes for evaluate later with middleware scope or scopes.
use Laravel\Passport\Passport;
Passport::tokensCan([
    'place-orders' => 'Place orders',
    'check-status' => 'Check order status',
]);

A: A good tip is go to app\Providers\AuthServiceProvider
In the method boot add the follows code:
    public function boot()
    {
        // ...

        Passport::routes();
        Passport::tokensCan([
            'place-orders' => 'Place orders',
            'check-status' => 'Check order status',
        ]);
    }

It's work for me. (:


text:
Q: ASP - Disable a button to prevent user from clicking twice I am working on an ASP website. I want to disable a button after the user clicks the button.
If the users click the button twice by mistake, the DetailsPage.ASP is executed twice and duplicate entries are inserted into Database.
How to disable a button in ASP code to prevent the users from clicking twice?
Page1: Mainpage.asp page
     <form action="DetailsPage.asp" method="POST">
     <input type="Submit" name="Submitbutton" value="Update Details">

How to prevent the users from clicking the button twice or alert them if they try to click second time?
Another other suggestions to handle this type of scenario will be helpful.
Thanks in advance.
Thanks
Ashok

A: <% dim disabled
If request.form("Submitbutton") <> "" Then
disabled = " disabled"
End If %>

Then code your button like this
<input type="Submit" name="Submitbutton" value="Update Details" <%=disabled%>>

A: Add a handler for the form in JavaScript;
function submitForm(form)
{
    form["Submitbutton"].disabled = true;
    return true;
}

Attach it:
<form action="DetailsPage.asp" method="POST" onsubmit="submitForm(this);">


text:
Q: Denying direct access to configuration files I'd like to know how i can go about denying direct web access to configuration files of application whilst allowing php to access them.
I know most answers would suggest to put the includes outside the public_html directory. But I really don't think it's that efficient.
Thanks.

A: PHP just uses the file system to access files where web users usually go through apache and that verifies a .htaccess file. So just place that file that contains deny from all into that directory and voilla.


text:
Q: Convert string list to non-string list In Python, I want to convert all strings in a list to non-string.
So if I have:
results =  ["['new','york','intrepid', 'bumbling']","['duo', 'deliver', 'good', 'one']"]

How do I make it:
 results =  [['new','york','intrepid', 'bumbling'],['duo', 'deliver', 'good', 'one']]

A: How about eval if you don't need to verify the correctness of input variables:
results = [eval(x) for x in results]

A: Using literal_eval() from ast is much safer than eval():
import ast

results =  ["['new','york','intrepid', 'bumbling']","['duo', 'deliver', 'good', 'one']"]
results_parsed = [ast.literal_eval(x) for x in results]
print(results_parsed)

Output:
[['new', 'york', 'intrepid', 'bumbling'], ['duo', 'deliver', 'good', 'one']]

ast.literal_eval() only parses strings containing a literal structure (strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), not arbitrary Python expressions.


text:
Q: How to get DataSource connection from a Groovy Class with this groovy code? I used to have a Java Class in my Grails app, but I needed to get a connection from DataSource.groovy so I passed it to a Groovy Class, and I made it getting the Context Application. But How can I connect to that that Datasource with this code?:
def dataSource = ctx.getBean('dataSource_Executer') // auto injected and referenced to a datasource
Connection conn = null;
Statement stmt = null;
Class.forName('driver');
conn = DriverManager.getConnection(dataSource);// Here it's the trouble

I need it like this because I need the Metadata of the result query like this:
 stmt = conn.createStatement();
 def rs = stmt.executeQuery('query');
 def rsmd = rs.getMetaData();
 num = rsmd.getColumnCount();

and control it with a While:
 while(rs.next()){..........}

A: I would use the groovy.sql package to do this.
import groovy.sql.GroovyRowResult
import groovy.sql.Sql

def dataSource = ctx.getBean('dataSource_Executer')
def connection = new Sql(dataSource)
def results = connection.rows('SELECT ...')
results.each { r ->
  println r['columnName']
  ...
}

You can also access the ResultSetMetaData as well. This blog post has a good example of how to do so.

A: you can also use auto-wiring in a service/controller:
class SomeService {

 DataSource dataSource

 @Transactional
 def someMethod( params = [:] ){
   Sql db = new Sql( dataSource )
   db.eachRow( "select * from table" ) {
     doSometething it
   }
   db.close()
 }


text:
Q: Can not parse the type datetime I'm tring to call bluedart pincode master api using soap client but after passing parameters it gives error
Request parameter -
$params = array(
            'lastSynchDate' => '06-04-2016',
            'Profile' =>
                array(
                    'Api_type' => 'S',
                    'LicenceKey'=>$licencekey,
                    'LoginID'=>$loginid,
                    'Version'=>'1.3'
                )
        );

Response error -
The formatter threw an exception while trying to deserialize the message:

There was an error while trying to deserialize parameter http://tempuri.org/:lastSynchDate.
The InnerException message was 'There was an error deserializing the object of type System.DateTime.
The value '06-04-2016' cannot be parsed as the type 'DateTime'

How can I resolve this?

A: Although i have never used bluedart pincode master api but i am sure it is because the date is not in standard YYYY-MM-DD format.
Instead of
06-04-2016
Try
2016-06-04


text:
Q: How to apply TDD to very high level functionality? Another name for this question could be: How to TDD the main function?
My situation: I'm writing a program from scratch that runs a sort of simulation, and I want to apply TDD to the whole development process. It seems straightforward to me when I think about the small detailed features, but at some point the program needs to start. For example, this is a rough outline of how the program will run:

*

*Read data from a database.

*Loop a bunch of times simulating the desired behavior.

*Write the output somewhere.

I'm tempted to write a test like testLoopProducesValidOutput but that's basically just checking to see if the entire program ran correctly, which doesn't seem very unit-like for a unit test.
In the spirit of "don't write code unless you have a failing test", I don't quite understand what kind of test to write to actually get that initial high-level code written that isn't running the entire thing. How would one generally approach this kind of situation?
(Of course one solution is just to not strictly follow TDD for this part, but if there's another solution I'm open to learning before I give up. :) )

A:
I'm tempted to write a test like testLoopProducesValidOutput but that's basically just checking to see if the entire program ran correctly, which doesn't seem very unit-like for a unit test.

You're specifically talking about unit testing, so "let's test the whole lot in one go" is not in the spirit of that. Analyzing this with our unit testing cap on, we can test individual potential points of failure here.

*

*Does the main logic call [mocked] database dependency to fetch the data?

*When [mocked data] is returned from the [mocked] database dependency, does the main logic call the expected [mocked] simulation dependencies the expected amount of times?

*When a [mocked] simulation dependency returns [mocked data], does the main logic pass [mocked data] into a [mocked] logging dependency?

I've been repetitively explicit about point out that effectively everything except the main logic's behavior itself is mocked. These are isolated tests that verify a specific piece of the puzzle. None of these tests verify the entire lot by themselves (that would be an integration test - also valuable but not in scope of what you asked about).

In the spirit of "don't write code unless you have a failing test"

As with all broad advice, there are cases where you shouldn't take it too literally.
Technically, the advice is possible. If we start from an empty main logic method:

*

*It doesn't call the database dependency

*It doesn't call any simulation dependencies, let alone the correct number of times

*It doesn't call the logger dependency

However, this is fairly trivial logic and it is silly to mandate that the tests must invariably have been written before you even touched this logic.
Yeah, the advice to write (failing) tests first makes sense in a larger codebase where you're trying to introduce or extend logic. In a trivial logic snippet, the value derived from doing it precisely that way decreases and can become obstructive.
(note: I'm not a purist about any design principle and I abhor dogmatic thinking, TDD purists might disagree with this paragraph)

Of course one solution is just to not strictly follow TDD for this part, but if there's another solution I'm open to learning before I give up. :)

I think you're overly focusing on the whole "first write failing tests" part. The intention of that advice is not to state that if you do anything else first, that it therefore invalidates the TDD-ness of the codebase. The intention is to point out that you should properly design and back your code using tests, rather than slapping them on at the end of the development process as an afterthought.
Avoid dogmatic thinking. Understand the spirit of the advice rather than the letter of the law. There is no universal piece of advice that does not have an edge case.

A: TDD isn't limited to unit tests, it can be applied at any granularity. What you're trying to do is covered by acceptance test-driven development (ATDD) which adds an outer loop to the classic red-green-refactor cycle: you write a failing acceptance test first which should help you come up with a skeleton of your overall program, then you write failing unit tests before finally implementing the actual logic. The acceptance tests ensure that you are building the right thing and your various components are wired together correctly, while the unit tests ensure that your components are implemented correctly.
There is an excellent book on this topic called Growing Object-Oriented Software, Guided by Tests that goes into detail about this process and includes a worked example of a GUI application built from scratch using TDD.

A:
How to TDD the main function?
one solution is just to not strictly follow TDD for this part

For what it is worth, on my own authority this is precisely what I've given myself permission to do.

I conclude that there are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies -- C.A.R Hoare, 1980

If we've written code that "obviously" has no deficiencies, are we really getting a good return on our investment trying to create tests to run in our refactoring loops?
Consider this sketch of a main method for a command line dice game:
// Java
public static void main (String [] args) {
    somethingMoreComplicatedButTestable(
        System.in,
        System.out,
        new Random()
    );
}

Do you really think an automated mistake detector targeting this code is going to pay for itself?

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence -- Kent Beck, 2008

Here, the confidence comes from being disciplined about two rules

*

*code that is hard to test must be too simple to break

*code that is complicated must be easy to test in isolation

TDD is an awareness of the gap between decision and feedback during programming, and techniques to control that gap.  -- Test Driven Development by Example

Simplicity is a valid technique for controlling that gap.

See also: Mark Seemann's answer from 2014

A: If you really want follow the "don't write code unless .." rule dogmatically, make your "main program" a class of its own, with injected dependencies for the 3 steps you scetched in your question, and mocks which are designed to allow verifying that the main processing functions were called:
    TestMain()
    {
         //arrange
         DatabaseReader dr = new DatabaseReaderMock();
         Simulator sim = new SimulatorMock();
         OutputWriter ow = new OutputWriterMock();

         //act
         MainProgram mainProgram = new MainProgram(dr,sim,ow);
         mainProgram.Run();

         //assert
         Assert(dr.ReadDataWasCalled());
         Assert(sim.SimulateWasCalled());
         Assert(ow.WriteOutputWasCalled());
     }

This unit test design expects the MainProgram class to look somehow like this:
class MainProgram
{
     // DatabaseReader, Simulator  and OutputWriter are just interfaces
     MainProgram(DatabaseReader dr, Simulator sim, OutputWriter ow)
     {
         _dr=dr;
         _sim=sim;
         _ow=ow;
     }
     Run()
     {
         var data = _dr.ReadData();
         var output = _sim.Simulate(data);
         _ow.WriteOutput(output);
     }
}

You could also extend the test above and verify that Simulate was called with the output of "ReadData", and "WriteOutput" was called with the output of simulate, or that the three functions are called in that particular order (however, that may be at the borderline of expecting a specific implementation).
If you think this is worth the hassle, then go ahead. As an alternative, you may consider to rely on integration tests for this part of your system and do not write such a unit test.
Personally, I prefer pragmatism over dogmatism and would probably do the latter, as long as the MainProgram stays to be that simple. Moreover, whenever possible, I would try to keep the dataflow simple by a clear separation between processing components (DatabaseReader, Simulator, OutputWriter) and components which just orchestrate them (MainProgram).
IMHO "TDD by the book" rarely pays off for purely orchestrating components, but YMMV.

A:
How to apply TDD to very high level functionality?

TDD doesn't care what level you're at. Levels are in our heads.

I want to apply TDD to the whole development process.

Then start with tests. Tests that mean something.

this is a rough outline of how the program will run:

*

*Read data from a database.

*Loop a bunch of times simulating the desired behavior.

*Write the output somewhere.

None of this is worth testing. Testing this only accomplishes locking down the structure of the program. Unless you have a product owner who says, "make sure you loop" stop distracting yourself from useful tests.
I completely reject this example because it's forcing us to look at this the wrong way. Let's say your program calculates π. That has a high level right? A good high level test tells you if you got the first 10 digits correct. Oh but it must also output a timestamp so we know when we calculated this. That's another test. Oh and a duration so we know how fast we calculated it. Yet another test. Do these other requirements keep our first test from being a high level test? No. It's simply a test that's about something important to us. It's not an intermediate part of something else. But it's also not the only thing going on.
What puts these tests on top is that they are independent of each other. You can remove any of them (and the code they're testing) and everything else just works.
TDD is more than happy to let you write up any of these tests before writing any code to actually do them. The tests don't need to know if the methods that satisfy them get their data from a DB, loop, or even write to the console. If you write tests that know that stuff you're insisting that that's how the methods must work. Where did you get that requirement from?

How would one generally approach this kind of situation?

The key thing I've done here is to not break down the steps of calculating π. Rather I've identified required behaviors that can be tested and satisfied independently.

Hey wait, how is the duration test independent of the calculate π test?

By writing it so that it doesn't care if it's timing the calculation or any other method.

But that's mocking!

Yes but it's mocking to make the tests requirement independent. Not because we crossed some meaningless arbitrary boundary like a class.
There is a school of thought that wants every class to be a unit surrounded by tests. I've worked in shops that follow this. I fully recommend doing that if you're goal is to create code that can't be changed without enormous pain.
If not then make your unit the functional core, not each class. Mock to keep your tests independent of each other. Mock to speed things up so you don't sit around waiting for the DB, file system, or network. Don't mock just because it's mockable.
You don't have to take my word for it. Fowler wrote about what he called solitary or sociable tests. His style is the sociable tests.

A: I think the point is being missed here.
You have two questions in fact:

*

*One is how to test a function/class.

*The other is what a test means in TDD

Testing a function/class should already be quite well practiced by you based on the question.
The answer is dependency injection.
The problem is that your main function assumes to know more than it should. It does not know every situation in which it might be created, same as any other class/function.
The solution is to humble it. It should accept those dependencies somehow, be it through a constructor, a property (which has some default), or an optional parameter.
This will make the program even more capable, as it is now much more configurable and testable.
If for some reason the test is complex to setup, then the function/class needs to be broken down. After all you are essentially asking anyone who uses your function/class to know all of this information in order to use it well. Most of the time that user is yourself.

As for the second question (which you didn't state but is lurking back there)...
English is tricky in that the meaning of a word can be broad or even change in a different context or usage. 'Test' is one such word.
The problem is that there are several kinds of test:

*

*Aspirational Tests: These test describe something to be desired. In short a kind of Specification.

*Adversarial Tests: These tests probe for weaknesses and exploitable gaps. In short evidence of safety/security.

*Affirmational Tests: These tests pin down something that exists. In short evidence of organic code.

In TDD the goal is to write Aspirational tests.
The best time to write an aspirational test is when the code doesn't exist, or in a pinch without looking at the code (and you've had it unload from your own memory).
The worst time to write such tests is when the code exists. The temptation is very high to instead write an Affirmational, or an Adversarial test. Those tests have their benefits, but they won't deliver the thinking that an Aspirational test does.
An Aspirational test challenges you to simplify your tests. The simpler the tests:

*

*the fewer prerequistes/knowledge needed to use the code effectively,

*the more likely the code can be reused,

*the easier it is to change the aspired for behaviour.

*the easier it is to burn the implementation down and rebuild it,

*the easier it is for another programmer (or your future self) to understand and maintain the code

Similarly this principal can be applied at higher levels of modularity under different names. eg: BDD, ATDD.

A: I am not a big fan of mocking. It is useful in certain very special scenarios, but if you need a mocking framework, in my opinion you are doing something wrong.
Certain things need to be mocked because they cannot (should not...) be done in a unit test. For example accessing the file system to write output files. Or logging into the real production system, or even the real development system.
But your own logic should never be mocked away. Because in the end, you have thousands of unit tests, and not one of them actually tests whether your program is working! Every one is testing a tiny bit of functionality packed into a huge mass of mocking. So thousands of test could be green but when actually put together without mocks, it still fails. At least the possibility exists, and the whole point of tests is to make sure there is no such possibility.
Things you need to modify (I'm not saying "mock", because you can just switch out implementations, no need for a mocking framework):

*

*Logging needs to log into a container that is accessible and constrained to that one test.

*Data input needs to come from a source in that test. For example an in-memopry database unique to that test with data you decide on for each test.

*Data output needs to go into a container that is accessible and constrained to that one test.

So your test should be your actual program, reading from an in-memory database, writing to an in-memory filesystem.
For the first test, it's an empty database. I don't know what that yields, maybe a file with no rows and just the column headers. Assert that. Done. Your first test is written and fails. Make it compile, build and light up green. Then add more.
The point is, do not waste 90% of your testing on building fancy mocks. Test real things. Test things that need testing, the mocking framework doesn't.
Next test might be with exactly one value in the database. That might yield a file of one row. And then your go to more complicated input and edge cases.
If you cannot build a public input for your test case, your program does not need that test case, or that functionality.
As an added bonus, if you test your programs public interface, you can refactor your heart out and you do not need to refactor your tests. Because they do what they were designed to do: test whether your program still works, not whether you have used those exact functions in that exact order.
To summarize:

*

*Test reality. Not your mocking framework.

*Test whether your program works, not what it does internally.

*Start with the simplest case: no data.

*Then branch out into all the test cases.


text:
Q: froala editor 3 with react js - how to hide toolbar on initialize? I am trying to implement froala editor in my react js application, and the i need to keep toolbar hidden by default and should only show up when the textarea/editor has focus. in the previous versions the initialize would work like below but not in version 3 anymore. any help is appreciated.
'froalaEditor.initialized': function (e, editor) {
editor.toolbar.hide();
}

A: You have to use the config prop and then set an initialized event like this:
(
  <FroalaEditor
    tag='textarea'
    config={{
      events: {
        'initialized': function() {
          // this is the editor instance.
          this.toolbar.hide();
        }
      }
    }}
  />
)


text:
Q: Post a Facebook Story as map with C# is not working I am trying to post a Facebook story with a map attachement. I can post the story successfully, but the attachement is not shown as map.
I am using the Facebook C# SDK (http://facebooksdk.net/).
This is how I set up the story:

The custom object is set up with a custom property called geolocation, on which i reffer in the attachement configuration of my story:

And this is how I set the parameters for the FB post call:
parameters["location"] = new Dictionary<string, object>();
((Dictionary<string, object>)parameters["location"])["title"] = "Title";
((Dictionary<string, object>)parameters["location"])["geolocation:latitude"] = pokk.Location.Latitude.ToString(CultureInfo.InvariantCulture);
((Dictionary<string, object>)parameters["location"])["geolocation:longitude"] = pokk.Location.Longitude.ToString(CultureInfo.InvariantCulture);

The story is posted successfully, but this is how it looks like:

I hope you can help me..
Thanx in advance!
Greets!

A: I have spent the last couple hours trying to diagnose this issue and came up with a solution however the code changes quite abit. Basically the first thing you can do is actually set the property "location" to be required. You will notice that once you set it as required that the Graph API is failing due to a required property missing.
This is a good sign, it means that something is not quite right with the submission. After digging around and manually creating objects in the Object Browser I came up with a solution. Now it is worth noting that I am using dnyamic ExpandoObjects instead of dictionaries but the concept is the same. Review the commented code
//create our location object
dynamic locationData = new ExpandoObject();
locationData.title = "sample app testing " + DateTime.Now.ToString();

//create our geolocation object
dynamic geoData = new ExpandoObject();
geoData.latitude = 37.416382;
geoData.longitude = -122.152659;
geoData.altitude = 42; //<-- important altitude figure

//create our geo data item container and add the geoData object to the geolocation property
dynamic geoDataItem = new ExpandoObject();
geoDataItem.geolocation = geoData;

//set the data property of our location data to the geo data item container
locationData.data = geoDataItem;

//create our root object setting the location property to the location data object
dynamic objItem = new ExpandoObject();
objItem.location = locationData;

var response = context.Client.Post("me/<my_app_name>:<app_action>", objItem);

Really all we are doing is creating a simple structure using the expando object. Where I personally got stuck what not understanding how the complete GeoPoint operates. If you notice we have to create 2 containers.
One container so we can set the geolocation property on the data property of the location object.
The final structure resembles
--- MyStory
    --- location
        --- title : 'Sample app testing....'
        --- data
            --- geolocation
                --- latitude  : 37.416...
                --- longitude : -122.1526...
                --- altitude  : 42

This does seem rather complex but here is a final output preview.


text:
Q: CSS grid with flex basis? Current I'm doing
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));

But I want that when the view port is less than 400px the container should resize to the view port...
Or how do I implement Flex-basis property to grid... Where the minimum should be 0px but the container should start at 400px and then grow to 1fr

A: You can combine what you have with min() and 100vw. Less than 100vw to avoid unwanted overflow and the 1fr will do its job filling the remaining space. Any value bigger than 50vw will do the job

.container {
  display:grid;
  grid-template-columns: repeat(auto-fill, minmax(min(400px,80vw), 1fr));
  grid-gap:10px;
}

.container div {
  height:50px;
  background:red;
}

body {
  margin:0;
}


text:
Q: Difference between CBLQuery's(a.k.a CouchQuery's) documentID and sourceDocumentID I was trying to wrap my head around the difference between documentID and sourceDocumentID but just couldn't. Should I access the documentID of the row or sourceDocumentID? I'm trying to implement pagination in my iOS app (i.e something similar to futon) so, I need the last documentID to generate next set of rows. Can someone please enlighten me?

A: You can implements pagination by using two levels of Reference Documents (http://docs.couchbase.com/couchbase-devguide-2.1/#using-reference-documents-for-lookups)
Create reference document(1st level), that contains ids of another ref. documents(2nd level). This ref. docs on 2nd level will be your pages. If something is not clear, I am ready to explain more.

A: documentID and sourceDocumentID both refers to same id until or unless at the point of creating view in your map function you explicitly put reference of some other document's id, In this scenario your document id will be overriden by some other doc id and you can still refer to original id by calling sourceDocumentID
Please refer this link they have explained about it very well here
http://developer.couchbase.com/documentation/mobile/1.1.0/develop/guides/couchbase-lite/native-api/view/index.html


text:
Q: How to record a call using freeswitch from terminal? How to record a call in freeswitch using terminal,should I have to change the dialplan configuration or can somebody explain the way to do it?

A: you can use "uuid_record" API call
freeswitch@media1.kazoo> uuid_record
-USAGE: <uuid> [start|stop|mask|unmask] <path> [<limit>]


text:
Q: the size of thumbnail image is not changing and showing extra30x30 with it i'm working on wordpress with twitter bootstrap theme. i just made a grid of images in my template with the plugin display post shortcode.
Here is the code for that :
<?php echo do_shortcode('[display-posts category="Uncategorized" image_size="thumbnail" posts_per_page="100000"]'); ?>

its workign nicely. i have taken the image_size as thumbnail and the size for this in my Settings > Media is 30x30.  now i have made this grid.but now my problem is that i want to change the size from 30x30 to 100x100 so i have change it from Settings > Media, but its not changing and after seeing my page through firebug its showing like this :
<img class="attachment-thumbnail wp-post-image" width="30" height="30" alt="Yashika Bajaj" src="http://pearlacademy.com/history/wp-content/uploads/2998/09/Yashika-Bajaj-30x30.jpg">

i dont know why its adding extra -30x30into evry image.here i want to mention that my all images are of different sizes in original.

A: The parameters in back office is to manage size for insert image in post not for featured image.
if you want to change the featured size, you have to add this in your function.php
if ( function_exists( 'add_theme_support' ) ) {
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 100, 100, false ); // width, height, crop
}


text:
Q: How to use Gensim doc2vec with pre-trained word vectors? I recently came across the doc2vec addition to Gensim. How can I use pre-trained word vectors (e.g. found in word2vec original website) with doc2vec?
Or is doc2vec getting the word vectors from the same sentences it uses for paragraph-vector training?
Thanks.

A: Note that the "DBOW" (dm=0) training mode doesn't require or even create word-vectors as part of the training. It merely learns document vectors that are good at predicting each word in turn (much like the word2vec skip-gram training mode).
(Before gensim 0.12.0, there was the parameter train_words mentioned in another comment, which some documentation suggested will co-train words. However, I don't believe this ever actually worked. Starting in gensim 0.12.0, there is the parameter dbow_words, which works to skip-gram train words simultaneous with DBOW doc-vectors. Note that this makes training take longer – by a factor related to window. So if you don't need word-vectors, you may still leave this off.)
In the "DM" training method (dm=1), word-vectors are inherently trained during the process along with doc-vectors, and are likely to also affect the quality of the doc-vectors. It's theoretically possible to pre-initialize the word-vectors from prior data. But I don't know any strong theoretical or experimental reason to be confident this would improve the doc-vectors.
One fragmentary experiment I ran along these lines suggested the doc-vector training got off to a faster start – better predictive qualities after the first few passes – but this advantage faded with more passes. Whether you hold the word vectors constant or let them continue to adjust with the new training is also likely an important consideration... but which choice is better may depend on your goals, data set, and the quality/relevance of the pre-existing word-vectors.
(You could repeat my experiment with the intersect_word2vec_format() method available in gensim 0.12.0, and try different levels of making pre-loaded vectors resistant-to-new-training via the syn0_lockf values. But remember this is experimental territory: the basic doc2vec results don't rely on, or even necessarily improve with, reused word vectors.)

A: Radim just posted a tutorial on the doc2vec features of gensim (yesterday, I believe - your question is timely!).
Gensim supports loading pre-trained vectors from the C implementation, as described in the gensim models.word2vec API documentation.

A: Well, I am recently using Doc2Vec too. And I was thinking of using LDA result as word vector and fix those word vectors to get a document vector. The result isn't very interesting though. Maybe it's just my data set isn't that good.
The code is below. Doc2Vec saves word vectors and document vectors together in dictionary doc2vecmodel.syn0. You can direct change the vector values. The only problem may be that you need to find out which position in syn0 represents which word or document. The vectors are stored in random order in dictionary syn0.
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
from gensim import corpora, models, similarities
import gensim
from sklearn import svm, metrics
import numpy

#Read in texts into div_texts(for LDA and Doc2Vec)
div_texts = []
f = open("clean_ad_nonad.txt")
lines = f.readlines()
f.close()
for line in lines:
    div_texts.append(line.strip().split(" "))

#Set up dictionary and MMcorpus
dictionary = corpora.Dictionary(div_texts)
dictionary.save("ad_nonad_lda_deeplearning.dict")
#dictionary = corpora.Dictionary.load("ad_nonad_lda_deeplearning.dict")
print dictionary.token2id["junk"]
corpus = [dictionary.doc2bow(text) for text in div_texts]
corpora.MmCorpus.serialize("ad_nonad_lda_deeplearning.mm", corpus)

#LDA training
id2token = {}
token2id = dictionary.token2id
for onemap in dictionary.token2id:
    id2token[token2id[onemap]] = onemap
#ldamodel = models.LdaModel(corpus, num_topics = 100, passes = 1000, id2word = id2token)
#ldamodel.save("ldamodel1000pass.lda")
#ldamodel = models.LdaModel(corpus, num_topics = 100, id2word = id2token)
ldamodel = models.LdaModel.load("ldamodel1000pass.lda")
ldatopics = ldamodel.show_topics(num_topics = 100, num_words = len(dictionary), formatted = False)
print ldatopics[10][1]
print ldatopics[10][1][1]
ldawordindex = {}
for i in range(len(dictionary)):
    ldawordindex[ldatopics[0][i][1]] = i

#Doc2Vec initialize
sentences = []
for i in range(len(div_texts)):
    string = "SENT_" + str(i)
    sentence = models.doc2vec.LabeledSentence(div_texts[i], labels = [string])
    sentences.append(sentence)
doc2vecmodel = models.Doc2Vec(sentences, size = 100, window = 5, min_count = 0, dm = 1)
print "Initial word vector for word junk:"
print doc2vecmodel["junk"]

#Replace the word vector with word vectors from LDA
print len(doc2vecmodel.syn0)
index2wordcollection = doc2vecmodel.index2word
print index2wordcollection
for i in range(len(doc2vecmodel.syn0)):
    if index2wordcollection[i].startswith("SENT_"):
        continue
    wordindex = ldawordindex[index2wordcollection[i]]
    wordvectorfromlda = [ldatopics[j][wordindex][0] for j in range(100)]
    doc2vecmodel.syn0[i] = wordvectorfromlda
#print doc2vecmodel.index2word[26841]
#doc2vecmodel.syn0[0] = [0 for i in range(100)]
print "Changed word vector for word junk:"
print doc2vecmodel["junk"]

#Train Doc2Vec
doc2vecmodel.train_words = False
print "Initial doc vector for 1st document"
print doc2vecmodel["SENT_0"]
for i in range(50):
    print "Round: " + str(i)
    doc2vecmodel.train(sentences)
print "Trained doc vector for 1st document"
print doc2vecmodel["SENT_0"]

#Using SVM to do classification
resultlist = []
for i in range(4143):
    string = "SENT_" + str(i)
    resultlist.append(doc2vecmodel[string])
svm_x_train = []
for i in range(1000):
    svm_x_train.append(resultlist[i])
for i in range(2210,3210):
    svm_x_train.append(resultlist[i])
print len(svm_x_train)

svm_x_test = []
for i in range(1000,2210):
    svm_x_test.append(resultlist[i])
for i in range(3210,4143):
    svm_x_test.append(resultlist[i])
print len(svm_x_test)

svm_y_train = numpy.array([0 for i in range(2000)])
for i in range(1000,2000):
    svm_y_train[i] = 1
print svm_y_train

svm_y_test = numpy.array([0 for i in range(2143)])
for i in range(1210,2143):
    svm_y_test[i] = 1
print svm_y_test

svc = svm.SVC(kernel='linear')
svc.fit(svm_x_train, svm_y_train)

expected = svm_y_test
predicted = svc.predict(svm_x_test)

print("Classification report for classifier %s:\n%s\n"
      % (svc, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))

print doc2vecmodel["junk"]

A: This forked version of gensim allows loading pre-trained word vectors for training doc2vec. Here you have an example on how to use it. The word vectors must be in the C-word2vec tool text format: one line per word vector where first comes a string representing the word and then space-separated float values, one for each dimension of the embedding.
This work belongs to a paper in which they claim that using pre-trained word embeddings actually helps building the document vectors. However I am getting almost the same results no matter I load the pre-trained embeddings or not.
Edit: actually there is one remarkable difference in my experiments. When I loaded the pretrained embeddings I trained doc2vec for half of the iterations to get almost the same results (training longer than that produced worse results in my task).


text:
Q: Verilog module order Is it syntax correct with gate level Verilog file, where the the sub-modules are defined after the owning module or they should be defined before? Does it matter according to Verilog rules?
Regards,

A: This might be compiler dependent, but if you are using a tool that supports SystemVerilog (which most commercial tools do these days), it should be syntactically correct to define modules in any order, perhaps even in separate files.
See IEEE Std 1800-2012, Section 3.12 for more info.
Notice that after compilation, there is another step which is called elaboration. At that point all the module description should have been compiled correctly. From SystemVerilog LRM:

Compilation is the process of reading in SystemVerilog source code, decrypting encrypted code, and analyzing the source code for syntax
  and semantic errors. Implementations may execute compilation in one or
  more passes. Implementations may save compiled results in a
  proprietary intermediate format, or may pass the compiled results
  directly to an elaboration phase. Not all syntax and semantics can be
  checked during the compilation process. Some checking can only be done
  during or at the completion of elaboration.
SystemVerilog supports both single file and multiple file compilation
  through the use of compilation units (see 3.12.1).
Elaboration is the
  process of binding together the components that make up a design.
  These components can include module instances, program instances,
  interface instances, checker instances, primitive instances, and the
  top level of the design hierarchy. Elaboration occurs after parsing
  the source code and before simulation; and it involves expanding
  instantiations, computing parameter values, resolving hierarchical
  names, establishing net connectivity and in general preparing the
  design for simulation.

A: The short answer is that you can forward-reference modules in Verilog; this has always been the case, and is not tool-dependent (in other words, you can do it in either order). There may be complications if you use libraries and configurations but, in general, you can assume that you can instantiate a module before it is defined.
In most of Verilog, you have to declare something before you reference it. There are some exceptions, including task and function calls, implicit wires, cross-module/hierarchical references, and module names. In these cases, the tool waits until elaboration to find the referenced object. There is no clear explanantion of much of this in the LRM, unfortunately. This is how Verilog-XL did it, and everyone else has done it ever since.
Note that this isn't related to 'gate-level' files.

A: According to the rules defined in the Verilog LRM, modules, functions and tasks are the only things that may be referenced before being declared. SystemVerilog adds interfaces and programs to that list. Verilog also has implicitly declared nets that makes it seem that you are referencing a net before it being declared, but I strongly suggest not using that feature by using the compile directive ``default_nettype none.


text:
Q: How to be sure about which version of ISO 9660 filesystem has been used to format a CD/DVD? Note: Current version of UDisks I have: gnome-disk-utility 3.36.3
UDisks 2.8.4 (built against 2.8.4))
I have a several empty DVD+RW disks. When I insert them in the disk player and use UDisks (the gnome-disk-utility) it just indicates "ISO 9660".
I know there are different versions/levels/extensions of the ISO 9660 filesystem (Rock Ridge, Joliet, etc.—See ISO 9660 on Wikipedia). Is there a way to check whether the filesystem used on a disk is the original ISO 9660 or one of the other extensions?
Alternatively, would UDisks indicate it if it were a different extension/level of the ISO 9660 filesystem or does it label all the versions under the same "ISO 9660" indication?

A: Original answer
You can use xorriso from the repository universe.
sudo apt update
sudo apt install xorriso

xorriso -indev file.iso  # iso file
xorriso -indev /dev/sr0  # optical disk (CD or DVD)

to see some details of the iso system, for example with an Ubuntu iso file:
$ xorriso -indev ubuntu-22.04.1-desktop-amd64.iso
GNU xorriso 1.5.3 : RockRidge filesystem manipulator, libburnia project.

xorriso : NOTE : Loading ISO image tree from LBA 0
xorriso : UPDATE :     963 nodes read in 1 seconds
libisofs: NOTE : Found hidden El-Torito image for EFI.
libisofs: NOTE : EFI image start and size: 1866280 * 2048 , 8496 * 512
xorriso : NOTE : Detected El-Torito boot information which currently is set to be discarded
Drive current: -indev 'ubuntu-22.04.1-desktop-amd64.iso'
Media current: stdio file, overwriteable
Media status : is written , is appendable
Boot record  : El Torito , MBR protective-msdos-label grub2-mbr cyl-align-off GPT
Media summary: 1 session, 1868570 data blocks, 3650m data, 2321g free
Volume id    : 'Ubuntu 22.04.1 LTS amd64'

and for example with the first of two Windows 8 optical disks delivered with a now old Toshiba laptop:
sudo umount /dev/sr0  # unmount the automounted disk

$ xorriso -indev /dev/sr0
GNU xorriso 1.5.3 : RockRidge filesystem manipulator, libburnia project.

xorriso : NOTE : Loading ISO image tree from LBA 0
xorriso : UPDATE :       1 nodes read in 1 seconds
libisofs: WARNING : Found hidden El-Torito image. Its size could not be figured out, so image modify or boot image patching may lead to bad results.
xorriso : NOTE : Detected El-Torito boot information which currently is set to be discarded
Drive current: -indev '/dev/sr0'
Media current: DVD-ROM
Media status : is written , is closed
Boot record  : El Torito
Media summary: 1 session, 3950832 data blocks, 7716m data,     0 free
Volume id    : 'TI30990500A_1'

Find more details in man xorriso
Edit: Forwarded answer from the author of xorriso
I asked the author of of xorriso, Thomas Schmitt, and received the following answer via email:
Hi,
today i cannot get past the captcha of askubuntu.
So either point the readers of question 1441688 to bug-xorriso@gnu.org
for discussions or post my following answer:

The current stable version xorriso-1.5.4 can report the presence of
Rock Ridge (an addon to the ISO 9660 directory tree), Joliet (an alternative
ISO 9660 directory tree for MS-Windows with 16 bit characters for file names),
or ISO 9660-1999 (another alternative directory tree with few benefit).
$ xorriso -indev debian-11.5.0-amd64-netinst.iso -toc
...
ISO offers   : Rock_Ridge Joliet
ISO loaded   : Rock_Ridge
...

If it had a ISO 9660-1999 tree, then the "ISO offers" line would also show
the word "ISO_9660_1999". If there is neither Rock Ridge, nor Joliet, nor
ISO 9660-1999, then the word "Only_ECMA_119" is shown.
The "ISO loaded" line shows which tree gets read and subsequentely used by
xorriso operations. (This can be chosen by xorriso command -read_fs.)
The development version xorriso-1.5.5 has a new command
-assess_indev_features

which inspects the loaded ISO in more detail and reports the "level of
interchange" (1= all ECMA-119 names comply with DOS 8.3 style, 2= all data
files are smaller than 4 GiB, 3= data files of 4 GiB or larger exist).
$ xorriso -indev debian-11.5.0-amd64-netinst.iso -assess_indev_features plain
...
Indev feature: size=195584
Indev feature: iso_level=1
Indev feature: rockridge=1
Indev feature: joliet=1
Indev feature: iso1999=0
Indev feature: eltorito=1
Indev feature: tree_loaded=0
Indev feature: tree_loaded_text=ISO9660
Indev feature: rr_loaded=1
Indev feature: aaip=0
Indev feature: untranslated_name_len=0
Indev feature: allow_dir_id_ext=1
Indev feature: omit_version_numbers=0
Indev feature: allow_deep_paths=0
Indev feature: allow_longer_paths=0
Indev feature: max_37_char_filenames=0
Indev feature: no_force_dots=2
Indev feature: allow_lowercase=0
Indev feature: allow_full_ascii=1
Indev feature: relaxed_vol_atts=1
Indev feature: joliet_longer_paths=0
Indev feature: joliet_long_names=1
Indev feature: joliet_utf16=0
Indev feature: rrip_version_1_10=1
Indev feature: rrip_1_10_px_ino=0
Indev feature: aaip_susp_1_10=0
Indev feature: record_md5_session=0
Indev feature: record_md5_files=0

It can tell the native xorriso commands to achieve the seen properties when
writing a new ISO:
$ xorriso -indev debian-11.5.0-amd64-netinst.iso -assess_indev_features cmd
...
-compliance iso_9660_level=1
-rockridge on
-joliet on
-compliance iso_9660_1999_off
-compliance untranslated_name_len=0
-compliance allow_dir_id_ext
-compliance omit_version_off:only_iso_version_off
-compliance deep_paths_off
-compliance long_paths_off
-compliance long_names_off
-compliance no_force_dots_off:no_j_force_dots
-compliance lowercase_off
-compliance full_ascii
-compliance joliet_long_paths_off
-compliance joliet_long_names
-compliance joliet_utf16_off
-compliance old_rr
-compliance aaip_susp_1_10_off

and it can tell the mkisofs options to achieve the seen properties:
$ xorriso -indev debian-11.5.0-amd64-netinst.iso -assess_indev_features as_mkisofs
-iso-level 1
-R
-J
-d
-U
-joliet-long

Download offer of the development snapshot
https://www.gnu.org/software/xorriso/xorriso-1.5.5.tar.gz
Compilation instructions are in
https://www.gnu.org/software/xorriso/README_xorriso_devel
"Compilation, First Glimpse, Installation"
I pronounce "xorriso" the german way, like an english speaker would read
"ksorr-ee-zo". But actually the natural english pronounciation "ksorr-i-so"
is the correct one. It stands for X/Open, Rock Ridge, ISO 9660.

Have a nice day
Thomas


text:
Q: Finding matching inner text in HTML controls and changing its format using JavaScript I am generating a page which renders a list of linkbuttons and labels. Now I want a javascript that parses the inner text of these controls and makes bold those with keywords that match like Google does while rendering a list of websites with linkbutton and its description.
How should i proceed ?

A: This should get you started: http://www.nsftools.com/misc/SearchAndHighlight.htm

A: To get the collection of link buttons and label elements use getElementsByTagName, then iterate through the collection and use the innerHTML property to access the content within them and match against your keywords. Then for the matching elements set the style.fontweight property to bold.


text:
Q: Create View with Collation I need to create a view from another database (linked as connectionserver) but here I need a different collation.
Example:
CREATE VIEW vw_table1
AS
SELECT *
FROM server2.table1;

How can I specify the collation by using this script?
Thanks in advance


text:
Q: jQuery document on('click') event preventing form on('submit') event I have an HTML div img_div which is receiving dynamically generated content including a form. The form has an input type="file" and input type="submit".
I wrote a jQuery function showImg() which dynamically populates img_div and overrides the submit event for the form, which prevents the page refresh and appends files uploaded by the form.
showImg() works perfectly on its own. However, I want img_div to disappear when the user clicks anywhere else on the page, so I created a $(document).click() event handler to hide the div when the user clicks anywhere else. This event also works, except when I implement it, the page now refreshes when I submit my form in img_div.
To be clear, if I disable the $(document).click() event, the form appends the image without refreshing the page. If I enable $(document).click() event, the form refreshes the page and navigates to a page just displaying the loaded image.
Why is the $(document).click() event handler preventing the on('submit', 'form') event handler from firing? How do I get the two event handlers to both fire when the form is submitted? I tried using event.stopPropagation() on the input type="submit" in my form, but it had no effect.
Here is the img_div html:

And here are the JS functions:
$(document).click(function( event ) {
    if (event.target.id != 'img_div' && $(event.target).parents('#img_div').length == 0) {
        var tag = 'div';
        var element_class = 'pop_up_menu';
        var div_list = document.getElementsByTagName(tag);
        for(var i=0;i<div_list.length;i++)
        {
            if(div_list[i].className == element_class)
            {
                var el_id = '#'+div_list[i].id;
                $(el_id).off();
                div_list[i].innerHTML="";
                div_list[i].style.display = 'none';
            }
        }
    } else {
    }
});

function showImg(event, divID, category, id)
{
    var y = event.pageY;
    var x = event.pageX;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById(divID).style.display = 'inline';
            document.getElementById(divID).innerHTML = xmlhttp.responseText;
            document.getElementById(divID).style.top = y+'px';
            document.getElementById(divID).style.left = x+'px';
            document.getElementById(divID).style.border="1px solid #A5ACB2";
        }
    }

    var url = "/rtd/plugins/includes/image_popup.php?category="+category;
    url += "&id="+id;
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
    $('img_div').off();
    $('#img_div').on('click', 'input', function( event ){
        event.stopPropagation();
    });
    $('#img_div').on('submit', 'form', function( event ){
        event.preventDefault();

        var rowid = 'row_'+Date.now();
        var rowpointer = '#'+rowid;
        var form_id = $(this).attr('id');
        var form_pointer = '#'+form_id;
        var form = $(form_pointer)[0];
        var formData = $(form_pointer).serialize();
        var action_url = $(form_pointer).attr('action');

        var fileData = new FormData(this);

        var ajIMAGE = $.ajax({
                type: 'POST',
                url: action_url,
                data: fileData,
                contentType: false,
                processData: false
            })
        ajIMAGE.done(function ( data ) {
            $("#image_table").append('
'+data+'
');
            $("#noimage").hide();
            $(form_pointer).trigger('reset');
        });
    });
}


text:
Q: How to apply CSS to my JQuery Plugin I'm writing a JQuery component plugin that requires some minimal default css. (The css is required for the component's functional layout- not just style dressing)  Should I:

*

*Write a separate .css file and dynamically load it in my plugin code (How would I do this?)

*Apply the css attributes directly in my plugin code using JQuery's .css(...)

It seems the second option would be a more secure way of ensuring my component gets the css it needs.  Thoughts?

A: I'd agree with Tom about keeping them separate. However, if you did want to go with styling the plugin in the jQuery code, then here's a great tutorial on how to set defaults and expose them as configurable properties: http://mattberseth.com/blog/2008/06/glowbuttons_writing_my_first_j.html

A: I'm a fan of keeping CSS in a separate file and then importing it using the plugin.
Overtime, this makes it easier to maintain and it makes it easier for users or future developers to work with your plugin rather than digging through JavaScript source (which will likely grow overtime).
To apply a stylesheet with jQuery, you can do this:
$(function() {
  $('head').append('<link rel="stylesheet" href="plugin-styles.css" type="text/css" />');
});

Obviously, you'll need to know the path to the CSS file but If you ship a css directory with your plugin, this shouldn't be problem.
As far as "ensuring [your] component gets the css it needs," the first option will work file as long as you make sure your elements have a unique identifier (classname or ID) that the JavaScript source can access.
If you want to make sure that you're not loading the stylesheet multiple times, you can do something like this:
$(function() {

  var bStylesheetExists = false;
  $('link').each(function() {
    if($(this).attr('href') === 'plugin-style.css')) {
       bStylesheetExists = true;
    }
  });

  if(bStylesheetExists === false) {
    $('head').append('<link rel="stylesheet" href="plugin-styles.css" type="text/css" />');
  }

});

A: Like @Tom idea, although I've seen plenty of jquery plugins with a separate CSS file.
But I'm inclined to suggest that a separate CSS file is involved so that:

*

*styles can be overridden by the user if necessary

*name clashes can be debugged

*the cascade is predictable

I've used a couple of jquery plugins that inexcusably defined styles for tag elements (not classes, not ids but the actual blummin' tags); so if you do 'hide' the styles, please use classes with a prefix/suffix related to your plugin to avoid clashes.