text:
Q: Prove that $\sum_{p}\frac{\log p}{p^{s}(p^{s}-1)}$ converges for $R(s)>1/2$ I am stydying Zagier's paper, Newman's Short Proof of the Prime Number Theorem. In proof (IV) he states that
$\sum_{p}\frac{\log p}{p^{s}(p^{s}-1)}$
converges for Re(s)>1/2, where $p$ runs over all prime and $s\in\mathbb{C}$. Can anyone help me see why this holds?
I believe I need to use some manner of comparison test, where I prove that $\sum_{n}\frac{\log n}{n^{s}(n^{s}-1)}$ converges for $Re(s)>1/2$ og $n\in \mathbb{N}$


text:
Q: Show N/A in datalabels, when value is null - Highcharts I want to show "N/A" in a column chart, when the data is null.
This is what I am currently trying to do:
http://jsfiddle.net/90amxpc1/1/
dataLabels: {
                formatter: function () {
                    if (this.y == null) {
                        return "N/A";
                    }
                    else {
                        return this.y;
                    }
                }
}

But, its not working. What I want to achieve is similar to the accepted Answer to this Question:
Highcharts: Returning N/A value instead of 0% in data label
or this fiddle: http://jsfiddle.net/v5vJR/3/
I tried modifying it for the column chart, but it doesnt works out.

A: There is just different logic for bar (inverted chart) and column chart, example for column:
            formatter: function () {
                if (this.y == null) {
                    var chart = this.series.chart,
                        categoryWidth = chart.plotWidth / chart.xAxis[0].categories.length,
                        offset = (this.point.x) * categoryWidth + categoryWidth / 2,
                        text = chart.renderer.text('N/A', -999, -999).add();

                    text.attr({
                        x: chart.plotLeft + offset - text.getBBox().width / 2, //center label
                        y: chart.plotTop + chart.plotHeight - 8 // padding
                    });

                } else {
                    return this.y;
                }
            },

Live demo: http://jsfiddle.net/90amxpc1/4/
Note:
You may want to store text variable to remove that text when hiding series or zooming into the chart.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Groovy @Memoize expiry based on custom event I am using groovy to process a batch job, I am planning to cache domain object by using groovy's @Memoize annotation, but problem is the expiry, I want to expire the cache when the job is finished. Is there any way to tell groovy to expire the cache from code?

A: As per the docs, @Memoized features only a max value and a protection cache size parameters.
Since the AST under the covers will create the memoize mechanism through Closure::memoize, you could emulate it with a map and memoized closures which can be disposed:
class Job {
    def log = []
    def repoBase = [
        sum: { a, b ->
            log << "sum $a and $b"
            a + b
        },
        multiply: { a, b ->
            log << "multiply $a and $b"
        }
    ]

    def repo

    def startJob() {
        repo = repoBase.collectEntries { key, value ->
            [(key): value.memoize()]
        } as Expando
    }

    def withJob(Closure c) {
        startJob()
        c.delegate = repo
        c.delegateStrategy = Closure.DELEGATE_FIRST
        c(this)
        repo = null
    }

}

And test:
j = new Job()

j.withJob {
    multiply 3, 4
    multiply 3, 4
    multiply 8, 8
    sum 9, 9
    sum 1, 2
    sum 9, 9
}

assert j.log == [
    "multiply 3 and 4",
    "multiply 8 and 8",
    "sum 9 and 9",
    "sum 1 and 2"
]


text:
Q: update one shapefile attribute table with values from another dbf table I try to explain here what I am trying to do:
I have one shapefile and one independent dbf table with the same fields. In the dbf table all the fields are populated but in the shapefile attribute table just one, lets name it "OneField". What I want to do is to check that the values from "OneField"(Shapefile) are the same as the values in "OneField"(dbf table) and if so, to populate the remaining empty fields in the shapefile attribute table with the ones in the independent dbf table.
At the moment I am trying just to copy the values from the independent dbf table to the shapefile attribute table but I am stuck.(when I run this code I get a message that pythonwin stopped working and nothing happens to the tables). Can you give me a hand please?
Here is the code:
import arcpy

table = "link/to/table.dbf"
fc = "link/to/shapefile.shp"

# Create a search cursor

rowsTable = arcpy.SearchCursor(table)

# Create an update cursor

rowsFc = arcpy.UpdateCursor(fc)

for row in rowsTable:
    row = row.getValue("OneField")
    valueTable = row
    for row in rowsFc:
        row = row.setValue("OneField", valueTable)
        rowsFc.updateRow(row)
        row = rowsFc.next()
    row = rowsTable.next()

del row, rowsFc, rowsTable

Thank you very much

A: That's exactly what QGIS ftools "Join by Attribute" tool is doing. It takes a shapefile and a dbf file (or a second shapefile) and joins their attribute tables. The tool is written in python, so you should find everything you need here: http://trac.osgeo.org/qgis/browser/trunk/qgis/python/plugins/fTools/tools/doJoinAttributes.py

A: From the code point of view, looks like you're using "row" for a bunch (~4) different things, some of which appear to be unnecessary.  I don't do much with arcpy, but I'd imagine something like this would work better. If it did, you'd end up with the whole OneField column in your FC populated with the last value of OneField from your table:
for rowT in rowsTable:
    valueTable = rowT.getValue("OneField")
    for rowF in rowsFc:
        rowF.setValue("OneField", valueTable)
        rowsFc.updateRow(rowF)
        rowF = rowsFc.next()
    rowT = rowsTable.next()

A: I spent a good amount of time trying to this myself and I've got something that works.  Refer to my code here to get it working.
How to update feature class by iterating through values with branching?.
You'll need to make a list that contains all the fields so you can iterate through them.

A: My method for moving data from a dbf to a shapefile. Is to (of course I prefer to do this inside a gui software) join the dbf to the shapefile.
At that point I normally select attributes that are not null (I do this on the id field of the second table). If they are not null then they did match.
Once this is done you can select the the values by shapefile.onefield <> table.onefield.
Then run your calculation in the shapefile.

A: Sorry for not answering your question, but I would definitely do this in db-environment instead. Especially if it is a lot of data, then that will probably be a lot faster.
If you for instance load the shapefile and the dbf into a PostGIS db your query could look something like this:
CREATE TABLE new_table AS
SELECT a.the_geom, a.populated_field, b.populated_field2, b.populated_field3
FROM shape_table a LEFT JOIN dbf_table b ON a.populated_field=b.populated_field1;

If you put index on the joining fields, this should be very fast.
You can of course update shape_table instead, but  like to create a new table instead to not destroy the original data.


text:
Q: How to handle values with spaces in Process.Start in C# I have a button, and I use Process.Start when clicking it, although I select data from textBox1.Text.
Although this data on textBox1.Text does not come out properly if there are spaces in textBox1.Text
e.g. textBox1.Text = testing_123 works
although textBox1.Text = testing 1 2 3   doesn't work (it will only include "testing")
The code is below:
    private void button19_Click(object sender, EventArgs e)
    {
        Process.Start("test.exe", textBox1.Text);
    }

A: Simply quote the args like this before passing:
private void button19_Click(object sender, EventArgs e)
{
    Process.Start("test.exe", "\"" + textBox1.Text + "\"");
}

A: Add quotes around your argument string.

A: If you just want to get rid of the spaces:
TextBox1.Text.Replace(" ",string.Empty)

Or if you want to substitute another character (underscore) then try:
TextBox1.Text.Replace(" ","_")

If you want to include the space then @Teoman has your answer...
It depends on what you mean by "handle".


text:
Q: Comparing url path in Django 2 middleware I need to develop a Django middleware and created class like this:
import re
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth import logout

class LoginRequiredMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')

        path = request.path_info
        print(path)

        p = path.lstrip('/')
        compiled_login_url = re.compile(settings.LOGIN_URL)

        print(compiled_login_url.match(p))

        if not request.user.is_authenticated:
            if path == '/':
                print("==============> INDEX PAGE")

Now here, I want to compare the path of urls. I have to determine if path match with settings.LOGIN_URL or not. I have tried using regular expressions, but they did no help.
Here are my urls
urlpatterns = [
              path('admin/', admin.site.urls),
              path('', views.index, name='index'),
              path('<slug:slug>/', include('app.urls')),
              path('<slug:slug>/accounts/login/', views.login, name='login'),
              path('<slug:slug>/accounts/logout/', views.logout, name='logout'),
              path('<slug:slug>/dashboard/', 'views.dashboard', name='dashboard'),
          ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I want to exempt login and logout from being checked in middleware also I need slug.
views.py
def user_login(request, slug):
    """
    Login user using email and password

    :param request: WSGI Request
    :param slug: to verify the facility
    :return: login page or redirect
    """

    context = {}
    try:
        facility = models.Facility.objects.get(slug=slug)
        context['facility'] = facility

    except models.Facility.DoesNotExist:
        return redirect('index')

    if request.method == "POST":
        email = request.POST['email']
        password = request.POST['password']

        user = authenticate(request, username=email, password=password)
        if user is not None:
            if user.profile.facility.slug == slug:
                login(request, user)
                return redirect('dashboard', slug=slug)
            else:
                context['error'] = "You don't belong to this facility"

        else:
            context['error'] = "Invalid email or password"

    return render(request, 'app/user/login.html', context)

@login_required
def dashboard(request, slug):
    """
    Display the dashboard of facility and list down bird
    view for the daily, weekly, monthly and yearly progress

    :param request:
    :return:
    """
    context = {}

    try:
        facility = models.Facility.objects.get(slug=slug)
        context['facility'] = facility
    except models.Facility.DoesNotExist:
        return render(request, 'app/404.html', status=404)

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    {% for f in facilities %}

{{ f.name }}

    {% empty %}

No Facility

    {% endfor %}

A: You could add Django's auth views one by one to your urlpatterns, decorating each with login_exempt.
OR
If you would like to move the checking into the middleware you could try something like:
urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("myapp.urls")),
    path('accounts/', include('django.contrib.auth.urls', namespace="accounts"))
]

middleware.py
class LoginRequiredMiddleware:            # <-- Custom Middleware
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_view(self, request, view_func, view_args, view_kwargs):

        if getattr(view_func, 'login_exempt', False):
            return

        if 'accounts' in request.resolver_match.namespaces:
            return

Other possibilities would maybe be checking the url or view name in the middleware, but still maybe the cleanest would be using your decorator and add the necessary views one by one.
OR
You can use django-decorator-include for this.
$ pip install django-decorator-include

In you project/url.py
from decorator_include import decorator_include
from project/custom_middleware import login_exempt

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("myapp.urls")),
    # do this
    path('accounts/', decorator_include(login_exempt, 'django.contrib.auth.urls'))

]

Don't forget to add the package in requirements.txt


text:
Q: Array is not working as expected in php I am running into a very strange issue.
I have a function which prints the columns name of a given database table from MySql.
function getColoumn() {

    //replace it with your host normally it could be localhost
    $hostname='localhost';
    //mysql user name
    $username='admin_datauser';
    //mysql user password
    $password='iCoq4KrJM8';
    //connect to the mysql server
    $ss = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
    //select a database on the mysql server
    //please change as you like the database name
    mysql_select_db('admin_data');

    //SHOW COLUMNS FROM TABLENAME
    $query=mysql_query('SHOW COLUMNS FROM user') or die(mysql_error());

    foreach($fields as $key=>$field){
    echo '"'.$field->Field.'", '; // print each field name

    }
}

The output looks like below-
"id", "first_name", "last_name", "email", "address", "country", "city", "state", "phone_number", "fax", "image", "datecreated", "dateupdated", "Company", "token",

I have another array variable where the current static values are like below-
$searchArray = array("first_name","last_name","email","address","country","city","state","phone_number","fax","image");

I need to use the function's variable in this $searchArray. I tried calling the variable in the arrya but it doesn't work in any way.
Any help please??

A: first of all you shouldn't use mysql_ functions anymore since they are deprecated and prone to SQL injections. rather use PHP's own PDO or mysqli libraries.
then it's much easier to directly add the elements to your array in the foreach loop:
$searchArray = array();

foreach($fields as $key=>$field){
    $searchArray[]= $field->Field;
}

note: the []= operator in PHP acts similar to the += operator. but instead of adding to a number value, it adds elements to an array.


text:
Q: Need facebook like button without count
Possible Duplicate:
Facebook Like-Button - hide count?

I need facebook like button without count information. I tried it with giving 50px width. but when someone "like" the page its turn in "you liked it" and distorting the UI.
I need just like image without counr.
Thanks
Suren

A: Can you wrap it in div containers w/ absolute dimensions & float it. . . so the overflow wont disrupt anything.

A: Just give a width of 47px and it seems to works fine. I think they have changed the UI recently - now when you like it there is just a tickbox added to the like button and it doesn't distort the UI.

A: NB. Facebook localizes the button - so the "like" button might be in a different language. Then of course this image is not a standard width - so you cant guarantee being able to hide it by setting width of iframe or css settings.

A: I do not think it is possible. The whole UI is driven from Facebook and you can see all the variations here http://developers.facebook.com/docs/reference/plugins/like/
However, if you want, you may apply some CSS/JavaScript hack. The count is under uiGrid class, you may target this element and set display none after the page has rendered. In JQuery, you would $('.uiGrid').hide()
But the suggestion above is not recommended.

A: Here's a question with several much more detailed answers to the different ways of doing this:
http://facebook.stackoverflow.com/questions/2950172/facebook-like-button-hide-count
There are apparently a few cases where the answer is slightly different -- one for the javascript version, one with the iframe version, etc.


text:
Q: perform Post method on current page I have this form where I'm sending a mail (via Post method) :
<form method="POST" action="sendmail.php">
  <input type="text" name="sender_name" placeholder="Name" required="">
  <input type="text" name="sender_email" placeholder="Email" required="">
  <input type="text" name="subject" placeholder="Subject" required="">
  <textarea placeholder="Message" name="message" required=""></textarea>
  <input type="submit" name="send" value="SEND">
</form>

and here's my sendmail.php :
<?php
  if($_POST['send'] == 'SEND'){
    $to      = 'queries@mydomain.com';
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $headers = "From: ".$_POST['sender_name']." <".$_POST['sender_email'].">\r\n"; $headers = "Reply-To: ".$_POST['sender_email']."\r\n";
    $headers = "Content-type: text/html; charset=iso-8859-1\r\n";
    'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
  }
?>

As you can see that in above code I'm sending a mail which is working fine, but the above action is executing by leaving current page
e.g before posting my url is mydomain.com after posting it becomes mydomain.com/sendmail.php.
So how can i execute above function without leaving current page?

A: Do you know about Ajax and jQuery? Read more, here.
Your ajax call can look like this.
    $.ajax({
      url: "yourApplication/methodWhichSendsEmail",
      type: "post",
      data:JSON.stringify({
           to : $to,
           subject: $subject,
           message: $message,
           headers: $headers
})

}).done(function() {
  //Whatever you want to do once the request is succeed. As you don't want to reload. i.e.
  alert("Email Sent");
});

A: Either by AJAX or you can do the following:

*

*You specify action="" in the <form>

*You include the code from sendmail.php to index.php (or whatever your homepage is)

A: You need to set your form action empty.
Then in PHP code you need to check if form is posted or not. SO need to check it first by php function isset then you can do whatever you want, This will only send email if a form is posted
  if(isset ($_POST['send']) && $_POST['send'] == 'SEND'){
    $to      = 'queries@mydomain.com';
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $headers = "From: ".$_POST['sender_name']." <".$_POST['sender_email'].">\r\n"; $headers = "Reply-To: ".$_POST['sender_email']."\r\n";
    $headers = "Content-type: text/html; charset=iso-8859-1\r\n";
    'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
  }


text:
Q: javascript - Audio with no play method I would like to create an Audio Object using a constructor like this:
       var Audio = function(side, name, src, index, duration) {
           this.side = side;
           this.name = name;
           this.src = src;
           this.index = index;
           this.duration = duration;
       };

I have added many objects to a var audios = [];,
but when I test playback with the first item on the array:
      function playTest(){
         var song = audios[0].src;
         song.play();
      }

I learn that "audio has no play method".
how do I add this Audio() method to my custom constructor?


text:
Q: Iterating through a string for frequency I need to iterate through the strings that I have established by writing 10 random strings to a text file then reading them back in and finding the frequency of each letter in each individual string. I have it up to the point where it reads the file back in but I cant figure out how to find the value of the characters. Any help?
import string
import random
from collections import Counter

print "******************************"

print "********* EXERCISE 5 *********"

print "******************************"

print "\n**** BEGIN RANDOM STRING *****\n"

def random_string_generator():
    size = random.randint(20, 80)
    return "".join(random.choice(string.ascii_lowercase + string.ascii_uppercase)
                   for _ in range(size))

def main():
    with open("exercise_five.dat", "w+") as f:
        for x in range(0, 10):
            data = random_string_generator()
            f.write(data + "\n")
        f.close()
    with open("exercise_five.dat", 'r') as f:
        count = 0
        c = Counter()
        for i in f:
            print i
        print "Count: %i" % count

if __name__ == '__main__': main()
print "*******************************"

The final output should look something like this:
***** BEGIN RANDOM STRING *****
xGYMSlMHGQAMNrSzXWqphkGntMpyjMoHyRDzaNOcmVtoeAZzcV
A ==> 2 D ==> 1 G ==> 3 H ==> 2 M ==> 5 O ==> 1 N ==> 2 Q ==> 1 S ==> 2
R ==> 1 W ==> 1 V ==> 2 Y ==> 1 X ==> 1 Z ==> 1 a ==> 1 c ==> 2 e ==> 1
h ==> 1 k ==> 1 j ==> 1 m ==> 1 l ==> 1 o ==> 2 n ==> 1 q ==> 1 p ==> 2
r ==> 1 t ==> 2 y ==> 2 x ==> 1 z ==> 3
*******************************

my code output right now looks like this:
**** BEGIN RANDOM STRING *****

QheDRPpVwDnfYWYMJQwEedJsjApRVafvMYUYuepYSerkoMgCTnHLSHwCitBr

zOFvifcwkrwXLxTrodqkxNxWVHdHDJZbYlcYjAUKz

DRgFXVkbtwpRfXPjzJmXYW

mpkVgUyvHEHAKUWpMZBYIKenicfdcBhxlqCZHFgxoFEmJjtrPykCzvQnFkTHfVthII

zEXLmudQVlpVQYexAvGFTBeUuZvqTO

KSRcpBlfNwcMoNViHFhS

QhTiBLuGCsClezAiVFYODiJXAQCQjwnBnHjWqlsZlljA

iYHznFLFeKwLtynubHTRtGGwjACdGlCpZSQcqnTSWVmufpHQRkwWYiajarnqNuzUzSC

NWlGeJFFcYwacXuUHWqmzSJmsrnWRvpmdSesXXmECuvAMkxGYpHv

WVAAiDgGaGnovCbbdazNGmWXARgdSfqCSztsNTPBdLumIXiDh

*******************************

A: Picking up from where you defined the Counter, you can initialize the Counter with each line read from the file. That will give you a Counter instance which has keys and values, similar to a dictionary:
with open("exercise_five.dat", 'r') as f:
    for line in f:
        c = Counter(line)
        print(' '.join('{} ==> {}'.format(key, val) for key, val in c.items()))

A more in-depth explanation of the last line:
>>> c = Counter("text")  # initialize a Counter object with the string "text"
>>> c.keys()  # this instance has `keys` and `values`, similar to a dictionary
dict_keys(['e', 't', 'x'])
>>> c.items()  # you can access both keys and values at the same time with `items`
dict_items([('e', 1), ('t', 2), ('x', 1)])
>>> c
Counter({'t': 2, 'e': 1, 'x': 1})
>>> for key, val in c.items():
...     print(key, val)
...
e 1
t 2
x 1

At that point, you merely need to use some string formatting to get the output format you desire, which is what the print(' '.join(...) construct does.

A: defaultdict is a great tool for doing this:
import collections

occurrences = collections.defaultdict(int)

word = 'ASDqasdqASD'

for c in word:
    occurrences[c] += 1
print occurrences
> defaultdict(<type 'int'>, {'A': 2, 'a': 1, 'D': 2, 's': 1, 'q': 2, 'S': 2, 'd': 1})


text:
Q: UserControl Click event not firing Hi this is my aspx page loading some values to the user control
protected void Page_Load(object sender, EventArgs e)
        {

        }

this is the usercontrol where i am loading and sending the values in find click event
protected void BtnFind_Click(object sender, EventArgs e)
        {
            Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
            BPOP.Date = txtDate.Text.Trim();
            BPOP.DocNo = txtDocNo.Text.Trim();
            BPOP.Code = txtCode.Text.Trim();
            BPOP.Name = txtName.Text.Trim();
            BPOP.Partcode = txtPartNo.Text.Trim();
            if (chkReprint.Checked)
            {
                BPOP.BtnReprintVisible = true;
                BPOP.BtnSaveVisible = false;
            }
            divControls.Controls.Clear();
            PlaceHolder1.Controls.Add(BPOP);

        }

this is my Usr_BPOP.ascx:
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnReprint.Click += new EventHandler(btnReprint_Click);
            }

            btnReprint.Visible = false;
            btnSave.Visible = BtnSaveVisible;
            btnReprint.Visible = BtnReprintVisible;
            if (btnReprint.Visible == false)
            {
                btnReprint.Text = "Print";
                btnReprint.Visible = true;
            }
            table = new DataTable();
            table.Columns.Add("DocNum", typeof(string));
            table.Columns.Add("DocEntry", typeof(string));
            table.Columns.Add("LineNum", typeof(string));
            table.Columns.Add("PartNo", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("QTR", typeof(string));
            table.Columns.Add("QTP", typeof(string));
            table.Columns.Add("Chk", typeof(bool));
            table.Columns.Add("BarCode", typeof(string));
            Datalayer dl = new Datalayer();
            DataTable dttable = new DataTable();
            if (!BtnSaveVisible && BtnReprintVisible)
                BtnSaveVisible = true;
            dttable = dl.GetPOItem(date, docNo, code, name, partcode, BtnReprintVisible, !BtnSaveVisible).Tables[0];
            foreach (DataRow dr in dttable.Rows)
            {
                table.Rows.Add(dr["DocNum"].ToString(), dr["DocEntry"].ToString(), dr["LineNum"].ToString(), dr["PartNo"].ToString(),
                    dr["ItemDesc"].ToString(), dr["QTR"].ToString(), dr["QTP"].ToString(), Convert.ToBoolean(dr["Chk"]), dr["Barcode"].ToString());
            }
            if (table != null && table.Rows.Count > 0)
            {
                grdlistofitems.DataSource = table;
                Session["Table"] = table;
                grdlistofitems.DataBind();
            }
            else
            {

            }

        }

this is the reprint button click event when i cilck this event it is not firing:
void btnReprint_Click(object sender, EventArgs e)
        {
}

A: Since you are not setting the ID of the control, it is generated anew every time the control added to the page. The generated ID might not be the same, and therefore the sender of the event cannot be recognized. So first thing you should do is assign an ID explicitly:
Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
BPOP.ID = "SomeID";

Secondly, assignment of the event handler should be done very time the control is created - that is, on every request, does not matter whether this is a postback or not - otherwise ASP.NET will not be able to determine what method should be called when the event is fired:
protected void Page_Load(object sender, EventArgs e)
{
    // No check for postback here
    btnReprint.Click += new EventHandler(btnReprint_Click);

Update. There is one more reason why this code does not behave as expected. The BPOP control is added to the page only on btnFind click. When the postback is caused by anything else, including btnReprint, on the response page generation BPOP control is not added to the page at all. If there is no control on the page - obviously its methods, including event handlers, cannot be triggered.
Here is quick and dirty fix for this situation. It should be applied to the page code where BPOP control is added:
protected void Page_Load(object sender, EventArgs e)
{
    bool? addBPOP = ViewState["AddBPOP"] as bool?;
    if (addBPOP.HasValue && addBPOP.Value)
    {
        AddBPOP();
    }
}

protected void BtnFind_Click(object sender, EventArgs e)
{
    AddBPOP();
    ViewState["AddBPOP"] = true;
}

protected void AddBPOP()
{
    Usr_BPOP BPOP = (Usr_BPOP)Page.LoadControl("~/Usr_BPOP.ascx");
    BPOP.ID = "BPOPID";

    BPOP.Date = txtDate.Text.Trim();
    BPOP.DocNo = txtDocNo.Text.Trim();
    BPOP.Code = txtCode.Text.Trim();
    BPOP.Name = txtName.Text.Trim();
    BPOP.Partcode = txtPartNo.Text.Trim();
    if (chkReprint.Checked)
    {
        BPOP.BtnReprintVisible = true;
        BPOP.BtnSaveVisible = false;
    }
    divControls.Controls.Clear();
    PlaceHolder1.Controls.Add(BPOP);
}

A: Change:
void btnReprint_Click(object sender, EventArgs e)
{
}

To
protected void btnReprint_Click(object sender, EventArgs e)
{
}


text:
Q: Can't bind to 'ngForOf' since it isn't a known property of 'tr'. even importing CommonModule/BrowserModule

Datatable.component. html

 <tr *ngFor="let articles of art">

I have added CommonModule/BrowserModule in appmodule/Datatablemodule nothing works....`same kind of error in FormBuilder also when using "form [formGroup]="loginForm" (ngSubmit)="onSubmit()">" even imported the @angular/forms

//app.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule  } from '@angular/common/http';
import { AppComponent } from './/app.component';
import { AppRoutingModule } from './/app-routing.module';

import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import {AddArticleModule} from './pages/add-articles/add-article.module';
import {DatatablesModule} from './pages/datatables/datatables.module';

@NgModule({
   imports: [
     BrowserModule,
     HttpClientModule,
     AppRoutingModule,
     LayoutModule,
     ReactiveFormsModule,
     AddArticleModule,
     DatatablesModule
   ],
  declarations: [
    AppComponent
  ],

  providers: [ScriptLoaderService],
  bootstrap: [AppComponent]
})
export class AppModule { }

//Datatables
.module.ts
import { NgModule } from '@angular/core';
import {CommonModule} from '@angular/common';
@NgModule({
  declarations: [
  ],
  imports: [
    CommonModule
  ],
  exports: []
})
export class DatatablesModule {}

`


text:
Q: Не выводит ошибку 404 страница не найдена Я хочу в своем проекте вывести ошибку 404 страница не найдена, в том случае если неправильный адрес будет. Я написал код но он не работает.
ErrorController
package adil.java.schoolmaven.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ErrorController {

    @RequestMapping(value = "errors", method = RequestMethod.GET)
    public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {

        ModelAndView errorPage = new ModelAndView("errorPage");
        String errorMsg = "";
        int httpErrorCode = getErrorCode(httpRequest);

        switch (httpErrorCode) {
            case 400: {
                errorMsg = "Http Error Code: 400. Bad Request";
                break;
            }
            case 401: {
                errorMsg = "Http Error Code: 401. Unauthorized";
                break;
            }
            case 404: {
                errorMsg = "Http Error Code: 404. Resource not found";
                break;
            }
            case 500: {
                errorMsg = "Http Error Code: 500. Internal Server Error";
                break;
            }
        }
        errorPage.addObject("errorMsg", errorMsg);
        return errorPage;
    }

    private int getErrorCode(HttpServletRequest httpRequest) {
        return (Integer) httpRequest
          .getAttribute("javax.servlet.error.status_code");
    }

    @RequestMapping(value = "500Error", method = RequestMethod.GET)
        public void throwRuntimeException() {
    throw new NullPointerException("Throwing a null pointer exception");
}
}

Web XML
<?xml version="1.0" encoding="windows-1251"?>

<error-page>
    <location>/views</location>
</error-page>

ErrorPage JSP
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${errorMsg}</h1>
</body>
</html>


text:
Q: MVC3 HTML helper doesn't update DropdownListFor on Submit the form I have a simple HTML form with dropdwonListFor bound to colors, a textBox below it and submit button to submit the form and save the color.
When I select a color from the dropdownlist, it will change the value of the textbox below it,  if the user clicks the submit form. it goes back to the controller and I save the color from the texebox and return view(model) as an action result, but the problem that the dropdownlistfor doesn't get updated with the value of the textbox whether the value in the textbox within the dropdownlist or not.
By the way you can test it urself
Can anybody help please ?
Model.cs
public class TestModel {
    public String Color { get; set; }
}

Controller.cs
public ActionResult Index() {
        var model = new TestModel();
        model.Color="Blue";
        ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
        return View(model);
    }

[HttpPost]
public ActionResult Index(TestModel model) {
        model.Color="Red";
        ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
        return View(model);
}

Index.cs
@using (Html.BeginForm()) {
@Html.DropDownListFor(m => m.Color, ViewData["Colors"], new { @class = "w200" })
<input type="submit" />

}

A: Model
public class TestModel {
    public String Color { get; set; }
    public SelectList Colors {get;set;} }

Controller
public ActionResult Index() {
        var model = new TestModel();
        model.Color="Blue";
        var colors =new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "red" } };
        model.Colors = new SelectList(colors,"Text","Value");

        return View(model);
    }

[HttpPost] public ActionResult Index(TestModel model) {
        model.Color="Red";

        var colors =new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "red" } };
        model.Colors = new SelectList(colors,"Text","Value");

        return View(model); }

View
@using (Html.BeginForm()) {
    <div>
        @Html.DropDownListFor(m => m.Color, Model.Colors, new { @class = "w200" })
       <input type="submit" />
     </div>
}

A: Okay guys, the problem is not about the way you implement this scenario, the problem here is ModelState. I POST to the Action and return the same view. The second time the view is rendered it will look at the ModelState and use those values to fill the controls.
So simply we need to clear the ModelState before returning the View.
Model.cs
public class TestModel {
    public String Color { get; set; }
}

Controller.cs
public ActionResult Index() {
        var model = new TestModel();
        model.Color="Blue";
        ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };

        return View(model);
    }

[HttpPost]
public ActionResult Index(TestModel model) {
        model.Color="Red";
        ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };

        ***ModelState.Clear();***
        return View(model);
}

Index.cs
@using (Html.BeginForm()) {
@Html.DropDownListFor(m => m.Color, ViewData["Colors"], new { @class = "w200" })
<input type="submit" />

}
Cheeeeeers

A: You need to include all colors in your Post action.
Also do not use ViewData but add the items to you view model:
public class TestModel {
    public String Color { get; set; }
    IEnumerable<SelectListItem> AvailableColors {get;set;}
}

But since view models are intended to be used to abstract away your models you could do something like:
public class TestModel {
    public TestModel(IEnumerable<string> colors)
    {
        AvailableColors = colors.Select(c => new SelectListItem{Text=c, Value = c});
    }

    public String Color { get; set; }
    IEnumerable<SelectListItem> AvailableColors {get;}
}

And in your controller:
public ActionResult Index() {
    var model = new TestModel(new string[]{"Red", "Green", "Blue"});
    model.Color="Blue";
    return View(model);
}

A: In order to make the dropdown list change what is selected you have to set the Selected attribute of the select list item corresponding to the textbox value to true.  Something like this: (Note: I did not compile and test this.  Tweaks may be needed to get it to compile. Also, I assumed that if a color was not in the list it should be added.)
[HttpPost]
public ActionResult Index(TestModel model) {
        model.Color="Red";
        var colors = new List<SelectListItem>() { new SelectListItem() { Text =  "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };

        SelectListItem selectedColor = colors.Where(c => c.Text == model.Color).FirstOrDefault();
        if (selectedColor != null)
        {
            selectedColor.Selected = true;
        }
        else
        {
            colors.Add(new SelectListItem() { Text = model.Color; Value = model.Color; Selected = true; };
        }
        ViewData["Colors"] = colors;
        return View(model);
}

EDIT
After doing some testing and digging, it appears that you will need to use javascript to do this as explained in this SO question.  Another option is to roll your own helper.


text:
Q: convert the array to the correct form After converting the file
$rows = array_map('trim', file($lines1));
foreach ($rows as $key => $value) {
  $params = array_map('trim', explode(';', $value));
}

an array of the following type is obtained, which is contained in a variable:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => i need this [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 )
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => i need this [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 )
etc...

how can you combine these arrays and put the values with the key = 3 into separate variables.
View:
Array ( [0] => i need this [1] => i need this and etc...

A: $range = range(1, 100);
$result = array_combine($range, $range);

check array_combine


text:
Q: How do I display "Android backspace" - ⌫ in Label I have a Xamarin application with a Label which is Bound like so:
<Label Text="{Binding BackSpace}"/>

and a property in my viewmodel like so:
public string BackSpace
{
   get
   {
        ResourceManager temp = new ResourceManager("MyProgram.ResourceStrings", typeof(MyClass).GetTypeInfo().Assembly);
        result = System.Text.RegularExpressions.Regex.Unescape(temp.GetString("Backspace"));
   }
}

now I have an element in my ResourceStrings called Backspace and I am trying to get the string associated with this key which I want to be the Android Backspace - ⌫
So initially I set the resource equal to the symbol ⌫ but this just gives me a label containing ?
Now I try set it equal to the HTML hex code from here:  ⌫ but this gives me ⌫
How do I get my label to display the ⌫ symbol?
PS. - Even if I try:
<Label Text="⌫"/>

I get a blank label

A: You'll need to change your label's font to a font which contains backspace as glyphicon.
You'll need two things:

*

*Appropriate font. Probably Noto Sans Symbols https://www.google.com/get/noto/#sans-zsym. ⌫ symbol

*Label renderer which allows custom fonts. See here: https://github.com/XLabs/Xamarin-Forms-Labs/wiki/ExtendedLabel
This Xamarin link will provide more infomation on working with Fonts


text:
Q: Python: In a dataframe, create a new column with a string sliced from a column with the value of another column I have a pretty simple problem that i can't get around.
I create a dataframe and i would like to generate a new column with a sliced string from one column with a slice value from another column.
Ex:
From this:
dftest = pd.DataFrame({'string' : ['EXAMPLE']*5, 'position' : [1, 2, 3, 4, 5]})

   position   string
0         1  EXAMPLE
1         2  EXAMPLE
2         3  EXAMPLE
3         4  EXAMPLE
4         5  EXAMPLE
5         1  OTHER
6         2  OTHER
7         3  OTHER

I want this:
   position   string    new
0         1  EXAMPLE  E
1         2  EXAMPLE  EX
2         3  EXAMPLE  EXA
3         4  EXAMPLE  EXAM
4         5  EXAMPLE  EXAMP
5         1  OTHER    O
6         2  OTHER    OT
7         3  OTHER    OTH

I tried:
dftest['new'] = dftest.string.str[:dftest.position]
dftest['new'] = dftest.string.str[:dftest['position']]
dftest['new'] = dftest.string[:dftest.position]

as well as different row iteration methods but each time I end up with Nan values.
Any help would be greatly appreciated

A: You can do the following
dftest['new'] = [dftest.iloc[i]['string'][0:dftest.iloc[i]['position']] for i in range(0,len(dftest))]

This will check the position.

A: One method is to enumerate the string using a list comprehension.
dftest['new'] = [s[:n] for s, n in zip(dftest.string, dftest.position)]

>>> dftest
   position   string    new
0         1  EXAMPLE      E
1         2  EXAMPLE     EX
2         3  EXAMPLE    EXA
3         4  EXAMPLE   EXAM
4         5  EXAMPLE  EXAMP
5         1    OTHER      O
6         2    OTHER     OT
7         3    OTHER    OTH

A: You could use iterrows method:
for i, row in df.iterrows():
    df.loc[i, 'new'] = row['string'][:row['position']]

Example:
In [60]: dftest
Out[60]:
   position   string
0         1  EXAMPLE
1         2  EXAMPLE
2         3  EXAMPLE
3         4  EXAMPLE
4         5  EXAMPLE
5         1    OTHER
6         2    OTHER
7         3    OTHER

for i, row in dftest.iterrows():
    dftest.loc[i, 'new'] = row['string'][:row['position']]

In [62]: dftest
Out[62]:
   position   string    new
0         1  EXAMPLE      E
1         2  EXAMPLE     EX
2         3  EXAMPLE    EXA
3         4  EXAMPLE   EXAM
4         5  EXAMPLE  EXAMP
5         1    OTHER      O
6         2    OTHER     OT
7         3    OTHER    OTH

EDIT
Or you could use apply which is more convenient:
dftest.apply(lambda x: x['string'][:x['position']], axis=1)


text:
Q: Can I use custome components created in flex in flash project? I created flash project in flash builder and a flash component project and then created a spark component in flex component project. When I tried to add the custom component in the flash it thrown error
//code
this.addChild(new TestComp);
//compilation error
1067: Implicit coercion of a value of type TestComp to an unrelated type flash.display:DisplayObject.   Main.as /pw3d/src   line 35 Flex Problem

Is it possible to use flex components in flash at all? Is there a work around?

A:
Is it possible to use flex components in flash at all?

Yes, it is possible, in theory, but I expect it to be tedious and difficult.  You'll have to do all your framework initialization manually.  That means you'll have to do things like setup the SystemManager class manually.
Honestly, I don't know everything that the Flex Compiler / Application tag does to setup the Flex Framework.  You may have to compile a simple Flex app with the 'keep' attribute and review the generated code to make sure you mimic that in your Flash Pro code.
Some reference information can be found here, here, and here.
The error you're seeing is odd; because a Flex Component must extend UIComponent and UIComponent extends DisplayObject.  I wonder if you are missing a SWC library in your class path somehow and Flash pro is unable to tell that TestComp is actually a DisplayObject.


text:
Q: Loading data to MySQL from CSV,but the attributes in SQL table need to do same calculation from the data I need to do an assignment that load date from csv, but the data attribute in the csv ins not fit with the SQL table. The SQL table schema like
BUS(id, Duration, totalcustomer)

But the csv file title like
id=1, Start time =00:00:00, end time=00:01:11, male customer=20, female customer=20

The output the Table will like id=1, drration=00:01:11, total customer =40
So, in the SQL table,Duration= end time -start time, and totalcustomer=male customer + female customer.
I try SQL expressions like below but not work
LOAD DATA LOCAL INFILE 'BUS.csv'
INTO TABLE BUS
FIELDS ENCLOSED BY '\"'TERMINATED BY ','
LINES TERMINATED BY '\n'
(@id, @Duration, @totalcustomer)
SET  'end time' - 'start time' = @Duration,
     'male customer'+ 'female customer' = @totalcustomer

So, do I need to make a new table to load the csv data and do the calculation in MySQL?

A: The variables in the load statement are for the columns in the table and/or temporary variables which can be manipulated and loaded with the set statement. So your load should look more like
(id, @starttime, @endtime, @malecustomer,@femalecustomer)
SET  duration = @endtime - @starttime,
     totalcustomer = @malecustomer + @femalecustomer

A: We can do it in Load data itself but it took time for me to figure it out, Let me know if you face any issues it works for me, make sure you replace schema_name and path in the query accordingly and also avoid spaces in column names.
Use duration table in database as time datatype.
Create table used :
create table BUS
(
id int,
 Duration time,
 totalcustomer int
 );

The Load statement :
LOAD DATA LOCAL INFILE 'C:\\Users\\path\\Downloads\\BUS.csv'
INTO TABLE schema_name.bus FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS
(id, @END_TIME,@START_TIME,@MALE_CUST,@FEMALE_CUST)
SET
     Duration = timediff(str_to_date(@START_TIME,'%H:%i:%S'),str_to_date(@END_TIME,'%H:%i:%S')),
     totalcustomer = @MALE_CUST+@FEMALE_CUST;

This is the csv data i have used
ID,START_TIME,END_TIME,MALE_CUST,FEMALE_CUST
1,00:00:00,00:01:11,20,30

The output in the table BUS after executing the Load data statement
# id    Duration    totalcustomer
   1    00:01:11      50

Here is what i understood, you have the first table column id is not using @ because it is getting mapped automatically to the first ID column name in csv, rest of the columns are not directly mapped so we use @ and col_name in
(id, @END_TIME,@START_TIME,@MALE_CUST,@FEMALE_CUST)

You can try change this above line by using @ID you might have to map id=@ID after SET
you should use table columns after SET
Duration =
totalcustomer =

and equate it to the data columns from csv source on RHS.


text:
Q: How to have return type from async I am using below code to have return type from async, but it throwing an error
async Task<double> getDuration(string fileFullPath)
{
    Windows.Storage.StorageFolder localRoot = Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFolder mp3 = await localRoot.GetFolderAsync(Path.GetDirectoryName(fileFullPath));
    Windows.Storage.StorageFile file = await mp3.GetFileAsync(Path.GetFileName(fileFullPath));
    Windows.Storage.FileProperties.MusicProperties music = await file.Properties.GetMusicPropertiesAsync();
    return music.Duration.TotalSeconds;
}

The error:

The type or namespace name 'Task' could not be found (are you missing
  a using directive or an assembly reference?)

How can I have the return value from async?

A:
The type or namespace name 'Task' could not be found (are you missing
  a using directive or an assembly reference?)

I think you haven't added the namespace
System.Threading.Tasks

How can i have the return value from async?

Sample Code
public async Task<int> ExampleMethodAsync()
{
    var httpClient = new HttpClient();
    int exampleInt = (await httpClient.GetStringAsync("http://msdn.microsoft.com")).Length;
    ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";
    // After the following return statement, any method that's awaiting
    // ExampleMethodAsync (in this case, StartButton_Click) can get the
    // integer result.
    return exampleInt;
}


text:
Q: Simple past or past perfect-story I have a question. I'm currently writing a story and I'm using the simple past as my main tense. However, I'm not sure if I should use the past simple or past perfect when I describe events that happened before the main story (for exemple, one character's childhood). It seems to me I should use the past perfect, but writing many paragraphs in the past perfect doesn't seem completely right. What do you think? Thanks.

A: First of all, you are right: You shouldn't be writing many paragraphs in past perfect.
Past perfect is a relative tense. It can only be used in conjunction with an absolute tense: simple past. If that isn't there in the same paragraph you shouldn't use past perfect.
Past perfect used correctly:

He went around a corner and nearly ran into a guard. He immediately drew his sword. He was glad his father had given it to him. It had once been his grandfather's sword. He slit the guard's throat before she could react.

Past perfect used incorrectly:

He had gone around the corner and had nearly run into a guard. He had immediately drawn his sword. He had been glad his father had had given it to him. It had once had been his grandfather's sword. He had slit the guard's throat before she had been able to react.

Please ignore that the pacing in my example is awful.
Your chapters and paragraphs don't have to be chronological at all times, as long as you give your readers the information they need to realize that your narrative has moved back to a previous point in time.
You don't switch to the future tense if a chapter is about events that happen after the previous one, do you? In the same way you don't switch tenses when a whole chapter or long paragraph is set before the one it succeeds. Instead you move your anchor back and narrate in your main tense (simple past in your case).
For questions about style you might also want to consult the Writing community of Stack Exchange.


text:
Q: ResultSet returned closed with ojdbc7 and hibernate 3.2.0 on Oracle 12.1.0.2
*

*We have a legacy java application which we have to migrate from oracle 11g to 12.1.0.2.

*The application was using ojdbc14 driver and we had to change it to ojdbc7 otherwise it could not connect to the database.

*After we changed the ojdbc driver, our Java Application which was using a Hibernate connection to make a call to an oracle function (which returns a ref cursor) stopped working. The symtoms are that a closed resultset is returned from the database.

*We also have code which is using a ppl connection instead of hibernate and it works fine with a resultset and a ref cursor.

What we've tried so far:

*

*We tried to call the database function from the database itself and it returns a full oracle cursor, so it's not a database issue.

*We tried setting property hibernate.jdbc.fetch_size to a number bigger than the query returns but this also didn't work.


text:
Q: Force the browser to end the current step Need:
Using Cucumber 1.0.1 and Watir 1.9.2, I need to execute javascript code in order for a proprietary portal to do some navigation.
Issue:
I am able to execute JS code with the following:
def execute_js(js_code)
  @browser.goto("javascript:#{js_code};void(0)")
end

execute_js("doNavigate()")

By doing so, the navigation is done as expected but Watir doesn't re-take control of the browser.
What I look for:
I look for a solution for Watir to re-take control of the browser after the 'javascript goto'.
Tested alternative:
@browser.execute_script('alert("toto");')

gives me this:
  execScript
      OLE error code:80070005 in <Unknown>
        Access Denied.

      HRESULT error code:0x80020009
        An exception occurred. (WIN32OLERuntimeError)
  ./features/lib/portal.rb:110:in `tln_main_tab'

Local gems:

*

*Ascii85 (0.9.0)

*builder (3.0.0)

*bundler (1.0.15)

*capybara (1.0.0)

*childprocess (0.1.9)

*commonwatir (1.9.2)

*cucumber (1.0.1)

*diff-lcs (1.1.2)

*ffi (1.0.9 x86-mingw32)

*firewatir (1.9.2)

*fuubar-cucumber (0.0.12)

*gherkin (2.4.5 x86-mingw32)

*hoe (2.10.0)

*json (1.5.3)

*json_pure (1.5.3)

*mime-types (1.16)

*nokogiri (1.5.0 x86-mingw32)

*pdf-reader (0.9.0)

*prawn (0.11.1)

*rack (1.3.0)

*rack-test (0.6.0)

*rake (0.9.2)

*rautomation (0.6.2)

*rspec (2.6.0)

*rspec-core (2.6.4)

*rspec-expectations (2.6.0)

*rspec-mocks (2.6.0)

*ruby-progressbar (0.0.10)

*rubygems-update (1.8.5)

*rubyzip (0.9.4)

*s4t-utils (1.0.4)

*selenium-webdriver (0.2.2)

*syntax (1.0.0)

*term-ansicolor (1.0.5)

*ttfunk (1.0.1)

*user-choices (1.1.6.1)

*viewcumber (0.1.2)

*watir (1.9.2)

*win32-api (1.4.8 x86-mingw32)

*win32-process (0.6.5)

*win32console (1.3.0 x86-mingw32)
-windows-api (0.4.0)

*windows-pr (1.2.0)

*xml-simple (1.1.0)

*xpath (0.1.4)

A: I found a workaround:
def execute_js(js_code)
  begin
    Timeout::timeout(2) do
      @browser.goto("javascript:#{js_code};void(0)")
    end
  rescue Exception => e
    goto "#{@browser.url}#"  # <<< workaround is here
    return
  end
end

execute_js("doNavigate()")

It's not ideal, but it enables javascript execution, then updates the URL hash so that Watir knows that an actual action was done, so that Watir can go further.

A: Access Denied error message is usually connected to frames on a page. Take a look at Frames page at Watir wiki.


text:
Q: How do I gracefully fall back to AutoIP when there is no DHCP service available? I am developing an embedded device based on Linux and Busybox, and trying to make it adaptable to different network configurations. I want to:
1- At boot time, if there is no DHCP reply, use an AutioIP address.
2- At run time, if a DHCP server become available, start using it.
Point 1 seems easy as I can set my eth0 to manual in my /etc/network/interfaces, and set up command to
udhcpc eth0 --now || zcip eth0 /etc/zcip.script

I am not sure of point 2. If I run both udhcpc and zcip daemons simultaneously, would they play well together?

A: You can do this with udhcpc+avahi. Avahi is zeroconf implementation for linux. It provides autoip (giving an address without dhcp) and mDNS (name resolution withoud DNS server).
I got it working in an embedded system with buildroot. There's also a modified udhcpc start script that enable fallback to autoip when dhcp isn't available.

*

*udhcpc + avahi fallback script

*buildroot

*avahi

A: If you only need to use AutoIP as a fallback to DHCP at boot time, then perhaps instruct zcip to get an address and exit instead of running as a daemon.
At boot time you'd do:
udhcpc eth0 --now || zcip -f -q eth0 /etc/zcip.script

When this command completes, either udhcpc will be running, or you will have a link local address
Then when a DHCP server becomes available, start the udhcpc daemon.


text:
Q: Google Map JavaScript Error(s) I am trying to install a Google Map via JavaScript on to my website which will have multiple markers. I am getting several errors and I cannot figure them out or resolve them. Please can someone help me?
The map:

I am loading the following JavaScript in the footer (below the map-canvas):

In my map.js I have:
// necessary variables
var map;
var infoWindow;

// markersdata variable stores the information necessary to each marker
var markersData = [{
        lat: 40.6386333,
        lng: -8.745,
        name: "Camping Praia da Barra",
        address1: "Rua Diogo Cão, 125",
        address2: "Praia da Barra",
        postalCode: "3830-772 Gafanha da Nazaré"
    },
    {
        lat: 40.59955,
        lng: -8.7498167,
        name: "Camping Costa Nova",
        address1: "Quinta dos Patos, n.º 2",
        address2: "Praia da Costa Nova",
        postalCode: "3830-453 Gafanha da Encarnação"
    },
    {
        lat: 40.6247167,
        lng: -8.7129167,
        name: "Camping Gafanha da Nazaré",
        address1: "Rua dos Balneários do Complexo Desportivo",
        address2: "Gafanha da Nazaré",
        postalCode: "3830-225 Gafanha da Nazaré"
    }
];

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(40.601203, -8.668173),
        zoom: 9,
        mapTypeId: 'roadmap',
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    // a new info window is created
    infoWindow = new google.maps.InfoWindow();

    // event that closes the info window with a click on the map
    google.maps.event.addListener(map, 'click', function() {
        infoWindow.close();
    });

    // finally displaymarkers() function is called to begin the markers creation
    displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);

// this function will iterate over markersdata array
// creating markers with createmarker function
function displayMarkers() {

    // this variable sets the map bounds according to markers position
    var bounds = new google.maps.LatLngBounds();

    // for loop traverses markersdata array calling createmarker function for each marker
    for (var i = 0; i < markersData.length; i++) {

        var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng);
        var name = markersData[i].name;
        var address1 = markersData[i].address1;
        var address2 = markersData[i].address2;
        var postalCode = markersData[i].postalCode;

        createMarker(latlng, name, address1, address2, postalCode);

        // marker position is added to bounds variable
        bounds.extend(latlng);
    }

    // finally the bounds variable is used to set the map bounds
    // with fitbounds() function
    map.fitBounds(bounds);
}

// this function creates each marker and it sets their info window content
function createMarker(latlng, name, address1, address2, postalCode) {
    var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        title: name
    });

    // this event expects a click on a marker
    // when this event is fired the info window content is created
    // and the info window is opened.
    google.maps.event.addListener(marker, 'click', function() {

        // creating the content to be inserted in the infowindow
        var iwContent = '
' +
            '
' + name + '
' +
            '
' + address1 + '
' +
            address2 + '
' +
            postalCode + '

';

        // including content to the info window.
        infoWindow.setContent(iwContent);

        // opening the info window in the current map and at the current marker location.
        infoWindow.open(map, marker);
    });
}

The errors that I am getting are:
1. Uncaught ReferenceError: google is not defined at map.js:52
2. Uncaught Qb
What does this mean?

A: You should be passing the name of your map initialisation function (initialize) in the callback query parameter of the google maps URL:

You also need to load your javascript file before loading the google maps API to ensure that your initialisation function is defined when the callback is called:

A: You're loading the Google API async.

Which means your map.js is being executed before it's loaded, in addition: the callback is 'initMap' which isn't doing anything in your own map.js at this moment.
google.maps.event.addDomListener(window, 'load', initialize);

Remove this line, and change the callback function in your script to initialize.

A: This line google.maps.event.addDomListener(window, 'load', initialize);
should be in your initialize function cos at the point where it is as your error says, it has not been loaded

A: Ok, let's looking for what is happening here. You have imported the g maps dependencies with this:

Look at that "async" word. That says that the js file will be loaded asynchronously. Now, look at the src attr:
https://maps.googleapis.com/maps/api/js?key=API_REMOVED&callback=initMap
The attribute callback in the query string defines a JS function that you need have in your code, that will be executed when the async load is finished. You don't have this function in your code,so you should create it with the inialization of your map.
Maybe, putting all your JS code into this will works:
function initMap(){
   // your code here
}


text:
Q: Running Game Services BasicSamples - Error "Install Google Play Games This app requires the latest version of the Google Play Games" I'm trying to run one of the modules in the BasicSamples for Google Play Services. I have configured the app in the Game Services in the Developer Console including the OAuth2, package name, achievements, leaderboard etc. I have also updated Intellij SDK Manager to install Google Play Services and Google Repository. I've also updated the Take A Number app to include the application id and all the other ids.
However, when I try to run Take A Number I get the dialog:
"Install Google Play Games
This app requires the latest version of the Google Play Games app."

The documentation for setting up projects to use game services says to add
compile 'com.google.android.gms:play-services:10.0.1'

to build.gradle. I see these sample projects don't have that. So I tried adding
it to build.gradle in TypeANumber but get the error:
 Error:Execution failed for task ':TypeANumber:dexDebug'.
> com.android.ide.common.process.ProcessException:     org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_92\bin\java.exe'' finished with non-zero exit value 2

I see BaseGameUtils build.gradle contains
compile "com.google.android.gms:play-services-games:${gms_library_version}"
compile "com.google.android.gms:play-services-plus:${gms_library_version}"

(but not  com.google.android.gms:play-services).
I updated gms_library_version defined in top level BasicSamples' build.gradle to 10.0.1 and that didn't work either.
This is taking quite an effort to set this up. Any help is appreciated.

A: The message `Install Google Play Games
This app requires the latest version of the Google Play Games app.' indicates that the Play Games App is out of date compared to the client library version (10.0.1) you are using.
As the comments to your question indicate, if you are using an emulator, then the Play Store and other Google Apps will not be present, so you can't run the game on the Emulator, but only on devices that have the Google Play Services installed.


text:
Q: "Keep Data on Update" behaviour does not work in the Smartface Whether I set the "Keep Data on Update" property true or false, it never affect.
If what I understand from this property is that it provides data on tables will be protected if it was set true, it does not work.
No matter what I did, all the data are deleted when I run the project.
How can I always save all the data on the database?

A: keep data on Update is used for protecting the databases when you are updating your application whether you change the data structure or not. ( ex. 1.0.0 -> 1.0.1 )
For more information please check the link below;
http://www.smartface.io/developer/guides/data-network/table/


text:
Q: Why is sscanf() is not scanning here? I have got a struct Log:
struct Log
{
    char message[1024];
    struct tm* time;
    char proc_name[256];
    char computer_name[256];
    int proc_pid;
};

I initialize it:
char buf[1024];
struct Log* log = malloc(sizeof(struct Log));
log->time = malloc(sizeof(struct tm));

And I trying to read info from string to struct Log, using this function:
void SyslogParse(const char* src, struct Log* log)
{
    strptime(src, "%b  %d %T", log->time);   //strptime WORK CORRECT!
    int a = sscanf(src, "%s %d %d:%d:%d %s %s[%d]: %[^\n]s", NULL, NULL, NULL, NULL, NULL, &log->computer_name, &log->proc_name, &log->proc_pid, &log->message);
};

Or this:
void SyslogParse2(const char* src, struct Log* log)
{
    strptime(src, "%b  %d %T", log->time);  //strptime WORK CORRECT!
    int a = sscanf(src, "%s %d %d:%d:%d %s %s: %[^\n]s", NULL, NULL, NULL, NULL, NULL, log->computer_name, log->proc_name, log->message);
};

Strings read from syslog file. For example:
Jan 21 17:58:04 bogdasar-System-Product-Name anacron[786]: Job `cron.daily' terminated
Jan 21 17:58:24 bogdasar-System-Product-Name 05efi: debug: /dev/sda2 is a FAT32 partition
Functions are called as follows:
SyslogParse2(buf, log);

A problem:
sscanf in SyslogParse functions is not working!!!
Full code of main:
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "DateTime.h"
#include "Log.h"
#include "Keys.h"
#define SIZE 1024

int main(int argc, char* argv[])
{
    FILE* fl;
    char buf[1024];
    //time_t d = time(NULL);

    struct Keys keys;
    struct tm* time = malloc(sizeof(struct tm));
    struct Log* log = malloc(sizeof(struct Log));

    log->time = malloc(sizeof(struct tm));
    keys.time = malloc(sizeof(struct tm));

    int opt;
    char args[] = "hd:t:";
    if(argc < 2)
    {
        fprintf(stderr, "Введите абсолютный путь к файлу\n");
        return -1;
    };

    if((fl = fopen(argv[1], "r")) == NULL)
    {
        fprintf(stderr, "Не удаётся открыть файл. Возможно его не существует. Проверьте правильность пути.\n");
        return -2;
    };

    while ((opt = getopt(argc, argv, args)) != -1)
    {
        switch (opt)
        {
        case 'h':
            system("cat help.txt");
            return 0;
        case 'd':
            keys.f_date = 1;
            strptime(optarg, "%b/%d", keys.time);
            break;
        case 't':
            keys.f_time = 1;
            strptime(optarg, "%T", keys.time);
            break;
        default:
            break;
        }
    };

    while (fgets(buf, SIZE, fl))
    {
        SyslogParse2(buf, log);

    };
    return 0;
}

Log.h
#ifndef LOG
#define LOG
#define SIZE 1024
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
struct Log
{
    char message[1024];
    struct tm* time;
    char proc_name[256];
    char computer_name[256];
    int proc_pid;
};

void SyslogParse(const char* src, struct Log* log);

void SyslogParse2(const char* src, struct Log* log);
#endif

Log.c
#include "Log.h"
#define _XOPEN_SOURCE
void SyslogParse(const char* src, struct Log* log)
{
    strptime(src, "%b  %d %T", log->time);
    int a = sscanf(src, "%s %d %d:%d:%d %s %s[%d]: %[^\n]s", NULL, NULL, NULL, NULL, NULL, &log->computer_name, &log->proc_name, &log->proc_pid, &log->message);
};

void SyslogParse2(const char* src, struct Log* log)
{
    strptime(src, "%b  %d %T", log->time);
    int a = sscanf(src, "%s %d %d:%d:%d %s %s: %[^\n]s", NULL, NULL, NULL, NULL, NULL, log->computer_name, log->proc_name, log->message);
};

A problem:
sscanf in SyslogParse functions is not working!!!


text:
Q: Gaussian random numbers The Tikz manual has all sorts of different options regarding math, but the following is the first version which actually worked.  Is there a better way to do this?
\documentclass{article}
\usepackage{tikz}

\usetikzlibrary{calc}

\newcount\gaussF
\edef\gaussR{0}
\edef\gaussA{0}

\def\gauss{
 \advance\gaussF by 1\relax
 \ifodd\gaussF
  \pgfmathrnd
  \edef\temp{\pgfmathresult}
  \pgfmathln{\temp}
  \edef\temp{\pgfmathresult}
  \pgfmathmultiply{-2}{\temp}
  \edef\temp{\pgfmathresult}
  \pgfmathsqrt{\temp}
  \edef\gaussR{\pgfmathresult}%radius = $sqrt(-2*ln(rnd))$
  \pgfmathrnd
  \edef\temp{\pgfmathresult}
  \pgfmathmultiply{360}{\temp}
  \edef\gaussA{\pgfmathresult}%angle = $360*rnd$
  \pgfmathcos{\gaussA}
  \edef\temp{\pgfmathresult}
  \pgfmathmultiply{\gaussR}{\temp}
 \else
  \pgfmathsin{\gaussA}
  \edef\temp{\pgfmathresult}
  \pgfmathmultiply{\gaussR}{\temp}
 \fi
 \pgfmathresult
}

\begin{document}

\noindent
\gauss\\
\gauss\\
\gauss\\
\gauss

\end{document}

A: I'm not sure that the algorithm in the question is correct, nevertheless it is certainly implemented in a sub-optimal manner. Although Jake's (now deleted) answer is readable it also has a huge overhead in calling the parser inside a function.
It is quite simple to use the lower level pgfmath macros (although I probably would be expected to say that).
Either way, in both cases, rnd produces pseudo-random numbers on the interval [0,1] so the possibility of ln(0) must be dealt with.
\documentclass[border=0.125cm]{standalone}
\usepackage{tikz}

\newcount\gaussF
\edef\gaussR{0}
\edef\gaussA{0}

\makeatletter
\pgfmathdeclarefunction{gaussR}{0}{%
 \global\advance\gaussF by 1\relax
 \ifodd\gaussF
  \pgfmathrnd@%
  \ifdim\pgfmathresult pt=0.0pt\relax%
    \def\pgfmathresult{0.00001}%
  \fi
  \pgfmathln@{\pgfmathresult}%
  \pgfmathmultiply@{-2}{\pgfmathresult}%
  \pgfmathsqrt@{\pgfmathresult}%
  \global\let\gaussR=\pgfmathresult%radius
  \pgfmathrnd@%
  \pgfmathmultiply@{360}{\pgfmathresult}%
  \global\let\gaussA=\pgfmathresult%angle
  \pgfmathcos@{\pgfmathresult}%
  \pgfmathmultiply@{\pgfmathresult}{\gaussR}%
 \else
  \pgfmathsin@{\gaussA}%
  \pgfmathmultiply@{\gaussR}{\pgfmathresult}%
 \fi
}

\pgfmathdeclarefunction{invgauss}{2}{%
  \pgfmathln{#1}% <- might need parsing
  \pgfmathmultiply@{\pgfmathresult}{-2}%
  \pgfmathsqrt@{\pgfmathresult}%
  \let\@radius=\pgfmathresult%
  \pgfmathmultiply{6.28318531}{#2}% <- might need parsing
  \pgfmathdeg@{\pgfmathresult}%
  \pgfmathcos@{\pgfmathresult}%
  \pgfmathmultiply@{\pgfmathresult}{\@radius}%
}

\pgfmathdeclarefunction{randnormal}{0}{%
  \pgfmathrnd@
  \ifdim\pgfmathresult pt=0.0pt\relax%
    \def\pgfmathresult{0.00001}%
  \fi%
  \let\@tmp=\pgfmathresult%
  \pgfmathrnd@%
  \ifdim\pgfmathresult pt=0.0pt\relax%
    \def\pgfmathresult{0.00001}%
  \fi
  \pgfmathinvgauss@{\pgfmathresult}{\@tmp}%
}

\begin{document}

\begin{tikzpicture}[x=10pt,y=10pt]
\foreach \i in {0,...,2000}
  \fill [opacity=1/10] (randnormal, randnormal) circle [radius=1/10];
\tikzset{shift=(0:10)}
\foreach \i  in {0,...,2000}
  \fill [blue, opacity=1/10] (gaussR, gaussR) circle [radius=1/10];
\end{tikzpicture}

\end{document}

A:
I defined the function randomNormal which takes one argument, the variance, and returns a Gaussian random number with average 0.  It is written using the math library, so it needs only one line of code.  The mathematical formula is the one appearing in the question and @Mark Wibrow 's answer.
The code
\documentclass[11pt, margin=.5cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{math, calc}

\begin{document}
\tikzmath{%
  function randomNormal(\s) {  % variance
    return {sin(360*rnd)*sqrt(-2*\s*ln(rnd))};
  };
}
\begin{tikzpicture}
  \foreach \s/\rgb [count=\i from 0] in {0.3/violet, 0.65/blue, 1/green!70!black}{
    \draw (-2 +5*\i,  0) -- ++(4, 0);
    \draw (5*\i,  -1.5) -- ++(0, 3);

    \foreach \k in {1, 2, ..., 1000}{%
      \filldraw[\rgb, opacity=.1]
      ($(5*\i, 0) +({randomNormal(\s)}, {randomNormal(\s)})$) circle (2pt);
    }
    \path (5*\i,  -2.5) node {variance=\s};
  }
\end{tikzpicture}

\end{document}


text:
Q: Java. How to return generalized object? I have a class
public class Product {
...
}

and
public class Phone extends Product {
...
}

I want to return a generic object. Now i try that :
public <T extends Product> T getProduct()
{
   return new Phone();
}

but the compiler give me error :
Incompatiple types :
Required : T
Found : Phone

What's wrong? And how i can fix this?

A: Generic return?
If you are looking for a return type which can work for all subtype of Product, then this should work.
public Product getProduct() {
   return new Phone();
}

A: Replace <T extends Product> by Product


text:
Q: Swap entanglement from harmonic oscillator chain I am currently analyzing a system of coupled harmonic oscillators in a thermal state and have already asked a question related to this.
I have calculated the entanglement entropy of a chain of two harmonic oscillators by taking the partial trace of the thermal state with respect to one harmonic oscillator and taking hte entropy of that and find that the entanglement entropy is finite. As expected as the inverse temperature vanishes the entanglement entropy vanishes as well.
Is it possible to swap this entanglement between the coupled harmonic oscillators into two independent harmonic oscillators? How can one mathematically describe this and how would one experimentally realize this?


text:
Q: WebStorm is auto downloading JavaScript typings. How to stop this? I've installed react-router v6 but WebStorm still use react-router v5 types.
In WebStorm folders: /Webstorm2021.2/javascript/typings/... has loadsh, react-dom, react-router-dom, styled-components libraries. When I remove those typings folders WebStorm auto creates and downloads those four libraries.
Why does this happens and how to stop this? Or let WebStorm choose the v6 types by default?

A: The IDE downloads typings for some popular libraries to its configuration folder and uses it to enhance code completion. You can remove the auto-downloaded typings from your <system directory>/javascript/typings (https://www.jetbrains.com/help/webstorm/directories-used-by-the-ide-to-store-settings-caches-plugins-and-logs.html#system-directory) and then either disable typescript.external.type.definitions Registry key or remove react-router-dom (and other stuff you don't like to be downloaded automatically) from typescript.external.type.definitions.packages key
The Registry can be located via: Help > Find action > type Registry...


text:
Q: Scrolling blend effect - performance issues in all browsers except Chrome With the help received in a previous answer, I'm utilizing a bit of JS along with CSS variables to achieve a "blend" effect when scrolling through a page as seen in this working example.
The solution is great... but only in Chrome. I've begun to implement this in my project though and testing in other browsers revealed severe performance issues, specifically the content block jumps around while scrolling. I revisited my test example in Firefox & Safari and found the same issues.
So my question is simply, what can I do to improve the performance of this effect? I've done quite a bit of searching to find an alternative way to pull off this effect, but no luck thus far. Perhaps there are modifications I can make to my JS to account for these issues though.
I've included my code below for reference. Any help would be greatly appreciated.

window.onscroll = function() {
  var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
  document.documentElement.style.setProperty('--scroll-var', scroll + "px");
}
:root {
  --scroll-var: 0px
}

body {
  margin: 0;
  padding: 0;
}

h2 {
  font-size: 48px;
}

p {
  font-size: 18px;
}

section {
  min-height: 100vh;
  width: 100%;
  text-align: center;
  overflow: hidden;
  background-attachment: fixed !important;
  background-size: cover !important;
  background-repeat: no-repeat !important;
  position: relative; /*Mandatory for the overflow effect*/
  height: 100vh;
}

section.first {
  background: linear-gradient(rgba(74, 180, 220, .85), rgba(74, 180, 220, .85)), url(https://picsum.photos/1920/500/?image=1057);
}

section.first .content {
  /* the first section so top start from 0*/
  top: calc((0 * 100vh) + var(--scroll-var));
}

section.second {
  background: linear-gradient(rgba(103, 198, 180, .85), rgba(103, 198, 180, .85)), url(https://picsum.photos/1920/500/?image=1067);
}

section.second .content {
  /* the second section so we need to remove the height of top section
     to have the same position so -100vh and we do the same for the other sections
  */
  top: calc((-1 * 100vh) + var(--scroll-var));
}

section.third {
  background: linear-gradient(rgba(5, 123, 188, .85), rgba(5, 123, 188, .85)), url(https://picsum.photos/1920/500/?image=1033);
}

section.third .content {
  top: calc((-2 * 100vh) + var(--scroll-var));
}

section.fourth {
  background: linear-gradient(rgba(187, 216, 100, .85), rgba(187, 216, 100, .85)), url(https://picsum.photos/1920/500?image=1063);
}

section.fourth .content {
  top: calc((-3 * 100vh) + var(--scroll-var));
}

.content {
  position: absolute;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.copy {
  color: #fff;
  font-family: 'Noto Serif', serif;
  font-weight: 300;
  max-width: 300px;
}

.button {
  border: 2px solid #fff;
  border-radius: 3px;
  padding: 15px 25px;
  display: inline-block;
  width: auto;
  font-family: 'Assistant', sans-serif;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 1px;
  transition: .2s ease all;
}

.button:hover {
  background: #fff;
  color: #333;
  cursor: pointer;
}

Header 1

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Header 2

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Header 3

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Call to action

        Button

A: I think by simplifing the logic of calcuting the top value you can fix your issues. You can use a fixed top value for each section then adjust margin-top for all of them.
You can also get rid of the CSS variable:

var all = document.querySelectorAll('.content');
var l = all.length;

window.onscroll = function() {
  var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
  for(var i=0;i<l;i++)
   all[i].style.marginTop=scroll + "px";
}
body {
  margin: 0;
  padding: 0;
}

h2 {
  font-size: 48px;
}

p {
  font-size: 18px;
}

section {
  min-height: 100vh;
  width: 100%;
  text-align: center;
  overflow: hidden;
  background-attachment: fixed !important;
  background-size: cover !important;
  background-repeat: no-repeat !important;
  position: relative; /*Mandatory for the overflow effect*/
  height: 100vh;
}

section.first {
  background: linear-gradient(rgba(74, 180, 220, .85), rgba(74, 180, 220, .85)), url(https://picsum.photos/1920/500/?image=1057);
}

section.first .content {
  /* the first section so top start from 0*/
  top:0;
}

section.second {
  background: linear-gradient(rgba(103, 198, 180, .85), rgba(103, 198, 180, .85)), url(https://picsum.photos/1920/500/?image=1067);
}

section.second .content {
  /* the second section so we need to remove the height of top section
     to have the same position so -100vh and we do the same for the other sections
  */
  top: -100vh;
}

section.third {
  background: linear-gradient(rgba(5, 123, 188, .85), rgba(5, 123, 188, .85)), url(https://picsum.photos/1920/500/?image=1033);
}

section.third .content {
  top: -200vh;
}

section.fourth {
  background: linear-gradient(rgba(187, 216, 100, .85), rgba(187, 216, 100, .85)), url(https://picsum.photos/1920/500?image=1063);
}

section.fourth .content {
  top:-300vh;
}

.content {
  position: absolute;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top:0px;
}

.copy {
  color: #fff;
  font-family: 'Noto Serif', serif;
  font-weight: 300;
  max-width: 300px;
}

.button {
  border: 2px solid #fff;
  border-radius: 3px;
  padding: 15px 25px;
  display: inline-block;
  width: auto;
  font-family: 'Assistant', sans-serif;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 1px;
  transition: .2s ease all;
}

.button:hover {
  background: #fff;
  color: #333;
  cursor: pointer;
}

Header 1

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Header 2

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Header 3

Nullam id dolor id nibh ultricies vehicula ut id elit. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.

Call to action

        Button


text:
Q: DismissModalView Not Working I've been pulling my hair out a bit over this. I'm creating a very simple app, it simply downloads an rss feed and displays it in a UITableview, which is inside a UINavigationController. Whilst it's downloading the feed I'm presenting a Modal View.
In my modal view I'm displaying a UIImageView and a UIActivityIndicatorView that is set to spin. I'm using ASIHTTRequest to asynchronously grab the feed and then using the either the completion block to get the response string and stop the spinner or the failure block to get the NSError and display a alert View. This all works perfectly.
I've then created a protocol to dismiss the modal view from the tableview which is called inside the completion block. But the modal view is never dismissed! I've tried pushing it into the navigation controller but exactly the same problem occurs. I even have tried setting the modal view delegate to nil but still no luck.
I've checked it without blocks using the ASIHTTPRequest delegate methods and it's the same, and if I don't present the modal view the table view is displayed normally.
Any Ideas? I've skipped out all the tableview delegate and datasource methods as well as the dealloc and any unused functions.
@interface MainTableViewController ()
-(void)loadModalView;
@end

@implementation MainTableViewController
@synthesize tableView;
@synthesize modalView;

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{

   [super loadView];
tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];

   [self loadModalView];

}

-(void)loadModalView
{
    modalView = [[ModalViewController alloc]init];
    modalView.delegate = self;
    [self presentModalViewController:modalView animated:NO];

}

//Modal View Delegate
-(void)downloadComplete
{
modalView.delegate = nil;
[self dismissModalViewControllerAnimated:NO];

}

@end

@interface ModalViewController ()

- (void)loadView
{
[super loadView];

backgroundImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];

[self.view addSubview:backgroundImage];

spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake(160, 240, spinner.bounds.size.width, spinner.bounds.size.height);
spinner.hidesWhenStopped = YES;
[self.view addSubview:spinner];
[spinner startAnimating];

NSString* urlString = FEED_URL;
NSURL* url = [NSURL URLWithString:urlString];

ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    [spinner stopAnimating];
    [delegate downloadComplete];
    // Use when fetching binary data

}];
[request setFailedBlock:^{
    NSError *error = [request error];
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Error" message:error.description delegate:self cancelButtonTitle:@"Continute" otherButtonTitles: nil];
    [alert show];
    [alert release];
}];
[request startAsynchronous];

}

Matt

A: In my understanding.. you solution is quite complicated..
wouldn't it be better if the class MainTableViewController is the
one who downloads the Feeds.. for the ModalView it will just act as an ActivityIndicator and dismiss after downloading..
so inside your MainTableViewController loadview:
- (void)loadView
{
  NSString* urlString = FEED_URL;
  NSURL* url = [NSURL URLWithString:urlString];

  ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
  [request startAsynchronous];
  //after starting the request show immediately the modalview
  modalView = [[ModalViewController alloc]init];
  [self presentModalViewController:modalView animated:NO];

  [request setCompletionBlock:^{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    //then when it is complete dissmiss the modal
    [modalView dismissModalViewControllerAnimated:NO];

    // Use when fetching binary data
  }];
  [request setFailedBlock:^{
    NSError *error = [request error];
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Error" message:error.description delegate:self cancelButtonTitle:@"Continute" otherButtonTitles: nil];
    [alert show];
    [alert release];
  }];

}

i didnt use blocks in my projects, but i think it will work the same..
also I use a plain UIActivityIndicatorView (large) as subviews not modalViews.. sadly i cant test the code here now.. but i can check it later though

A: The only way I solved this error was to synchronously download the data and push and pop the download view onto the navigation stack. Not ideal but it works.