text:
Q: How do I disable autovivification in Perl? Suppose you have a HUGE application "develoopped" ;) by a big team.
Here is a simplified model of the potential disaster that may occur when somebody checks too deep in a data structure.
If not possible to disable autovification completely or in scope, how to work around this?
Thank you very much :) !!!!
use strict; use warnings;use Data::Dumper;

my $some_ref = {akey=>{deeper=>1}};
print Dumper($some_ref );
if($some_ref->{deep}{doot} == 1){
    print 'too deep '.$/;
}

if($some_ref->{deep}){
    print 'Already in a deep doot'.$/;
}

print Dumper($some_ref );

This outputs the following:
$VAR1 = {
          'akey' => {
                      'deeper' => 1
                    }
        };
Use of uninitialized value in numeric eq (==) at autovivify_test.pl line 5.
Already in a deep doot
$VAR1 = {
          'deep' => {},
          'akey' => {
                      'deeper' => 1
                    }
        };

Yes I know there is a warning, but... it may be too late.
It will help to say that my hashref references a tied HASH.
May be if I implement a good FETCH method which checks for checks deeper in the structure, I will solve easily my problem?

I looked at Tie::StrictHash,Tie::Hash and perltie.
Here is simplified version of my solution:
#!/usr/bin/env perl;
#test_tie.pl

package StrictHash;
use strict; use warnings;
use Tie::Hash;
our @ISA = qw(Tie::StdHash);
use Carp;

sub TIEHASH {
    my $class = shift;
    my $hash = bless {@_}, $class;
    return $hash;
}
##========================================================================
## FETCH fails if applied to a member that doesn't exist.
##========================================================================
sub FETCH {
    my ($hash, $key) = @_;
    Carp::confess "key '$key' does not exist" unless exists $hash->{$key};
    return $hash->{$key};
}
##========================================================================
package main;
use strict;use warnings;use Data::Dumper;
#Imagine StrictHash is in ./StrictHash.pm
#use StrictHash;
my %hash;
tie %hash, 'StrictHash', akey => {deeper=>1} ;

my $some_ref =\%hash;
print Dumper($some_ref );
if($some_ref->{deep}{doot} == 1){
    print 'too deep '.$/;
}

What I achieved is to touch only one place in the app.
Now all Places like if($some_ref->{deep}{doot}) will cause die with stack-trace.
So I will easily find them and correct them.
And new writings of this kind will NOT be possible.
Perl is good for big apps too, you just need to know more ;).
Thank you all!
I hope this helps others too.

A: You can lock the hash using one of the functions from Hash::Util (a core module).
use Hash::Util qw( lock_keys unlock_keys );

my $some_ref = { akey => { deeper => 1 } };
lock_keys %$some_ref;

print "too deep" if $some_ref->{deep}{shit} == 1;

Now the last statement will throw an exception:
Attempt to access disallowed key 'deep' in a restricted hash

The downside is, of course, that you'll have to be very careful when checking for keys in the hash to avoid exceptions, i.e. use a lof of "if exists ..." to check for keys before you access them.
If you need to add keys to the hash again later you can unlock it:
unlock_keys %$some_ref;
$some_ref->{foo} = 'bar'; # no exception

A: I upvoted @zoul, but you should take it one step further.
Write Tests
You should have your code covered with tests, and you should run some of those tests with
use warnings FATAL => 'uninitialized';

declared in the test-case itself. Its the only way to address the concern you have with developers not checking things in advance properly. Make sure their code is tested.
And take it another step further, and make it easy to run your tests under Devel::Cover to get a coverage report.
cover -delete
PERL5OPT='-MDevel::Cover' prove -l
cover -report Html_basic

And then check the lines of code and statements are being executed by the tests, otherwise making those warnings fatal will just make code die at an unexpected time later.

A: Relatively new is the autovivification module, which lets you do this:
no autovivification;

Pretty straightforward.

A: Another option is to use Data::Diver to access your data structures.
if( 1 == Dive($some_ref, qw/ deep structures are not autovivified now / )) {
    Do_Stuff();
}

A: You might want to use an object instead of the hash (see Moose) or use a strict tied hash. Or you can turn warnings into errors, if you really want to:
use warnings NONFATAL => 'all', FATAL => 'uninitialized';


text:
Q: Force all users to disconnect from 2010 Access backend database We have multi user frontend/backend MS Access 2010 application.  We added a process that will close remote frontends when we want to do work on backend such as compact and repair.  This is timer based check on table field that if has certain value will close the application.
I do two checks to see if users are connected to database:

*

*i have login/logout process and can see who is still logged in (its form based so is fallible eg they close form but frontend is still open).

*i used .ldb file viewer to see if anything is still connected
Two questions:

*

*is there any possibility that a connection to backed could exist if it wasn't viewable with ldb viewer?

*is there any bullet proof 100% certain way to forcefully disconnect all connections from backend?

A: Users put "locks" into an LDB. An LDB is a kind of database of locks for MS Access.
Users also put "locks" onto LDB's and MDB's. These locks are part of the native database primitives provided by Windows and Windows networking.
If there are no locks IN the ldb, the user is not writing into the MDB.
If there are no locks ON the mdb, the user is not using that Windows/Networking service.
To get exclusive locking on an MDB, you need both. MSAccess won't let you exclusive lock while the LDB has entries showing someone else is using the database, and Windows won't give you an exclusive lock while it has locks showing someone else is using the database.
To 100% bulletproof empty the LDB, you delete the LDB. That is why Access always attempts to delete the LDB on close. If Access crashes, or the network is disconnected, or the PC or Server is turned off, the LDB will have data ("locks") that have not been deleted. You get rid of them by deleting the LDB.
Access won't be able to delete the LDB if a user still has Windows/Network locks on the LDB. Since Access is ignoring existing "lock" entries to clear broken "lock" entries, this is how Access/Windows prevents Access deleting the LDB while another user is still using it.
If EITHER the Windows locks or the Access/LDB "locks" exist, you can't get exclusive ownership. If ONLY the Access/LDB "locks" exist, you can delete the LDB, and then get exclusive ownership.
If ANY Windows/Network locks exist, nothing you do with Access can allow you to disconnect another person from the network. You need to go to the Server/PC that hosts the file, and force the disconnection. Access is not a network administration program that does this for you.
Last I looked, Windows Server was set by default to time-out broken file connections 15 minutes after the network session was lost. So if you turn off a PC, wait 15 minutes, then the Windows/Network locks will go (default timing). Alternatively: Admin tools, Computer Management,System Tools,Shared Folders, Sessions. Select the file you wish to unlock, and delete the session.

A: A fix exists, and I have it in place for an MS-Access Application I maintain. However, it's not convenient, and it's not simple to implement.
First, some background on locking files and the locked file.
The locking file is a useful tool but it's an indicator, not the actual lock: you can edit it but that has no effect.
Live MS-Access sessions can keep a file lock on the .accdb or .mdb back-end database file if they edit data, change an object (eg: index a table) or perform a maintenance task. The last two items in that list are rare - it takes some effort to affect another database file outside the one you've opened in your session, but it is sometimes observed in the wild -  but closing those sessions should release the lock and almost always will.
Crashed MS-Access sessions can keep a file lock on the .accdb or .mdb back-end database file. Forced restarts of the offending machines should release the lock, and mostly will.
You can trace those using the lock file (.ldb or .laccdb)
Third-party reporting applications using ODBC or ADO to your Access database should have their connections set read-only, so that they can't lock the file. If you're lucky, the system owners use a dsn file you control, and you can see that setting.
Some reporting apps, like QLikView, are opaque interfaces that demand the full filename and nobody knows what happens next: maybe it locks, maybe it doesn't. You have no way of knowing.
Some reporting apps - and Excel Pivot Tables - may link to your db, and the owners simply don't tell you. If their connections are badly configured, they can lock your table while retrieving: and terminating the client session can leave the lock in place. Bored Excel users watching a slow pivot 'refresh' do this all the time.
Worse, some third-party systems may well need to write data: this should be avoided - go through the Access client application! - but you don't always get to make that decision.
If you're lucky, the connection object is configured correctly, so the machine ID is in the connection string, ensuring it'll turn up in the locking file and allow you to locate the machine with the lock...
Maybe they do that: often they don't.
...Note that row-locking queries, page-locking queries, and table-locking queries are functionally identical for the issue that matters to you: if you need to do something (like compact and repair) at the 'file' level, the file is locked against you. Until that lock is released, you're locked out.
You may or may not be able to identify the machine. You may or may not be able to force them off the network. They may or not release the lock successfully in normal operation, and they almost certainly won't if they crash out.
So: it's not a pretty picture.
Your Best solution, in a corporate environment, is to have a direct line to a network administrator with the 'finger' tool to identify who is locking the database file, the ability to contact the user, and the ability to disconnect the offending session.
The modes of failure are:

*

*If your organisational structures do not allow you to establish that
line of communication, you're screwed.

*If your organisation's network administrators do not have the ability
or the authority to do that in a useful timeframe, you're screwed.

*If your organisation's network  administrator chooses not to do it,
you're screwed.

However, I do have a fix in place for my MS-Access Application:
The workaround I use is extremely aggressive - not quite the 'nuclear option' of putting a shovel through the building's power supply, or giving in to the sysadmin's demands for human sacrifice, but deeply unpleasant and a ridiculous amount of work to implement:

*

*Configure the clients - your MS-Access front-end applications - to
switch between named back-end databases easily.

*Likewise, the dsn files you have written and allowed other apps to
use should be accessible to a pre-existing script to edit the
'DBQ='or 'Data Source=' clause to a new  filename.

*Grab a copy of the database file, take it down to a local temp
folder for the maintenance work you needed to do, and post it back
up to your application's 'Data' folder under a new name.

*Now run the 'Change back-end' script or VBA function...

*...And to hell with anyone else who's using the old, locked,
back-end file.

Hint: implementing your front-end application so that it's regularly polling the back-end database (or some other resource, your worst case scenario is a total lockout) for a 'Maintenance shutdown' or 'Change database' instruction is a smart thing to put in your 'Main Menu' form's timer event.
Also, there's code out there to automate switching the source db for linked tables.

A:
is there any possibility that a connection to backed could exist if it
  wasn't viewable with ldb viewer?

Yes, I have had on numerous occasions had issues where the the backend was locked but I could not see anything with an ldb viewer.  In these cases, we have even resulted in doing hard-shutdown on the machines that users access the DB from.  Awful solution but in times of need you are sometimes desperate.

is there any bullet proof 100% certain way to forcefully disconnect
  all connections from backend?

No, I have not been able to find a 100% way to force everyone out of the backend DB.  The closest thing that I found to perfect was using Chris Symonds Timeout-Force Out code located on Utter Access

This database accomplishes several tasks:

*

*Allows developer to go to any PC using db and force all users off a split db so that the developer can open db exclusively to
  modify/maintain db.

*Kicks users off db if they haven't used db in a specified number of minutes set by developer.

*Allows developer to specify a time each day to force all users off split db and close the db for backup, compile or whatever.

*All functions are optional and may be bypassed with no extra coding, use only what you need for each db.

I implemented his code and it works about 99% of the time, but there are still those occasions where MS Access gets a bit touchy and I cannot see why the DB is locked or force-everyone out.

A: "I do two checks to see if users are connected to database"
If you need to open the db exclusively, you can skip the other checks and just check whether you can do it.
Public Function CheckExclusive(ByVal pFullPath As String) As Boolean
    Dim blnReturn As Boolean
    Dim cn As Object
    Dim strConnection As String

On Error GoTo ErrorHandler

    strConnection = "Provider=" & _
        CurrentProject.Connection.Provider & _
        ";Data Source=" & pFullPath & ";"
    Set cn = CreateObject("ADODB.Connection")
    cn.Mode = 12& ' adModeShareExclusive '
    cn.Open strConnection
    blnReturn = True
    cn.Close

ExitHere:
    On Error Resume Next
    Set cn = Nothing
    On Error GoTo 0
    CheckExclusive = blnReturn
    Exit Function

ErrorHandler:
    blnReturn = False
    GoTo ExitHere
End Function

Then call that function with the full path to your db file.
If CheckExclusive("C:\SomeFolder\YourDb.mdb") = True Then
    ' do what you need here which requires exclusive access: '
    '     make backup; compact; whatever '
End If

redpajama_set_name: RedPajamaStackExchange


text:
Q: An Issue with Passing a Vector into a Loop I've been using the Rosalind problems to learn clojure and the code below is part of a solution for the mortal rabbits problem. My solution was to create a record called rabbit that would keep track of each rabbit. The rabbit record would be stored in a vector and I would loop over the months and at each month update the vector by adding new rabbits (add-rabbits) and filtering the dead ones (remove-rabbits).
This sounds straightforward enough but I have run into a problem that I can't seem to wiggle around: when I try to pass the updated vector back into the loop I run into an error and I'm looking to figure out whats going on. I'm sure its one of those errors that I'll back on and it will be super obvious but hey, thats what happens with a new language right? Any insights would be appreciated.
;define a rabbit record with birth and death months
(defrecord rabbit [born dies] )
; function that calculates number of living rabbits
(defn iter-rabbit2 [months lifemonths]
  (letfn [ (add-rabbits [month rabbits]
           ;add-rabbits looks for reproductively active rabbits and creates new rabbits
               (let [num-repr-rabbits (count (filter #(>= (+ month 1) (.born %)) rabbits))
                     new-rabbits (vec (repeat num-repr-rabbits (rabbit. (+ month 1) (+ month lifemonths 1))))]
                    (do
                     (println "rabbits" rabbits)  ; for debugging
                     (println "rabbits type " (type rabbits))
                     (if (seq new-rabbits)
                         (apply conj (vec rabbits) (vec new-rabbits))
                         (rabbits)))))

          (remove-rabbits [month rabbits]
          ;remove rabbits filters the rabbits vector of dying rabbits
                (let [livingrabbits (vec (filter #(not= month (.dies %)) rabbits ))]
                     (do
                       (println "remove rabbits rabbits" livingrabbits) ;for debugging
                       (println (type livingrabbits))
                       (livingrabbits)))) ]

   (loop [month 0
          lifemonth lifemonths
          rabbits  [(rabbit. month lifemonth)] ]

    (if (= month months)
        [rabbits]
        (recur (+ month 1)
               (+ lifemonth 1)
               ( ->> rabbits
                      (add-rabbits month)
                      (remove-rabbits month)
                      (apply vector)
                      ))))))
(iter-rabbit2 5 6)

The error i am getting is the following:
    ArityException Wrong number of args (0) passed to: PersistentVector
    clojure.lang.AFn.throwArity (AFn.java:437)

A: At the end of remove-rabbits you have (livingrabbits) which calls livingrabbits as an IFn with 0 arguments. Above that you define livingrabbits as a vector filtered from rabbits. A vector when called as an IFn takes one or two arguments: the index to look up and return, and the optional default if that index does not exist.
Similarly at the end of add-rabbits you have a call to (rabbits). In the recursion at the bottom of the function it seems that rabbits should also be a vector, so it also is being called with too few arguments.
I assume that you didn't mean to invoke livingrabbits / rabbits, but instead to return them. You can likely simply remove the extraneous parens (unless you meant to put rabbits in a parent data structure, in which case you can replace the parens with square brackets).

A: Can I make a few suggestions.

*

*You don't need to create a record for every individual rabbit. All
rabbits born in the same year behave the same way. You only need to
count them.

*Using your code, corrected as noisesmith suggests above, the
numbers are wrong: they do not match the solution given on the problem page.

*For problems like this, the Clojure idiom is to present the
solution as a lazy sequence. You can find an excellent account
of this in Chapter 4 of Programming Clojure by Halloway and
Bedra. A good starting point for your problem is Christopher Grand's solution for the Fibonacci sequence.

Here it is (from memory).
(defn fibo-base []
  (let [step (fn [[a b]] [b (+ a b)])]
    (map first (iterate step [0 1]))))

In general, I find it easier to learn with problems for which Clojure solutions are available. The following are helpful:

*

*4Clojure

*Rosetta Code

*Project Euler


text:
Q: jquery cancel click action after a script I have a script showing the content of tabs. This part works fine but when the user clicks on the link the browser seems to execute the click and bring the user back to the top of the page.
I have a return false into the script to cancel ent click and have also tried with event.preventDefault() but no luck there either.
Here is the HTML:

Tab 1

Tab 2

Tab 3

Tab 1

Tab 1 info here

Tab 2

This is tab 2 here

This is tab 2 here

Tab 3

tab 3 info here

And here is the JS:
$(document).ready(function() {

//When page loads...
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab_content:first").show(); //Show first tab content

//attribute an idea to each tab
$('.tabs li').each(function(i) {
var thisId = $(this).find("a").attr("href");
thisId = thisId.substring(1,thisId.length) + '_top';
$(this).attr("id",thisId);
});

function changeTab(activeTab)
{

            $("ul.tabs li").removeClass("active"); //Remove any "active" class
            $(activeTab + '_top').addClass("active"); //Add "active" class to selected tab, using the id created at document load

            $(".tab_content").hide(); //Hide all tab content

            $(activeTab).fadeIn(); //Fade in the active content

}

//On Click Event
$("ul.tabs li").click(function() {

        //call above function
        changeTab($(this).find("a").attr("href"));
    //event.preventDefault();
    return false;

});

});

A: You apply the click event to LI element, if you want return false; to work, you should apply onclick to A tag.
$("ul.tabs li a").click(function() {
  changeTab($(this).attr("href"));
  return false;
}

A: Change your on click event to this:
$("ul.tabs li a").click(function() {
    //call above function
    changeTab($(this).attr("href"));
    //event.preventDefault();
    return false;

});


text:
Q: BootBox javascript Confirm delete I am using asp.net MVC 5.
In Bootbox js
 $(document).on("click", ".MyLink", function (e) {
     bootbox.confirm("Are you sure?", function(result) {
     Example.show("Confirm result: "+result);
     });
});

@Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { @class = "MyLink" })

How to delete the HTML action link ?
Please find the full details of the code:-
Javascript code:-

    $(document).on("click", ".MyLink", function (e) {
        var self = this;
        bootbox.confirm("Are you sure?", function (result) {
            Example.show("Confirm result: " + result);
            $(self).remove();
        });
    });

HTML Code:-

Index

Content here. Alert!

        @Html.ActionLink("Create New", "Create")

Also see the inside
  code for your
reference:-

             First Name
             Last Name

    @foreach (var item in Model) {

             @Html.DisplayFor(modelItem => item.FirstName)
             @Html.DisplayFor(modelItem => item.LastName)

                @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
                @Html.ActionLink("Details", "Details", new { id = item.CustomerID }) |
                @*@Html.ActionLink("Delete", "Delete", new { id = item.CustomerID, @class = "MyLink" })*@
                Delete

    }

Also see the Controller code for your reference:-
public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Customer customer = db.Customers.Find(id);
        db.Customers.Remove(customer);
        db.SaveChanges();
        if (customer == null)
        {
            return HttpNotFound();
        }
        return RedirectToAction("Index");
        //return View(customer);
    }


text:
Q: Looking for a Test Class for code coverage I have created an Apex Class and VF page for Popup Alert. I am looking for a test class for the same.
Below is my Apex Class:
public class PopUpAlert
{
public Contact cont;

  public PopUpAlert(ApexPages.StandardController contact)
  {

   Contact cont = (Contact)contact.getRecord();
    cont=[select id,Customer__c from Contact where Id=: cont.ID];

  }

  public void setAlertVal(){
     cont.Customer__c = true;
     update cont;
  }
}

This is my Test Class:
@IsTest(SeeAllData=true)

public class TestPopUpAlert
{
    static testMethod void createContact()

 {

        Contact cont = new Contact();
        cont.FirstName = 'Bob';
        cont.LastName  = 'Test';
        cont.MailingStreet = '298 S. Ringo Street';
        cont.MailingCity = 'Little Rock';
        cont.MailingState = 'AR';
        cont.MailingPostalCode = '72201';

        insert cont;
        System.debug('created primary contact');

          Apexpages.StandardController sc = new Apexpages.StandardController(cont);
          PopUpAlert pua = new PopUpAlert(sc);
          setAlertVal sav = new setAlertVal(sc);
          test.startTest();

          cont.Customer__c = True;
          update cont;
          test.stopTest();

 }
}

I have been able to achieve 50% code coverage thus far but am looking for atleast 100% coverage.
Request your help.
Thanks!

A: In order to maximize your test coverage, you need to design test cases that covers every functionality of your class.
Note that the class PopUpAlert has two methods:

*

*The class constructor

*setAlertVal

Your test is covering only the class constructor part, thus you have 50% of code coverage.
I also suggest that you use the AAA pattern while designing your test code. You can read more about it here: http://wiki.c2.com/?ArrangeActAssert.


text:
Q: Type definitions: Create instance of module I'm using the excellent Cleave.js library in my Typescript-based application. Cleave.js is used as follows:
import * as Cleave from 'cleave.js';

new Cleave(element).[whatever]

To aid in development, I'm developing typings for Cleave.js, however, I can't find an pattern in Typescript that allows me to specify the above construct.
When I use export class Cleave { ...}  export default Cleave;
In the case above Typescript complains:
TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

When I import Cleave as import Cleave from 'cleave.js' typescript attempts to find the default field on the imported object which obviously does not exist.
How can write typings for new-able modules?

A: This does not work. The import * as X from 'y' syntax creates a module namespace object. It is meant to be not callable.
You should use the syntax: import Cleave = require('cleave.js') instead.
For learning how to write typings, check out http://www.typescriptlang.org/docs/handbook/declaration-files/templates.html and related sections in the handbook.


text:
Q: Sum all of DB numbers that has a similar email address (spring security - java) So im building a web application on spring boot security.
my application currently allows you to register & login locally, or you can login using a server provider that is google & linkedin.
after registering, it asks you to submit a number of bitcoins, then it saves it to DB in your profile.
every time you register with different provider, it will save in the DB a new profile, the common thing is the email. but the bitcoins will differ since every profile is separated.
what i want to do is sum up the attribute "bitcoin" for those who has the same email (different providers, one email)
to display it in each page with same value.
i'm using this class to access my DB
public interface UserRepository extends JpaRepository<User, Long> {
User findByRegName(String regName);

}
and this is in the main controller to view the bitcoins in the authenticated user page.
    public String wallet(Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    String regName = authentication.getName();

    User user = userRepository.findByRegName(regName);
    model.addAttribute("user", user);
    return "wallet";
}

the DB looks like this
please note that im a beginner in coding. a simple explaination would be appreciated
also if you need extra code to be displayed let me know

A: Assuming you would like to do this entire calculation in a query without requiring any in memory calculation you can do the following (with/without JPA):
with JPA:
@PersistenceContext
    private EntityManager em;

    public Double sumBitCoinForUser(String email) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Double> q = cb.createQuery(Double.class);
        Root<User> r = q.from(User);
        q.select(cb.sum(r.get(User_.bitcoinSum))).where(cb.equal(r.get(User_.email), email));
        return em.createQuery(q).getSingleResult();
    }

where User_ is the metamodel for User , if you dont have a metamodel you can just use the field name so "email" instead of User_.email
if you are not using jpa:
@Query("SELECT sum(u.bitcoinSum) FROM User u WHERE u.email = ?#{[0]}")
    Double findAllActiveUsers( String email);

A: Your repository should look like this -
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByEmail(String email);
}

That will return you all the users with matching email.
In your controller, you can then loop through all the users returned and add up the Bitcoin values.
List<User> users = userRepository.findByRegName(regName);
int total = 0;
for(User user:users) {
    total = total + user.getBitcoin()
}
model.addAttribute("totalBitcoin", total);


text:
Q: How to run Swarm Optimization in a function presented in the same script I want to run Swarm optimization with a function written in the same script.
rng default  % For reproducibility
nvars = 2;
x = particleswarm(fun,nvars)

function val = fun(x)
val=x(1)*exp(x(2));
end

When I run this script the promp windows shows me an error.
How could I fix this?

A: Just at and @ at the begininf of fun ie:
rng default  % For reproducibility
nvars = 2;
x = particleswarm(@fun,nvars)

function val = fun(x)
val=x(1)*exp(x(2));
end


text:
Q: How to get rid of CSS cascading in internal element widgets I've a web app with a bunch of pages. Each page have a few of modal windows.
Such page with modals have structure as below:

Page 1 content here

Modal window

The question is how to separate css styles of modals and pages, i.e. to make page style not affect modal style.
For example, a style p { font-weight: 900 } will affect both page and modal paragraphs.
To clarify: the question is not about how to write css selector which narrows selector by div.page + p,
its question how to organize HTML for widgets as modals, which are contextually bound to certain elements/pages/components.
A simplest solution would be to put all those modals outside of the page components, but that would reduce readability because it would become not clear to which context modal belongs.

A: Whilst you could define a bunch of styling to remove every possible style that could have been set within the page to clear it ready for your widget, this isn't a very good approach if you have control over this code structure.
A much better approach would be to use CSS semantically and define a set of class names that apply to your page styling and not use the generic tag selectors unless you actually want every tag in your markup to use that style.
p { somestyles: here; }

Should mean every p has to do obey this, regardless of where it comes from, widgets and all. If you want ps within my content to obey my style then write
.mycontent > p { somestyles: here; }

and have the markup be

Page 1 content here

Modal window

Say what you really mean and the CSS will flow more naturally.
Edit
An iframe will stop the cascade, but you're completely removing the widget from the markup then (to a different file), which it sounded like you didn't want.
To me, modals are separate to the markup that calls them and can be placed elsewhere, you could include a comment where it is opened if a developer needs to know that information. One modal could legitimately be re-used by many elements on the page.
As for stopping containers affecting their contents, that's what they're for in the land of CSS, but if you really want to work around it then you can create a "reset" class that sets all of the style properties back to the way they were before you applied your styles. There's not a way to just turn off cascading though.

A: Use  .modal p { font-weight: 900 } or .modal > p { font-weight: 900 } for modal elements!
Use .modal before each element of modal that will not create confusion!
For more details learn css selectors its fun CSS Selectors


text:
Q: Python update variable progressively over time I am trying to make a cue list that holds DMX values.
I have two dictionaries:
dict1 = {'test': [0, 24, 45]}
dict2 = {'test': [24, 56, 89]}

I can do
dict1['test'] = dict2['test']

to set dict one values to equal dict2, but this happens immediately. How can I have dict1['test'] transition to the values of dict2['test'] over a span of three seconds? In a ramping motion ie: 0, 1, 2, 3, 4, 5, 6, etc but for every value in the list.
For example, dict1['test'][0] would be
1 sec: 8
2 sec: 16
3 sec: 24 = dict2['test'][0]

and the values would interpolate in between.
Thanks in advance!

A: import time
dict2['test'][0] = 0
while True:
    dict2['test'][0] = dict2['test'][0] + 8
    time.sleep(1)

You can optionally print(dict2['test'][0]) after time.sleep(1) to print what the number is.
To break it down you set the variable to 0, you do a infinite loop, you set the variable to the variable + 8, then you pause the program for one second.
Good luck!


text:
Q: Retrieve already signed document with Docusign API Is there a way to retrieve a document that has already been signed with docusign API. What I want to do is store like a url to the signed document in the database. So that I can retrieve and render the signed document again

A: Yes, as long as your account is not configured to purge completed documents (via Document Retention) the DocuSign cloud will have the completed document(s). Please see the REST API documentation:
https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#Basic%20Scenarios/Retrieving%20Envelope%20and%20Documents.htm?Highlight=documents


text:
Q: Select in ember I have following code in my Handlebars template.
{{#each vouchers in content.vouchers}}
    {{view Ember.Select viewName="hoa[]"
        prompt = "Select Account"
        contentBinding = "content.chartOfAccounts"
        optionLabelPath = "content.ca_name"
        optionValuePath = "content.id"
        selectionBinding = vouchers.ca_id
    }}
{{/each}}

The select is populating correctly, But it seems my selectionBinding is not working.
In vouchers.ca_id I have the id for current selected option. But it,s not working.
Another thing is I cannot set name for the created dropdown.

A: selectionBinding will bind the entire selected model.  If you just want to pass the value, you should use valueBinding instead of selectionBinding.
As for the Select name, just use name="" instead of viewName:
{{view Ember.Select name="name_of_select"}}


text:
Q: Adding array into another array (not array_push or array_merge) I am quite new to PHP and I have some problems with pushing arrays to another. For more details, I want to show a part of my code:
This is a sample response data:
edit: I have more than one "sentenceArray"

{
  "data": [
    {
      "sentenceArray": [
        {
          "path": {
            "type": "walk",
            "nodes": [
              {
                "lat": 39.952614,
                "lng": 32.854491
              },
              {
                "lat": 39.952083,
                "lng": 32.857761
              }
            ]
          }
        },
        {
          "path": {
            "type": "bus",
            "nodes": [
              {
                "lat": 39.952418,
                "lng": 32.85727
              },
              {
                "lat": 39.952797,
                "lng": 32.856825
              },
              {
                "lat": 39.953102,
                "lng": 32.856438
              }
            ]
          }
        },
        {
          "path": {
            "type": "bus",
            "nodes": [
              {
                "lat": 39.964951,
                "lng": 32.841305
              },
              {
                "lat": 39.964785,
                "lng": 32.841514
              }
            ]
          }
        }
      ]
    },
    {
      "sentenceArray": [
        {
          "path": {
            "type": "walk",
            "nodes": [
              {
                "lat": 39.952614,
                "lng": 32.854491
              },
              {
                "lat": 39.952083,
                "lng": 32.857761
              }
            ]
          }
        },
        {
          "path": {
            "type": "bus",
            "nodes": [
              {
                "lat": 39.952418,
                "lng": 32.85727
              },
              {
                "lat": 39.952797,
                "lng": 32.856825
              },
              {
                "lat": 39.953102,
                "lng": 32.856438
              }
            ]
          }
        },
        {
          "path": {
            "type": "bus",
            "nodes": [
              {
                "lat": 39.964951,
                "lng": 32.841305
              },
              {
                "lat": 39.964785,
                "lng": 32.841514
              }
            ]
          }
        }
      ]
    }
  ]
}

Here is what I did so far:
for($j = 0; $j < $l; $j++) {
        if($sentenceArray[$j]['path']['type'] == "bus") {
            if(isset($sentenceArray[$j]['path']['nodes'])){
                $busCount++;
                $nodes = $sentenceArray[$j]['path']['nodes'];
                for($k = 0, $c = count($nodes); $k < $c; $k++) {
                    $latlng = $nodes[$k];
                    array_push($arrBus,$latlng);
                }

            }
        }
    }

At first, I tried to push arrays into one array but my code merged it all in one array, not two separated arrays in one array. By the way, real data is much bigger than this and generated dynamically. So bus array count can be two or more.  It is little bit confusing for me as a newbie PHP developer.
Let me show you what is my goal here:

var lineCoordinates = {
  "0": [
    {
                                "lat": 39.952418,
                                "lng": 32.85727
                            },
                            {
                                "lat": 39.952797,
                                "lng": 32.856825
                            },
                            {
                                "lat": 39.953102,
                                "lng": 32.856438
                            }
  ],
  "1": [
    {
                                "lat": 39.964951,
                                "lng": 32.841305
                            },
                            {
                                "lat": 39.964785,
                                "lng": 32.841514
                            }

  ]
}

This sample output will work for me well.
I spend many hours to do this by myself and I also read my posts on web but couldn't find the solution. Please, do not judge me. As I said, I am newbie. Thanks in advance.
By the way, I use json_decode() when I pull data first and I use json_encode() at the end. But I didn't need to mention it.

A: Iterate the data subarray, then iterate the sentenceArray, then if the ['path']['type'] value is bus and the ['path']['nodes'] subarray exists, then store that subarray as a separate group in the result array.
Code: (Demo)
$array = json_decode($json, true);
foreach ($array['data'] as $datas) {
    foreach ($datas['sentenceArray'] as $subitem) {
        if ($subitem['path']['type'] == 'bus' && isset($subitem['path']['nodes'])) {
            $result[] = $subitem['path']['nodes'];
        }
    }
}
echo json_encode($result);

Output:
[[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514}],[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514}]]

This also work on your full json input string to provide:
[[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438},{"lat":39.953273,"lng":32.856239},{"lat":39.953713,"lng":32.855659},{"lat":39.954017,"lng":32.855296},{"lat":39.95498,"lng":32.854037},{"lat":39.955138,"lng":32.853829},{"lat":39.955317,"lng":32.853592},{"lat":39.955448,"lng":32.853421},{"lat":39.955638,"lng":32.853161},{"lat":39.955744,"lng":32.85303},{"lat":39.956395,"lng":32.852171},{"lat":39.957293,"lng":32.851087},{"lat":39.957668,"lng":32.850631},{"lat":39.957715,"lng":32.850579},{"lat":39.957854,"lng":32.850421},{"lat":39.957963,"lng":32.850286},{"lat":39.959664,"lng":32.848184},{"lat":39.960768,"lng":32.846954},{"lat":39.961228,"lng":32.846328},{"lat":39.961566,"lng":32.845869},{"lat":39.962472,"lng":32.844696},{"lat":39.963265,"lng":32.843721},{"lat":39.963397,"lng":32.84357},{"lat":39.963511,"lng":32.843414},{"lat":39.963628,"lng":32.843271},{"lat":39.963804,"lng":32.843048},{"lat":39.963898,"lng":32.842929},{"lat":39.965452,"lng":32.840996}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514},{"lat":39.964555,"lng":32.841818},{"lat":39.963827,"lng":32.842688},{"lat":39.963622,"lng":32.842942},{"lat":39.963542,"lng":32.843037},{"lat":39.96343,"lng":32.843185},{"lat":39.963304,"lng":32.843335},{"lat":39.962502,"lng":32.844327},{"lat":39.961437,"lng":32.845665},{"lat":39.961162,"lng":32.84601},{"lat":39.961054,"lng":32.84613},{"lat":39.960679,"lng":32.846639},{"lat":39.960299,"lng":32.84711},{"lat":39.959572,"lng":32.848031},{"lat":39.959476,"lng":32.848146},{"lat":39.957918,"lng":32.85016},{"lat":39.957835,"lng":32.850267},{"lat":39.957696,"lng":32.850436},{"lat":39.957636,"lng":32.850509},{"lat":39.957244,"lng":32.850993},{"lat":39.95635,"lng":32.852096},{"lat":39.955658,"lng":32.852909},{"lat":39.954229,"lng":32.854682},{"lat":39.953853,"lng":32.855119},{"lat":39.953422,"lng":32.85567},{"lat":39.953096,"lng":32.856053},{"lat":39.952949,"lng":32.856252},{"lat":39.952406,"lng":32.856964},{"lat":39.952278,"lng":32.857091},{"lat":39.951554,"lng":32.857753},{"lat":39.951114,"lng":32.857934},{"lat":39.950962,"lng":32.857907},{"lat":39.950826,"lng":32.857881},{"lat":39.950556,"lng":32.857782},{"lat":39.94987,"lng":32.857458},{"lat":39.948744,"lng":32.856459},{"lat":39.948303,"lng":32.856178},{"lat":39.947866,"lng":32.855815},{"lat":39.947623,"lng":32.855625},{"lat":39.947283,"lng":32.855428},{"lat":39.946974,"lng":32.855249},{"lat":39.946209,"lng":32.854963},{"lat":39.945342,"lng":32.854679},{"lat":39.945094,"lng":32.85462},{"lat":39.944673,"lng":32.854562},{"lat":39.944124,"lng":32.854557},{"lat":39.943877,"lng":32.854564},{"lat":39.943572,"lng":32.854576},{"lat":39.943336,"lng":32.854503},{"lat":39.943041,"lng":32.854494},{"lat":39.942475,"lng":32.854465},{"lat":39.942371,"lng":32.85444},{"lat":39.942294,"lng":32.854403},{"lat":39.94201,"lng":32.854252},{"lat":39.941672,"lng":32.854101},{"lat":39.941495,"lng":32.854233},{"lat":39.940512,"lng":32.854229}],[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438},{"lat":39.953273,"lng":32.856239},{"lat":39.953713,"lng":32.855659},{"lat":39.954017,"lng":32.855296},{"lat":39.95498,"lng":32.854037},{"lat":39.955138,"lng":32.853829},{"lat":39.955317,"lng":32.853592},{"lat":39.955448,"lng":32.853421},{"lat":39.955638,"lng":32.853161},{"lat":39.955744,"lng":32.85303},{"lat":39.956395,"lng":32.852171},{"lat":39.957293,"lng":32.851087},{"lat":39.957668,"lng":32.850631},{"lat":39.957715,"lng":32.850579},{"lat":39.957854,"lng":32.850421},{"lat":39.957963,"lng":32.850286},{"lat":39.959664,"lng":32.848184},{"lat":39.960768,"lng":32.846954},{"lat":39.961228,"lng":32.846328},{"lat":39.961566,"lng":32.845869},{"lat":39.962472,"lng":32.844696},{"lat":39.963265,"lng":32.843721},{"lat":39.963397,"lng":32.84357},{"lat":39.963511,"lng":32.843414},{"lat":39.963628,"lng":32.843271},{"lat":39.963804,"lng":32.843048},{"lat":39.963898,"lng":32.842929},{"lat":39.965452,"lng":32.840996}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514},{"lat":39.964555,"lng":32.841818},{"lat":39.963827,"lng":32.842688},{"lat":39.963622,"lng":32.842942},{"lat":39.963542,"lng":32.843037},{"lat":39.96343,"lng":32.843185},{"lat":39.963304,"lng":32.843335},{"lat":39.962502,"lng":32.844327},{"lat":39.961437,"lng":32.845665},{"lat":39.961162,"lng":32.84601},{"lat":39.961054,"lng":32.84613},{"lat":39.960679,"lng":32.846639},{"lat":39.960299,"lng":32.84711},{"lat":39.959572,"lng":32.848031},{"lat":39.959476,"lng":32.848146},{"lat":39.957918,"lng":32.85016},{"lat":39.957835,"lng":32.850267},{"lat":39.957696,"lng":32.850436},{"lat":39.957636,"lng":32.850509},{"lat":39.957244,"lng":32.850993},{"lat":39.95635,"lng":32.852096},{"lat":39.955658,"lng":32.852909},{"lat":39.954229,"lng":32.854682},{"lat":39.953422,"lng":32.85567},{"lat":39.953096,"lng":32.856053},{"lat":39.952949,"lng":32.856252},{"lat":39.952406,"lng":32.856964},{"lat":39.952278,"lng":32.857091},{"lat":39.951554,"lng":32.857753},{"lat":39.951114,"lng":32.857934},{"lat":39.950962,"lng":32.857907},{"lat":39.950826,"lng":32.857881},{"lat":39.950556,"lng":32.857782},{"lat":39.94987,"lng":32.857458},{"lat":39.948744,"lng":32.856459},{"lat":39.948303,"lng":32.856178},{"lat":39.947866,"lng":32.855815},{"lat":39.947623,"lng":32.855625},{"lat":39.947283,"lng":32.855428},{"lat":39.947283,"lng":32.855428},{"lat":39.946974,"lng":32.855249},{"lat":39.946209,"lng":32.854963},{"lat":39.945342,"lng":32.854679},{"lat":39.945094,"lng":32.85462},{"lat":39.944673,"lng":32.854562},{"lat":39.944124,"lng":32.854557},{"lat":39.943877,"lng":32.854564},{"lat":39.943572,"lng":32.854576},{"lat":39.943336,"lng":32.854503},{"lat":39.943041,"lng":32.854494},{"lat":39.942475,"lng":32.854465},{"lat":39.942371,"lng":32.85444},{"lat":39.942294,"lng":32.854403},{"lat":39.94201,"lng":32.854252},{"lat":39.941672,"lng":32.854101},{"lat":39.941495,"lng":32.854233},{"lat":39.940512,"lng":32.854229}],[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438},{"lat":39.953273,"lng":32.856239},{"lat":39.953713,"lng":32.855659},{"lat":39.954017,"lng":32.855296},{"lat":39.95498,"lng":32.854037},{"lat":39.955138,"lng":32.853829},{"lat":39.955317,"lng":32.853592},{"lat":39.955448,"lng":32.853421},{"lat":39.955638,"lng":32.853161},{"lat":39.955744,"lng":32.85303},{"lat":39.956395,"lng":32.852171},{"lat":39.957293,"lng":32.851087},{"lat":39.957668,"lng":32.850631},{"lat":39.957715,"lng":32.850579},{"lat":39.957854,"lng":32.850421},{"lat":39.957963,"lng":32.850286},{"lat":39.959664,"lng":32.848184},{"lat":39.960768,"lng":32.846954},{"lat":39.961228,"lng":32.846328},{"lat":39.961566,"lng":32.845869},{"lat":39.962472,"lng":32.844696},{"lat":39.963265,"lng":32.843721},{"lat":39.963397,"lng":32.84357},{"lat":39.963511,"lng":32.843414},{"lat":39.963628,"lng":32.843271},{"lat":39.963804,"lng":32.843048},{"lat":39.963898,"lng":32.842929},{"lat":39.965452,"lng":32.840996}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514},{"lat":39.964555,"lng":32.841818},{"lat":39.963827,"lng":32.842688},{"lat":39.963622,"lng":32.842942},{"lat":39.963542,"lng":32.843037},{"lat":39.96343,"lng":32.843185},{"lat":39.963304,"lng":32.843335},{"lat":39.962502,"lng":32.844327},{"lat":39.961437,"lng":32.845665},{"lat":39.961162,"lng":32.84601},{"lat":39.961054,"lng":32.84613},{"lat":39.960679,"lng":32.846639},{"lat":39.960299,"lng":32.84711},{"lat":39.959572,"lng":32.848031},{"lat":39.959476,"lng":32.848146},{"lat":39.957918,"lng":32.85016},{"lat":39.957835,"lng":32.850267},{"lat":39.957696,"lng":32.850436},{"lat":39.957636,"lng":32.850509},{"lat":39.957244,"lng":32.850993},{"lat":39.95635,"lng":32.852096},{"lat":39.955658,"lng":32.852909},{"lat":39.954229,"lng":32.854682},{"lat":39.953853,"lng":32.855119},{"lat":39.953422,"lng":32.85567},{"lat":39.953096,"lng":32.856053},{"lat":39.952949,"lng":32.856252},{"lat":39.952406,"lng":32.856964},{"lat":39.952278,"lng":32.857091},{"lat":39.951554,"lng":32.857753},{"lat":39.951114,"lng":32.857934},{"lat":39.950962,"lng":32.857907},{"lat":39.950826,"lng":32.857881},{"lat":39.950556,"lng":32.857782},{"lat":39.94987,"lng":32.857458},{"lat":39.948744,"lng":32.856459},{"lat":39.948303,"lng":32.856178},{"lat":39.947866,"lng":32.855815},{"lat":39.947623,"lng":32.855625},{"lat":39.947283,"lng":32.855428},{"lat":39.946974,"lng":32.855249},{"lat":39.946209,"lng":32.854963},{"lat":39.945342,"lng":32.854679},{"lat":39.945094,"lng":32.85462},{"lat":39.944673,"lng":32.854562},{"lat":39.944124,"lng":32.854557},{"lat":39.943877,"lng":32.854564},{"lat":39.943572,"lng":32.854576},{"lat":39.943336,"lng":32.854503},{"lat":39.943041,"lng":32.854494},{"lat":39.942475,"lng":32.854465},{"lat":39.942371,"lng":32.85444},{"lat":39.942294,"lng":32.854403},{"lat":39.94201,"lng":32.854252},{"lat":39.941672,"lng":32.854101},{"lat":39.941495,"lng":32.854233},{"lat":39.940512,"lng":32.854229}],[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438},{"lat":39.953273,"lng":32.856239},{"lat":39.953713,"lng":32.855659},{"lat":39.954017,"lng":32.855296},{"lat":39.95498,"lng":32.854037},{"lat":39.955138,"lng":32.853829},{"lat":39.955317,"lng":32.853592},{"lat":39.955448,"lng":32.853421},{"lat":39.955638,"lng":32.853161},{"lat":39.955744,"lng":32.85303},{"lat":39.956395,"lng":32.852171},{"lat":39.957293,"lng":32.851087},{"lat":39.957668,"lng":32.850631},{"lat":39.957715,"lng":32.850579},{"lat":39.957854,"lng":32.850421},{"lat":39.957963,"lng":32.850286},{"lat":39.959664,"lng":32.848184},{"lat":39.960768,"lng":32.846954},{"lat":39.961228,"lng":32.846328},{"lat":39.961566,"lng":32.845869},{"lat":39.962472,"lng":32.844696},{"lat":39.963265,"lng":32.843721},{"lat":39.963397,"lng":32.84357},{"lat":39.963511,"lng":32.843414},{"lat":39.963628,"lng":32.843271},{"lat":39.963804,"lng":32.843048},{"lat":39.963898,"lng":32.842929},{"lat":39.965452,"lng":32.840996}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514},{"lat":39.964555,"lng":32.841818},{"lat":39.963827,"lng":32.842688},{"lat":39.963622,"lng":32.842942},{"lat":39.963542,"lng":32.843037},{"lat":39.96343,"lng":32.843185},{"lat":39.963304,"lng":32.843335},{"lat":39.962502,"lng":32.844327},{"lat":39.961437,"lng":32.845665},{"lat":39.961162,"lng":32.84601},{"lat":39.961054,"lng":32.84613},{"lat":39.960679,"lng":32.846639},{"lat":39.960299,"lng":32.84711},{"lat":39.959572,"lng":32.848031},{"lat":39.959476,"lng":32.848146},{"lat":39.957918,"lng":32.85016},{"lat":39.957835,"lng":32.850267},{"lat":39.957696,"lng":32.850436},{"lat":39.957636,"lng":32.850509},{"lat":39.957244,"lng":32.850993},{"lat":39.95635,"lng":32.852096},{"lat":39.955658,"lng":32.852909},{"lat":39.954229,"lng":32.854682},{"lat":39.953853,"lng":32.855119},{"lat":39.953422,"lng":32.85567},{"lat":39.953096,"lng":32.856053},{"lat":39.952949,"lng":32.856252},{"lat":39.952406,"lng":32.856964},{"lat":39.952278,"lng":32.857091},{"lat":39.951554,"lng":32.857753},{"lat":39.951114,"lng":32.857934},{"lat":39.950962,"lng":32.857907},{"lat":39.950826,"lng":32.857881},{"lat":39.950556,"lng":32.857782},{"lat":39.94987,"lng":32.857458},{"lat":39.948744,"lng":32.856459},{"lat":39.948303,"lng":32.856178},{"lat":39.947866,"lng":32.855815},{"lat":39.947623,"lng":32.855625},{"lat":39.947283,"lng":32.855428},{"lat":39.946974,"lng":32.855249},{"lat":39.946209,"lng":32.854963},{"lat":39.945342,"lng":32.854679},{"lat":39.945094,"lng":32.85462},{"lat":39.944673,"lng":32.854562},{"lat":39.944124,"lng":32.854557},{"lat":39.943877,"lng":32.854564},{"lat":39.943572,"lng":32.854576},{"lat":39.943336,"lng":32.854503},{"lat":39.943041,"lng":32.854494},{"lat":39.942475,"lng":32.854465},{"lat":39.942371,"lng":32.85444},{"lat":39.942294,"lng":32.854403},{"lat":39.94201,"lng":32.854252},{"lat":39.941672,"lng":32.854101},{"lat":39.941495,"lng":32.854233},{"lat":39.940512,"lng":32.854229}],[{"lat":39.952418,"lng":32.85727},{"lat":39.952797,"lng":32.856825},{"lat":39.953102,"lng":32.856438},{"lat":39.953273,"lng":32.856239},{"lat":39.953713,"lng":32.855659},{"lat":39.954017,"lng":32.855296},{"lat":39.95498,"lng":32.854037},{"lat":39.955138,"lng":32.853829},{"lat":39.955317,"lng":32.853592},{"lat":39.955448,"lng":32.853421},{"lat":39.955638,"lng":32.853161},{"lat":39.955744,"lng":32.85303},{"lat":39.956395,"lng":32.852171},{"lat":39.957293,"lng":32.851087},{"lat":39.957668,"lng":32.850631},{"lat":39.957715,"lng":32.850579},{"lat":39.957854,"lng":32.850421},{"lat":39.957963,"lng":32.850286},{"lat":39.959664,"lng":32.848184},{"lat":39.960768,"lng":32.846954},{"lat":39.961228,"lng":32.846328},{"lat":39.961566,"lng":32.845869},{"lat":39.962472,"lng":32.844696},{"lat":39.963265,"lng":32.843721},{"lat":39.963397,"lng":32.84357},{"lat":39.963511,"lng":32.843414},{"lat":39.963628,"lng":32.843271},{"lat":39.963804,"lng":32.843048},{"lat":39.963898,"lng":32.842929},{"lat":39.965452,"lng":32.840996}],[{"lat":39.964951,"lng":32.841305},{"lat":39.964785,"lng":32.841514},{"lat":39.964555,"lng":32.841818},{"lat":39.963827,"lng":32.842688},{"lat":39.963622,"lng":32.842942},{"lat":39.963542,"lng":32.843037},{"lat":39.96343,"lng":32.843185},{"lat":39.963304,"lng":32.843335},{"lat":39.962502,"lng":32.844327},{"lat":39.961437,"lng":32.845665},{"lat":39.961162,"lng":32.84601},{"lat":39.961054,"lng":32.84613},{"lat":39.960679,"lng":32.846639},{"lat":39.960299,"lng":32.84711},{"lat":39.959572,"lng":32.848031},{"lat":39.959476,"lng":32.848146},{"lat":39.957918,"lng":32.85016},{"lat":39.957835,"lng":32.850267},{"lat":39.957696,"lng":32.850436},{"lat":39.957636,"lng":32.850509},{"lat":39.957244,"lng":32.850993},{"lat":39.95635,"lng":32.852096},{"lat":39.955658,"lng":32.852909},{"lat":39.954229,"lng":32.854682},{"lat":39.953422,"lng":32.85567},{"lat":39.953096,"lng":32.856053},{"lat":39.952949,"lng":32.856252},{"lat":39.952406,"lng":32.856964},{"lat":39.952278,"lng":32.857091},{"lat":39.951554,"lng":32.857753},{"lat":39.951114,"lng":32.857934},{"lat":39.950962,"lng":32.857907},{"lat":39.950826,"lng":32.857881},{"lat":39.950556,"lng":32.857782},{"lat":39.94987,"lng":32.857458},{"lat":39.948744,"lng":32.856459},{"lat":39.948303,"lng":32.856178},{"lat":39.947866,"lng":32.855815},{"lat":39.947623,"lng":32.855625},{"lat":39.947283,"lng":32.855428},{"lat":39.947283,"lng":32.855428},{"lat":39.946974,"lng":32.855249},{"lat":39.946209,"lng":32.854963},{"lat":39.945342,"lng":32.854679},{"lat":39.945094,"lng":32.85462},{"lat":39.944673,"lng":32.854562},{"lat":39.944124,"lng":32.854557},{"lat":39.943877,"lng":32.854564},{"lat":39.943572,"lng":32.854576},{"lat":39.943336,"lng":32.854503},{"lat":39.943041,"lng":32.854494},{"lat":39.942475,"lng":32.854465},{"lat":39.942371,"lng":32.85444},{"lat":39.942294,"lng":32.854403},{"lat":39.94201,"lng":32.854252},{"lat":39.941672,"lng":32.854101},{"lat":39.941495,"lng":32.854233},{"lat":39.940512,"lng":32.854229}]]

Question Extension
To filter the results by user-provided value seq:
if (!isset($_GET['seq']) || !ctype_digit($_GET['seq'])){
    echo "Missing/Invalid SEQ value.";
} else {
    $array = json_decode($json, true);
    $result = [];
    $selected_seq = (int)$_GET['seq'];
    foreach ($array['data'] as $seq => $datas) {
        if ($seq === $selected_seq) {
            foreach ($datas['sentenceArray'] as $subitem) {
                if ($subitem['path']['type'] == 'bus' && isset($subitem['path']['nodes'])) {
                    $result[] = $subitem['path']['nodes'];
                }
            }
        }
    }
    echo json_encode($result);
}

A: Please follow below code:
 for($j = 0; $j < $l; $j++) {
    if($sentenceArray[$j]['path']['type'] == "bus") {
        $childArr = array();
        if(isset($sentenceArray[$j]['path']['nodes'])){
            foreach($sentenceArray[$j]['path']['nodes'] as $nodes)
            {
                array_push($childArr, $nodes);
            }
        }
        $arrBus[$j] = $childArr;
    }
}

$arrBus = array_values($arrBus);
$arrBus = json_encode($arrBus);

Output as below:
 [
   [
      {
         "lat":39.952418,
         "lng":32.85727
      },
      {
         "lat":39.952797,
         "lng":32.856825
      },
      {
         "lat":39.953102,
         "lng":32.856438
      }
   ],
   [
      {
         "lat":39.964951,
         "lng":32.841305
      },
      {
         "lat":39.964785,
         "lng":32.841514
      }
   ]
]

A: This code will produce the output that you desire ($json is assumed to contain the JSON from your first snippet):
$arr = json_decode($json);
$buslines = new stdClass();
$routenum = 0;
foreach ($arr->data as $data) {
    foreach ($data->sentenceArray as $route) {
        if (!isset($route->path, $route->path->type, $route->path->nodes)) continue;
        if ($route->path->type != 'bus') continue;
        $buslines->{$routenum} = array();
        foreach ($route->path->nodes as $node) {
            $buslines->{$routenum}[] = $node;
        }
        $routenum++;
    }
}
echo json_encode($buslines);

Output:
{
  "0": [
        {"lat":39.952418,"lng":32.85727},
        {"lat":39.952797,"lng":32.856825},
        {"lat":39.953102,"lng":32.856438}
       ],
  "1": [
        {"lat":39.964951,"lng":32.841305},
        {"lat":39.964785,"lng":32.841514}
       ]
}


text:
Q: Page size specification does not work when saving HTML file as PDF in Chrome using python I wanted to open an HTML file on Chrome and save it as a PDF,
I wrote the following code using python, but even I set the "pageSize" in appState in the code to A3, A5, letter size or other size,
the page size of the output PDF file will always be A4.
If I change the values of the other properties "isLandscapeEnabled" or "isHeaderFooterEnabled" in appState, it works well.
So, it seems the "pageSize" property only not works.
And, I found when Control Panel-> Region-> Format (F) is set to Japan, the page size of the output PDF file will always be A4,
and if I set it to the United States, it will always be letter size.
So, I think the "pageSize" is always be set by the default value.
I'm a python beginner and I don't really understand it yet.
Is there something wrong with my code?
Please give me any advice.

*

*Python 3.9.6

*selenium 3.141.0

*Chrome 94.0.4606.71

*ChromeDriver 94.0.4606.61

*windows10

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
import time

def PrintSetUp():
    chopt=webdriver.ChromeOptions()
    appState = {
        "recentDestinations": [
            {
                "id": "Save as PDF",
                "origin": "local",
                "account":""
            }
        ],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
        "isLandscapeEnabled": False,
        "pageSize": 'A3',
        "marginsType": 0,
        "scalingType": 3 ,
        "scaling": "100" ,
        "isHeaderFooterEnabled": False, #ヘッダーとフッター
        "isCssBackgroundEnabled": True, #背景のグラフィック
    }

    prefs = {'printing.print_preview_sticky_settings.appState':
             json.dumps(appState),
             "download.default_directory": "~/Downloads"
             }
    chopt.add_experimental_option('prefs', prefs)
    chopt.add_argument('--kiosk-printing')
    return chopt

def main_WebToPDF(BlogURL):
    chopt = PrintSetUp()
    driver_path = "C:/Work/pythonTest/Ver94/chromedriver_win32/chromedriver.exe" #webdriverのパス
    driver = webdriver.Chrome(executable_path=driver_path, options=chopt)
    driver.implicitly_wait(10) # 秒 暗示的待機
    driver.get(BlogURL) #ブログのURL 読み込み
    WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located)  # ページ上のすべての要素が読み込まれるまで待機(15秒でタイムアウト判定)
    driver.execute_script('return window.print()') #Print as PDF
    time.sleep(10) #ファイルのダウンロードのために10秒待機
    driver.quit() #Close Screen

if __name__ == '__main__':
    BlogURLList=["file://C:/Work/pythonTest/1_pdf.html",
                 "file://C:/Work/pythonTest/2_pdf.html",
                 "file://C:/Work/pythonTest/3_pdf.html"]
    for BlogURL in  BlogURLList:
        main_WebToPDF(BlogURL)


text:
Q: How do I perform arbitrary calculations on groups of records in a Spark dataframe? I have a dataframe like this:
|-----+-----+-------+---------|
| foo | bar | fox   | cow     |
|-----+-----+-------+---------|
|   1 |   2 | red   | blue    | // row 0
|   1 |   2 | red   | yellow  | // row 1
|   2 |   2 | brown | green   | // row 2
|   3 |   4 | taupe | fuschia | // row 3
|   3 |   4 | red   | orange  | // row 4
|-----+-----+-------+---------|

I need to group the records by "foo" and "bar" and then perform some magical computation on "fox" and "cow" to produce "badger", which may insert or delete records:
|-----+-----+-------+---------+---------|
| foo | bar | fox   | cow     | badger  |
|-----+-----+-------+---------+---------|
|   1 |   2 | red   | blue    | zebra   |
|   1 |   2 | red   | blue    | chicken |
|   1 |   2 | red   | yellow  | cougar  |
|   2 |   2 | brown | green   | duck    |
|   3 |   4 | red   | orange  | peacock |
|-----+-----+-------+---------+---------|

(In this example, row 0 has been split into two "badger" values, and row 3 has been deleted from the final output.)
My best approach so far looks like this:
val groups = df.select("foo", "bar").distinct
groups.flatMap(row => {
  val (foo, bar): (String, String) = (row(0), row(1))
  val group: DataFrame = df.where(s"foo == '$foo' AND bar == '$bar'")
  val rowsWithBadgers: List[Row] = makeBadgersFor(group)
  rowsWithBadgers
})

This approach has a few problems:

*

*It's clumsy to match on foo and bar individually. (A utility method can clean that up, so not a big deal.)

*It throws an Invalid tree: null\nnull error because of the nested operation in which I try to refer to df from inside groups.flatMap. Don't know how to get around that one yet.

*I'm not sure whether this mapping and filtering actually leverages Spark distributed computation correctly.

Is there a more performant and/or elegant approach to this problem?
This question is very similar to Spark DataFrame: operate on groups, but I'm including it here because 1) it's not clear if that question requires addition and deletion of records, and 2) the answers in that question are out-of-date and lacking detail.
I don't see a way to accomplish this with groupBy and a user-defined aggregate function, because an aggregation function aggregates to a single row. In other words,
udf(<records with foo == 'foo' && bar == 'bar'>) => [foo,bar,aggregatedValue]

I need to possibly return two or more different rows, or zero rows after analyzing my group. I don't see a way for aggregation functions to do this -- if you have an example, please share.

A: A user-defined function could be used.
The single row returned can contain a list.
Then you can explode the list into multiple rows and reconstruct the columns.
The aggregator:
import org.apache.spark.sql.Encoder
import org.apache.spark.sql.Encoders.kryo
import org.apache.spark.sql.expressions.Aggregator

case class StuffIn(foo: BigInt, bar: BigInt, fox: String, cow: String)
case class StuffOut(foo: BigInt, bar: BigInt, fox: String, cow: String, badger: String)
object StuffOut {
  def apply(stuffIn: StuffIn): StuffOut = new StuffOut(stuffIn.foo,
stuffIn.bar, stuffIn.fox, stuffIn.cow, "dummy")
}

object MultiLineAggregator extends Aggregator[StuffIn, Seq[StuffOut], Seq[StuffOut]] {
  def zero: Seq[StuffOut] = Seq[StuffOut]()
  def reduce(buffer: Seq[StuffOut], stuff: StuffIn): Seq[StuffOut] = {
    makeBadgersForDummy(buffer, stuff)
  }

  def merge(b1: Seq[StuffOut], b2: Seq[StuffOut]): Seq[StuffOut] = {
    b1 ++: b2
  }
  def finish(reduction: Seq[StuffOut]): Seq[StuffOut] = reduction
  def bufferEncoder: Encoder[Seq[StuffOut]] = kryo[Seq[StuffOut]]
  def outputEncoder: Encoder[Seq[StuffOut]] = kryo[Seq[StuffOut]]
}

The call:
val averageSalary: TypedColumn[StuffIn, Seq[StuffOut]] = MultiLineAggregator.toColumn

val res: DataFrame =
  ds.groupByKey(x => (x.foo, x.bar))
          .agg(averageSalary)
          .map(_._2)
          .withColumn("value", explode($"value"))
          .withColumn("foo", $"value.foo")
          .withColumn("bar", $"value.bar")
          .withColumn("fox", $"value.fox")
          .withColumn("cow", $"value.cow")
          .withColumn("badger", $"value.badger")
          .drop("value")


text:
Q: How to pronounce "Karl Wilhelm Bücher" in american english? How to pronounce "Karl Wilhelm Bücher" in american english?
please use the standard phonetics
Karl Wilhelm Bücher (16 February 1847, Kirberg, Hesse – 12 November 1930, Leipzig, Saxony) was a German economist, one of the founders of non-market economics, and the founder of journalism as an academic discipline.[citation needed]

A: As a U.S. speaker I would suggest that it depends on your audience.  If your audience is educated, you might expect them to have some understanding of German pronunciation and it may serve you well to pronounce it as Germans would.  This will let your audience know you too are educated and undaunted by umlauts.
If your audience is common you should expect them to have no understanding of German pronunciation and pronounce it as you would were it an English name.  Common folk in the U.S. have trouble with umlauts.  Nothing will alienate you from a group of common folk quicker than 'fancy pronunciations'.


text:
Q: OpenGL application fades when texturing an object I have an application that animates a person traversing the halls of a spaceship. I have also created an OpenGL DLL that the application links to. The purpose of this OpenGL DLL is to intercept specific calls, and then do something when these calls are intercepted.
The main call that i am concerned about intercepting is wglSwapBuffer ( i think thats the name ). In this call, i render a 3D object ( half sphere or half cylinder ) and specify texture coordinates for each vertex. I then capture the output of the framebuffer, and use it to texture the contents of the sphere using glCopyTexImage2D, or something like that.
After i do all that stuff, my dll the calls the real dll and the real swapbuffer method is called.
When i place my dll in the same folder as the application, I get what i expect, a dome with graphics textured onto it. What i did not expect is that the screen fades constently. What i mean by that is that everything looks the way its supposed to, and then over a second interval, the screen will fade to be completly black, and then it will come back to being normal. This repeats with an average frequency of about a second, sometimes its faster, sometimes its slower, it seems to depend on hard the processor is working.
Any ideas?

A: Turns out it was something to with blending. So in the swapbuffer method, i disabled blending, did my stuff, and then re-enabled blending, and now it works.


text:
Q: Function containing pandas query can't find local variable only if imported EDIT Before BOUNTY:
I would like to have a function where I can write subset(pd.dataframe,query="col %in% list_with_substrings")
Where it returns the same dataframe where only rows contains any of the substrings in list_with_substrings for the col.
As if i had written:  dataframe.query("col in @list_with_substring")
And it should be possible to import that function into another script, and not have to redefine the function everytime it is used. If redefining is the only option, then it should be done inside the function itself. So that the subset call is a single line.
Original Post:
I have two scripts:
"dataprocessing.py"
import pandas as pd
def subset(df,query):
    query = query.replace("%in%", "in @")
    query = query.replace("%!in%", "not in @")
    return pd.DataFrame(df.query(query))

and "test_dataprocessing.py"
from dataprocessing import *

df = pd.DataFrame({'countries':['US','UK','GE','Ch',"DK","SW"]})
countries_to_subset = ['UK','CH']

subset(df,query="countries %in% countries_to_subset")

This produces the error:
pandas.core.computation.ops.UndefinedVariableError: local variable 'countries_to_subset' is not defined
but if I then define the function inside the same script
def subset(df,query):
    query = query.replace("%in%", "in @")
    query = query.replace("%!in%", "not in @")
    return pd.DataFrame(df.query(query))

subset(df,query="countries %in% countries_to_subset")

Out:
  countries  GDP
1        UK    2
3     China    4

So I can't import a function that uses query and pass it a local variable?
Is there a way to import the subset function "as if" it was defined in the same script?
tested on Python 3.6 & 3.7 and pandas 0.23.0 & 0.24.2

A: It looks like the easiest thing to do is use f-strings:
dataprocessing.py
import pandas as pd

def subset(df,query):
    query = query.replace("%in%", "in") # remove @
    query = query.replace("%!in%", "not in") # remove @
    return pd.DataFrame(df.query(query))

test_dataprocessing.py
import pandas as pd
from dataprocessing import *

df = pd.DataFrame({'countries':['US','UK','GE','Ch',"DK","SW"]})
countries_to_subset = ['UK','CH']

subset(df, query=f"countries %in% {countries_to_subset}")

A: This happens because you evaluate the query in subset.
subset has only access to the variables in it's scope, meaning the:

*

*parameters passed into the function (df and query)

*local variables (query)

*module scope variables: (pd and subset)

Since it is evaluated there, it has no access to any of the variables mentioned in the query.
A simple way too solve this, is instead of return the result of the query, the translated query.

A: Here is a solution but the only doubt is that you have extra lines in the testing file, and using an unsafe exec.
test_dataprocessing.py:
import inspect
exec(inspect.getsource(__import__('dataprocessing')))

df = pd.DataFrame({'countries':['US','UK','GE','Ch',"DK","SW"]})
countries_to_subset = ['UK','CH']

subset(df,query="countries %in% countries_to_subset")

And no changes with dataprocessing.py.
It will result as expected.


text:
Q: Find and convert a **date** in a string to its numeric form I am extracting strings of dates from documents. Dates can have the following formats:

*

*12 JAN 2014

*June 12 1999

*1999 February 9

*Feb-7-2008

I want to check if a string contains the name of a month and then convert it to its numeric form. For example: 12 JAN 2014 ==> 12 1 2014, June 12 1999 ==> 6 12 1999 etc.

A: I came out with the following solution:
First I create a file with the dates and their numeric values
JANVIER 1
FEVRIER 2
MARS    3
AVRIL   4
MAI 5
JUIN    6
JUILLET 7
AOUT    8
SEPTEMBRE   9
OCTOBRE 10
NOVEMBRE    11
DECEMBRE    12

#include <boost/algorithm/string/replace.hpp>
#include <vector>
#include <iostream>

using namespace std;
vector<pair<string,int>> getDates();
bool dateExists(string,strin);

int main()
{
   //replace JANVIER
    string date = "JANVIER-12-1999";
    vector<pair<string,int>> d = getDates("dates.txt");
    for(size_t i = 0; i < d.size();i++)
    {
        string searchDate = d[i].first;

        if(dateExists(date,searchDate ))
        {
            string num = std::to_string(d[i].second);
            boost::replace_all(date, searchDate ,num );
        }
    }

    cout << date << endl;
    return 0;
}

vector<pair<string,int>> getDates(string path)
{
    vector<pair<string,int>> vec;

    boost::iostreams::stream<boost::iostreams::file_source> file(path.c_str());
    string line;

    while (std::getline(file, line))
    {
        std::vector<string> splitLine;
        boost::split(splitLine,line,boost::is_any_of("\t"));
        vec.push_back(make_pair(splitLine[0],atoi(splitLine[1].c_str())));
    }
    return vec;
}

bool dateExists(string str,string str2)
{
    if (str.find(str2) != string::npos)
        return true;
    else
        return false;

}//end function


text:
Q: How can I bypass Activation Lock? I bought a used iPhone 4.  The previous owner re-set the phone, but did not remove the device from their iCloud.  It is asking me for their iCloud information when I try to set-up the phone.  I don't have contact with the previous owner anymore.  Is there a way to remove the device from their iCloud so I can use a new one?

A: Official steps to turn off Find My iPhone Activation Lock are documented by Apple at https://support.apple.com/en-us/HT201441

In a nutshell, the various ways to remove iCloud Activation Lock include:

*

*Apple will remove the lock if they can verify the original purchaser is requesting the action.

*Self-service removal if you can authenticate as the iCloud account that placed the lock on that device.

*Business using DEP can often use their MDM to remove the lock as a self-service action without needing Apple to be involved.

For consumers, you will likely need to make an appointment at an Apple Store and provide the Genius on-hand proof of purchase (to show you're the authorized owner) along with proof of identity and they will reset Activation Lock, giving you access to the device.
For businesses, it depends if you are enrolled in DEP - Apple's Device Enrollment Program or just want to provide copies of the original purchase listing serial numbers to verify ownership.
If you bought the device second hand, stole it, found it or came to possess the device by some means other than buying it from Apple directly, then you will probably need the original owner to show proof of purchase, etc. They will then transfer the device to your account or simply disable Activation Lock.
The only self-service way to remove the lock if you can't type your password into the device itself is to authenticate at https://icloud.com and remove the activation lock when the device is not connected to the internet.

A: Yes, but with some limitations
Checkm8 Software, while awkwardly named, is able to bypass the Activation Lock Screen by exploiting its namesake vulnerability. Note that the software can only temporary bypass the activation lock and thus provide one-time access to the system. You need to follow the developers' how-to guide, which requires you to run the software between Step 3 and 4, to get a permanent (persists between reboots) bypass.
The limitations are, citing their own words:

Unfortunately, deleting Setup.app will force your device to get the
  baseband activation status to UNACTIVATED so the following services
  won't work on your device:

*

*No SIM signal (no service issue)

*No iMessage

*No Facetime

*Not able to add new iCloud account

*Not able to use with iTunes (it will show device activation screen in iTunes)

Honestly, I didn't expect it to work, so I was amazed after successfully bypassed the activation lock on my iPhone 5s running iOS 12.4.4.

A: You cannot do anything technically to get past it. Your only method is to get back to the seller. If they have disappeared, then perhaps you might want to entertain the possibility that you have been sold a stolen iPhone.
In this instance, then rather than have a very expensive paperweight, you might want to report it to the Police. There is a slim chance that it has been reported as stolen, and they may be able to reunite it with it's true owner, in which case there is also a chance that they may reward you in some way to make up for your loss, or (perfect scenario) they will have already replaced it on insurance, and will simply unlock it for you and let you keep it.
To confirm, there is only a human solution to this problem, by getting the owner of the registered Apple ID to unlock it.

A: You can't just bypass it.
The very nature of Activation Lock is that it is impassible so that the device can still be tracked by the owner if it is lost/stolen. You can't bypass it — the only way to remove it is by deleting the device from Find my iPhone on iCloud.com or logging in using the Apple ID that was used to set up Find my iPhone.
You can read more about bypassing (or not) Activation Lock in the following question:

*

*How secure is Activation Lock on iOS 7 (and later)?

A: You can use this method to bypass the iCloud activation (it works only for iPhone 4) http://www.unlockboot.com/2014/03/bypass-ios-71-activation-lock-jailbreak.html


text:
Q: Just started Java, Is this an appropriate solution to 99 Bottles of Beer on the Wall? Link to the problem: http://rosettacode.org/wiki/99_Bottles_of_Beer
My code:
import java.util.Scanner;

public class Application {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Please enter the number of bottles of beer on the wall: ");

    int X = input.nextInt();

    do {
        if (X == 1) {
            System.out.println(X + " bottle of beer on the wall");
            System.out.println(X + " bottle of beer");
            System.out.println("Take one down, pass it around");
            System.out.println(X-- + " bottle of beer on the wall");
            System.out.println();
        } else {
            System.out.println(X + " bottles of beer on the wall");
            System.out.println(X + " bottles of beer");
            System.out.println("Take one down, pass it around");
            System.out.println(X-- + " bottles of beer on the wall");
            System.out.println();
        }
    } while (X >= 0);
}

}
Are there better ways of doing this? I have touched a tiny bit on recursion at school, but do not know how to implement it in Java yet. Any suggestions?

A: Since you know the number of bottles, I would use a for loop instead of a do while. Since the number of bottles entered could be 1 I would use a while instead of a do/while (use a do/while if you want it to happen at least once).
Stylistically, X should be x, or better yet, numberOfBottles.
I'd also move the:
System.out.println();

Out of the if/else as it is the same for both.
And, finally, I'd also move the X-- to a line by itself so that people don't have to think does the X-- happen before or after the print.

A: Here is a very easy implantation of a for loop. Note: I used "\n" which is how you do a new line after you print to the console, in case you are not familiar
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Please enter the number of bottles of beer on the wall: ");

    int numOfBottles = input.nextInt();

    for(int i = numOfBottles; i >= 1; i--){
        System.out.println(i + " bottle of beer on the wall");
        System.out.println(i + " bottle of beer");
        System.out.println("Take one down, pass it around");
        System.out.println(i-1 + " bottle of beer on the wall\n");

}

A: Try this do-while loop:-
    do {
        System.out.println(X + " bottles of beer on the wall");
        System.out.println(X + " bottles of beer");
        System.out.println("Take one down, pass it around");
        X--;
        System.out.println(X + " bottles of beer on the wall\n");
    } while (X > 0);


text:
Q: Community Builder usage of jQuery (or any external .js resource) I'm trying to use jQuery from one of my component helpers inside Community Builder (Lightning Component). I'm concerned about reference conflicts across the various components that may be used, so I don't want to use a static resource reference within the component, itself.
I found this recommendation to be that you include the script reference in the  section for the entire community (which would be a great solution, in my case).
I tried adding the script reference in this section for my community, but it didn't work. I'm using Winter 16.

A: You can use ltng:require to make sure your jquery is encapsulated in every component .Loading the external script on the head might not be available inside each of the component while ltng:require ensures you have files completed loaded
<ltng:require scripts="{!$Resource.***resourceName***}"
    afterScriptsLoaded="{!c.afterScriptsLoaded}" />

Note the Jquery has to be inside the static resources .


text:
Q: Angularjs jsonp on static files I'm getting a CORS issue when downloading a static file from our AWS S3. I'm aware that S3 can be configured to support CORS. However, I also want to learn and know how AngularJS' jsonp works. I've looked at few examples and I'm still confused on the url it is calling.
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";

$http.jsonp(url)
.success(function(data){
    console.log(data.found);
});

If let's say my AWS S3 file is at http://www.amazon.com/S3/sample.jpg, how will I call it with $http.jsonp?


text:
Q: Table borders overlap hover content I'm having an issue where table borders overlap my tooltips, but only in the most recent version of chrome (Version 91.0.4472.77 (Official Build) (arm64)). As an example:

Code is in this notebook.

A: The SVG needed to be wrapped in a div:

    ${Histogram(data, "bill_depth")}

    ${Histogram(data, "bill_length")}


text:
Q: Delay android requesting permissions I have an app which contains <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Is there a way to delay asking the user for the location permission until they take an account which requires it? I've tried removing uses-permission from the XML, this breaks location even after programmatically asking for location permissions.
I do programmatically ask for location info, but that only seems to work if the permission is also specified in the XML.

A: I am assuming that you are experiencing this as you're targeting below Android 6.0?
As per the docs

Android 6.0 Marshmallow introduced a new permissions model that lets
apps request permissions from the user at runtime, rather than prior
to installation. Apps that support the new model request permissions
when the app actually requires the services or data protected by the
services.

Therefore, you will be unable to avoid requesting permissions before the user actually needs to use that particular service, unless you target a higher API level.

A: If you need permission, you can not remove it from manifest. If your target API is above 23 (Android 6) Just ask for permission programmatically when you need it. You as developer determine when to ask for permissions.
Otherwise if user's device is below android 6 or if your target API is below 23 then permissions will be requested at install time and you can not change it.


text:
Q: main.c:19: undefined reference to `usbInit' & undefined reference to `usbPoll' I faced with this error in building my project using v-usb library.followed is my code :
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>

#include "usbdrv.h"

#include <util/delay.h>

USB_PUBLIC uchar usbFunctionSetup(uchar data[8]) {
    return 0; // do nothing for now
}

int main() {

uchar i;

wdt_enable(WDTO_1S); // enable 1s watchdog timer

usbInit();

usbDeviceDisconnect(); // enforce re-enumeration
for(i = 0; i<250; i++) { // wait 500 ms
    wdt_reset(); // keep the watchdog happy
    _delay_ms(2);
}
usbDeviceConnect();

sei(); // Enable interrupts after re-enumeration

while(1) {
    wdt_reset(); // keep the watchdog happy
    usbPoll();
}

return 0;
}

and this is relative part in usbdrv.h:
 #ifndef USB_PUBLIC

 #define USB_PUBLIC

 #endif

USB_PUBLIC void usbInit(void);

USB_PUBLIC void usbPoll(void)

can someone help me?

A: i guess you have forgotten to add the usbdrv-c files to your makefile or may be they are already compiled and you have to add them as a lib to your make file. (But afair with v-usb you have to add c-files)
Please read the documentation of the library and look at the numerous examples that are available for v-usb.


text:
Q: How to negate class selector in Cytoscape.js? I want to select all elements that do not have the class "myclass". How can I do that in Cytoscape.js?
According to http://js.cytoscape.org/#selectors/data, "[^name] Matches elements if the specified data attribute is not defined", however a class is not a data attribute and ^.myclass does not work, neither does :not(.myclass).
The error is The selector :not(.myclass) is invalid.
Is there a way to negate classes?

A: If you want to get the negative class selector, you can do this:
cy.elements().not(cy.$('.yourClass'));

// in more detail
var allElements = cy.elements(); // get all elements
var negators = cy.$('.yourClass');  // get all elements with the class to negate
var result = allElements.not(negators); // gets the difference between the two collections

A: If you really want to achieve this by using selectors only, then you might add a data field to each element which has myclass (this can be done while adding the class), and then use [^myclass]


text:
Q: Using word embeddings to train for document similarity or topic classification This is just a general question since i started on a course but it is closed during christma/ny
I know that word embeddings are mathematical representation of words, my question if I had a dataset which had a large corpus representing the unique words in different documents. When it learn the word embeddings of this corpus can it then be used for classification tasks such as the probability that a given document is said topic
Further for my own curiosity and because i want to get into this industry, what would be a good NLP task to do to represent on my cv? i've got the hang of selenium, pytorch and opencv


text:
Q:   to space not getting converted in javascript The following code simply replace " " to empty space and then compare the resulted string with the actual text but the result always comes "Not Equal" because the variable text always takes one space after replace function call. The console log shows same value for text and content; but at the time of comparison it gives false
<!DOCTYPE html>

A: When in string you use   it is parsed literally as those characters. Instead if you want a non-breaking space, you should use \xa0 character, which is a non-breaking space character.

A: Do not do this .replace(/ /gi, ' '); after declaring your text variable. Istead, do it here
var result = "";
if (text.replace(/ /gi, ' ') == content) {
    result = "Equal";
} else {
     result = "Not Equal";
}


text:
Q: Showing given solution solves ODE?
Let $a(x),b(x)$ two continuous functions and $v=\begin{pmatrix} v_1 \\ v_2\end{pmatrix}$ a solution to the ODE $$y'=\begin{pmatrix}0 & 1 \\ -b(x) & a(x)\end{pmatrix}y$$
  Additionally $v_1 \neq0$ and $w$ is a non-constant solution to the ODE $$y'=\begin{pmatrix}0 & 1 \\ 0 & -2\frac{v_1'}{v_1} + a(x)\end{pmatrix}y$$
  Proof that $u=\begin{pmatrix} (v_1 w_1) \\ (v_1w_1)'\end{pmatrix}$ is a second solution to the first ODE.

As far as I know it would suffices, if we plug in the solution and see that it'll work , but this doesn't work for me because
$u'=\begin{pmatrix} (v_1 w_1)' \\ (v_1w_1)''\end{pmatrix}=$
$\begin{pmatrix}0 & 1 \\ -b(x) & a(x)\end{pmatrix}\begin{pmatrix} (v_1 w_1) \\ (v_1w_1)'\end{pmatrix}$
Now I'm stuck on $(v_1w_1)''=-b(x)(v_1w_1)+a(x)(v_1w_1)'$
Maybe for some $a(t),b(t)$ this is a true statement, but I don't know which ones.

A: This is the info you currently have:
\begin{align*}
  \begin{pmatrix} v_1 ' \\ v_2' \end{pmatrix} &= \begin{pmatrix} 0 & 1 \\ -b(x) & a(x) \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix}\\[0.3cm]
  \begin{pmatrix} w_1 ' \\ w_2' \end{pmatrix} &= \begin{pmatrix} 0 & 1 \\ 0 & -2\frac{v_1'}{v_1} + a(x) \end{pmatrix} \begin{pmatrix} w_1 \\ w_2 \end{pmatrix}
\end{align*}
It can be rewritten as follows:
\begin{align*}
  v_1' &= v_2\\
  v_2' &= -b(x) v_1 + a(x) v_2 \tag{1}\\
  w_1' &= w_2\\
  w_2' &= -2\frac{v_1'}{v_1} w_2 + a(x)w_2 \tag{2}
\end{align*}
Equation $(2)$ gives this:
$$ v_1 w_2' = -2 v_1' w_2 + a(x)v_1w_2 $$
And since $w_1' = w_2$, then $w_1'' = w_2'$ and we have:
$$ v_1 w_1'' = -2 v_1' w_1' + a(x)v_1w_1' \tag{3}$$
You want to show this:
$$ (v_1 w_1)'' = -b(x) (v_1w_1) + a(x) (v_1w_1)'$$
Expand on the LHS to get this:
$$ v_1''w_1 + 2v_1'w_1' + v_1w_1'' = -b(x) (v_1w_1) + a(x) (v_1w_1)' \tag{4}$$
What we're going to do is manipulate the LHS of Equation $(4)$ to make it look like the RHS.  First substitute Equation $(3)$ into the LHS of Equation $(4)$ above and simplify to get:
$$ v_1''w_1 + a(x) v_1 w_1' = -b(x) (v_1w_1) + a(x) (v_1w_1)' \tag{5}$$
Since $v_1' = v_2$, then $v_1'' = v_2'$ and from Equation $(1)$ above we have:
$$ v_1'' = -b(x) v_1 + a(x) v_1' $$
Now multiply both sides by $w_1$ to get:
$$ v_1''w_1 = -b(x) v_1w_1 + a(x) v_1'w_1 \tag{6} $$
Substitute Equation $(6)$ into the LHS of Equation $(5)$ to get:
$$ -b(x) v_1w_1 + a(x) v_1'w_1 + a(x) v_1 w_1' = -b(x) (v_1w_1) + a(x) (v_1w_1)' \tag{7}$$
Notice we have the $b(x)$ term that we want.  Next:
\begin{align*}
  a(x)v_1'w_1 + a(x) v_1w_1' &= a(x) \left(v_1'w_1 + v_1w_1'\right)\\
    &= a(x) (v_1w_1)'
\end{align*}
The last equality above follows from the product rule.  Finally, substitute that into Equation $(7)$ to get the desired result:
$$ -b(x) v_1w_1 + a(x) (v_1w_1)' = -b(x) (v_1w_1) + a(x) (v_1w_1)' $$


text:
Q: rails 3.1 iframe issue I am trying to open an iframe in my application and its not loading, its giving me a error message like WARNING: Can't verify CSRF token authenticity and logging me out. Cam any one suggest as to what could be the workaround. Thahnks.
This link (Iframe causes Can't Verify CSRF Token Authenticity n Rails) does not answer my question, I have the p3p gem installed my iframe loads correctly, but there is any request that is happening in iframe that time niether p3p headers nor csrf token are sent
Here is how i call my iframe
<iframe name="frmane" id="batch_grid_frame" src="<%= store_batches_path(@store, :id => @batch.id) %>" style="border:none; height:100%;width:100%;"></iframe>
I have tried many ways but p3p header or csrf token is not sent on requests made in iframe

A: After struggling a lot and doing research, i finally found a link which helped me resolve my issue. http://forum.dhtmlx.com/viewtopic.php?f=19&t=32855
i added the CSRF token in the dhtmlx grid and it worked i.e. the content inside iframe started loading


text:
Q: How to implement a QThread that runs forever{} with a QWaitCondition but still needs to catch another Slot while doing that I implemented a class that can write data to a serial port via a QQueue and read from it by a slot. I use QAsyncSerial for this which in turn uses boost::asio with a callback.
The class is moved to a thread and its start() method is executed when the QThread emits "started()"
The problem is that I dequeue the QQueue in the start()-method using forever {} and a QWaitCondition. While this is running (which obviously runs forever) the slot connected to the dataReceived signal of QAsyncSerial can not be called, thus I never read anything from the serial port.
What is the usual approach to this problem?
SerialPortHandler::SerialPortHandler(SerialPort serialPort, QObject *parent) : QObject(parent), serialPort(serialPort)
{
    m_enqueueMessageMutex = new QMutex();
    m_messageQueue = new QQueue<BaseMessage*>();
    m_waitCondition = new QWaitCondition();
    serial.open(serialPort.deviceName(), 2400);
    connect(&serial, SIGNAL(dataReceived(QByteArray)), this, SLOT(serialSlotReceivedData(QByteArray)));
}

void SerialPortHandler::serialSlotReceivedData(QByteArray line)
{
    qDebug() << QString(line).toAscii();
}

void SerialPortHandler::sendTestPing()
{
    PingMessage *msg = new PingMessage();
    enqueueMessage(msg);
}

void SerialPortHandler::enqueueMessage(BaseMessage *msg)
{
    QMutexLocker locker(m_enqueueMessageMutex);
    m_messageQueue->enqueue(msg);
    m_waitCondition->wakeAll();
}

void SerialPortHandler::start()
{
    if (!serial.isOpen())
        return;

    forever {
        m_enqueueMessageMutex->lock();
        if (m_messageQueue->isEmpty())
            m_waitCondition->wait(m_enqueueMessageMutex);
        BaseMessage *msg = m_messageQueue->dequeue();
        serial.write(msg->encodeForWriting());
        m_enqueueMessageMutex->unlock();
    }
}

The changed QAsyncSerial callback used by boost::asio:
void QAsyncSerial::readCallback(const char *data, size_t size)
{
    emit dataReceived(QByteArray::fromRawData(data, (int) size));
}

Edit:
I solved this problem with another approach. I ditched QAsyncSerial and instead used the CallbackAsyncSerial which is also distributed by QAsyncSerial directly. Now the callback used by boost::asio is the serialSlotReceivedData "slot". This "solves" the problem since the callback is called in the thread boost::asio runs in. Since it has its own thread it doesn't matter that the thread SerialPortHandler runs in is blocked by the forever loop.
New code: (since QAsyncSerial is something like a wrapper to CallbackAsyncSerial only some trivial things changed)
SerialPortHandler::SerialPortHandler(SerialPort serialPort, QObject *parent) : QObject(parent), serialPort(serialPort)
{
    m_enqueueMessageMutex = new QMutex();
    m_messageQueue = new QQueue<BaseMessage*>();
    m_waitCondition = new QWaitCondition();
    /* serial is now CallbackAsyncSerial and not QAsyncSerial */
    serial.open(QString(serialPort.deviceName()).toStdString(), 2400);
    serial.setCallback(bind(&SerialPortHandler::serialSlotReceivedData, this, _1, _2));

    m_messageProcessingState = MessageProcessingState::Inactive;
}

void SerialPortHandler::start()
{
    if (!serial.isOpen())
        return;

    forever {
        m_enqueueMessageMutex->lock();

        if (m_messageQueue->isEmpty())
            m_waitCondition->wait(m_enqueueMessageMutex);

        BaseMessage *msg = m_messageQueue->dequeue();
        QByteArray encodedMessage = msg->encodeForWriting();
        serial.write(encodedMessage.constData(), encodedMessage.length());

        m_enqueueMessageMutex->unlock();
    }
}

A: 1) Create slot in your thread, for example onMessageReady(), which will do the job.
2) Create a signal indicates that new message ready, and emit it each time you creating a new message.
3) Connect them using QueuedConnection and call your thread's exec function.
This won't block your thread, as WaitforObject does, and you will handle all incoming signals.
something like this:
SerialPortHandler: public QThread
{
  Q_OBJECT
...
signals:
    void sNewMessageReady();
slots:
    void onNewMessageReady();
    void serialSlotReceivedData(QByteArray);
};

SerialPortHandler::SerialPortHandler(SerialPort serialPort, QObject *parent) : QThread(parent), serialPort(serialPort)
{
    m_enqueueMessageMutex = new QMutex();
    m_messageQueue = new QQueue<BaseMessage*>();
    serial.open(serialPort.deviceName(), 2400);
    connect(&serial, SIGNAL(dataReceived(QByteArray)), this, SLOT(serialSlotReceivedData(QByteArray)));
    connect(this, SIGNAL(sNewMessageReady()), this, SLOT(onNewMessageReady()),Qt::QueuedConnection);
}

void SerialPortHandler::enqueueMessage(BaseMessage *msg)
{
    QMutexLocker locker(m_enqueueMessageMutex);
    m_messageQueue->enqueue(msg);
    emit sNewMessageReady();
}

void SerialPortHandler::onNewMessageReady()
{
    QMutexLocker locker(m_enqueueMessageMutex);
    BaseMessage *msg = m_messageQueue->dequeue();
    serial.write(msg->encodeForWriting());
}

after all simply call thread's exec() method, you don't need to reimplement  run() and to use QWaitCondotion at all.

A: This is kind of a shot in the dark, since I'm pretty new to using Qt and I don't know the "usual" approaches to problems like this, but perhaps a call to QCoreApplication::processEvents within the loop would help.

A: Unless it's strictly necessary for some reason, I'd get rid of the QWaitCondition.  Instead, when the have enqueueMessage() emit a (Qt) signal after it has appended new data to the QQueue, and have your worker thread receive that signal (along with whatever other signals it needs to receive) in the usual Qt way.  Then your problem goes away, with no timeouts or other hackery needed.
(optional optimization:  have the serial port only emit the signal if the QQueue was empty before it added the new data, and have the main thread's corresponding slot read from the QQueue until the QQueue is empty -- that can cut down on the number of signals that need to be sent)


text:
Q: Charset issue when scraping webpage with Python and Requests When attempting to download a page in Chinese (appears to be gb2312 according to meta tags). I get gibberish symbols e.g. ê×××(ò) where the Chinese characters are supposed to be after I run the code below and open the file in gb2312 format in gEdit.
Here's the source code of the page in question: https://gist.github.com/anonymous/27663069655db7fd7a19 - the actual site is for educational institutes only.
My code:
r = requests.post("http://example.com", data=payload, cookies=cookies)
f = open('myfile.txt', 'w')
f.write(r.text.encode('gb2312',errors="ignore"))
f.close()

The headers for the page:

{'content-length': '6164', 'x-powered-by': 'ASP.NET', 'date': 'Mon, 11 Mar 2013 05:11:24 GMT', 'cache-control': 'private', 'content-type': 'text/html', 'server': 'Microsoft-IIS/6.0'}

If I try to decode instead of encode, I get this error in Python:

f.write(r.text.decode('gb2312',errors="ignore"))

UnicodeEncodeError: 'ascii' codec can't encode characters in position 2017-2018: ordinal not in range(128)

A: djc@enrai http $ python
Python 2.7.3 (default, Jun 18 2012, 09:39:59)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> rsp = urllib.urlopen('https://gist.github.com/anonymous/27663069655db7fd7a19/raw/836a5c55d0f87a2fa5edcc9a14097c945452f520/chinese.html').read()
>>> import chardet
>>> chardet.detect(rsp)
{'confidence': 0.99, 'encoding': 'utf-8'}
>>> rsp.decode('utf-8')
u'\n(snip)\n'

So, don't believe the charset header, I guess?