Q: Jquery International Telephone number input I am trying to follow jquery tutorial on http://www.jqueryscript.net/form/jQuery-International-Telephone-Input-With-Flags-Dial-Codes.html to create input type number with country code in a form. However, in my case though flag is appearing to change, the country code is not added inside the input field as they show in the demo.
Following is the code they have provided:
<head>
<meta charset="utf-8">
<title>International Telephone Input</title>
<link rel="stylesheet" href="build/css/intlTelInput.css">
<link rel="stylesheet" href="build/css/demo.css">
</head>
   <body>

<form>
  <input id="mobile-number" type="tel">
  <button type="submit">Submit</button>
</form>

<!-- Load jQuery from CDN so can run demo immediately -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="build/js/intlTelInput.js"></script>
<script>
  $("#mobile-number").intlTelInput({
    //allowExtensions: true,
    //autoFormat: false,
    //autoHideDialCode: false,
    //autoPlaceholder: false,
    //defaultCountry: "auto",
    //ipinfoToken: "yolo",
    //nationalMode: false,
    //numberType: "MOBILE",
    //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
    //preferredCountries: ['cn', 'jp'],
    //preventInvalidNumbers: true,
    utilsScript: "lib/libphonenumber/build/utils.js"
  });
</script>

Here is the link where I am trying to implement it: https://www.easyaccom.com/mobile/verifynumber.html
I have tried changing the commented out options in script but it doesn't help.

A: Ok I solved this problem.
So basically here are the option fields that must be true and we need to place the below script before </head> tag.
Script:
<script>
$(function() {
$("#mobile-number").intlTelInput({
allowExtensions: true,
autoFormat: false,
autoHideDialCode: false,
autoPlaceholder: false,
defaultCountry: "auto",
ipinfoToken: "yolo",
nationalMode: false,
numberType: "MOBILE",
//onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
//preferredCountries: ['cn', 'jp'],
preventInvalidNumbers: true,
utilsScript: "lib/libphonenumber/build/utils.js"
});
});
</script>

Place it before closing head tag and remember to call $("#mobile-number").intlTelInput(); as it is important.

A: You just forget to put your jquery code inside de document.ready.
see below:
$(document).ready(function(){

    $("#mobile-number").intlTelInput({
        //allowExtensions: true,
        //autoFormat: false,
        //autoHideDialCode: false,
        //autoPlaceholder: false,
        //defaultCountry: "auto",
        //ipinfoToken: "yolo",
        //nationalMode: false,
        //numberType: "MOBILE",
        //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
        //preferredCountries: ['cn', 'jp'],
        //preventInvalidNumbers: true,
        utilsScript: "lib/libphonenumber/build/utils.js"
    });
});

A: Country code will always be in input field with this code
$("#mobile-number").on("blur keyup change", function() {
if($(this).val() == '') {
    var getCode = $("#mobile-number").intlTelInput('getSelectedCountryData').dialCode;
    $(this).val('+'+getCode);
}});
$(document).on("click",".country",function(){
    if($("#phone").val() == '') {
        var getCode = $("#mobile-number").intlTelInput('getSelectedCountryData').dialCode;
        $("#mobile-number").val('+'+getCode);
}});

A:

$(function() {
$("#mobile-number").intlTelInput({
   autoHideDialCode: false,
   autoPlaceholder: false,
   nationalMode: false
});
});

A: Why country flag and country code are not stable on page post back.
Here is what I have tried so far:
<script>
        $(document).ready(function () {
            $("#Phone").intlTelInput({
                allowDropdown: true,
                // autoHideDialCode: false,
                // autoPlaceholder: "off",
                // dropdownContainer: "body",
                // excludeCountries: ["us"],
                defaultCountry: "auto",
                // formatOnDisplay: false,
                //geoIpLookup: function (callback) {
                //    $.get("http://ipinfo.io", function () { }, "jsonp").always(function (resp) {
                //        var countryCode = (resp && resp.country) ? resp.country : "";
                //        callback(countryCode);
                //    });
                //},
                //initialCountry: "auto",
                // nationalMode: false,
                // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
                // placeholderNumberType: "MOBILE",
                // preferredCountries: ['in','pk', 'np','bd', 'us','bt','sg','lk','ny','jp','hk','cn'],
                // separateDialCode: true,
                utilsScript: "build/js/utils.js"
            });

            $("#Phone").on("countrychange", function (e, countryData) {
                $("#hdnPhone").val(countryData.dialCode);
            });
        });
  </script>
<script>
        $(document).ready(function () {
            $("#Phone").val('');
            var HdnVal = $("#hdnPhone").val();

            if (HdnVal != '') {
                var countryData = $("#Phone").intlTelInput("getSelectedCountryData");

                $("#hdnPhone").val(countryData.dialCode);
            }
        });

    </script>

A: try this code

$("#mobile-number").intlTelInput({
       // allowExtensions: true,
       //autoFormat: false,
        autoHideDialCode: false,
       // autoPlaceholder: false,
       // defaultCountry: "auto",
        //ipinfoToken: "yolo",
        nationalMode: false,
       // numberType: "MOBILE",
       // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
        //preferredCountries: ['cn', 'jp'],
        //preventInvalidNumbers: true,
        utilsScript: "lib/libphonenumber/build/utils.js"
    });
});

A:  //if you want to get coutry code value in input box then set  false
                   nationalMode: false,

 separateDialCode: false,

Pease set this two lines in your function property it will run


Q: Flickr: How to use flickr.photos.geo.getLocation in python or any language? I used the following code to get Latitude and Longitude in python in pycharm environment as
import flickr

api_key = u'xxxxx'
secret_api_key = u'xxxxxx'

photoID=8636126004

for photo in flickr.photos.geo.getLocation(api_key=api_key,photo_id=photoID,extras="geo"):
    print (photo.attrib['id'])
    print (photo.attrib['latitude'])
    print (photo.attrib['longitude'])

But I get the below error as

for photo in flickr.geo.getLocation(api_key=api_key,photo_id=photoID,
  extras="geo"): AttributeError: module 'flickr' has no attribute
  'photos'

Guide me to resolve this error and to get Latitude and Longitude in python. If the suggestion maybe in java or php etc. also helps me. Thanks in advance.


Q: Dynamic sorting with nullable column I am writing dynamic sorting with lambda expression as below:
string sortColumn = imageFilterType == 1 ? "CreatedDate" : "AbuseCount";
var paramExp = Expression.Parameter(typeof(Items), typeof(Items).ToString());
Expression propConvExp = Expression.Convert(Expression.Property(paramExp, sortColumn), typeof(object));
var sortExp = Expression.Lambda<Func<Items, object>>(propConvExp, paramExp);

Above I am creating dynamic sort column and I am applying this sortexpression in bellow query:
var items = _db.Items.AsQueryable()
                     .AsExpandable()
                     .OrderByDescending(sortExp)
                     .Where(predicate)
                     .Select(x => x)
                     .Join(_db.Users, i => i.UserId, u => u.UserID, (i, u) => new
                        {
                            i,
                            FullName = u.UserType == 1 ? u.FirstName + " " + u.LastName : u.CompanyName,
                            u.UserType,
                            u.UserName
                        })
                    .ToList()
                    .Skip(pageIndex)
                    .Take(pageSize);

I have 2 columns in input by which I have to sort data one is CreatedDate and another is Abusecount. I have to apply sorting with one column among both of them. but as I am trying to run above code I am getting error:

"Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types."

Since in my database both column is of nullable type thatswhy I am getting this problem. Is anyone have solution of this problem? I don't want to change in DB. I have to solve it from fron end only.

A: Try this, it's much simplier:
var items = _db.Items.AsQueryable()
                 .AsExpandable();
if (imageFilterType == 1)
   items=items.OrderByDescending(a=>a.CreatedDate);
else
   items=items.OrderByDescending(a=>a.AbuseCount);

items=items.Where(predicate)
                 .Select(x => x)
                 .Join(_db.Users, i => i.UserId, u => u.UserID, (i, u) => new
                    {
                        i,
                        FullName = u.UserType == 1 ? u.FirstName + " " + u.LastName : u.CompanyName,
                        u.UserType,
                        u.UserName
                    })
                 .Skip(pageIndex)
                 .Take(pageSize)
                 .ToList();


Q: Extremely slow WordPress user import on XAMPP I'm posting this question here because I'm not sure it's a WordPress issue.
I'm running XAMPP on my local system, with 512MB max headroom and a 2.5-hour php timeout. I'm importing about 11,000 records into the WordPress wp_user and wp_usermeta tables via a custom script. The only unknown quantity (performance-wise) on the WordPress end is the wp_insert_user and update_user_meta calls. Otherwise it's a straight CSV import.
The process to import 11,000 users and create 180,000 usermeta entries took over 2 hours to complete. It was importing about 120 records a minute. That seems awfully slow.
Are there known performance issues importing user data into WordPress? A quick Google search was unproductive (for me).
Are there settings I should be tweaking beyond the timeout in XAMPP? Is its mySQL implementation notoriously slow?
I've read something about virus software dramatically slowing down XAMPP. Is this a myth?

A: yes, there are few issues with local vs. hosted. One of the important things to remember is the max_execution time for php script. You may need to reset the timer once a while during the data upload.
I suppose you have some loop which takes the data row by row from CSV file for example and uses SQL query to insert it into WP database. I usually put this simple snippet into my loop so it will keep the PHP max_exec_time reset:
$counter = 1;

// some upload query
if (($handle = fopen("some-file.csv", "r")) !== FALSE) {

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

mysql_query..... blablabla....

// snippet
if($counter == '20')  // this count 20 loops and resets the counter
{
    set_time_limit(0);
    $counter = 0;
}
 $counter = $counter + 1;

} //end of the loop

.. also BTW 512MB room is not much if the database is big. Count how much resources is taking your OS and all running apps. I have ove 2Gb WO database and my  MySql needs a lot of RAM to run fast. (depends on the query you are using as well)


Q: designing virtual methods I wonder under what circumstances you would choose the first or the second design :
First design : the child method have to call the base method
public abstract class Base
{
    public virtual void Enable() { IsEnable = true;  }
    public virtual void Disable() { IsEnable = false; }
    public bool IsEnable { get; private set; }
}

public class Child : Base
{
    public override void Enable() { /* do stuffs */  base.Enable(); }
    public override void Disable() {  /* do stuffs */ base.Disable(); }
}

Second design : a virtual method is used to be sure the child do not forget to call the base
public abstract class Base
{
    public void Enable()
    {
        IsEnable = true;
        OnEnable();
    }

    public void Disable()
    {
        IsEnable = false;
        OnDisable();
    }

    public bool IsEnable { get; private set; }
    public virtual void OnEnable() {}
    public virtual void OnDisable() {}
}

public class Child : Base
{
    override void OnEnable() { /* do stuffs */ }
    override void OnDisable() { /* do stuffs */ }
}

Thanks

A: It depends if you really want to make sure IsEnable gets set or not.  If you can imagine scenarios in which the user doesn't want to set it, then I suppose you leave it up to them to call the base method.  Otherwise, do it for them.

A: The second, template-based approach is better in my opinion. It allows you to ensure that some base functionality is always called, and gives you room to add some if none is present at first without the risk of breaking any subclass.

A: As soon as you make a method virtual, you are giving a derived class a chance to break your class.  A responsible deriver will always ask himself "should I call the base implementation?"  Guidance for this should always come from documentation.  MSDN uses standard verbiage:

Notes to Inheritors:
When overriding Xxxxx in a derived
  class, be sure to call the base
  class's Xxxx method so that blablah
  happens.

The C# language makes that easy with the "base" keyword.  Working from the assumption that this documentation is not available or unclear, your second example would strongly discourage a deriver to call the other base class method.  After all, s/he wouldn't use the standard pattern.  Use this pattern only if you want to discourage the inheritor from calling a base class method.

A: In the first one, where the overring class could prevent Enable from being set, I reckon Enable and Disable could potentially be misleading method names.
Something like TryEnable and TryDisable would probably be more accurate implying that there are situations where you cannot enable.
A third possible situation could be catered for if you took example 2 and changed it so the base class calls OnEnable before setting the flag:
public void Enable()
{
    OnEnable(); // Exceptions raised from here prevent the flag being set.
    IsEnable = true;
}

Then overriding classes could prevent the setting of the flag by raising an exception if an error were to occur. Thus error situations would prevent the flag from being changed.
Just food for thought.


Q: What is the need or benefit to use an instance variable/function attribute to implement memoization vs passing down the memo in each call? In a lot of examples of memoization, I see it most commonly that people favor making a wrapper or decorator (or some language-dependent variation of this, such as using a higher-order function to close over a memo object) to store the results of previous function calls in an almost 'state-like' fashion.  Such an example can be seen below:
class Memoize(object):
    def __init__(self, func):
        self.func = func
        self.cache = {}
    def __call__(self, *args):
        if args in self.cache:
            return self.cache[args]
        ret = self.func(*args)
        self.cache[args] = ret
        return ret

@Memoize
def fib(n):
    if n < 2:
        return 1
    return fib(n-2) + fib(n-1)

What is the difference / tradefoff between doing things this way, vs simply passing down a memo in the arguments of your function?  For example, like so:
def fib(n, memo = {}):
    if (n < 2):
        return 1
    if (n in memo):
        return memo[n]
    memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]

A: Separation of concerns: you don't want to muddy your nice clean implementation of fib with all the bookkeeping required to make it more efficient. Let fib compute Fibonacci numbers, and let Memoize worry about memoizing fib (or any other function).


Q: Trigger python script on raspberry pi from a rails application I have a rails application, and when there is an update to one of the rows in my database, I want to run a python script which is on a raspberry pi (example: lights up a LED when a user is created). I'm using PostgreSQL and have looked into NOTIFY/LISTEN channels, but can't quite figure that out. Is there an easy way to do this? The raspberry pi will not be on the same network as the rails application.

A: There are many "easy" ways, depending on your skills.
Maybe: "Write triggers, which are sending the notify on insert/update" is the hint you need?


Q: Closing/tabbing between windows using Javascript or HTML I have a small query. Is it possible to switch between open windows using HTML or JavaScript, for example;
IE open with Intranet. Intranet has a button which when clicked it opens an already running application in this case Citrix Receiver. Basically minimizing the web browser or tabbing across.


Q: error with base logout after extending LogoutListener class My target is to perform a logout from a controller being able to have base logout mechanism correctly performing.
After googling and stack-overflowing on some similar  questions I have tried to implement an extension of class LogoutListener as suggested in the answer here How to log user out of Symfony 2 application using it's internal handlers
I have created the class and I've added the parameter "security.logout_listener.class" in parameters.yml which is imported from config.yml.
Exactly my new class is
# MyBundle/MyLogoutListener.php

    namespace MyBundle;

    use Symfony\Component\Security\Http\Firewall\LogoutListener;
    use Symfony\Component\HttpFoundation\Session\SessionInterface;
    use Symfony\Component\HttpFoundation\Request;

    class MyLogoutListener extends LogoutListener{

        /**
         * Whether this request is asking for logout.
         *
         * @param Request $request
         *
         * @return Boolean
         */
        protected function requiresLogout(Request $request)
        {
            if ($request->hasSession())
              if ( $request->getSession->get('logout') ) {
                  return true;
              }
            }

            return parent::requiresLogout($request);
        }
    }

And the row I've added in parameters.yml is
security.logout_listener.class: MyBundle\MyLogoutListener

Whit this things I have a well working logout functionality activable in the login of a controller but if I try to use the base logout functionality of Symfony2  I receive this error :

Runtime Notice: Declaration of
  MyBundle\MyLogoutListener::requiresLogout() should be compatible with
  Symfony\Component\Security\Http\Firewall\LogoutListener::requiresLogout(Symfony\Component\HttpFoundation\Request
  $request)

For base logout functionality I mean the configuration in the firewall with :
…
           logout:
             path:  /logout
             target: /someaction

…

Please can somebody explain where is the problem ?
Do I need to define a service with MyLogoutListener ?


Q: Zend storing data in session I'm new in Zend and php. For a project, i need to gather 3 ajax Zend Forms together. I know i need to use session to do that but i can't find any information about how to do that. Can someone help me ?
EDIT :
    public function formResAction(){

        $form = new Front_Form_ResPhone();
        $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form1 = $formData;
                print_r ($session->form1);

                echo $this->view->bloc11Fid($formData);
                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

    public function formFidAction(){

            $form = new Front_Form_FidForm();
            $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form2 = $formData;
                print_r ($session->form2);

                echo $this->view->bloc11Fid2($formData);
                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

    public function formFid2Action(){

            $form = new Front_Form_FidForm2();
            $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form3 = $formData;
                print_r ($session->form3);

                echo $this->view->bloc11Res($formData);

                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;

}

public function resFormAction(){

        $form = new Front_Form_ResForm();
        $bdd_Reservation = new Front_Model_DbTable_Reservation();

        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost())){
                // Données non valides

                $session = new Zend_Session_Namespace('forms');
                $formData = $form->getValues();
                $session->form4 = $formData;
                print_r ($session);

                $bdd_Reservation->insert($forms);

                echo $this->view->bloc11Fel($formData);
                exit;

                exit;
            }
            else{
                // Données non valides
//              echo "non valide";
            }
        }
        else{
            // Appel en GET
//              echo "GET";
        }
        echo $form;
        exit;
}

A: Check this:
//create a session namespace
$session = new Zend_Session_Namespace('myapp');

$session->somevar = 'somevalue';

echo $session->somevar; //somevalue

Zend_Session_Namespace has magic getter and setter.
So, if a attribute of the session object is not set, it will be NULL by default.
http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html


Q: Directx Texture interface to existing memory I'm writing a rendering app that communicates with an image processor as a sort of virtual camera, and I'm trying to figure out the fastest way to write the texture data from one process to the awaiting image buffer in the other.
Theoretically I think it should be possible with 1 DirectX copy from VRAM directly to the area of memory I want it in, but I can't figure out how to specify a region of memory for a texture to occupy, and thus must perform an additional memcpy.  DX9 or DX11 solutions would be welcome.
So far, the docs here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb174363(v=vs.85).aspx have held the most promise.

"In Windows Vista CreateTexture can create a texture from a system memory pointer allowing the application more flexibility over the use, allocation and deletion of the system memory"

I'm running on Windows 7 with the June 2010 Directx SDK, However, whenever I try and use the function in the way it specifies, I the function fails with an invalid arguments error code.  Here is the call I tried as a test:
    static char s_TextureBuffer[640*480*4]; //larger than needed
    void* p = (void*)s_TextureBuffer;
    HRESULT res = g_D3D9Device->CreateTexture(640,480,1,0, D3DFORMAT::D3DFMT_L8, D3DPOOL::D3DPOOL_SYSTEMMEM, &g_ReadTexture, (void**)p);

I tried with several different texture formats, but with no luck. I've begun looking into DX11 solutions, it's going slowly since I'm used to DX9. Thanks!


Q: Short story about aliens who use terrifying dreams/visions to conquer other species I read this story many years ago so I've forgotten most of the details.  I think it was told from the point of view of a narrator going through the experience.
People all over the world began having terrifying dreams and/or visions about some impending disaster.  (I think it was an alien invasion, but it might have been some other sort of calamity.)  All the people of Earth were going to suffer horribly before being wiped out.  Everyone became convinced that it was really going to happen and that it could not be avoided.  So the whole world collectively decided to commit suicide to avoid the suffering.  I believe they planned first to painlessly euthanize all the children, and then the adults would kill themselves.
It was revealed (too late) at the end of the story that there really was an alien invasion, but the aliens had only one weapon: the ability to telepathically project images of suffering and death into the minds of other species in order to frighten them into destroying themselves.


Q: Python detect 'key up' event from the terminal I'm trying to write a python program to emulate a musical instrument. While the button is pressed down the note plays, when you take your finger off the button the sound automatically stops:
while buttonUp:
  noteSilent()

  if buttonDown:
     notePlay()

From what I understand the two main ways of doing this are with pygame and through curses. Pygame seems simpler but it seems to be aimed at making graphical apps whereas I'm quite content running this program purely from the command line. I've been trying to get it to work with curses but it's not really having the desired effect. This is what I currently have:
        while key != ord('q'):
        key = stdscr.getch()
        curses.echo()
        stdscr.addch(20, 25, key)
        stdscr.refresh()

        NoteSilent(2)

        if key == ord('a'):
            print "hello"
            NotePlay(2)

This doesn't seem to have the desired effect and so any advice on how to tackle this would be much appreciated.

A: curses doesn't provide separate events for key presses and releases, so you'd probably be better off with pygame if you want it to work that way.
(Weird quasi-exception: ncurses and PDCurses can provide separate press and release events for mouse buttons, if you wanted to go that way. This isn't quite standard curses, and I don't know if the Python interface supports it.)


Q: How to manage products in category on store view Basis I have multiple store views with same root category, also with the same categories for all the store-views. Can we add different products in a category on the basis of store view.
If not, is there any way to do the same ?

A: You can't add different products to the same categories on different stores views.
A workaround would be to duplicate the categories, assign different products to them and disable them based on store view. The drawback here is that you won't be able to use the same URL key for them.
Maybe it's useful to mention that you could use rewrites to 'mimic' the same URL key in the stores (say if you want to the same url_key in the menu or somewhere else), here's how to: https://docs.magento.com/user-guide/marketing/url-rewrite-product.html


Q: ol3 geometryFunction interaction.Draw add GPS point In a project i'm developing we are using the ol.interaction.Draw functionality to draw geometry. The geometryFunction we are using to add a GPS point to the geometry (linestring or polygon). This is accomplished by setting a boolean to add this GPS point. This boolean is set by a button some were in the HTML.
Al works well but the sketch isn't updated untill we move the cursor over the map again. Is there a way to trigger the geometryFunction without moving the cursor over the map?
// Interaction
        $scope.interactions.draw = new ol.interaction.Draw({
            source: $scope.vector.getSource(),
            type: (function () {
                var type = 'Point';
                if ($scope.layer.TypeName == 'LineStyle')
                    type = 'LineString';
                if ($scope.layer.TypeName == 'PolygonStyle')
                    type = 'Polygon';
                return type;
            })(),
            geometryFunction: function (coordinates, geometry) {

                if (!_.isUndefined(geometry)) {
                    // Is move to GPS position selected?
                    if ($scope.moveToGpsPosition_) {
                        // GPS position
                        var pos = _geolocation.geolocation.getPosition();
                        // Line
                        if ($scope.layer.TypeName == 'LineStyle')
                            coordinates.splice(coordinates.length - 1, 0, pos);
                        // Polygon
                        if ($scope.layer.TypeName == 'PolygonStyle')
                            coordinates[0].splice(coordinates.length - 2, 0, pos);
                        // Stop move to GPS position
                        $scope.moveToGpsPosition_ = false;
                    }
                    geometry.setCoordinates(coordinates);
                } else {

                    // Detect geometry type
                    if ($scope.layer.TypeName == 'PointStyle')
                        geometry = new ol.geom.Point(coordinates);
                    if ($scope.layer.TypeName == 'LineStyle')
                        geometry = new ol.geom.LineString(coordinates);
                    if ($scope.layer.TypeName == 'PolygonStyle')
                        geometry = new ol.geom.Polygon(coordinates);
                }
                return geometry;
            }
        });

A: I'm having a difficult time replicating your problem but I suspect you can solve it by added one of the following after your geometry.setCoordinates(coordinates); line:
map.updateSize();
or
map.render();


Q: tomcat to send SSL client certificate I am trying to do a https rest API call with a SSL certificate(PFX file) which have a password. I tested the connection from my desktop with SOAP UI and it is working fine.
I have a web application which is running on tomcat and I need my tomcat to send this certificate for all the http/https call which it will make.
I am not a tomcat person so i am stuck with this now.
I can find in online about how to set up a keystore & server.xml so that my web app can use Client Authentication against things connecting to it, not for when it needs to connect out to some other server(outgoing call).
my tomcat version is : 9.0.22
connector settings on my server.xml file


Q: Error messages on Java code that has me make 2 calculator objects and perform operations on them Here's the main Java file:
   class Main {
  public static void main(String[] args) {
   Calculator One = new Calculator(100,50,"Addition");
   One.calculateNums();
   One.showResults();
   Calculator Two = new Calculator(100,50,"Subtraction");
   Two.changeNumOne("200");
   Two.calculateNums();
   Two.showResults();

  }
}

And here's the calculator java code:
public class Calculator {
  // instance variables - first number, second number, operation
  private int firstNum;
  private int secondNum;
  private String operation;

  // static field to keep track of number of Calculator objects
  public static int Calculatorobjects = 0;
  // default constructor
  public Calculator(){
    int firstNum = 0;
    int secondNum = 0;
    operation = "Addition";
  }
  // initializing constructor
  public Calculator(int firstNum, int secondNum, int NumOperation){
    NumOne = firstNum;
    NumTwo = secondNum;
    NumOperation = operation;
  }
  // getters for all 3 instance variables
  public int one(){
    return firstNum;
  }
  public int two(){
    return secondNum;
  }
  public String three(){
    return operation;
  }
  // setters to be able to change any of the 3 instance variables after creating them
  public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
  }
  public void changeNumOne(int NewNumTwo){
    SecondNum = NewNumTwo;
  }
  public void changeNumOne(String NewNumOperation){
    operation = NewNumOperation;
  }
  // instance method to perform operation
  public void calculateNums(int result){
    if(operation == "Addition"){
      result = firstNum + secondNum;
    }
    if(operation == "Subtraction"){
      result = firstNum - secondNum;
    }
  }
  // instance method to display results
  public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
  }
}

I'm getting the following error messages:
exit status 1
Calculator.java:35: error: method changeNumOne(int) is already defined in class Calculator
  public void changeNumOne(int NewNumTwo){
              ^
Calculator.java:36: error: cannot find symbol
    SecondNum = NewNumTwo;
    ^
  symbol:   variable SecondNum
  location: class Calculator
Calculator.java:52: error: cannot find symbol
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
                                                                               ^
  symbol:   variable result
  location: class Calculator
Main.java:4: error: method calculateNums in class Calculator cannot be applied to given types;
   One.calculateNums();
      ^
  required: int
  found: no arguments
  reason: actual and formal argument lists differ in length
Main.java:8: error: method calculateNums in class Calculator cannot be applied to given types;
   Two.calculateNums();
      ^
  required: int
  found: no arguments
  reason: actual and formal argument lists differ in length
5 errors

I've tried a bunch of random things while trying to fix it and all of them have either done nothing or made even more errors. I'm an amateur at Java so I definitely did a lot of things wrong but if someone could point them out and send the right code that would be great.

A: 1.) At least you need to fix:
public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
}

// Error: Same name as above
public void changeNumOne(int NewNumTwo){
    // Error: Capital SecondName
    SecondNum = NewNumTwo;
}

To:
public void changeNumOne(int firstNum){
    this.firstNum = firstNum;
}

public void changeNumTwo(int secondNum){
    this.secondNum = secondNum;
}

2.) And here you would like to print result, but your class does not have such a variable (also check, if your function calculateNums makes sense):
public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
}

3.) This should also fail:
public Calculator(int firstNum, int secondNum, int NumOperation){
    NumOne = firstNum;
    NumTwo = secondNum;
    NumOperation = operation;
}

Should be:
public Calculator(int firstNum, int secondNum, string operation){
    this.firstNum = firstNum;
    this.secondNum = secondNum;
    this.operation = operation;
}

4.) Here you do not assign the values:
public Calculator(){
    int firstNum = 0;
    int secondNum = 0;
    operation = "Addition";
}

Should be:
public Calculator(){
    this.firstNum = 0;
    this.secondNum = 0;
    this.operation = "Addition";
}

Overall:
There might be other errors.
You need to check all your variables names. They are quite inconsistent. Though, read your error messages carefully and try to understand them for the future.

A: There are many errors. I solved with this code, acting with Calculator class. I commented on the code where there were errors.
class Calculator {
// instance variables - first number, second number, operation
private int firstNum;
private int secondNum;
private int result;   //I declare the result variable so I can print it
private String operation;

// static field to keep track of number of Calculator objects
public static int Calculatorobjects = 0;
// default constructor
public Calculator(){
    this.firstNum = 0;    //useless because uninitialized int are already 0
    this.secondNum = 0;     //same
    this.operation = "Addition";
}
// initializing constructor
public Calculator(int firstNum, int secondNum, String NumOperation){   //NumOperation is a String, not an int
    this.firstNum = firstNum;    //I'm setting the global variables as the local variables that you pass to the constructor
    this.secondNum = secondNum;
    this.operation = NumOperation;
}
// getters for all 3 instance variables
public int one(){
    return firstNum;
}
public int two(){
    return secondNum;
}
public String three(){
    return operation;
}
// setters to be able to change any of the 3 instance variables after creating them
public void changeNumOne(int NewNumOne){
    firstNum = NewNumOne;
}
public void changeNumTwo(int NewNumTwo){.   //changed method name
    secondNum = NewNumTwo;
}
public void changeNumOne(String NewNumOperation){
    operation = NewNumOperation;
}
// instance method to perform operation
public void calculateNums(){
    if(operation.equals("Addition")){     //equals is used to compare strings
        result = firstNum + secondNum;
    }
    if(operation.equals("Subtraction")){
        result = firstNum - secondNum;
    }
}
// instance method to display results
public void showResults(){
    System.out.println(firstNum + " " +  operation + " " + secondNum + " = " + result);
}


Q: Navigation Bar Title Font Size I need to change the size of the Navigation Bar title text for one view controller in my iPhone app. I'm using iOS5, and tried the following code:
if ([self.tabBarItem respondsToSelector:@selector(setTitleTextAttributes:)]) {
    NSLog(@"*** Support method(iOS 5): setTitleTextAttributes:");
    [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                [UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont,
                                                [UIColor blackColor], UITextAttributeTextColor,
                                                [UIColor grayColor], UITextAttributeTextShadowColor,
                                                [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], UITextAttributeTextShadowOffset,
                                                nil]];
}

However this only applies to the tabBarItem.

A: Swift 2.0:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UINavigationBar.appearance().titleTextAttributes = [
            NSFontAttributeName: UIFont(name: "DINNextLTW04-Regular", size: 20)!
        ]

        return true
    }

Or
 override func viewDidLoad() {
  super.viewDidLoad()

  self.navigationController?.navigationBarHidden =  false
  self.title = "SAMPLE"

//Set Color
  let attributes: AnyObject = [ NSForegroundColorAttributeName: UIColor.redColor()]
  self.navigationController!.navigationBar.titleTextAttributes = attributes as? [String : AnyObject]

//Set Font Size
  self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial", size: 37.0)!];

 }

A: You got it already,but you can also use following attributes methods.
For Color,
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor RedColor],UITextAttributeTextColor, nil];

self.navigationController.navigationBar.titleTextAttributes = attributes;

For Size,
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],UITextAttributeFont, nil];

self.navigationController.navigationBar.titleTextAttributes = size;

Thanks.
For iOS 7 and above
For Size:
NSDictionary *size = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Arial" size:17.0],NSFontAttributeName, nil];

self.navigationController.navigationBar.titleTextAttributes = size;

A: You need to grab the navigation bar property and the use @property(nonatomic, copy) NSDictionary *titleTextAttributes.
For further info see UINavigationBar Class Reference and Customizing UINavigationBar section.
To understand better your question: What type of controller do you have?
EDIT
[self.navigationController.navigationBar setTitleTextAttributes:...];

if you access the navigationController within a pushed controller.
[navigationController.navigationBar setTitleTextAttributes:...];

if navigationController is your current UINavigationController. This could be used when for example if you have the following code:
UINavigationController* navigationController = ...;
[navigationController.navigationBar setTitleTextAttributes:...];

A: Since iOS7, I always do like following:
[[UINavigationBar appearance] setTitleTextAttributes:
    [NSDictionary dictionaryWithObjectsAndKeys:
        [UIFont fontWithName:@"Helvetica-Bold" size:18.0],NSFontAttributeName,
        nil]];

The Keyword UITextAttributeFont has been depressed from iOS7, you'd supposed to replace with
NSFontAttributeName.
You can use
[self.navigationController.navigationBar setTitleTextAttributes:]to set someone navigationController's appearence, while [UINavigationBar appearance] setTitleTextAttributes:] works for your whole App directly.(Of course you need to put it in a property position.)

A: My example
guard let sansLightFont = UIFont(name: "OpenSans", size: 20) else { return }
navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : sansLightFont]


Q: In search of the origins of term censor, I hit a dead end stuck with the greek term, to censor, λογοκρίνω I have been looking in OED for a history that makes sense, yet, I just find crumbs, and I can not piece the history of this term. I am  hitting a dead end researching the greek term to censor, named λογοκρίνω
According to Oxford English Dictionary  the word censure, n., is first documented in use in

*Wyclif Sel. Wks. III. 361  Censures þat þe fend blowiþ, as ben suspendingis, enterditingis, cursingis, and reisingis of croiserie. Back then it was defined as  ‘A spiritual punishment inflicted by some ecclesiastical judge.’ Ayliffe. (The earliest recorded sense.)

  A Roman censor, formerly just called a censor was The title of two magistrates in ancient Rome, who drew up the register or census of the citizens, etc., and had the supervision of public morals.

In the same entry as censure, definition 5 explores, the concept further.

*Censorship; the office or action of a censor.
a. Of the ancient Roman censors (= Latin censūra): also concrete (obsolete).

λογοκρίνω
See Screenshots of the OED entries for all the details, and referenced material.
Entry for  censor
entry for censure n.
Additional context - http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.04.0063:entry=censor-cn

A: censor etymonline

1530s, "Roman magistrate of 5c. B.C.E. who took censuses;  sense of
  "officious judge of morals and conduct" in English is from 1590s. From
  1640s as "official empowered to examine books, plays (later films,
  etc.) to see they are free of anything immoral or heretical." By the
  early decades of the 19c. the meaning of the English word had
  concentrated into "state agent charged with suppression of speech or
  published matter deemed politically subversive

Initially the simple taking of a census, the term began to imply the 'morality police' in English in ~1600, and has remained so since.

A: I have found an etymological account that carries the Latin verb censeo (a probable root of censor and related terms) back to Proto Indo-European. Etymological Dictionary of Latin and the other Italic Languages
by Michiel de Vaan includes the following entry:

Rather than going to Greek, de Vaan goes to the Proto-Italic *knse-; the star denotes that it is a reconstruction based on comparative evidence from related languages, like Faliscan and Oscan. Wiktionary presents some of the other cognates and hypothesized roots in an easily readable format here.


Q: Set of bytes, what are the values of a and b program Project1;
var
  a,b:set of byte;
  c:set of byte;
  i:integer;

begin
  a:=[3];
  b:=[2];
  c:=(a+b)*(a-b);
  FOR i:= 0 TO 5 DO
    IF i IN c THEN write(i:2);
  readln;
end.

Can someone please explain to me what is going on in this code. I know that c=3 but dont understand how, what are the values of a and b ? Tried writeln(a,b);  but gives me an error ...

A: Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well:
The line:
c := (a+b)*(a-b);

does the following:
a + b is the union of the two sets, i.e. all elements that are
      in a or in b or in both, so here, that is [2, 3];
a - b is the difference of the two sets, i.e. it is a minus the
      elements of a that happen to be in b too. In this case, no
      common elements to be removed, so the result is the same as a,
      i.e. [3]
x * y is the intersection of the two sets, i.e. elements that are in
      x as well as in y (i.e. a set with the elements both have in common).

Say, x := a + b; y := a - b;, then it can be disected as:
x := a + b; // [3] + [2] --> [2, 3]
y := a - b; // [3] - [2] --> [3]
c := x * y; // [2, 3] * [3] --> [3]


Q: Silverstripe migration, index and other pages not found. Why? I recently migrated a silverstripe website from a server with apache2 to a new server with nginx. I followed these instructions: http://doc.silverstripe.org/framework/en/installation/nginx . I am using php5-fpm with tcp port (127.0.0.1:9000).
The problem is that i am facing "file not found." as soon as i try to reach the website from the browser.
I would appreciate any help.
Thanks.

A: *

*Which SilverStripe version?

*Is there anything in the logs (both nginx and PHP)?

My slightly tuned nginx configuration for SilverStripe 3 looks like this: https://gist.github.com/xeraa/eab6bc9914e4b75009b8 — this might get you started


Q: Running Code View (assembly debugger) on Win7 x64 I am using Win7 x64.
In my class, we use Win XP x32 and write program in standard MS-DOS editor, and debug our programs with Code View.
But my problem is that I can't set it up home, because I can't run Code View on x64.
I two solutions. One is to change my OS to winXP x32 or install Virtual Machine and use winXP x32 on it.
Is there maybe some other emulator/program that can do same as Code View ? any good tutorials about that?

A: Late answer but hopefully someone will find it useful.
One way to run it is to download DOSBox, it is an emulator of old-timer DOS. Since you are mentioning Code View, I am guessing that you are using MASM as well so short instructions how to run it would be as follows:

*

*Run DOSBox

*In the console, write something like 'mount D C:/masm' where 'masm' is a folder where you have stored your compiler and Code View (cv.exe)

*Next is command 'D:' which will make you inside your 'masm' folder

*Compile it - 'masm myfile.asm'

*Link it - 'link myfile'

*Finally, debug in the Code View 'cv myfile.exe'


Q: Book involving children traveling between alternate worlds via switches I know I read this after 2012, I think as an ebook. The cover depicted a knife switch by itself, I think closed with the handle up. At the beginning of the story, the protagonist, a boy, is told by his friend at school (another boy) about a strange house on the back of a flatbed truck in their neighborhood which they explore after school. It was a small house, like shed-sized, I think with red walls. They find the door is unlocked and inside, there's a switch, I think described as being like the ones in the cover image. I don't remember if they opened the switch, closed it, or maybe tried switching it a few times, but seemingly nothing happened before his friend runs off, saying they need to get home.
The next day, the protagonist finds the world around him has changed. His family treats him in a subtly different way (I want to say that his parents got along better). His school has him enrolled in different activities. Strangest, he's friends with a bully from before, and his friend he was with the day before is afraid of him. I think he finds the house from before and tries the switch again, and winds up in an even different world where that house doesn't exist. I don't remember exactly what happens, but he winds up friends with another boy, who takes him to a homeless man (either the boy or the man had a fancy name, maybe Shakespeare based) who has talked about switches and other worlds. Said man, I think, has a respiratory illness, and he makes them a meal on a hotplate plugged into the building he's squatting in. After talking to them, the man shows them a switch in the basement of the house, which the two boys pull to go to another world.
I forget the details, but they went through several worlds. One involved a theocratic dictatorship with a guy with a fairly normal sounding name, and where they also encountered that homeless man, who didn't recognize them, but still gave some good advice. Another world was a hive mind world, I think on the shores of Lake Michigan (maybe an alternate Chicago?), and I remember they had to recover someone, and at this point they'd been joined by a girl. A later world was a tropical paradise where they found the friend from the beginning, who's served hand and foot by the natives, and who doesn't want to leave. When they try to remove said friend, the natives get violent.
Eventually, they wind up in a very alien world, I think with crystalline grass and telepathic quadrupeds, and they find a man in a building who explains the nature of the various worlds, and that he serves some purpose in keeping them all stable with the controls on front of him. He needs a replacement, and one of the kids volunteers. When he touches the controls, he rapidly ages into adulthood, I think as part of the training process, and sends them home to their original realities. After returning, the original protagonist encounters the boy who was left behind, now elderly, and I think realizes he knew him from before.
The book was in English, and might have been targeted for teenagers, as I remember there wasn't any real sex or violence.

A: In the process of writing the question, I started thinking it might have been named The Switch, so I started searching for that name, and site:goodreads.com "the switch" parallel worlds got me A.W. Hill's The Switch.

IMAGINE THAT you could change your world with the flip of a switch. You might be prettier, more athletic, more popular, or even living on an exotic island, because your history—your world line—would be different. But here’s the catch: you have no way of knowing if the reality on the other side of that switch will be better…or much worse.
JACOBUS ROSE is a fifteen year-old who believes—as many fifteen year-olds do—that his life could use improvement. School is a numbing routine, and his parents’ marriage seems to be imploding before his eyes. ‘Maybe I was born into the wrong world,’ he thinks. Lured by his best friend, CONNOR, into a strange little house containing nothing but empty rooms and an oversized circuit breaker, he’ll discover that reality comes in a plural form, and that our choices create a continuous web of branching worlds, any of which is as ‘real’ as another.
A solo odyssey becomes a duo, a trio, and then a quartet, as Jacobus befriends other interdimensional travelers along the way: GORDON NIGHTSHADE, the veteran pilgrim and chief theorist; MOSES DeWITT, the alley cat with an old soul; JEMMA DOONE, a girl of many-worlds who becomes the main river home for Jacobus and his crew; and finally, his lost friend Connor, who just may have preferred an alternate universe to his own.
THE SWITCH is the story of their journey home. The question is: if they get there, will it be the same place they left behind?

And indeed, the cover shows a knife switch, although it's more colorful than I remember.

I also misremembered the homeless man who goes by the "Duke of Earl".


Q: Is my LUKS header damaged? "Device... is too small..." It's a 38 GB partition, still showing in fdisk as 38 GB.
On entering
$sudo cryptsetup luksOpen /dev/sdb2 ext

I get:
Device /dev/sdb2 is too small. (LUKS requires at least 1049600 bytes.)

I can't imagine what could have happened, EXCEPT that I've been trying to also mount it in Windows 10 (dual-boot) and found that Libre Crypt no longer works; it says that the drive is mounted, but I have no way to access it, as ext2fs is no longer working on this new Windows installation. I only successfully mounted it on Windows 7, before "up"grading to 10. Libre Crypt still says that the passcode is correct and shows it as mounted, and unmounts it normally.
Under Linux, I get the above error message for any attempted LUKS operation, and yes, this only started after the "up" grade.
From what I've read, it does sound like that would be a corrupted header. Is there another way to check?
Many thanks!
(P.S. In this particular case, it is not much actual data and not that urgent, but I still want to know more.)


Q: VBA refresh form I have a simple progress bar. I want to fill it when I make iteration through my loop, but I only see my form with 0 and 100 progress value, so it doesn't refresh during the loop. How can I achieve the runtime refreshment? Thank you!
Sub test()
UserForm1.Show (False)
DoEvents

For i = 1 To 700
    For j = 1 To 5000
        UserForm1.Label1.Caption = 100 * i / 700 & "% Completed"
        UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar
    Next j
Next i

End Sub

A: You just have the DoEvents in the wrong place. Try it like this.
Sub test()
UserForm1.Show vbModeless

For i = 1 To 700
    For j = 1 To 5000
        UserForm1.Label1.Caption = 100 * i / 700 & "% Completed"
        UserForm1.Bar.Width = 200 * i / 700 '200 - width of the bar
        DoEvents
    Next
Next

End Sub


Q: Convert $x/y \cdot \frac{1-\delta_1-\delta_3}{(1-\delta_2)}$ to $x/y \cdot (1-\delta)$ using calculus Want expression in the form $x/y \cdot (1-\delta)$

*

*$\delta_3 \delta_1$ and anything $\delta^2$ can be excluded since they are too small

*$=x/y \cdot \frac{(1-\delta_1)}{(1-\delta_2)}(1-\delta_3)\\=x/y \cdot \frac{(\delta_3 \delta_1 - \delta_1 - \delta_3 + 1)}{(1-\delta_2)}\\\approx x/y \cdot \frac{1-\delta_1-\delta_3}{(1-\delta_2)}$
As you can see its not in the correct form I'm not sure how to simplify the denominator in this case.
Here is an example with multiplication/addition from my textbook

A: Suppose $\max_i(|\delta_i|)\leqslant\epsilon$:
$$\frac{1-\delta_1-\delta_3}{1-\delta_2} \leqslant 1-\delta \iff 1-\delta_1-\delta_3 \leqslant (1-\delta_2)(1-\delta) = 1-\delta_2-\delta+\delta_2\delta \iff$$
$$\iff \delta \leqslant \delta_1-\delta_2+\delta_3 \iff |\delta| \leqslant |\delta_1-\delta_2+\delta_3| \leqslant |\delta_1|+|\delta_2|+|\delta_3| \leqslant 3\epsilon$$
So if you set $|\delta| \leqslant 3\epsilon$, you get:
$$\frac{x}{y} . \frac{1-\delta_1-\delta_3}{1-\delta_2} \leqslant x/y.(1-\delta)$$


Q: Why are we seeing parquet write errors after switching to EMRFS consistent view? we have a large ETL process running on an EMR cluster that reads and writes large number of parquet files to into S3 buckets
Here is the code:
a = spark.read.parquet(path1)
a.registerTempTable('a')
b = spark.read.parquet(path2)
b.registerTempTable('b')
c = spark.read.parquet(path3)
c.registerTempTable('c')

sql = '''
select
a.col1,
a.col2,
b.col1,
b.col2,
c.col1,
c.col2,
a.dt
from
a
join
b
on
a.dt = b.dt
join
c
on
a.dt = c.dt
''''

df_out = spark.sql(sql)

df_out.repartition('dt').write.parquet( path_out, partitionBy='dt', mode='overwrite')

We recently had to switch to transient clusters and thus had to start using consistent view. I am positing our ERMFS site setup below:
{
"fs.s3.enableServerSideEncryption": "true",
"fs.s3.consistent": "false",
"fs.s3.consistent.retryPeriodSeconds": "10",
"fs.s3.serverSideEncryption.kms.keyId": "xxxxxx",
"fs.s3.consistent.retryCount": "5",
"fs.s3.consistent.metadata.tableName": "xxxxx",
"fs.s3.consistent.throwExceptionOnInconsistency": "true"
}

Running the same code wit the same spark configuration - that works on the permanent cluster - on the transient cluster with consistent view enabled results in an error.
...
19/02/25 23:01:23 DEBUG S3NativeFileSystem: getFileStatus could not find key 'xxxxxREDACTEDxxxx'
19/02/25 23:01:23 DEBUG S3NativeFileSystem: Delete called for 'xxxxxREDACTEDxxxx' but file does not exist, so returning false
19/02/25 23:01:23 DEBUG DFSClient: DFSClient writeChunk allocating new packet seqno=465, src=/var/log/spark/apps/application_1551126537652_0003.inprogress, packetSize=65016, chunksPerPacket=126, bytesCurBlock=25074688
19/02/25 23:01:23 DEBUG DFSClient: DFSClient flush(): bytesCurBlock=25081892 lastFlushOffset=25075161 createNewBlock=false
19/02/25 23:01:23 DEBUG DFSClient: Queued packet 465
19/02/25 23:01:23 DEBUG DFSClient: Waiting for ack for: 465
19/02/25 23:01:23 DEBUG DFSClient: DataStreamer block BP-75703405-10.13.32.237-1551126523840:blk_1073741876_1052 sending packet packet seqno: 465 offsetInBlock: 25074688 lastPacketInBlock: false lastByteOffsetInBlock: 25081892
19/02/25 23:01:23 DEBUG DFSClient: DFSClient seqno: 465 reply: SUCCESS downstreamAckTimeNanos: 0 flag: 0
Traceback (most recent call last):
File "xxxxxREDACTEDxxxx", line 112, in <module>
main()
File "xxxxxREDACTEDxxxx", line xxxxxREDACTEDxxxx, in main
xxxxxREDACTEDxxxx
File "xxxxxREDACTEDxxxx", line 70, in main
partitionBy='dt', mode='overwrite')
File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/readwriter.py", line 691, in parquet
File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco
File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o232.parquet.
: org.apache.spark.SparkException: Job aborted.
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply$mcV$sp(FileFormatWriter.scala:215)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:173)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:173)

I suspect that the error is due to the setup of EMRFS but I was not able to find any EMRFS setting that would work. The only thing that results in this error not being thrown while I am running the code above is increasing the number of node to double the normal number. The error also isn't thrown if I decrease the amount of data.
Changing the output commuter and spark speculation does not help either.
Thanks a lot. I will be great full for any ideas / suggestions.

A: "fs.s3.consistent": "false" should be true for emrfs consistent view to work


Q: Shidoku solver matlab code I'm trying to write a Shidoku  ( smaller and easier 4x4 variant of Sudoku) solver code in MATLAB.
I have found some soduko solver (9x9) but i could't revise them to be suitable for my problem. For example:
% Solving Sudoku Using Recursive Backtracking

function X = sudoku(X)
% SUDOKU  Solve Sudoku using recursive backtracking.
%   sudoku(X), expects a 9-by-9 array X.
 % Fill in all “singletons”.
 % C is a cell array of candidate vectors for each cell.
 % s is the first cell, if any, with one candidate.
 % e is the first cell, if any, with no candidates.
 [C,s,e] = candidates(X);
 while ~isempty(s) && isempty(e)
    X(s) = C{s};
    [C,s,e] = candidates(X);
 end
 % Return for impossible puzzles.
 if ~isempty(e)
    return
 end
 % Recursive backtracking.
  if any(X(:) == 0)
    Y = X;
    z = find(X(:) == 0,1);    % The first unfilled cell.
    for r = [C{z}]            % Iterate over candidates.
       X = Y;
       X(z) = r;              % Insert a tentative value.
       X = sudoku(X);         % Recursive call.
       if all(X(:) > 0)       % Found a solution.
          return
       end
     end
   end
% ------------------------------
   function [C,s,e] = candidates(X)
      C = cell(9,9);
      tri = @(k) 3*ceil(k/3-1) + (1:3);
      for j = 1:9
         for i = 1:9
            if X(i,j)==0
               z = 1:9;
               z(nonzeros(X(i,:))) = 0;
               z(nonzeros(X(:,j))) = 0;
               z(nonzeros(X(tri(i),tri(j)))) = 0;
               C{i,j} = nonzeros(z)';
            end
         end
      end
 L = cellfun(@length,C);   % Number of candidates.
 s = find(X==0 & L==1,1);
 e = find(X==0 & L==0,1);
 end % candidates
end % sudoku

Any help will be helpful.

A: Just reduce the problem dimensionality from 3 to 2 (I know now that it is said "9x9" instead of "3x3", but the important dimensional number for the puzzle is N=3):
    % SHIDOKU  Solve Shidoku using recursive backtracking.
    %   shidoku(X), expects a 4-by-4 array X.
    function X = shidoku(X)

            [C,s,e] = candidates(X);
            while ~isempty(s) && isempty(e)
                    X(s) = C{s};
                    [C,s,e] = candidates(X);
            end;

            if ~isempty(e)
                    return
            end;

            if any(X(:) == 0)
                    Y = X;
                    z = find(X(:) == 0,1);

                    for r = [C{z}]
                            X = Y;
                            X(z) = r;
                            X = shidoku(X);
                            if all(X(:) > 0)
                                    return;
                            end;
                    end;
            end;

            % ------------------------------
            function [C,s,e] = candidates(X)
                    C = cell(4,4);
                    bi = @(k) 2*ceil(k/2-1) + (1:2);
                    for j = 1:4
                            for i = 1:4
                                    if X(i,j)==0
                                            z = 1:4;
                                            z(nonzeros(X(i,:))) = 0;
                                            z(nonzeros(X(:,j))) = 0;
                                            z(nonzeros(X(bi(i),bi(j)))) = 0;
                                            C{i,j} = transpose(nonzeros(z));
                                    end;
                            end;
                    end;

                    L = cellfun(@length,C);   % Number of candidates.
                    s = find(X==0 & L==1,1);
                    e = find(X==0 & L==0,1);
             end % candidates

    end % shidoku


Q: printing a div using jQuery How do I just print the article on my web page using jQuery, article is inside a div
window.print() will print the entire window.
So little confused with that...!

A: Don't use jQuery ... use css and media=print.  Here is an article for reference, and here.
Basically, create a new stylesheet for what you want to show when you print, and set the media to print:
<link rel="stylesheet" type"text/css" href="print.css" media="print">

A: You could probably put the content in an iframe and call print() on that window.
A quick google gave me http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=449 which mentions you must focus() before you print(). Note that that page is a few years old.
Also see How do I print an IFrame from javascript in Safari/Chrome.

A: Styling html for printing is commonly achieved using a different style sheet, e.g. in your head element:
<head>
    ...

    <link rel="stylesheet" type="text/css" media="screen" href="style.css">
    <link rel="stylesheet" type="text/css" media="print" href="print.css">
    ...

</head>

The style sheet style.css is used to style your html on screen, while print.css is used to style your html for print. By providing the appropriate styling in print.css you can easily show or hide html elements to achieve the output you are looking for.


Q: How to have working breadcrumbs with several taxonomies associated with a custom post type I have a breadcrumb / navigation problem. I don't know if it's possible to achieve what i want or if i can do it with mysetings or not.
I have a custom post type "Formation", for which i created 2 custom taxonomies :
"Formation type" (formationtype) => hierachical
"Formation public" (formationpublic) => non hierarchical
Formation type :

*

*FT1

*

*FT1.1

*FT1.

*FT2

*

*FT2.1

And "formation public"
public1, public2, ...
I want to have this menu links :
...

*

*Formations    (non clickable)

*

*FT 1     (clickable)

*FT 2     (clickable)

and when I click on FT 1, I have a page displaying a list of all formation of type FT1

*

*FT11

*

*formation1 of type FT11

*formation2 of type FT11

*FT2

*

*formation1 of type FT12

*formation2 of type FT12

And finally when i click on one of the formations : "formation1 of type FT11" i get the complete description of that formation.
So my goal is to be able to make a breabcrumb like :
<Home> / <Formation> / FT1
with the url :  http://mydomain/formation/formation1-of-type-FT11
And
<Home> / <Formation> / <FT1> / <FT11> / formation1 of type FT11
With all the non final elements <...> being clickable to be able to navigate through the breadcrumb and not having to go back to the menu.
Since I create my lists with custom requests, if i use any breadcrumb tool, i only get  something like :
Home / FT1 (at best)
For the second type of taxonomy, I associate one or several terms from "formationpublic" (doctor, nurse, ...) to a formation, I have in the complete description of that formation :

*

*formation1 of type FT11

*Public : ,

*Description ....

If i choose doctor, i have the list of all formation for doctors, but i choose from there a formation i loose the breadcrumb, it is different from the Formation type path.
I have the url : http://mydomain/formation/formation1-of-type-FT11
So my question is what would you suggest as a structure to have "working" breadcrumbs as i (tried to) explain ?
Thank you


Q: Keras LSTM + TensorFlow and a number sequence (improve loss) first of all, I'm running with the following setup:

*

*Running on windows 10

*Python 3.6.2

*TensorFlow 1.8.0

*Keras 2.1.6

I'm trying to predict, or at least guesstimate the following number sequence:
https://codepen.io/anon/pen/RJRPPx (limited to 20,000 for testing), the full sequence contains about one million records.
And here is the code (run.py)
import lstm
import time
import matplotlib.pyplot as plt

def plot_results(predicted_data, true_data):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    plt.plot(predicted_data, label='Prediction')
    plt.legend()
    plt.show()

def plot_results_multiple(predicted_data, true_data, prediction_len):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    #Pad the list of predictions to shift it in the graph to it's correct start
    for i, data in enumerate(predicted_data):
        padding = [None for p in range(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()

#Main Run Thread
if __name__=='__main__':
    global_start_time = time.time()
    epochs  = 10
    seq_len = 50

    print('> Loading data... ')

    X_train, y_train, X_test, y_test = lstm.load_data('dice_amplified/primeros_20_mil.csv', seq_len, True)

    print('> Data Loaded. Compiling...')

    model = lstm.build_model([1, 50, 100, 1])

    model.fit(
        X_train,
        y_train,
        batch_size = 512,
        nb_epoch=epochs,
        validation_split=0.05)

    predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50)
    #predicted = lstm.predict_sequence_full(model, X_test, seq_len)
    #predicted = lstm.predict_point_by_point(model, X_test)

    print('Training duration (s) : ', time.time() - global_start_time)
    plot_results_multiple(predictions, y_test, 50)

I have tried to:

*

*increase and decrease epochs.

*increase and decrease batch size.

*amplify the data.

The following plot represents:

*

*epochs  = 10

*batch_size = 512

*validation_split = 0.05

As well, as far as I understand, the loss should be decreasing with more epochs? Which doesn't seem to be happening!
Using TensorFlow backend.
> Loading data...
> Data Loaded. Compiling...
> Compilation Time :  0.03000473976135254
Train on 17056 samples, validate on 898 samples
Epoch 1/10
17056/17056 [==============================] - 31s 2ms/step - loss: 29927.0164 - val_loss: 289.8873
Epoch 2/10
17056/17056 [==============================] - 29s 2ms/step - loss: 29920.3513 - val_loss: 290.1069
Epoch 3/10
17056/17056 [==============================] - 29s 2ms/step - loss: 29920.4602 - val_loss: 292.7868
Epoch 4/10
17056/17056 [==============================] - 27s 2ms/step - loss: 29915.0955 - val_loss: 286.7317
Epoch 5/10
17056/17056 [==============================] - 26s 2ms/step - loss: 29913.6961 - val_loss: 298.7889
Epoch 6/10
17056/17056 [==============================] - 26s 2ms/step - loss: 29920.2068 - val_loss: 287.5138
Epoch 7/10
17056/17056 [==============================] - 28s 2ms/step - loss: 29914.0650 - val_loss: 295.2230
Epoch 8/10
17056/17056 [==============================] - 25s 1ms/step - loss: 29912.8860 - val_loss: 295.0592
Epoch 9/10
17056/17056 [==============================] - 28s 2ms/step - loss: 29907.4067 - val_loss: 286.9338
Epoch 10/10
17056/17056 [==============================] - 46s 3ms/step - loss: 29914.6869 - val_loss: 289.3236

Any recommendations? How could I improve it? Thanks!
Lstm.py contents:
import os
import time
import warnings
import numpy as np
from numpy import newaxis
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #Hide messy TensorFlow warnings
warnings.filterwarnings("ignore") #Hide messy Numpy warnings

def load_data(filename, seq_len, normalise_window):
    f = open(filename, 'rb').read()
    data = f.decode().split('\n')

    sequence_length = seq_len + 1
    result = []
    for index in range(len(data) - sequence_length):
        result.append(data[index: index + sequence_length])

    if normalise_window:
        result = normalise_windows(result)

    result = np.array(result)

    row = round(0.9 * result.shape[0])
    train = result[:int(row), :]
    np.random.shuffle(train)
    x_train = train[:, :-1]
    y_train = train[:, -1]
    x_test = result[int(row):, :-1]
    y_test = result[int(row):, -1]

    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    return [x_train, y_train, x_test, y_test]

def normalise_windows(window_data):
    normalised_data = []
    for window in window_data:
        normalised_window = [((float(p) / float(window[0])) - 1) for p in window]
        normalised_data.append(normalised_window)
    return normalised_data

def build_model(layers):
    model = Sequential()

    model.add(LSTM(
        input_shape=(layers[1], layers[0]),
        output_dim=layers[1],
        return_sequences=True))
    model.add(Dropout(0.2))

    model.add(LSTM(
        layers[2],
        return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Dense(
        output_dim=layers[3]))
    model.add(Activation("linear"))

    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("> Compilation Time : ", time.time() - start)
    return model

def predict_point_by_point(model, data):
    #Predict each timestep given the last sequence of true data, in effect only predicting 1 step ahead each time
    predicted = model.predict(data)
    predicted = np.reshape(predicted, (predicted.size,))
    return predicted

def predict_sequence_full(model, data, window_size):
    #Shift the window by 1 new prediction each time, re-run predictions on new window
    curr_frame = data[0]
    predicted = []
    for i in range(len(data)):
        predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
        curr_frame = curr_frame[1:]
        curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
    return predicted

def predict_sequences_multiple(model, data, window_size, prediction_len):
    #Predict sequence of 50 steps before shifting prediction run forward by 50 steps
    prediction_seqs = []
    for i in range(int(len(data)/prediction_len)):
        curr_frame = data[i*prediction_len]
        predicted = []
        for j in range(prediction_len):
            predicted.append(model.predict(curr_frame[newaxis,:,:])[0,0])
            curr_frame = curr_frame[1:]
            curr_frame = np.insert(curr_frame, [window_size-1], predicted[-1], axis=0)
        prediction_seqs.append(predicted)
    return prediction_seqs

Addendum:
At nuric suggestion I modified the model as following:
def build_model(layers):
    model = Sequential()
    model.add(LSTM(input_shape=(layers[1], layers[0]), output_dim=layers[1], return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(layers[2], return_sequences=False))
    model.add(Dropout(0.2))
    model.add(Dense(output_dim=layers[3]))
    model.add(Activation("linear"))
    model.add(Dense(64, input_dim=50, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(1))
    start = time.time()
    model.compile(loss="mse", optimizer="rmsprop")
    print("> Compilation Time : ", time.time() - start)
    return model

Still a bit lost on this one...

A: Even though you normalise the input, you don't normalise the output. The LSTM by default has a tanh output which means you will have a limited feature space, ie the dense layer won't be able to regress to large numbers.
You have a fixed length numerical input (50,), directly pass that to Dense layers with relu activation and will perform better on regression tasks, something simple like:
model = Sequential()
model.add(Dense(64, input_dim=50, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(1))

For regression it is also preferable to use l2 regularizers instead of Dropout because you are not really feature extracting for classification etc.


Q: angular2 / RxJS - how to retry from inside subscribe() this is my code:
this._api.getCompanies().subscribe(
    res => this.companies = JSON.parse(res),
    exception => {if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() } }
)

in case an exception happened, it will be sent to a function in the API then return true if the problem is fixed (like token refreshed for example) and it just needs to retry again after its fixed
I could not figure out how to make it retry.

A: In your .getCompanies() call right after the .map add a .retryWhen:
.retryWhen((errors) => {
    return errors.scan((errorCount, err) => errorCount + 1, 0)
                 .takeWhile((errorCount) => errorCount < 2);
});

In this example, the observable completes after 2 failures (errorCount < 2).

A: You mean something like this?
this._api.getCompanies().subscribe(this.updateCompanies.bind(this))

updateCompanies(companies, exception) {
    companies => this.companies = JSON.parse(companies),
    exception => {
        if(this._api.responseErrorProcess(exception)) {
            // in case this retured TRUE then I need to retry()
            this.updateCompanies(companies, exception)
        }
    }
}


Q: File and directory permissions I am learning umask command , and I get few questions. So:
1.For files and directories default permissions is 666 and 777
how can I config the default permission, specifically where is configuration file for default permissions.
2 The umask command is reduce  permissions, how to ADD permissions ?

A: The umask takes away - correct.  But it takes away from everyone having access to everything.
user@darkstar ~ $ umask
0022
user@darkstar ~ $ touch umasktestfile
user@darkstar ~ $ mkdir umasktestdir
user@darkstar ~ $ umask 0000
user@darkstar ~ $ umask
0000
user@darkstar ~ $ touch umasktestfile2
user@darkstar ~ $ mkdir umasktestdir2
user@darkstar ~ $ ls -ld umasktest*
drwxr-xr-x 2 user user 4096 Dec 26 19:07 umasktestdir
drwxrwxrwx 2 user user 4096 Dec 26 19:08 umasktestdir2
-rw-r--r-- 1 user user    0 Dec 26 19:07 umasktestfile
-rw-rw-rw- 1 user user    0 Dec 26 19:08 umasktestfile2
user@darkstar ~ $ umask 0022
user@darkstar ~ $ umask
0022
user@darkstar ~ $

A: There is no global configuration file for file permissions. The permissions are determined by the mode parameter to the system calls creating the file or directory, and it is up to the application what to put there. Before the file or directory is created, the mode is modified by the process's umask.


Q: generic casting from object-boxed type Why does this work:
decimal dec = new Decimal(33);
double dd = (double) dec;
Console.WriteLine(dd);

But not this:
decimal dec = new Decimal(33);
object o = (object)dec;
double dd = (double) o;
Console.WriteLine(dd);

The second example throws:

System.InvalidCastException: Specified cast is not valid.

This question comes from a situation where I have a generic method
public T GetValue(string q)

That gets values from a datasource. The types of these values are unknown, but the method assumes that it can cast the value to T. Sometimes the value will be object{decimal} and T will be double, in which case the InvalidCastException will be thrown. But in principle this should not be an issue since the value is a decimal (albeit boxed by an object) which can be cast to double.
How do I handle this generically?

A: The latter doesn't work because the decimal value is boxed into an object. That means to get the value back you have to unbox first using the same syntax of casting, so you have to do it in 2 steps like this:
double dd = (double) (decimal) o;

Note that the first (decimal) is unboxing, the (double) is casting.

A: This can be done with Convert.ChangeType:
class Program
{
    static void Main(string[] args)
    {
        decimal dec = new Decimal(33);
        object o = (object)dec;
        double dd = GetValue<double>(o);
        Console.WriteLine(dd);
    }

    static T GetValue<T>(object val)
    {
        return (T)Convert.ChangeType(val, typeof(T));
    }
}

The reason your code doesn't work has been well explained by others on this post.

A: You can only cast boxed value types back to the exact type that was boxed in. It doesn't matter if there is an implicit or explicit conversion from the boxed type to the one you are casting to -- you still have to cast to the boxed type (in order to unbox) and then take it from there.
In the example, this means two consecutive casts:
double dd = (double) (decimal) o;

Or, using the Convert methods:
double dd = Convert.ToDouble(o);

Of course this won't do for your real use case because you cannot immediately go from a generic type parameter to ToDouble. But as long as the target type is IConvertible, you can do this:
double dd = (double)Convert.ChangeType(o, typeof(double));

where the generic type parameter T can be substituted for double.


Q: extracting words from a sentence using indexOf and substring and storing them in an array in java Here is what I have so far for this part of my program;
String text = JOptionPane.showInputDialog("enter a sentence");

String newWord = "";
char space = '_';
int count = 0;

for(int i = 0; i < text.length(); i++)
{
  int found = text.indexOf(space, i);

  int start = found + 1; // start location of substring after a space
  int end = text.indexOf(space, start); // end of word
  count = end + 1;
}
  while(count < text.length())
  {

newWord[count] = text.substring(start, end);

  count++;

}

System.out.println(newWord[count]);

A: to split a sentence, use String's .split() method
String [] splitter = text.split(" ");

this will break the sentence based on spaces. Then you can do whatever you need to the array

A: String text = JOptionPane.showInputDialog("Enter a sentence");
int count = 0;
char space = ' ';

int index = 0;
do
{
   ++ count;
   ++ index;
   index = text.indexOf(space, index);
}
while (index != -1);

    String[] array = new String[count];
    index = 0;
    int endIndex = 0;
    for(int i = 0; i < count; i++)
    {
      endIndex = text.indexOf(space, index);

      if(endIndex == -1)
     {
       array[i] = text.substring(index);
     }else{
       array[i] = text.substring(index, endIndex);
     }

     index = endIndex + 1;
    }
    for(String s : array)
    {
      System.out.println(s);
    }


Q: IBM MQ transmission queue exclusive lock I have a WebSphere MQ Queue Manager with transmission queue defined and I'm using API to get some information about the queue. When trying to inquire the queue (using .NET interface, but I believe this is not important here), I always receive an exception with reason 2042: MQRC_OBJECT_IN_USE - according to the documentation, this means that there's an exclusive lock at the queue. By some further investigation I can see that the process holding the lock is runmqchl - part of MQ Server.

*

*Is the exclusive lock typical for transmission queues?

*Or this means that there's something wrong with the queue or the transmission?

*Even better, maybe there is a way to do some inquiries (read-only) to that locked queue (i.e. to get its depth or browse the messages) using API?

A: The SDR or SVR channel will always open the transmission queue for exclusive use.  If the .Net client is getting an error because of this then it is asking for input rights as well as inquire.  You can verify this by using WMQ Explorer to inquire on the queue and you will see that it has no problem getting queue attributes, depths, etc.  So open for inquire but not browse or get and you should be fine.


Q: React change state of one component from another I need to change the state of my sidebar component from another component.
My code:
Sidebar.tsx >
const SideBar: React.FC = () => {

    const [open, setOpen] = useState<boolean>(false);

    function switchSidebar() {
       setOpen(!open);
    }

    const bar = useMemo(() => <Menu open={open} sidebar={true} />, [open])

        return (
           <>
              <SidebarButton />
              { bar }
           </>

}

SidebarButton.tsx >
export const SidebarButton:React.FC = () => {
  return(
        <svg xmlns="http://www.w3.org/2000/svg" onMouseDown={/* ? */}>
            <path stroke="currentColor" strokeWidth={3} d="M0 1.5h28M0 10.5h28M8 19.5h20"/>
        </svg>
 )
}

Menu.tsx >
const Menu: React.FC = ({sidebar, open, data = HeaderData}) => {
       return (
         <ul>
            <SidebarButton />
            { /* Other things to render */ }
         </ul>
       )
}

How you can see I need a method to change the state that is contained in Sidebar from SidebarButton.

A: You can pass the setOpen function as a prop to the SidebarButton component and then simply call the setOpen function to change the value.
<SidebarButton setOpen={setOpen} />

If you would like to also call it from the menu component then you may need to move the declaration of open to a higher component that is common between Sidebar and Menu since props can only be passed downwards.


Q: How to animate (resize) a Linear layout loaded into listview on item click in android Hi i need to animate (resize height and width) a linear layout added into a Listview through adapter in android.

A: I'm not entirely sure as to what you want to do here. If im correct what your looking for is an expanded listview. You can achieve this using the following library it takes two layouts one for the listview item and the second the layout which needs to be expanded when the listview item is clicked
https://github.com/tjerkw/Android-SlideExpandableListView


Q: How to translate whole words into morse-code with a dictionary? I'm writing a program that translates normal text to Morse code and I've written the core program that translates single letters to Morse code I still can't figure out how to translate whole words and text.
more clarification:
 i can translate single letters but i cant translate whole words
Here's the code:
from tkinter import *

#key down function
def click():
    entered_text=textentry.get() #this wil collect the text from the text entry box
    outpout.delete(0.0, END)
    try:
        definition = my_dictionary[entered_text]
    except:
        definition= "sorry an error occured"
    outpout.insert(END, definition)

#### main
window = Tk()
window.title("THIS IS A SIMPLE TITLE")
window.configure(background="yellow")

#create label
Label (window,text="Enter a text here.", bg="YELLOW", fg="BLACK", font="arial 30 bold italic" ) .grid(row=1, column=0, sticky=W)

#create a text entry box
textentry= Entry(window, width=20, bg="WHITE")
textentry.grid(row=2, column=0, sticky=W)

#add a submit button
Button(window, text="SUBMIT", width=6, command=click) .grid(row=3 ,column=0, sticky=W)

#create another label
Label (window,text="THE ENCRYPTED TEXT IS:", bg="YELLOW", fg="BLACK", font="arial 10 bold" ) .grid(row=4, column=0, sticky=W)

#create a text box
outpout = Text(window, width=75, height=6, wrap=WORD, bg="WHITE")
outpout.grid(row=5, column=0, columnspan=2, sticky=W)

#the dictionary
my_dictionary = {
    "A" : ".-",
    "B" : "-...",
    "C" : "-.-.",
    "D" : "-..",
    "E" : ".",
    "F" : "..-.",
    "G" : "--.",
    "H" : "....",
    "I" : "..",
    "J" : ".---",
    "K" : "-.-",
    "L" : ".-..",
    "M" : "--",
    "N" : "-.",
    "O" : "---",
    "P" : ".--.",
    "Q" : "--.-",
    "R" : ".-.",
    "S" : "...",
    "T" : "-",
    "U" : "..-",
    "V" : "...-",
    "W" : ".--",
    "X" : "-..-",
    "Y" : "-.--",
    "Z" : "--..",
    " " : "/"
    }
#run the main loop
window.mainloop()

A: I think the issue is that you are trying to use the entire text as the key to the dictionary. So, if the text "A" is entered into the text input then it works as "A" is a key in my_dictionary. If the text "AS" is entered into the text box, this will fail as there is no key "AS" in my_dictionary.
What you will want to do, therefore, is loop over each of the characters in the entered string and add the Morse value of that letter to your definition string. You will also want to make sure that the letter is uppercase (unless it is guaranteed that the input will be upper case). This is done using the string .upper() method in the following example. Something like the following should do what you want.
definition = str()  # Create a blank string to add the Morse code to

# Go through each letter and add the Morse definition of the letter to definition
for letter in entered_text:
    definition += my_dict[letter.upper()]  # The upper makes sure the letter is a capital so that there will be a match in my_dict


Q: Does Flask trim  items? Within Flask and using Jinja2, I'm calling a datalist but for some reason any option with a space is trimmed so "tomato sauce" becomes "tomato". Is this something Flask is doing or have I messed up the templating?
<!-- HOMEPAGE -->
<form type="text" id="homeForm" class="centered" method="post" onsubmit="return false;">
        {{ form.hidden_tag() }}
        <input type="text" id="homeInput" autocomplete=off list="topps" placeholder="Input here">
        <datalist id="topps">
            {% for top in topps %}
            <option value={{ top }}>
            {% endfor %}
        </datalist>
        <button type="submit" id="homeSubmit">Submit</button>
</form>

# ROUTES.PY #
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    topps = ["tomato sauce", "chilli flakes","something else"]
    return render_template('index.html', title='Home', form=form, topps=topps)

A: Your problem is here:
<option value={{ top }}>

add quotes outside of {{top}}
<option value="{{ top }}" />


Q: ProxySQL between master/slave replication on flaky connection I have two MySQL servers with master/slave replication between them. The connection between them is ADSL. It is not reliable at all. I decided to add another ADSL connection from another ISP with its own IP address.
The problem is that when when one ADSL connection goes down, the other one is useless because the slave is using the first connection's IP address which is down now.
I want to know if is it possible to put a proxysql node between and give its IP to the slave.
Is it possible for proxysql to do fail-over connection handling for the same node? Proxysql must choose the second IP address when the first one is not available.

A: ADSL is generally not a fixed IP, which means that the server does not recognize it.
As I understand it, you want to balance the load.
Analyzing your doubt. I leave my case study.
1 - How each server is separate.
Place a fixed IPv4 from there, create a fixed DNS and point to the corresponding fixed IP. Also place a domain and add the DNS configuration. If you have IPv6 (AAA), add it for even more answers. And prioritize cryptography.
If you need a secure proxy, use CloudFlaure to manage your settings. It helps the configuration become more practical.
2 - Pointing the DNS to fixed IP, create NS for both servers.
example: ns1.server.com //// ns2.server.com
I recommend creating 4 NS for each server.
3 - The same procedure is used on the slave. but do not use ns, switch to another silga, for example: (tl1.server.com).
This facilitates orientation.
So, for each server.
An IPv4
An Ipv6
Four NS
Two DNS
Therefore, when the first server goes down, the other server takes over. Be on IPV4 or IPV6. And the DNS and the DNS are congested or are not recognized for some reason, promptly the other takes over. So, without loss.
If there is a problem with your hosting, create IP or domains. Due to fees.
There are some free ones and, that work 90%, cloudflare itself has this service.
If I was able to understand your demand, I recommend the services later.
It works for me.
Submit questions and follow the case.

A: My Idea.
You use dynamic dns to know always, which IP Address is valid, to reach the site with the spotty connection.
A fail over Router like the one in the comment, has the advantage, that it always knows which connection is the better one, and actualizes the dyndns serverip.
For the rest, i would see that both sites build a vpn. Most router can be VPN server as also client and with the dynamic Ip, establishing the connection is no problems, as long any connection actually work. For your replication it is the same network, with a fixed ip.
If you have already a ssl server,all is the same, only you need to bridge the port, so that packet will enter the network.
For all that, you should get some help, because the are many points that can be tweaked, to fit the situation on side.


Q: Aframe + Meteor - Add a conditional custom component to an entity <a-gltf-model id='playerone' {{#if myplayer playerone}}entitymove{{/if}} src="#myMixBun"> </a-gltf-model>

Using Aframe in Meteor, I want to add the custom component “entitymove” if the value of myplayer is “playerone”.
The value of {{myplayer}} is “playerone” in main.html, so the variable is set correctly. But I get the Meteor error “A template tag of type BLOCKOPEN is not allowed here”.
If “entitymove” was a “class”, for instance,  I think I could solve this with the following:
<a-gltf-model id='playerone' class={{#if myplayer playerone}}entitymove{{/if}}  src="#myMixBun"> </a-gltf-model>

But since it’s a component, I am at a loss as to how to fix the syntax.

A: Assuming that this uses Meteor-Blaze templates you need to include the conditionals for DOM element attributes inside quotes/double quotes:
<a-gltf-model id='playerone' class="{{#if myplayer playerone}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

Readings:
http://blazejs.org/guide/spacebars.html

A: SOLVED
This is my original, which doesn’t work.
In main.js:
player = "player not active";

Template.hello.helpers(
  counter() {......

// if player one
player = "playerone";
// if player two
player = "playertwo";

return { myplayer: player };
  }

In main.html:
// This statement works
{{counter.myplayer}}....

<a-gltf-model id='playerone' class="{{#if counter.myplayer playerone}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

<a-gltf-model id='playertwo' class="{{#if counter.myplayer playertwo}}entitymove{{/if}}"  src="#myMixBun"> </a-gltf-model>

I think there are 2 problems with this:
1) spacebars doesn’t seem to like the if statement with a comparison?:
{{#if counter.myplayer playertwo}}

It only allows true or false if statements?, such as:
{{#if counter.player1}}

2) My aframe custom component isn’t actually a class, so I can’t put the meteor #if statement inside the  entity.
I changed the code to the following and it now works:
Changed main.js to:
playerone ="";
playertwo ="";

// if player one
     playerone = "true";
    playertwo = "";

// if player two
     playerone = "";
    playertwo = "true";
 return { player1: playerone, player2: playertwo};
  }

Changed main.html to:
// These statements work
{{#if counter.player1}}player1 is true{{/if}}
{{#if counter.player2}}player2 is true{{/if}}....

{{#if counter.player1}}
 <a-gltf-model id='playerone' entitymove   src="#myMixBun" ></a-gltf-model>
 <a-gltf-model id='playertwo'   src="#myMixBun" ></a-gltf-model>
 {{/if}}

  {{#if counter.player2}}
 <a-gltf-model id='playerone'  src="#myMixBun" ></a-gltf-model>
 <a-gltf-model id='playertwo' entitymove   src="#myMixBun" ></a-gltf-model>
 {{/if}}


Q: count frequency group by pandas I am trying to add a new column to a data below, in which columns Algorithm1,2 & 3 are derived from Text column. I want to count each element in the 3 columns and create new column to only have elements which have count > 1
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX']})

This is how the final output should look like with columns values AB, AX & AAX as they have frequency > 1
df2 = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX'],
                   'Majority': ['AB','AX','AAX']})

A: IIUC count values in Algorithm columns and filter if greater like 1:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['BX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAX']})
s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AB     3
AX     2
AAX    2
AAB    1
BX     1
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX         BX         AX   AB
1  AAABBX         AB        AAX         AB   AX
2  AAABBX        AAB         AB        AAX  AAX

If number of values is greater like length of DataFrame:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AAB'],
                     'Algorithm2' : ['AAX','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AAB']})

s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AB     3
AAB    2
AX     2
AAX    2
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX        AAX         AX   AB
1  AAABBX         AB        AAX         AB  AAB
2  AAABBX        AAB         AB        AAB   AX

If number of values is less like length of DataFrame:
df = pd.DataFrame({'T':['AAABBX','AAABBX','AAABBX'],
                     'Algorithm1': ['AX','AB','AX'],
                     'Algorithm2' : ['AA','AAX','AB'],
                     'Algorithm3' : ['AX','AB','AX']})

s = df.filter(like='Algorithm').stack().value_counts()
m = s.gt(1)
print (s)
AX     4
AB     3
AAX    1
AA     1
dtype: int64

df['new'] = pd.Series(s.index[m])[:m.sum()]
print (df)
        T Algorithm1 Algorithm2 Algorithm3  new
0  AAABBX         AX         AA         AX   AX
1  AAABBX         AB        AAX         AB   AB
2  AAABBX         AX         AB         AX  NaN


Q: Making a table of contents for a book I'd like to know how to create a table of contents in LaTeX. For example, if I were to write a book, I would want something like this
Contents
    Chapter 1
      1.1 Real Analysis .............. 1
      1.2 Role of LUB Axiom........... 3

How do I create this? I'd like to know.

A: A table of contents (ToC) is produced by inserting \tableofcontents at the appropriate place in your document.
\documentclass{book}

\begin{document}

\tableofcontents

\chapter{(Chapter Name)}

\section{Real Analysis}

\section{Role of LUB Axiom}

\end{document}

Note that you need at least two LaTeX runs to produce the ToC (LaTeX collects the data for the ToC in the first run and typesets it in the second run). If the ToC itself comprises several pages, a third LaTeX run may be necessary to get the ToC's page references right.

A: There's just one command necessary: \tableofcontents, as already mentioned by lockstep. It takes the entries from the sectioning commands \part, \chapter, \section etc.
Additionally, you could use the optional argument of a sectioning command to get a different, shorter entry for the table of contents, for example:
\section[short entry]{long title}

This is useful if you have very long titles in the body text but need shorter list entries in the table of contents.
There are package for further customization of the contents list, if desired, for example:

*

*tocloft

*titletoc

*tocbasic (part of KOMA-script)

*tocstyle (part of KOMA-script)

A very similar index could be created for your figures and tables. The commands are \listoffigures and \listoftables. I mention it because it's the same concept, here the content entries come from the \caption commands.


Q: Limiting points of coaxial system of spheres Find the limiting points of coaxial system of spheres determined by the spheres $x^2+y^2+z^2+3x-3y+6=0$ and $x^2+y^2+z^2-6y+6z+6=0$. what I observed is that the first equation does not represent a sphere(because radius is imaginary). Can limiting points found for imaginary spheres. Can any one help?