text:
Q: Dynamic UI Progress Updates using Interface + ExecutorService Issue So I have a music application. I am trying to update the UI with the progress of the media player (like current time, current song, album cover) everytime the song changes. I found that using interfaces was a awesome magical way of communication between activity and fragments so I implemented an interface in my MusicManger class. My code will show what and how did it.
Two problems
1) Commented look below, ExecutorService seems to stop after one loop. No Errors in catch block (this is why I tagged with java)
2) Commented please look, All the System.out methods print but the UI doesn't update. I do believe I called the method from mainThread so it should update.
I'll show code in logical order will add titles in bold before code segment to tell you basic idea of code.
Passing UI references from fragment to MusicManager class, code below in Fragment class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_songlist, container, false);

    // Set the adapter

    TextView musicManagerSongName, musicManagerCurrent, musicManagerTotal;
    ProgressBar musicManagerProgress;
    ImageView musicManagerImageView;
    mListView = (AbsListView) view.findViewById(R.id.slist);
    musicManagerSongName = (TextView)view.findViewById(R.id.textView12);
    musicManagerCurrent = (TextView)view.findViewById(R.id.textView10);
    musicManagerTotal = (TextView)view.findViewById(R.id.textView11);
    musicManagerProgress = (ProgressBar)view.findViewById(R.id.progressBar);
    musicManagerImageView = (ImageView)view.findViewById(R.id.imageView2);

    MainActivity.mediaPlayer.passUIReferences(musicManagerSongName, musicManagerCurrent, musicManagerTotal, musicManagerProgress, musicManagerImageView, view);

// line above is a method within MusicManager that takes the references will show code next!

    ImageButton playbutton = (ImageButton)view.findViewById(R.id.playbuttonbar);
    ImageButton nextButton = (ImageButton)view.findViewById(R.id.nextbuttonbar);
    ImageButton backButton = (ImageButton)view.findViewById(R.id.backbuttonbar);
    ImageButton toggleButton = (ImageButton)view.findViewById(R.id.shufflebuttonbar);
    ImageButton pausebutton = (ImageButton)view.findViewById(R.id.pausebuttonbar);
    playbutton.setBackgroundResource(R.drawable.playbuttonbar);
    playbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                MainActivity.mediaPlayer.stateChange(1);
            }catch(Exception e) {

            }
        }
    });
    backButton.setBackgroundResource(R.drawable.backbutton1);
    nextButton.setBackgroundResource(R.drawable.nextbutton1);
    toggleButton.setBackgroundResource(R.drawable.shufflebuttonselected);
    pausebutton.setBackgroundResource(R.drawable.pausebutton1);
    pausebutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                MainActivity.mediaPlayer.stateChange(0);
            } catch (Exception e){

            }
        }
    });
    mListView.setAdapter(mAdapter);
    ((MainActivity) mListener).restoreActionBar();

    return view;
}

As Commended above the code that is located in MusicManager class that takes references and stores them. Also shows interface implementation with MusicManager class. And the Executor service
public void passUIReferences(View... views) {
    this.uiElements = views;
}

 private ExecutorService executorService = Executors.newSingleThreadExecutor();
private MediaplayerUpdateInterface uiUpdateInterface;

public MediaPlayerManager(MediaplayerUpdateInterface inter) {
    this.player = new MediaPlayer();
    this.uiUpdateInterface = inter;

// The below line starts the single thread while loop for excutorservice and only loops and prints "this" once after I start one song then it never loops again
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            while(true) {
                if (player.isPlaying() && uiElements != null) {
                    System.out.println("this");
                    uiUpdateInterface.updateUI(uiElements, 0);
                }
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

public interface MediaplayerUpdateInterface {
    public void updateUI(View[] views, int type);
}

Finally some code from MainActivity class that actually is suppose to update the UI note that both println's work as expected but only once as stated above because of the executorservice issue
  public static MediaPlayerManager mediaPlayer = new MediaPlayerManager(new MediaPlayerManager.MediaplayerUpdateInterface() {
    @Override
    public void updateUI(View[] views, int type) {
        System.out.println("check1 " + type);
        updateMediaplayerViews(views, type);
    }
});

private static void updateMediaplayerViews(View[] views, int type)
{
    switch(type) {
        case 0:
            System.out.println("that?");
            ((TextView)views[0]).setText(mediaPlayer.getCurrentSongInfo().getName().length() > 22? mediaPlayer.getCurrentSongInfo().getName().substring(0, 19)+"..." : mediaPlayer.getCurrentSongInfo().getName());
            break;
    }
    views[views.length - 1].invalidate();
}

The view array is shown perviously! Also the last view in the array is shown as the main view for songlist fragment.
I am sorry for all the code I've tried to debug it as you can see from my println's there is just something I am unaware of going on here.

A: Ok so there was an error that I needed to catch to see within the following code:
private static void updateMediaplayerViews(View[] views, int type)
{
switch(type) {
    case 0:
        System.out.println("that?");
        ((TextView)views[0]).setText(mediaPlayer.getCurrentSongInfo().getName().length() > 22? mediaPlayer.getCurrentSongInfo().getName().substring(0, 19)+"..." : mediaPlayer.getCurrentSongInfo().getName());
        break;
}
views[views.length - 1].invalidate();
}

The issue is I was trying to change the view from a different thread then the one which created it. Solving it was pretty long and painful but basically I made it nonstactic used more interfaces then used the famous
Mainactivity.runOnUiThread(new Runnable(....));


text: Q: Sequence of continuous functions convergent to continuous by each variable function in $\mathbb{R}^2$ Solving a problem from a book, in the hints section I encountered a statement, which I cannot prove. Let $\bar{U}$ be a closed circle in $\mathbb{R}^2$ and $f:\bar{U}\to\mathbb{R}$ a function, continuous with respect to each of the two variables (as a one-variable function). Prove, that there exists a sequence of continuous functions $\{f_n:\bar{U}\to\mathbb{R},n\in\mathbb{N}\}$, such that $f_n$ converges to $f$ pointwise, i.e. $\forall(x_0,y_0)\in\bar{U}, \lim\limits_{n\to\infty} f_n(x_0,y_0)=f(x_0,y_0)$. Please, help me to prove this statement.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to organise via Custom Fields on Category Page I have a custom field named: eventdate
The posts are all in the standard post type.
I want to order by this field ascending.
I have tried over 15 different solutions but no joy .
Every post simply gets turned into a list of all posts.
I have tried all solutions both before and after the following.
if(have_posts()){
 while (have_posts()) : the_post();

Please help, I have been trying to sort this for at least 14 hours.

A: you can use query_posts to sort the post by you custom field,
Add this before you loop
query_posts( $query_string . 'meta_key=eventdate&order=ASC&orderby=meta_value');


text:
Q: Maven not running tests in parallel if value is set to tests I have api test, which runs with maven and testng. But while running it on parallel it doesnot run when its set to tests and I have multiple @Test.
 <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M5</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>src/test/java/suite.xml</suiteXmlFile>
          </suiteXmlFiles>
          <systemProperties>
            <property>
              <name>env</name>
            </property>
          </systemProperties>
          <properties>
            <property>
              <name>parallel</name>
              <value>tests</value>
            </property>
            <property>
              <name>dataproviderthreadcount</name>
              <value>10</value>
            </property>
            <property>
              <name>threadCount</name>
              <value>10</value>
            </property>
          </properties>
        </configuration>
      </plugin>

A: parallel=tests in testng suite parlance do not translate to @Test methods.  You need to set parallel=methods for all @Test annotated methods to run in parallel.


text:
Q: C++ Functional Composition - Compose Methods Optimisation I have written my own compose method which works fine for PODs how can optimise this for handling user defined types which are expensive to copy?
#include <iostream>

template<typename T, typename U, typename V>
std::function<V(T&&)> compose(std::function<V(U)> f, std::function<U(T)> g)
{
    std::function<V(T&&)> result = [&](T&& value){
        return f(g(value));
    };
    return result;
}

int main(int argc, const char * argv[])
{

    std::function<int(int)> f = [](int v){ return v + 1;};
    std::function<int(int)> g = [](int v){ return v + 2;};

    std::function<int(int)> h = compose(f, g);

    std::cout << "compose(f,g): " << (h(5)) << std::endl;

    return 0;
}

Blair

A: the answer is boost::call_traits<T>...


text:
Q: javascript, including variables from loop inside google functions So you have probably seen something similar alot, where someone has a problem with using the "i" variable in a functions inside a for loop. Now that can easily be fixed with:
(function(){
    return function() {
        //something
    }
})(i);

But, how do I do this in my scenario?
GMap.prototype.drawDirection = function (directionsRenderer, directionsService, headMarker, tailMarkers, callback) {
var request;
var array = [];
var count = 0;
for (var i = 0; i < tailMarkers.length; i++) {
    count = i;

    request = {
        origin: headMarker.getPosition(),
        destination: tailMarkers[i].getPosition(),
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(response);
            console.log(i + " " + count);
            callback(response.routes[0].legs[0].distance.value, i, tailMarkers.length - 1);
        } else {
            alert('Error: ' + status);
        }
    });
    }
};

To be more accurate, it's about the directionsService object:
directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsRenderer.setDirections(response);
        console.log(i + " " + count);
        callback(response.routes[0].legs[0].distance.value, i, tailMarkers.length - 1);
    } else {
        alert('Error: ' + status);
    }
});

Now, I don't want to use JFiddle since it would be alot to write, so I'm just going to link to my site where I'm trying this.
http://stud.aitel.hist.no/~andersfy/html5.proj/
If you look at the checkbox in the bottom right corner, where it says "vis min posisjon" you just need to click on that, and you'll see the problem.
The code is in the file galled GMap.js at line 134 to 142.
I hope I'm giving you enough information!

A: You should not create functions inside of for loops for this very reason.
Your problem is in this closure, that shares the variable  i:
function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsRenderer.setDirections(response);
        console.log(i + " " + count);
        callback(response.routes[0].legs[0].distance.value, i, tailMarkers.length - 1);
    } else {
        alert('Error: ' + status);
    }
}

I would rewrite that function to not depend on i, but if you need i then
/*before your for loop */
function createRouter(i){
    return function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(response);
            console.log(i + " " + count);
            callback(response.routes[0].legs[0].distance.value, i, tailMarkers.length - 1);
        } else {
            alert('Error: ' + status);
        }
    }
};

/* in your for loop */
directionsService.route(request, createRouter(i));


text:
Q: Use Model Scope in Laravel Validation Rule I have a rule like so:
Rule::exists('tokens', 'key')
    ->where(function ($q) {
        $q->where('state', 'unused');
    })

But I'm trying to get access to the actual Token model scopes so I can just just do ->unused() and not repeat my query.
Rule::exists(\App\Models\Token::class, 'key')
    ->where(function ($q) {
        $q->unused();
    })

It appears to get a query builder, but not from the Token model.
I've tried some variation with passing the Token model in as the argument instead of the tokens table name but it just throws errors for call to undefined method.
Is there anyway to do this?

A: As you've already noticed; you've access to the query builder instead of the model. What you could do is new up a model and just use the scope directly.
use App\Models\Token;

Rule::exists('tokens', 'key')
    ->where(function ($q) {
        (new Token)->scopeUnused($q);
    });


text:
Q: pass values from the view to the controller ruby on rails This is my controller:
def addcar
    @car = Car.new(params[:car])
    render :action => "list"
end

this is my view:
<%(@allcars).each do |cell|%>

<%= link_to cell.to_s, :controller => "car", :action => "addcar", :car => cell.to_s %>

<%end %>

In the link_to statement I want to pass cell.to_s to the controller. How can I do that please? The cell.to_s is just a string but I want it to be the name of the car object (car.Name)

A: Car.new(params[:car]) expects params[:car] to be a Hash ({:foo => "bar"}). So change your code:
<% @allcars.each do |cell| %>

    <%= link_to cell.to_s,
          :controller => "car",
          :action => "addcar",
          :car => { :name => cell.to_s } %>

<% end %>


text:
Q: Issues Saving Objects to Firebase Realtime Database Working on saving user objects to my Firebase Database, but cannot seem to save any complex custom objects.
protected DatabaseReference userRef =  FirebaseDatabase.getInstance().getReference().child("users");
/.../
User user = new User();
User.setGroups(new ArrayList<String>());
User.setCurrentlyReading(new ArrayList<String>());
userRef.child(userId).setValue(user);

I can save data when I swap out the user in setValue with a string, so I know at least my connection works and I can at least write something to the database.
Any help would be much appreciated.
Update: Adding details on user object
@IgnoreExtraProperties
public class User {

    private List<String> groups;
    private List<String> currentlyReading;

    public User(){}

    public List<String> getGroups() {
        return books;
    }

    public void setGroups(List<String> groups) {
        this.groups = groups;
    }

    public List<String> getCurrentlyReading() {
        return currentlyReading;
    }

    public void setCurrentlyReading(List<String> currentlyReading) {
        this.currentlyReading = currentlyReading;
    }

}

A: Ah, finally found the issue. Firebase doesn't like empty objects. Added the userId to the user object and that finally saved it into my database.


text:
Q: Opencv 4.3.0 installation Windows Error: vs_version.rc : No such file or directory? I'll install Opencv 4.3.0. But I'm getting the errors.
Opencv Cmake Flags:
cmake -D OPENCV_ENABLE_ALLOCATOR_STATS=OFF -D OPENCV_ALLOCATOR_STATS_COUNTER_TYPE = int64_t -D WITH_MFMS=OFF  -D WITH_IPP=OFF -D WITH_TBB=OFF  -D ENABLE_PRECOMPILED_HEADERS=OFF -D WITH_QT=ON ..
Error: vs_version.rc : No such file or directory.
How can i solve the problem ?
Thanks,

A: according to the bug reported in the official repository here: you need to set this param
-DOPENCV_ALLOCATOR_STATS_COUNTER_TYPE=int64_t


text:
Q: Why does $\frac{V_n}{A_n}$ represent the concentration of volume around the boundary? I read this answer about the volume of a ball in $\mathbb{R}^n$ being concentrated around the boundary.
I don't understand why:

*

*$$\frac{V_n}{A_n}$$ is a measure of concentration around the boundary?

*$$\frac{V_n}{V_{n-1}}$$ is a measure of concentration around the equator?

$V_n$ and $A_n$ denotes the volume and surface area of a (unit) ball in $\mathbb{R}^n$. We know that $A_n = nV_n$.
Also what exactly is the difference between the equator and the boundary in this context? Is there a diagram that can help me?
Thanks a lot!

A: Intuitively, A$_n$ * r  should be equal to volume of the shell V$_n$(1) - V$_n$(1-r).
Here V$_n$(x) stands for volume of n-dimensional ball with radius x; also, V$_n$ is just V$_n$(1).
In words: area of base * height = volume.
The strange thing here is that one can take small r (= 1/n) to get almost whole unit ball volume, hence the claim that volume is concentrated around surface.
Similarly, one can cut V$_n$ around equator (to get "base" with area V$_{n-1}$) and ask about height of a cylinder with base V$_{n-1}$ so that its volume is equal to volume of V$_n$.
The answer is 1/sqrt(n), i.e. quantity much smaller than radius of the ball (=1).
These things entered modern (graduate level) analysis and probability under the name
"concentration of measure" in the last few decades.

A: I'll try to answer the question in your last paragraph without drawing pictures.
The surface of a disk is a circle; the surface of a ball is a sphere. An $n$-dimensional ball of radius $R$ (centered at the origin) is the set $\{(x_1,x_2,\ldots,x_n)\mid x_1^2+x_2^2+\ldots+x_n^2\le R^2\}$; its surface is the set $\{(x_1,x_2,\ldots,x_n)\mid x_1^2+x_2^2+\ldots+x_n^2=R^2\}$.
In the context of the answer you link to, an equator of a disk is a line segment that cuts it in half (a diameter). An equator of a ball is the cross section you get when you slice the ball in half with a plane. This cross section is a disk—a disk of largest diameter that fits inside the ball. For an $n$-dimensional ball, an equator is the cross section (of dimension $n-1$) you get when you slice the ball into two equal halves. This cross section is a ball of dimension $n-1$ and radius equal to that of the original ball.
Equivalently, an equator is what you get when you do an orthogonal projection of the $n$-dimensional ball onto an $(n-1)$-dimensional hyperplane through its center. An easy way to produce an example is to set one coordinate equal to zero. An equator of the disk $x^2+y^2\le R^2$ is the line segment $x^2\le R^2$ (by setting $y=0$); an equator of the ball $x^2+y^2+z^2\le R^2$ is the disk $x^2+y^2\le R^2$ (by setting $z=0$).
Notice that the equator of a ball is also a ball (of dimension one less). The ratio $V_n/V_{n-1}$ is a length. It tells you how a tall a "cylinder" with an $(n-1)$-dimensional ball as its base would have to be to have the same volume as an $n$-dimensional ball of the same radius. So $V_2/V_1$ is the height a rectangle of base $2R$ would have to have to equal the area of a disk of radius $R$. It is $\pi R^2/(2R)=\frac{\pi}{2}R$. And $V_3/V_2$ is the height a cylinder with base $\pi R^2$ would have to have to equal a ball of radius $R$. It is $\frac{4}{3}\pi R^3/(\pi R^2)=\frac{4}{3}R$.
If $V_n/V_{n-1}$ is a small fraction of $R$, it means that the cylinder doesn't have to be very tall to equal the volume $V_n$; if it is large, then the cylinder does have to be tall. Now if instead of slicing the $n$-dimensional ball in half, we were to slice slightly above and slightly below the midpoint, that is, instead of slicing at, say, $x_n=0$, we sliced at $x_n=\epsilon$ and $x_n=-\epsilon$, where $\epsilon$ is a small positive number, the volume between the slices would be approximately a cylinder with the equator as base. So if $V_n/V_{n-1}$ were small, we could set $\epsilon$ equal to half this ratio, and almost all of the volume $V_n$ would lie between the slices.
When $n=2$ or $3$, the ratio is not a small fraction of $R$. (Both $\pi/2$ and $4/3$ are greater than $1$.) But as $n$ grows, it can be shown that $\sqrt{n}V_n/V_{n-1}$ approaches $\sqrt{2\pi}R$; the coefficient of $R$ in $V_n/V_{n-1}$ approaches $\sqrt{2\pi/n}$, which is indeed small when $n$ is large. So most of the volume $V_n$ lies in a narrow slice containing the equator.
The surface calculation is similar. The ratio $V_n/A_n$ is again a length. The difference $V_n(R)-V_n((1-\epsilon)R)$ (where the argument of $V_n$ is the radius of the ball) is the volume of the "spherical shell" of thickness $\epsilon R$. Roughly speaking, it's the part of the volume of the onion that is contained in the onion peel. Since $V_n(R)=C_nR^n$, where $C_n$ does not depend on $R$, we have, using that $A_n(R)=\frac{d}{dR}V_n(R)$,
$$
V_n(R)-V_n((1-\epsilon)R)=C_nR^n(1-(1-\epsilon)^n)\approx C_nR^n\cdot n\epsilon=nC_nR^{n-1}\cdot\epsilon R=A_n(R)\cdot\epsilon R.
$$
So if $V_n(R)/A_n(R)$ is a small fraction times $R$, we can set $\epsilon$ equal to this small fraction, and conclude that the volume of the onion peel is approximately that of the whole onion.
For $n=2$ and $n=3$ we get $\pi R^2/(2\pi R)=\frac{1}{2}R$ and $\frac{4}{3}\pi R^3/(4\pi R^2)=\frac{1}{3}R$. In fact, from the previous paragraph you can see that $V_n(R)/A_n(R)=\frac{1}{n}R$ in general. When $n$ is big, this is indeed a small fraction of $R$.


text:
Q: is there a way to get Breadcrumbs to display correct information when you navigate to an item that was in a 3rd level category, if you copy that url and go to a completely different product in a completely different 3rd level category and then paste in the URL you copied only the product name in the breadcrumbs is updated, the category path wont change
ie
go to Men's, Clothing, Coats, Men's Coat 1, the Breadcumbs will say something like "Home > Men's > Clothing > Coats > Men's Coat 1",
copy the URL than go to Women's, Footwear, Heels, Women's Heel 1, the breadcrumb will be "Home > Women's > Footwear> Heels > Women's Heel 1"
Now if you paste the URL you copied from the Coat, the Breadcrumbs will be "Home > Women's > Footwear> Heels > Men's Coat 1" which isn't correct
i set up a clean build of magento without any of the extensions and duplicated the test and it did the same so it's obviously a problem with magento, i'm wondering if there already exists a way to fix this
UPDATE: my current solution that i am using now is to rebuild the breadcrumbs when a customer enters the product view which is hardly efficient so i still want to know if there is a better why

A:
Now if you paste the URL you copied from the Coat, the Breadcrumbs
  will be "Home > Women's > Footwear> Heels > Men's Coat 1" which isn't
  correct

In my experience this is local to 1.11EE - This is due to the fact that Magento uses the cookie value from LAST_CATEGORY. I requested a patch from EE support for this and they provided one to me. I'd be surprised if this wasn't fixed in 1.12.
While I don't have the patchfile at the moment, an SVN diff yielded the following:
Index: app/code/core/Enterprise/PageCache/Model/Processor/Default.php
===================================================================
--- app/code/core/Enterprise/PageCache/Model/Processor/Default.php  (revision 717)
+++ app/code/core/Enterprise/PageCache/Model/Processor/Default.php  (revision 718)
@@ -103,6 +103,7 @@
          */
         if ($container && !Mage::getIsDeveloperMode()) {
             $container = new $container($this->_placeholder);
+            $container->setProcessor(Mage::getSingleton('enterprise_pagecache/processor'));
             $blockContent = $matches[1];
             $container->saveCache($blockContent);
         }
Index: app/code/core/Enterprise/PageCache/Model/Container/Breadcrumbs.php
===================================================================
--- app/code/core/Enterprise/PageCache/Model/Container/Breadcrumbs.php  (revision 717)
+++ app/code/core/Enterprise/PageCache/Model/Container/Breadcrumbs.php  (revision 718)
@@ -51,6 +51,10 @@
     protected function _renderBlock()
     {
         $productId = $this->_getProductId();
+
+        /** @var $product null|Mage_Catalog_Model_Product */
+        $product = null;
+
         if ($productId) {
             $product = Mage::getModel('catalog/product')
                 ->setStoreId(Mage::app()->getStore()->getId())
@@ -60,6 +64,12 @@
             }
         }
         $categoryId = $this->_getCategoryId();
+
+        if ($product !== null && !$product->canBeShowInCategory($categoryId)) {
+            $categoryId = null;
+            Mage::unregister('current_category');
+        }
+
         if ($categoryId && !Mage::registry('current_category')) {
             $category = Mage::getModel('catalog/category')->load($categoryId);
             if ($category) {
@@ -68,7 +78,7 @@
         }

         //No need breadcrumbs on CMS pages
-        if (!$categoryId) {
+        if (!$productId && !$categoryId) {
             return '';
         }

Index: app/code/core/Enterprise/PageCache/Model/Observer.php
===================================================================
--- app/code/core/Enterprise/PageCache/Model/Observer.php   (revision 717)
+++ app/code/core/Enterprise/PageCache/Model/Observer.php   (revision 718)
@@ -546,6 +546,10 @@
      */
     public function updateProductInfo(Varien_Event_Observer $observer)
     {
+        if (!$this->isCacheEnabled()) {
+            return $this;
+        }
+
         $paramsObject = $observer->getEvent()->getParams();
         if ($paramsObject instanceof Varien_Object) {
             if (array_key_exists(Enterprise_PageCache_Model_Cookie::COOKIE_CATEGORY_ID, $_COOKIE)) {
Index: app/code/core/Mage/Catalog/Helper/Product.php
===================================================================
--- app/code/core/Mage/Catalog/Helper/Product.php   (revision 717)
+++ app/code/core/Mage/Catalog/Helper/Product.php   (revision 718)
@@ -307,6 +307,8 @@
             if ($product->canBeShowInCategory($lastId)) {
                 $categoryId = $lastId;
             }
+        } elseif (!$product->canBeShowInCategory($categoryId)) {
+            $categoryId = null;
         }

         if ($categoryId) {
@@ -322,9 +324,7 @@
         try {
             Mage::dispatchEvent('catalog_controller_product_init', array('product' => $product));
             Mage::dispatchEvent('catalog_controller_product_init_after',
-                            array('product' => $product,
-                                'controller_action' => $controller
-                            )
+                array('product' => $product, 'controller_action' => $controller)
             );
         } catch (Mage_Core_Exception $e) {
             Mage::logException($e);


text:
Q: Creating a function to generate a matrix using several lists Suppose I have the following lists:
brice_grades <- list(math = c(90, 64, 100), reading = c(55, 71, 50),
                 science = c(100, 100, 98))
talia_grades <- list(math = c(70, 64, 70), reading = c(100, 80, 50),
                     science = c(100, 92, 98))
annie_grades <- list(math = c(14, 64, 50), reading = c(90, 71, 99),
                     science = c(88, 70, 98))

I am trying to create a function, report_card, that I can run through the sapply function such that I return a matrix with average grades for each class, unless the grade is below a 70, in which case it says "fail" rather than the grade.
Here is what I mean:
          brice_grades  talia_grades  annie_grades
math      84.7          fail          fail
reading   fail          76.7          86.7
science   99.3          96.7          85.3

I'm new to creating functions in R so I'm a little tripped up. I'm not sure if I should be using sapply given that all of my output is not the same class ("fail" is a string and the means are numeric obviously). Additionally, it gets a little weird for me writing this function using vectors contained within lists.

A: If you're happy with a character matrix output, a double loop with sapply should take care of it.
failfun <- function(x) {m <-  mean(x); if(m < 70) "fail" else round(m,1)}
sapply(mget(c("brice_grades", "talia_grades", "annie_grades")), \(x) sapply(x, failfun))
#        brice_grades talia_grades annie_grades
#math    "84.7"       "fail"       "fail"
#reading "fail"       "76.7"       "86.7"
#science "99.3"       "96.7"       "85.3"

A: Another option is to turn your lists into a data frame and use tidyverse for the rest:
library(tidyverse)

# All into a data frame
df <-
  mget(ls(pattern = "_grades")) |>
  imap(~ .x |> as_tibble() |> mutate(person = .y)) |>
  bind_rows()

# Inspired by thelatemail
failfun <- function(x) {
  m <- mean(x)
  if (m < 70) "fail" else as.character(round(m, 1))
}

# Do the calculations
df <-
  df |>
  group_by(person) |>
  summarise(across(everything(), ~ failfun(.))) |>
  pivot_longer(-person) |>
  pivot_wider(person)

df

Output:
# A tibble: 3 × 4
  person       math  reading science
  <chr>        <chr> <chr>   <chr>
1 annie_grades fail  86.7    85.3
2 brice_grades 84.7  fail    99.3
3 talia_grades fail  76.7    96.7

A: You can use transpose from purrr package
purrr::transpose(list(brice_grades , talia_grades , annie_grades))
|> sapply(\(x) sapply(x ,
\(x) if(mean(x) < 70) "fail" else round(mean(x) , 1))) -> avg

row.names(avg) <- c("brice_grades" , "talia_grades" , "annie_grades")

avg <- t(avg)

*

*output

        brice_grades talia_grades annie_grades
math    "84.7"       "fail"       "fail"
reading "fail"       "76.7"       "86.7"
science "99.3"       "96.7"       "85.3"


text:
Q: What is "QApplication app(argc, argv)" trying to do? #include <QtGui/QApplication>
#include <QtDeclarative>
#include "qmlapplicationviewer.h"

int main(int argc, char **argv) {
    QApplication app(argc, argv);
    QmlApplicationViewer viewer;

    viewer.setMainQmlFile("app/native/assets/main.qml");
    viewer.showFullScreen();

    return app.exec();
}

My C++ is a bit rusty.  Can someone please explain to me what is "QApplication app(argc, argv)" trying to do ?
Is it trying to declare a function which takes in 2 arguments (argc and argv) and return a variable of type QApplication ?

A: Here's a quote from Qt Docs:

The QApplication class manages the GUI application's control flow and
  main settings.
QApplication contains the main event loop, where all events from the
  window system and other sources are processed and dispatched. It also
  handles the application's initialization, finalization, and provides
  session management. In addition, QApplication handles most of the
  system-wide and application-wide settings.
For any GUI application using Qt, there is precisely one QApplication
  object, no matter whether the application has 0, 1, 2 or more windows
  at any given time. For non-GUI Qt applications, use QCoreApplication
  instead, as it does not depend on the QtGui library.
The QApplication object is accessible through the instance() function
  that returns a pointer equivalent to the global qApp pointer.

So, the line
QApplication app(argc, argv);
creates an instance of the QApplication class.

A: QApplication is a Qt class that contains the main event loop.
When you write QApplication app(argc, argv);
you are creating a object app of this class, by calling its constructor with argc and argv
When int main(int argc, char **argv) is called while running the program, int argc is intialized to contain the number of arguments passed while running the program. char **argv contains an array of arguments passed to the program when executing it.
char* argv[0] will contain (point to) the name of the program, while the subsequent elements will point to the other arguments passed.
argc and argv are in turn, passed to the constructor of QApplication, so that one can pass Qt specific arguments when running your program.
For an example of such arguments try running ./yourProgramName --help in a terminal window

A: app() is not a function, it is a constructor call.
If you come from C# or Java or something, imagine it as
QApplication app = new QApplication( argc, argv );

Just that app would be a pointer this way, while it actually is the object itself if it is created like in your example.
In short, Qt needs a QApplication instance to run so signals&slots are processed (if you are using them) and events like painting etc are handled

A: The line
QApplication app(argc, argv);

creates a new instance of type QApplication and invokes the constructor of this class. In your example, the variable app now stores this instance. It is somewhat (semantically) a shorthand of this:
QApplication app = QApplication(argc, argv);


text:
Q: How to insert data in SQL Server using F#? I want to make a module which helps to execute SQL query from F#. I unable to use System.Data.SqlClient and getting error.
module SQL_Helper

open System.Data.SqlClient

type SqlHelper (connection) =
    let exec bind parametres query =
        use conn = new SqlConnection (connection)
        conn.Open()
        use cmd = new SqlCommand (query, conn)
        parametres |> List.iteri (fun i p ->
                        cmd.Parameters.AddWithValue(sprintf "@p%d"  i, box p) |> ignore)
        bind cmd

    member __.Execute = exec <| fun c -> c.ExecuteNonQuery() |> ignore
    member __.Scalar  = exec <| fun c -> c.ExecuteScalar()
    member __.Read f  = exec <| fun c -> [ let read = c.ExecuteReader()
                                           while read.Read() do
                                               yield f read ]


text:
Q: ant task to print the contents of a directory to a file As part of a custom ant build I'm toying with I'd like to have the build

*

*Perform a <replaceregexp> on an html document

*For the 'replace' on the regex, I'd like to iterate a directory of .js files and inject a  tag to point at each file.

I've been looking through the ant docs at
http://ant.apache.org/manual/index.html
but I haven't seen anything to help me iterate or list the files.

A: You probably want to generate the replace text first, by processing the directory containing the .js files.
One approach might be to use a fileset to gather the names of the files, then a pathconvert task to construct the html snippet to use a replacement text.  For a directory 'my_dir', for example:
<fileset id="dir.contents" dir="my_dir">
    <include name="*.js"/>
</fileset>

<pathconvert pathsep="${line.separator}" property="js.html" refid="dir.contents">
  <chainedmapper>
    <mapper type="flatten" />
    <regexpmapper from="(.*)"
       to='<script type="text/javascript" src="http://your.url/\1"></script>' />
  </chainedmapper>
</pathconvert>

<echo>${js.html}</echo>

The flatten removes the directory part of the file path, leaving just the file name.
The echo then yields something like:
 [echo] <script type="text/javascript" src="http://your.url/a.js"></script>
 [echo] <script type="text/javascript" src="http://your.url/b.js"></script>
 [echo] <script type="text/javascript" src="http://your.url/c.js"></script>

So, you can then use ${js.html} as your regexp replace text.

A: The replaceregexp task supports nested fileset element.
Example from task doc
<replaceregexp match="\s+" replace=" " flags="g" byline="true">
    <fileset dir="${html.dir}" includes="**/*.html"/>
</replaceregexp>

at http://ant.apache.org/manual/Tasks/replaceregexp.html
Is this what you are looking for?


text:
Q: Determinants and Functions
For every square matrix, there is one and only one determinant associated with the matrix.

Can you explain how this statement illustrates the concept of a function?

A: A function is a relation that for every element in its domain yields exactly one output.
In your example, if we consider the set of square matrices as the domain, for each element in the domain (i.e. for every square matrix) a scalar is output (the determinant). Hence, the determinant is a well-defined function.

A: The most important detail of a function is that it maps each value in the domain to exactly one output value. This is why we have the vertical line test from grade school - it's a way of saying that each $x$ value only corresponds to one $y = f(x)$ value.
In this case, the determinant is a function that takes in a matrix and outputs a real number. Since there's only one determinant for each matrix, it's a valid or well defined function.


text:
Q: Elasticsearch term aggregation document count issue This the request I'm sending to ElasticSearch:
{
  "aggregations":{
    "followUpActivity.metainfo.metainfos.string1":{
      "terms":{
        "field":"metainfos.string1",
        "missing":"null",
        "order":{
          "_count":"asc"
        }
      }
    }
  }
}

I'm asking for buckets on field metainfos.string1 and ordering them by _count. This is the response:
{
  "took":7,
  "timed_out":false,
  "_shards":{
    "total":1,
    "successful":1,
    "failed":0
  },
  "hits":{
    "total":3,
    "max_score":1.0,
    "hits":[
      {
        "_index":"living_v1",
        "_type":"fuas",
        "_id":"be9b29f3-37a5-11e6-a66a-30b5c2122322",
        "_score":1.0,
        "_routing":"living_team",
        "_source":{
          "user":"living_team",
          "timestamp":"2016-06-22T11:27:25.531Z",
          "metainfos":{
            "string1":[
              "s1",  <<<<<<<<<<<<<--------------
              "s2"   <<<<<<<<<<<<<--------------
            ]
          }
        }
      },
      {
        "_index":"living_v1",
        "_type":"fuas",
        "_id":"c3af0f64-37a5-11e6-a66a-30b5c2122322",
        "_score":1.0,
        "_routing":"living_team",
        "_source":{
          "user":"living_team",
          "timestamp":"2016-06-22T12:30:01.625Z",
          "metainfos":{
            "string1":[
              "s1",    <<<<<<<<<<<<<--------------
              "s2"     <<<<<<<<<<<<<--------------
            ]
          }
        }
      },
      {
        "_index":"living_v1",
        "_type":"fuas",
        "_id":"ee790469-48f3-11e6-9f47-30b5c2122322",
        "_score":1.0,
        "_routing":"living_team",
        "_source":{
          "user":"living_team",
          "timestamp":"2016-07-13T13:33:41.231Z",
          "metainfos":{
            "string1":[
              "s2"    <<<<<<<<<<<<<--------------
            ]
          }
        }
      }
    ]
  },
  "aggregations":{
    "followUpActivity.metainfo.metainfos.string1":{
      "doc_count_error_upper_bound":0,
      "sum_other_doc_count":0,
      "buckets":[
        {
          "key":"s2",
          "doc_count":2       <<<<<<<<<<<<<--------------
        },
        {
          "key":"s1",
          "doc_count":3       <<<<<<<<<<<<<--------------
        }
      ]
    }
  }
}

As you can see, there are two buckets: s1 and s2. However, s1 is present only in two documents but ES is telling me that doc_count = 3!!! Moreover, s2 is present in three documents, but ES is telling me that doc_count = 2!!!!
I'm performing it using only one node.
Any ideas?
MAPPING
{
  "living_v1":{
    "mappings":{
      "fuas":{
        "properties":{
          "metainfos":{
            "properties":{
              "string1":{
                "type":"string"
              }
            }
          },
          "timestamp":{
            "type":"date",
            "format":"strict_date_optional_time||epoch_millis"
          },
          "user":{
            "type":"string",
            "index":"not_analyzed"
          }
        }
      }
    }
  }
}


text:
Q: Cannot subscribe on slickgrid scroll event I'm using slickgrid as container for data, and trying to subscribe on it's onscroll event as of described in documentation, i.e.
task_list.onscroll.subscribe(function(e, args) {
    console.log('scrolling occured');
});

Actually, I'm trying to do other processing afterwards, which is translating contents of the web page. The content is not fully translated, so I need to translate each time I scroll the page. However I get the message
Uncaught TypeError: Cannot read properties of undefined (reading 'subscribe')

How can I troubleshoot this error and find out why I get it?

A: There's a few small errors in your code, first the event names are camelCase so it should be onScroll and second if you want to subscribe to SlickGrid events then you need to use the grid object
grid.onScroll.subscribe(function(e, args) {
 // ...
});

and don't forget to unsubscribe when leaving the page because you'll have quite a leak with the onScroll. I prefer to use the Slick EventHandler since it has an easier unsubscribeAll method that I can use when destroying/leaving the page
var eventHandler = new Slick.EventHandler();
var grid = new Slick.Grid("#myGrid", dataView, columns, options);

function something() {
  eventHandler.subscribe(grid.onScroll, function(e, args) {
    // ...
  });
}

function destroy() {
  eventHandler.unsubscribeAll();
}

Hopefully there's no error in my code but just to let you know I wrote by memory here so please double-check the code and look at the multiple SlickGrid Examples which all have easy code access


text:
Q: Remove array of object if object inside is empty I am preparing an array like this
 datas[5] = { "qty_sized": "1", "resolution": "5", "status": "", "order": 1342 };

where [5] is dynamic from response.
I have and object mydata and inside that I have a object items.
I push array to  object items, with assign
Object.assign(mydatadata.items, datas);
Now mydata.items has an array set,
`
items{
1 {qty_auth: "", resolution: "4", status: "", order: "1495"},
5 {qty_sized: "1", resolution: "4", status: "", order: "1485"}
}`

Now if  qty_auth: "" , from which i need to check if qty_ is empty then remove the array . So expected output is something like this:
Note: qty_ is dynamic here.
items{ 5 {qty_sized: "1", resolution: "4", status: "", order: "1485"} }
and i want to result inside same object mydata.items
I tried something like this
const mydatadata.items  = mydata.items.filter((o) =>
            Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);

console.log(result);

but its now giving me any output

A: *

*Using Object#entries, get the key-value pairs of items

*Using Array#filter, iterate over the above array

*In each iteration, check if the current item has a key starting with qty_ whose value is not empty. You can do this using Object#keys, Array#some, and String#startsWith.

*Using Object#fromEntries, convert the filtered pairs to an object again.

const obj = {
  items: {
    1: {qty_auth: "", resolution: "4", status: "", order: "1495"},
    5: {qty_sized: "1", resolution: "4", status: "", order: "1485"}
  }
};

obj.items = Object.fromEntries(
  Object.entries(obj.items)
  .filter(([_, item]) =>
    Object.keys(item).some(key => key.startsWith('qty_') && item[key])
  )
);

console.log(obj);

A: You're talking about an array, but using curly brackets instead of square brackets. For filter() to work it would have to look like:
mydata = {
   items: [
      {qty_auth: "", resolution: "4", status: "", order: "1495"},
      {qty_sized: "1", resolution: "4", status: "", order: "1485"}
   ]
}

Assuming it is an actual array there's still a problem with "const mydatadata.items", or at least it throws an error for me because mydatadata is not initialized. Unless it's a typo and it should be mydata, but then you'd be redeclaring it. So depending on what you want:
mydata.items = mydata.items.filter((o) =>
        Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);

or
let mydatadata = {};
mydatadata.items = mydata.items.filter((o) =>
        Object.keys(o).some((k) => k.startsWith("qty") && o[k])
);

Furthermore you're storing the result in mydatadata but you're logging the variable result.
So depending on the previous answer:
console.log(mydatadata);

or
console.log(mydata);

Here's a fiddle: https://jsfiddle.net/b57qa82d/

A: You should probably just be using an array rather than an object. It's not really clear from your question what structure you need as you keep changing the terminology to describe your data. For example: "Now mydata.items has an array set" but your code says that it should be object with keys, not an array.
So I suggest: get your data in an array, and filter it by iterating over each object's entries and checking to see if any of the keys starting with "qty" has a value that isn't an empty string. You can then assign that filtered array to myObject.items.

const data = [
{ "qty_sized": "0", "resolution": "5", "status": "", "order": 2 },
{ "qty_auth": "", "resolution": "5", "status": "", "order": 3 },
{ "qty_auth": "1", "resolution": "5", "status": "", "order": 1342 },
{ "qty_sized": "", "resolution": "2", "status": "", "order": 1 },
{ "qty_sized": "1", "resolution": "1", "status": "", "order": 142 }];

const filtered = data.filter(obj => {
  return Object.entries(obj).find(([key, value]) => {
    return key.startsWith('qty') && value;
  });
});

const myObject = { items: filtered };

console.log(myObject);

Additional documentation

*

*Object.entries

*find


text:
Q: How to extend an existing jQuery UI widget? I am using jQuery v1.8.3 and jQuery UI v1.9.2. I would like to extend an existing jQuery UI widget (in my case the Autocomplete widget) by adding and overriding just some options and methods but keeping the others functionalities as those present in the official release. How can I make that the "proper" (maybe, the "standard") way?

P.S.: I searched on the Web (1, 2, ...) and I found documentation mostly related to creating a new jQuery UI widget but not to extending an existing one.

A: In jQuery UI 1.9+, extending a widget is done in the same manner as creating a new widget. The widget factory ($.widget()) supports a few scenarios:
Creating a new widget using the base widget ($.Widget) as the starting point:
$.widget( "ns.widget", { ... } )
Creating a new widget that inherits from an existing widget:
$.widget( "ns.widget", $.ns.existingWidget, { ... } )
Extending a widget:
$.widget( "ns.widget", $.ns.widget, { ... } )
You'll notice that the extending syntax and the inheritance syntax are the same. The widget factory is smart enough to notice that the widget you're creating and the widget you're inheriting from are the same and handle it appropriately.
When inheriting or extending a widget, you only need to define what you want to change or add. There are also a few new methods that exist on the base widget to make it easier to work with inheritance and methods that change context. Read the jQuery.Widget documentation for a full list of methods and their descriptions. You'll definitely want to read about _super() if you're extending a widget.
Here's an example that would change the default delay option to 500 and add a new option prefix which is added to all suggestions:
$.widget( "ui.autocomplete", $.ui.autocomplete, {
    options: {
        delay: 500,
        prefix: ""
    },

    _renderItem: function( ul, item ) {
        var label = item.label;
        if ( this.options.prefix ) {
            label = this.options.prefix + " " + label;
        }
        return $( "<li>" )
            .append( $( "<a>" ).text( label ) )
            .appendTo( ul );
    },
});


text:
Q: Validar dados e gerar senha temporária - cakePHP Bom dia,
estou precisando criar uma função que valide os campos do cliente e compara para vefificar se estão corretos se estiverem, gerar uma senha temporária.
Segue abaixo meu código.
function _gerar_senha_validando_campos(){

        if (!empty($this->data['Cliente']['codcontrato']) && !empty($this->data['Cliente']['cpf_cnpj']) && !empty($this->data['Cliente']['login']) && !empty($this->data['Cliente']['ip'])) {

            $cliente = $this->Cliente->find(array('situacao'=>'APR', 'codcontrato' => $this->data['Cliente']['codcontrato']));

        if (($this->data['cliente']['codcontrato'] == $cliente['cliente']['codcontrato']) &&
            ($this->data['cliente']['cpf_cnpj'] == $cliente['cliente']['cpf_cnpj']) &&
            ($this->data['cliente']['login'] == $cliente['cliente']['login']) &&
            ($this->data['cliente']['ip'] == $cliente['cliente']['ip'])) {

        $CaracteresAceitos = 'acefghijrsuxz23456789';
        $max = strlen($CaracteresAceitos)-1;
        $password = null;
        for($i=0; $i < 8; $i++) {
            $password .= $CaracteresAceitos{mt_rand(0, $max)};
        }

        return $password;

        $this->set('sucesso', 'Senha alterada com sucesso!');
        $this->set('newAviso','ATENÇÃO: Sua senha é temporária e vai expirar-se em 2 horas. Você deverá efetuar a troca da senha no site da Virtual Telecom ou clicando AQUI.');

        }

        if (($this->data['cliente']['codcontrato'] != $cliente['cliente']['codcontrato'])) {
            $this->set('erro', 'Código do contrato inválido!');
        }

        if (($this->data['cliente']['cpf_cnpj'] != $cliente['cliente']['cpf_cnpj'])) {
            $this->set('erro', 'CPF inválido!');
        }

        if (($this->data['cliente']['login'] != $cliente['cliente']['login'])) {
            $this->set('erro', 'Login inválido!');
        }

        if (($this->data['cliente']['ip'] != $cliente['cliente']['ip'])) {
            $this->set('erro', 'IP diferente do cadastrado!');
        }

        else{

            $this->set('erro', 'Dados não conferem! Favor Verificar novamente');
        }

    }

        else{

            $this->set('erro', 'Campos obrigatórios não preenchidos');

    }

}


text:
Q: Free RTMP audio player Does anyone know any free RTMP audio player? I could find several video players, but not for audio.

A: there have some audio player, you can try it!
Free RTMP Streaming Player 2.0
http://www.topshareware.com/Free-RTMP-Streaming-Player-download-57014.htm


text:
Q: Fetching MongoDB data in Flask using pyMongo I need help with fetching data from a MongoDB collection in a simple Flask webpage. I've been trying to figure out how to fetch it but it has been of no help. My JSON data is an array of documents with 3 nested fields and I have attached it with the question. I'm trying to fetch all the data of the JSON template at first but I've been unable to. Once I know, I'll fetch the individual array.
Here is my Flask code:
from flask import Flask
from pymongo import MongoClient

app = Flask(__name__)

client = MongoClient("mongodb://localhost:27017/")
db = client.Learning
todos = db.data

@app.route('/')
def lists():
    for x in todos.find():
        y = print(x)
    return ""

if __name__ == '__main__':
    app.run()

And this is my data structure for the MongoDB data:

Any help or hint will be really appreciated so I can know how to fetch the data. Do I have to use HTML? If so, how can I fetch the arrays within arrays with HTML?

A: You could try using Flask-PyMongo.
It works like this:
from flask import Flask
from flask_pymongo import PyMongo
from flask.json import jsonify

app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/Learning"
mongo = PyMongo(app)

@app.route("/")
def lists():
    print([i for x in mongo.db.data.find({})])
    return jsonify([i for i in mongo.db.data.find({})])

if __name__ == '__main__':
    app.run()


text:
Q: How to make spark write a _SUCCESS file for empty parquet output? One of my spark jobs is currently running over empty input and so produces no output. That's fine for now, but I still need to know that the spark job ran even if it produced no parquet output.
Is there a way of forcing spark to write a _SUCCESS file even if there was no output at all? Currently it doesn't write anything to the directory where there would be output if there was input so I've no way of determining if there was a failure (this is part of a larger automated pipeline and so it keeps rescheduling the job because there's no indication it already ran).

A: _SUCESS file is written by Hadoop code. So if your spark app doesn't generate any output you can use Hadoop API to create _SUCCESS file yourself.
If you are using PySpark - look into https://github.com/spotify/snakebite
If you are using Scala or Java - look into Hadoop API.
Alternative would be to ask Spark write empty dataset into to the output. But this might not what you need - because there will be part-00000 and _SUCESS file, which downstream consumers might not like.
Here is how to save empty dataset in pyspark (in Scala the code should be the same)
$ pyspark
>>> sc.parallelize([], 1).saveAsTextFile("/path/on/hdfs")
>>> exit()

$ hadoop fs -ls /path/on/hdfs
Found 2 items
-rw-r--r--   2 user user          0 2016-02-25 12:54 /path/on/hdfs/_SUCCESS
-rw-r--r--   2 user user          0 2016-02-25 12:54 /path/on/hdfs/part-00000

A: With Spark 1.6:
If writing a DataFrame with a forced schema and Avro writer, zero rows produces at least one part-r-{part number}.avro file (containing essentially a schema without rows) and a _SUCCESS file. With this pseudocode example:
resultData.persist(/* optional storage value */)

if(resultData.count == 0)
  resultData
    .coalesce(1)
    .write
    .avro(memberRelationshipMapOutputDir)
else
  doSomething()

resultData.unpersist()

It's possible to tweak avro to parquet and figure out the row count's relationship to the coalesce factor. (And ... switch to use approximate counts.) The above example brings up that schema may need to be forced on the internal data before writing. So ... this may be required:
case class Member(club : String, username : String)

hiveContext
    .read
    .schema(ScalaReflection.schemaFor[Member].dataType.asInstanceOf[StructType])
    .avro(memberRelationshipMapInputDir)

Some useful imports / code  may be:
import com.databricks.spark.avro._
import org.apache.spark.sql.catalyst.ScalaReflection
import org.apache.spark.sql.types.StructType
import org.apache.spark.storage.StorageLevel
import org.apache.spark.sql.hive.HiveContext

val hiveContext = new HiveContext(sparkContext)
import hiveContext.implicits._

Disclaimer: Some of this may be changed for Spark 2.x and all the above is 'scala-like pseudocode'.
In order to convert a RDD of myRow to a DataFrame, it's possible to use the read above to get the data or convert the RDD to an appropriate DataFrame with createDataFrame or toDF.

A: You can use emptyRDD for writing just _SUCCESS flag:
    spark.sparkContext.emptyRDD[MyRow].saveAsTextFile(outputPath)


text:
Q: Scan filename and move to respective folders on a different server
*

*I have a folder (Students located in server A) containing 800 files, each has a unique identifier in the first 6 characters of the filename (e.g.Y9L-01_xxx.xlsx; Y9L-02_xxx.xlsx; Y9L-03_xxx.xlsx etc).

*I have folders with sub folders where I would like to transfer the files. These folders are located in server B.

*Each folder in number 2 above contains the same 6 character unique identifier of the filename at the beginning of the folder name (Y9L-01; Y9L-02; Y9L-03). There is a sub folder called 2014_Hockey under the folders Y9L-01; Y9L-02; Y9L-03;

*I would like to transfer the files from the "Students" folder described in 1 above to each of the 2014_Hockey folder that is located under Y9L-01; T9L-02; Y9L-03 etc described in 2 and 3 above.
Effectively, I would like the script to match the first 6 characters of the file name with the first 6 characters of the folder names described in #3 and then move the file to the 2014_Hockey folder under that folder.
Example:
The .xslx file in \Students\Y9L-01_HockeyChampionship.xslx located in server A to move to Y9L-01\2014_Hockey located in server B
How do I do this?
Thanks
Regards
Rauri

A: This should be easily doable with PowerShell. I haven't tested this myself yet, so you should try it on some sample data before using it on your real files.
Get-ChildItem '\\ServerA\Students' | ForEach-Object {$NewFolder = $_.Name.Substring(0,6); Move-Item $_ "\\ServerB\$NewFolder\2014_Hockey"}

You may see unexpected results if some of the files in \\ServerA\Students don't match the naming convention you've specified.
This will, for example, do the following:
\\ServerA\Students\Y9L-01_HockeyChampionship.xlsx
will be moved to
\\ServerB\Y9L-01\2014_Hockey\Y9L-01_HockeyChampoinship.xlsx
If you need to only move the Excel files, you'll need to filter the rest out by adding in Where-Object like this:
Get-ChildItem '\\ServerA\Students' | Where-Object {$_.Extension -eq '.xlsx'} | ForEach-Object {$NewFolder = $_.Name.Substring(0,6); Move-Item $_ "\\ServerB\$NewFolder\2014_Hockey"}


text:
Q: PHP Symfony 2, use a method parameter in a service I have a controller with a method calculateMaterial($product) where $product is a Doctrine entity.
I have tried to build a service for calling this method, i called my service Calculator.
Here's my services.xml file :
http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
    <service id='acv.calculator'
             class='Arto\AcvBundle\Calculator\Calculator'>
             <argument type="service" id="doctrine.orm.entity_manager"/>
             <call method="calculateMaterial">
                  <argument type="service" id="acv.product"></argument>
             </call>
    </service>
    <service id='acv.product'
             class='Arto\AcvBundle\Entity\Product'
             public='true'>
            <call method="getAssemblies"></call>
    </service>
</services>

All works fine, i call my service in a method from my controller but when i execute the calculateMaterial($product) method, which is now in my service Calculator, i always get a $product NULL.
I don't know how to do for giving the product in the method from my controller to the method of my service.

A: I don't think you should inject your $product entity in your service, but use it punctually, injecting your acv.calculator where you need it, and then call your calculateMaterial when you need it.
<?php
// ...
$caculator->calculateMaterial($product);

Especially if you need to retrieve a $product when you need it (after getting it from a repo, instanciating it, ... etc)


text:
Q: Internet Explorer 8 won't modify HTML5 tags in print stylesheet I was working on a print stylesheet earlier and came across a problem with IE8. I am using HTML5 and several layout tags including header, nav and footer.
For some reason in my print stylesheet the display:none; declaration on these tags is being ignored in IE8 (and I can only assume subsequent lower versions). I first thought that Developer Tools in IE9 could be causing a false representation, however I have a Windows XP installation in VirtualBox which shows the problem also.
My guess its because HTML5 tags aren't seen properly by anything below IE9. The print stylesheet hides the layout tags in Firefox and Chrome.
Is there anyway to get around this?
Edit:
Here is what I have at the moment:
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/print.css" type="text/css" media="print" />

Ignore the PHP Statements, they are specific to my CMS which is WordPress.
Then I simply hide the layout tags in the print.css:
nav,footer {
display:none;
}

This works for IE9, Firefox, Chrome but not in anything lower than IE9. It seems to ignore HTML5 tags.

A: Use Modernizr. In the Extra, make sure html5shiv /w printshiv is selected. Include this javascript library on your site and it should work like a charm.

A: I suggest you try html5shiv. The main shiv does document.createElement() as you have but it's been optimized / minified like crazy. More importantly, it includes printshiv (IE Print Protector) which will let you style HTML5 elements for print.

A: Since all i can do is guess without actually seeing the code, my first guess would be that the html5 shiv that is being used after the css declarations, and the css simply skips the html 5 tags, without applying the css styles to them. Try setting the script at the very top, before any css link tags in the head.

A: You could try a workaraound using Javascript by including a pair of functions onbeforeprint and onafterprint in which you hide/show the content that should be display:none.

A: I highly recomend for the use of boilerplate for your trouble. Is a nice compilation for web standarts and some know and common issues in almost every browser. It use modernizr and have an awesome stylesheet that have a @media print that you can use for all your printing troubles in all browsers.


text:
Q: parsing json data from alpha vantage I am new to Ajax and JSON. I am facing issues with the parsing of Json data from the Alpha Vantage API. My project is to create a stock widget using the jive platform in a html5 widget and I have existing code using the yahoo finance api. The yahoo api url is no longer working and I found another api that is working and giving me json data. I have tried to work with the existing code but the trouble I am stumbling on is how to parse the code from json data to the html.
Also console is giving me the following error for the first line of the json data so I added a callback to the url thinking it would fix it
Uncaught SyntaxError: Unexpected token :

 (common stock)

Retrieving stock information...

        Price

        $

        Change

        Volume

        Average Daily Volume

        52 Week Range

This is the json info

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "0787.HK",
        "3. Last Refreshed": "2017-12-07",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2017-12-07": {
            "1. open": "0.6700",
            "2. high": "0.6800",
            "3. low": "0.6600",
            "4. close": "0.6600",
            "5. volume": "20488001"
        }
        // More rows
    }
}

What am i doing wrong and how do I do this correctly?

A: Remove &callback=? from
var theURL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W&callback=?";

and change dataType :"jsonp" to dataType :"json".

var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=0787.HK&interval=1min&apikey=AOIAMG3WFZ8LS58W';

jQuery.ajax({
    url: url,
    dataType: 'json',
    contentType: "application/json",
    success: function(data){
      console.log(data);
    }
});

A: I think your script was coded to retrieve data from yahoo finance.
I tried my best to rewrite part of the code in order to use ALPHAVANTAGE. I'd appreciate some feedback on it please.

var theURL = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo";

$(document).ready(function() {
  $("#stockIndicator").show();
  doAjax(theURL);

  $('.ajaxtrigger').click(function() {
    $("#stockIndicator").show();
    doAjax(theURL);
    return false;
  });

  function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
  }

  function doAjax(url) {
    $.ajax({
      url: url,
      dataType: 'json',
      contentType: "application/json",
      success: function(data) {

        var symbol = data['Meta Data']['2. Symbol']
        var lastRefreshed = data['Meta Data']['3. Last Refreshed']
        var lastTradePriceOnly = data['Time Series (1min)'][lastRefreshed]['4. close']
        var lastVolume = data['Time Series (1min)'][lastRefreshed]['5. volume']

        $('#stockSymbol').html(symbol);
        $('#stockAsk').html(lastTradePriceOnly);
        $('#stockVolume').html(numberWithCommas(lastVolume));
        $("#stockIndicator").hide();
      }
    });
  }
});
#stockIndicator {
  text-align: left;
  padding: 10px;
  margin: 5px;
  color: red;
}

.ajaxtrigger:hover {
  cursor: pointer;
  cursor: hand;
}

#stock_miniQuote_head {
  background-color: #464A55;
  color: #FFFFFF;
  font-size: 14px;
  font-weight: bold;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
}

#stock_miniQuote {
  border-bottom-color: #DDDDDD;
  border-bottom-left-radius: 5px 5px;
  border-bottom-right-radius: 5px 5px;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  border-left-color: #DDDDDD;
  border-left-style: solid;
  border-left-width: 1px;
  border-right-color: #DDDDDD;
  border-right-style: solid;
  border-right-width: 1px;
  border-top-color: initial;
  border-top-style: none;
  border-top-width: initial;
  list-style-type: none;
  margin-bottom: 10px;
  padding-bottom: 0;
  padding-top: 10px;
  vertical-align: text-top;
  height: 100%;
  width: 99%;
}

.stock_divider {
  border-bottom: 1px solid #B2B0AD;
  padding-bottom: 5px;
}

#stock_left {
  float: left;
  width: 35%;
  height: 50px;
  border-right: 1px solid #B2B0AD;
  padding: 0 15px;
}

#stock_right {
  float: right;
  width: *;
  padding: 0 20px;
  vertical-align: text-top;
}

.stock_label {
  font-size: 14px;
}

.stock_strong {
  font-size: 17px;
}

#stock_body {
  padding: 10px 0 15px;
}

#stock_body_content {
  float: left;
  width: 170px;
  padding: 0 15px;
}

 (common stock)

Retrieving stock information...

      Price

      $

      Change

      Volume

      Average Daily Volume

      52 Week Range


text:
Q: SVG transition issues in Chrome and Opera I have an inline SVG and I want to animate it on hover. The way it's supposed to look, after you hover, a circle grows in size and inverts the SVG. I.e. what was opaque is now transparent. It's done by using a CSS transition on the radius parameter of a circle inside a mask.
The animation works flawlessly in Safari, but not in Chrome and Opera. In these browsers, it acts very weird. In short, it seems to only repaint the SVG when the cursor leaves the screen.
Firefox does nothing at all, but I'd attribute that to the lack of vendeor prefixes.
Thank you for your help in advance!
How can I remedy this? What alternative approaches I can take?
Here is a Pen of it (doesn't seem to animate): http://codepen.io/anon/pen/LGNaBw
<html>
    <head>
        <style>
        *
        {
            margin: 0;
            padding: 0;
        }

        body
        {
            width:100%;
            height:100%;

            background: #0F0F0F;
        }

        svg
        {
            position: relative;
            width: 60%;
            height:60%;

            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);

        }

        #svg_tm
        {
            transition: r 350ms;
        }

        svg:hover #svg_tm
        {
            r: 50;
        }

        </style>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
            <defs>
                <circle id="svg_tm" cx="50" cy="50"></circle>
                <path id="svg_ts" d="M86.915 27.103c-2.716 1.204-5.636 2.02-8.7 2.385 3.128-1.875 5.53-4.843 6.66-8.38-2.926 1.735-6.168 2.996-9.618 3.675C72.494 21.84 68.557 20 64.2 20c-8.365 0-15.147 6.782-15.147 15.147 0 1.187.134 2.343.392 3.452-12.588-.633-23.75-6.663-31.22-15.827-1.304 2.237-2.05 4.838-2.05 7.615 0 5.255 2.673 9.89 6.737 12.607-2.482-.08-4.818-.76-6.86-1.894l-.002.19c0 7.34 5.222 13.462 12.15 14.854-1.27.346-2.608.53-3.99.53-.976 0-1.925-.094-2.85-.27C23.29 62.42 28.883 66.8 35.51 66.92c-5.184 4.063-11.715 6.484-18.812 6.484-1.222 0-2.428-.07-3.613-.21C19.788 77.492 27.75 80 36.305 80 64.164 80 79.4 56.92 79.4 36.903c0-.657-.014-1.31-.043-1.96 2.96-2.135 5.527-4.803 7.558-7.84"/>
                <mask id="svg_ta">
                    <use xlink:href="#svg_ts" fill="#fff"></use>
                    <use xlink:href="#svg_tm"></use>
                </mask>
                <mask id="svg_tb">
                    <use xlink:href="#svg_tm" fill="#fff"></use>
                    <use xlink:href="#svg_ts"></use>
                </mask>
            </defs>
            <circle r="50" cx="50" cy="50" fill="#F0F0F0" mask="url(#svg_ta)"></circle>
            <circle r="50" cx="50" cy="50" fill="#F0F0F0" mask="url(#svg_tb)"></circle>
        </svg>
    </body>
</html>

A: With SVG (1.1) you can't modify attributes like r with CSS. Only style properties.
List of SVG style properties
The upcoming SVG2 spec allows it, and some browsers have started implementing it, but most have not.
You will need to use another method to animate your radius.


text:
Q: Using recursion combinations to subset array I recently posted a poor question on how to use recursion to estimate all combinations of lower triangle in C++. I managed to find a recursive algorithm that given an array of size n, generates and prints all possible combinations of r elements in array. I've employed this function using Rcpp in R. I've then written a loop around this function to get all the subsets of combinations r to r + n.
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int recursive(IntegerVector arr, IntegerVector data, int start, int end, int index, int r)
{
    if (index == r)
  {
    for (int j=0; j<r; j++)
        printf("%d ", data[j]);
    printf("\n");
  }

  for (int i=start; i<=end && end-i+1 >= r-index; i++)
    {
    data[index] = arr[i];
    recursive(arr, data, i+1, end, index+1, r);
    }

}

R code with five groups:
Rcpp::sourceCpp('recursive2.cpp')
nComm <- 5
r <- c(2:nComm)
n <- nComm
arr <- c(1:nComm)
dat <- c(1:nComm)
for(i in 1:(n-1)){
   recursive(arr, dat, 0, n-1, 0, r[i])
}
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
1 2 3 4 5

Currently, this just prints the subsets of combinations I need to estimate my dissimilarities. I'd like to be able to  remove the loop and use it as a single Rcpp function/script. With the end goal to be able to use the subsets (currently printed combinations) as way to subset rows in an array. Which will be used to calculate the intersect between vectors. So 1 2 will be used to compare rows 1 and 2 in an array. And so forth.


text:
Q: KnpSnappyBundle header and footer doesn't show As the title says I can't visualize the footer and header with knp_snappy.pdf, I have seen several examples and none has worked for me, I get the pdf but not the footer and header, I don't know is config problem or something else, this link below works but others but not in my code.
I am using symfony 3.4 , "knplabs/knp-snappy-bundle": "^1.5" and wkhtmltopdf-0.12.2.4
Examples:
https://github.com/KnpLabs/KnpSnappyBundle/issues/195
https://github.com/KnpLabs/KnpSnappyBundle/issues/154
This is my code:
config.yml
knp_snappy:
pdf:
    enabled:    true
    binary:     /usr/bin/xvfb-run /usr/bin/wkhtmltopdf
    options:    []

pdf/report.html.twig
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>My PDF</title>

My PDF

Harum trium sententiarum nulli prorsus assentior.

My PDF

pdf/footer.html.twig
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Contrat Thuasne Services</title>

      Test
      /
      © Society {{ "now"|date("Y") }}

controler
public function testPDFAction()
  {
    $snappy = $this->get('knp_snappy.pdf');
    $content = $this->renderView( 'pdf/report.html.twig' );

    $footer = $this->renderView( 'pdf/footer.html.twig' );
    //$snappy->setOption('header-html', $header);
    $snappy->setOption('footer-html', $footer);

    $html = $snappy->getOutputFromHtml($content);

    return new Response($html,200, [
      'Content-Type'          => 'application/pdf',
      'Content-Disposition'   => 'inline; filename="test.pdf"'
     ]
    );

    // Others test i make

 /*$html = $snappy->getOutputFromHtml($content,
 [
  // 'images' => true,
  'enable-javascript' => true,
  'page-size' => 'A4',
  // 'viewport-size' => '1280x1024',
  'header-html' => $header,
  'footer-html' => $footer,
  'margin-left' => '10mm',
  'margin-right' => '10mm',
  'margin-top' => '30mm',
  'margin-bottom' => '25mm',
 ]);*/
    //$snappy->setOption('header-html', $header);
    // $snappy->getOutputFromHtml($html);
    /*$options = [
     'header-html' => $header,
     'footer-html' => $footer
    ];*/

    /*return new PdfResponse(
     $this->get('knp_snappy.pdf')->getOutputFromHtml($html, $options),
     'file.pdf'
    );*/

    /*return new Response(
     $this->get('knp_snappy.pdf')->getOutputFromHtml($html,$options),
     200,
     [
      'Content-Type'        => 'application/pdf',
      'Content-Disposition' => sprintf('attachment; filename="%s"', "test"),
     ]
    );*/
  }

I don't know what is the problem, thanks in advance!!


text:
Q: How to set up javascript functions in Rails? I'm not sure how to load my google maps API code outside of a script that's not in my HTML page.
I get the error:
Error: google is not defined
Source File: http://localhost:3000/javascripts/google-map.js?1319030830
Line: 57

This is the line it is talking about:
google.maps.event.addDomListener(window, 'load', initialize);

Here is the full code of my google-map.js file:
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng( 37.09024 ,-95.712891 ),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById('google_map'),
    mapOptions);

    var input = document.getElementById('business_retail_address');
    var options = { types: ['geocode']};

    autocomplete = new google.maps.places.Autocomplete(input, options);

    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        infowindow.close();
        var place = autocomplete.getPlace();
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(16);  // Why 17? Because it looks good.
        }

        var image = new google.maps.MarkerImage(
        place.icon,
        new google.maps.Size(71, 71),
        new google.maps.Point(0, 0),
        new google.maps.Point(17, 34),
        new google.maps.Size(35, 35));
        marker.setIcon(image);
        marker.setPosition(place.geometry.location);

        var address = '';
        if (place.address_components) {
            address = [(place.address_components[0] &&
                place.address_components[0].short_name || ''),
            (place.address_components[1] &&
                place.address_components[1].short_name || ''),
            (place.address_components[2] &&
                place.address_components[2].short_name || '')
            ].join(' ');
        }

        infowindow.setContent();
        infowindow.open(map, marker);
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

I have little understanding of Javascript right now so I am at a lost of how to load this correctly or how to write the function in the JS file itself.
How do I put this google script in a JS file correctly?
Thank you.

A: Are you loading the google maps script before your script in the page? It looks like you might not be.
You need
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

then your script reference
<script type="text/javascript" src="your-script.js"></script>

put this either in the <head> section, or before the closing </body> tag.


text:
Q: Problem with BWidget's MessageDlg I am trying to use BWidget's MessageDlg. As it follows from the documentation here, the -aspect ratio defines the ratio between the width and height of the message window.
However, seems it has no effect. For this code:
For
package require BWidget
MessageDlg .msg -type yesno -icon warning  -message "Some text." -aspect 50

and
package require BWidget
MessageDlg .msg -type yesno -icon warning  -message "Some text." -aspect 500

in both cases i am getting messages windows with the default ratio (which is 150).
I am using BWidget 1.9.4. Is this a known issue for BWidget? Can you suggest a better alternative?

A: It appears to be declared and then just ignored, and has been this way for a long time. Ow! File a bug report please (and remember to set the Category field to bwidget).


text:
Q: Automating C# web app Deployment processes, using secure remote desktop access, and recent svn changes I want to create an application that will automate a very specific build process that is repeated daily.

*

*I need to build a C# web app, package the dlls and other necessary files (diff from last checkin in svn) into a .zip file in a certain structure.

*Connect to a secure remote Windows web server (with specific authentication), copy, unzip and deploy the files to the correct locations.

I was thinking a C# console app which will handle the connection to the remote server, and a combination of file operations in the code, or batch files run on the local machine and the remote server. I intend to use batch script to build the Visual Studio project, and run a diff on the svn tree and export changed files to a certain directory structure.
Is this at all possible? How would I achieve the remote connection and copy the files?
Just wanting to see your thoughts.
Thanks for any help.

A: What you're trying to create is effectively build automation for which there are some excellent continuous integration products available. My advice would be to jump on the free, Professional version of TeamCity and use this to orchestrate your builds. It plays great with SVN and has built-in Visual Studio and MSBuild runners.
While you're there, unless you're trying to do something very bespoke, take a look at using Web Deploy to push the app out. There's a five part blog series titled You're deploying it wrong! which walks you through the entire process.


text:
Q: Facebook Graph API: Can't get user gender using curl I used the following command:
curl -i -X GET "https://graph.facebook.com/me?fields=gender,email,id,name,likes,birthday&access_token=XXX"

But the response I get doesn't have the field gender
{"email":"XXX\u0040gmail.com","id":"XXX","name":"XXX","likes":{"data":[{...}],"paging":{"cursors":{"before":"XXX","after":"XX"}}},"birthday":"XX\/XX\/XXXX"}

My APP is in development state and user_gender permission is enabled as well as user_birthday. I got access token by using PHP SDK.
    $loginUrl = $helper->getLoginUrl($redirect_url, array(
        'email',
        'user_birthday',
        'gender',
        'user_location',
        'user_likes'
    ));

A: Under the permissions, put user_gender


text:
Q: Snap packages can't use my SSH key I have installed GitKraken, a git client, through snappy.
$ sudo snap install gitkrakren

But when I try to push to my repository, I get an authentication error. This was weird since I can make the push from the terminal without problems. So I went into the configuration and tried to manually set the public and private key. But when I tried to open the folder ~/.ssh I got a message that it was forbidden.

*

*Could it be that GitKraken uses its own SSH keys, since it is a snap package?

*Is there a way to make it use my own keys or am I forced to use the SSH keys from the snap package?

*If it is the last case, where can I find them?

A: It is intentional that by default confined snaps cannot access your ssh keys (or indeed anything in hidden folders/files in your home directory) for good reason. You don't want a random application grabbing your keys and sending them to a remote server.
You can however copy all or some of your keys from ~/.ssh into the home directory the snap sees under ~/snap/gitkraken/current/

A: Since there is a reason NOT to allow snaps to access your .ssh directly I would advice to copy only PUB key to a 'readable' folder.
I created a second .sshpub folder and copied over only the public keys to it, not the private ones.
mkdir ~/.sshpub
cp ~/.ssh/*.pub ~/.sshpub


text:
Q: Cloud Functions for converting PDF to image I've setup a cloud function with guidance from this post Cloud Functions for Firebase - Converting PDF to image
When running the function it runs without errors but the image is not created.
const tempDir = os.tmpdir()
await new Promise(function (resolve, reject) {
  gs()
    .batch()
    .nopause()
    .executablePath('lambda-ghostscript/bin/./gs')
    .option('-dTextAlphaBits=4')
    .res(300)
    .device('jpg')
    .output(`${tempDir}/page-01.jpg`)
    .input(filepath)
    .exec(function (err, stdout, stderr) {
        if (!err) {
          console.log('gs executed w/o error');
          console.log('stdout',stdout);
          console.log('stderr',stderr);
          resolve();
        } else {
          console.log('gs error:', err);
          reject(err);
        }
    });
});
fs.lstat(tempDir+'/page-01.jpg', (err, stats) => {
  if(err)
      return console.log(err); //Handle error
  console.log(`Is file: ${stats.isFile()}`);
});

This is the output when checking if the new file was created:
gs command: -dBATCH,-dNOPAUSE,-dTextAlphaBits=4,-r300,-sDEVICE=jpg,-sOutputFile=/var/folders/dd/zdnq1dcn2vb328ntxxt7_97c0000gn/T/page-01.jpg,/var/folders/dd/zdnq1dcn2vb328ntxxt7_97c0000gn/T/m5YF7ipQsLCuTE9c0pWC_raw.pdf
info: gs executed w/o error
info: stdout
stderr undefined
info: { Error: ENOENT: no such file or directory, lstat '/var/folders/dd/zdnq1dcn2vb328ntxxt7_97c0000gn/T/page-01.jpg'
  errno: -2,
  code: 'ENOENT',
  syscall: 'lstat',
  path: '/var/folders/dd/zdnq1dcn2vb328ntxxt7_97c0000gn/T/page-01.jpg' }```

A: The error you are getting is because you are trying to write in a file which does not exist, or it is not writable.
I suppose that the "fs" variable comes from filesystem. Note that, as it is stated in the official documentation:

The only writeable part of the filesystem is the /tmp directory, which you can use to store temporary files in a function instance. This is a local disk mount point known as a "tmpfs" volume in which data written to the volume is stored in memory. Note that it will consume memory resources provisioned for the function.

The "var" directory in which you are trying to write is read-only and accessible to the function.
My suggestion is to try to modify the parameter for the "gs().output(param)" function with something  like :
 tempPath = path.join(os.tmpdir(), newName);

Where "newName" would be the name of the image you want to create.


text:
Q: When talking about many things that all have one thing, do you use the plural or singular? If you have something like:

Get the name(s) of all users.

Should name be singular or plural?
The way I see it, each user has only one name, so it could be singular, but you will be getting many names, one for each users, so it could also be plural. Anyone know what is the proper way?

A: When used with the word all, the plural is preferred in order to match the plural users:

Get the names of all users.

With the word each, the singular is preferred in order to match the singular user:

Get the name of each user.

However, even in this latter case, some people would accept or prefer names. There is not a hard-and-fast rule in this case, though in general English speakers err on the side of using the plural.

A: You want names, so names is correct.  Consider 'age' instead of 'name'.  You may ask for the age of all kids in one grade at school, but you would ask for the ages of the kids from all grades that do music.
And definitely each user.


text:
Q: Autorotation unicorn log file I have unicorn config file in rails application:
config/unicorn.rb
app_name = "my_app"
root = "/home/user/my_sites/#{app_name}/current"

working_directory root
pid "#{root}/tmp/pids/unicorn.pid"
stderr_path "#{root}/log/unicorn.err.log"
stdout_path "#{root}/log/unicorn.out.log"

listen "/tmp/unicorn.#{app_name}.sock"
worker_processes 2
timeout 30

before_exec do |_|
  ENV["BUNDLE_GEMFILE"] = File.join(root, 'Gemfile')
end

How can auto rotate these log files?
For rails app and rails log I do:
Rails.logger = Logger.new(Rails.root.join("log",Rails.env + ".log"), 3, 20*1024*1024)
What is the best solution for unicorn?

A: Under /etc/logrotate.d  create a file name called unicorn (or the name of your app) and add below lines
/var/log/unicorn/*log {
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 $(cat /var/log/unicorn/unicorn.pid 2>/dev/null) 2>/dev/null || :
    endscript
}

According to Unicorn's documentation:

USR1 - reopen all logs owned by the master and all workers See Unicorn::Util.reopen_logs for what is considered a log.

So /bin/kill -USR1 will send this signal to the unicorn's process using its pid from /var/log/unicorn/unicorn.pid (you may need to update according to yours).
postrotate is executed at end of logrotate's rotation.

A: Use logrotate
See https://stackoverflow.com/a/4883967/159721 for details


text:
Q: Using avconv to select only one audio channel in output I have a two-channel AAC file and I am trying to get two separate AAC files, each of which with one of the two channels in the original AAC file. Is there an option in avconv that does that?
Something like:
avconv -channel=0 -i input.aac input_ch1.aac

avconv -channel=1 -i input.aac input_ch2.aac

A: Solved.
This works for an input stereo aac file that has front left and front right channels.
avconv -i input.aac -filter_complex channelsplit="channel_layout=2[FL][FR]" -map [FL] channel1.aac -map [FR] channel2.aac
In case your input file has more than two channels, you can map each channel (either by name as in FL, or by their index starting from zero) to a separate single-channel file.

A: Assuming you're referring to channels (as opposed to streams), the following ffmpeg command should work:
ffmpeg -i input.aac -map_channel 0.0.0 left.aac -map_channel 0.0.1 right.aac


text:
Q: Restkit 0.20: Handling mapping to abstract entities My app can receive something like the following from the server:
{
    'data': [{
          'class': 'B',
          'id': ...,
          ...
     },
     {
          'class': 'C',
          'id': ...,
          ...
     }]
}

where B and C are descendents of A.
In my app, my coredata model reflects the server i.e. an abstract entity A and descendents B andC. Using the above response I then need to map data[0] and data[1] onto entities of type B and C respectively.
As far as I can tell so far, RESTKit is only able to discern how to map an entity via the URL pattern and a key path e.g.:
RKResponseDescriptor *resourceDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"A/" keyPath:@"data" statusCodes:[NSIndexSet indexSetWithIndex:HttpResponseCodeSuccess]];

which means that the above objects end up being mapped onto entities of type A. Am I wrong in this? If not are there any ways round this?

A: You're half right, RestKit can also use dynamic mapping. But that won't really help you (mainly because the data is an array).
The only workaround (and it is a workaround because RestKit is not designed for this scenario) would be to create response descriptors for each entity type and allow them all to run on the response. Then, use KVC validation to reject any mappings which are for the wrong class type.
It would be sensible to use mogenerator so that your model classes are maintained sensibly as your validation logic would live there.


text:
Q: Active Admin Name Error uninitializedconstant Resource::Users So I have a couple of models in my app and they are all registered with ActiveAdmin. They all work great except for one and I can't figure out why. I keep getting the same error:

NameError at /admin/reports
  uninitialized constant Report::Users

The model that it is happening on is called Report
    class Report < ActiveRecord::Base
      belongs_to :users
      belongs_to :cars
      enum reason: [:accident,:totaled,:stolen]
      validates :reason, presence:true
    end

The controller looks like this:
Class ReportsController < ApplicationController
  before_action :authenticate_user!

  def create
    @car=Car.find(params[:car_id])
    @report=@car.reports.build(report_params)
    @report.user_id=current_user.id
    @report.car_id=@car.id
    if @report.save
      redirect_to car_path(car)
    else
      render 'new'
    end
  end

  def destroy
    @report=Report.find(params[:id])
    @report.destroy
  end

  private
  def report_params
    params.require(:report).permit(:reason)
  end
end

This is the migration used to create the model:
class CreateReports < ActiveRecord::Migration
  def change
    create_table :reports do |t|
      t.references :user, index: true
      t.references :car, index: true
      t.integer :reason, default: 0

      t.timestamps null: false
    end
    add_foreign_key :reports, :users
    add_foreign_key :reports, :cars
  end
end

Lastly here is the active_admin app/admin/report.rb:
ActiveAdmin.register Report do

# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
#   permitted = [:permitted, :attributes]
#   permitted << :other if resource.something?
#   permitted
# end

end

I have been trying to figure it out for a couple of hours. Solutions that I saw on SO that don't work. I ran rails generate active_admin:resource Report to create it so it is singular.  Why is it misbehaving?

A:
NameError at /admin/reports uninitialized constant Report::Users

Association name for a belongs_to should be singular as per naming conventions.
class Report < ActiveRecord::Base
belongs_to :user #here
belongs_to :car #and here too
enum reason: [:accident,:totaled,:stolen]
validates :reason, presence:true
end


text:
Q: can not set datatable's width of jquery's datatable plugins 10.1 I have many datatables of jQuery plugin in the page. For some datatables, the with fit with the page, but for others, the datatable's width is more larger than the page. I have tried a lot of things without success:
-set style in html
-use this function of datatables
fnInitComplete : function() {
   $("#tableid").css("width","100%");
}

. with these method, I have not been able to set it properly and don't know how to do this.

A: if you table columns are so much to fit in the page width, then you can use datatable responsive plugin example is here
https://datatables.net/extensions/responsive/examples/column-control/auto.html
if you table columns are enough to fit in the page then it would take the width automatically, if you are using bootstrap add class in the table tag.
for ex.

with css use
max-width:100%

A: Just set table width to 100%


text:
Q: Calling a function with a string as the command / dynamic Function Name? I'm working full-stack on a project, and I've run into a bit of a situation that I think I'll need to resolve fully so I can re-use it in future projects (fairly new to Node, but tons of programming languages and syntax under my belt), so a dirty fix might not be the best (eval()?) I have 3 files, here is an example of the logic:
// main.js
const call = require('./test.js');
config = require('config');
configObj = config.get('Site')
sites = Object.keys(configObj);
siteObj = config.get('Site' + "." + sites[0]); // This only calls Amazon, but in the real project it is a dynamic element
var callCommand = "call." + siteObj.functionCall + "(siteObj)"; // evaluates as call.amazon(siteObj)
setTimeout(() => {callCommand;}, 1500);     // This does not work
setTimeout(() => {call.amazon(siteObj);}, 1500);    /// This works

// default.json
{
"Site": {
        "Amazon": {
            "homePage": "https://www.amazon.com/",
            "functionCall": "amazon"
        }
}

// test.js
function amazon(siteObj) {
// some code
console.log("reached the function");
}

Basically, I'm going to be calling different functions from main.js, targeting the test.js. I need the function call to be dynamic, because it is based on the Site's callFunction key. For instance, once there are 10 sites, maybe it would call "call.xxxxxxx(siteObj)", instead. The string creating the call does not seem to be working, I think because it's a String and the line is looking for a function to execute. I get that, but again, I'm fairly new to Node/JS in general and I'm not exactly sure how to even word the question. I thought simply placing the proper text of the function call as a string would cause JS to execute that text, but I guess not.
Am I missing something simple? I know I will need dynamic function calls in the future of this project, and others, so while I can write logic in test.js or main.js to work around THIS example, writing separate function calls for each Site:
if (sites[0]) {call.amazon(siteObj);
if (sites[1]) {call.ebay(siteObj);

for instance, will get cumbersome, as the Sites list will only grow.
Therefore, we created the callFunction key to try and give each object it's exact call.
I'm not sure if it's parenthesis placement, or the way arrow functions work for the setTimeout, or what it is, but I've tried different instances of:
setTimeout(() => {call.$(siteObj.functionCall)(siteObj);}, 1500);     // This does not work
setTimeout(() => {call.$(siteObj.functionCall)(siteObj))); }, 1500) // This does not work

I'm not sure how to use a regular variable, or an object's key properly in this instance to fetch "amazon", especially with the (siteObj) parameter.
and things like that. I am hoping more to be able to one-liner it like that SOMEHOW, but I don't know all of the tricks of this language yet.
I've also tried:
var callCommand = "call." + siteObj.functionCall + "(siteObj)"; // evaluates as call.amazon(siteObj)
var codeToExecute = callCommand;
var tmpFunc = new Function(codeToExecute);
setTimeout(() => {tmpFunc(); }, 1500);

With the above, I get "call" is not defined.
It works with the explicit text in there (call.amazon(siteObj)), but I need that "amazon" to be dynamic, preferably called from it's config key (even if I need to turn that key into a json formatted function).
I know this a huge wall of a read, but it is my first post here. Thanks in advance! Hopefully I formatted and named this post correctly without causing too much of a headache, I apologize if I did.
So, am I missing something simple? I feel like I am, but I'm not new to coding at all, and I am alone on this project (no other developers), and I'm trying to keep it good practice without too many, or any, dirty workarounds. Thank you!

A: setTimeout(() => {callCommand;}, 1500);

That evaluates the string and does nothing.
You can dynamically call the function from the exported object:
call[siteObj.functionCall](siteObj)

This way you access the object with the functions, that is the module exported, using the property that holds the function, and call it
const call = require('./test.js');

Is giving you something similar to
{
  amazon: function() {}
}

Which is just an object
And as you want to dynamically access it, you have to use brackets instead of the dot notation, which allows you to access an object using a variable


text:
Q: Probability of alternating shirts 5 men are wearing red shirts and 5 men are wearing blue shirts. If the 10 men are lined up randomly, what is the probability that the colors will alternate?
My attempt: I started out by assuming that the first person was blue, and analyzing each sequential person case by case, I got $$\underbrace{\frac{5}{10}}_\text{blue}\cdot\underbrace{\frac{5}{9}}_\text{red}\cdot\underbrace{\frac{4}{8}}_\text{blue}\cdot\underbrace{\frac{4}{7}}_\text{red}\cdot\underbrace{\frac{3}{6}}_\text{blue}\dots,$$ and multiplying that by 2 (since the probability given the the first person chosen was wearing a red shirt should be the same), I got an answer of $$2\bigg(\frac{(5!)^2}{10!}\bigg)=\frac{1}{126}.$$ Is this right? And if it is, is there an easier way of going about this?


text:
Q: Hide default message of ais-state-results widget I am using ais-instant-search and ais-state-results to display my data. I hide the result until query.length > 0. It works but if I don't enter any search string, it always shows a message. Below are my code and screenshot:

<ais-state-results>

                Not found for: <q>{{ query }}</q>

            <template v-else slot-scope="{ query }">
                <ais-hits v-if="query.length > 0">
                    <template slot="item"
                            slot-scope="{ item }"
                    >

                            <ais-highlight
                                    :hit="item"
                                    attribute="name"
                            />

{{ item.price }}

                    </template>
                </ais-hits>
            </template>
        </ais-state-results>

A: The widget <ais-state-results> contains a fallback content which renders when the default slot is empty (this is the screenshot you gave). Both conditions you've written inside your example are false once the App starts. Since nothing is rendered inside the slot the default one kicks in. You can solve this issue with an empty div when none of the conditions are met. Here is an example:
<ais-state-results>
  <template slot-scope="{ query, hits }">

Not found for: <q>{{ query }}</q>

    <ais-hits v-else-if="query" />

  </template>
</ais-state-results>

You can find a live example on CodeSandbox.