text:
Q: Modern CPU Inner Loop Indirection Optimizations From http://www.boost.org/community/implementation_variations.html
"... coding differences such as changing a class from virtual to non-virtual members or removing a level of indirection are unlikely to make any measurable difference unless deep in an inner loop. And even in an inner loop, modern CPUs often execute such competing code sequences in the same number of clock cycles!"
I am trying to understand the "even in the inner loop" part. Specifically what mechanisms do CPUs implement to execute the two codes (virtual vs non-virtual or an additional level of indirection) within the same number of clock cycles? I know about instruction pipelining and caching, but how is it possible to perform a virtual call within the same number of clock cycles as a non-virtual call? How is the indirection "lost"?

A: Caching (e.g. branch target caching), parallel load units (part of pipelining, but also things like "hit under miss" which don't stall the pipeline), and out-of-order execution are likely to help transform a load-load-branch into something that is closer to a fixed branch.  Instruction folding/elimination (what's the proper term for this?) in the decode or branch prediction stage of the pipeline may also contribute.
All of this relies on a lot of different things, though: how many different branch targets there are (e.g. how many different virtual overloads are you likely to trigger), how many things you loop over (is the branch target cache "warm"? how about the icache/dcache?), how the virtual tables or indirection tables are layed out in memory (are they cache-friendly, or is each new vtable load possibly evicting an old vtable?), is the cache being invalidated repeatedly due to multicore ping-ponging, etc...
(Disclaimer: I'm definitely not an expert here, and a lot of my knowledge comes from studying in-order embedded processors, so some of this is extrapolation.  If you have corrections, feel free to comment!)
The correct way to determine if it's going to be a problem for a specific program is of course to profile.  If you can, do so with the help of hardware counters -- they can tell you a lot about what's going on in the various stages of the pipeline.

Edit:
As Hans Passant points out in an above comment Modern CPU Inner Loop Indirection Optimizations, the key to getting these two things to take the same amount of time is the ability to effectively "retire" more than one instruction per cycle.  Instruction elimination can help with this, but superscalar design is probably more important (hit under miss is a very small and specific example, fully redundant load units might be a better one).
Let's take an ideal situation, and assume a direct branch is just one instruction:
branch dest

...and an indirect branch is three (maybe you can get it in two, but it's greater than one):
load vtable from this
load dest from vtable
branch dest

Let's assume an absolutely perfect situation: *this and the entire vtable are in L1 cache, L1 cache is fast enough to support amortized one cycle per instruction cost for the two loads.  (You can even assume the processor reordered the loads and intermixed them with earlier instructions to allow time for them to complete before the branch; it doesn't matter for this example.)  Also assume the branch target cache is hot, and there's no pipeline flush cost for the branch, and the branch instruction comes down to a single cycle (amortized).
The theoretical minimum time for the first example is therefore 1 cycle (amortized).
The theoretical minimum for the second example, absent instruction elimination or redundant functional units or something that will allow retiring more than one instruction per cycle, is 3 cycles (there are 3 instructions)!
The indirect load will always be slower, because there are more instructions, until you reach into something like superscalar design that allows retiring more than one instruction per cycle.
Once you have this, the minimum for both examples becomes something between 0 and 1 cycles, again, provided everything else is ideal.  Arguably you have to have more ideal circumstances for the second example to actually reach that theoretical minimum than for the first example, but it's now possible.
In some of the cases you'd care about, you're probably not going to reach that minimum for either example.  Either the branch target cache will be cold, or the vtable won't be in the data cache, or the machine won't be capable of reordering the instructions to take full advantage of the redundant functional units.
...this is where profiling comes in, which is generally a good idea anyway.
You can just espouse a slight paranoia about virtuals in the first place. See Noel Llopis's article on data oriented design, the excellent Pitfalls of Object-Oriented Programming slides, and Mike Acton's grumpy-yet-educational presentations. Now you've suddenly moved into patterns that the CPU is already likely to be happy with, if you're processing a lot of data.
High level language features like virtual are usually a tradeoff between expressiveness and control.  I honestly think, though, by just increasing your awareness of what virtual is actually doing (don't be afraid to read the disassembly view from time to time, and definitely peek at your CPU's architecture manuals), you'll tend to use it when it makes sense and not when it doesn't, and a profiler can cover the rest if needed.
One-size-fits-all statements about "don't use virtual" or "virtual use is unlikely to make a measurable difference" make me grouchy.  The reality is usually more complicated, and either you're going to be in a situation where you care enough to profile or avoid it, or you're in that other 95% where it's probably not worth caring except for the possible educational content.

A: Pipelining is the main way.
It might take 20 clock cycles to load an instruction, decode it, perform it's actions and load indirect memory references. But due to the pipleline the processor can be executing parts of 19 other instructions at the same time in different stages of the pipeline giving an overall throughput of 1 instruction every clock cycle regardless of how long it actually takes to feed that instruction through the pipeline.

A: What happens, I think is that the processor has a special cache which holds the locations and targets of branches and indirect jumps.  If an indirect jump is encountered at $12345678, and the last time it was encountered it went to address $12348765, the processor can start speculative execution of the instructions at address $12348765 even before it resolves the address of the branch.  In many cases, within the inner loop of a function, a particular indirect jump will always jump to the same address throughout the duration of the loop.  The indirect-jump cache can thus avoid branching penalties.

A: Modern CPUs use an adaptive branch prediction technique which can predict many indirect jumps such as you get with a vtable implementation of virtual functions.  See http://en.wikipedia.org/wiki/Branch_prediction#Prediction_of_indirect_jumps

A: If the CPU already has the memory address in cache, then executing a load instruction is trivial, if that.


text:
Q: How to halt user keyboard input while a certain task is running? I have a maze game in a console that i'm creating for programming practice. I have created an animation and will have it running after the user has read the instruction. Though unfortunately I have a found a flaw in the way I have created my animation. I use the Console.setCursorPosition() and Console.Write(). When the user hits keys on the keyboard during the animation it enters it in the middle of the animation, so it interupts it and doens't complete the animation currectly.
My question is how do I halt user input during this animation?

A: You could use a combination of Console.KeyAvailable and Console.ReadKey(false)

redpajama_set_name: RedPajamaStackExchange


text:
Q: AdMob "currency" system I have an app which uses a virtual currency to do certain actions. You get "coins" each time you click on an ad.
Is this against AdMob TOS?

A: Here is a quote from the Terms Of Use under the title RESTRICTIONS

User shall not, and shall not authorize or encourage any third party
  to generate fraudulent impressions of or fraudulent clicks on any
  advertisement, including but not limited to, through repeated manual
  clicks, the use of robots or other automated query tools and/or
  computer generated search requests, and/or the fraudulent use of other
  search engine optimization services and/or software.

And this one is from the Integration / implementation dos and don'ts Google Support website

Users should not be encouraged to click on ads
Phrases such as "click the ads" or similar language are not allowed.
  Any compensation or other incentives to click ads are strictly
  prohibited. Additionally, incentivizing users to click on links and/or
  non-AdMob ads is also prohibited, as it will train users to perform
  actions that cause invalid activity.

It clearly states that it is not allowed. I would normally stay away from such an activity if I want to continue using the Admobs platform.


text:
Q: Wordpress - List posts of a custom post type from sub-categories I have a custom post type called my-plays, within which I've created the categories short-plays and long-plays. I would like to just be able to output a list of the posts in each category... at the moment I can only find code which just outputs a lists of all posts in my-plays. Is it possible to list posts in a category of a custom post type?

A: Taken from here.
<?php

$args = array
(
    'numberposts' => 3,
    'category'    => array(48,43,49,46,47,44,51,50,42),
    'orderby'     => 'post_date',
    'order'       => 'ASC',
    'post_type'   => 'post',
    'post_status' => 'publish'
);
query_posts($args);

?>

<?php while (have_posts()) : the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>


text:
Q: How can I build a table of contents in iReport/JasperReports? We use iReport to enable our customers to generate catalogs for print for their products. This process works GREAT. One of the things we've struggled with is how to create a table of contents for these product catalogs.
I decided to use the Scriptlet functionality to give this a shot. Note that our reports are all master-detail in nature, in that there is a master report and a subreport.
At first, I attached the scriptlet to the master report, and tried to find a way to collect all of the product numbers in the detail report, then pass that value back to the master report. I can't figure out how to get the detail information back to the master report, as it appears that you can only pass default variables from the subreport back to the master (eg PAGE_NUMBER, COLUMN_NUMBER, PAGE_COUNT, COLUMN_COUNT).
So then I tried attaching the Scriptlet to the detail report. Well, the detail report doesn't know what page the master is on, so I started passing the master's page_number into a variable in the detail report. That worked great, except that sometimes the detail can overflow to the point that page numbers from the master are skipped. In other words, if a subreport returns more than two pages worth of data, you are going to miss a page number when the subreport is called the next time.
So how to do this?

A: I found an approach that worked, similar to one of my ideas above. First of all, I could NOT get a subreport to return a value to the calling report, and then retrieve that value using getVariableValue from inside a scriptlet. I tried forever, and I just could not get that to work.
Instead, I went with the approach where I attached the same scriptlet to both the master and subreports. The scriptlet has a class variable where I can keep a running tally of all the product numbers I encounter in the detail, and this code goes inside the afterDetailEval() method of the scriptlet. Note that I only want this code to run for the subreport, so I do a check to see if a particular detail field, which will never be null, is present. If it's not, I don't run the code. So when that event is called by the master report, the code doesn't run.
Now for the part that I learned from the example. The admirable side-effect programming in the example is that there is a line of dimensions 1x1 that contains a call to a custom scriptlet method in the "Print When Expression" property. That's a great idea! So this custom method returns false no matter what, and the line never prints. I did the same thing in the Page Footer band, and this method collects the values from the class variable, determines the page, and stores the results in a hash. Then it resets the class variable.
In the Report Summary band, I have another line that will never print, that calls another custom method. All I do here is iterate through a map of product numbers and show all the pages each one appears on. Done!

A: There is an example of tables of contents (with subreport) in project folder jasperreports-x.x.x/demo/samples/tableofcontents.
And see the hyperlink example also.
Hyperlinks, Anchors and Bookmarks

JasperReports allows you to create drill-down reports, which introduce tables of contents
  in your documents or redirect viewers to external documents using special report elements called hyperlinks.


text:
Q: Knockout JS - observing a mutation in any property of an array without ko.mapping In my application I have to show only the top 5 items of a long list that have the highest rating. I have implemented this as follows:
The long list is an array that I have turned into an observable array with all elements as observables with ko.mapping, and the top 5 items are a computed array that depends on the long list. Whenever anything in the long list changes the computed array resorts the long list and takes the top 5 items.
My problem is that the long array with ko.mapping takes up 60MB of memory, whereas without ko.mapping it only takes 4MB. Is there a way to achieve this effect without ko.mapping the long array?
Here is a fiddle in which I have recreated the scenario with a smaller and simpler long array, but it's just for you to understand what I'm talking about.
This is the long array, for the demo I've made it 12 elements long:
 this.longArray = ko.mapping.fromJS([
    {name:"Annabelle"},
    {name:"Vertie"},
    {name:"Charles"},
    {name:"John"},
    {name:"AB"},
    {name:"AC"},
    {name:"AD"},
    {name:"AE"},
    {name:"AF"},
    {name:"AG"},
    {name:"AH"},
    {name:"AJ"}
]);

And this is the computed array(showing only the top 5):
this.sortedTopItems = ko.computed(function() {
    return self.longArray().sort(function(a, b) {
        if(a.name() < b.name()) return -1;
            if(a.name() > b.name()) return 1;
            return 0;
    }).slice(0, 5);
}, this);

The change one button is to simulate the long array changing and the reset button is to reset the array to its initial state.

A: You sure can, but the simplest way would be to filter the data before putting into knockout. If you only ever care about the first 5. Let's assume your long array of items is called data. Note that I'm not able to test this right now, but it should give you a good idea.
const sortedTopItems = ko.observableArray([]);

// Call with new data
const update = (data) => {
    data.sort((a,b) => a.name - b.name);
    sortedTopItems(data.slice(0, 5));
}

This handles the case for simple data where it's not observable. If you want the actual data items (rows) to be observable then I'd do the following:
const length = 5;

// Create an empty array and initialize as the observable
const startData = new Array(length).map(a => ({}));
const sortedTopItems = ko.observableArray(startData);

// Call with new data
const update = (data) => {
    data.sort((a,b) => a.name - b.name);

    for(let i = 0; i < length; i++) {
        const item = sortedTopItems()[i];
        ko.mapping.fromJS(data[i], item); // Updates the viewModel from data
    }
}


text:
Q: Varied batch file output when run with scheduler  @echo off
 setLocal DisableDelayedExpansion
 pushd H:\reports\Revenue\ZREVEXP
 setLocal EnableDelayedExpansion
 for /f "tokens=* delims= " %%G in ('dir/b/od') do (set newest=%%G)
 copy %newest% D:\FILES\zbookings_revenue\archivezbookings_revenue%date:~10,4%%date:~4,2%%date:~7,2%.txt
 DEL D:\FILES\zbookings_revenue\zbookings_revenue.txt
 copy %newest% D:\FILES\zbookings_revenue\zbookings_revenue.txt
 REM PAUSE
 POPD

The batch file runs perfect manually but when I run it as a scheduled task I get the following odd results. The first is that the zbookings_revenue.txt file will contain the .bat file contents. So what you see above is copied to my zbookings_revenue.txt file. Another is that the output file grows to 33MB from a 6MB source file. Maybe there is something wrong with my batch code but I'm not sure how it runs fine through explorer all else being equal. Is there any way that the code above could produce these results? Thanks for the help!


text:
Q: Hide MenuItem if an action is performed I'm following this turorial to add option menu to my app. I would hide one of the items when an action is performed.
For example if the user does the login, then i want to hide the login item...
How to select it for setting not visibile?
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.Login:
            clickLogin();

        case R.id.BugReport:
            clickBugReport();

        case R.id.About:
            clickAbout();

        case R.id.Credits:
            clickCredits();

        default:
            return super.onOptionsItemSelected(item);
    }
}

A: If you insist that you do not to show the menu item, when user has already logged in, then create another xml file with 'login' option removed. Before you set the menu xml file in onCreateOptionsMenu, check if user not logged in then set the old xml file else if logged in, then set the new xml file. That's a simple way.
Other way is to set the visibility of that item to be false. See setVisibility and How do I hide a menu item in the actionbar? and
If you just want to disable the login option, then you may check if user has logged in before performing the action on 'login' click, inside onOptionsItemSelected. Then you can show the background as disabled of that menu item.
Hope this helps.


text:
Q: Hibernate's nullable = false not working in all cases I have the following class:
@Entity
@Table(name = "USERS")
public class User {

    private Long userID;

    @Id
    @Column(name = "userID")
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    public Long getUserID() {
        return userID;
    }

    @Column(nullable = false)
    private boolean isActive;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Calendar lastLoggedIn;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Calendar createdDate;

    @Version
    private Integer version;

    public String getEmail() {
        return email;
    }

    public boolean isActive() {
        return isActive;
    }

    public void setActive(boolean isActive) {
        this.isActive = isActive;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Calendar getLastLoggedIn() {
        return lastLoggedIn;
    }

    public void setLastLoggedIn(Calendar lastLoggedIn) {
        this.lastLoggedIn = lastLoggedIn;
    }

    public Calendar getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Calendar createdDate) {
        this.createdDate = createdDate;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public void setUserID(Long userID) {
        this.userID = userID;
    }

    public User(Long userID, String email, String password, Calendar lastLoggedIn, Calendar createdDate, Integer version) {

    }

    // No argument constructor
    public User() {}
}

When I run my application, Hibernate loads the configuration and creates the table for Users. I'm using Postgresql. This is the SQL statement being generated (logged by hibernate):
Hibernate: create table USERS
           (userID int8 not null, active boolean not null, createdDate timestamp,
            email varchar(255), lastLoggedIn timestamp,
            password varchar(255), version int4, primary key (userID))

Why is it that a boolean is created as not null and a String/Timestamp is not? I won't there to be an exception if you try to insert a User without an email or password, but with this generated schema it won't. Is there another way to force Hibernate to create the field as not nullable?

A: From  5.1.4.1.2. Access type :

By default the access type of a class hierarchy is defined by the
  position of the @Id or @EmbeddedId annotations. If these annotations
  are on a field, then only fields are considered for persistence and
  the state is accessed via the field. If there annotations are on a
  getter, then only the getters are considered for persistence and the
  state is accessed via the getter/setter.

As you annotate @Id on the getter , you are using property access. So , hibernate will ignore all mapping annotations marked on the fields and only use annotations on getters to generate DDL . Because there are no annotations on getters , default settings are used .
You should get your desired result if you change to annotate @Id on the userID instead of getUserID()


text:
Q: Isomorphism between $H/H\cap N$ and $HN/N$ Suppose we have a group G under operation +, and let H be a subgroup and N a normal subgroup.
I want to prove that $H/H\cap N$ is isomorphic to $HN/N$.
Where, if I am not mistaken:

*

*$H/H\cap N = \{H\cap N + h | h \in H\}$

*$HN/N = \{N+(h+n)|h \in H, n \in N\}$

A: Compose the maps
$$H\xrightarrow{\text{inclusion}}HN\xrightarrow{\text{quotient}}HN/N$$
Show that the composite map from $H$ to $HN/N$ is surjective. Observe that its kernel is $H\cap N$. Then apply the first isomorphism theorem.
(Incidentally, the fact that $H/(H\cap N)\cong HN/N$ is known as the second isomorphism theorem.)

A: Hint: Define $\phi:H \to \frac{HN}{N}$ by $\phi(h)=hN$ and show that this is surjective homomorphism whose kernel is $H\cap N$ and therefore from isomorphism theorem $\frac{H}{H\cap N}$ and $\frac{HN}{N}$ are isomorphic.


text:
Q: Add email attachments from string array I have some code that I am using to send an email with an attachment. The next thing I wanted to do was add attachments from a string array or a List. I had a google but I could only find attachments from byte arrays. Is it possible to do something like this?
Attachment[] attachments = new Attachment(string array);
mail.Attachments.Add(attachments);

I know that won't compile but just so you get the idea. Or is the only way to foreach an array and create attachments one at a time? Thanks.

A: There is no AddRange on an AttachmentCollection so you're out of luck doing it as a slick one-liner (short of creating an extension method).  You could use something like this:
string[] attachmentNames = ...

foreach(var attachment in attachmentNames.Select(n => new Attachment(n)))
{
    mail.Attachments.Add(attachment);
}


text:
Q: localStorage is saving html as [object HTMLDivElement] I want to save some html into localStorage

text

Here's what I tried:
var table = document.getElementsByClassName('table')[0]
localStorage.setItem("mykey", table)
console.log(localStorage)

https://jsfiddle.net/gdv60aoL/
what I'm getting is:
Storage {mykey: "[object HTMLDivElement]", length: 1}
What's [object HTMLDivElement]? Is this empty? I just want to store this as html.
Thank you in advance.

A: It is not empty, when you are logging, you are saying console.log(localStorage), if you would to see the real value, do console.log(localStorage.getItem("mykey")).
Also remember, localStorage only takes in string values, so you could do JSON.stringify, to convert it to a string.

A: Your variable is not a value, it's html element, use below example to do it.
var tableValue = document.getElementsByClassName('table')[0].value;
localStorage.setItem("myKey", tableValue);

A: You are almost there. If you want the complete block add outerHTML to the line that fetches the content. Everything else works.
var table = document.getElementsByClassName('table')[0].outerHTML
localStorage.setItem("mykey", table)

console.log(localStorage)

The outpus is as expected:
mykey: "

text

"

If you want only the paragraph element, then use .innerHTML.

A: The thing you save in localStorage is parsing of a HTML Object. Here you need to parse HTML Object into string and save it in to localStorage because localStorage stores data only in "key":"string" format (it means value must be in string data type)
To use HTML object as string:
var tableContent = table.outerHTML;
localStorage.setItem('myKey', tableContent);

Reference: outerHTML

A: It's showing up as '[object HTMLDivElement]' because you haven't serialized the object before storing it. Keep in mind that LocalStorage only stores string key-value pairs so whatever you store must be a string.
If what you were expecting is the html of the element, try:
var table = document.getElementsByClassName('table')[0]
localStorage.setItem("mykey", table.outerHTML)
console.log(localStorage)


text:
Q: Firebase on AWS Lambda Import Error I am trying to connect Firebase with an AWS Lambda. I am using their firebase-admin sdk. I have installed and created the dependancy package as described here. But I am getting this error on Lambda:
 Unable to import module 'index':
 Failed to import the Cloud Firestore library for Python.
 Make sure to install the "google-cloud-firestore" module.

I have previously also tried setting up a similar function using node.js but I received an error message because GRPC was not configured. I think that this error message might be stemming from that same problem. I don't know how to fix this. I have tried:
pip install grpcio -t path/to/...

and installing google-cloud-firestore, but neither fixed the problem. When I run the code from my terminal, I get no errors.

A: Part of the problem here is that grpcio compiles a platform specific dynamic module: cygrpc.cpython-37m-darwin.so (in my case). According to this response you cannot import dynamic modules in a zip file: https://stackoverflow.com/a/58140801

A: Updating to python 3.8 fix this for me

A: As Alex DeBrie mentioned in his article on serverless.com,

The plugins section registers the plugin with the Framework. In the custom section, we tell the plugin to use Docker when installing packages with pip. It will use a Docker container that's similar to the Lambda environment so the compiled extensions will be compatible. You will need Docker installed for this to work.

Which means, the environment is different between Local and Lambda, so the compiled extensions would differ. If use a container to contain packages installed by pip, the container would mimic the environment of Lambda, then everything would run well.
If you use Serverless Frame work to deploy your Python app to AWS Lambda, add these lines to serverless.yml file:
...
plugins:
  - serverless-python-requirements
...
custom:
  pythonRequirements:
    dockerizePip: non-linux
    dockerImage: mlupin/docker-lambda:python3.9-build
...

then serverless-python-requirements would automatically open a Docker container based on mlupin/docker-lambda:python3.9-build image.
This container would mimic the Lamda environment, let pip install and compile everything in it. So the compiled extensions will be compatible.
This worked in my case. Hope this helps.


text:
Q: How can I play a mp3 file in a Nodejs Replit? I have a mp3 file and I would like to play it when a button is pressed. But I belive I am not serving the file to the server correctly. Here is the code on Replit.com:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env['port'];
const admin = require('firebase-admin');
const express = require("express");
const path = require("path");

admin.initializeApp();

const db = admin.firestore();

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index/index.html');
});
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index/script.js');
});
app.get('/', (req, res) => {
    res.sendFile(__dirname + './index/ding.mp3');
});

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        if (msg === "ping") {
            io.emit('chat message', "pong");
        }
        io.emit('chat message', msg);
    });
    socket.on('serverLog', (m) => {
        console.log(m);
    });
    socket.on('loggedInWithName', (name) => {
        console.log('User Connected. Username: ' + name);
    });

});

http.listen(port, () => {
    console.log(`Socket.IO server running at http://localhost:${port}`);
});

Replit.com

A: I've tested the repl, and it works. Check your volume settings.
Tip. If you don't want to repeat res.sendFile for each static file, I recommend to use this notation:
app.use('/static', express.static(path.join(__dirname, 'public')))


text:
Q: TestNg/Selenium call by ant always return Cannot find class in the classpath I'm pretty new with this setup. And having issue to call my project with TestNG by ant.
I can run the testng.xml without any problem in Eclipse but I alway receive Cannot find class in classpath by ant.
Build.xml
<project basedir="." default="runTest" name="Ant file for TestNG">

<property name="src" location="src" />
<property name="bin" location="bin" />
<property name="telus" location="C:\ESP_Testware\ESP_Projects\Selenium\telus-pharma-integration-tests\src\test\resources\suite\local" />
<property name="libs" location="lib" />

<path id="class.path">
     <pathelement location="${libs}/testng-6.4.jar" />
     <pathelement location="${libs}/selenium-java-client-driver.jar" />
     <pathelement location="${libs}/selenium-server-standalone-2.39.0.jar" />
     <pathelement location="${bin}"/>
     <pathelement location="${telus}"/>

     </path>

<taskdef name="testng" classname="org.testng.TestNGAntTask">
<classpath>
<pathelement location="${libs}/testng-6.4.jar"/>
</classpath>
</taskdef>

<target name="runTest">

     <echo message="mkdir"/>

 <mkdir dir="testng_output"/><!-- Create the output directory. -->
     <echo message= "TestNg Start"/>
  <testng outputdir="testng_output" classpathref="class.path">
     <xmlfileset dir="${telus}" includes="testng.xml"/>
    <!--    <xmlfileset dir="." includes="TestNG2.xml"/> -->
   </testng>

</target>
 </project>

Testng.xml
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Bolt harness QA" verbose="1">
    <parameter name="test.env" value="qa" />
    <parameter name="selenium.url" value="https://www.google.com" />
    <!-- Valid values for browser: FF, IE, Chrome -->
    <parameter name="selenium.browser" value="Chrome" />

    <listeners>
        <listener class-name="com.gdo.test.integration.listener.SoftAssertTestListener" />
    </listeners>

    <test name="Test_MS_Website" preserve-order="true">
        <classes>

            <class name="com.gdo.telus.SC006">
                <methods>
                    <include name="Web_InvalidPassword" />
                    <exclude name="Web_LockedAccount" />
                </methods>
            </class>

        </classes>
    </test>
</suite>

My Class are at this path :
C:\ESP_Testware\ESP_Projects\Selenium\telus-pharma-integration-tests\src\test\java\com\gdo\telus
Thanks for your help.

A: Try my build.xml file, I did add the ReportNG plugin into this build.xml file to generate better looking reports instead of the default TestNG reports. You can just download the jar file for ReportNG and place it into your lib folder and it should still work fine:
<project name="Some Bullshit Goes Here" default="clean" basedir=".">

    <!-- Initilization properties -->
        <!-- <property name="lib.dir" value="${basedir}/lib"/> -->

<!-- using the ${basedir} allows you to use relative paths. It will use the working directory and add folders that you specify -->

    <property name="build.dir" value="${basedir}/build"/>
    <property name="lib.dir" value="hardcoded value can go here"/>
    <property name="src.dir" value="${basedir}/src"/>
    <property name="bin.dir" value="${basedir}/bin"/>
    <property name="output.dir" value="${basedir}/output"/>

<!-- I chose to hardcode the location where my jar library files will be, it will be used for compilation. Again you can set relative path if you wish.-->
<path id="assloadoflibs">
    <fileset dir="/automated/tests/library">
        <include name="*.jar"/>
    </fileset>
    <pathelement path="${basedir}/bin"/>
</path>

    <!-- setting libraries -->
    <target name="setClassPath">
        <path id="classpath_jars">
            <pathelement path="${basedir}/"/>
        <fileset dir="/automated/tests/library" includes="*.jar"/>
        </path>

    <!-- Convert jar collection from a given reference into one list, storing the result into a given property, separated by colon -->

    <pathconvert pathsep=":" property="test.classpath" refid="classpath_jars"/>
</target>

<target name="loadTestNG" depends="setClassPath">
<!-- Creating task definition for TestNG task -->
    <taskdef resource="testngtasks" classpath="${test.classpath}"/>

    </target>

    <target name="init">
    <!-- Creating build directory structure used by compile -->
        <mkdir dir="${build.dir}"/>
    </target>

    <target name="clean">
        <echo message="deleting existing build directory"/>
        <delete dir="${build.dir}"/>
    </target>

    <!-- In compile target dependency is given over clean target followed by init,
    this order makes sure that build directory gets created before compile takes place
    This is how a clean complile is achieved.
    -->

    <target name="compile" depends="clean,init,setClassPath,loadTestNG">
        <echo message="classpath:${test.classpath}"/>
        <echo message="compiling..."/>
        <javac destdir="${build.dir}" srcdir="${src.dir}" classpath="${test.classpath}"/>

    </target>

    <target name="run" depends="compile">

        <!-- testng classpath has been provided reference of jar files and compiled classes
        this will generate report NG report.
        -->

    <testng classpath="${test.classpath}:${build.dir}" outputdir="${basedir}/output" haltonfailure="false" useDefaultListeners="true" listeners="org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter" classpathref="reportnglibs">
<xmlfileset dir="${basedir}" includes="testng.xml"/>

<!-- This value here will show the title of the report -->
<sysproperty key="org.uncommons.reportng.title" value="Example Test Report"/>
        </testng>
    </target>
</project>

Here is my TestNG.xml file:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Example Test Suite">

<test name ="Example TestCase Name">
    <classes>
        <class name="packageName.JavaFilename"></class>
    </classes>
</test>
</suite>

A: I've found my answer on this site. I need to use maven to call my solution.
http://rationaleemotions.wordpress.com/2012/05/14/continuous-integration-with-selenium/
but thanx anyway for your help


text:
Q: Active Page not working Hello I am terribly sorry for the 'easy' question, it's just that I did this verbatim from the website and so I must be missing something painfully obvious. Ok so I have an li list and I want the first one to be yellow and the other elements to be white. I have for one of my rules in the real project li a { color: white but I am pretty sure that this specific class should override that rule, no? Any help would be appreciated, thanks.

.active{
 color: yellow;
}

#subnav {
 height: 10%;
 text-align: center;
}

#subnav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: green;
 text-align: center;
 width: 100%;
 font-weight: bold;

}

#subnav li {
    display: inline-block;
}

#subnav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

#subnav li a:hover {
   color: yellow;
}

 Overview

A: Add a more specific css selector to override the white color coming from #subnav li a like below:
#subnav li a.active {
  color: yellow;
}

and you will have the first li yellow if you have put active class to it.

.active {
  color: yellow;
}
#subnav {
  height: 10%;
  text-align: center;
}
#subnav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: green;
  text-align: center;
  width: 100%;
  font-weight: bold;
}
#subnav li {
  display: inline-block;
}
#subnav li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
#subnav li a.active {
  color: yellow;
}
#subnav li a:hover {
  color: yellow;
}

 Overview

 Test

A: Try this, it should work. Thanks
#subnav li a:hover,
#subnav li a.active {
   color: yellow;
}


text:
Q: show that the plane z=h intersects the surface S in an ellipse Have the equation
4x^2 + 9y^2 - z = 0
I'm asked to identify the type of surface. It's an Elliptic Paraboloid. I'm then asked to "Assuming h>0, show that the plane z=h intersects the surface S in an ellipse, and calculate the semi-axes of the ellipse." How am I meant to go about this?
Reshaping the equation gives me:
x^2/3^2 + y^2/2^2 = h/6^2
and that is about as far as I've gotten. Thanks

A: If $z=h>0$, the intersection will have equation
$$(\frac {2x}{\sqrt {h}})^2+(\frac {3y}{\sqrt {h}})^2=1$$
which represents an ellipse in the plane $z=h $.
thus the great axe is $a=\frac {\sqrt {h}}{2} $ and the small is $b=\frac {\sqrt {h}}{3} $.


text:
Q: Webpage keeps prompting to download I have my files hosted on my website. If I have a .php file the page loads fine, however, if I have a .html file with some php in it. EG:
<?php include 'nav.php'?>

and a .htaccess file with:
AddType application/x-httpd-php .html .htm

The page simply shows up blank in IE, Chrome and Firefox and has a download option for the page. This can be seen here. If you download this file, the php is still visible, and has not been run. Does anyone know why this is happening? Does anyone know how to fix it?
NOTE: Other .php files work fine, so PHP is obviously working. Can be seen by going to here


text:
Q: Selecting distinct values from a single column excluding Nulls Why does these two statements return Null values in the combobox?
This returns Null values:
str = "SELECT DISTINCT ColumnName FROM TableName WHERE ColumnName IS NOT NULL"
Me.comboList.RowSource = str

This also still returns Null values:
str = "SELECT ColumnName FROM TableName WHERE ColumnName IS NOT NULL " & _
"UNION " & _
"SELECT ColumnName FROM TableNamek WHERE ColumnName IS NOT NULL"
Me.comboList.RowSource = str

I want to return DISTINCT values ONLY excluding Nulls.
How do I fix it? Or is there a better way of doing it?
Thank you!


text:
Q: Parse XML with class information and instantiate via Reflection I have two XML Files that contain information about some classes. After parsing the XML i want to instantiate these classes via Reflection.
I parse the xml with DOM and Recursion. What i want to know is which is the most generic way to implement it. Which is the optimal way to transfer the information and build the GUI.
I really cannot think anything else expect many IF...ELSE(
like this:
if (node.getNodeName() == "class") {
      Class cls = Class.forName(node.getNodeValue());
}
)
statements but i do not think that this is the optimal way.
The dom parser:
 for (int count = 0; count < nodeList.getLength(); count++) {

        Node tempNode = nodeList.item(count);

        // make sure it's element node.
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {

            // get node name and value
            System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
            System.out.println("Node Value =" + tempNode.getNodeValue());

            if (tempNode.hasAttributes()) {

                // get attributes names and values
                NamedNodeMap nodeMap = tempNode.getAttributes();

                for (int i = 0; i < nodeMap.getLength(); i++) {

                    Node node = nodeMap.item(i);
                    System.out.println("attr name : " + node.getNodeName());
                    System.out.println("attr value : " + node.getNodeValue());
                    //    System.out.println("Node Value : " +);
                    if (node.getNodeName() == "class") {
                        Class cls = Class.forName(node.getNodeValue());
                    }
                }

            }

            if (tempNode.hasChildNodes()) {

                // loop again if has child nodes
                printNote(tempNode.getChildNodes());

            }

            System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");

        }

The XML files looks like this:
<ui-model>
<waui>
    <abstract-container wauiId = '1'>
        <abstract-button wauiId = '2'></abstract-button>
        <abstract-button wauiId = '3'></abstract-button>
        <abstract-button wauiId = '4'></abstract-button>
    </abstract-container>
</waui>
<wrm>
    <wr-item wauiId = '2'>
        <abstract-properties>
            <abstract-property name='text'>Button1</abstract-property>
        </abstract-properties>
        <polymorphic-properties>
            <polymorphic-instance piId='swingRectButton'>
                <polymorphic-property name='width'>100</polymorphic-property>
                <polymorphic-property name='height'>50</polymorphic-property>
            </polymorphic-instance>
            <polymorphic-instance piId='swingRoundButton'>
                <polymorphic-property name='radius'>80</polymorphic-property>
                <polymorphic-property name='background-color'>red</polymorphic-property>
            </polymorphic-instance>
        </polymorphic-properties>
    </wr-item>
    <wr-item wauiId = '3'>
        <abstract-properties>
            <abstract-property name='text'>Button2</abstract-property>
        </abstract-properties>
        <polymorphic-properties>
            <polymorphic-instance piId='swingRectButton'>
                <polymorphic-property name='width'>200</polymorphic-property>
                <polymorphic-property name='height'>60</polymorphic-property>
            </polymorphic-instance>
        </polymorphic-properties>
    </wr-item>
    <wr-item wauiId = '4'>
        <abstract-properties>
            <abstract-property name='text'>Button3</abstract-property>
        </abstract-properties>
        <polymorphic-properties>
            <polymorphic-instance piId='swingRoundButton'>
                <polymorphic-property name='radius'>9</polymorphic-property>
                <polymorphic-property name='background-color'>blue</polymorphic-property>
            </polymorphic-instance>
        </polymorphic-properties>
    </wr-item>
</wrm>

<widget name='abstract-button'>
<abstract-properties>
    <property name='text' id='wsl_1'/>
</abstract-properties>
<polymorphic-instances>
    <instance name='swingRectButton'>
        <polymorphic-properties>
            <property name='width' />
            <property name='height' />
        </polymorphic-properties>
    </instance>
    <instance name='swingRoundButton'>
        <property name='radius' />
        <property name='background-color' />
    </instance>
</polymorphic-instances>

<polymorphic-instances-api>
    <polymorphic-instance id='swingRectButton' class='javax.swing.JButton'>
        <property name='text'>
            <native-method>setText</native-method>
            <param-type>String</param-type>
        </property>
        <property name='width'>
            <native-method>setWidth</native-method>
            <param-type>Integer</param-type>
        </property>
        <property name='height'>
            <native-method>setHeight</native-method>
            <param-type>Integer</param-type>
        </property>
    </polymorphic-instance>
    <polymorphic-instance id='swingRoundButton' class='gr.epp.aswing.RoundButton'>
        <property name='text'>
            <native-method>setLabel</native-method>
            <param-type>String</param-type>
        </property>
        <property name='radius'>
            <native-method>setRadius</native-method>
            <param-type>Integer</param-type>
        </property>
        <property name='background-color'>
            <native-method>setBackgroundColor</native-method>
            <param-type>String</param-type>
        </property>
    </polymorphic-instance>
</polymorphic-instances-api>

A: I thought about writing this as a comment to your question, but after more thought, I think it is an appropriate answer.
Avoid premature optimization.
If you've already written code that works and you're running into a specific problem then explain that problem. But you should not try to optimize your code unless there is an identifiable problem with it.
See http://c2.com/cgi/wiki?PrematureOptimization


text:
Q: Block user registration by country ip range I have the following table in MYSQL
CREATE TABLE IF NOT EXISTS `countryip` (
`ip_from` bigint(10) unsigned NOT NULL DEFAULT '0',
`ip_to` bigint(10) unsigned NOT NULL DEFAULT '0',
`country_iso2` varchar(2) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_iso3` varchar(3) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_name` varchar(32) COLLATE utf8_bin NOT NULL,
KEY `ip_from` (`ip_from`,`ip_to`))
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

And here i have added the entire ip ranges of all countries in the world.
I want to make in php a script that will compare the user ip with the ip range from this database and after that echo a message.
From what i undestood i need to start by declaring
<?php
    mysql_select_db("database_name")   or die(mysql_error());
$ip = $_SERVER['REMOTE_ADDR'];
    $query = mysql_query("SELECT `IP` FROM `ban_ip` WHERE `IP` = '$ip'"); // this works only if i have the single static ip in the dbs, but now i have the ip range
    if (mysql_num_rows($query) > 0)
    {
echo ' <!DOCTYPE html> <html> <head> <script type="text/javascript"> alert("You are not allowed to access this website"); window.location.replace("index.php"); </script> </head> <body> </body> </html>';
    }

What can i do instead of this query
$query = mysql_query("SELECT `column` FROM `table` WHERE `column` = '$ip'");

in order to make possible the comparison between the User IP and the ip range.
And the IP FROM column, TO IP column looks like this
16777216, 16777471,
In order to find out the ip there was a formula similar with ip = 256 + CLASS B * 256 + CLASS C * 256 * 256 + CLASS D * 256 * 256 * 256

A: You could use the following SQL query for the table you have specified:
SELECT `country_iso2` FROM `countryip` WHERE `ip_from` <= inet_aton('$ip') AND ip_to >= inet_aton('$ip')

This will select the two character country ISO code for the IP address that you have specified.  From here it is a simply matter of comparing the the ISO code with the entries from a banned country code table.

A: I know it's not an direct answer to your question, but I used this API lately;
http://ipinfodb.com/ip_location_api_json.php
Very easy to use with JSON and also fast reply from the server. It's free, try it out, would save you some storage in your database.

A: Not a direct answer to the question, but maintaining IP database yourself is a bit of a hassle in my experience.
I have used MaxMind's free GeoLite2 database for this, as it is updated quite often and provides pretty precise results:
https://github.com/maxmind/GeoIP2-php

A: I would recommend using the PHP Extension API if you are concerned at all about performance. You can get upwards of 7 million queries per second with the PHP (C API) extension. MySQL is not tuned for these types of queries and managing the changing IP address updates via SQL can become a pain point. Maxmind releases monthly updates that you can easily download.
I describe how to compile the extension, and how to use the mmdb databases in PHP to restrict countries by iso-3316 2-character codes here:
Intro to Maxmind GeoLite2 with Kohana PHP


text:
Q: Is there a way other than eval to prevent my perl scripts from terminating on errors I am coding a web API that uses a MongoDB database, interacts with node.js and starts all types of processes, anything can go wrong and if it does I want the api to return an "unknown error" message to the caller.
The problem is that sometimes the modules I'm using crash and the whole application dies without giving the api the opportunity to return an "Unknown error" message I want to control this without having to put an eval block in every database insert, process call, etc.
is there something like autoeval ?

A: If your process is crashing, something is very wrong, and you should look into why that is and fix it.
But failing that, do all your work in a child process, and have the parent monitor it and return an error response.
Though even easier than that is running your service behind a proxy server (which you may very well be doing anyway) and ensuring that the proxy server returns an appropriate api response on proxy errors.


text:
Q: Inheritance and known type issue I'm trying to use protobuf .net to serialize an instance of a class which is inherited from a base class. When trying to serialize\deserialize i'm getting an exception about "type not expected". As I already read, adding the protoinclude with the derived type to the base wil solve the problem. BUT, my problem is that I can't add the attribute, since I don't know the types that will  derive my base. As I already read, I understand that V2 is going to provide a way to define a type model in order to describe inheritance. So my questions are:

*

*When V2 release will be avilable?

*Is there a workaround in the mean time to solve this issue?

Thanks in advance,
Gil

A: V2 is available both from nuget and google-code (nuget is a few revs ahead IIRC - and both are a little behind the head). There are a few v1 features not yet re-implemented, but for most purposes you won't notice this. They will be re-added in due course.
Re your problem; that is available via MetaType.AddSubType - however, to use that approach you must be able to reproduce the same int identifiers per-subtype in the future - they are important keys and must not change.
RuntimeTypeModel.Default[typeof(SomeType)].AddSubType(7, subType);

There is also DynamicType available on "object" properties - however this has a few kinks with inheritance-based models; I would avoid that for now (this too will be rectified shortly).


text:
Q: JavaScript nested loop unexpected result I would expect the following code to return the result (matrix)
[ [0,0], [0,0,0,0], [0,0,0,0,0,0] ]
function zeroArray(m, n) {
  let newArray = [];
  let row = [];
  for (let i = 0; i < m; i++) {

    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

but it returns:
[ [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0] ]
I cannot see how row is [0,0,0,0,0,0] for each iteration of the outer loop?
I see row iterating from [0,0] to [0,0,0,0] to [0,0,0,0,0,0] and pushing to newArray on each instance.  However, this is evidently wrong.
Can anyone explain this result for me?

A: You could push a copy of row. This eliminates the same object reference.

function zeroArray(m, n) {
  let newArray = [];
  let row = [];
  for (let i = 0; i < m; i++) {

    for (let j = 0; j < n; j++) {
      row.push(0);
    }
    newArray.push([...row]);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

A: The bounds checking was wrong in the inner loop according to your output, in each iteration of the outer loop allocate a new array of i * 2 length.
You can use Array.prototype.fill to simplify your code more.

function zeroArray(m, n) {
  const newArray = [];
  for (let i = 1; i <= m; i++) {
    const row = new Array(i * 2).fill(0);
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

A: Your inner loop is run for every value of n, then again for every value of m in the out loop.
For every number in M > Run every number in N and push to row. 3*2 gives 6 results in that table.


text:
Q: Is BlockingQueue useful for implementing a producer/consumer system? I have two threads that read two files. Each thread collects information from objects. As the two threads continue to read the file, I want to add the generated objects to a map or a temp list which are shared by the threads, and I want to process the added objects from the map/temp list simultaneously as they are added.
I am interested in using producer/consumer model for this. But will it be the way to use it on a process which itself depends on two threads? Can BlockingQueues be used in these cases?

A: BlockingQueue is definitely what you want. Just as described in BlockingQueue
"BlockingQueue implementations are designed to be used primarily for producer-consumer queues, but additionally support the Collection interface."

A: Unless the files are too large to fit into memory, you would be better off reading all of file1 into memory, then reading all of file2 into memory, then processing them - ideally this will require only two disk seeks.  If you try to read both files simultaneously then you're going to cause the disk head to do a lot of seeks between the two files.
If the files are too large to fit into memory, then read a chunk of File1, then read a chunk of File2, then process the chunks and null their references so the garbage collector can take care of them; repeat until the files have been completely processed.
Once the files are read into memory you can process them in parallel, and then a BlockingQueue would be an appropriate data structure.


text:
Q: TikZ: Complicated Flow Chart I do know how to build easy flow charts with TikZ, but now I'm completely overextended with this one. I need to rebuild the following Flow Chart. It doesn't need to look exactly like it, but the structure should be the same. I would really appreciate every help!
My main questions are:

*

*I have my tikzpicture inside a figure environment and I would like to have my whole tikzpicture rotated by 90 degree (landscape). How do I do this?

*Can I build a Flow-Chart inside a node like you can see in the figure?

*Is it possible to create this nice looking headline boxes on top of the actual node-boxes?

My Code so far:
\documentclass{article}

\usepackage{tikz} %für Flow Charts
\usetikzlibrary{shapes.geometric, arrows, positioning, calc, matrix}

\begin{document}

\begin{figure}[!h]
\centering
\tikzstyle{process} = [rectangle, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=orange!25]
\tikzstyle{block} = [rectangle, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=blue!25]
\tikzstyle{line} = [draw, very thick, color=black!80, -latex']

 \begin{tikzpicture}[scale=1.0, align=center, on grid, auto],
% Place nodes
\node (A) [block] {header \\ formular \\ formular \\ text \\ formular };
\node (B) [process, right of=A, node distance=7.0cm] {text \\ formular};
\node (C) [process, right of=B, node distance=7.0cm] {header \\ formular \\ formular};
\node (D) [process, below of=A, node distance=5.0cm] {header \\ text \\ formular};
\node (E) [block, right of=D, node distance=14.0cm] {header \\ formular \\ formular \\ text \\ forular};

% Draw edges
\path [line] (A) -- (C);
\path [line,dashed] ($(A.east)+(0.2,0)$) |- (B);
\path [line,dashed] (B.east) -| ($(C.west)-(0.2,0)$);
\path [line] (C) -- (E);
\path [line,dashed] ($(E.west)-(0,1)$) -| (D.south);
\path [line,dashed] (D) -- (A);
\end{tikzpicture}

\caption{caption}

\end{figure}

\end{document}

A: To answer the questions in order:

*

*Rotating a figure is relatively easy.  Add \usepackage{rotating} and change the figure environment to a sidewaysfigure one.

*You can add most things within a TikZ node.  For your particular question, I would suggest something along the lines of:
\node[text width=5cm,rectangle,draw,rounded corners] (outerNode) {
    \begin{tikzpicture}
        \node[text width=2cm,draw] (innerNode1) {$A$};

        \node[text width=2cm,draw,above of=innerNode1] (innerNode2) {$B$};

        \path[line] (innerNode1) -- (innerNode2);
        \path[line] (innerNode2) -- (innerNode1);
    \end{tikzpicture}
};

which will result in something along the lines of:

*Again, similar to the above answer, you can add a lot of different things to a node.  In this case I would suggest \usepackage{tcolorbox}, and then having:

    \node[text width=5cm] (node:1) {
        \begin{tcolorbox}[%
            title={Node title},
            width=\textwidth
        ]
            Box interior text.
        \end{tcolorbox}
    };

which would result in something like:

There are lots of different skins, etc. you can alter the tcolorbox by to suit your styles.

A: For my answer (and these are just examples on how one could do it),
you need

*

*from my tikz-ext package package

*

*the ext.positioning-plus library,

*the ext.paths.ortho library and its ortho/install shortcuts key
for the shortcuts -|, |-, -* and |* and

*the ext.node-families library
with its sublibrary ext.node-families.shapes.geometric that also loads

*the shapes.geometric library for the ellipse shape,

*the fit library (loaded by ext.positioning-plus),

*the backgrounds library to draw stuff behind other stuff and

*the calc library for some funny coordinate calculations.

Code
\documentclass[tikz]{standalone}
\usetikzlibrary{
  arrows.meta,                        % for arrow tips
  backgrounds,                        % for background layer
  ext.paths.ortho,                    % for ortho paths
  ext.positioning-plus,               % for
  ext.node-families.shapes.geometric, % loads ext.node-families and
% shapes.geometric,                   % for ellipse
  calc}                               % for ($<calculations>$)
\tikzset{
  basic box/.style={
    shape=rectangle, rounded corners, align=center, draw=#1, fill=#1!25},
  header node/.style={
    node family/width=header nodes,
    font=\strut\Large\ttfamily,
    text depth=+.3ex, fill=white, draw},
  header/.style={%
    inner ysep=+1.5em,
    append after command={
      \pgfextra{\let\TikZlastnode\tikzlastnode}
      node [header node] (header-\TikZlastnode) at (\TikZlastnode.north) {#1}
      % the next node contains both \tikzlastnode and its header
      % this is needed so that h-<name> can be used to connect lines
      node [span=(\TikZlastnode)(header-\TikZlastnode)]
           at (fit bounding box) (h-\TikZlastnode) {}
    }
  },
  fat blue line/.style={ultra thick, blue}
}
\begin{document}
\begin{tikzpicture}[
  node distance=1cm and 1.2cm,
  thick,
  nodes={align=center},
  >={Latex[scale=.9]},
  ortho/install shortcuts]

\path[node family/width=loop]
  node[shape=ellipse, fill=red]       (imp-sol) {ellipsoid box}
  node[fill=yellow, below=of imp-sol] (rec-box) {
    rectangular box, and very wiiiiiiiiiiiiiiide \\ 2nd line};
\node at ($(imp-sol.west|-imp-sol.south)!.5!(rec-box.north west)$) [
  shift=(left:.5*x_node_dist)]  (for-1) {formula 1};
\node at ($(imp-sol.east|-imp-sol.south)!.5!(rec-box.north east)$) [
  shift=(right:.5*x_node_dist)] (for-2) {formula 2};

\scoped[on background layer]
  \node[
    basic box=blue, header=DMFT loop,
    fit=(for-1)(for-2)(imp-sol)(rec-box)] (dmft-l) {};

\path[very thick, blue, -|] (rec-box) edge[->] (for-1) edge[<-] (for-2)
                            (imp-sol) edge[->] (for-2) edge[<-] (for-1);

\node[
  basic box=green, header=DMFT prelude,
  east above=of dmft-l] (dmft-p) {
    Math and text math and text math and text \\
    math and text math and text math and text};
\node[
  basic box=green, header=$\rho$ update,
  north left=of dmft-l,  shift=(down:y_node_dist)] (rho) {
    Much more text much more text \\ much more text much more text};
\node[basic box=blue, header=DFT part, anchor=north] at (dmft-p.north-|rho)
  (dft) {So much text so much text so much text \\
            I think I need \texttt{tikz-lipsum} \\ or something like that.};
\node [basic box=green, below=+0pt of (dft.north east)(dmft-p.north west)]
  (upd) {update\\$math$};

\coordinate (dmft-p-sse) at ($(dmft-p.south)!.5!(dmft-p.south east)$)
 coordinate (dmft-l-ssw) at ({$(rho.south)!.5!(dmft-l.south)$}-|dmft-l.south west)
 coordinate (dmft-p-ssw) at ({$(upd.south)!.5!(dmft-p.south)$}-|dmft-p.south west);

\path[fat blue line, ->]
  (rho) edge[<-, dashed, |-] (dmft-l-ssw)
  (dmft-p-ssw) edge[<-, -*] coordinate[pos=.15] (@s)
                            coordinate[pos=.85] (@e) (dft)
  {[every edge/.append style=dashed, |-] (@s) edge[<-] (upd)
                                         (@e) edge     (upd)}
  (h-rho)      edge[dashed] (dft)
  (dmft-p-sse) edge[|*]     (dmft-l);
\end{tikzpicture}

Output


text: Q: Which expression is more polite? Could you or can you? If I can't find something in a grocery, which question is more polite? "Could you tell me where I can find the mouthwash?" or "Can you tell me where I can find the mouthwash?"  And I'm not sure "Could you tell me ...." is a common expression for asking or needing help.


text:
Q: change boolean field to True after Payment? I use stripe Api Payment method and I have a boolean filed in my database called ordered set to False
I just want it to be True after payment
Here is my views.py:
class OrderSummary(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        order = Order.objects.get(user=self.request.user) #this is to bring the order
        delivered = order.ordered
        YOUR_DOMAIN = "http://127.0.0.1:8000"
        checkout_session = stripe.checkout.Session.create(
         payment_method_types=['card'],
             metadata={
                "order_id":order.id,
                "order":order,
                "delivered":delivered
            },
            mode='payment',
            success_url=YOUR_DOMAIN + "/",
            cancel_url=YOUR_DOMAIN + "/",
        )

        return JsonResponse({'id': checkout_session.id})

And here is after payment webhook views:
@csrf_exempt
def stripe_webhook(request):
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None
    try:
        event = stripe.Webhook.construct_event(
        payload, sig_header, endpoint_secret
        )

    except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return HttpResponse(status=400)
    if event['type'] == 'checkout.session.completed': #this is to bring the order
        session = event['data']['object']
        customer_email = session["customer_details"]["email"]
        orders =session["metadata"]["delivered"]
        orders=True
        orders.save()
        print(session)
    # Passed signature verification

    return HttpResponse(status=200)

but I got this error
AttributeError: 'bool' object has no attribute 'save'

A: This is because you can not .save() a variable (orders here) , you must .save() the model, so you must retrieve the Order object and set its ordered to True and then .save() the Order object.

A: You are calling save on a variable which is not your model object.
Try:
Order= OrderSummary.Objects.get(id=id)
Order.Ordered=True
Order.save()


text:
Q: Can't make changes in my production Rails project using Capistrano,Puma,Nginx i can't make changes in my production Rails project using Capistrano,Puma,Nginx.
I was commited into git and use 'cap production deploy' , after restart the server with 'sudo service nginx restart'. My changes don't apply.
deploy.rb
    lock '3.5.0'

set :repo_url, '...'
set :scm, :git
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp

set :user, 'deployer'
set :application, 'MyApp'
set :rails_env, 'production'
server '...', user: "#{fetch(:user)}", roles: %w{app db web}, primary: true
set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :pty, true
set :deploy_via, :remote_cache
set :linked_files, %w{config/database.yml}
set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml', 'config/puma.rb')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'public/uploads')

set :config_files, %w{config/database.yml config/secrets.yml}
set :puma_conf, "#{shared_path}/config/puma.rb"

namespace :git do
  desc 'Deploy'
  task :deploy do
    ask(:message, "Commit message?")
    run_locally do
      execute "git add -A"
      execute "git commit -m '#{fetch(:message)}'"
      execute "git push"
    end
  end
end

namespace :deploy do
  before 'check:linked_files', 'config:push'
  before 'check:linked_files', 'puma:config'
  before 'check:linked_files', 'puma:nginx_config'
  before 'deploy:migrate', 'deploy:db:create'
  after 'puma:smart_restart', 'nginx:restart'
end


text:
Q: Domain classes not visible to Data layer (Application context class ) To make data-layer be aware of my domain classes, I've added a reference between the two class libraries, HMSContext (i.e., data-layer) and Hms.Entities (i.e., domain-classes).
Following is code from HMS.Entities:
namespace HMS.Entities
{
    class Accomodation
    {
        public int ID { get; set; }
        public int AccomodationPackageID { get; set; }
        public AccomodationPackage AccomodationPackage { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

Code from HMSContext.cs:
using System.Data.Entity;

namespace HMS.Data
{
    public class HMSContext : DbContext
    {
        public DbSet<Accomodation> Accomodations { get; set; }

    }
}

I've added a reference between these two .dlls. A snapshot showing this is attached here. For some reason, HRMContext.cs is not reading HMS.Entities despite added reference. Am I missing anything? Can someone please shed light on this. Thanks in advance.

A: You are using using System.Data.Entity; where it is not related to your project structure. So add HMS.Entities too.
Any time you have such a problem, try using the full namespace and check if it is correct or not.
Note that you also have refactoring capabilities too. You can use ( Ctrl + . ) and Visual Studio helps you to use the correct namespace.
Your code has to be like this:
using System.Data.Entity;
using HMS.Entities;

namespace HMS.Data
{
    public class HMSContext : DbContext
    {
        public DbSet<Accomodation> Accomodations { get; set; }
    }
}

And for the Entity class you should use public keyword:
namespace HMS.Entities
{
    public class Accomodation
    {
        public int ID { get; set; }
        public int AccomodationPackageID { get; set; }
        public AccomodationPackage AccomodationPackage { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}


text:
Q: How to customize the_archive_title()? Cannot figure out how to change the value it produces I've searched the web for help on this, I found similar questions, but not exactly what I'm looking for. Hopefully someone can help.
The following code is in my theme's archive.php file:

<?php
    the_archive_title( '
', '
' );
    the_archive_description( '
', '
' );
?>

the_archive_title section of the code is causing the following text to appear on my WP page:

*

*Archives: Projects

It's formatted a certain way where the text is large and bold. It looks really nice however, I want to change the value of this. I want it to display the following instead:

*

*Viewing All Offices

I've literally have tried to do everything. I'm a bit of a noob at WP, but this is my first time doing this. I could not figure how how to change the text value to that.
If someone can please help me out, that would be great. Looking for the most cleanest and secure solution.

A: I've always found that the best way to learn about how WP works and how you can modify it is to search the Codex at https://codex.wordpress.org/
For example, first I find the Codex page for the_archive_title() and there I see that it's a wrapper for get_the_archive_title() and there, looking at the source code, I see that at the end of the function the result is returned through a filter also called get_the_archive_title.
So, now I know I can affect the output using that filter, I can write a little function to add to my theme's functions.php file to hook into that:
function change_my_title( $title ){
    if ( $title == "Archives: Projects" ) $title = "Viewing All Offices";
    return $title;
}
add_filter( "get_the_archive_title", "change_my_title" );

Hope that helps


text:
Q: Overlapping Transactions Apolgies in advance if this has been discussed before, or is even fundamental enough for it to be outlined on, say, Wikipedia. I just felt that asking would be more efficient!
Anyway, I want to ask about transactions, from a theoretical point of view. In particular, say we have two (or more) users looking at a dataset and the following occur at the times indicated (tX):
t0   User1 starts a transaction
t1   User2 starts a transaction
t2   User1 runs a DML operation on the dataset
t3   User2 runs a different DML on the same dataset
t4   User1's operation finishes and is committed
t5   User2 commits

My question is: how do the DML operations run between User1 and User2 interact with each other? Does the operation started at t2 by User1 operate on the data as it was defined at the start of their transaction (i.e., at t0), and likewise for User2's operation, so that there is no interaction? Or, if say User1 committed their operation after User2's transaction had started but before they had started their operation, would the data User2 was looking at be updated respectively? Moreover, how is consistency maintained in the case of any conflicts?

A: For all general cases, the second transaction will be blocked until the first one commits or rolls back. As Martin notes, your isolation level may affect this, but the entire point of ACID compliance is to keep them separate.


text:
Q: Preventing changesets with files matching .hgignore patterns from being pushed to an hg repo How can I prevent changesets (from the source repo) with files matching .hgignore patterns (in the head of each respective target branch in the target repo) from being pushed to an hg repo?
It looks like the ACL Extension can deny pushes based on file name globs, but I prefer to keep [acl.deny] in hgrc in sync with .hgignore.
Can the ACL Extension read .hgignore, and use it to specify file selectors for [acl.deny]?
If not, is there any existing script to sync .hgignore patterns to [acl.deny]?
Is there any other way to achieve this (other than manual syncing)?


text:
Q: Argument of type '""' is not assignable to parameter of type '"prototype"' jasmine Update:
Seems the following works:
let gaService = TestBed.get(GAService);

and spy on gaService.
I am really blank on what I am missing exactly here. The service sends data to google analytics so i have to mock it during my tests. The service itself is:
import { Injectable } from '@angular/core';
import { CoreService} from "./core.service";

@Injectable()
export class GAService {
  constructor(
    public coreService: CoreService
  ) { }

  public sendException (
    description: string,
    isFatal: boolean
  ) : Promise<any> {

    let promise = new Promise((resolve, reject) => {

      (<any>window).ga('send', 'exception', {
        'exDescription': description,
        'exFatal': isFatal
      });
    });

    return promise;
  }

}

and it is mocked like this:
import { Injectable } from "@angular/core";
@Injectable()
export class MockGAService {
  constructor() {}

  sendException(
    description: string,
    isFatal: boolean
  ): Promise<any> {
    return Promise.resolve(true);
  }

}

now during my tests, I have an event that will raise an exception and I want to make sure the sendException is indeed called, so I spied on the event like this:
let preventDefaultSpy = spyOn(
  GAService,
  "sendException"
);

but it doesn't compile at all with the message:
Argument of type '"sendException"' is not assignable to parameter of type '"prototype"'

The only way I get it to compile is if i do:
let preventDefaultSpy = spyOn(
  GAService.prototype,
  "sendException"
);

but then it is never called when I do:
expect(preventDefaultSpy).toHaveBeenCalled();

just for check, I did a console output on sendException() of the mock and it shows output, hinting it was indeed called.
What am I doing wrong?

A: Jasmine spyOn installs a spy onto an existing object, in your example however you provide a class (first argument).
let preventDefaultSpy = spyOn(GAService, "sendException").and.returnValue(Promise.resolve(true));

Hence your test could be rewritten as follows (no need of MockGAService):
const service = TestBed.get(GAService);
spyOn(service , "sendException").and.returnValue(Promise.resolve(true));

// do some stuff that is expected to invoke GAService.sendException

expect(service.sendException).toHaveBeenCalled();


text:
Q: UIGraphicsEndImageContext could not be resolved while running Swift through command line I am running Swift through the command line:
xcrun swift -sdk $(xcrun --show-sdk-path --sdk iphonesimulator --find clang) -

Then I am passing in
import UIKit
UIGraphicsBeginImageContextWithOptions(CGSizeMake(500, 500), false, 0.0)
UIColor.blackColor().setStroke()
let path = UIBezierPath()
path.moveToPoint(CGPointMake(100, 0))
// some path stuff...
path.dynamicType
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();

The compiler is returning:
LLVM ERROR: Program used external function '_UIGraphicsEndImageContext' which could not be resolved!

Is there a way that I can run this and include the needed libraries to run UIGraphicsGetImageFromCurrentImageContext()?
I tried finding the way to include other libraries but I thought that this method would be included in UIKit.
EDIT
I tried adding in frameworks to the command but I am not sure what framework I'd need to add. I tried the following.
xcrun swift -v -F /Applications/Xcode.app/Contents/SharedFrameworks -F /Applications/Xcode.app/Contents/OtherFrameworks -F /Applications/Xcode.app/Contents/Frameworks -sdk $(xcrun --show-sdk-path --sdk iphonesimulator --find clang)

This did not work either.
NOT A DUPLICATE
This is not a duplicate of this question because this is able to import UIKit and Foundation. If you write the following code for the REPL it works:
import Foundation
import UIKit
print("works")

In that case it does not throw errors. I also posted an answer there which works.


text:
Q: Unable to locate and login to by PostgreSQL I am using Ubuntu 20.04 LTS, and I have configured PostgreSQL 9.5 to work on the server. I am trying to log in but I have forgotten the password for the user postgres and therefore I tried to reset it by using the suggestions in the forum.
As it did not work for me I tried to check what was happening. First, I saw that I have two services of PostgreSQL available on my server: 10 and 9.5. PostgreSQL 10 is configured to be running in docker while 9.5 is running in the server (for 2 different applications). This can be seen in the screenshot below:

I stopped PostgreSQL using:  sudo systemctl stop postgresql and when I check for the status of the service, it has already stopped. This can be seen in the image below:

Even after stopping the PostgreSQL service, I saw that my applications were running correctly and I could access all the data in both applications. Then I try to see if there is anything running in port 5432 where my PostgreSQL service is configured to run and I see the following:

The PostgreSQL service is running but I do not know where it is located. Does anybody here have an idea, how to solve this problem without losing the data from both databases?

A: you can probably find it with ps -efl|fgrep /postgre.

0 S postgres    1080       1  0  80   0 - 41587 -      Sep11 ?        00:00:03 /usr/local/pgsql/bin/postgres -D data

In this case, since the argument to -D was a relative path not an absolute one, the answer is not totally complete.  But at least you know the name of the directory to search for, you can use find or some other OS tool to search.


text:
Q: Trigger function on deserialization I have a class with a number of fields which are normally calculated in the constructor from other data in the class. They are not serialized to XML because any changes to the rest of the data will likely require their recalculation.
Is there a way I can set up a function call to be triggered on deserialization?

A: What you are describing is [OnDeserialized]
XmlSerializer does not support serialization callback methods (at least, not in MS .NET; mono may be different). Depending on your needs, you could try DataContractSerializer which does support serialization callbacks (as do a number of other serializers). Otherwise, your best approach may be to just have your own public method that you call manually.
Another option is to manually implement IXmlSerializable, but this is hard.

A: -- Edit:
Just confirmed that, as the commenter below says, the xml serialisation process doesn't hit the 'OnDeserialized'-attribute-declared method. Which is a shame.
-- Previous response:
Yes indeed, take a look here.
Specifically of interest would be the OnDeserialized attribute, discussed here.
It may be worth noting that, depending on the serialization method used (I think) your no-arg constructor will be called. Obviously, this will happen before anything else is set. So it's probably not entirely useful.

A: Since an object that can be XML serialized need a public parameterless constructor, it seems you have a hole in your class design even before you hit XML serialization.
Personally I would go with lazy calculation of those fields. Store a flag inside the class whether you have calculated the fields or not, and set that field to a value signifying "out of date" when any of the properties that are used in the calculation is changed. Then, in the properties that return the calculated values, check if you need to recalculate before returning the value.
This would then work regardless of XML serialization or not.
example:
[XmlType("test")]
public class TestClass
{
    private int _A;
    private int? _B;

    public TestClass()
        : this(0)
    {
    }

    public TestClass(int a)
    {
        _A = a;
    }

    [XmlAttribute("a")]
    public int A
    {
        get { return _A; }
        set { _A = value; _B = null; }
    }

    [XmlIgnore]
    public int B
    {
        get { if (_B == null) Recalculate(); return _B; }
        set { _B = value; }
    }

    private void Recalculate()
    {
        _B = _A + 1;
    }
}

A: You can implement IDeserializationCallback interface


text:
Q: c# Insert/Update multiple lookup values to an SPListItem sharepoint allows multiple items to be added for a lookup column type. Is there a good article that has the code snippet to update or add lookup values?

A: Take a look at this object SPFieldLookupValueCollection. What you need to do is to create an instance of this class, fill the collection with SPFieldLookupValue objects and assign the collection to the field, that's it.
http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/02c889fc-6b15-4a60-b0f6-ed5d020ec6c2


text:
Q: "Save for later" for articles and publishing pages, where does it save? I'm planning to make a custom web part that using the users articles/pages that they have "saved for later". However, I have no clue to WHERE to get this information, or where its stored.
The "save for later" can be found on the social bar.

A: "Save for later" Favorites are added and read via an undocumented API and thus not recommended for production.
If you go to F12 Dev tools you might discover calls similar to these:
https://TENANT_REGION-sphomep.svc.ms/api/v1/documents/saveForLater?start=0&count=20
You can get the URL of the endpoint for your region and the token by calling /_api/sphomeservice/context?$expand=Token from a SharePoint page.

After you have a token, endpoint URL and and your absolute site URL, you need to add two headers to all your GET calls:
headers: {
'authorization': `Bearer ${token}`,
'sphome-apicontext': `{"PortalUrl":"${this.props.context.pageContext.site.absoluteUrl}"}`
}

Send your GET request to https://REGION-sphomep.svc.ms/api/v1/documents/saveForLater?start=0&count=20
Update
Adding "Save for later": requres a GET call to /api/v1/documents/saveForLater/addwith these URL params: siteId, webId, listId, uniqueId

https://REGION-sphomep.svc.ms/api/v1/documents/saveForLater/add?siteId=765d4b61-1bc6-42b7-9667-94c343fbf859&webId=93e10f19-d8b4-491e-90d8-c3e766fbe497&listId=0ba06207-75ff-4aa9-87c7-f859dec39bcc&uniqueId=70e6835b-5ee0-4581-bb73-0c2ed3c43044

Removing "Save for later": requres a GET call to /api/v1/documents/saveForLater/remove with these URL params: siteId, webId, listId, uniqueId
Removing "Save For later": (siteId, webId, listId, uniqueId)

https://REGION-sphomep.svc.ms/api/v1/documents/saveForLater/remove?siteId=765d4b61-1bc6-42b7-9667-94c343fbf859&webId=93e10f19-d8b4-491e-90d8-c3e766fbe497&listId=0ba06207-75ff-4aa9-87c7-f859dec39bcc&uniqueId=70e6835b-5ee0-4581-bb73-0c2ed3c43044


text:
Q: Using JQuery to separate out the "value" parameter data of a selected option? I have a Select object that gets the Option value dynamically populated with a set of numbers.  The code for that looks like:
<select name="TheServices" id="services-selector">
     <option value="" disabled selected hidden>Static Selection</option>
     <option value="6398 6390" title="Service 1" data-description="desc info here">Service 1 Description</option>
     <option value="6399" title="Service 2" data-description="desc info here">Service 2 Description</option>
     <option value="6398 6390 6399" title="Service 3" data-description="desc info here">Service 3 Description</option>
     <option value="6390" title="Service 4" data-description="desc info here">Service 4 Description</option>
</select>

As you can see, sometimes there is only 1, while other times there may be 2, 3, 4, etc. sets of numbers.
What I need to do is take those numbers and run a function that builds out a DIV for each number to contain the information associated with that number.
So far, I have been able to display the value data using an alert which is activated when the selection is made:
$(function() // Start Main Function
{
      $('select').change(function() { //Start Change Function
            alert($(this).val());

            var item_ids = $(this).val();
    //      alert(item_ids);

      }); // End Change Function

}); // End Main Function

I've also successfully assigned it to a variable, which then displays the value in the alert when the selection is made:
$(function() // Start Main Function
{
      $('select').change(function() { //Start Change Function

            var item_ids = $(this).val();
            alert(item_ids);

      }); // End Change Function

}); // End Main Function

The next step is where I'm having the issue.  I now need to take that variable, and break it down into the separate numbers, and create a DIV for each one.  Below is my current code:
$(function() // Start Main Function
{
      $('select').change(function() { //Start Change Function

            var item_ids = $(this).val();

$('#services-section').html(
  $('<div/>')
    .attr("id", "service-block")
//    .addClass("")
);

$('#service-block').append(
  $('<h1/>')
//    .attr("id", "service-block")
//    .addClass("")
      .text($(this).find("option:selected").attr("title"))
);

$('#service-block').append(
  $('<p/>')
//    .attr("id", "service-block")
//    .addClass("")
      .text($(this).find("option:selected").data("description"))
);

$('#service-block').append(
  $('<div/>')
    .attr("id", "service-items")
//    .addClass("")
);

// This is where I have started trying to set up the loop to cycle through the value data and create the new DIV for each number.

                $.each( item_ids, function(  ){ // Start Items Function

    console.log(item_ids);

                $('#service-items').append(
                  $('<div/>')
                    .attr("id", "service-item-block")
                //  .addClass("")
                );

            }); // End Items Function

      }); // End Change Function

}); // End Main Function

When I test it, it never builds any new DIVs.  If I place the "console" line before the new function, it displays the data correctly in the console.  When I move back within the function, it doesn't show any data.  I believe the issue lies with how I have set up the .each(function()), but being a complete novice at JQuery, I don't understand the proper syntax to make it work.
Can someone please shed some light on how to get this working correctly?

A: item_ids is a string with numbers separated by a space. Which means there is nothing to loop through with the each function.
So first thing, you will want to split it using the space as the delimiter.
var item_ids = $(this).val().split(" ");
Next, in your each loop will need to get that value in the loop itself. Which can be referenced by using this
$.each(item_ids, function() {

  console.log(this);

  $('#service-items').append(
    $('<div/>')
    .attr("id", "service-item-block")
    //  .addClass("")
  );

}); // End Items Function


text:
Q: Rmarkdown: Datatable conflicts with jquery I would like to use a live timestamp in my rmarkdown file. To do so, I need to include the jquery and moment.js libraries. However, the jquery library conflicts with the datatable R library. I tried many solutions I saw online, without success.
This is my header (header.html) with the jquery, moment.js and livestamp.js libraries:

And this is my Rmarkdown file main.Rmd:
---
title: "Test"
output:
  html_document:
    includes:
      in_header: header.html
---

```{r setup, include=FALSE}
library(DT)
```

```{r echo=FALSE}
datatable(cars)
```

The timestamp works fine, but the datatable does not work. In my web browser console I get the following error:
main.html:1406 Uncaught TypeError: $table.DataTable is not a function
    at Object.renderValue (main.html:1406)
    at main.html:868
    at Array.forEach (<anonymous>)
    at forEach (main.html:270)
    at main.html:791
    at Array.forEach (<anonymous>)
    at forEach (main.html:270)
    at Object.window.HTMLWidgets.staticRender (main.html:789)
    at maybeStaticRenderLater (main.html:913)
    at HTMLDocument.<anonymous> (main.html:920)

How can I solve this conflict?

A: I'm going to put what I was referring to in my comment here. Whether you use header.html or put the script calls directly into the RMD file, the results are the same. Since jquery is called already, it shouldn't be called again.
If this is not what you're looking for, please let me know.
Update header.html to (dropping the first script call)

Alternatively, you could drop header.html and put it all in your RMD file (less jquery script).


text:
Q: Multiple PHP Pools for SAME User - Nginx Upstream on Debian I'm trying to take advantage of nginx upstream using socket but receiving errors in my log:
connect() to unix:/var/run/user_fpm2.sock failed (2: No such file or directory) while connecting to upstream

I might be going about this wrong and looking for some advice/input.
Here's the nginx conf block:
upstream backend {
    server unix:/var/run/user_fpm1.sock;
    server unix:/var/run/user_fpm2.sock;
    server unix:/var/run/user_fpm3.sock;
}

And:
location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        fastcgi_pass backend;
        fastcgi_index index.php;
        include fastcgi_params;
}

Then, I have 3 PHP pools at /etc/php/7.0/fpm/pool.d/ that look pretty much the same as below. The only difference between the pools is _fpm1, _fpm2, and _fpm3 to match the upstream block.
[user]

listen = /var/run/user_fpm1.sock
listen.owner = user
listen.group = user
listen.mode = 0660
user = user
group = user
pm = ondemand
pm.max_children = 200
pm.process_idle_timeout = 30s
pm.max_requests = 500
request_terminate_timeout = 120s
chdir = /
php_admin_value[session.save_path] = "/home/user/_sessions"
php_admin_value[open_basedir] = "/home/user:/usr/share/pear:/usr/share/php:/tmp:/usr/local/lib/php"

I've noticed the /var/run always ONLY has the user_fpm3.sock file.
Am I going about this wrong? Is it possible to make this upstream config work? All advice and critique welcome.
I'm running PHP7 on Debian Jessie with nginx 1.10.3 - Server has 6 CPU's and 12GB RAM.
Thanks in advance.
UPDATE: I figured the answer myself, but leaving the question in case someone else is trying to do the same thing, or there's a way to optimize this further.
All I had to do was change my pool names to [user_one], [user_two], and [user_three]

A: Changing the the name of each PHP pool fixed the problem, like so:
[user_one]

[user_two]

[user_three]


text:
Q: How to update user email field in firebase using web? I am working with mobile developer.
As they are creating new user in mobile application, they register the user on firebase also.
Mobile application also has Admin section where I can edit the user information.
Now I have a requirement that while I am updating any user information, I also need to update the user email field on firebase also.
Is there any way to update the field of user on firebase?
I searched a lot and got the way how to add the reference to firebase on web but am not able to update user field.
Code
Given reference on cshtml page of firebase
  <script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>

This code i have added in jquery file. Configuration is replace for security purpose.
 var config = {
                        apiKey: "Apikey",
                        authDomain: "domainname",
                        databaseURL: "given db url",
                        projectId: "ProjectId",
                        storageBucket: "storageBucket",
                        messagingSenderId: "000000"
                    };
                    firebase.initializeApp(config);

This is used for firebase database reference as got from the google doc.
 var firebaseRefs = firebase.database().ref();

This is the code i am using for updating email field in firebase users node
var uid = '';
                firebase
               .auth()
               .signInWithEmailAndPassword(data.Email, data.Password)
               .then(function () {
                   auth = user;
                  firebaseRefs.ref("users/" + data.Id).update({ email: data.Email});
               .catch(function (error) {
                   console.log("Login Failed!", error);
               });

A: You can use the updateEmail() method of the JavaScript SDK (https://firebase.google.com/docs/reference/js/firebase.User#updateEmail), but, if I am not mistaking, you should be authenticated as the user itself.

You can also update a User (including the email) through the Admin SDK, see https://firebase.google.com/docs/auth/admin/manage-users#update_a_user.
In this case you don't need to be authenticated as the user.
You should use this SDK from a managed environment, for example Cloud Functions, but it can be from your server too.
If you want to use this method from the web you could call, from your web front-end, an HTTP Cloud Function (or a callable one, see https://firebase.google.com/docs/functions/callable)

Following your update, you could do as follows:
firebase
    .auth()
    .signInWithEmailAndPassword(data.Email, data.Password)
    .then(function (userCredential) {
         var user = userCredential.user;
         return user.updateEmail(data.Email);
    })
    .then(function () {
         return firebaseRefs.ref("users/" + data.Id).update({ email: data.Email});
    })
    .catch(function (error) {
         console.log("Login Failed!", error);
    });

Note that signInWithEmailAndPassword() returns a UserCredential, from which you get the user, see
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInWithEmailAndPassword


text:
Q: Change sha1 password mysql and Cakephp log in I'm very new to CakePHP.
I've recently taken over a project that was built in CakePHP v 1.2.4.8284.
I'm trying to change the password for the login page.
There is only one user stored in a mysql database.
fields - id, username, password(varchar 40),  nacl(char(6), firstname, lastname
In phpAdmin, I've tried changing the password while using the SHA1 function, but that doesn't work.
I've even tried creating a new user, but the new user information will not work either.
I've narrowed it down to the usercontroller in the following if statement:
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password'])))

It looks like the password in the database should have sha1(nacl field) + sha1(password field).
But it is all wrapped in a sha1.
I'm not sure how the encryption is working.
Any help would be appreciated.
Thanks in advance.
Here is the complete login function.
function login()
{
    $this->set('error', false);
    if ($this->Session->read('user'))
    {
        $this->redirect('/test-folder/');
    } else {
        $this->User->set($this->data);
        if ($this->data) {
            //$results = $this->User->findByUsername($this->data['User']['username']);
            $results = $this->User->find('first', array(
                'conditions' => array('username' => $this->data['User']['username'])
            ));
            if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password']))) {
                $this->Session->write('user', $this->data['User']['username']);
                $this->Session->write('admin', $results['User']['group']);
                $this->redirect('/test-folder/');
            } else {
                $this->set('error', true);
            }
        }
    }
}

A: *

*Get the Security.salt in Config/core.php: 'securitysaltvalue'

*Take a password 'yourplainpassword'
UPDATE user SET password = SHA1( CONCAT('securitysaltvalue', 'yourplainpassword')) WHERE id = 123

A: According to your code, you should be able to generate a new Password with these steps:
1) Generate a Password, for example "test123"
2) Get the id of the user you want to change the password for, for example 123
3) Execute this SQL in your phpMyAdmin (Replace my demo values!!!)
UPDATE user SET password = CONCAT( SHA1(nacl), SHA1("test123")) WHERE id = 123

And please make a complete DB dump on that table before any changes. And better yet, test on some development instance.

A: The answer from @StefanoDP works, but the table name is 'users', not 'user'. So the command should be:
UPDATE users SET password=SHA1(CONCAT('securitysaltvalue','yourplainpassword')) WHERE id=123;

Don't forget to add the semicolon at the end of the statement.


text:
Q: composer and nodejs on same server So I want to run composer and nodejs on same website. Is it good practice? How I should deal with environment and file structures?

A: No problem: It will work very well, but it needs to be set to a different port. For example: apache2 is using port 80. And NodeJs will use the port that you set.


text:
Q: Создание фильтра для карточки посредством html, js, css, svg Друзья, возник такой вопрос, как реализовать такой blur для карточки? Как переместить в низ карточки вопросов не возникает, а вот как сделать такой blur непонятно, кто-то может помочь в этом вопросе? Реализовать бы посредством js, html, css, svg или любыми другими методами

A: Как вариант(исправлено, используя пример некоего Stas'а https://codepen.io/html_man/pen/oeNvOa):

*,*:after,*:before {
 -webkit-box-sizing: border-box;
 box-sizing: border-box;
 padding: 0;
 margin: 0;
 outline: 0;
}
/*стили выше добавлены только для этого примера, в реальном проекте используйте normilize.css\reset.css*/
.main {
 position: relative;
 z-index: -1;
 height: 300px;
 width: 400px;
 border: 2px solid #000;
 -webkit-border-radius: 10px;
 border-radius: 10px;
 background: url(https://www.visitfinland.com/app/uploads/Aland_Islands_fishing-400x300.jpg) no-repeat 50% 50%;
 overflow: hidden;
}

.filter-child {
 position: absolute;
 left: -10px;
 right: -10px;
 bottom: -10px;
 height: 110px;
 background: inherit;
 background-repeat: no-repeat;
 background-position: bottom;
 overflow: hidden;
}

.filter-child::after {
 content: '';
 left: 0;
 right: 0;
 bottom: 0px;
 height: 100%;
 position: absolute;
 z-index: 99;
 background: inherit;
 -webkit-box-shadow: inset 0 0 0 200px rgba(99, 99, 99, 0.4);
 box-shadow: inset 0 0 0 200px rgba(99, 99, 99, 0.4);
 -webkit-filter: blur(5px);
 filter: blur(5px);
}


text:
Q: Google Charts setting the side to show only
The above image is a Google Chart I made up. I would like to control the values at the side so it only shows 0 200 400 600 instead of 0 150 300 450 600.
Ive looked over the google documentation and can't quite figure out what I should be looking for.

A: Set the vAxis.ticks option:
vAxis: {
    ticks: [0, 200, 400, 600]
}