Q:

CSS: Floated element after the content in code

I need to have a floated element after the content/text that's supposed to flow around it in my code for SEO reasons. Usually floats are done like so:
CSS:
#menu {
float: right;
width: 180px;
padding: 10px;
background: #fcc;
margin: 0 0 15px 15px;
}

HTML:

This is a right float. The long text flows around it.

This is a long text. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Praesent nec risus.
Praesent adipiscing aliquet magna. Proin bibendum velit
vitae tortor. Vestibulum a dui quis urna feugiat viverra.
Vestinbulum diam dui, ullamcorper in, rhoncus at, facilisis at,
lorem. Phasellus turpis metus, sodales sit amet, laoreet nec,
aliquet sit amet, tortor. Vivamus massa orci, gravida sit amet,
dictum quis, euismod a, est. Aenean pretium facilisis nunc.

Nulla eros mauris, egestas eget, ullamcorper sed, aliquam ut,
nulla. Phasellus facilisis eros vel quam. Etiam rutrum turpis
a nibh. Integer ipsum. Vestibulum lacus diam, varius in,
blandit non, viverra sit amet, sapien. Sed porta sollicitudin
nibh. Nam eget metus nec arcu ultricies dapibus.

But I need to have the HTML like this:

This is a long text. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Praesent nec risus.
Praesent adipiscing aliquet magna. Proin bibendum velit
vitae tortor. Vestibulum a dui quis urna feugiat viverra.
Vestinbulum diam dui, ullamcorper in, rhoncus at, facilisis at,
lorem. Phasellus turpis metus, sodales sit amet, laoreet nec,
aliquet sit amet, tortor. Vivamus massa orci, gravida sit amet,
dictum quis, euismod a, est. Aenean pretium facilisis nunc.

Nulla eros mauris, egestas eget, ullamcorper sed, aliquam ut,
nulla. Phasellus facilisis eros vel quam. Etiam rutrum turpis
a nibh. Integer ipsum. Vestibulum lacus diam, varius in,
blandit non, viverra sit amet, sapien. Sed porta sollicitudin
nibh. Nam eget metus nec arcu ultricies dapibus.

This is a right float. Because it's placed below the text in code,
it also appears that way.

Basically, I need this HTML to look like the previous example (HTML and CSS). How can I do this?
The width of the floated element is constant, but the height can change. The content has to flow around it. The reason I need to have it this way is because the floated element is the menu, which doesn't contain any important text and is usually the same for many pages, so the content should be topmost in the code.

A:

Simple you have add the following css
#content {
    float: left;
    width: 300px; /* put here the width you want */
}

demo: http://jsfiddle.net/qTDLr/1/
Edit: make sure that the sum of #content and #menu width is less than the container width.

A:

This recent question may be the same
Wrap text around right floated column where left column appears first in html
the solution involves floating a empty "spacer" div right , this spacer is first in source, it should  have the width and height of the content to be in the right side - in the link a solution including a bit of jQuery to get the height - the position the actual menu over the top of the floated spacer
a JS fiddle example produced from that link : HERE


Q:

Jquery mousewheel scrolling jerks page

I have this jquery to mousewheel scroll a div with an id of conentBox. It jerks the page up and down not just the div?  i think i need like a bind or something but i dont know?
    $(function() {
$('#contentBox').mousewheel(function(event, delta) {
var scrollTop = $(this).scrollTop();
$(this).scrollTop(scrollTop-Math.round(delta * 10));
return false; // prevent default
});
});

A:

Try reducing the amount you add/subtract from the scrollTop:
$(this).scrollTop(scrollTop-Math.round(delta * 2));

Update: It seems that it does work for me in IE7+... I made this demo.


Q:

react-router browserHistory.push doesn't navigate to new page

I tried to follow the solutions in this question and in the react-router example but I'm still having trouble.
I'm using react-router version 2.4.1, React version 15.1.0, and webpack 1.13.1.
I have a router that is set up like this:
import React from 'react';
import {render} from 'react-dom';
import {Router, Route, Link, browserHistory} from 'react-router';
import Component from './component';
import Merchant from './merchant';
import CreateMerchant from './create-merchant';
require('bootstrap/dist/css/bootstrap.css');
// /* globals document, window */
//
// const { pathname, search, hash } = window.location
// const location = `${pathname}${search}${hash}`

render((
    <Router history={browserHistory}>
        <Route path="/" component={Component}/>
        <Route path="/merchant" component={CreateMerchant}/>
        <Route path="/merchant/:merchantId" component={Merchant}/>
    </Router>
), document.getElementById("app"))

When I go to http://localhost:8080/ I see the component as expected:
import React from 'react';
import {Link, browserHistory} from 'react-router';

export default class Component extends React.Component {
    handleSubmit(event) {
        const merchantId = event.target.elements[1].value;

        console.log("Merchant id is " + merchantId);

        const path = `/#/merchant/${merchantId}`;

        browserHistory.push(path);
    }

    render() {
        return

Welcome to VPager!

Would you like to create a merchant?

                    <Link className="btn btn-primary" to="/merchant">Yes, create a merchant and start taking
                        customers.</Link>

Or do you have an existing merchant?

            <form onSubmit={this.handleSubmit.bind(this)}>

                        <button type="submit" className="btn btn-primary">I have an
                            existing merchant ID, and it is:</button>

<input id="merchantId" className="form-control" type="number" />

            </form>

    }
}

When I click the second button, though, the URL in the address bar changes, but the new view is not rendered.
It seems that people had similar issues in the past, but those solutions aren't working either.
I also tried creating a higher order component and nesting the routes with a top-level component.  In that case, however, I get the error that "The root route must render exactly one element."
How do I get the form to navigate to a new view?

A:

You have an errant # in your path variable, possibly left over from using hashHistory. Leave it out, should work:
const path = `/merchant/${merchantId}`


Q:

Understanding Ruby Inheritance

I've been reading the Well Grounded Rubyist and it mentions how a class inherits the instance methods of its super class so that objects of the class will be able to call those instance methods.  Here's an example:
class C
  def run_instance_method
    puts "This is an instance method."
  end
  def C.run_class_method
    puts "This is a class method."
  end
end

class D < C
end

Based on what I've read, it's always been described that class D would inherit just the instance methods of class C (in which case, the C::run_class_method would not be inherited by D).  However, after running the above code, I notice that:
D.run_class_method # => "This is a class method."

Here's my guess as to why this is happening and please let me know if this is the correct understanding. If there is an instance d of class D and you try to run d.run_instance_method, that object will search its method-lookup path and see if that method is defined in its singleton class, its own class, or in its superclasses.  Since run_instance_method is defined in class C, no issues will occur and run_instance_method will be called.  For the class object D (which is a subclass of C and Object), if D.run_class_method is called, it'll again check the method lookup path for the D class object.  Again, Ruby will find it in the class object C.
Is this reasoning accurate?

A:

Class methods may be inherited and overridden just as instance methods can be. If your parent class defines a class method, the subclass inherits that method. That is, if your subclass does not define it's own class method, then it inherits from it's superclass.
As a recommendation: when invoking a class method with an explicit receiver, you should avoid relying on inheritance. Always invoke the class method through the class that defines it. Otherwise, it would be very difficult for someone who relies on your code to find the parent class which defines the class method.
Referring back to your original assumption: the invocation of a class method from a subclass it's possible because the class methods are instance methods of the eigenclass.
class C
   # instance methods goes here
   class << self # open the eigenclass
   # class methods go here as instance methods of the eigenclass
   end
end

In general, it's clearer to define class methods as individual singleton methods without explicitly opening the eigenclass.
For a clear explanation read The Ruby Programming Language by David Flanagan and Yukihiro Matsumoto


Q:

DataSet does not support System.Nullable<> error on linq

When i run the code i get "DataSet does not support System.Nullable<>" error
I tried many thing to eliminate this problem.
Is there any way to rid of this error. please help me.
       ///SONRA GEL
        DataTable dtFinal = new DataTable();
        dtFinal.Columns.Add(new DataColumn("AY", typeof(string)));

        dtFinal.Columns.Add(new DataColumn("KIMYASAL", typeof(string)));

        dtFinal.Columns.Add(new DataColumn("MIKTAR", typeof(double?)));
        dtFinal.Columns.Add(new DataColumn("MAKINA", typeof(string)));

        dtFinal.Columns.Add(new DataColumn("PRICE", typeof(double?)));

        var result = from dataTable1 in dt1.AsEnumerable()
                     join dataTable2 in dt2.AsEnumerable()
                     on dataTable1.Field<string>("KIMYASAL") equals dataTable2.Field<string>("eliaradı")
                     select dtFinal.LoadDataRow(new object[]
         {

            dataTable1.Field<string>("AY"),
            dataTable1.Field<string>("KIMYASAL"),
            dataTable1.Field<double?>("MIKTAR"),
            dataTable1.Field<string>("MAKINA"),
              dataTable2.Field<double?>("PRICE"),
          }, false);
        result.CopyToDataTable();

        MessageBox.Show("finale geldi");

        //   dataGridView1.DataBind();
        bindingSource1.DataSource = dtFinal;
        dataGridView2.DataSource = bindingSource1;

A:

Here:
dtFinal.Columns.Add(new DataColumn("MIKTAR", typeof(double?)));

you define a data column with a nullable type (double?). That's not necessary: The DataTable/DataColumn classes support nullability for all data types out of the box (since those classes predate .NET generics and, thus, .NET value type nullability).
In other words:
dtFinal.Columns.Add(new DataColumn("MIKTAR", typeof(double)));

(double instead of double?) will work fine, you are still able store store null in that column.

Note: If you explicitly don't want to support nullability for a certain column, you need to set the AllowDBNull property to false:
 // This column is nullable
 dtFinal.Columns.Add(new DataColumn("NullableColumn", typeof(double)));

 // This one isn't
 var col = new DataColumn("NotNullableColumn", typeof(double));
 col.AllowDBNull = false;
 dtFinal.Columns.Add(col);


Q:

Why are the nations of Shem summarized differently than the nations of Ham?

The genealogies of Ham and Shem conclude with nearly identical statements:

These are the sons of Ham, according to their families, according to their languages, by their lands, and by their nations. (10:20 NET)
These are the sons of Shem according to their families, according to their languages, by their lands, and according to their nations. (10:31 NET)

Ham (10:20): לְמִשְׁפְּחֹתָ֖ם לִלְשֹֽׁנֹתָ֑ם בְּאַרְצֹתָ֖ם בְּגוֹיֵהֶֽם
Shem (10:31):לְמִשְׁפְּחֹתָ֖ם לִלְשֹֽׁנֹתָ֑ם בְּאַרְצֹתָ֖ם לְגוֹיֵהֶֽם

The NET translation reflects the difference in nations as "by their" and "according to their."
The meanings are similar but why are the nations of Shem summarized differently than Ham?

A:

Much ink has already been spilled and many quills broken on this inconsistency in the MT, but the result has been only contrived explanations.
As Steve Taylor notes, the inconsistency does not have any semantic importance.
The difference between ב and ל is a difference of preposition usage. The use of ב is a earlier usage. The use of ל is both OT and post OT. Each of these prepositions is used in so many different contexts that is is not possible to pin down an intended difference in meaning between בגויהם and לגויהם in Genesis 10.
The ל in לגויהם of verse 31 could be a copyist mistake. The reasoning is as follows:

The chapter has three instances of בגויהם and only one of לגויהם
The Onkelos targum for this לגויהם is "בעממיהון" with a ב as in the previous instances of בגויהם. The Jonathan Ben-Uziel has a ל but it is a later targum and the version that we have could have been "corrected"
Jedidiah Norzi (the "Minhat Shai") claims an OT manuscript called the Hilleli Copy (העתק הללי) reads בגויהם in verse 30, that is ב and not ל
There are four ל's in verse 30 preceding לגויהם, three of them in word initial position. This raises the likelihood of a copyists elision of a ל to the begining of the final word in the phrase.
The change from ב to ל does not change the meaning significantly, increasing the likelihood that the change could go unchallenged
The LXX has ἐν τοῖς ἔθνεσιν αὐτῶν for both verse 20 and verse 31

There is no "Dead Sea" version of these verses to use for comparison AFAIK, but I do not have access to the 2010 edition of Emanuel Tov's Revised Lists of the Texts from the Judaean Desert.
AFAIK the SP also has a ל in verse 31, which might be an argument against this being a copyists mistake.


Q:

By the eyes of a child

I'm translating a song from my Portuguese to English. Its title (Aos Olhos de uma Criança) literally means "At/on the eyes of a child". It means that the things said in this song are being witnessed by a child. Does it sound natural to translate it to "By the eyes of a child" with no verbs?

A:

Titles are able to be fragments of sentences, so yes, that title would be fine. (Another translation might be "In the eyes of a child," or "Through the eyes of a child." But because those are both common sayings in English, "By the eyes of a child" would be more unique.)


Q:

sbt-native-packager docker: How to add entry in /etc/hosts

I'm using the docker plugin of sbt-native-packager to build a Docker image. I would like my image to have an additional entry in /etc/hosts.
I've tried the following:
dockerCommands in Docker := dockerCommands.value.flatMap {
  case cmd@Cmd("FROM", _) =>
    List(Cmd("FROM", "anapsix/alpine-java")) ++ List(
      Cmd("ENV", "JAVA_MIN_MEM", "1024m"),
      Cmd("RUN", "echo 8.8.8.8 foo >> /etc/hosts")
    )
}

Unfortunately it doesn't seem to work. When I start a container based on this image, the /etc/hosts does not have the extra entry.
It looks like it's actually writing the file because I tried the following instead:
....
Cmd("RUN", "echo 8.8.8.8 foo >> /etc/hosts; ping -c 4 foo")
....

And I'm getting as output the following:
[info] Step 9/15 : RUN echo 8.8.8.8 foo >> /etc/hosts; ping -c 4 foo
[info]  ---> Running in b6d7ba25f96f
[info] PING foo (8.8.8.8): 56 data bytes
[info] 64 bytes from 8.8.8.8: seq=0 ttl=37 time=5.521 ms
[info] 64 bytes from 8.8.8.8: seq=1 ttl=37 time=3.188 ms
[info] 64 bytes from 8.8.8.8: seq=2 ttl=37 time=6.012 ms
[info] 64 bytes from 8.8.8.8: seq=3 ttl=37 time=4.192 ms

So it looks like the modified /etc/hosts is being overridden!
What is the correct way to do this?

A:

The file /etc/hosts is managed by Docker and cannot be customized as part of building an image.
As you already figured out, you can add a custom entry using RUN echo 8.8.8.8 foo > /etc/hosts; <some_command_requiring_custom_hosts_file>. But this modification is only available during the execution of this particular RUN command.
In case you need custom entries when running containers use the --add-host parameter of docker run (see docs).
In general it is a best practise to not include configuration details in a Docker images. Applying configuration only at the time you are running your containers helps to keep the images portable.


Q:

CodeIgniter pagination url page number

From what I saw, CodeIgniter's pagination is counting the page wrong way, because I got pagination looking like this:

1 2 3 >

And its good, the problem is in the each pagination number url, except the first one:
Number 2 from the pagination has the following url:

http://my-url.com/index.php/page/1

And number 3 has the following url:

http://my-url.com/index.php/page/2

So, the number is URL is decreased by 1 everytime.
How can I solve that, so the page numbers in urls will be the same as the page numbers in the pagination?
My pagination config:
$config['per_page']    = 5;
$config['base_url']    = site_url('page');
$config['uri_segment'] = 2;
$page = $this->uri->segment(2);
$total_rows_array = $this->records->get($config['per_page'], $page * $config['per_page']); // parameters: limit, offset.
$config['total_rows']  = count($total_rows_array);

A:

Had the same problem you have, and I added this configuration line:
$config['use_page_numbers'] = TRUE;

and it works like a charm!

A:

Are you using page numbers in the pagination config?
The way CodeIgniters pagination works (by default) is that you set the number of records to show in the code, CodeIgniter works out the offset and appends that to the URL.
The reason page 1 (if you will) has no number at the end is because there is no offset, page 2 will have an offset of 1 because it is offsetting that many records. Wow this is a lot harder to explain than I thought before I started typing this answer!
:EDIT:
Also, if you are using page numbers in the pagination config, I imagine that code igniter is taking the per_page amount and multiplying it by the page number to get the real offset for the records.
Page 2 would really work out as per_page (15) * page_number (1) = 15 for the real offset.


Q:

Is posible to submit multipart/form-data without refresh page in jQuery?

I want to upload picture from "my_form" in jQuery, I tried submit() function it alway redirect to SavePicture.jsp. Is posible to sumbit this form without refresh any page?
This is my html code
<form action="SavePicture.jsp" method="post" id="my_form" enctype="multipart/form-data">
<input name="file" type="file" id="file" size="35">
<input type="button" onClick="upload()" value="upload"></input>
</form>

And my script
function upload(){
   jQuery("form#my_form").submit();
}

A:

You can post to an iframe


Q:

ActionbarSherlock - how do I implement a tab navigation once and have that used in my app?

I am looking at the tab navigation example from the ActionbarSherlock download. The examples show one element type per class. But I would like all my screens to reuse the tab navigation.
So I added the tab_navigation.xml to my project
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dip">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="@string/tab_navigation_content" />
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

And now I am wondering how I can add the code for the tabs to my project? Do I absolutely have to define the tabs in every Activity? Or is there a way to just have one definition I can reuse in multiple places?
Here is how my activities look like:
public class MainActivity extends FragmentActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ...

A:

Use Fragments
Whether you have seen this?
http://wptrafficanalyzer.in/blog/adding-navigation-tabs-containing-listview-to-action-bar-in-pre-honeycomb-versions-using-sherlock-library/


Q:

My Bootstrap columns aren't lining up

I used to have a working layout of a header, side navigation column, main large content column , and a footer. Now the navigation column is sitting on top of the content column even though the numbers should add up. I just need my navigation column to line up next to my content. You can see my WIP HERE. What am I doing wrong?
Here is basically what my code for my layout is:

HEADER

NAVIGATION

CONTENT

FOOTER

Your help is greatly appreciated. Thank you! :)

A:

The column divs only line up beside each  other for the divs actually are "siblings" to each other, apart from adding up numberwise.
Try putting the navigation and content columns in the same container -> row tag, like so:

NAVIGATION

CONTENT


Q:

Django redirect for legazy php url

Basically what I want to do is:
urlpatterns = patterns('',
    url(r'^old/site/url.php?someshit=(?P<id>\d+)',
    'website.views.redirect_php'),
)

But I always get a 404 ..
I've also tried to escape it like this
urlpatterns = patterns('',
    url(r'^old/site/url\.php\?someshit\=(?P<id>\d+)',
    'website.views.redirect_php'),
)

No luck.
Any ideas ?

A:

What you're doing does not work because GET parameters are not included in the string being matched by URLconf. (See What the URLconf searches against.)
To achieve the desired behaviour, you'll need to extract the GET parameter from within the view and redirect according.
urlpatterns = patterns('',
    url(r'^old/site/url\.php$',
        view='website.views.redirect_php',
        name='redirect_php'
    ),
)

and in your view:
def redirect_php(request):
    id = request.GET.get("somesheet", None)
    if id == None:
        # handle case where "somesheet=?" was not provided
    else:
        # handle redirects based on id


Q:

Two sequences have the same limit

Let  $f$ and $g$ be real-valued continuous functions on $\Bbb R^2$ that satisfy the following condition:
$$
x<y \implies x< f(x,y) < g(x,y) <y
$$
Assume that there are two sequences $\{a_n\}$ and $\{b_n\}$ that satisfy the following:
$$ a_1 < b_1, a_1,b_1 \in \Bbb R,\quad a_{n+1}=f(a_n, b_n),\quad b_{n+1}=g(a_n,b_n).
$$
It's easily seen that
$$a_1 < a_2 < ...< a_n < ...< b_n < b_{n-1} < ... < b_1.$$
Hence $\{a_n\}$ and $\{b_n\}$  are monotonic and bounded thus convergent.
Now I want to prove that $\lim_{n \to \infty} a_n= \lim_{n \to \infty} b_n$.
My attempt: Assume that $\lim_{n \to \infty} a_n=a, \lim_{n \to \infty} b_n=b$.
Since $a_n < b_n$, $a \le b$. Since $a_{n+1}=f(a_n, b_n)$, we have $a=f(a,b)$.
If $a< b$ then $a < f(a,b)$, a contradiction.
It follows that $a=b$.
Does the proof above look fine?

A:

It looks fine to me.
$\lim f(a_n, b_n) = f(a,b)$ follows from the continuity of $f(x,y)$, for if $f(x,y)$ is continuous at $(a,b)$ then for any sequence converging to $(a,b)$ the sequence of the images of the sequence converges to $f(a,b)$. This is known as the sequential criterion of continuity.


Q:

Disable IPv6 on Windows Server 2008 R2 using Puppet

I am using the Puppet module windows_disable_ipv6 but it seems it's not really working.
# cat /etc/puppetlabs/code/environments/production/manifests/site.pp
node my_instance.net {
        include windows_disable_ipv6
}

# cat /etc/puppetlabs/code/environments/production/hieradata/common.yaml
---
windows_disable_ipv6::ipv6_disable: true
windows_disable_ipv6::ipv6_reboot: true

# cat /etc/puppetlabs/puppet/hiera.yaml
---
:backends:
  - yaml
:hierarchy:
  - "nodes/%{::trusted.certname}"
  - common

:yaml:
Windows
  :datadir:

I checked the module's manifest. It changes the registry setting to '0xFFFFFFFF' if it has to disable IPv6.
When i run puppet agent -t on the agent, i do see that the key changes to above value and the system reboots but when i login again post-reboot, i see that the check-box for IPv6 is still enabled.

This link suggests using '0xff' instead of '0xFFFFFFFF'. I tried changing the value and then restarted the server as well but the issue still persists.
Any pointers?

A:

The puppet modules disables IPv6 on the system which is validated through an ipconfig /all on the system. The checkbox simply handles the binding to the interface and doesn't actually disable IPv6 on the system.


Q:

How to save data to user session in Parse.com

After I log in the user on the backend (I use Parse.com CloudCode) I would like to save the uri to his avatar in his session.
How would I do it in Parse.com. I know there is an object Parse.Session.current() but not sure how to use it.

A:

Treat it just like other objects provided by parse.
Parse.Session.current().then(function(session) {
    session.set("foo", "bar");
    session.save().then(function() {
        console.log(session.get("foo"));
    });
});

The session CLP should be set to allow this.  (And the app must be setup to require revokable sessions).


Q:

Auto-generated values for columns in database

Is it a good practice to initialize columns that we can know their values in database, for example identity columns of type unique identifier can have a default value (NEWID()), or columns that shows the record create date can have a default value (GETDATE()).
Should I go through all my tables and do this whereever I am sure that I won't need to assign the value manually and the Auto-generated value is correct.
I am also thinking about using linq-to-sql classes and setting the "Auto Generated Value" property of these columns to true.
Maybe this is what everybody already knows or maybe I am asking a question about a fundamental issue, if so please tell me.

A:

Yes, I would definitely recommend assigning sensible default values to your table columns.
If you have e.g. some BIT fields that are "0" or "1" most of the time, specfying a default makes sure they're initialized to their most likely state, and only if you really need to change them, you have to do something yourself.
If you have sensible default values for your table columns, you can have very simple initial INSERT statements - just insert what you really need, all the other things are being set to a default value.
The default value also only ever comes into play when you INSERT something, so as soon as you already have a row, you can change it any way you like, no problem.
Also, default values help you be able to define NOT NULL constraints - after all, if you set a column to NOT NULL, you have to make sure it always has a valid value stored in it. If you define a default value and happen to forget to set a value in your INSERT, the default will apply and satisfy the NOT NULL constraint.
All in all: yes, default values are a "good thing" ! Use them where appropriate and where they make sense!!


Q:

Follow-up to Displaying attributes in Dash/Plotly results in KeyError

After a helpful answer to my original question, I decided to use internal data (which I can't share here). The internal data follows the same format as the mock data. I simply copied the data over to the same working directory, making sure that the new data has the same format, i.e. same column headers, etc. I used DiffChecker to make sure that app.py (from my original post) matches the Proof of Concept (appPOC.py). The internal data has more than 600 nodes, and more than 3000 edges.
The code to make the interactive dashboard is the same as the one I used for my original post. However, this time I run into this KeyError:
Traceback (most recent call last):
  File "appPOC.py", line 75, in <module>
    hovertext = "Document Description: " + str(G.nodes[node]['Description']) + "
" + "Document Name: " + str(G.nodes[node]['DocName']) + "
" + "Document ID: " + str(G.nodes[node]['DocumentID'])
KeyError: 'Description'

The data itself should be fine, as I can plot a network without the hovering text next to the node.
To summarize: app.py can plot the mock data, appPOC.py (which is identical, but has a different file name) can't plot the internal data. This leads me to believe that there is something wrong with the internal data in the CSV file.
Edit: I figured out that if the target is not listed in the elements, the graph fails to be drawn. Is there anyway to create a node automatically (like in Gephi) if the (target) node is not defined in the elements?

A:

NetworkX creates nodes for from- and to-nodes of each edge. Hence, with
G = nx.from_pandas_edgelist(edges, 'Source', 'Target')

you're graph has all possible nodes. However, with
nx.set_node_attributes(G, nodes.set_index('Doc')['Description'].to_dict(), 'Description')
nx.set_node_attributes(G, nodes.set_index('Doc')['DocumentID'].to_dict(), 'DocumentID')

you only fill the node attributes 'Description' and 'DocumentID' for those in your nodes data frame. A simple workaround is to replace the
str(G.nodes[node]['Description'])

with
str(G.nodes[node].get('Description', ''))

and similarly for 'DocName' and 'DocumentID'. More information on the get method you find at: Why dict.get(key) instead of dict[key]?
Basically, we use that networkx uses dict to store values and make use of the get method, which allows to supply a default value.
A simple reproducible and minimal example
import networkx as nx
g = nx.karate_club_graph()
# all nodes in this graph have the node attribute 'club' filled
# we add a node without this node attribute
g.add_node("Test")
print(g.nodes[0]["club"])
# 'Mr. Hi'
# print(g.nodes["Test"]["club"]
# results in KeyError: 'club'
print(g.nodes["Test"].get("club", ""))
# ''


Q:

how to disable SSH login with password for some users?

On Linux (Debian Squeeze) I would like to disable SSH login using password to some users (selected group or all users except root). But I do not want to disable login using certificate for them.
edit: thanks a lot for detailed answer! For some reason this does not work on my server:
Match User !root
PasswordAuthentication no

...but can be easily replaced by
PasswordAuthentication no
Match User root
PasswordAuthentication yes

A:

Try Match in sshd_config:
Match User user1,user2,user3,user4
    PasswordAuthentication no

Or by group:
Match Group users
    PasswordAuthentication no

Or, as mentioned in the comment, by negation:
Match User !root
    PasswordAuthentication no

Note that match is effective "until either another Match line or the end of the file." (the indentation isn't significant)

A:

Match in sshd_config works well. You should use Match all to end the match block if you're using openssh 6.5p1 or above. Example:
PasswordAuthentication no
Match User root
PasswordAuthentication yes
Match all

A:

There are a few ways that you can do this - first, you could concievably run a second sshd daemon on a different port with different config - its a bit of a hack, but with some chroot work it should work just fine.
Also, you could allow password authentication, but lock the passwords
for all but the one user. The users with locked passwords will still be
able to authenticate with public keys.


Q:

Why is the display of QgsMessageBar delayed?

When a function is called - a file is tested for existence.  This checksum pushes a messageBar() object for both circumstances (True/False), yet the actual bar does not
display in MapCanvas until after the subsequent exec_() is called and finished running.
def callUtherPendragonsSon(self):
    holyGrailFile = 'C:\ALongWayFrom\camelot.csv'
    if os.path.exists(holyGrailFile):
        self.iface.messageBar().pushMessage("Notice", "You will need many coconuts...",\
                                            level=QgsMessageBar.INFO, duration=3)
        beginTheJourney = gatherProvisionsAndMen()
        beginTheJourney.exec_()
    else:
        self.iface.messageBar().pushMessage("Warning", "There is no grail :( ",\
                                            level=QgsMessageBar.CRITICAL, duration=3)
        return

Is there a means to assure the message bar is pushed prior to calling the exec_() ?
UPDATE (1):
As it turns out, a command in the external Ui gatherProvisionsAndMen()'s init  is causing the trouble.  It is a data-thirsty function call, and seems to supersede the messagebar (even though it is executed thereafter).   The messageBar itself is intended to preliminarily notify the user of this nested 'lengthy process' - but it seems such a notice needs to take place in another manner...
Perhaps I hold a misunderstanding in the logistics of programming but,
wouldn't the call to push a QgsMessageBar() need to complete before moving forward and executing the external Ui?

A:

Just put dummy print 'xxx' statement immediately after self.iface.messageBar().pushMessage call.


Q:

Using Fluent NHibernate Persistence Tester Tool with Object that has encrypted Password field

First of all: I am completely new to Fluent and NHibernate.
I have a User object that contains a password field.  When setting that field  the value gets encrypted.  Now I try to use the
new PersistenceSpecification<User>(session)
    ...
    .CheckProperty(p => p.Password, "secret")
    ...
    .VerifyTheMappings();

persistence checker tool.  The problem I am facing is the handling of the password field.  The debugger told me that the tool calls the Password field setter multiple times.  The first time with the cleartext password "secret".  The following times with the encrypted versions ending up with encrypting my password multiple times.
Any idea how to cope with this?

A:

EDIT:
NHibernate has to set the password on the user after it loaded it from db and when you use the standard
Map(user => user.Password);

it will use the property to set the db-value
Map(user => user.Password).Access.CamelCaseField(Prefix.Underscore);

prevents this then


Q:

Embedding Jetty 9 using ServletContext

I'm trying to upgrade from Jetty 7 to Jetty 9 using the samples here:
http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e18177
Server server = new Server(8080);
ServletContextHandler context=new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
HttpServlet servlet=new TestServlet();
context.addServlet(new ServletHolder(servlet), "/*");
server.setHandler(context);
server.start();
server.join();

However, it dies at runtime:
java.lang.NullPointerException
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:304)
at org.eclipse.jetty.util.component.ContainerLifeCycle.addBean(ContainerLifeCycle.java:213)
at org.eclipse.jetty.server.Server.<init>(Server.java:128)
at org.eclipse.jetty.server.Server.<init>(Server.java:103)

The servlet in the sample is a simple hello world sample.

A:

Below is an example using Jetty9 Embedded/Servlets using a supplied Jetty 'DefaultServlet' class.
public static void main(String[] args) throws Exception {
  Server server = new Server(8080);
  ServletContextHandler context=new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  DefaultServlet defaultServlet = new DefaultServlet();
  ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
context.addServlet(holderPwd, "/*");
  server.setHandler(context);
  server.start();
  server.join();
}

Output:

2014-04-08 10:04:18.173:INFO::main: Logging initialized @132ms
  2014-04-08 10:04:18.243:INFO:oejs.Server:main: jetty-9.1.3.v20140225
  2014-04-08 10:04:18.282:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@52e21a17{/,null,AVAILABLE}
  2014-04-08 10:04:18.298:INFO:oejs.ServerConnector:main: Started ServerConnector@7388665b{HTTP/1.1}{0.0.0.0:8080}
  2014-04-08 10:04:18.298:INFO:oejs.Server:main: Started @259ms


Q:

Show that the cardinal of $ A := \left\{ k \in \mathbf{Z} | 0 \leq k \leq n \text{ and } \binom{n}{k} \text{ is odd} \right\} $ is a power of 2

Let $ A := \left\{ k \in \mathbf{Z} | 0 \leq k \leq n \text{ and } \binom{n}{k} \text{ is odd} \right\}  $.
I must show that the cardinal of $A$ is a power of 2.
I have tried to show that there exist a bijection between $A$ and the set of subparts of another set, but unsuccessfully.
I also thought about trying to show that the cardinal of $A$ must divide the cardinal of $ P(\left\{ k \in \mathbf{Z} | 0 \leq k \leq n \right\}) $ (it is $ 2^{n+1} $), which would ensure the result, but I do not think this a good path.
Are there simple arguments to show that ?

A:

Let $n=a_r\cdot2^r+\cdots+a_1\cdot2+a_0$ where all $a_i\in\{0,1\}$. For $0\le k\le n$ let $k=b_r\cdot2^r+\cdots+b_1\cdot2+b_0$ where all $b_i\in\{0,1\}$.
For convenience, denote $Z=\{i:a_i=0\}$ and $N=\{i:a_i=1\}$. Then Lucas Correspondence tells us that
$\binom{n}{k}$ is odd if and only if $\prod_{i\in Z}\binom{0}{b_i}\cdot\prod_{j\in N}\binom{1}{b_j}=1$. Since $b_i,b_j\in\{0,1\}$, we can conclude that $\binom{n}{k}$ is odd if and only if $b_i=0$ for all $i\in Z$. This implies that the number of integers $k$ such that $\binom{n}{k}$ is odd is exactly $2^{|N|}$.


Q:

convergence of the sum of reciprocals of "fake twin" primes

This question is inspired by the announcement of a proof that "fake twin" primes, i.e. pairs of consecutive primes differing by at most K, are -in infinite number- where K is a fixed integer which can be taken = 70,000,000.
It is not known OTOH whether the above would hold where K would be  = 2 instead (the twin prime conjecture).
Anyway, my question may be (hopefully is)  much simpler : it's been known after Viggo Brun that the sum of reciprocals of actual "twin primes" is finite (whether the number of terms in this sum is finite or infinite). Does the sum of reciprocals of the "fake twins" as defined above (for K=70 million) also converge ? Does it follow from an easy extension of Brun's method ?
I should make it clear I am no expert, just curious... I do not have accesss to a proof of Brun's original theorem, even a sketchy one.

A:

Your instinct is correct: the same proof that establishes the convergence of the sum of the reciprocals of the actual twin primes also establishes the convergence of the sum of the reciprocals of "$K$-twin primes" for any value of $K$.
To give a tiny amount of detail: sieve methods (which Brun pioneered) can show that the number of primes $p\le x$ for which $p+K$ is also prime is at most $c(K) x/\log^2 x$, for some constant $c(K)$ depending on $K$. This is enough to show that the sum of the reciprocals of such primes $p$ converges (consider the contribution of such primes between $2^n$ and $2^{n+1}$, then sum over $n$).


Q:

How to change a transposed table to make it horizontally scrollable?

I am making a table for products comparison. It's a table with vertical rows, a header at the left side and two or more product descriptions in vertical rows inside table body. It should be horizontally scrollable in case if user chooses a lot of products.
I have used CSS from this answer to transpose a table (i.e. make vertical rows). And now I can't manage to add a horizontal scrollbar inside tbody in case if table exceeds the predefined width. I am looking for something similar to this question but applied to my transposed table.
Here's what I have now: JSFiddle and here's what happens when I limit the table width to 200px:

A:

Try the combination of inline-blocks and nowrap:

table { border-collapse: collapse; white-space: nowrap; }
tr { display: block; float: left; }
th, td { display: block; border: 1px solid black; }
tbody, thead { display: inline-block; }

tbody {
  width: 300px;
  overflow-y: hidden;
  overflow-x: auto;
}

      name
      number

      James Bond
      007

      Lucipher
      666

      Jon Snow
      998

table shouldn't be displayed as block, if it not necessary for your other layout
I've added white-space: nowrap to prevent line wrapping
I've displayed tbody and thead as inline-block so now you can manage them like inline elements.

If you would like to scroll the tbody only without thead, it might looks like this:

table { border-collapse: collapse; white-space: nowrap; }
tr { display: inline-block; }
th, td { display: block; border: 1px solid black; }
tbody, thead { display: inline-block; vertical-align: top; }

tbody {
  width: 150px;
  overflow-y: hidden;
  overflow-x: auto;
  white-space: nowrap;
}
tbody tr { margin-right: -5px;}

      name
      number

      James Bond
      007

      Lucipher
      666

      Jon Snow
      998

You can think about blocks layout instead. In fact you've already implemented itexcept the HTML what is a bad pattern.


Q:

Devexpress can I update project with devexpress 12 to 17 but it's still run well on Windows XP?

My company has used the Devexpress 12 since 10 years ago and now I'm researching how to update it's version to newest version like 17.2.6 but I'm confusing that the project will not run on Windows XP anymore, that's all, thanks!

A:

Current major is v17.2
it still supports the .net 4 and works well on the win xp with last updated .net 4.
so DevExpress controls works well on .net 4, but may be a lacks on desktop features (WPF platform for example). WinForms should works well.
documentation says 17.2.6, Supported Frameworks: .NET Framework 4.0+
but please note that Win XP is currently not supported by the Microsoft.


Q:

Custom malloc for lots of small, fixed size blocks?

I need to allocate, and free lots of fixed size, small (16 byte) blocks of memory, in no fixed order.  I could just call malloc and free for each, but that will probably be very inefficient.  A better solution probably would be to call malloc and free for larger blocks, and handle the allocation within those blocks itself.
The question is, how best to do this?
It seems that this should not be a very unusual problem or rare problem, and that it should have been "solved", but I can't seem to find anything.  Any pointers?
To clarify, I am aware that memory pool libraries, and what-not exist, but these also take a size parameter.  If the size is constant, then different options for more efficient algorithms are available, are there any implementations of these?

A:

You're right, it's a common problem [Edit: how to do fixed-size allocation, I mean. "malloc is slowing down my application" is less common than you might think].
If your code is too slow and malloc a plausible culprit, then a simple cell allocator (or "memory pool") might improve things. You can almost certainly find one somewhere, or it's easy to write:
Allocate a large block, and put a singly-linked list node at the start of each 16-byte cell. Link them all together. To allocate, take the head off the list and return it. To free, add the cell to the head of the list. Of course if you try to allocate and the list is empty, then you have to allocate a new large block, divide it into cells, and add them all to the free list.
You can avoid that big up-front work if you want. When you allocate a big block, just store a pointer to the end of it. To allocate, move your pointer back 16 bytes through the block and return the new value. Unless it was already at the start of the block[*], of course. If that happens, and the free list is also empty, you need a new large block. Free doesn't change - just add the node to the free list.
You have an option whether to deal out of the block first, and check the free list if that's exhausted, or to check the free list first, and deal off the block if that's empty. I don't know which tends to be faster - the good thing about a last-in-first-out free list is that it's cache-friendly, since you're using memory that was used recently, so I'd probably try that first.
Note that the list node is not needed while the cell is allocated, so there's essentially zero overhead per cell. Quite aside from speed, this is likely to be an advantage over malloc, or other general-purpose allocators.
Do be aware that dropping the whole allocator is pretty much the only way to release memory back to the system, so users who are planning to allocate a lot of cells, use them, and free them all, should create their own allocator, use it, and then destroy it. Both for performance (you don't have to free all the cells) and to prevent the fragmentation-style effect where a whole block must be kept if any of its cells are in use. If you can't do this, your memory use will be the high-water-mark of the time your program has been running. For some programs that's a problem (for instance a long-running program with occasional big spikes in memory use, on a system where memory is constrained). For others it's absolutely fine (for instance if the number of cells in use increases until very near the end of the program, or fluctuates within a range where you really don't care that you're using more memory than you strictly could). For some its actively desirable (if you know how much memory you're going to use, you can allocate it all up-front and not have to worry about failures). For that matter, some implementations of malloc have difficulty releasing memory back from the process to the OS.
[*] Where "start of the the block" probably means "the start of the block, plus the size of some node used to maintain a list of all blocks, so they can all be freed when the cell allocator is destroyed".

A:

Before embarking on the onerous task of re-writing malloc, the standard advice applies.  Profile your code, and make sure that this is actually a problem!

A:

The best way to do this is to not assume it will be inefficient.  Instead try out the solution with malloc, measure the performance and prove that it is either efficient or not.  Then once it's provide to be innefficient (likely won't be) is the only time you should move to a custom allocator.  Without the proof you'll never know if your solution is actually faster or not.


Q:

Easily digestible UI tips for developers

What are some key UI design tips that every developer should know?
While there are a number of UI resources for developers (for example, Joel Spolsky's User Interface Design for Programmers), I'm interested in more of a bullet list that can be communicated in 1 to 2 pages.
I'm interested in more tactical, day-to-day UI tips, as opposed to overarching UI design goals that would be covered in a UI design meeting (presumably attended by at least one person with a good UI sense).  A collection of these tips might cover about 80% of the cases that an everyday programmer would come across.

A:

use a standard menubar (amateur GUI designers seem to like to chart their own course here for some reason). Make sure the first items are File, Edit and View, and the last one is Help
don't worry about color themes or skins; stick to a standard look that is consistent with your platform
use the default system font
use menu accelerators that are consistent with your platform
stick to the tried and true layout with a menubar on top, a status bar on the bottom, and if required, a navigation pane on the left
never do a system-wide grab
If you have a choice, make all windows resizable.
use groups of radiobuttons for "choose exactly one". Always make sure one of them is selected by default. If you want the user to be able to not choose any, add another radiobutton for "no choice"
use groups of checkbuttons for "choose zero or more"
constrain input if necessary (ie: simply ignore non-digits in a numeric input field) rather than waiting for a user to enter data, submit, then throw up a dialog saying "hey, letters aren't allowed!". If they aren't allowed, don't accept them in the first place.
be liberal in what you accept as input. For goodness sake, don't throw a fit for a SSN field if they leave out the hyphens, or put then in when you don't want them. The computer is smart, let it figure out that xxxxxxxxx and xxx xx xxxx and xxx-xx-xxxx are all valid social security numbers.
always allow spaces in long fields such as serial numbers and whatnot. Data quality goes way up if a user is allowed to group numbers in sets of three or four. If your data model can't handle the spaces you can remove them before saving the data.
Avoid pop-up dialogs like the plague. Never display one unless you absolutely must. If you decide you must, stop and rethink your design before continuing. There are times when they are necessary, but those times are considerably less frequent than you might imagine.
pay attention to keyboard traversal. Most toolkits make an attempt to get it right, but always double-check. A use should be able to use the tab key to traverse the widgets in a logical manner.

All of these rules can, of course, be broken. But only break it if you are breaking it for a justifiable reason.
Remember, the software is there to aid the user, it should be doing what they want, rather than making them do what it wants.

A:

When you are about to perform an action that will change or delete information, don't ask 'are you sure' - users will learn to click the button as part of the action.  Try to allow for an 'Undo' in the system design.

A:

Make the default choice the one most users would be happy with.


Q:

App Engine Backend not working

I'm having a hard time getting a backend to run on the GAE servers.  The following works locally, but not when deployed:
counter.py:
from google.appengine.api import logservice
logservice.AUTOFLUSH_ENABLED = False
logging.error("Backend started!")
logservice.flush()

No log message is seen when deployed.  I've even tried putting syntax error's in, they are not reported either, so it doesn't seem like the backend is actually running my code.  I've tried doing the same in infinite loops with sleeps and such too, same result.
Here is the backends.yaml:
backends:
- name: counter
  start: counter.py
  instances: 1
  class: B1

The backend is listed as running in the management console, but doesn't seem to be actually doing anything.
Anyone able to get a backend running on the GAE servers?  Thanks!

A:

There are three ways to call a backend service: scheduled Backend, tasked Backend and browsed Backend. Try http://counter.appname.appspot.com/path.
Sources:

http://www.pdjamez.com/2011/05/google-app-engine-backend-patterns/
http://www.pdjamez.com/2011/05/google-app-engine-backends/comment-page-1/


Q:

Rails 5 CSV merge export

I'm trying to export CSV file from a table in my rails app. I can export booking.attributes.values and I can export booking.user.attributes.values separately however when I try merge these two I receive an error.
"no implicit conversion of Array into Hash"
Here is my code I am working with including some commented code. The csv file does only pull in the header for booking.attributes though. This is something extra I need to figure out.
Booking model
    def self.to_csv(options = {})
#       desired_columns = ["fname","lname","email","nationality","date_of_birth","phone_number"]
        CSV.generate(options) do |csv|
            csv << column_names
            all.each do |booking|
#               csv << booking.user.attributes.merge(booking.course.attributes).values_at(*desired_columns)
#               csv << booking.user.attributes.values
#               csv << booking.attributes.values
                csv << booking.attributes.merge(booking.user.attributes.values).values
            end
        end
end

Booking Controller
   def index
        @bookings = Booking.all.paginate(page: params[:page], per_page: 20)

        # respond to look for html but also csv data and xls
        respond_to do |format|
        format.html
        format.csv { send_data @bookings.to_csv }
        format.xls
        end
    end

Here is the table view I am trying to recreate in CSV format. This works as intended.

      Name
      Email
      Nationality
      D.O.B
      Phone Number
      Course Name
      Course Start

    <% @bookings.each do | booking | %>

       <%= booking.user.fname %> <%= booking.user.lname %>
        <%= booking.user.email %>
        <%= booking.user.nationality %>
        <%= booking.user.date_of_birth&.strftime("%d/%m/%Y") %>
        <%= booking.user.phone_number %>
        <%= booking.course.title %>
        <%= booking.schedule.start_date&.strftime("%d %B %Y") %>
        <%= link_to 'View User', user_path(booking.user), class: "btn btn-info" %>

    <% end %>

Any direction would be appreciated. Thank you.

A:

I believe your problem is that you are mismatching the booking's attributes (a hash) with the booking's user's attributes' values (an array)
Thus as the error message shows, there is no way for the computer to know which values belong to which keys.
My guess is that you intended to write:
booking.attributes.merge(booking.user.attributes).values
You did write:
booking.attributes.merge(booking.user.attributes.values).values
Whatever the case, the thing you are merging needs keys!


Q:

Incorrect credentials for pushing to git repository with netbeans8

I've just upgraded to netbeans 8. I have a git repository on bitbucket.org  when I try to push to it with netbeans 7.4 it works fine. If I close Netbeans 7.4 , open NB8 and try to push to the same repository I get:
Incorrect credentials for repository at bitbucket.org:MYACCOUNT/MYPROJECT.git.

How can I fix this?

A:

I know this is a bit old but it comes up when I search every time so I'm going to put the fix here for next time.
To fix this edit your PROJECT/.git/config file where PROJECT is the path of your project.
Change the url line under the [remote "origin"] section:
url = https://YOURUSERNAME@bitbucket.org/YOURUSERNAME/REPO.git

Be sure to replace YOURUSERNAME with your bitbucket username and REPO with your bitbucket repository which should have already been there.


Q:

Lotus Notes create email folder

Goal: excel macro that creates a new lotus notes email subfolder
I am totally new when it comes to VBA and Lotus Notes in general.
I would appreciate if smb would indicate some directions in achieving my goal, because until know I wasn't able to find anything similar.
1) how do I connect to needed mail (regarding this I saw some info, but a clear code example would be great)
2) how do I create the subfolder with a specified name and indicate the folder where it should be created

A:

There is no API for a folder architechture because there really is no folder architecture. Nested folders are an illusion just based on the name of the folder.  I.e., the folder name "folder1\folder2" indicates that folder2 appears to be inside folder1, but the structure is flat as far as all APIs are concerned.
The NotesDatabase.EnableFolder() method will create a folder.  (It's a dumb name for the method!)  Existing folders can be accessed via NotesDatabase.GetView() method because from the high-level API point of view Folder and Views are treated as equals.  The NotesView.Remove() method can be used to delete a folder. The NotesView.Name property is read/write.


Q:

Updating NSDate and NSString in background

Good day! I just want to ask if how can i update this codes in background?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd  hh:mm:ss"];
self.txtTimestamp.text = [formatter stringFromDate:[NSDate date]];

NSString *buyUrl = @"https://docs.google.com/spreadsheet/pub?key=0AkgWFqjLQz0TdHdMQzBsc1lhaGFPZEFCYXBLWEt1Q0E&single=true&gid=3&output=txt";
NSString *buyFile= [NSString stringWithContentsOfURL:[NSURL URLWithString:buyUrl] encoding:NSUTF8StringEncoding error:nil];
self.txtBuydata.text = buyFile;

the date and time is updating IF the app is freshly opened because it is in ViewDidLoad and also the NSString code. Now, How can i update the NSDate and NSString on background every minute? so even the app is in background the NSSting is updating every minute even the app is in background or open. thanks a lot!

A:

You need to use NSTimer to do an action repeatedly.
Example:
- (void)viewDidLoad {
    //...
    //declare "NSTimer *timerTest;" in the .h
    timerTest = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self
                                               selector:@selector(doThisRepeatedly:)
                                               userInfo:nil
                                                repeats:YES];
    //...
}

- (void)doThisRepeatedly:(NSTimer *)sender
{
    NSLog(@"%@",sender);
    //...
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd  hh:mm:ss"];
    self.txtTimestamp.text = [formatter stringFromDate:[NSDate date]];
    //...

    //fyi: if you want to stop the timer from within this method (generally in a condition)
    //then use the following commented line:
    //[sender invalidate];
}

To stop the timer from within another method then reference it by it's object name and simply:
[timerTest invalidate];


Q:

How do I fix the errors in this code (Triangle class in Python)?

I'm trying to test my triangle class, especially at the draw_triangle function but keep getting error: "unbound method forward() must be called with Turtle instance as first argument (got int instance instead)". How do I fix that?
from __future__ import print_function, division
from math import sqrt, degrees, acos
import turtle

class Triangle():
    def __init__(self, a = None, b = None, c = None):
        self.a = a;
        self.b = b;
        self.c = c;

def is_triangle(self):
    s = 0.5 * (self.a + self.b + self.c)
    return (s - self.a) > 0 and (s - self.b) > 0 and (s - self.c) > 0

def perimeter(self):
    return self.a + self.b + self.c

def area(self):
    s = 0.5 * (self.a + self.b + self.c)
    return sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))

def a_angle(self):
    return degrees(acos((self.b ** 2 + self.c ** 2 - self.a ** 2) / (2.0 * self.b * self.c)))

def b_angle(self):
    return degrees(acos((self.a ** 2 + self.c ** 2 - self.b ** 2) / (2.0 * self.a * self.c)))

def c_angle(self):
    return degrees(acos((self.a ** 2 + self.b ** 2 - self.c ** 2) / (2.0 * self.a * self.b)))

def angles(self):
    angA = a_angle(self)
    angB = b_angle(self)
    angC = c_angle(self)
    return angA, angB, angC

def __str__(self):
    return 'lengths =  %d, %d, %d' % (self.a, self.b, self.c) + \
           ', perimeter = %d' % (perimeter(self)) + \
           ', area = %d' % (area(self)) + ', angles = %d' % (angles(self))

def draw_triangle(self):
    window = turtle.Screen()
    t = turtle.Turtle
    t.forward(self.c)
    t.left(180 - a_angle(self))
    t.forward(self.a)
    t.left(180 - b_angle(self))
    t.forward(self.b)
    t.done()
    window.exitonclick()

if __name__ == '__main__':
    triangle1 = Triangle(100,100,72)
    triangle2 = Triangle(100,100,100*sqrt(2))
    triangle3 = Triangle(100,50,50)
    print (triangle1)
    print (triangle2)
    print (triangle3)
    Triangle.draw_triangle(triangle1)
    Triangle.draw_triangle(triangle2)
    Triangle.draw_triangle(triangle3)
    turtle.mainloop()

A:

This seems to work:
from __future__ import print_function, division
from math import sqrt, degrees, acos
import turtle

class Triangle():
    def __init__(self, a = None, b = None, c = None):
        self.a = a;
        self.b = b;
        self.c = c;

    def is_triangle(self):
        s = 0.5 * (self.a + self.b + self.c)
        return (s - self.a) > 0 and (s - self.b) > 0 and (s - self.c) > 0

    def perimeter(self):
        return self.a + self.b + self.c

    def area(self):
        s = 0.5 * (self.a + self.b + self.c)
        return sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))

    def a_angle(self):
        return degrees(acos((self.b ** 2 + self.c ** 2 - self.a ** 2) / (2.0 * self.b * self.c)))

    def b_angle(self):
        return degrees(acos((self.a ** 2 + self.c ** 2 - self.b ** 2) / (2.0 * self.a * self.c)))

    def c_angle(self):
        return degrees(acos((self.a ** 2 + self.b ** 2 - self.c ** 2) / (2.0 * self.a * self.b)))

    def angles(self):
        angA = self.a_angle()
        angB = self.b_angle()
        angC = self.c_angle()
        return angA, angB, angC

    def __str__(self):
        return 'lengths =  %d, %d, %d' % (self.a, self.b, self.c) + \
               ', perimeter = %d' % (self.perimeter()) + \
               ', area = %d' % (self.area()) + ', angles = %d %d %d' % (self.angles())

    def draw_triangle(self):
        window = turtle.Screen()
        t = turtle.Turtle
        t.forward(self.c)
        t.left(180 - self.a_angle(self))
        t.forward(self.a)
        t.left(180 - self.b_angle(self))
        t.forward(self.b)
        t.done()
        window.exitonclick()

if __name__ == '__main__':
    triangle1 = Triangle(100,100,72)
    triangle2 = Triangle(100,100,100*sqrt(2))
    triangle3 = Triangle(100,50,50)
    print (triangle1)
    print (triangle2)
    print (triangle3)

You need "self."  in front of method calls
Here is a slightly modified draw_triangle function.  It runs, but probably doesn't do exactly what you want.
    def draw_triangle(self):
        window = turtle.Screen()
        t = turtle.Turtle()
        t.forward(self.c)
        t.left(180 - self.a_angle())
        t.forward(self.a)
        t.left(180 - self.b_angle())
        t.forward(self.b)
        turtle.done()
        window.exitonclick()

I think you should work on it a bit by yourself now.


Q:

What does "take the line (that)" mean?

While reading god is not Great by Christopher Hitchens, I've come across the following sentence:
This echoes the line taken by the Shinto —another quasi-religion enjoying state support— that Japanese soldiers really fell for the cause of Asian independence.
I can't come up with what take the line means here at all.
I've made my search and found a few examples on the Internet, which are:

“One may take the line that metaphorical devices are inevitable in the early stages of any science and that although we may look with amusement today upon the “essences,” “forces,” “phlogistons,” and “ethers,” of the science of yesterday, these nevertheless were essential to the historical process. (B.F. Skinner, Critique of Psychoanalytic Concepts and Theories)
“If the Creator should take the line that I am born to work and not to sleep, I would agree that I am indeed born to work but I would also make the unanswerable point that I cannot work unless I also rest.” (Sōseki Natsume, I Am a Cat)
Further, let me at once make it plain that in regard to the part that the Church might play I am not going to take the line that it and it alone has the monopoly of so-called healing. (Symposium on the Rehabilitation of the Cancer Disabled: At the Royal College of Surgeons London 1971)

Having considered these examples, I can only suggest, though I'm not so sure, that it might mean have the view that.
Am I right or is it something far more different?
Thank you very much.

A:

See Merriam-Webster's definition 4a: "a course of conduct, action, or thought; especially :  an official or public position", as in the party line.  So take the line that X means something like to adopt X as an official position or stance on an issue.
Your suggestion of have the view that is approximately right, but I think take the line is a little more forceful.  It suggests that this is their view, but it also suggests that they believe it very firmly, might try to convince other people of it, and might take action based on it.


Q:

How to test Angular 1.6 component with injected service?

I want to test my Angular component which is syntactically based on John Papa's styleguide:
'use strict';

 angular.module('MyModule')
    .component('MyCmpnt', MyCmpnt())
    .controller('MyCtrl', MyCtrl);

function MyCmpnt() {

    return {
        restrict: 'E',
        templateUrl: 'myPath/myTemplate.html',
        bindings: {
            foo: '=',
            bar: '<'
        },
        controller: 'MyCtrl',
        controllerAs: 'vm'
    };
}

MyCtrl.$inject = ['MyService'];

function MyCtrl (MyService) {
    // controller logic
}

As you can see I want to inject MyService into the controller and spy in a function on that very service.
My test code:
'use strict';

describe('component: MyCmpnt', function () {

    var $componentController,
        MyService;

    beforeEach(module('MyModule'));

    beforeEach(module(function ($provide) {
        $provide.value('MyService', MyService);

        spyOn(MyService, 'serviceFunc').and.callThrough();
    }));

    beforeEach(inject(function (_$componentController_) {
        $componentController = _$componentController_;
    }));

    it('should initiate the component and define bindings', function () {

        var bindings = {
            foo: 'baz',
            bar: []
        };

        var ctrl = $componentController('MyCmpnt', null, bindings);

        expect(ctrl.foo).toBeDefined();
    });
});

However, this setup lets me run into the following error:

TypeError: undefined is not a constructor (evaluating '$componentController('MyModule', null, bindings)')

A:

The code above has $componentController('MyModule'..., and there is no MyModule component.
MyService variable is undefined when spyOn(MyService... is called. This will throw an error prevent the application from being bootstrapped correctly.
If testing rig uses PhantomJS, this may lead to error suppression in beforeEach blocks, for correct error reporting Chrome Karma launcher is recommended.
If the problem is that MyService is undefined at the point where mocked service is defined, it can be defined in-place as a stub:
beforeEach(module(function ($provide) {
    $provide.value('MyService', {
      serviceFunc: jasmine.createSpy().and.callThrough()
    });
}));


Q:

Generating random number with different digits

So I need to write a program which generates random numbers from 100 to 999, and the tricky part is that the digits in the number can't be the same.
For example: 222, 212 and so on are not allowed.
So far, I have this:
import random

a = int (random.randint(1,9)) <-- first digit
b = int (random.randint(0,9)) <-- second digit
c = int (random.randint(0,9)) <-- third digit

if (a != b and a != b and b != c):
    print a,b,c

As you can see, I generate all three digits separately. I think it's easier to check if there are same digits in the number.
So, now I want to do a loop that will generate the numbers until the requirements are met (now it either prints blank page or the number). Note that it generates only once and I have to open the program again.
In C++ I did that with the 'while loop'. And here I don't know how to do it.
And one more question. How can I code the number(quantity) of random numbers I want to generate?
To be more specific:
I want to generate 4 random numbers. How should I code it?
P.S.
Thank you all for your answers and suggestions, I am really keen on learning new techniques and codes.

A:

To loop until it's ok you can also use while in Python:
from random import randint

a = randint(1, 9)
b = randint(0, 9)
c = randint(0, 9)
while not (a!=b and b!=c and c!=a):
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)

You can also put it in a function:
def generate_number():
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)
    while not (a!=b and b!=c and c!=a):
        a = randint(1, 9)
        b = randint(0, 9)
        c = randint(0, 9)
    return (a, b, c)

And if you want n such numbers (they are not actually numbers since (a, b, c) is a tuple of 3 int values), you can call it n times:
for i in range(n):
    print(generate_number())

If you prefer formatting the values, you can also do:
for i in range(n):
    print('%d %d %d'%generate_number()) # old style formatting
    print('{} {} {}'.format(*generate_number())) # new style

Finally, you can use get n from the command line:
import sys
n = sys.argv[1]

Or you can ask it directly:
n = int(input("Please enter some number: ")) # in python2.x you'd use raw_input instead of input

You'll get an exception if the value cannot be converted; you can catch the exception and loop as for the generation of numbers.
Putting it all together with the typical main construct:
from random import randint
import sys

def generate_number():
    a = randint(1, 9)
    b = randint(0, 9)
    c = randint(0, 9)
    while not (a!=b and b!=c and c!=a):
        a = randint(1, 9)
        b = randint(0, 9)
        c = randint(0, 9)
    return (a, b, c)

def main():
    n = sys.argv[1]
    for i in range(n):
        print('{} {} {}'.format(*generate_number()))

if __name__=='__main__':
    main()


Q:

how to fire an event on my custom switch toggle

i am creating my custom switch but i don't know how to create a custom event which will be fired every time a user toggle the switch
i know that it has something to do with UIControl but i don't know anything about the same.
here is my class
@IBDesignable
public class CustomSwitch: UIView {

    enum MyCustomEvents: UInt{
        case valueChanged
    }

    @IBInspectable public var isOn: Bool = true
    @IBInspectable public var OffColor: UIColor! = .white
    @IBInspectable public var onColor: UIColor! = .green

    public let valueChanged: UIControl = UIControl()

    private var ball: UIView = UIView()
    private var ballwidth: CGFloat!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSwitch()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupSwitch()
    }

    private func setupSwitch() {

        if isOn {
            backgroundColor = onColor
        }else {
            backgroundColor = OffColor
        }

        self.layer.cornerRadius = height/2
        setupBall()

        let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)

    }

    private func setupBall() {
        ballwidth = height-2
        ball.frame = .init(x: 1, y: 1, width: ballwidth, height: ballwidth)
        ball.layer.cornerRadius = ballwidth/2
        ball.backgroundColor = .white

        if isOn {
            self.ball.frame.origin.x = self.width - self.ballwidth - 1
        }else {
            self.ball.frame.origin.x = 1
        }

        self.addSubview(ball)
    }

    public func toggle(_ animated: Bool) {

        isOn = !isOn

        if animated {
            UIView.animate(withDuration: 0.3) {
                if self.isOn {
                    self.ball.frame.origin.x = self.width - self.ballwidth - 1
                    self.backgroundColor = self.onColor
                }else {
                    self.ball.frame.origin.x = 1
                    self.backgroundColor = self.OffColor
                }
            }
        }else{
            if isOn {
                ball.frame.origin.x = width - ballwidth - 1
                backgroundColor = onColor
            }else {
                ball.frame.origin.x = 1
                backgroundColor = OffColor
            }
        }

    }

    @objc private func tapped(_ gesture: UIGestureRecognizer) {
        toggle(true)
    }

}

please help!

A:

You can change your base from UIView to UIControl, and then add a value changed action in your toggle function
public class CustomSwitch: UIControl {
...
...
    public func toggle(_ animated: Bool) {
    isOn = !isOn
    sendActions(for: UIControl.Event.valueChanged)
    ...
    }

and then you can add the target that you need
customSwitchTest.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)


Q:

C Program: Create Linked List Using argv, argc, Segmentation Fault

I have a program that takes in strings using the command line prompts argv and argc. I keep getting a segmentation fault when I go to run the code and after much researching, I cannot determine what might be causing this. Maybe how I execute the code is the issue? I am using gcc -o code code.c then ./code one two three with one two three being the strings added to the linked list. Any assistance in determining where my error might be would be great.
Here is my code:
#include <stdio.h>
#include <stdlib.h>

typedef struct list_node_s{
    char the_char;
    struct list_node_s *next_node;
}list_node;

void insert_node(list_node *the_head, char the_char);
void print_list(list_node *the_head);

int main(int argc, char *argv[]){
    char next_char;
    list_node *the_head = NULL;
    insert_node(the_head, next_char);
    the_head->next_node = malloc(sizeof(list_node));
    if(the_head == NULL){
            return 1;
    }

    the_head->the_char = 1;
    the_head->next_node == NULL;
    int the_count, the_count2;
    for(the_count = 0; the_count < sizeof(argv); the_count++){
            for(the_count2 = 0; argv[the_count][the_count2] != '\0'; the_count2++){
                    next_char = argv[the_count][the_count2];
                    insert_node(the_head, next_char);
            }
    }

    print_list(the_head);
    return (0);
}

void insert_node(list_node *the_head, char the_char){
    list_node * current_node = the_head;
    while (current_node->next_node != NULL) {
        current_node = current_node->next_node;
    }

    current_node->next_node = malloc(sizeof(list_node));
    current_node->next_node->the_char = the_char;
    current_node->next_node->next_node = NULL;
}

void print_list(list_node *the_head){
    if(the_head == NULL){
            printf("\n");
    }else{
            printf("%c", the_head->the_char);
            print_list(the_head->next_node);
    }

}

A:

Change this:
list_node *the_head = NULL;
insert_node(the_head, next_char);
the_head->next_node = malloc(sizeof(list_node));

to:
list_node the_head = { '\0', NULL };

to initialize the_head to an empty node.


Q:

Xubuntu menu bar disappeared after unplugging external monitor

I've searched for something similar to this problem and I didn't find it. I apologise if it's a duplicate.
I'm trying Xubuntu installed ontop of my Ubuntu 13.10. I've been trying to connect an external monitor and extend the desktop. It worked, no complains there. This is the result (left: latop - right: 24" VGA external monitor):

However, when I go back to the laptop screen only the menu bar disappears, as shown on the next screenshot:

If I plug in/activate the external monitor again it goes back to work normally as shown earlier.
Update:
output of xrandr as requested (no external monitor)
Screen 0: minimum 320 x 200, current 3286 x 1080, maximum 32767 x 32767
LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 277mm x 156mm
   1366x768       60.0*+
   1360x768       59.8     60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
VGA1 disconnected 1920x1080+1366+0 (normal left inverted right x axis y axis) 0mm x 0mm
HDMI1 disconnected (normal left inverted right x axis y axis)
DP1 disconnected (normal left inverted right x axis y axis)
HDMI2 disconnected (normal left inverted right x axis y axis)
HDMI3 disconnected (normal left inverted right x axis y axis)
DP2 disconnected (normal left inverted right x axis y axis)
DP3 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)
  1920x1080 (0x4d)  148.5MHz
        h: width  1920 start 2008 end 2052 total 2200 skew    0 clock   67.5KHz
        v: height 1080 start 1084 end 1089 total 1125           clock   60.0Hz

External monitor plugged in:
Screen 0: minimum 320 x 200, current 3286 x 1080, maximum 32767 x 32767
LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 277mm x 156mm
   1366x768       60.0*+
   1360x768       59.8     60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
VGA1 connected 1920x1080+1366+0 (normal left inverted right x axis y axis) 531mm x 299mm
   1920x1080      60.0*+
   1600x1200      60.0
   1680x1050      60.0
   1280x1024      75.0     60.0
   1440x900       59.9
   1280x960       60.0
   1152x864       75.0
   1024x768       75.1     70.1     60.0
   832x624        74.6
   800x600        72.2     75.0     60.3     56.2
   640x480        75.0     72.8     66.7     60.0
   720x400        70.1
HDMI1 disconnected (normal left inverted right x axis y axis)
DP1 disconnected (normal left inverted right x axis y axis)
HDMI2 disconnected (normal left inverted right x axis y axis)
HDMI3 disconnected (normal left inverted right x axis y axis)
DP2 disconnected (normal left inverted right x axis y axis)
DP3 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

A:

OK, the issue is that when you unplug the monitor, your desktop settings are not refreshed and the system still thinks it has a second monitor attached. This can probably be fixed using udev rule but they can get complicated for this kind of thing. I have written a little script that refreshes my desktop and I have mapped it to a shortcut key so I can easily run it and fix this type of issue. I have modified it to match your setup based on the output of your xrandr
#!/usr/bin/env bash

## If the VGA1 screen is currenlty connected
if ( xrandr | grep VGA1 | grep -qw connected )
then
    ## print a pretty message
    notify-send "Extending desktop to screen VGA1"

    ## extend the desktop to the external screen. If you want your panel
    ## to appear on the right hand screen move the '--primary' flag to
    ## the VGA1: --output VGA1 --primary ...
    xrandr --output LVDS1 --auto  --primary --output VGA1 --auto --right-of LVDS1
else

    ## If the external screen is not connected, refresh the desktop and
    ## make everything appear on the laptop's
    xrandr --output LVDS1 --auto --primary --output VGA1 --off

fi

Save this script as ~/screen_switch.sh, make it executable (chmod +x ~/screen_switch.sh) and then use the System Settings to set a keyboard shortcut that runs it. You can now use the shortcut to fix your problem.


Q:

Binding a value in asp.net

I want to bind the non zero value in the text field.
I have written like this :
  <asp:TextBox ID="txtHaulZoneCodeLEM" runat="server" CssClass="cagText" Text='<%# Bind("HaulZoneCodeLEM") %>'></asp:TextBox

How to make sure the value is non-Zero in this field?. I don't want Zero in this text field.
I am tried like this :its giving syntax error : "Identifier expected"
<asp:TextBox ID="txtHaulZoneCodeLEM" runat="server" CssClass="cagText" Text='<%# Eval("HaulZoneCodeLEM") != 0 ? Eval("HaulZoneCodeLEM") : "" %>'></asp:TextBox>

A:

try this

<%# Eval("HaulZoneCodeLEM").ToString().Equals("0") ? ""
  :Eval("HaulZoneCodeLEM").ToString() %> hope this will help you


Q:

What does "lazy" mean with this code in Kotlin?

What is this code line doing?
fun<T:x>a.b(y: Int)=lazy{u.v<T>(y)}

I do not know what is 'lazy' doing or is 'lazy' something special in Kotlin.

A:

fun<T:x>a.b(y: Int)=lazy{u.v(y)}

Let's break this down. First, let's reformat for readability :)
fun <T: x> a.b(y: Int) = lazy { u.v<T>(y) }
Now, let's go piece by piece.
fun means we're declaring a new method.
<T:x> means this is a generic method operating on type T where T is constrained to be of type x.
a.b means this is an extension function named b on type a.
(y: Int) means that the defined function b takes a single argument named y of type Int.
= is expression body syntax - shorthand for returning a short line of code. This means that a.b will return the value that is the result of evaluating lazy { }
lazy is a Kotlin standard library function that delays the evaluation of the function provided to it until it's needed and then caches the result. The return value of this function is actually a type Lazy that wraps the provided function.
{ u.v<T>(y) } is the function that will be executed by the Lazy object when it's value is obtained the first time and the return value of u.v<T>(y) will be saved as the lazy object's value.
Phew! So what does that mean? Let's look at an example. Suppose we add a print statement to the function to see when it's called.
fun <T: x> a.b(y: Int) = lazy {
  println("Executing 'b'")
  u.v<T>(y)
}

Now if you tried to use it:
fun main() {
  val a = A<T>() // Assume some type T
  val lazyObject = a.b<T>(42) // Call the extension method that returns a `Lazy`

  // Get the value from the lazy object - prints "Executing 'b'",
  // executes `u.v<T>(y)`, caches the result, returns it - then print it
  println(lazyObject.value)

  // Get the value from the lazy object again. This time, DOES NOT print
  // "Executing 'b'", DOES NOT execute `u.v<T>(y)`, and just returns the
  // result that was already computed and cached, then print it
  println(lazyObject.value)
}

So, in summary, the code you posted is creating an extension method that returns a Lazy object that, when queried for its value, executes the lambda it's initialized with and caches that result for later use.
Hope that helps!


Q:

Why is one article used for two nouns and why is it the definite article?

Clara first bought the five-room house, including the kitchen and bathroom, for $3,000 in 1994. (source)

This is the first time ever the article mentions the house's kitchen and bathroom, so shouldn't both be preceded by indefinite articles? Why does the definite article occur here and why is there only one of it?
I thought a sensible sentence should look like:

Clara first bought the five-room house, including a kitchen and a bathroom, for $3,000 in 1994.

A:

Short answer
It's assumed that the five-room house already has a kitchen and a bathroom, and the reader is reasonably expected to make that assumption. Therefore, "the" is appropriate.
Also, "the kitchen and bathroom" can be written as "the kitchen and the bathroom", but the latter is too wordy and thus omitted for conciseness. In "the kitchen and (the) bathroom", the second "the" is understood.
Explanation
The rule for "the" isn't necessarily for its noun to have already been mentioned beforehand. Rather, if the reader (listener) can be expected to reasonably answer the question, "which one?", then "the" is appropriate.
In the case of the sentence you posted, the writer says "including the kitchen and bathroom". The reader can ask "which kitchen and bathroom?", and the reader should be reasonably expected to answer it: "the kitchen and bathroom (in the five-room house)".


Q:

Monitoring File Changes in C#

I'm using C# for a mini project of mine, I am trying to monitor files that are changed, Deleted, And/or created. And export that to a file. But I am not quite sure how to monitor files. Any ideas?

A:

You can use the FileSystemWatcher class to monitor file creation, modifications, deletions and renames.
You have the following events available:

Changed
Created
Deleted
Renamed

A:

you can only monitor one Directory with FSW, if you want more you may have to make multiple instances of FSW. It monitors the directory not the file; if the file is moved (changed+created; changed+renamed) then you need another FSW for that destination folder.


Q:

Restoring unprocessed SKPaymentTransaction for non-renewing subscription

In my app I want to implement non-renewing subscriptions. I have set up (I believe correctly) my logic. I place the observer in the app delegate and then in the class that implements SKPaymentTransactionObserver I implement the following function:
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { }

Within this method I loop through all the updatedTransactions and I check every transactionState, and accordingly I implement my logic.
What troubles me is this: when the transaction is successful I have to contact our servers to update the user's profile and add more days to his/her subscription. This means that I have to call SKPaymentQueue.default().finishTransaction(transaction) after I have received a successful response from our servers. However there is a chance that something goes wrong from the moment that Apple's servers send that the transaction has been completed, until our servers respond.
A shortcut would be to mark the transaction as finished as soon as Apple responds, but by reading the documentation, it doesn't seem correct. How can I restore an unprocessed transaction? (in the case our servers do not respond and the SKPaymentQueue.default().finishTransaction(transaction) is not called).
Thank you in advance.

A:

You should mark the transaction as finished only after your server acknowledges it.
If something does go wrong (let's say a crash occurs) between the time the transaction succeeds but your server hasn't seen it, the transaction will stay incomplete, and will be accessible in SKPaymentQueue.default.transactions right after you add the observer to the queue.
You can then grab those transactions or the receipt and send it to your server for another attempt at increasing the duration of their subscription.
Additionally, from Apple's docs:

For example, consider the case of a user buying something in your app
  right before going into a tunnel. Your app isn’t able to deliver the
  purchased content because there’s no network connection. The next time
  your app is launched, StoreKit calls your transaction queue observer
  again and delivers the purchased content at that time. Similarly, if
  your app fails to mark a transaction as finished, StoreKit calls the
  observer every time your app is launched until the transaction is
  properly finished.


Q:

A question about continuous functions from a closed interval into itself

I got this question:
Let $f, g:[a,b]\to [a,b]$ be functions that are continuous on [a,b] such that $g$ is onto $[a,b]$, Must it be the case that $\exists x \in  [a,b]$ such that $f(x) = g(x)$?
This statement sounds true from an intuitive point of view but how can I prove or disprove it, Thanks.

A:

Hint: consider $c,d$ such as $g(c)=a, g(d)=b $ and consider also
$f-g$ on $[c,d]$.
details:
assume that $f(c)\neq g(c), f(d)\neq g(d)$ (otherwise you are done).
$$f(c)-g(c) > a-g(c)=0
\\
f(d)-g(d) < b-g(c)=0
$$
hence as $f-g$ is continuous, according to the intermediate values theorem,
there is a $X\in (c,d)\subset [a,b]$ such as $f(X)=g(X)$.


Q:

How to insert reports/dashboards inside a lightning component?

I'm facing issues in inserting reports inside the lightning component.
As in VF pages we have analytics report tag or iframe..but in lightning i'm not able to find a solution.
If any body has done it..please share your thoughts.
I have to place  bar graphs,..pie chart..line graphs etc in my components.
Thanks in advance

A:

There is a Report Chart component that can be added to the lightning app builder, however, it is currently not available in the community builder. Documentation have a lightning component in the AppExchange which can be used in the Community Builder, however, it does still require some code/configuration to get it working, but it will handle the rendering for you.

A:

there is a developer blog post on this.
It basically amounts to:

let Apex Controller get Report Data by Report MetaData API
process to your needs and return to lightning component
render as needed
you can also use some JavaScript charting liberaries

General approach:
Transforming Report Data for Lightning Component by D. Peter
JS charting library, and a slightly different approach by p. Battison
enter link description here


Q:

How to pass param from controller to layout in YII2

I want to send a parameter from controller to layout (i.e. main.php). But I am not able to get the param in main.php
I tried:
Controller Code:
$this->render('index',array('param' => $paramValue));

And this is how i was trying to get this in layout ie. main.php

$this->param (as in yii 1)
$param

But i am not able to get param value in layout. Can anyone tell me how to do this?

A:

yii\base\View has special $params property.
For example it's used for building breadcrumbs in default generated CRUD code templates with Gii.
You can set it like this before rendering:
use Yii;

Yii::$app->view->params['customParam'] = 'customValue';

Inside a controller you can set it like this:
$this->view->params['customParam'] = 'customValue';

Then it will be available in views (including main layout):
/* @var $this yii\web\View */

echo $this->params['customParam'];

You can also find it in official guide.


Q:

Clicking "Back" button from a page showing a PDF in Firefox and Chrome causes header to appear in the  tag

I'm running into a very strange error in Firefox and Chrome. The error doesn't occur in Safari. I'm displaying a PDF on a page with the following code (works fine):
header('Content-Length: ' . filesize($pdfPath));
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename="' . $pdfId . '.pdf"');

readfile($pdfPath);

The PDF loads up beautifully, but when I click the back button in the browser (Firefox and Chrome), the page that I jump back to has the HTTP header included in the body tag.
HTTP/1.1 200 OK Date: Tue, 08 Mar 2011 00:18:47 GMT Server: Apache/2.0.63 (Unix) PHP/5.2.13 DAV/2 mod_ssl/2.0.63 OpenSSL/0.9.7l X-Powered-By: PHP/5.2.13 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Length: 7010 Keep-Alive: timeout=15, max=92 Connection: Keep-Alive Content-Type: text/html

This header is for the current page (not the page that displayed the PDF). In debugging, I printed out the body tag with the following jQuery code:
console.log($('body').html());

The header appears before any other content in the body. Any ideas as to what could be causing this rogue header to appear?

A:

Finally figured out what was going on, and the fix was quite simple. I just added an exit() after the readfile(), so the final code ended up looking like this:
header('Content-Length: ' . filesize($pdfPath));
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename="' . $pdfId . '.pdf"');

readfile($pdfPath);
exit();


Q:

A strange question about sequence limit

I found in my professor's lecture note that $\mathop {\lim }\limits_{k \to \infty } {x_k} = x$ is equivalent to "$\exists x$ such that every subsequence $x_{k_l}$ has a subsequence $x_{k_{l_t}} \rightarrow x$".
However, I am puzzled why it is not simply "$\exists x$ such that every subsequence $x_{k_l} \rightarrow x$"? Is my professor right? If my professor is correct, why "$\exists x$ such that every subsequence $x_{k_l} \rightarrow x$" does not lead to $\mathop {\lim }\limits_{k \to \infty } {x_k} = x$? Thank you.

A:

He is right, there is a proposition that says;
$x_n \to  x$ if and only if for every $(x_{n_{k}})$ subsequence of $(x_n)$ you have that $x_{n_k} \to x$ when $k \to \infty$
There is another proposition that says that
$x_n \to x$ if for every subsequence $(x_{n_k})$ of $(x_n)$ there exist a subsequence $(x_{n_{k_j}})$ of $(x_{n_k})$ such that $x_{n_{k_j}} \to x$
There are two different equivalences of $x_n \to x$. You may find useful any of them when trying to solve exercises. Its a nice exercise to prove the second statement if your professor hasn't done it yet.


Q:

Div position related to its container and window

I can't manage to style a div so that it is horizontally positioned at the middle (width) of its container And vertically at the middle of the window height.

A:

Do you mean something like this?

body, html { height: 100%; margin: 0; padding: 0; }

div { padding: 1em; box-sizing: border-box; }

.parent {
  width: 50%;
  background: lightblue;
  border:1px solid blue;
}

.child {
  width: 50%;
  background: lightpink;
  border:1px solid red;
  margin: 0 auto;
  top: 50vh;
  position: relative;
  transform: translateY(-100%);
}

middle

jsFiddle: https://jsfiddle.net/azizn/pxsL7usy/
Logic:
Centering a div horizontally inside its parent/container is pretty easy, we just define a width and add margin: 0 auto.
To make an element in the center of viewport vertically, you can use the CSS viewport units, in this case vh which is viewport height. You apply a non-static position (like relative, absolute or fixed) and a top value of 50vh to offset the div to half of viewport. Then add transform: translateY(-100%) to reduce the element's height from the top offset.


Q:

What was special about ground foods for sacrificial meals?

To avoid repetition, I use 'pabulum' to mean food products ground for sacrificial meals.

[Etymonline:] [...] immolare "to sacrifice," originally "to sprinkle with sacrificial meal," from assimilated form of in- "into, in, on, upon" (see in- (2)) + mola (salsa) "(sacrificial) meal," related to molere "to grind" (see mallet). [...]

The etymology of the English verb 'immolate' implies the importance of pabulum.  This blog asserts 'barley cake' as the pabulum;  while page 79 of  A Companion to Food in the Ancient World
 edited by John Wilkins, Robin Nadea states:

The Greek text
  refers to the pounding of the flour of emmer (far) for the sacrificial meals which would be mixed with salt (mola salsa), and the prohibition applies only in the gender relation that assumes marriage between a traditional Roman citizen and a young free girl.

So what were the pabulum? Anything that was able to be ground?
What is special about pabulum? Why did sacrificial meals require them?

A:

The Roman tradition of animal sacrifice, among many specific acts, required mola salsa to be sprinkled on the victim's head and spine. Along with salt, the grain used to make the mola salsa was far, which is anglicized as either emmer or spelt wheat. According to the NovaRoma site, it came in the form of a cake. An article on Religio et Pietas explains that the sprinkling rituals were required by law and similar to Jewish practices.

A:

Sacrificial meals required pabulum, I believe, because the manual labour of grinding all the ingredients - a long tiring task with mortar and pestle - was a manifest representation of the gift one was personally preparing for the god(s).
This would be especially true for a wealthy individual. Offering a physical object of which one has many is hardly a sacrifice; but every person, wealthy or not, is given only 24 hours in each day, and to spend one's day preparing an offering is a true *sacrifice *. Additionally, it allows both rich and poor to make an equal sacrifice. Certainly the rich man may spend more on the ingredients, but if the true offering is of time he has no more to give than the widow.


Q:

HTML DOM : How to get the whole list of registered event handlers?

For debugging purpose and memory leak, I'd like to have the full list of registered event handlers. There's this nice visual tool but a plain text list would be welcomed.
Cheers.

A:

As the mentioned link says, there is no JavaScript API to retrieve all registered listeners. So, for testing purposes you might try overriding the EventTarget.prototype.addEventListener/removeEventListener methods and storing their arguments in your own storage to inspect later.
On a similar note, you can use the Chrome Developer Tools to examine currently registered listeners for a particular node (or the node chain up to the document root) in the Elements panel ("Event Listeners" section in the sidebar.)


Q:

What convict records for Australia exist?

Esther Emma Leach, born Sydney 15/5/1824, may have been the daughter of a convict transported to Australia in 1813. How do I find convict records not from the first 3 fleets?

A:

There are several very comprehensive collections of records concerning the people exported to Australia from the United Kingdom between 1788 and 1866.

The Convict Database has been compiled from British Home Office (HO) records which are available on microfilm as part of the Australian Joint Copying Project (AJCP). The HO 11 Criminal – Convict Transportation Registers series has been indexed by the State Library of Queensland and the index contains the following information:
Name of convict, including any known aliases
  Place of trial *
  Term of years
  Name of ship and date of departure
  Place of arrival
  Miscellaneous notes e.g. Died at sea; Ticket of Leave, etc.
  * The date of trial is recorded on the original registers and will be gradually added to this database

A search of that database indicates that there were 53 convicts named Leach among the 123,000 records and that 1812 was a particularly bad year for men of that name. There were three among the 200 convicts aboard the Fortune when it sailed in November of that year (reaching Sydney in 1813)

Title: Thomas Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Middlesex Gaol Delivery for a term of 14 years on 10 July 1811.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 85 (44)
  Record number: 1103363
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1103363
Title: Robert Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Middlesex Gaol Delivery for a term of life on 15 January 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 86
  Record number: 1101510
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101510
Title: James Leach, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at York County Assizes for a term of life on 07 March 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 90
  Record number: 1101892
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101892

Of course, all of that is based on the assumption that the putative convict father's name was Leach. If it was not, then you can use these links to run your own searches.
Update
And if it happens that Esther is actually Esther Locke (who married William Watson in 1842) then her father might well be

Title: Stephen Locke, one of 200 convicts transported on the Fortune, November 1812.
  Details: Sentence details: Convicted at Surrey Assizes for a term of life on 27 July 1812.
  Vessel: Fortune.
  Date of Departure: November 1812.
  Place of Arrival: New South Wales.
  Source: Australian Joint Copying Project. Microfilm Roll 87, Class and Piece Number HO11/2, Page Number 89 (46)
  Author/Creator: Great Britain. Home Office. ; State Library of Queensland.
  Subjects: Locke, Stephen ; Fortune (Ship) ; Convicts -- Australia -- Registers ; Australia -- Genealogy
  Publisher: Canberra A.C.T. : Australian Joint Copying Project
  Is Part Of: Criminal : Convict transportation registers [HO 11]
  Record number: 1101887
  Link to this record: http://onesearch.slq.qld.gov.au/primo_library/libweb/action/dlDisplay.do?vid=SLQ&docId=slq_voyager1101887