text:
Q: c++11 construct an object for a caller I have some Foo struct that requires knowledge of some other object's state to be initialized, so I make a factory method for it:
struct Foo {
  Foo(int x) : x_(x) {}

  int x_;
};

struct FooFactory {
  Foo MakeFoo() {
    return Foo(++counter);
  }

  int counter = 0;
};

So while callers could just do Foo(++factory.counter), it's cleaner to be able to just say factory.MakeFoo().
But this code requires copying, and say we want to avoid that. We can use a move constructor instead.
struct Foo {
  Foo(int x) : x_(x) {}
  Foo(Foo& foo) = delete;
  Foo(Foo&& foo) : Foo(foo.x_) { foo.x_ = 0; }

  int x_;
};

struct FooFactory {
  Foo MakeFoo() {
    return Foo(++counter);
  }

  int counter = 0;
};

Which works, but still seems like "more" than I want. Something like Foo foo = factory.MakeFoo() still creates a temporary inside of MakeFoo() and then constructs foo via its move constructor.
Is there a way to write this so that MakeFoo constructs directly into what it's being assigned to?

A: Yes, using braced-init-list return for direct initialization of the target object:
struct FooFactory {
  Foo MakeFoo() {
    return {++counter};
  }
  // ...
};

Note that this will not work if the 1-argument constructor of Foo is explicit.

6.6.3 [stmt.return]:
[...] A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list. [...]

A: While I would not suggest it, a macro is a valid solution:
#define MAKE_FOO() Foo(++factory.counter)

or for initialization of class members or locals:
#define INIT_FOO(x) x(++factory.counter)


text:
Q: PHP copying and deleting file and deleting record from database This code runs when a user hits a delete button on my form. I am trying to copy a file, $picfile, from "/pics/" to "/pics/deletedrecordpics/" and then delete the orginal. Finally, delete the record from the database. Deleting the record from the databse works, but copying the file and deleting the original does nothing. There are no errors in the error log, so I am really confused as to why this code isn't running as I think it should.
   $sql = ("select picfile,title,author from $table where id=$delete");
   $file=mysql_query($sql);
   $resrow = mysql_fetch_row($file);
   $picfile = $resrow[0];
   $title = $resrow[1];
   $author = $resrow[2];
   copy("pics/".$picfile,"pics/deletedrecordpics/".$author." - ".$title." - ".$picfile);
   unlink("pics/".$picfile);
   $sql = ("DELETE FROM $table WHERE id=$delete");
   $result = mysql_query($sql);

A: To make sure unlink should work check if your permissions are set correctly, and if unlink is available on the server installation.
Copy might not be working if "/deletedrecordpics" is a non existing directory, not created yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The system cannot find the file specified when using the command "meteor npm install" > botfront@0.25.0-rc.1 postinstall c:\botfront\botfront
> copy -R node_modules/semantic-ui-css/themes/default/assets/fonts ./public/ && copy -R node_modules/semantic-ui-css/themes/default/assets/fonts ./client/

The system cannot find the file specified.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! botfront@0.25.0-rc.1 postinstall: `copy -R node_modules/semantic-ui-css/themes/default/assets/fonts ./public/ && copy -R node_modules/semantic-ui-css/themes/default/assets/fonts ./client/`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the botfront@0.25.0-rc.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

This is the error i am getting


text:
Q: Is there any command to execute SQL and cut a last words in row of database? I'm importing a database to DB Browser SQLite and need to execute SQL and cut a last words include '-' as in red circle for all rows under 'slug' in database.

Is there any command to do these?
Thanks

A: The ending strings all look like they are the same length.  If so, you can do:
select substr(slug, 1, length(slug) - <n>)

where <n> is the length of the string to be removed.

A:
Is there any command to execute SQL and cut a last words in row of
  database?

In Short NO.
However, you could extract the last word, but it would be cumbersome assuming there are no further specific regard word, such as it's length.
It would probably be far more productive to design the database with it's intended use taken into consideration.
For example the following would extract the last word with the following assumptions/conditions/constraints :-

*

*The last word is at least 1 character in length and less than 30 characters in length.

*There is just the one separator character, namely -.

:-
SELECT *,
    CASE
        WHEN instr(substr(slug,length(slug) -2),'-') > 0
            THEN substr(slug,length(slug)-1)
        WHEN instr(substr(slug,length(slug) -3),'-') > 0
            THEN substr(slug,length(slug)-3)
        WHEN instr(substr(slug,length(slug) -4),'-') > 0
            THEN substr(slug,length(slug)-4)
        WHEN instr(substr(slug,length(slug) -5),'-') > 0
            THEN substr(slug,length(slug)-4)
        WHEN instr(substr(slug,length(slug) -6),'-') > 0
            THEN substr(slug,length(slug)-5)
        WHEN instr(substr(slug,length(slug) -7),'-') > 0
            THEN substr(slug,length(slug)-6)
        WHEN instr(substr(slug,length(slug) -8),'-') > 0
            THEN substr(slug,length(slug)-7)
        WHEN instr(substr(slug,length(slug) -9),'-') > 0
            THEN substr(slug,length(slug)-8)
        WHEN instr(substr(slug,length(slug) -10),'-') > 0
            THEN substr(slug,length(slug)-9)
        WHEN instr(substr(slug,length(slug) -11),'-') > 0
            THEN substr(slug,length(slug)-10)
        WHEN instr(substr(slug,length(slug) -12),'-') > 0
            THEN substr(slug,length(slug)-11)
        WHEN instr(substr(slug,length(slug) -13),'-') > 0
            THEN substr(slug,length(slug)-12)
        WHEN instr(substr(slug,length(slug) -14),'-') > 0
            THEN substr(slug,length(slug)-13)
        WHEN instr(substr(slug,length(slug) -15),'-') > 0
            THEN substr(slug,length(slug)-14)
        WHEN instr(substr(slug,length(slug) -16),'-') > 0
            THEN substr(slug,length(slug)-15)
        WHEN instr(substr(slug,length(slug) -17),'-') > 0
            THEN substr(slug,length(slug)-16)
        WHEN instr(substr(slug,length(slug) -18),'-') > 0
            THEN substr(slug,length(slug)-17)
        WHEN instr(substr(slug,length(slug) -19),'-') > 0
            THEN substr(slug,length(slug)-18)
        WHEN instr(substr(slug,length(slug) -20),'-') > 0
            THEN substr(slug,length(slug)-19)
        WHEN instr(substr(slug,length(slug) -21),'-') > 0
            THEN substr(slug,length(slug)-20)
        WHEN instr(substr(slug,length(slug) -22),'-') > 0
            THEN substr(slug,length(slug)-21)
        WHEN instr(substr(slug,length(slug) -23),'-') > 0
            THEN substr(slug,length(slug)-22)
        WHEN instr(substr(slug,length(slug) -24),'-') > 0
            THEN substr(slug,length(slug)-23)
        WHEN instr(substr(slug,length(slug) -25),'-') > 0
            THEN substr(slug,length(slug)-24)
        WHEN instr(substr(slug,length(slug) -26),'-') > 0
            THEN substr(slug,length(slug)-25)
        WHEN instr(substr(slug,length(slug) -27),'-') > 0
            THEN substr(slug,length(slug)-26)
        WHEN instr(substr(slug,length(slug) -28),'-') > 0
            THEN substr(slug,length(slug)-27)
        WHEN instr(substr(slug,length(slug) -29),'-') > 0
            THEN substr(slug,length(slug)-28)
        WHEN instr(substr(slug,length(slug) -30),'-') > 0
            THEN substr(slug,length(slug)-29)
        ELSE 'ooops not found'
    END AS lastword
FROM mytable;

*

*The above could be shorter accordingly if the minimum length of the last word were greater than 1 and/or the maximum length is less than 30

*the above will output all columns of the table plus a new one named lastword
For example if the input table were (data is different as I wasn't going to try copying from a screenshot, nor try to count to see if the last words were the same length):-

The result from the above would be :-

A: select SUBSTRING_INDEX(slug,"-", -1) from xxx.


text:
Q: Strongly typed views is it possible to pass derived types where base types are expected to strongly typed views?
I.e

*

*Products/List

*News/List

where "list" view Inherits System.Web.Mvc.ViewPage<Model<BaseList>>
controller renders view i.e View("List", ProductsList)

edited
return View("List", new Model<ProductsList>());
Model<T> where T : IMyList
ProductsList : BaseList
NewsList : BaseList
BaseList : IMyList

where ProductsList & NewsList : BaseList
compiles fine but get a runtime error about differing model types.
If this not possible what is the best way to accomplish this rather than creating n no of views ?

A: I think (but am not sure) this has to do with Covariance.
How I'm doing this is create a strongly typed viewData like for example this:
public class YourViewData: System.Web.Mvc.ViewDataDictionary
{
    public IMyList TheList { get; set; }
}

You can then make a ViewPage that you call like
return View("List", new YourViewData(){TheList = new ProductList(){abunchOfItems});

Disclaimer: All freehand code

A: Your question is a little unclear, but I guess it has to do with you having an IList<Base> in your model and you want to pass an IList<Derived>. This is not possible, but in C#4 you can pass an IEnumerable<Derived> instead of an IEnumerable<Base>.


text:
Q: print in console all the function which is being executed in javascript I am creating AngularJS Javascript application in which i have 500/600  function in a single Directive,
Many functions are Inter connected with each other,
flow starts from the On load Event,
I want to know when i run the project,
which functions are being called on Onload Event
and i want to print the same on console,

I google it but i am not able to get anything,

is there any way to find out the functions which is being executed?

A: You can wrap all your functions into "log wrapper":
var self = this;
function LogWrapper(action){
    return function(){
        console.log(action.name);
        return action.apply(self, arguments);
    }
}

//usage:
function ActualFunctionInner(arg1, arg2){
    //some logic
}
var ActualFunction = LogWrapper(ActualFunctionInner);
var result = ActualFunction(1, 2);//console: ActualFunctionInner

Second solution is via Proxy:
let handler = {
       get(target, propKey) {
            var inner = target[propKey];
            return function () {
                console.log(inner.name);
                return inner.apply(this, arguments);
            };
        }
    };
var loggedSelf = new Proxy(self, handler);
var result = loggedSelf.ActualFunction(1, 2);//console: ActualFunction

A: Call console.trace('calling on-load') to find stack-trace on on-load function. It would be better to call trace on the last function you expect to be executed to find all other function which has been called before.


text:
Q: Even or Odd? Python in JES Program Here is my code, I am having trouble getting the last IF statement to work properly, I want it to print only when the answer is not even or odd, but it prints almost every time. how should i fix it?
def evenOdd(x):
 for x in range (1, 6):
  num= random.randrange(1,101)
  ans=raw_input("Is" + str(num) + "Odd or Even?")
  if (num % 2 == 0 and ans=="even") or (num % 2 == 1 and ans == "odd"):
    print "correct"
  if (num % 2 == 0 and ans=="odd") or (num % 2==1 and ans == "even"):
    print "incorrect"
  if (num % 2 ==0 or num % 2 == 1 and ans != "odd" or ans != "even"):
    print "Please answer with Even or Odd"

A: The problem is that in your last if, you're checking each equality individually instead of as groups.
You need to have them grouped as logical groupings. Also, I don't know why this is a function with an input that you never use. This will work for you:
import random
for x in range(1, 6):
    num = random.randrange(1, 101)
    ans = input("Is" + str(num) + "Odd or Even?")
    if (num % 2 == 0 and ans == "even") or (num % 2 == 1 and ans == "odd"):
        print("correct")
    if (num % 2 == 0 and ans == "odd") or (num % 2 == 1 and ans == "even"):
        print("incorrect")
    if (ans != "odd" or ans != "even"):
        print("Please answer with Even or Odd")

The change in the last line is because you don't actually need to check if the number is odd or even, just if the user responded with something other than 'odd' or 'even'.


text:
Q: Notation question from differential geometry and PDE Let Greek indices denote indices that range over $0,1,\dots,d$. I'm looking at $\mathbb R^d \times \mathbb R$ (here I'm looking at the wave equation, so there are space and time indices). Let $g$ be a function. What do the notations $\partial^\alpha g \partial_\alpha g$ and $\partial_\beta g\partial^\beta g$ mean and how are they different? I know that the repeated indices means that you are summing over all values of the indices, so $\partial^\alpha g \partial_\alpha g = \sum_{\alpha=0}^d \partial^\alpha g \partial_\alpha g$ and similarly $\partial_\beta g\partial^\beta g = \sum_{\beta=0}^d \partial_\beta g\partial^\beta g$. But what is the difference between these two? It has something to do with the Minkowski metric.
One of these is probably $-g_t^2 + |\nabla g|^2$, but what is the other one?

A: Basically $\partial^\beta$ are the components of the dual vector to $\partial_\beta$. In Minkowski space the sum $\partial_\beta g\partial^\beta g$ is indeed $-g_t^2 + |\nabla g|^2$.
And because $\alpha$ and $\beta$ are dummy variables the two sums $\partial_\beta g\partial^\beta g$ and $\partial^\alpha g\partial_\alpha g$ are the same, the product of functions is commutative.
When we talk about the dual of $\partial_\beta$ we mean as follows:
Let's say that we are given a smooth manifold of dimension n, if we look at the tangent space of a point p in the manifold we can prove that it is isomorphic to the derivation space which is spanned by $\partial_\beta$ therefore we can treat the tangent space as the vector space spanned by $\partial_\beta$ which has dimension n.
For this vector space we can define the dual space as in linear algebra which is spanned by $\partial^\beta$ which satisfy $\partial^\alpha(\partial_\beta) = \delta^\alpha{}_\beta$.
If you have a metric g (or a pseudo metric as in general relativity), which means the tangent space is an inner product space, then the components of dual vectors are related by the formula:
$$v_\alpha=g_{\alpha\beta} v^\beta, v^\alpha=g^{\alpha\beta} v_\beta$$
where subscript components are for the dual vector and superscript for the vector in the tangent space.


text:
Q: C# passing multiple oracle PL\SQL blocks gets "Encountered the symbol / " I'm trying to pass the oracle a PL\SQL script consists of a multiple blocks (begin/end).
The following example code works on SqlDev, but not with C#.
BEGIN
  DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE()) || ' Block1');
END;
/

BEGIN
   DBMS_OUTPUT.put_line(TO_CHAR(SYSDATE()) || ' Block2');
END;

C# code:

var str = @"
begin
    DBMS_OUTPUT.put_line(TO_CHAR(SYSDATE()) || ' Block1');
end;
/
begin
    DBMS_OUTPUT.put_line(TO_CHAR(SYSDATE()) || ' Block2');
end;
";
str = str.Replace(Environment.NewLine, "\n");
ExecuteNonQueryThis(str2)

The error I get:
ORA-06550: line 5, column 1: PLS-00103: Encountered the symbol "/"

Is it even possible to execute a multi-block-script of Oracle via the C#?

A: just wrap it into one begin end
var str = @"
begin

begin
    DBMS_OUTPUT.put_line(TO_CHAR(SYSDATE()) || ' Block1');
end;

begin
    DBMS_OUTPUT.put_line(TO_CHAR(SYSDATE()) || ' Block2');
end;

end;";


text:
Q: sites are refusing to connect when I window.location them So I have a google site that I use for html hosting and I want to make a button that replaces the current window with a search window. So I do the normal routine:
<button onclick="doThis();">🔎</button>
<script>
function doThis(){
  window.location="https://sites.google.com/example/search";
}
</script>

It replaces the window but just says "sites.google.com refused to connect".
Anyone know what's going on?

A: Try to use
window.location.assign()
<script>
function doThis(){
  window.location.assign("https://sites.google.com/example/search");
}
</script>

And "https://sites.google.com/example/search" does not exist.
If you want to go to the search page, use: "https://www.google.com/"
If you want to use a goodle search engine for your website, you have to do something like this:
Passing html form values to google search query


text:
Q: How can I work against two different versions of a web service? My project is a consumer for a 3rd party web service (old school web service vs. WCF service), and it has two versions, the "sandbox" (staging), and prod services. The APIs on these services are almost identical, and I am looking for a way to cleanly switch between the two versions, preferably without using conditional compilation.
I instinctively rushed off and extracted an interface from the client generated by Visual Studio's "Add web reference", i.e. AgentImport but that class is not partial, so I can't make it derive from the interface, or from any other superclass. I already have the creation of AgentImport instances nicely encapsulated in an abstract base for all my clients of AgentImport, but without using more risky compiler directives, how can I switch between v1 and v2 of AgentImport?
Some code:
using Clients.PrivateProperty.AgencyServicesApiService;

namespace Client.PrivateProperty
{
    public abstract class PrivPropFacilityBase
    {
        protected static AgentImport Client;

        protected PrivPropFacilityBase()
        {
            Client = new AgentImport();
            Client.Timeout = 10000;
        }

        protected virtual AgentImport GetClient()
        {
            return new AgentImport();
        }
    }
}

I have tried adding service references instead of web references, as advised in comments below, to at least get access to partial classes, but when I add the first service reference, for the production service, and extract an interface from the auto-generated SOAP client, i.e. IAsapiClient, that interface references objects declared in other auto-generated classes, in the same namespace as the client, e.g. SecurityToken:
void UpdateUniqueAgentID(string PrivatePropertyAgentId, string AgentId, AgencyServicesApiService.SecurityToken Token);

If I add the second service reference, for the staging service, that second auto-generated SOAP client references objects in its own namespace, e.g. now it uses AgencyServicesApiSandbox.SecurityToken, so my compiler tells me that it doesn't implement the interface I extracted the first time. I am then left with the messy business of having to extract an new interface for each object that the main interface, IAsapiClient, references, so that this main interface only uses the extracted contracts, not actual class names.
In pursuing the above< I have reached the conclusion that my only feasible, and lowest risk, way forward is to use two client projects, one specifically for the production service, and one for the staging service. Then, at execution time, I only need to worry about dynamically choosing between two well known, i.e. not auto-generated, client objects.


text:
Q: Program feedback: named loop index and reference to constant data I had a class assignment that the teacher took off points for a lot of things that I agree with, but a couple of them I'm not so sure about.
"I am not a fan of naming variables like i, when in fact the counter represents a real thing, a port number:"
"It would be better to call it something like portNum, or the like."
In response to the following lines:
for(int i = 1; i <= boat.getLastPort(); ++i){
    boat.load();
    boat.move(i);
    boat.unload();
}

My first question is, is this sound advice, or not even worthwhile? I rarely see a named loop variable. I thought most people would instantly know what's happening in a situation like this one (in the context of the rest of the program).

Second and last feedback:
"First, method names need to start with lowercase letters, not uppercase. This is a very strong convention in OOP.  But worse, there is no reason to pass in the range value by reference.  The requested value is returned, which is how methods usually work with each other." --- "...No program wants to call a class method and pass in anything by reference:  you would never trust a class with your program variables. Use pass-by-value in methods."
This quote refers to this member function:
int FerryBoat::Rand(const int& range)
{
    return rand() % (range+1);
}

The member function was required for the assignment, otherwise I would have just made a macro to do it outside of the class or something. The instructions didn't specify a name so I just named it after the library function, but I guess I should have named it random so it wouldn't have had a capital first letter.
Anyway my second question is:
If a function takes a reference to const data (const variable sounds oxymoronic), why wouldn't you trust it? Can't it not alter the data because of constness?

A: I would suck it up and move on :-) Even if your teacher is borderline psycho, your job is to pass. Once you're out of school, you can follow your own guidelines if they're better (subject to company rules and regulations of course).
I have to agree with the first sentiment since boat.move(portNum) conveys more information then boat.move(i).
Even better would be boat.moveTo(portNum) or even boat.moveToPortNumber(i).
Probably not too bad if those three lines are all there is but it doesn't cost much to do it "right" even for that small sample. Given how much time people spend maintaining code, the more readable it is, the better.
The second one, I think your teacher has concentrated on the wrong thing. It's not whether it can be corrupted, it's that there's absolutely no point and no advantage to passing an int by reference unless you want to modify it in the function.
References are good in C++ to avoid the C problems encountered when having to emulate pass-by-reference with pointers and to minimise copying of large structures. In fact, I hope ISO adds them to the next iteration. But, if it's a variable that's cheap to copy (like an int) and you don't want to change the variable and have it reflected back to the caller, references are a waste of time.
I very much disagree that method names need to start with lower-case letters. While this is a common convention (one I actually use myself), it's not a requirement of OOP. The code doesn't suddenly become less object-oriented because your method is called IsTeacherLoony() rather than isTeacherLoony().


text:
Q: Composite function is bijective Suppose $f : X → Y$ and $g : Y → Z$ are functions. If $g ◦ f$ is bijective and $f$ is surjective. Then what would $g$ be? Would it be bijective or invective?
I know that $g ◦ f$ is injective then $f$ is injective and that if $g ◦ f$ is surjective then $g$ is surjective. And I know how to prove these but how would I show if $g ◦ f$ is bijective and if $f$ is surjective what $g$ would be?

A: Hint:

*

*If $g$ isn't surjective, can $g\circ f$ be surjective?

*If $g$ isn't injective, can $g\circ f$ be injective? (Here you need to use that $f$ it's surjective.)


text:
Q: How to cast a generic parameter? Here's what I am trying to write:
public void Foo<T>(T parameter) {
  otherObject.Bar<T>(parameter);
}

The signature of the Bar() method is:
public void Bar<T>(T parameter) where T: class

So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
public void Foo<T>(T parameter) where T: class {
  otherObject.Bar<T>(parameter);
}

because Foo is implementing a method defined in an external interface.  Question is:
Can I somehow transpose the T within the method Foo before calling Bar.  (Note, I can be sure that T always will be a class  -  I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing.

A: You can use the dynamic keyword like this:
public void Foo<T>(T parameter)
{
    dynamic p = parameter

    otherObject.Bar(p);
}

What's happening is that the resolution of the call to otherObject.Bar is being made at run-time, because one of the parameters has a type of dynamic.  Assuming that T is a reference type, the resolution will succeed.
Granted, this ultimately uses reflection (as you've indicated), but the syntax is probably better than what you're using.
Of course, this will give you a run-time error in the event that T is not a class.

A: public void Foo<T>(T parameter)
{
    otherObject.Bar<object>(parameter);
}

A: Here's a slightly different take on casperOne's answer, using implicit interface implementation:
public void Foo<T>(T parameter) where T: class {
    otherObject.Bar<T>(parameter);
}

void IFoo.Foo<T>(T parameter){
    Foo((dynamic)parameter);
}

This allows you to include the constraint on anything that knows what specific object type they're calling .Foo on at compile time, while still allowing you to implement the IFoo interface.

A: If you are the owner of otherObject.Bar, could you not just remove the class constraint? of that method.  Or create a new similar method without the constraint?
casperOne. I am not sure your answer is correct, as you have the class constraint on your Foo method. The question stated that this was not possible as Foo was an implementation of an external interface. For instance, the code below does not work.
public void Foo<T>(T param)
    {
        dynamic xx = param;

        this.Bar(param);
    }

    private void Bar<T>(T param) where T: class {

    }

And shows up as an error.


text:
Q: Installation procedure for cassandra, Datastax Enterprise and community and Opscenter in Ubuntu Hi I'm a Java programmer and new to Cassandra, as per my project requirement I need to install in Ubuntu machine and start playing with it. By reviewing lot of websites I got a conclusion that, to setup Cassandra need to install cassandra, Datastax Enterprise and community and Opscenter.
But I don't know which s/w need to install first and what is the configuration I need to do with that. So please some one can guide me directly or please suggest me good websites for simple procedure into setup Cassandra in Ubuntu machine.

A: For Installing Datastax Community follow this instruction set
And for Datastax Enterprise, simply follow this


text:
Q: does HTTP/2 work in CORS request? index.html is loaded from server https://foo.com, which supports http 1.1 only, but with proper CORS header, an XMLHttpRequest can be sent out to a 2nd server https://bar.com, which supports http/2.
Will my application be able to leverage the http/2 features between the browser and server https://bar.com?

A: Yes, it's a completely separate connection but I doubt it will matter as not sure what "features" you hope to benefit from?
Nearly all of the features and advantages of HTTP/2 are designed to improve performance of many connections to the same domain:

*

*Proper Multiplexing allows you to make many requests over a single connection while removing the head of line blocking seen under HTTP/1.1.

*Prioritisation looks to ensure the multiplexed connection is used efficiently.

*Header Compression allows similar HTTP Headers to be sent over multiple requests without a performance penalty (e.g. large numbers of cookies being sent with every request).

*Binary format is more a technical change to make writing software that parses HTTP requests (e.g. webservers and web browsers) more robust - especially relevant when multiplexing.

So unless your website is making huge numbers of XMLHttpRequests to the same host those features won't really benefit you that much. The overheads of HTTP/2 coupled with the implementations being fairly new and so probably not 100% optimal yet, will often mean that HTTP/2 could actually be slower for small numbers of requests.
That only leaves Server Push. This can only be sent in response to an original request, so is less beneficial for XMLHttpRequests in most cases. Additionally there seems to be some confusion as to how to handle pushed XMLHttpRequests.

A: Yes, your application will be able to leverage the HTTP/2 features provided by bar.com.
This is also why CDNs providers are so interested in HTTP/2.
XMLHttpRequest is no different: the browser still makes a HTTP request (whether it's to a CDN or via XMLHttpRequest), and if bar.com supports HTTP/2, the browser will make the call using HTTP/2.


text:
Q: AppSetting Data is visiblae in Controller but does not pass to View Fairly new to ASP.NET CORE so this could be a rookie mistake but it has be baffled!
I have been working on integrating a plugin for Square with some existing code, and when I write the data to console it's there but as soon as it's passed to the view I get a nullable error.
Controller
public IActionResult AccountPayments()
    {
        var appId = _config.GetValue<string>("AppSettings:ApplicationId");
        var locId = _config.GetValue<string>("AppSettings:LocationId");
        var env = _config.GetValue<string>("AppSettings:Environment");

        ModelState.Clear();

        var acc = new AccountPayment();
        acc.ApplicationId = appId;
        acc.LocationId = locId;
        acc.PaymentFormUrl = env;

        Console.WriteLine(acc.LocationId + " " + locId + " " + env);
        return View(acc);
     }

View
    @page
@model AccountPayment

@section Scripts {
    <!-- link to the SqPaymentForm library -->
    <script type="text/javascript" src="@Model.PaymentFormUrl"></script>
    <script type="text/javascript">
        window.applicationId = "@Model.ApplicationId";
        window.locationId = "@Model.LocationId";
    </script>
    <!-- link to the local SqPaymentForm initialization -->
    <script type="text/javascript" src="~/js/sq-payment-form.js"></script>
}

Model
namespace WebInvoice.Pages
{
    public class AccountPayment : PageModel
    {
        public string PaymentFormUrl { get; set; }
        public string ApplicationId { get; set; }
        public string LocationId { get; set; }

    }

}

When I remove the @model from the view it works OK.
When I check the console it displays the information.
When I run the application the view above returns the below error.
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
Eternally grateful to anyone who can shed some light on the issue.

A: If you want to return View,don't add @page in your view,@page means it's a razor page rather than razor view.And also PageModel is used in razor page.You can refer to the official doc about razor page.Here is a demo about mvc:
Model:
public class AccountPayment
    {
        public string PaymentFormUrl { get; set; }
        public string ApplicationId { get; set; }
        public string LocationId { get; set; }

    }

View(AccountPayment.cshtml):
@model AccountPayment

@section Scripts {
    <!-- link to the SqPaymentForm library -->
    <script type="text/javascript" src="@Model.PaymentFormUrl"></script>
    <script type="text/javascript">
        window.applicationId = "@Model.ApplicationId";
        window.locationId = "@Model.LocationId";
    </script>
    <!-- link to the local SqPaymentForm initialization -->
    <script type="text/javascript" src="~/js/sq-payment-form.js"></script>
}

Controller:
public IActionResult AccountPayments()
    {
        var appId = _config.GetValue<string>("AppSettings:ApplicationId");
        var locId = _config.GetValue<string>("AppSettings:LocationId");
        var env = _config.GetValue<string>("AppSettings:Environment");

        ModelState.Clear();

        var acc = new AccountPayment();
        acc.ApplicationId = appId;
        acc.LocationId = locId;
        acc.PaymentFormUrl = env;

        Console.WriteLine(acc.LocationId + " " + locId + " " + env);
        return View(acc);
     }

appsettings.json:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "ApplicationId": "123",
    "LocationId": "456",
    "Environment": "Development"
  }
}

result:


text:
Q: How do I get android system accent color to put it in xml (I mean non-programmatically, I'm trying to mod already existing app, so I can't add code) I've tried
@*android:color/accent_device_default_light

And
@android:color/accent_device_default_700

I don't have idea how to get it.


text:
Q: ERROR 1060 (42S21): Duplicate column name 'eid' I am trying to figure out why I'm getting a duplicate column name in this query. I feel like I am properly prefixing my search terms and shouldn't be getting this error. Please advise.
Model
Emp(eid:integer, ename:varchar, age:integer, salary:integer)
Works(did:integer, eid:integer)
Dept(did:integer, managerid:integer) //managerid is foreign key to eid

Query
CREATE VIEW Manager AS
SELECT e.eid, e.ename, e2.eid, e2.ename
FROM Emp AS e,
    Dept AS d
        LEFT JOIN Emp AS e2 ON d.managerid = e2.eid;

A: Try some ALIAS in your fields. See Below:
CREATE VIEW Manager AS
SELECT
      e.eid AS eid1,
      e.ename AS ename1,
      e2.eid AS eid2,
      e2.ename AS ename2
FROM Emp AS e,
    Dept AS d
LEFT JOIN Emp AS e2 ON d.managerid = e2.eid2;


text:
Q: Approximation of an integral involving x and 1-x I am looking for an approximation of the integral
$F(k,R)=\displaystyle\int_0^1\frac{\mathrm{d}x}{(Rx)^{-2}+(1-x)^{-k}}$,
that is valid to within 1% over the range $2<k<10$ and $R>1$. Is there a standard approach to problems like this?
This integral came about in a research problem where I am trying to smoothly connect the functions $x^{2}$ and $(1-x)^{k}$. If someone can provide an approximation (or a closed form solution!) I'll gladly acknowledge them in the research paper this result is needed for.

A: The final solution was to use Gauss-Laguerre quadrature, with an order 10 scheme being sufficient to achieve the accuracy I required.


text:
Q: Is there a way of telling whether GUICtrlCreateInput has text in it? I am writing a GUI in AUTOIT that has a lot of GUICtrlCreateInputs.
Is there a way to tell if the user has entered text into a "GUICtrlCreateInput"
I tried the StringCompare and StringLen functions but they didn't help.
I "StringCompare"ed with ""
StringLen returned 9 and sometimes 10 in cases where I hadn't typed anything into the inputs.

A: If StringStripWS(GUICtrlRead($inputCtrl), 8)  "" Then
       ; do something
EndIf


text:
Q: How to replace only the selected text from SWT with new Text I have an SWT Text widget. I have text inside the widget say for example "B for Bat" and I select(through mouse and key board) a part of it i.e. "Bat" and trigger an event through a button wherein i have my code to replace with "Ball" . So my final output would be "B for Ball".
How do I achieve this. Please help me

A: This will solve your problem:
public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout(SWT.VERTICAL));
    shell.setText("StackOverflow");

    final Text text = new Text(shell, SWT.BORDER);

    Button button = new Button(shell, SWT.PUSH);
    button.setText("Replace");
    button.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event arg0)
        {
            String content = text.getText();
            Point selection = text.getSelection();

            /* Get the first non-selected part, add "Ball" and get the second non-selected part */
            content = content.substring(0, selection.x) + "Ball" + content.substring(selection.y, content.length());

            text.setText(content);
        }
    });

    shell.pack();
    shell.setSize(400,shell.getSize().y);
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

The crucial part is using Text#getSelection(), which will return a Point whose x coordinate is the start of the selection and the y coordinate is the end of the selection.
You might want to add a check for empty selections.

BTW: Please always post what you have tried yourself...


text:
Q: Restricting/Blocking iPhone access with a passcode for workers? I would like to implement an app that is capable of doing the following when a worker doesn't return the iPhone for 45 days:

*

*Based on IMEI or a unique app client id the phone should be disabled with a random passcode, by bypassing the faceid or touch id.

*It should not be enabled until allowed from backend admin end.

*The iOS should not be overwritten while the app is enabled.

I would like to seek advice if this software exists?

A: Apps can not do this on iOS due to how the OS restricts an app to the sandbox. However, this is precisely what an MDM does.
You need no app whatsoever on the iOS side - just a profile and an identity to get Apple to recognize your authority and for each device owner to accept your MDM profile.

*

*https://support.apple.com/en-us/HT202804
If you are a company that owns the devices - you will want to use Apple Business Manager and then work with Apple or someone else to shop for and set up the best MDM for your size. There are some great for 5 devices and some great for 50,000 devices.

*

*https://support.apple.com/business
If you are a service provider, you also can learn about MDM and then offer it to clients. If you're a developer, there are open-source MDM frameworks so you can learn if you want to build a better wheel.

*

*https://micromdm.io/
Most of the professionals that manage mac and iOS devices congregate under the MacAdmin community, so reach out if you need help managing your devices or are just a highly motivated learner.

*

*https://www.macadmins.org/


text:
Q: Question about a dimension in this IC package drawing this is the first time I'm making a PCB layout, so I'm not too familiar with datasheets. The picture below shows a diagram for an IC I'm using. The datasheet says all dimensions are in mm.  However, near the bottom you can see a number that has 0.25 with a circled M, followed by an A and C. What do these letters mean? And does that mean the hole size is 0.25 mm for a pin? I'm really confused because I know it can't be 0.25mm.
Is that in mils instead?

A: You can read more about those symbols in this Drafting Manual but those particular symbols are related to the tolerance rather than size:

It seems to me the seven pins have a diameter of 0.6 mm +/- 0.1mm with a spacing of 1.27 mm between them. It's quite common for dimensions to be prefixed by "7 x" etc to indicate the same dimension applies to multiple items.


text:
Q: Timeseries Objects Duplicate Entries I am working on a time series NoSQL database where I need to stamp values on an hourly basis. However, some times the values might stay the same. If the values, which are coming from a third party API, are the same, should I store them as duplicates or wait until the values are updated? In the first case, it results in many duplicates but I am not sure if it's the right approach? Any thoughts?

A: If values stays the same then it is not a duplicate entry as timestamp has changed.

A: If the history of value changes is important, I would store this information in additional columns. It's what NoSQL is for, right?

*

*received_time

*update_time

*modified-time

*repeat-counter

*value


text:
Q: XMLHttpRequest asynchronous read, how not to use anonymous function? After searching Google for examples, all the examples I found use anonymous functions, like below. But I would like to avoid it because it makes the code complicated.
var xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

If I want to do like this, how can I pass the request or response?
function startRequest()
{
    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = "https://developer.mozilla.org/";

    xhr.open(method, url, true);
    xhr.onreadystatechange = myhandler;
    xhr.send();
}

function myhandler()
{
  //how to get xhr here?
  if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200)
  {
    console.log(xhr.responseText);
  }
}

I am more familiar with statically typed languages, so JavaScript is confusing. I tried to look the signature (input parameters) of onreadystatechange, but the documentation pages did not mention it. It seems that the documentations for dynamically typed languages (Python, PHP) tend to not describe the input parameters formally, so that I would have to guess what types of parameters the methods take.
It has no parameters, and should I use global variable to pass the request and response to myhandler? Is there a better way?

A: You can pass the xhr object to the handler, which contains the response objects.
function startRequest()
{
    var xhr = new XMLHttpRequest(),
        method = "GET",
        url = "https://stackoverflow.com/questions/45887959/xmlhttprequest-asynchronous-read-how-not-to-use-anonymous-function";

    xhr.open(method, url, true);
    xhr.onreadystatechange = myhandler(xhr);
    xhr.send();

}

function myhandler(xhr)
{
  //how to get xhr here?
  if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200)
  {
    console.log(xhr.responseText);
  }else if(xhr.status===0){
      console.log(xhr.responseText);
  }
}

startRequest();


text:
Q: Remove unnecessary url from scrapy import scrapy
from scrapy.http import Request

class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['https://www.ifep.ro/justice/lawyers/lawyerspanel.aspx']
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1,
        'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
        }

    def parse(self, response):
        books = response.xpath("//div[@class='list-group']//@href").extract()
        for book in books:
            url = response.urljoin(book)
            print(url)

I want to remove these unnecessary url from the link the website is https://www.ifep.ro/justice/lawyers/lawyerspanel.aspx
http://www.unbr.ro
http://www.inppa.ro
http://www.uniuneanotarilor.ro/
http://www.caav.ro
http://www.executori.ro/
http://www.csm1909.ro
http://www.inm-lex.ro
http://www.just.ro

A: You can apply endswith method  along with continue keyword to remove the desired urls
import scrapy
from scrapy.http import Request

class TestSpider(scrapy.Spider):
    name = 'test'
    start_urls = ['https://www.ifep.ro/justice/lawyers/lawyerspanel.aspx']
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1,
        'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
        }

    def parse(self, response):
        books = response.xpath("//div[@class='list-group']//@href").extract()
        for book in books:
            url = response.urljoin(book)
            if url.endswith('.ro') or url.endswith('.ro/'):
                continue
            print(url)

Output:
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=1091&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159077&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159076&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159075&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159021&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159020&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159019&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=159018&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=21846&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=165927&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=83465&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=47724&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=32097&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=29573&Signature=378270
https://www.ifep.ro/justice/lawyers/LawyerFile.aspx?RecordId=19880&Signature=378270


text:
Q: Cypress tests continuously run XHR posts when visiting localhost (running vue.js) I'm relatively new to cypress, however, whenever I run cy.visit on localhost the XHR requests continuously run. This does not happen if I am visiting a remote URL. Here's the code:
describe('Applicant Login', () => {
  it('focuses input on login box', () => {
    cy.visit('http://localhost:3000/login')
  })
})

Cypress continually runs XHR requests over and over until I stop. I'm running a vue.js app via nuxt.js. Here's the log output:

I have no errors, no request or response info, the continuous requests.
Thanks for the help!

A: Many thanks to Kondasamy Jayaraman. The request is coming from a logrocket plugin trying to reach its service. I hadn't noticed it in the network tab when using the application.
Much appreciation.


text:
Q: Select data from a table to insert/update another similar table I have two tables (in two databases):
create table catalog_product_entity_text
(
    value_id int auto_increment comment 'Value ID'
        primary key,
    attribute_id smallint unsigned default 0 not null comment 'Attribute ID',
    store_id smallint unsigned default 0 not null comment 'Store ID',
    entity_id int unsigned default 0 not null comment 'Entity ID',
    value longtext null comment 'Value',
    constraint CATALOG_PRODUCT_ENTITY_TEXT_ENTITY_ID_ATTRIBUTE_ID_STORE_ID
        unique (entity_id, attribute_id, store_id),
    constraint CATALOG_PRODUCT_ENTITY_TEXT_STORE_ID_STORE_STORE_ID
        foreign key (store_id) references store (store_id)
            on delete cascade,
    constraint CAT_PRD_ENTT_TEXT_ATTR_ID_EAV_ATTR_ATTR_ID
        foreign key (attribute_id) references eav_attribute (attribute_id)
            on delete cascade,
    constraint CAT_PRD_ENTT_TEXT_ENTT_ID_CAT_PRD_ENTT_ENTT_ID
        foreign key (entity_id) references catalog_product_entity (entity_id)
            on delete cascade
)

create table catalog_product_entity_varchar
(
    value_id int auto_increment comment 'Value ID'
        primary key,
    attribute_id smallint unsigned default 0 not null comment 'Attribute ID',
    store_id smallint unsigned default 0 not null comment 'Store ID',
    entity_id int unsigned default 0 not null comment 'Entity ID',
    value varchar(255) null comment 'Value',
    constraint CATALOG_PRODUCT_ENTITY_VARCHAR_ENTITY_ID_ATTRIBUTE_ID_STORE_ID
        unique (entity_id, attribute_id, store_id),
    constraint CATALOG_PRODUCT_ENTITY_VARCHAR_STORE_ID_STORE_STORE_ID
        foreign key (store_id) references store (store_id)
            on delete cascade,
    constraint CAT_PRD_ENTT_VCHR_ATTR_ID_EAV_ATTR_ATTR_ID
        foreign key (attribute_id) references eav_attribute (attribute_id)
            on delete cascade,
    constraint CAT_PRD_ENTT_VCHR_ENTT_ID_CAT_PRD_ENTT_ENTT_ID
        foreign key (entity_id) references catalog_product_entity (entity_id)
            on delete cascade
)

My _text table contains some data that I would like to transfer to the _varchar table, but there's no correlation with the primary keys. The primary key is just auto increment.
Logically the tables are connected by the set (attribute_id, store_id, entity_id).
I would like to perform two actions:

*

*Select all the values from _text table for specific attribute ids, e.g.
select cpet.attribute_id, cpet.store_id, cpet.entity_id, cpet.value
from catalog_product_entity_text cpet
where cpet.attribute_id in
      (<myids>)
  and cpet.value is not null;

Now for each row in the above results I'd like to:

*If there's corresponding (attribute_id, store_id, entity_id) in the _varchar table, update that row.

*If there's no corresponding (attribute_id, store_id, entity_id) in the _varchar table, add a new row with the data from the source row.
If I had a common primary key, I'd use REPLACE INTO, but in this case I don't think it's suitable.
How can I build such a query? It doesn't need to be a single query.

A: Here's how to update the records that exist in catalog_product_entity_varchar and relate to a record in catalog_product_entity_text:
UPDATE catalog_product_entity_varchar cpev
INNER JOIN catalog_product_entity_text cpet
    ON cpet.attribute_id = cpev.attribute_id
    AND cpet.store_id = cpev.store_id
    AND cpet.entity_id = cpev.entity_id
SET cpev.value = cpet.value
WHERE cpet.attribute_id IN (<myids>)
  AND cpet.value IS NOT NULL;

After you do the update, then you can insert what's missing like this:
INSERT INTO catalog_product_entity_varchar (attribute_id, store_id, entity_id, value)
SELECT cpet.attribute_id, cpet.store_id, cpet.entity_id, cpet.value
FROM catalog_product_entity_text cpet
LEFT JOIN catalog_product_entity_varchar cpev
    ON cpet.attribute_id = cpev.attribute_id
    AND cpet.store_id = cpev.store_id
    AND cpet.entity_id = cpev.entity_id
WHERE cpet.attribute_id IN (<myids>)
  AND cpet.value IS NOT NULL
  AND cpev.attribute_id IS NULL; -- This last predicate ensures we only insert new records (i.e. the join didn't match any records in cpev to this record in cpet, if cpev.attribute_id is null here)


text:
Q: SQL input - how to update a reference table when new input? I've got a table where I'm inputting new doses as they arrive.
I want to have a reference table so it doesn't get messy over time for what is being inputted, but am confused about how to write the insert statements to accommodate for this.
The Schema is something like this,
-- Drop table

-- DROP TABLE public.users;

CREATE TABLE users (
    id serial NOT NULL,
    user_id varchar(50) NOT NULL,
    CONSTRAINT users_pkey PRIMARY KEY (user_id)
);

-- Drop table

-- DROP TABLE public.devices;

CREATE TABLE devices (
    id int4 NOT NULL,
    devices varchar NOT NULL,
    CONSTRAINT devices_pk PRIMARY KEY (id)
);
CREATE INDEX devices_id_idx ON devices (id int4_ops);

-- Drop table

-- DROP TABLE public.substances;

CREATE TABLE substances (
    id int4 NOT NULL,
    "input" varchar(255) NOT NULL,
    CONSTRAINT substances_pk PRIMARY KEY (id)
);
CREATE UNIQUE INDEX substances_id_idx ON substances (id int4_ops);

-- Drop table

-- DROP TABLE public.substanceactual;

CREATE TABLE substanceactual (
    id int4 NOT NULL,
    user_id varchar NOT NULL,
    "input" int4 NOT NULL,
    dose float4 NULL,
    device int4 NOT NULL,
    duration float4 NULL,
    timetaken timestamptz NOT NULL,
    "timestamp" timestamptz NOT NULL DEFAULT now(),
    CONSTRAINT substanceactual_pk PRIMARY KEY (id),
    CONSTRAINT substanceactual_fk FOREIGN KEY (user_id) REFERENCES users(user_id),
    CONSTRAINT substanceactual_fk_1 FOREIGN KEY (input) REFERENCES substances(id),
    CONSTRAINT substanceactual_fk_2 FOREIGN KEY (device) REFERENCES devices(id)
);
CREATE INDEX substanceactual_id_idx ON substanceactual USING btree (id);

An example input would be,
INSERT INTO substanceactual (user_id,"input",dose,device,duration)
    VALUES ('xxax',"Dexamphetamine",15.0,1,4.0,'2016-01-25 10:10:10.555555-05:00','2016-01-25 10:10:10.555555-05:00');

How would I make it so when it inserts, it creates a new value, or uses the existing on in the table for substances?

A: I changed a bit your schema for the purpose of simplicity, as other tables are not involved in the insert process. If I understood you correctly, your aim is to compare "input" field.
By using trigger before insert you can check if the row is already presented in your table, if that is the case you would update it will new values; in other case you would insert new row.
All code:
CREATE TABLE substances (
    id int4 NOT NULL,
    "input" varchar(255) NOT NULL,
    CONSTRAINT substances_pk PRIMARY KEY (id)
);

CREATE TABLE substanceactual (
    id int4 NOT NULL,
    user_id varchar NOT NULL,
    "input" int4 not null,
    dose float4 NULL,
    device int4 NOT NULL,
    duration float4 NULL,
    timetaken timestamptz NOT NULL,
    "timestamp" timestamptz NOT NULL DEFAULT now(),
    CONSTRAINT substanceactual_pk PRIMARY KEY (id),
    CONSTRAINT substanceactual_fk_1 FOREIGN KEY (input) REFERENCES substances(id)
);

insert into substances
values
(
    1, 'Dexamphetamine'
)

INSERT INTO substanceactual (id, user_id, input, dose, device, duration, timetaken, timestamp)
VALUES
(
    1,
    'xxax',
    1,
    7.0, -- old
    1,
    2.0, -- old
    '2016-01-10 10:10:10.555555-05:00', -- old
    '2016-01-15 10:10:10.555555-05:00' -- old
);

CREATE OR REPLACE FUNCTION on_before_insert_input()
    RETURNS trigger
    LANGUAGE plpgsql
AS
$$
BEGIN
    --to escape endless recursion
    IF pg_trigger_depth() = 1 THEN

        --if row with the same input exists, it will update it, otherwise it will insert a new one
        IF EXISTS (SELECT 1 FROM substanceactual WHERE input = NEW.input) THEN
                UPDATE substanceactual
                SET
                    --I excluded new.id on purpose, you can update it also if you don't identity set for you id column
                    user_id = NEW.user_id,
                    dose = NEW.dose,
                    device = NEW.device,
                    duration = NEW.duration,
                    timetaken = NEW.timetaken,
                    timestamp = NEW.timestamp
                WHERE input = NEW.input;
        ELSE
                INSERT INTO substanceactual (id, user_id, input, dose, device, duration, timetaken, timestamp)
                VALUES
                (
                    NEW.id,
                    NEW.user_id,
                    NEW.input,
                    NEW.dose,
                    NEW.device,
                    NEW.duration,
                    NEW.timetaken,
                    NEW.timestamp
                );
        END IF;
        RETURN NULL;
    ELSE
        RETURN NEW;
    END IF;
END;
$$;

CREATE OR REPLACE TRIGGER input_trigger BEFORE INSERT ON substanceactual
FOR EACH ROW EXECUTE PROCEDURE on_before_insert_input();

select * from substanceactual;

INSERT INTO substanceactual (id, user_id, input, dose, device, duration, timetaken, timestamp)
VALUES
(
    2,
    'xxax',
    1,
    15, -- new
    1,
    4, -- new
    '2016-01-25 10:10:10.555555-05:00', -- new
    '2016-01-25 10:10:10.555555-05:00' -- new
);

select * from substanceactual;


text:
Q: How to use a C# Object Array as a Property I can use this snippet:
public object Obj
{
    get;
    set;
}

Like this:
public fubar()
{
    ...
    Obj = SomeObject;
}

But cannot seem to use this snippet:
public object[] ObjectAsArray
{
    get;
    set;
}

Like this or any other way I have tried so far:
public fubar()
{
    ...
    Obj[n] = SomeObject;
    //or
    var x = Obj[0] as SomeObject;
    //or other ways...
}

I seem to be missing something here.
Can somebody give a simple example of the correct declaration of a C# property that is of type object[] and consumption thereof?

A: As soon as you change it from Obj to ObjectAsArray it should compile. You'll still need to actually create the array though:
ObjectAsArray = new object[10];
ObjectAsArray[5] = "Hello";

A: You're trying to set Obj[n] before Obj itself is initialized... so, I imagine you're getting a null-reference exception. You need to perform an assignment, like so:
Obj = new Object[];

... and in context:
public fubar()
{

  Obj = new Object[13]{}; // where 13 is the number of elements
  Obj[n] = SomeObject;
}

A: I would suggest adding a private backing field for the object[] property and initialize it - either directly or in the getter.
object[] _objectsAsArray = new object[10];

OR
public object[] ObjectAsArray
{
     get
     {
         if(_objectsAsArray == null)
             _objectsAsArray = new object[10];
         return _objectsAsArray;
     }
     set
     {
        _objectsAsArray = value;
     }
}

The complier is creating a private backing field anyhow so why not be explicit about it.  Also, auto-implemented properties have some drawbacks (serialization, threading, etc).  Doing it the "old-fashioned" way also gives you a nice place to actually create the array.  Of course if you don't need to worry these issues - go ahead and use the auto-implemented property.


text:
Q: How do I remove previous extension<->Program affiliations programatically? I would like to write a batch file which ensures that when a user clicks on a .JNLP file, it opens using javaws.exe (located in program files/java/... you know the drill)
I have written the following batch file:
ASSOC .jnlp=JNLPFILE
IF EXIST "%ProgramFiles% (x86)" (GOTO x86) ELSE (GOTO x64)
:x86
FTYPE JNLPFILE="%ProgramFiles% (x86)\Java\jre7\bin\javaws.exe" "%1"
goto:eof
:x64
FTYPE JNLPFILE="%ProgramFiles%\Java\jre7\bin\javaws.exe" "%1"

I am testing this all in windows 7 64-bit.
This... doesn't work.   Well, that's not entirely accurate.   It modifies the registry correctly, and it adds .jnlp to windows list of Recommended programs to run.  It does exactly what it should.
But it doesn't solve my problem.   See, For testing, I went to Default Programs and associated .jnlp files with Notepad.   And when I try to open .Jnlp files, IT tries to open in notepad, even after my code has run.
If I do an open with on a .jnlp, it gives me  the option to open with Notepad or javaws.exe   If I've run my code with the ASSOC, it adds a SECOND option of javaws.exe
I've tried ASSOC .jnlp="" and FTYPE JNLPFILE=""  To try and clear notepad out, but had no luck.
How do I make my batch file blow away prior settings and assert its dominance on the machine?
EDIT:   Using the answers below, I have added a single command to the beginning of my batch file, which should take care of my problem and make things work correctly.
REG DELETE HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jnlp /f

A: Windows Explorer keeps its own list of file extensions for the user.
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts

To remove programs from this list, delete the program entry from

*

*HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jnlp\OpenWithList

*HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jnlp\OpenWithProgIDs

and set the desired UserChoice Progid in

*

*
  HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.jnlp\UserChoice

Also, note that the OpenWithList and OpenWithProgids can be set at multiple levels.

*

*HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.xyz\OpenWithList

*HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.xyz\OpenWithProgIDs

*HKCR\.xyz\OpenWithList

*HKCR\.xyz\OpenWithProgIDs

*HKCR\SystemFileAssociations\FileType\OpenWithList


text:
Q: How to detect window size and then do something with jquery switch statement i would like to check for the window size with jquery and based on the different resolutions i would like to change the background image. So i was thinking to somehow use the "switch" statement for more cases, but i just don't know how this would look like. This is the basic structure i want but with more options:
if ((screen.width>=1024) && (screen.height>=768)) {
 //do something
}
else {
//do something else
}

Thanks for your help.

A: You should use:
$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

$(window).height();   // returns heightof browser viewport
$(document).height(); // returns height of HTML document

and then you could do:
var width = $(window).width();
var height = $(window).height();

if ((width >= 1024  ) && (height>=768)) {
 //do something
}
else {
//do something else
}

EDIT - i don't think that using a switch  statement is useful in this case. The switch statement is just an alternate way for the if...else notation that in this case i find more useful because you have multiple comparison to do:
if ((width >= 1280) && (height>=1024)) {
 //do something
}
else if ((width >= 1024  ) && (height>=768)){
//do something else
} else if ((width >= 800) && (height>=600)){
//do something else
}else{
//do something else
}

A: The switch statement won't let you do stuff like checking for numbers between certain values, and it won't let you check on multiple variables, either...
So for this particular scenario, I think the best fit is actually just a list of if-elseif statements, like you're already on your way to do.
To do "range checks" in switch is really verbose:
switch(windowWidth) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        //Do something if value is less than or equal to 5
        break;
    case 6:
    case 7:
    case 8:
    case 9:
    case 10:
        //Do something if value is higher than 5 AND less than or equal to 10
        break;
    ...
    ...
}


text:
Q: Is there a way to train a neuronal network (LSTM model) with multiple datasets in order to do time series forecasting? I want to do predictions with a LSTM model, but the dataset isn't a single file, it's composed with multiple files (for example 3 Excels).
I've already checked that if you want to deal with a time series forecasting problem you have to prepare your data like (number of samples, number of time steps, number of features) and it works well if I implement this for a single Excel.
The problem consists in training with the three Excels at the same time, in this case the input tensor for the LSTM layer has the shape: (n_files, n_samples, n_timesteps, n_features), with dim = 4. This doesn't work because LSTM layers only admits input tensors with dim = 3.
My files have the same amount of data. It's collected from a device and the data has 1 value for each minute along the duration of the experiment. All the experiments have the same duration too.
I've tried to concatenate the files in order to have 1, and choosing the batch_size as the number of samples in one Excel (because I can't mix the different experiments) but it doesn't produce a good result (at least as good as the results from predicting with 1 experiment).
def build_model():
  model = keras.Sequential([
    layers.Masking(mask_value = 0.0, input_shape=[1,1]),
    layers.LSTM(50, return_sequences=True),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.Adam(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae','RootMeanSquaredError'])
  return model

model_pred = build_model()
model_pred.fit(Xchopped_train, ychopped_train, batch_size = 252,
               epochs=500, verbose=1)

Where Xchopped_train and ychopped_train are the concatenated data from the 3 Excel.
Another thing I've tried is to train the model within a loop, and changing the Excel:
for i in range(len(Xtrain)):
    model_pred.fit(Xtrain[i], Ytrain[i], epochs=167, verbose=1)

Where Xtrain is (3,252,1,1) and the first index refers to the number of Excel.
And by far this is my best approach but it feels like this isn't a good solution since I don't know what's happening with the NN weights or which loss function is minimizing...
Is there a more efficient way to do this? Thanks!


text:
Q: Inside .each() function jQuery I've got this

        Text Here

        Text Here

        Text Here

Got a jQuery to know wich "span" I've clicked:
$("#results").on('click', 'article .sel', function() {
    var index = $(this).index("#results article .sel");
});

If I would like to change that "span" class, how I could do it?
I thought about doing an .each() function for each "article", but I wouldn't know how to enter the "span" inside the .each() function.
May there is an easier way that I don't know.
Thanks for all.

A: Just use removeClass() and addClass() (or even toggleClass()) to change the class of an element.
$(".sel").on("click", function()
{
    $(this).removeClass("sel").addClass("yournewclass");
});

A: The clicked element is referenced by this so
$("#results").on('click', 'article .sel', function() {
    var index = $(this).index("#results article .sel");
    //to change the class
    $(this).addClass('newclass');//or do something
});


text:
Q: Debug MATLAB functions called from a JAVA program So I have a jar built with the MATLAB Builder JA tool. Is it possible to debug the MATLAB functions from the Java process using the jar file?

A: You can't debug them in the sense of being able to step through the MATLAB code line by line, as you can with MATLAB's own debugger prior to compilation. One of the steps that the MATLAB deployment products take is to encrypt the MATLAB code (so you can preserve your IP when distributing the deployed component). The ability to step through the code in a debugger after deployment would defeat the purpose of that.
Typically you would want to debug in MATLAB before deployment, or perhaps spread some disp  statements around your code in a way that can be turned off after deployment (sorry if that advice doesn't help you now that have a .jar file).


text:
Q: How to decode/encode ASCII_8BIT in the Scala? I have an external system written in Ruby which sending a data over the wire encoded with ASCII_8BIT. How should I decode and encode them in the Scala?
I couldn't find a library for decoding and encoding ASCII_8BIT string in scala.
As I understand, correctly, the ASCII_8BIT is something similar to Base64. However, there is more than one Base64 encoding. Which type of encoding should I use to be sure that cover all corner cases?

A: What is ASCII-8BIT?
ASCII-8BIT is Ruby's binary encoding (the name "BINARY" is accepted as an alias for "ASCII-8BIT" when specifying the name of an encoding). It is used both for binary data and for text whose real encoding you don't know.
Any sequence of bytes is a valid string in the ASCII-8BIT encoding, but unlike other 8bit-encodings, only the bytes in the ASCII range are considered printable characters (and of course only those that are printable in ASCII). The bytes in the 128-255 range are considered special characters that don't have a representation in other encodings. So trying to convert an ASCII-8BIT string to any other encoding will fail (or replace the non-ASCII characters with question marks depending on the options you give to encode) unless it only contains ASCII characters.
What's its equivalent in the Scala/JVM world?
There is no strict equivalent. If you're dealing with binary data, you should be using binary streams that don't have an encoding and aren't treated as containing text.
If you're dealing with text, you'll either need to know (or somehow figure out) its encoding or just arbitrarily pick an 8-bit ASCII-superset encoding. That way non-ASCII characters may come out as the wrong character (if the text was actually encoded with a different encoding), but you won't get any errors because any byte is a valid character. You can then replace the non-ASCII characters with question marks if you want.
What does this have to do with Base64?
Nothing. Base64 is a way to represent binary data as ASCII text. It is not itself a character encoding. Knowing that a string has the character encoding ASCII or ASCII-8BIT or any other encoding, doesn't tell you whether it contains Base64 data or not.
But do note that a Base64 string will consist entirely of ASCII characters (and not just any ASCII characters, but only letters, numbers, +, /  and =). So if your string contains any non-ASCII character or any character except the aforementioned, it's not Base64.
Therefore any Base64 string can be represented as ASCII. So if you have an ASCII-8BIT string containing Base64 data in Ruby, you should be able to convert it to ASCII without any problems. If you can't, it's not Base64.


text:
Q: Using custom markers instead of default marker (Openlayers) This is a simple problem but I'm tangled up in the code and can't figure out the solution; hope someone can help!
I have three markers on a map and want each marker to be a different icon.
I can't work out where to make this happen - do I need to redraw?
I have seen this question OpenLayers problem with marker icons , but don't understand how to implement the solution.
My code:
      function init() {
    map = new OpenLayers.Map("basicMap");
    var mapnik         = new OpenLayers.Layer.Stamen("toner-background");
    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection   = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
    var position       = new OpenLayers.LonLat(30,55.515).transform( fromProjection, toProjection);
    var zoom           = 4;

    map.addLayer(mapnik);
    map.setCenter(position, zoom );

var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);

var icon1 = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);
var icon2 = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker-gold.png', size, offset);
var icon3 = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker-green.png', size, offset);

        var lonLat1 = new OpenLayers.LonLat(0.1062,51.5171).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        map.getProjectionObject() // to Spherical Mercator Projection
                        );

        var lonLat2 = new OpenLayers.LonLat(2.3470,48.8742).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        map.getProjectionObject() // to Spherical Mercator Projection
                        );

                        var lonLat3 = new OpenLayers.LonLat(7.2692,43.7028).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        map.getProjectionObject() // to Spherical Mercator Projection
                        );

var marker1 = new OpenLayers.Marker(lonLat1);
    var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    marker1.icon.size = size;
marker1.icon.offset = offset;

var feature = new OpenLayers.Feature(markers, lonLat1);
feature.closeBox = true;
feature.popupClass = OpenLayers.Class(OpenLayers.Popup.AnchoredBubble, { autoSize: true });
feature.data.popupContentHTML = '
Marker1
';
feature.data.overflow = "hidden";

marker1.feature = feature;

var markerClick = function (evt) {
    if (this.popup == null) {
        this.popup = this.createPopup(this.closeBox);
        map.addPopup(this.popup);
        this.popup.show();
    } else {
        this.popup.toggle();
    }
    OpenLayers.Event.stop(evt);
};
marker1.events.register("mousedown", feature, markerClick);

var marker2 = new OpenLayers.Marker(lonLat2);
        var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);

var feature = new OpenLayers.Feature(markers, lonLat2);

feature.closeBox = true;
feature.popupClass = OpenLayers.Class(OpenLayers.Popup.AnchoredBubble, { autoSize: true });
feature.data.popupContentHTML = '
Marker2
';
feature.data.overflow = "hidden";
marker2.feature = feature;

var markerClick = function (evt) {
    if (this.popup == null) {
        this.popup = this.createPopup(this.closeBox);
        map.addPopup(this.popup);
        this.popup.show();
    } else {
        this.popup.toggle();
    }
    OpenLayers.Event.stop(evt);
};
marker2.events.register("mousedown", feature, markerClick);

var marker3 = new OpenLayers.Marker(lonLat3);
        var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    marker3.icon.size = size;
marker3.icon.offset = offset;
var feature = new OpenLayers.Feature(markers, lonLat3);
feature.closeBox = true;
feature.popupClass = OpenLayers.Class(OpenLayers.Popup.AnchoredBubble, { autoSize: true });
feature.data.popupContentHTML = '
Marker 3
';
feature.data.overflow = "hidden";

marker3.feature = feature;

var markerClick = function (evt) {
    if (this.popup == null) {
        this.popup = this.createPopup(this.closeBox);
        map.addPopup(this.popup);
        this.popup.show();
    } else {
        this.popup.toggle();
    }
    OpenLayers.Event.stop(evt);
};
marker3.events.register("mousedown", feature, markerClick);

markers.addMarker(marker1, icon1);

markers.addMarker(marker2, icon2);

markers.addMarker(marker3, icon3);

  }

Thanks!

A: See the OpenLayers Marker documentation which has an example. You are passing the icon at the wrong location. It has to be done inside the OpenLayers.Marker() constructor and not at OpenLayers.Layer.Markers.addMarker().
Instead of
var marker1 = new OpenLayers.Marker(lonLat1);

try
var marker1 = new OpenLayers.Marker(lonLat1, icon1);

and remove the second parameter at your addMarker() calls because they are ignored.


text:
Q: Testlink installation failed within xammp in Windows Today i tried to install Testlink on windows with xammp. path also set as
$g_repositoryPath = 'C:/xampp/htdocs/testlink/upload_area';
$tlCfg->log_path = 'C:/xampp/htdocs/testlink/logs';

But when i click on "Continue" button after checking the terms check box it gives
Parse error: syntax error, unexpected 'SCREEN' (T_STRING) in C:\xampp\htdocs\Testlink\config.inc.php on line 298

In the config.inc.php file code showing as below(mentioned part)
/**
 * @var string How to warning user when security weak points exists.
 *
 * 'SCREEN': messages will displayed on login screen, and tl desktop
 * 'FILE': a file with a list is created but users are not notified via GUI
 *         user will receive a message on screen. (default)
 * 'SILENT': same that FILE, but user will not receive message on screen.
 */
$tlCfg->config_check_warning_mode = 'FILE';

IS there any way to resolve this?


text:
Q: Get json payload then strip the html with python I have a json values that I need stripped of all html tags.
After using the following function:
def payloaded():
from urllib.request import urlopen
with urlopen("www.example.com/payload.json") as r:
    data = json.loads(r.read().decode(r.headers.get_content_charset("utf-8")))
text = (data["body"]["und"][0]["value"])
return(text)

This is the returned (text):
<div class="blah">'
This is the text.
\r\n'

This is the original (text):

This is the text.

Note: I need all html tags stripped, and there is no real guidelines of what the tags I will be getting.
This is what I want the (text) to be:
This is the text.

This is the post function I am using:
def add_node_basic(text)
url = "www.example.com"
headers = {"content-type": "application/json"}
payload = {
    "auth_token": x,
    "docs":
        {
            "id": y,
            "fields": [
                {"name": "body", "value": text, "type": "text"},
            ]}
}

r = requests.post(url, data=json.dumps(payload), headers=headers)

Any suggestions on how to achieve this is much appreciated!

A: You can try slicing the string along with find method, like this:
>>> print text[text.find('
'):text.find('
')].strip('
')
This is the text.

If you are trying to extract text only from the HTML source, then you can use HTMLParser library in Python. Example:
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()


text:
Q: Skew $~3$D plane and keep coordinates I think my problem would be much easier to explain if I make you a sketch:

I've got two planes in $R^3~: π_1 ~~\text{and}~~ π_2$
$π_1~$ is defined by $~4~$ points : $~~ A = (a_1, a_2, a_3),~~ B = (b_1, b_2, b_3),~~ C = (c_1, c_2, c_3),~~ D=(d_1, d_2, d_3)~$
$π_2~$ is also defined by another $~4~$ points: $~~A_2 = (a_{21},  a_{22},  a_{23}),~~ B_2 = (b_{21}, b_{22}, b_{23}),~~ C_2 = (c_{21}, c_{22}, c_{23}),~~ D_2 = (d_{21}, d_{22}, d_{23})$
First what I need is to transform $~π_2~$ by changing the points $~C_2~$ and $~D_2~$. I need them to be the same value as $~C~$ and $~D~$.
Then I need to obtain points from that new $~π_2~$ plane with $~R_2~$ points as input. Like any $~2$D plane. I'm also drawing a sketch for that requirement because I think it will be easier to understand:

Anybody can help/save me? Thanks!


text:
Q: How to create tabs - Jquery or JSF I want to create JSF page with tabs. Something like this. But I wonder if I choose to do this with Jquery can I implement lazy loading - when I click a tab on the JSF page the content is generated when the tab is opened. Is it possible to implement lazy loading of tabs in pure JSF? And I suppose that I can easily implement AJAX in both cases.
Best wishes

A: The Primefaces Tabview component supports lazy loading.
Quote from the showcase:

Tab contents can be lazy loaded with ajax as well, when dynamic
  attribute is set to "true" only the active tab's content will be
  rendered and clicking on a lazy tab will fetch the tab contents with
  ajax. This behavior is handy to save bandwith and reduce page size
  when dealing with tabs having a lot of content.

Quick example from the showcase:
<h:form id="form">

      // tabs

</h:form>

The cache attribute is used to prevent ajax reloading of tab content if you toggle between tabs.

A: Note: If you want your tabs beans be Session Scope then read instructions in the buttom of the Answer...
Since you are don't want to use any third party Libarary here is a PureJSF + jQuery example
JSF + Jquery + Ajax Lazy Loading + View Scope Beans Example...
B.T.W here is how it looks like eventually :

You can look at the web server console for the print outs of @PostConstruct and the @PreDestroy when you click on each tab...
The content of the tab  - the xhtml page and its bean will be loaded upon tab click (Lazy Loading) and will be destroyed upon click on other tab,
I suggest you to create a new project and slowly place all the files inside it and start playing and looking into it... its 100% working , but I placed some print outs just to see that it is really working...
The Example is very simple and straight forward....
First Of all go to jQueryUI and download it(1.8.18)
and place jquery-1.7.1_.min.js and jquery-ui-1.8.18.custom.min.js in WebContent\resources\js and jquery-ui-1.8.18.custom.css in WebContent\resources\css
Now to the other files...
myTabs.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
 <h:outputScript library="js" name="jquery-1.7.1_.min.js" target="head" />
 <h:outputScript library="js" name="jquery-ui-1.8.18.custom.min.js" target="head" />
 <h:outputStylesheet library="css" name="jquery-ui-1.8.18.custom.css" target="head"     />
 <h:outputScript library="js" name="mytabs.js" target="head" />
</h:head>
<h:body>

<f:view>
    <h:form prependId="false">
        <h:panelGroup id="tabs" layout="block">

                <c:forEach items="#{myTabs.tabs}" var="tab">

#{tab.tabid}

                    <h:commandButton id="button_#{tab.tabid}" value="TabClick" action="#{myTabs.switchPages(tab.tabid)}" style="display:none">
                        <f:ajax render="tabs"></f:ajax>
                    </h:commandButton>
                </c:forEach>

            <c:forEach items="#{myTabs.tabs}" var="tab">
                <h:panelGroup id="#{tab.tabid}" layout="block" rendered="#{tab.tabid eq myTabs.selectedTab}">
                    <ui:include src="#{tab.tabfilename}"></ui:include>
                </h:panelGroup>
            </c:forEach>
        </h:panelGroup>
    </h:form>
</f:view>
</h:body>

MyTabs.java
package pack;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class MyTabs{

@PostConstruct
public void init(){
    tabs = new ArrayList<MyTabObject>();
    tabs.add(new MyTabObject("tab1.xhtml", "tab1"));
    tabs.add(new MyTabObject("tab2.xhtml", "tab2"));
    tabs.add(new MyTabObject("tab3.xhtml", "tab3"));

}
String selectedTab="tab1";

public String getSelectedTab() {
    return selectedTab;
}

public void setSelectedTab(String selectedTab) {
    this.selectedTab = selectedTab;
}

public String switchPages(String selTab) {
    selectedTab = selTab;
    return "myTabs.xhtml";
}

List<MyTabObject> tabs;

public List<MyTabObject> getTabs() {
    return tabs;
}

public void setTabs(List<MyTabObject> tabs) {
    this.tabs = tabs;
}

}

MyTabObject
package pack;

public class MyTabObject{

String tabfilename;
String tabid;
public String getTabfilename() {
    return tabfilename;
}
public void setTabfilename(String tabfilename) {
    this.tabfilename = tabfilename;
}
public String getTabid() {
    return tabid;
}
public void setTabid(String tabid) {
    this.tabid = tabid;
}
public MyTabObject(String tabfilename, String tabid) {
    super();
    this.tabfilename = tabfilename;
    this.tabid = tabid;
}

}

Tab1Page , (Tab2Page and Tab3Page are exactly the same , just change the number in all places)
package pack;

import java.io.Serializable;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class Tab1Page implements Serializable{

/**
 *
 */
private static final long serialVersionUID = 254415216070877770L;
// Constants
public final static String hashKey = "tab1PageTab";
public String actionString = "";

@PostConstruct
public void post(){
  Format formatter;
  Date date = new Date();

  // Time formate 01:12:53 AM
  formatter = new SimpleDateFormat("hh:mm:ss a");
  tabName = formatter.format(date);
    System.out.println("Tab1Page\t"+tabName+"\t@PostConstruct...");
}

@PreDestroy
public void destroy(){
  Format formatter;
  Date date = new Date();

  // Time formate 01:12:53 AM
  formatter = new SimpleDateFormat("hh:mm:ss a");
  tabName = formatter.format(date);
    System.out.println("Tab1Page\t"+tabName+"\t@PreDestroy...");
}

String tabName;

public String getTabName() {
    return this.getClass().getName().substring(this.getClass().getName().lastIndexOf("."))+"\t"+tabName;
}
public void setTabName(String tabName) {
    this.tabName = tabName;
}

public String getActionString() {
    return actionString;
}

public void setActionString(String actionString) {
    this.actionString = actionString;
}

}

tab1.xhtml (tab2.xhtml and tab3.xhtml are exactly the same - just replace the numbers)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">

<h:panelGroup>
    <h:form>
        <h:outputText value="#{tab1Page.tabName}" />
    </h:form>
</h:panelGroup>
</ui:composition>

and to the last file
mytabs.js (place it in WebContent\resources\js)
$(document).ready(function () {
    $("#tabs").tabs();
});

$(window).load(function() {
    jsf.ajax.addOnEvent(function (data) {
        if (data.status === "success") {
                $("#tabs").tabs();
        }
    });
});

In order to use Session Scope Beans:
The method switchPages in MyTabs.java should be void and not to return anything, like this
    public void switchPages(String selTab) {
    selectedTab = selTab;
}

A: It's not a problem at all implement an ajax tab with jQuery UI.
See the documentation of jQuery Tabs with ajax here and click on "view source" to find the code you need.

A: You can look at the book Core Java Server Faces third edition page 339 to see how you can implement simple tabs with h:panelGrid.
The output is something like this:

This is the code example from the book:
...
<h:form>
<h:panelGrid styleClass="tabbedPane" columnClasses="displayPanel">

<f:facet name="header">
<h:panelGrid columns="4" styleClass="tabbedPaneHeader">
<h:commandLink tabindex="1"
title="#{msgs.jeffersonTooltip}"
styleClass="#{tp.jeffersonStyle}"
actionListener="#{tp.jeffersonAction}">
#{msgs.jeffersonTab}
</h:commandLink>
...
</h:panelGrid>
</f:facet>

<ui:include src="washington.xhtml" />
<ui:include src="roosevelt.xhtml" />
<ui:include src="lincoln.xhtml" />
<ui:include src="jefferson.xhtml" />
</h:panelGrid>
</h:form>
...

This is the description:
The tabbed pane is implemented with h:panelGrid. Because we do not specify
the columns attribute, the panel has one column. The panel's header—defined
with an f:facet tag—contains the tabs, which are implemented with another
h:panelGrid that contains h:commandLink tags for each tab. The only row in the panel
contains the content associated with the selected tab.
When a user selects a tab, the associated action listener for the command link is
invoked and modifies the data stored in the backing bean. Because we use a
different CSS style for the selected tab, the styleClass attribute of each h:commandLink
tag is pulled from the backing bean with a value reference expression.
As you can see from the top picture in Figure 8–11, we have used the title
attribute to associate a tooltip with each tab. Another accessibility feature is the
ability to move from one tab to another with the keyboard instead of the
mouse. We implemented that feature by specifying the tabindex attribute for
each h:commandLink.
The content associated with each tab is statically included with the JSP include
directive. For our application, that content is a picture and some text, but
you could modify the included JSF pages to contain any set of appropriate
components. Notice that even though all the JSF pages representing content are
included, only the content associated with the current tab is rendered. That is
achieved with the rendered attribute—for example, jefferson.xhtml looks like this:
Putting It All Together
<h:panelGrid columns="2" columnClasses="presidentDiscussionColumn"
rendered="#{tp.jeffersonCurrent}">
<h:graphicImage value="/images/jefferson.jpg"/>
"#{msgs.jeffersonDiscussion}"
</h:panelGrid>
Figure 8–12 shows the directory structure for the tabbed pane application and
Listings 8–14 through 8–17 show the most important files.

Unfortunately I don't know how to add lazy loading and AJAX support to this code.


text:
Q: Вычислить скидки на продукцию Калькулятор работает на FormCalc. Помогите, пожалуйста, сделать, чтобы при заказе от 1 до 5 шт выводил 100% цену (сейчас только ее и выводит), при заказе от 5 до 10- 96%, от 10 и выше 93%.
Код шаблона:

<col class="calc-td" />
<col class="calc-top" />
<col class="calc-top" />
<col class="calc-top" />

Цвета антивандальных пластин для врезного исполнения:

Серебристый

Чёрный

Зелёный

Бокс для накладного исполнения:

Антрацит

   <fieldset><legend>
    Привратник 01C
  </legend>

Врезное исполнение

      <input type="checkbox" name="C01_gray" value="флажок" id="C01_gray" />
      Серебристый

    Количество:
    <input type="text" name="colvo01Cgray" id="colvo01Cgray" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

      <input type="checkbox" name="C01_black" value="флажок" id="C01_black" />
      Чёрный

    Количество:
    <input type="text" name="colvo01Cblack" id="colvo01Cblack" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

      <input type="checkbox" name="C01_green" value="флажок" id="C01_green" />
      Зелёный

    Количество:
    <input type="text" name="colvo01Cgreen" id="colvo01Cgreen" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

          <input type="radio" name="BOX01C" value="переключатель" id="BOX01C" />
          В боксе

     Количество:
    <input type="text" name="colvoBOX01C" id="colvoBOX01C" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

</fieldset>

   <fieldset><legend>
  Привратник 02A</legend>

Врезное исполнение

      <input type="checkbox" name="A02_gray" value="флажок" id="A02_gray" />
      Серебристый

    Количество:
    <input type="text" name="colvo02Agray" id="colvo02Agray" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

      <input type="checkbox" name="A02_black" value="флажок" id="A02_black" />
      Чёрный

    Количество:
    <input type="text" name="colvo02Ablack" id="colvo02Ablack" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

      <input type="checkbox" name="A02_green" value="флажок" id="A02_green" />
      Зелёный

    Количество:
    <input type="text" name="colvo02Agreen" id="colvo02Agreen" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

          <input type="radio" name="BOX02A" value="переключатель" id="BOX02A" />
          В боксе

     Количество:
    <input type="text" name="colvoBOX02A" id="colvoBOX02A" size="5" value="0" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" /> шт.

</fieldset>

Рассчитанная стоимость составляет
 <input type="hidden" id="rez" name="rez" value=""/>
 руб. (с учетом НДС 18%)

<input class="button" type="reset" name="reset" value="Отменить" onclick="change(),newdoc()" />

Выслать заявку на e-mail:
<input type="text" value="Введите ваш e-mail" name="mailto" id="mailto" class="validate['email']" onfocus="this.value=(this.value=='0')? '' : this.value;" onblur="this.value=(this.value=='')? '0' : this.value;"  onclick="this.value='';" />

Прикрепить реквизиты:
<input type="file" name="file" value="Выберите файл" />

{CAPTCHA}

<input type="submit" class="button validate" value="Отправить заявку" />

Формула для расчета:
rez={colvo01Cgray}23351.02+{colvo01Cblack}23351.02+{colvo01Cgreen}23351.02+{colvoBOX01C}29109.42+{colvo02Agray}000+{colvo02Ablack}000+{colvo02Agreen}000+{colvoBOX02A}000


text:
Q: Creating folder with cell as name As I create a project number using the below code, I need to create a folder with the title as the new project number in the following path: W:\My system\me\my work\PROJECTS\Projects\Reliability, I know the code needs to be placed after (.Cells(MyRow, "Q").Value = Sheets("Tracker").Cells(3, "E").Value   'project NUMBER) as title of the new project will be placed in "active column 17" once the below code is completed
So I have this code which checks if a cell is empty and when prompted to create a project number, This works fine but I'm not sure how to add code to create the new folder in the above folder
Sub MyFileprojectTF()
    'Detemine to open or create report.
    'Application.ScreenUpdating = False
    Dim MyNewFile As String
    Dim MySht, MyWBK As String
    Dim MyRow As Integer
    MyRow = ActiveCell.Row
    MySht = ActiveSheet.Name
    MyWBK = ActiveWorkbook.Name

    If ActiveCell.Column = 17 Then
        If ActiveCell.Value <> "" Then 'if cell in the is empty
            MyFileprojectOpenTF
        Else
            OpenTemplate 'opens template tracker for new project number

            With Workbooks("project.xls").Sheets("Tracker")
                .Cells(9, "B").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "H").Value  'Project
                .Cells(10, "B").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "J").Value  'Customer
                .Cells(2, "G").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "P").Value  'tracker
                .Cells(14, "E").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "O").Value  'tech
                .Cells(15, "E").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "N").Value  'FILE REF
                .Cells(25, "A").Value = Workbooks(MyWBK).Sheets(MySht).Cells(MyRow, "L").Value  'Description
            End With

            '***********************************
            NewProjectGSRTF
            UpDateMyDataBaseTF
            '***********************************

            With Workbooks(MyWBK).Sheets(MySht)
                .Cells(MyRow, "Q").Value = Sheets("Tracker").Cells(3, "E").Value   'project NUMBER
            End With

            ActiveWorkbook.Saved = True
            ActiveWorkbook.Close
            Workbooks(MyWBK).Save
        End If
    End If
    Application.ScreenUpdating = True
End Sub

A: Expanding on the two version I mentioned in comments.  Update Activesheet with correct sheet and range with correct cell to collect folder name from. Currently have default "Testing" name created in case cell is empty where getting name from.
1) MKDIR
Option Explicit

Public Sub MyFileprojectTF()

    Dim startPath As String
    Dim myName As String

    startPath = "W:\My system\me\my work\PROJECTS\Projects\Reliability"
    myName = ActiveSheet.Range("D1").Text        ' Change as required to cell holding the folder title

    If myName = vbNullString Then myName = "Testing"

    Dim folderPathWithName As String
    folderPathWithName = startPath & Application.PathSeparator & myName

    If Dir(folderPathWithName, vbDirectory) = vbNullString Then
        MkDir folderPathWithName
    Else
       MsgBox "Folder already exists"
       Exit Sub
    End If

End Sub

2) FSO
Option Explicit

Public Sub MyFileprojectTF()

    Dim startPath As String
    Dim myName As String

    startPath = "W:\My system\me\my work\PROJECTS\Projects\Reliability"
    myName = ActiveSheet.Range("D1").Text        ' Change as required to cell holding the folder title

    If myName = vbNullString Then myName = "Testing"

    Dim folderPathWithName As String
    folderPathWithName = startPath & Application.PathSeparator & myName

    If Dir(folderPathWithName, vbDirectory) = vbNullString Then
        Dim fso As Object
        Set fso = CreateObject("FileSystemObject")
        fso.CreateFolder folderPathWithName
    Else
       MsgBox "Folder already exists"
       Exit Sub
    End If

End Sub

A: Use MkDir create a folder using VBA:
MkDir "FolderName"

...creates a folder named "FolderName" in the current directory, or:
MkDir "c:\users\bob\desktop\FolderName"

...creates a folder named "FolderName" on Bob's desktop.
To create folder W:\My system\me\my work\PROJECTS\Projects\Reliability, use:
MkDir "W:\My system\me\my work\PROJECTS\Projects\Reliability"

More info here (but there's not much more to say).


text:
Q: Python & MySQL - solution for storing lists in databases? So I'm new to databases and stumped as to how to do something that seems fairly ubiquitous in websites:
I have a database (working with Python, flask, flask-sqlalchemy), that currently is storing info about individual files(images), model looks something like:
class Storedfile(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.Text)
    filesize = db.Column(db.Integer)
    upload_time = db.Column(db.DateTime)

But what I want to do is be able to group these files if they are uploaded together into galleries. Up to 100 files can be uploaded at a time but the gallery could be any number of files 2-100. So first thing that comes to mind is having a gallery model(class?) that stores lists of images(which would be instances of the Storedfile class), but I know that storing lists in columns of relational databases pretty much defeats the purpose of relational databases, and even if you wanted to do this it requires hacky and cumbersome solutions. So basically, I need to store a list of images associated with a gallery,  of which could  consist of any number of entries between 2 and 100.   How could I go about doing this? Thank you.

A: Modify your StoredFile model so it has an index to the gallery (gallery_id for instance), modify the table as well.
Create a gallery table with an id field, and perhaps a name.


text:
Q: how to change dynamical attribute on slider I have a dynamical slider. And trying to add tabindex="-1" attribute to child when it's parent li element has aria-hidden="true" attribute.
Here is Fiddle example :
Or see below snippet :

$('.bxslider').bxSlider({
  minSlides: 3,
  maxSlides: 3,
  moveSlides: 1,
  slideWidth: 150,
  slideMargin: 0
});

$('li[aria-hidden=true]').children().attr('tabindex', '-1');
body {
  margin: 50px 0 0 30px;
}

.my-slider {
  text-align: center;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.12/jquery.bxslider.min.css" rel="stylesheet" />

aaa

bbb

ccc

dd

eee

How do I change the code as dynamical attribute ?
Please help

A: You have to use the BxSlider onSlideAfter callback.

Executes immediately after each slide transition. Function argument is the current slide element (when transition completes).

See documentation.
$('.bxslider').bxSlider({
  minSlides: 3,
  maxSlides: 3,
  moveSlides: 1,
  slideWidth: 150,
  slideMargin: 0,

  onSlideAfter: function(){
    $('li[aria-hidden=true]').children().attr('tabindex', '-1');
  }
});

Your Fiddle Updated.

A: As Louys reported you should use onSlideAfter calback function :
but some small addition in order to remove tabindex you should remove from all li's children that add it to li with aria-hidden=true
by adding $('.bxslider li').children().removeAttr('tabindex');
See below Snippet :

$('.bxslider').bxSlider({
  minSlides: 3,
  maxSlides: 3,
  moveSlides: 1,
  slideWidth: 150,
  slideMargin: 0,
  onSlideAfter : function(elt,oldIndex,neIndex) {
   $('.bxslider li').children().removeAttr('tabindex');
   $('li[aria-hidden=true]').children().attr('tabindex', '-1');
  }
});

$('li[aria-hidden=true]').children().attr('tabindex', '-1');
body {
  margin: 50px 0 0 30px;
}

.my-slider {
  text-align: center;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.12/jquery.bxslider.min.css" rel="stylesheet" />

aaa

bbb

ccc

dd

eee