text:
Q: How to display custom image on cart page in magento I want to display custom image of product on cart page in Magento.
Config.xml file
<checkout>
    <rewrite>
        <cart_item_renderer>ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer</cart_item_renderer>
    </rewrite>
</checkout>

I have added below code in Block/Checkout/Cart/Item/Renderer.php file
<?php
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{

    public function getProductThumbnail()
    {
        $item = $this->_item;
        $customize_data = $item->getData('customize_data');
        $customize_image = $item->getData('customize_image');

        $results_data = $item->getOptionByCode("customizer_data")->getValue();
        if(!is_null($results_data)){
            $results = unserialize($results_data);
            $path = Mage::getBaseDir()."/skin/";
            $_product = $item->getProduct()->load();
            $customize_image = $this->helper('catalog/image')->init($_product, 'thumbnail',$path.'adminhtml/default/default/images/logo.gif');

            //$customize_image = $this->helper('catalog/image')->init($_product, 'thumbnail',$results['image']);
        }

        if (!empty($customize_image)) {
            return $customize_image;
        } else {
            return parent::getProductThumbnail();
        }
    }
}

I have tried $customize_image with image "URL", "Path" and "Data (data:image/png;base64,iVBORw0KG....)" but it is not working.

A: So here is the idea. The init function you are calling is creating the issue for you. Do something like this as you have already done the override of that class.
public function getProductThumbnail1()
    {
        if (!is_null($this->_productThumbnail)) {
            return $this->_productThumbnail;
        }
        return $this->getSkinUrl('images/jhonson.jpg');
        //return $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail');
    }

Add this function in that class you have already overridden which is Mage_Checkout_Block_Cart_Item_Renderer. Now in your app/design/frontend/rwd/default/template/checkout/cart/item/default.phtml file or whatever your file is call this function like this echo $this->getProductThumbnail1() rather than this echo $this->getProductThumbnail()->resize(180).

A: I have found solution. You have override Core class, I have added below class.
Create helper "Customezerimage.php" in Helper in custom module
<?php
class ProductCustomizer_ProductCustomizer_Helper_Customezerimage extends Mage_Catalog_Helper_Image {
    public function setCustomeImage($path){
        $this->_imageFile = $path;
        $this->_setModel(Mage::getModel('productcustomizer/product_image'));
        $this->_getModel()->setCustomeBaseFile($this->_imageFile);
        return $this;
    }
    public function __toString() {
        try {
            $model = $this->_getModel();
            $url = $model->getUrl();
        } catch (Exception $e) {
            $url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
        }
        return $url;
    }
}

Create Model "Image.php" in Model/Product directory in custom module.
    <?php
class ProductCustomizer_ProductCustomizer_Model_Product_Image extends Mage_Catalog_Model_Product_Image{

    public function setCustomeBaseFile($baseFile){
        if (!file_exists($baseFile)) {
            throw new Exception(Mage::helper('catalog')->__('Image file was not found.'));
        }
        $this->_newFile = $this->_baseFile = $baseFile;
        return $this;
    }

    public function saveCustomeImage($file = ""){
        if(empty($file)){
            $file = $this->_newFile;
        }
        Mage::log($file);
        $this->getImageProcessor()->save($file);
        return ;
    }

    public function getUrl(){

        $baseDir = Mage::getBaseDir();
        $path = str_replace($baseDir . DS, "", $this->_newFile);
        return Mage::getBaseUrl() . str_replace(DS, '/', $path);
    }
}

Now you can set custom image path that you want to display in cart like below
<?php
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{
    public function getProductThumbnail()
    {
        $item = $this->_item;
        $customize_data = $item->getData('customize_data');
        $customize_image = $item->getData('customize_image');

        $results_data = $item->getOptionByCode("customizer_data")->getValue();
        if(!is_null($results_data)){
            $results = unserialize($results_data);
            $imagePathFull = $customize_image;

            $_product = $item->getProduct();
            $image = $imagePathFull;
            return $this
                ->helper('productcustomizer/customezerimage')
                ->init($_product, 'thumbnail')->setCustomeImage($image);
        }else{
            return parent::getProductThumbnail();
        }
    }
}


text:
Q: How do I read functional composition in es6/javascript? Background:

Composition is putting two functions together to form a third function where the output of one function is the input of the other.

No matter how much I look at this I struggle with how to read it.  In particular why the compose() return => (a) => captures the 121.2121212 in local scope. Also I struggle with how final fn f(g(a)) would look with all the values/fn present w/o the use of variables.
Question: Does anyone have any techniques or diagrams for quickly reading examples like this; how can I mentally debug and follow the function flow?
Reference:
const compose = (f, g) => (a) => f(g(a)) // Definition
const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage

floorAndToString(121.212121) // '121'

A: As mentioned by T.J. Crowder, it often helps rewriting arrow functions as regular functions. So the function:
const compose = (f, g) => (a) => f(g(a))

Can be rewritten as:
function compose (f, g) {
    return function (a) {
        return f(g(a));
    }
}

Now it is perhaps more obvious what's going on. So now let's rewrite the other parts:
const floorAndToString = compose((val) => val.toString(), Math.floor)

Can be rewritten as:
function convertToString (val) { return val.toString() };

const floorAndToString = compose(convertToString, Math.floor);

Now it may be more obvious that the compose function will return the function:
// remember that we pass `convertToString` as `f`
// and `Math.floor` as `g`:

function (a) {
    return convertToString(Math.floor(a));
}

So it's obvious that the function floorAndToString simply returns the result of convertToString(Math.floor(a)). There is nothing special about compose that captures 121.2121212 because it doesn't. Instead it creates a function where 121.2121212 can be passed as an argument to convertToString(Math.floor(a)).

A: It might help to look at the Wikipedia article for function composition. But I think your problem is not really related to function composition but to the arrow notation in general.
Maybe it helps to look at a simpler example first:
const addOne = (x) => x + 1
const addN = (n) => (x) => x + n
const addSeven = addN(7)

The last line produces a new function that adds seven to the input (x) => x + 7. You can think of the parameter tuples between the arrows as being filled from left to right when values are provided (and the variables to the right are bound to these values). As long as you don't provide all parameters, you will obtain a new function.
You can also provide all parameters like this:
addN(5)(3) // yields 8

Note that addN can be seen as taking two parameters but in separate bracket pairs. The arrows between the brackets in the definition kind of allow you to omit parameters to the right and obtain a function with fewer parameters with the left ones being already fixed.
Let's look at an alternative definition of compose:
const weirdCompose = (f, g, a) => f(g(a))

It should be clear how it works, but the problem is that you cannot use this to compose two functions without evaluating the result of the composition with the value a right away. By separating the parameters into two groups you can partially apply the function and only provide f and g in a first step.
To understand this better, I suggest you also have a look at the concept of currying

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add balloons in OpenStreetMap? How do I add balloons like those on Google Maps (such as the one shown here) into OpenStreetMap? This is my OpenStreetMap code below:
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;

public class MainActivity extends Activity {

MyItemizedOverlay myItemizedOverlay = null;
  private MapController myMapController;

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    myMapController = mapView.getController();
    myMapController.setZoom(16);

    Drawable marker=getResources().getDrawable(android.R.drawable.star_big_on);
    int markerWidth = marker.getIntrinsicWidth();
    int markerHeight = marker.getIntrinsicHeight();
    marker.setBounds(0, markerHeight, markerWidth, 0);

    ResourceProxy resourceProxy = new
   DefaultResourceProxyImpl(getApplicationContext());

    myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
    mapView.getOverlays().add(myItemizedOverlay);

    GeoPoint myPoint1 = new GeoPoint(24.893379000000000000, 67.028060900000010000);
    myItemizedOverlay.addItem(myPoint1, "myPoint1", "myPoint1");
    GeoPoint myPoint2 = new GeoPoint(24.824796300000000000, 67.031565699999990000);
    myItemizedOverlay.addItem(myPoint2, "myPoint2", "myPoint2");

  }

}

import java.util.ArrayList;

import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IMapView;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import android.graphics.Point;
import android.graphics.drawable.Drawable;

public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {

    private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();

    public MyItemizedOverlay(Drawable pDefaultMarker,
       ResourceProxy pResourceProxy) {
     super(pDefaultMarker, pResourceProxy);
       // TODO Auto-generated constructor stub
     }

     public void addItem(GeoPoint p, String title, String snippet){
        OverlayItem newItem = new OverlayItem(title, snippet, p);
        overlayItemList.add(newItem);
        populate();
     }

     @Override
     public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3) {
       // TODO Auto-generated method stub
       return false;
     }

     @Override
     protected OverlayItem createItem(int arg0) {
       // TODO Auto-generated method stub
       return overlayItemList.get(arg0);
     }

     @Override
     public int size() {
       // TODO Auto-generated method stub
       return overlayItemList.size();
     }

}

A: I was with the same question and now I found a way:

*

*Download the osmbonuspack here: https://code.google.com/p/osmbonuspack/

*Follow this code:
ArrayList<ExtendedOverlayItem> overlayItemArray = new ArrayList<ExtendedOverlayItem>();

ExtendedOverlayItem item = new ExtendedOverlayItem("Title, "Description, new GeoPoint(Double latitude, Double longitude), this);

//creates a layer with ballons

ItemizedOverlayWithBubble<ExtendedOverlayItem> poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, overlayItemArray, mapView, new CustomMapInfoWindow(mapView));

// add the layer
mapView.getOverlays().add(poiMarkers);

*Create a class called CustomMapInfoWindow:
import org.osmdroid.bonuspack.overlays.DefaultInfoWindow;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.views.MapView;

public class CustomMapInfoWindow extends DefaultInfoWindow {

    public CustomMapInfoWindow(MapView mapView) {
        super(R.layout.bonuspack_bubble, mapView);

    }

    @Override
    public void onOpen(ExtendedOverlayItem item) {
        super.onOpen(item);
    }
}

*Go to OSMBONUSPACKDEMO REPOSITORY and get bonuspack_bubble.xml and the drawables into drawable-mdpi folder.

A: You should take a look at the osmbonuspack library, which is an add-on for osmdroid. It includes an overlay that will display popup balloons:
https://code.google.com/p/osmbonuspack/


text:
Q: module object has no attribute after using different version of Python I have both versions python 2.7 and 3.4 installed. I am using some code which is developed under 2.7 but I am using under 3.4. So after compiling using the following command
python manage.py runserver

I get the following error -
  File "C:\pyprojects\focus\site\general\forms.py", line 26, in Meta
    model = models.UserProfile
AttributeError: 'module' object has no attribute 'UserProfile'

The directory structure is
├───focus
│   ├───data_dumps
│   ├───notes
│   ├───setup
│   └───site(main project folder)
|       └───static
|       └───general
|           +--forms.py
|           +--models.py
|       └───pro
|           └───models
|               +--__init__.py
|               +--plans.py
│       └───focus2
│           └───templates
|           +--__init__.py
│           +--settings.py
│           +--util.py
│           +--wsgi.py
│       +--manage.py

As models.py and forms.py is under same directory(general) so I have imported the model in forms.py in this way
from .models import models

Now in models.py I have defined the class
class UserProfile(models.Model, HashedPk):
        user = models.OneToOneField(User, unique=True)
        is_pro = models.BooleanField(default=False, blank=True)
        ......................................................

In forms.py the code is
class UserProfileForm(forms.ModelForm):
    class Meta:
        model = models.UserProfile
        .....................

Is there any special way to call the model in python 3.4.
Any help is highly appreciated.

A: It's sorted. The import needs to be
from . import models

instead
from .models import models


text:
Q: Why isn't the rvm installed version of Rails working? Still struggling with a pernicious bug in my rvm environment:
    rails -v
/usr/local/lib/site_ruby/1.8/rubygems/dependency.rb:296:in `to_specs': Could not find 'railties' (>= 0) among 0 total gem(s) (Gem::LoadError)
    from /usr/local/lib/site_ruby/1.8/rubygems/dependency.rb:307:in `to_spec'
    from /usr/local/lib/site_ruby/1.8/rubygems/core_ext/kernel_gem.rb:47:in `gem'
    from /usr/bin/rails:22

This looks like a path problem, because it is looking in the default Ruby that comes with Debian.  Here is my path:
/home/caseyr/.rvm/gems/ruby-2.0.0-p0/bin:/home/caseyr/.rvm/gems/ruby-2.0.0-p0@global/bin:/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin:/home/caseyr/.rvm/bin:/home/caseyr/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games
Yet, this is the default Ruby version:
ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [i686-linux]

Could it be that Rails has its own, separate path? Don't know, but this is instructive:
which rails
/usr/bin/rails

which seems to totally ignore rvm, since the path should be pointing to ruby 2.0.0. How can this be?
The gem environment seems ok:
    $ gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.0
  - RUBY VERSION: 2.0.0 (2013-02-24 patchlevel 0) [i686-linux]
  - INSTALLATION DIRECTORY: /home/caseyr/.rvm/gems/ruby-2.0.0-p0
  - RUBY EXECUTABLE: /home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin/ruby
  - EXECUTABLE DIRECTORY: /home/caseyr/.rvm/gems/ruby-2.0.0-p0/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /home/caseyr/.rvm/gems/ruby-2.0.0-p0
     - /home/caseyr/.rvm/gems/ruby-2.0.0-p0@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-rdoc --no-ri"
  - REMOTE SOURCES:
     - http://rubygems.org/

--as well as the rvm one:
<BS>$ rvm info

ruby-2.0.0-p0:

  system:
    uname:       "Linux beta 2.6.32-5-686 #1 SMP Sun Sep 23 09:49:36 UTC 2012 i686 GNU/Linux"
    system:      "debian/6.0.7/i386"
    bash:        "/usr/local/bin/bash => GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)"
    zsh:         " => not installed"

  rvm:
    version:      "rvm 1.19.6 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]"
    updated:      "8 days 17 minutes 26 seconds ago"

  ruby:
    interpreter:  "ruby"
    version:      "2.0.0p0"
    date:         "2013-02-24"
    platform:     "i686-linux"
    patchlevel:   "2013-02-24 revision 39474"
    full_version: "ruby 2.0.0p0 (2013-02-24 revision 39474) [i686-linux]"

  homes:
    gem:          "/home/caseyr/.rvm/gems/ruby-2.0.0-p0"
    ruby:         "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0"

  binaries:
    ruby:         "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin/ruby"
    irb:          "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin/irb"
    gem:          "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin/gem"
    rake:         "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin/rake"

  environment:
    PATH:         "/home/caseyr/.rvm/gems/ruby-2.0.0-p0/bin:/home/caseyr/.rvm/gems/ruby-2.0.0-p0@global/bin:/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/bin:/home/caseyr/.rvm/bin:/home/caseyr/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games"
    GEM_HOME:     "/home/caseyr/.rvm/gems/ruby-2.0.0-p0"
    GEM_PATH:     "/home/caseyr/.rvm/gems/ruby-2.0.0-p0:/home/caseyr/.rvm/gems/ruby-2.0.0-p0@global"
    MY_RUBY_HOME: "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0"
    IRBRC:        "/home/caseyr/.rvm/rubies/ruby-2.0.0-p0/.irbrc"
    RUBYOPT:      ""
    gemset:       ""

I realize there are similar questions like this have already been answered (such as this one), but have still not found one that has let me understand what's really going on (after several removals, re-installs, etc...)
Any help will be much appreciated; would really like to get Rails working again...
--rixter

A: first see which rubies are installed using rvm
rvm list

It will display ruby versions installed.
Then make use of rvm --default use ruby-2.0.0-p0
then create gemset using rvm gemset create gemset1
rvm use ruby-2.0.0-p0@gemset1

gem install rails -v rails_version

after installing try rails -v


text:
Q: How to handle graphs and read graph data using selenium webdriver when graph loads using flash player
Here the graph loads using Adobe Flash Player. When I mouseover on the graph bar it displays some text data, I want to fetch that data automatically using Selenium Webdriver.
Problem: I am unable to inspect text on the graph.

A:
"...The graph loads using Adobe Flash Player. When I mouseover on the graph bar it displays some text data, I want to fetch that data automatically using Selenium Webdriver."

Maybe Selenium Webdriver is the wrong tool for this task.
That Graph app (.swf) will getting its information from some other database (and then just displaying it as a graph). You need to access the same database / information. Usually this is stored in an XML or JSON file.

*

*Use the Developer Tools in your browser (I recommend Chrome) to check Network requests.

*Look for a new file (of type .xml or .json) being  added to the list when you refresh the chart or when you select new settings within the chart itself (eg: a new region).

*Whatever type of files requested, your required file will be text (or even HTML), so you can search and extract whatever you want from result by using String functions of Java.


text:
Q: QMenu is not displaying but still able to interact with it I have a graphic manager that is used to manage and interact with graphics using mouse input.
Inside the mousePressEvent (not overidden from QWidget, is just a normal method that gets passed mouse location and buttons from a QWidget) I create a QMenu which is displayed on right click and when clicking on a graphic.
if( button == Qt::RightButton && activeGraphic) {

        QMenu menu("Edit", view());

        QAction * deleteAction = new QAction( "Delete", &menu );
        connect( deleteAction, &QAction::triggered, [=](bool) {
            _lineGraphicHandler->releaseActiveGraphic();
            _lineGraphicHandler->removeGraphic( activeGraphic );
        });
        menu.addAction( deleteAction );

        QAction * settingsAction = new QAction( "Settings", &menu );
        connect( settingsAction, &QAction::triggered, [=](bool) {
            emit showSettings(QString::fromStdString(activeGraphic->type()));
        });
        menu.addAction( settingsAction );

        connect( &menu, &QMenu::aboutToHide, [=] {
            qDebug() << "menu closing";
        });
        connect( &menu, &QMenu::aboutToShow, [=] {
            qDebug() << "menu opening";
        });

        menu.exec( view()->mapToGlobal( pos.toPoint() ) );
    }

This code is used within two different projects and in one project the menu is displayed as expected and in the other project the menu is not visible but able to accept mouse clicks (I originally had a problem with the menu immediately being closed).
The difference between the projects is in the widget hierarchy within which the QMenu resides.
failing project
graphichanlder - QObject
graphicsmode - QObject
graphicwidget - QFrame
graphicsview - QGraphicsView

working project
graphichanlder - QObject
graphicsmode - QObject
videotile - QGraphicsObject
graphicsScene - QGraphicsScene

What am I doing that could be causing this behavior?

Fixed
Discovered this bug https://bugreports.qt-project.org/browse/QTBUG-7556 which explained the problem I was having. Fixed by adding a margin around my QGLWidget so it is no longer fullscreen.


text:
Q: Extrat data from rest post node js I use the request library to develop service post:
var request = require('request');

request.post(
    'http://localhost:3000/carica',
    { json: { id: "", input: 52, rfid:"M2" } },
    function (error, response, body) {
            console.log(body)
    }
);

The question is the following: how can I extrat this data in my server? I want to handle the information not as json object but as string(for the field rfid) or as numeric type(for the field input).


text:
Q: What is the Purpose of Console.WriteLine() in Winforms I once saw the source code of a winform application and the code had a Console.WriteLine();. I asked the reason for that and i was told that it was for debugging purposes.
Pls what is the essence of Console.WriteLine(); in a winform and what action does it perform because when i tried using it, it never wrote anything.

A: Winforms are just console apps that show windows. You can direct your debug info to the console app.
As you can see in the below example there is a command that attaches the parent window then pumps info to it.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MyWinFormsApp
{
    static class Program
    {
        [DllImport( "kernel32.dll" )]
        static extern bool AttachConsole( int dwProcessId );
        private const int ATTACH_PARENT_PROCESS = -1;

        [STAThread]
        static void Main( string[] args )
        {
            // redirect console output to parent process;
            // must be before any calls to Console.WriteLine()
            AttachConsole( ATTACH_PARENT_PROCESS );

            // to demonstrate where the console output is going
            int argCount = args == null ? 0 : args.Length;
            Console.WriteLine( "nYou specified {0} arguments:", argCount );
            for (int i = 0; i < argCount; i++)
            {
                Console.WriteLine( "  {0}", args[i] );
            }

            // launch the WinForms application like normal
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );
            Application.Run( new Form1() );
        }
    }
}

Here is the resource for this example:http://www.csharp411.com/console-output-from-winforms-application/

A: You wouldn't really use it normally but if you've attached a Console or use AllocConsole, it will function like in any other console application and the output will be visible there.
For quick debugging, I prefer Debug.WriteLine but for a more robust solution, the Trace class may be preferable.

A: It wouldn't perform anything unless the Console was redirected to say the Output window. Really, they should be leveraging Debug.WriteLine instead.
The benefit of Debug.WriteLine is that it gets optimized away when building in Release mode.
NOTE: as pointed out by Brad Christie and Haedrian, apparently it will in fact write to the Console window in Visual Studio when running a Windows Forms application. You learn something new every day!

A: It writes to the Console.
The end user won't see it, and to be honest its much cleaner to put it into a proper log, but if you run it through VS the Console window will populate.


text:
Q: How would I implement a Round Robin scheduling simulator? Using a deque of structs that look like this:
struct{
    int ID;
    int arrivalTime;
    int burstTime;
};

How would I step through the deque of structs so that if the input where like this:
0 0 3
1 5 2
3 8 4

where each row is a struct's ID, arrivalTime, and burstTime respectively, I would be able to print out something like this:
Time 0 Process 0 is running
Time 2 Process 0 is running
Time 3 Processor is Idle
Time 5 Process 1 is running
Time 7 Processor is Idle
Time 8 Process 3 is running
Time 10 Process 3 is running

this output is assuming a time quantum of 2. Is there a way to do this with just one deque or would it be easier to create another deck as a FIFO queue to process this? I know I'll need an integer to keep track of how much time has elapsed, but other than that this problem is really stumping me. Its the idle time that throws me off. Any help in C++ code or even psuedocode would really help. Thanks!

A:
I know I'll need an integer to keep track of how much time has elapsed

I would start with three values - elapsed time, current process and next process. Your scheduling loop might look something like below. I've put the logic choosing next process to a standalone function for the sake of simplicity:
time = 0;
currentProcess = deque.end();
while(some processes remaining)
{
    nextProcess = getNextProcess(time, currentProcess, deque);

    if(nextProcess->arrivalTime > time)
    {
        // nothing to do now
        // advance time by smaller of quota or nextProcess->arrivalTime
    } else {
        // at least one process has work ready
        if(currentProcess != nextProcess)
        {
            // preemt currentProcess
            // start nextProcess
            // advance time by the smaller of quota or nextProcess->burstTime
            // reduce nextProcess->burstTime by the time advanced
        } else {
            // continue with current process for quota or its remaining burstTime
            // reduce its burstTime
        }
    }

    currentProcess = nextProcess;
}

Implementing getNextProcess depends on your priority criteria, a naive approach might look like this:

*

*You go through deque starting at position currentProcess + 1. When you hit the end, continue from beginning.

*Take note of the process with smallest arrivalTime that is greater than time. Lets call it closestCandidate

*If you find suitable process with arrivalTime <= time and burstTime > 0, return that

*If you hit currentProcess again, decide between currentProcess and closestCandidate which is better to process and return that.

One last thing to do is to effectively implement the looping condition. I will leave that for you to figure out.
NOTE: Im not sure if deque is the best container here, I would pobably use forward_list and delete the processes as they finish. You could do this in the deque too, but thats O(n) operation.


text:
Q: What are the list of OS that have Python preinstalled and which versions? As I am moving from C# to Python, I was wondering if there is a list of the pre-installed versions of Python on different Operating Systems like Windows, Linux, etc...

A: There is no such list. However, I think you can safely assume every generic, modern Linux distro will have Python installed (every recent (>2years) with Python 2.5 at least), as well as most Unix SOs (FreeBSD, Solaris etc.). Mac OS X also comes with Python. OTOH you cannot expect it from most Window machines - just a few have Python by default. This usually is no problem, however, because Python is fairly easy to install and, in the end, you can rely on things such as py2exe and cx_freeze.
This is, of course, a rule of thumb, not a really precise answer. Nonetheless, I find that those assumptions make sense enough.


text:
Q: Have to click twice to run a function via Bootstrap buttons plugin Why I have to click twice to run a function that uses active class added by Bootstrap buttons plugin?
var monthly = $("input[name='montly_total']");
var once = $("input[name='once_total']");

$(".button-selector").click(function () {
 $(".button-selector.monthly.active").sum("click", monthly);
 $(".button-selector.once.active").sum("click", once)
});

Live example: http://jsfiddle.net/ynts/3Z6sm/. Inputs are updated only on a second click on a button.

A: Those buttons are a pain to use, because they don't fire any custom event you can hook your functionality onto.
That said, here's an ugly setTimeout() workaround:
$(".button-selector").click(function () {
    // break out of click handler chain
    setTimeout(function() {
        // by the time this runs, the active state will have been updated
        $(".button-selector.monthly.active").sum("click", monthly);
        $(".button-selector.once.active").sum("click", once)
    }, 0);
});


text:
Q: Conda can't find packages at pypi.org/simple I have a problem with installing packages via conda. It can not find any package in channel https://pypi.org simple.
conda install logbook

returns:
PS C:\WINDOWS\system32> conda config --add channels
https://pypi.org/simple
Warning: 'https://pypi.org/simple' already in 'channels' list, moving to the top
PS C:\WINDOWS\system32> conda install Logbook
Fetching package metadata ....
WARNING: The remote server could not find the noarch directory for the
requested channel with url: https://pypi.org/simple

It is possible you have given conda an invalid channel. Please double-check
your conda configuration using `conda config --show`.

If the requested url is in fact a valid conda channel, please request that the
channel administrator create `noarch/repodata.json` and associated
`noarch/repodata.json.bz2` files, even if `noarch/repodata.json` is empty.
$ mkdir noarch
$ echo '{}' > noarch/repodata.json
$ bzip2 -k noarch/repodata.json
...........

PackageNotFoundError: Packages missing in current channels:

  - logbook

We have searched for the packages in the following channels:

  - https://pypi.org/simple/win-64
  - https://pypi.org/simple/noarch
  - https://repo.continuum.io/pkgs/main/win-64
  - https://repo.continuum.io/pkgs/main/noarch
  - https://repo.continuum.io/pkgs/free/win-64
  - https://repo.continuum.io/pkgs/free/noarch
  - https://repo.continuum.io/pkgs/r/win-64
  - https://repo.continuum.io/pkgs/r/noarch
  - https://repo.continuum.io/pkgs/pro/win-64
  - https://repo.continuum.io/pkgs/pro/noarch
  - https://repo.continuum.io/pkgs/msys2/win-64
  - https://repo.continuum.io/pkgs/msys2/noarch

I have checked manually in browser, that the logbook module is in the list on page https://pypi.org/simple.
hoever, it seems that conda seeks packages in https://pypi.org/simple/win-64, but the win-64 directory does not exist there.
conda config --show says, that configured channel is https://pypi.org/simple
add_anaconda_token: True
add_pip_as_python_dependency: True
allow_non_channel_urls: True
allow_softlinks: False
always_copy: False
always_softlink: False
always_yes: False
anaconda_upload: None
auto_update_conda: True
changeps1: True
channel_alias: https://conda.anaconda.org
channel_priority: True
channels:
  - https://pypi.org/simple
  - https://pypi.org/simple/
  - defaults
client_ssl_cert: None
client_ssl_cert_key: None
clobber: False
create_default_packages: []
custom_channels:
  pkgs/main: https://repo.continuum.io/
  pkgs/free: https://repo.continuum.io/
  pkgs/r: https://repo.continuum.io/
  pkgs/pro: https://repo.continuum.io/
  pkgs/msys2: https://repo.continuum.io/
  C:/Program%20Files/Anaconda3/conda-bld: file:///

Any advice?

A: A conda channel has to have a specific layout (win-64, win-32, ...) and the package has to be built in a conda-specific way (see Building conda packages with conda skeleton). The packages are generally build against specific Python versions (although there should also be noarch packages) and/or numpy versions and for different platforms (windows, linux, mac 32bit or 64bit).
You cannot directly install packages from PyPI using conda because PyPI doesn't qualify as conda-channel and even if it were the packages there aren't build like conda-packages. But you can install them using pip (within conda).
But: You could check if the packages you want are distributed in a conda-conforming channel (a very popular channel currently is conda-forge). At a first glance several channels contain a package named logbook in the anaconda cloud (search results for logbook).
If you find a channel that distributes the desired version of your package (and against the desired Python version and platform) then just use:
conda install -c channel_name logbook

A: Many Python products are available for Windows on the Gohlke page.
Assuming you have 64-bit Py3.6 installed in its own environment, called Py36, you can do this.
Download Logbook-1.1.0-cp36-cp36m-win_amd64.whl from Gohlke (or whatever version it is that you need).
Then within a command prompt:

*

*activate the conda environment where you want to install Logbook.

*Use pip to install the whl that you have downloaded within that environment.

*Verify success, if you wish.

C:\scratch>activate Py36

(Py36) C:\scratch>pip install Logbook-1.1.0-cp36-cp36m-win_amd64.whl
Processing c:\scratch\logbook-1.1.0-cp36-cp36m-win_amd64.whl
Installing collected packages: Logbook
Successfully installed Logbook-1.1.0

(Py36) C:\scratch>conda list
# packages in environment at C:\ProgramData\Miniconda3\envs\Py36:
#
beautifulsoup4            4.6.0                     <pip>
certifi                   2017.11.5        py36hb8ac631_0
chardet                   3.0.4                     <pip>
idna                      2.6                       <pip>
Logbook                   1.1.0                     <pip>
opencv-python             3.4.0+contrib             <pip>
pip                       9.0.1            py36h226ae91_4
python                    3.6.3                h3b118a2_4
requests                  2.18.4                    <pip>
setuptools                36.5.0           py36h65f9e6e_0
urllib3                   1.22                      <pip>
vc                        14                   h2379b0c_2
vs2015_runtime            14.0.25123           hd4c4e62_2
wheel                     0.30.0           py36h6c3ec14_1
wikipedia                 1.4.0                     <pip>
wincertstore              0.2              py36h7fe50ca_0

Edit: Answer to query in comment.
I entered this:
conda env export -n Py36 -f Py36.yml

Content of yaml file.
name: Py36
channels:
- defaults
dependencies:
- certifi=2017.11.5=py36hb8ac631_0
- pip=9.0.1=py36h226ae91_4
- python=3.6.3=h3b118a2_4
- setuptools=36.5.0=py36h65f9e6e_0
- vc=14=h2379b0c_2
- vs2015_runtime=14.0.25123=hd4c4e62_2
- wheel=0.30.0=py36h6c3ec14_1
- wincertstore=0.2=py36h7fe50ca_0
- pip:
  - beautifulsoup4==4.6.0
  - chardet==3.0.4
  - idna==2.6
  - logbook==1.1.0
  - opencv-python==3.4.0+contrib
  - requests==2.18.4
  - urllib3==1.22
  - wikipedia==1.4.0
prefix: C:\ProgramData\Miniconda3\envs\Py36


text:
Q: Android. How to correct handle intent from BroadcastReceiver I have activity and two fragments which opened in this activity (for example FragmentFirst, FragmentSecond). In my activity I register BroadcastReceiver. And when i receive any event (inside onReceive) I need to display the received text in the TextView of second fragment.
I could register the BroadcastReceiver in the second fragment, however, the event may come at the moment when my second fragment opens and then I do not have time to register the BroadcastReceiver and I lose the event.
So my code inside the onReceive of activity looks like this:
        @Override
        public void onReceive(Context context, Intent intent) {
            String receivedMessage = intent.getStringExtra(MY_MESSAGE);
            Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (currentFragment instanceof FragmentSecond) {
                ((FragmentSecond) currentFragment).initMessage(receivedMessage);
            }
        }

And now I have a question, can there be such a situation that the current fragment is FragmentSecond, but the view of this fragment has not yet been created. In this case, I can get a NPE when calling a initMessage of my FragmentSecond that sets the receivedMessage for the TextView.
If this is really possible, then I will have to add some kind of checks inside the initMessage:
public void initMessage(String receivedMessage) {
    if (isViewCreated) { // flag to detect when view was created
        tvMessage.setText(receivedMessage);
        savedMessage = "";
    } else {
        savedMessage = receivedMessage; // save message to display it when view will be created
    }
}

In practice, I was not able to reproduce such a situation, but it seems to me that this is possible. Please tell me if this is possible?
P.S. I get the feeling that the onReceive controls the life cycle and is called exactly when the fragment view is created. Because I tried to send a broadcast until the moment when the FragmentSecond view was created, but until the onViewCreated of my FragmentSecond was called, onReceive was not called. However, I may be wrong

A: You can store the message in the Activity and use it the fragment WHEN fragment is ready.
Activity
    String message = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        message = intent.getStringExtra(MY_MESSAGE);
    }

You can "touch" the Activity in onAttach(context) method of the fragment.
Fragment
    private String message = null;

    void onAttach(Context: context) {
        super.onAttach(context)
        if (context instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) context;
            message = mainActivity.message;
        }
    }

That is for grabbing the latest value.
Since you are operating in Java is it a bit more verbose but for updates you can use Observer pattern(create listener interface which the fragments will implement and register themselves to the activity).
interface MessageObserver {
    void onMessageChange(String message);
}

Use WeakReference for the Activity so it doesn't leak the context.
Fragment
    private WeakReference<MainActivity> mWeakRefActivity;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) context;
            mWeakRefActivity = new WeakReference<MainActivity>(mainActivity);
            mainActivity.addObserver(this);
        }
    }

    @Override
    public void onDetach() {
        // Clean up after yourself
        mWeakRefActivity.get().removeObserver(this);
        super.onDetach();
    }

Activity
    ArrayList<MessageObserver> mObservers = new ArrayList<MessageObserver>();

    void addObserver(MessageObserver observer) {
        mObservers.add(observer);
    }

    void removeObserver(MessageObserver observer) {
        mObservers.remove(observer);
    }

    public void onReceive(Context context, Intent intent) {
        message = intent.getStringExtra(MY_MESSAGE);
        for (MessageObserver observer : mObservers) {
            observer.onMessageChange(message);
        }
    }


text:
Q: MySql Foreign key primary key not matching I am having a trouble linking all the foreign keys with the primary keys. I have two tables:
CREATE TABLE Patients
        (pid        INT NOT NULL AUTO_INCREMENT,
         name       VARCHAR(25),
         address        VARCHAR(30),
         telephone  VARCHAR(10),
         care_centre_id INT,
CONSTRAINT Patients_PK PRIMARY KEY (pid));

CREATE TABLE Care_centres
        (cid        INT NOT NULL AUTO_INCREMENT,
         name       VARCHAR(25),
         location       VARCHAR(30),
         nurse_charge_id    INT,
CONSTRAINT Care_centres_PK PRIMARY KEY (cid));

ALTER TABLE Patients ADD FOREIGN KEY (care_centre_id) REFERENCES Care_centres(cid);

cid is a primary key of Care_centres table, and care_cente_id is the foreign key of Patients table. Whenever I run the query table(MySql) it shows NULL values in foreign key. How can I index the correspondence of foreign key with primary key, it is Ok to randomly assigned values to foreign key.
mysql> SELECT * FROM Patients;
+-----+--------+----------------+------------+----------------+
| pid | name   | address        | telephone  | care_centre_id |
+-----+--------+----------------+------------+----------------+
|   1 | Joe    | 8 Walker Road  | 7800921111 |           NULL |
|   2 | Jose   | 10 Runner Road | 7800922222 |           NULL |
|   3 | Joseph | 12 Jogger Road | 7800923333 |           NULL |
+-----+--------+----------------+------------+----------------+

Any ideas ?
Thanks.

A: When you insert rows into the Patients table, you need to specify the care_centre_id column to create the association between that patient and the specified care centre.  Otherwise the database has no way of knowing which patient belongs to which care centre.
So, for example, let's say you have care centres like this:
+-----+--------+----------------+------------+
| cid | name   | location       | nurse_charge_id |
+-----+--------+----------------+------------+
|   1 | centre1| someplace      | 1              |
|   2 | centre2| someplace else | 1              |

You could, for example, assign Joe and Jose to care centre 1 and Joseph to care centr 2
+-----+--------+----------------+------------+----------------+
| pid | name   | address        | telephone  | care_centre_id |
+-----+--------+----------------+------------+----------------+
|   1 | Joe    | 8 Walker Road  | 7800921111 |           1    |
|   2 | Jose   | 10 Runner Road | 7800922222 |           1    |
|   3 | Joseph | 12 Jogger Road | 7800923333 |           2    |

You would do this during your initial insert of the patient, or on a subsequent update.


text:
Q: pdfminer doesn't extract data from filled-out pdf form I'm trying to use pdfminer to extract the filled-out contents in a pdf form. The instructions for accessing the pdf are:

*

*Go to https://www.ffiec.gov/nicpubweb/nicweb/InstitutionProfile.aspx?parID_Rssd=1073757&parDT_END=99991231

*Click "Create Report" next to the fourth report from the top (i.e.,Banking Organization Systemic Risk Report (FR Y-15))

*Click "Your request for a financial report is ready"

To extract the contents in blue, I copied code from this post:
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdftypes import resolve1

filename = 'FRY15_1073757_20160630.PDF'
fp = open(filename, 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
fields = resolve1(doc.catalog['AcroForm'])['Fields']

for i in fields:
    field = resolve1(i)
    name, value = field.get('T'), field.get('V')
    print '{0}: {1}'.format(name, value)

This didn't extract the data fields as expected -- nothing was printed. I tried the same code on another pdf and it worked so I suspect the failure might have to do with the security setting of the first pdf, which is shown below

For the second pdf on which the code worked, the security setting shows "Allowed" for all the actions. I also tried using pdfminer's pdf2txt.py functionality (see here) but the filled-out data in the fields in the original pdf form (which is what I want) was not in the converted text file; only the "flat" non-fillable part of the pdf was converted. Interestingly, if I use Adobe Reader's Save As Text to convert the pdf to a text file, the fillable part was in the converted text file. This is what I've been doing to get around the failed code.
Any idea how I can extract data directly from the pdf form? Thanks.

A: I can only explain what the problem is but cannot present a solution because I have no working Python knowledge.
Your code iterates over the immediate children of the AcroForm Fields array and expect them to represent the form fields.
While this expectation often is fulfilled, it actually only represents a special case: Form fields are arranged as a tree structure with that Fields array as root element, e.g. in case of your sample document there is large tree:

Thus, you have to descend into the structure, not merely iterate over the immediate children of Fields, to find all form fields.


text:
Q: Trouble installing luasocket/lfs using luarocks I installed luarocks and now I am trying to use it to install luasocket.
My command is
luarocks install luasocket-2.0.2-3.win32-x86.rock

and the response I get is
C:\Program Files (x86)\LuaRocks\lua\luarocks\command_line.lua:186: bad argument #1 to 'require' (string expected, got table)

The line of code in command_line.lua giving trouble is
if commands[command] then
    local cmd = require(commands[command])

and putting trace writes in the code reveals that commands[command] is indeed a table, of length zero.
This sort of fundamental runtime error is way beyond anything a Lua novice can be expected to fix. Any suggestions?
Edit
Turns out it's not just luasocket. I get the same problem with
luarocks install luafilesystem

A: Turns out that this is caused by having an old LuaRocks 2.0.10 installation that I wasn't aware of. It was put there by a failed attempt to install LuaDist-Batteries.
Solution here: https://github.com/luarocks/luarocks/issues/714 .


text:
Q: Image Upload at Google Appengine using AJAX and PHP I'm trying to upload an image on Google appengine hosting using ajax and php and I always get server error 500
My approach is create upload url which will be later used to submit the form to:
<?php
$upload_url = CloudStorageTools::createUploadUrl('/upload_script', $options);

The form which will be submitted as soon as any change is made to the input type file:
<form <?php echo 'action="$upload_url"'; ?> enctype="multipart/form-data" method="post">
    Files to upload: <br>
   <input type="file" name="uploaded_files" size="40">
   <input type="submit" value="Send">
</form>

Since I'm doing it using AJAX here is the ajax code:
$(document).ready(function () {
    $('#form').on('submit',(function(event) {
        event.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(){
                console.log("success");
            },
            error: function(){
                console.log("error");
            }
        });
    }));

    $("#browse").on("change", function() {
        $("#form").submit();
    });
});

This produces server error 500 when looking on it in console does anyone know where might be the problem?


text:
Q: How to join Array to String (Java)? Let's assume there is an array:
String[] myArray = new String[]{"slim cat", "fat cat", "extremely fat cat"};

Now I want to transform this array into String with tokens "&", which value is:

slim cat&fat cat&extremely fat cat

How can I achieve this without using for loop? I mean the simplest solution, like we used to to in reverse way like someString.split();

A: Use guava's Joiner or java 8 StringJoiner.

A: Edit: Why without a for loop?
Use a StringBuilder
StringBuilder builder = new StringBuilder();
builder.append( myArray.remove(0));

for( String s : myArray) {
    builder.append( "&");
    builder.append( s);
}

String result = builder.toString();

A: Using Java 8:
String result = String.join("&", myArray);

Using Java 7 or earlier, you either need a loop or recursion.

A: You might use Arrays.toString(Object[]) and rewrite the result. Something like,
String[] myArray = { "slim cat", "fat cat", "extremely fat cat" };
String str = Arrays.toString(myArray).replace(", ", "&");
str = str.substring(1, str.length() - 1);
System.out.println(str);

Output is (as requested)

    slim cat&fat cat&extremely fat cat
Note, this only works if there are no ", " in your inputs (as is the case here).

A: There's no way to do this job without some sort of iteration over the array.  Even languages that offer some form of a join() function (which do not include Java < version 8) must internally perform some sort of iteration.
About the simplest way to do it in Java <= 7 is this:
StringBuilder sb = new StringBuilder();
String result;

for (String s : myArray) {
    sb.append(s).append('&');
}
sb.deleteCharAt(sb.length() - 1);

result = sb.toString();

A: Please, take a look at http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#join(java.lang.Object[], char). This library is compatible with a lot of version of JDK and, as you can see, you have a lot of overridden methods.


text:
Q: If everything that is placed within Form1() braces is executed while Form initializing? I placed try/catch block within "Area1" and I've got a feeling that is not being executed constantly while app running. It was executed only once.
Could someone to shed the light on this.
I'm interested if everything is placed between Form1() braces "Area1", is executed only once while Form initializing.
And where I have to put try/catch block if I have not any event handlers and I need constant processing of try/catch block.

A: Yes it does executes only once when you instantiate the form saying Form1 frm = new Form1() since you have placed it inside form constructor

I have to put try/catch block...

try..catch inside constructor? Umm ... not sure why. Constructor are for member initialization purpose, what kind of operation are you performing there that you need a try block. Consider using dependency injection if really such need there. cause, if there any exception occurs while constructing the object then the object become useless for the life of application


text:
Q: how to add customer name in shopify coming soon page? I am looking for a simple way to implement a simple "coming soon" (pre-launch) page for my project. Users should be able to leave an email and name in order to be notified when the project is launched.

A: You already have an email field on this page. When enters his email and clicks the Notify button, an inactive customer account will be created for that user. On launching your store you can send account invites to all the customers that submitted this form, using standard Shopify functionality.
You mentioned that you also want to collect customers names. You can do that by adding additional fields to this form. You're using Debut theme so just open the sections/password-content.liquid file and add these fields between {% form 'customer' %} ... {% endform %} tags. Note, as Shopify customer will be created, you have to use two fields - one for the first name and one for the second name. Just duplicate the email field and change name attributes. See an example below how these fields may look like, note how field names are grouped with contact[...]:
<input type="text" name="contact[first_name]" placeholder="First Name">
<input type="text" name="contact[last_name]" placeholder="Last Name">

You can also change the tags to be applied to the customer on creation. In the Debut theme, these tags are password page and prospect by default.
Adding more fields
You can collect more information on this page. Just add "note" fields with names like contact[note][Field name]. The information from these fields will be displayed in the Customer Note field. For example, if you want to ask customer leave a phone number you would use something like that:
<input type="text" name="contact[note][Phone]" placeholder="Phone">

You can follow the logic from this tutorial: Add fields to the customer registration form. Just make sure you're grouping fields with contact[] prefix rather than customer[] as described in the tutorial, which is actually about another form.

A: What I found with the Debut theme is that if you put
<input type="text" name="contact[first_name]" placeholder="First Name">
<input type="text" name="contact[last_name]" placeholder="Last Name">

in between these tags {% form 'customer' %} ... {% endform %}
The form fields get squished together.
I found that the below worked for me, if you add it before the section {% form 'customer' %} ... {% endform %}:
  <input
      type="text"
      name="contact[first_name]"
      placeholder="First Name">

  <input
      type="text"
      name="contact[last_name]"
      placeholder="Last Name"
  >

I've added a screenshot to show you what it looks like in Shopify
This is the final result of my code

A: I have got it working to capture the first and second name by adding these fields:
First Name
    <input
      type="text"
      name="contact[first_name]"
      id="{{ formId }}-first_name"
      class="input-group__field {% if form.errors contains 'first_name' %} input--error{% endif %}"
      placeholder="Please enter your first name..."
      {%- if form.errors contains 'first_name' -%}
        aria-invalid="true"
        aria-describedby="{{ formId }}-first_name-error"
        data-form-status
      {%- endif -%}
    >

  Last Name
    <input
      type="text"
      name="contact[last_name]"
      id="{{ formId }}-last_name"
      class="input-group__field {% if form.errors contains 'last_name' %} input--error{% endif %}"
      placeholder="Please enter your surname..."
      {%- if form.errors contains 'last_name' -%}
        aria-invalid="true"
        aria-describedby="{{ formId }}-last_name-error"
        data-form-status
      {%- endif -%}
    >

I'd love to know how to display errors if the fields are left blank though. Anyone know how to do this?
Many thanks.


text:
Q: Why do we call it a "board spin"?
Possible Duplicate:
Interesting/Unusual/Old Electronics nomenclature

I've been getting into some minor board design work lately, and got confused a few times, because some of my colleagues were talking about "spinning" boards or getting things right on the first "spin" of a board.
Where did the term "spin" come from for fabricating / printing a circuit board?

A: The term is in common use.
Boards used to be spin-coated with liquid resist. Perhaps that is where it came from.

A: It is a common term which refers to the process of laying out, routing, fabricating, populating, and testing a PC board.
I don't know where the term came from, but I'm guessing it refers to re-doing part of the engineering cycle.  To "re-spin" something isn't limited to circuit boards or electronics.  It basically means to re-do, retry, make another revision, "back to the drawing board" (partially), etc.  Eventually the term "spin" came to be used sortof as slang in the industry for this particular set of tasks.  Now it's to the point where you can talk about the "first spin", even though nothing is re-done.

A: As others have pointed out, the term is not limited to electronics. Spin literally means to "turn around" rapidly.
http://www.etymonline.com/index.php?term=spin

Sense of "to cause to turn rapidly" is from 1610s; meaning "revolve,
  turn around rapidly" first recorded 1660s

In PCB terms, the turnaround time is how long it takes to make a design change and get boards made. So, a spin is a design change and manufacturing turnaround.

A: Spinning makes me think of the textile industry. My best guess is that the term spinning worked its way into electronics production terminology somehow, as they are both industrial type processes.
Also, the fact that PCBs are "fabricated" lends some small amount of credence to my spinning theory, as spinning is one of the processes that leads to the creation of fabrics.


text:
Q: replace value of element in XML I need to replace value of <ResourceId> element. If I delete everything before
<VectorLayerDefinition> and after this element everything works fine, but I have a lot of these xml files and I can't delete anything from it manually. Any suggestions?
Here the xml code:
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <ns0:FeatureSource xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" rdf:resource="fsd://1" />
  </rdf:Description>
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <rdf:type rdf:resource="http://www.autodesk.com/gis/resource/definitions/LayerDefinitionResource" />
  </rdf:Description>
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <ns0:name xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">FeatureClass1</ns0:name>
  </rdf:Description>
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <ns0:isURL xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">no</ns0:isURL>
  </rdf:Description>
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <ns0:description xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">
    </ns0:description>
  </rdf:Description>
  <rdf:Description rdf:about="sdf:FeatureClass1">
    <ns0:LayerDefinitionResourceStream xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">
      <LayerDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="LayerDefinition-2.4.0.xsd" version="2.4.0">
        <VectorLayerDefinition>
          <ResourceId>Library://SDF_1.FeatureSource</ResourceId>
          <FeatureName>sdf:FeatureClass1</FeatureName>
          <FeatureNameType>FeatureClass</FeatureNameType>
          <Geometry>Geometry</Geometry>
    </VectorLayerDefinition>
      </LayerDefinition>
    </ns0:LayerDefinitionResourceStream>
  </rdf:Description>
  <rdf:Description rdf:about="fsd://1">
    <rdf:type rdf:resource="http://www.autodesk.com/gis/resource/definitions/FeatureSourceResource" />
  </rdf:Description>
  <rdf:Description rdf:about="fsd://1">
    <ns0:name xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">1</ns0:name>
  </rdf:Description>
  <rdf:Description rdf:about="fsd://1">
    <ns0:isURL xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">no</ns0:isURL>
  </rdf:Description>
  <rdf:Description rdf:about="fsd://1">
    <ns0:description xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">
    </ns0:description>
  </rdf:Description>
  <rdf:Description rdf:about="fsd://1">
    <ns0:FeatureSourceResourceStream xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">    </ns0:FeatureSourceResourceStream>
  </rdf:Description>
  <rdf:Description rdf:about="LayerSchema">
    <ns0:version xmlns:ns0="http://www.autodesk.com/gis/resource/definitions/" xml:lang="en" rdf:parseType="Literal">1</ns0:version>
  </rdf:Description>
</rdf:RDF>

Here my code:
public void Main()
{
    XDocument doc = XDocument.Load(@"D:\Repositories\Library\Content\Layers\FeatureClass1.LayerDefinition");
    string str = doc.Element("VectorLatyerDefinition").Element("ResourceId").Value;
    doc.Element("VectorLayerDefinition").Element("ResourceId").Value = "SomeValue";
    doc.Save(@"D:\Repositories\Library\Content\Layers\FeatureClass1.LayerDefinition");
}

But it works after I "cleaned" xml file

A: Using xml liinq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication80
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement resourceId = doc.Descendants("ResourceId").FirstOrDefault();
            resourceId.SetValue("//SDF_2.FeatureSource");

        }
    }
}


text:
Q: ViewPager doesnt inflate all XML layout files I want to create Tabs within tabs in my app. I have created a TabLayout in my MainActivity XML file along with ViewPager. I have then created another XML file which contains the inner TabLayout with its corresponding ViewPager. Now, when I run my app, I can see inflated views of all other tabs except my first tab(home icon tab). Also, I have a CardView to be displayed when one of my inner tabs is selected which is not being seen. Please help!
This is my MainActivity.java code :
public class MainActivity extends AppCompatActivity {

    ViewPager viewPagerOuter, viewPagerInner;
    TabLayout tabLayoutouter, tabLayoutinner;

    public static class InnerFragment extends Fragment{
    private static final String TAB_POSITION = "tab_position";
    View rootView;
    public InnerFragment(){

    }
    public static InnerFragment newInstance(int tabPosition){
        InnerFragment fragment = new InnerFragment();
        Bundle args = new Bundle();
        args.putInt(TAB_POSITION, tabPosition);
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        Bundle args = getArguments();
        int tabPosition = args.getInt(TAB_POSITION);
        switch (tabPosition){
            case 0:{
                rootView = inflater.inflate(R.layout.card_view_layout, container, false);
                break;
            }
            case 1:{
                TextView tv = new TextView(getActivity());
                tv.setGravity(Gravity.CENTER);
                tv.setText("Text in tab #" + tabPosition);
                rootView = tv;
                break;
            }
        }
        return rootView;
    }
}
static class InnerPagerAdapter extends FragmentStatePagerAdapter{
    public InnerPagerAdapter(FragmentManager fm){
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        return InnerFragment.newInstance(position);
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position){
        String x = "";
        switch (position){
            case 0:
                x = "feed"; break;
            case 1:
                x = "events"; break;
        }
        return x;
    }
}

public static class OuterFragment extends Fragment{
    private static final String TAB_POSITION1 = "tab_position";
    View rootView;
    public OuterFragment(){

    }
    public static OuterFragment newInstance(int tabPosition){
        OuterFragment fragment1 = new OuterFragment();
        Bundle args1 = new Bundle();
        args1.putInt(TAB_POSITION1, tabPosition);
        fragment1.setArguments(args1);
        return fragment1;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater1, ViewGroup container1, Bundle savedInstanceState){
        Bundle args1 = getArguments();
        int tabPosition = args1.getInt(TAB_POSITION1);
        switch (tabPosition){
            case 0:{
                rootView = inflater1.inflate(R.layout.inner_tab_layout, container1, false);
                break;
            }
            default:{
                TextView tv = new TextView(getActivity());
                tv.setGravity(Gravity.CENTER);
                tv.setText("Text in tab #" + tabPosition);
                rootView = tv;
                break;
            }
        }
        return rootView;
    }
}
static class OuterPagerAdapter extends FragmentStatePagerAdapter{
    public OuterPagerAdapter(FragmentManager fm){
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        return OuterFragment.newInstance(position);
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {return null;}
}
final int icons[] = new int[]{R.drawable.ic_chat_black_24dp, R.drawable.ic_home_black_24dp, R.drawable.ic_notifications_black_24dp, R.drawable.ic_person_black_24dp};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    InnerPagerAdapter innerPagerAdapter = new InnerPagerAdapter(getSupportFragmentManager());
    OuterPagerAdapter outerPagerAdapter = new OuterPagerAdapter(getSupportFragmentManager());

    viewPagerOuter = (ViewPager) findViewById(R.id.viewpagerouter);
    viewPagerOuter.setAdapter(outerPagerAdapter);
    tabLayoutouter = (TabLayout) findViewById(R.id.tablayoutouter);

    final LayoutInflater factory = getLayoutInflater();
    final View view = factory.inflate(R.layout.inner_tab_layout, null);
    viewPagerInner = (ViewPager) view.findViewById(R.id.viewpagerinner);
    viewPagerInner.setAdapter(innerPagerAdapter);
    tabLayoutinner = (TabLayout) view.findViewById(R.id.tabLayoutinner);
    tabLayoutinner.setupWithViewPager(viewPagerInner);
}
}

And this is XML file of MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayoutouter"
        android.support.tabIndicatorColor="?attr/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/colorPrimary"
        app:tabSelectedTextColor="@android:color/background_light">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpagerouter"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

    </android.support.v4.view.ViewPager>

</LinearLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginRight="16dp"
    android:layout_marginBottom="16dp"
    android:src="@drawable/ic_create_black_24dp" />

</RelativeLayout>

This is inner_tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayoutinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorBlack">
</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpagerinner"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

</LinearLayout>

I am sorry for posting such long bits of code. Please don't mind..

A: Move viewPagerInner, tabLayoutinner and innerPagerAdapter code to OuterFragment.
1. Update your OuterFragment  as below:
public static class OuterFragment extends Fragment {
    private static final String TAB_POSITION1 = "tab_position";
    View rootView;

    ViewPager viewPagerInner;
    TabLayout tabLayoutinner;

    public OuterFragment(){

    }
    public static OuterFragment newInstance(int tabPosition){
        OuterFragment fragment1 = new OuterFragment();
        Bundle args1 = new Bundle();
        args1.putInt(TAB_POSITION1, tabPosition);
        fragment1.setArguments(args1);
        return fragment1;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater1, ViewGroup container1, Bundle savedInstanceState){
        Bundle args1 = getArguments();
        int tabPosition = args1.getInt(TAB_POSITION1);
        switch (tabPosition){
            case 0:{
                rootView = inflater1.inflate(R.layout.inner_tab_layout, container1, false);

                viewPagerInner = (ViewPager) rootView.findViewById(R.id.viewpagerinner);
                tabLayoutinner = (TabLayout) rootView.findViewById(R.id.tabLayoutinner);

                InnerPagerAdapter innerPagerAdapter = new InnerPagerAdapter(getActivity().getSupportFragmentManager());

                viewPagerInner.setAdapter(innerPagerAdapter);
                tabLayoutinner.setupWithViewPager(viewPagerInner);

                break;
            }
            default:{
                TextView tv = new TextView(getActivity());
                tv.setGravity(Gravity.CENTER);
                tv.setText("Text in tab #" + tabPosition);
                rootView = tv;
                break;
            }
        }
        return rootView;
    }
}

2. Update onCreate() method as below:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewPagerOuter = (ViewPager) findViewById(R.id.viewpagerouter);
    tabLayoutouter = (TabLayout) findViewById(R.id.tablayoutouter);

    OuterPagerAdapter outerPagerAdapter = new OuterPagerAdapter(getSupportFragmentManager());

    viewPagerOuter.setAdapter(outerPagerAdapter);
    tabLayoutouter.setupWithViewPager(viewPagerOuter);
}

Hope this will work~


text:
Q: php xpath returns Array(0) I read the following XML:
http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
controller:
$ECB_rates = array();
$currencies = explode(',', 'GBP,USD,RUB,AUD');
foreach($currencies as $currency) {
    $ECB_rates[$currency] = $ECB_XML->xpath('//Cube/Cube/Cube[@currency="' . $currency . '"]/@rate');
}
$this->set('ECB_rates', $ECB_rates);

view:
var_dump($ECB_rates);

and I get the following:
array(4) { ["GBP"]=> array(0) { } ["USD"]=> array(0) { } ["RUB"]=> array(0) { } ["AUD"]=> array(0) { } }

I can't figure out why the rates are returned as empty array.

A: The document has a default namespace, which can commonly confuse XPath expressions if not done correctly.  The other part is that xpath() returns an array of SimpleXMLElements which also doesn't help your cause.
The following code first registers the default namespace with the prefix 'def' and then (I've simplified the expression as well) uses this as a prefix to find the <Cube> element with the currency you want.  Then it takes the first result (there should only be one anyway) and casts it to a string to make it more useful.
$ECB_XML->registerXPathNamespace("def", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
$ECB_rates = array();
$currencies = explode(',', 'GBP,USD,RUB,AUD');
foreach($currencies as $currency) {
    $ECB_rates[$currency] = (string)$ECB_XML->xpath('//def:Cube[@currency="' . $currency . '"]/@rate')[0];
}
var_dump($ECB_rates);

Which gives...
array(4) {
  'GBP' =>
  string(7) "0.87295"
  'USD' =>
  string(6) "1.2234"
  'RUB' =>
  string(7) "70.8270"
  'AUD' =>
  string(6) "1.5934"
}

Update:
You could (if the XML format is stable) just use SimpleXML element/attribute access.  Checking if the currency is in the array of currencies your after...
foreach($ECB_XML->Cube->Cube->Cube as $rate) {
    $currency = (string)$rate["currency"];
    if ( in_array($currency, $currencies))   {
        $ECB_rates[$currency] = (string)$rate["rate"];
    }
}

This may give you the items in a different order, but this might not be an issue.


text:
Q: Why kivy give new children index = 0? I add new widgets to BoxLayout with function:
def create_new_tracker(self):
    self.trackers_count += 1
    new_id = self.trackers_count
    self.root.ids['box'].add_widget(TrackerContainer(ID=new_id))

When I add 4 widgets with ids: 0, 1, 2, 3, BoxLayout have 4 children with ids in order: 3, 2, 1, 0.
Shouldn't they be appended, so the last added widget should be the last children and not the first?
Isn't that a bug?
How to control this?

A: This is a probably-misguided design choice from many years ago when Kivy was first written - the children list is simply in the opposite order to what you expect. There is no need to control it, as long as you know that fact you can achieve whatever result you want.
I think the reason is that this ordering is more convenient for things like dispatching touches, which goes in reverse order of addition as the last-added widget is on top. I guess that user iteration through the children list was not on the original developer's mind at the time.


text:
Q: Using Rails with existing database So I have an existing postgres database which gets populated by a python script. Now I am making a rails api which serves that data to a client. To my amusement all that I had to do is to create model classes and simply define relationships. No migration files, no schema, it just works. So a couple of questions.

*

*Am I right in saying that schema.rb is only needed for creating the
database? If I am not running any migrations in my rails app I don't
need any schema or migration files at all?

*I used to think that rails infers the names of model methods with the
help of schema.rb . But it seems the only glue that ties ORM layer
and the database is naming conventions? Are there any pitfalls I
might be overlooking in doing things this way?

A: schema.rb is indeed not required by ActiveRecord.
It is used for:

*

*having a quick overview of the state of the database

*creating thedatabase tables when using db:schema:load task

*in gems like Apartment, (I think) it is used to create tenant specific schemas

TL:DR; - you don't really need schema.rb file but it's always good to have it as an authoritative source of db information.
More info here: http://edgeguides.rubyonrails.org/active_record_migrations.html#schema-dumping-and-you


text:
Q: Prove $\frac{\ln(1+x)}{1+x}=x-\left(1+\frac{1}{2}\right)x^2+\left(1+\frac{1}{2}+\frac{1}{3}\right)x^3-\ldots$ I have to prove that :
$$\frac{\ln(1+x)}{1+x}=x-\left(1+\frac{1}{2}\right)x^2+\left(1+\frac{1}{2}+\frac{1}{3}\right)x^3-\ldots$$
I already know that the Maclaurin series of $\ln(1+x)$ is $x-\frac{1}{2}x^2+\frac{1}{3}x^3-\frac{1}{4}x^4+\frac{1}{5}x^5+\ldots$ But how can I use it to prove the first claim? Should I just multiply $\frac{1}{1+x}$ to the Maclaurin series of $\ln(1+x)$? Still, I don't know how to do that.
I tried to use the derivatives of $\frac{\ln(1+x)}{1+x}$ then substitute that into the Maclaurin formula. But I don't think that's the right way to do this efficiently.

A: \begin{align*}
\frac{\ln(1+x)}{1+x}
    &= \ln(1- -x) \cdot \frac{1}{1- -x}  \\
    &= \left( \sum_{i=1}^\infty \frac{-(-x)^i}{i} \right) \left( \sum_{j=0}^\infty (-x)^j \right),  & |x| < 1\\
    &=_{\text{why?}} \sum_{i=1}^\infty \sum_{j=0}^\infty \frac{-(-x)^i}{i} (-x)^j  \\
    &= \sum_{i=1}^\infty \sum_{j=0}^\infty \frac{(-1)^{i+j+1}}{i} x^{i+j}
\end{align*}
Now change variables to $k = i+j$ and $\ell$.  On a diagram of the terms in this double series (a plot of points on the $(i,j)$-plane corresponding to terms in the series), the lines of constant $k$ have slope $-1$ and meet $k$ points, so we may take $\ell = i$, running from $1$ to $k$.  (Again, this is vastly easier to see in the diagram.)  Now make $k$ be the outer sum and $\ell$ be the inner sum and you will immediately have your result,
$$  \sum_{k=1}^\infty \left( -(-1)^k x^k \sum_{\ell =1}^k \frac{1}{\ell} \right)  \text{.}  $$

A: Multiply the two series $\ln(1+x) = x - \frac{1}{2} x^2 + \frac{1}{3} x^3 - \cdots$ and $\frac{1}{1+x} = 1 - x + x^2 - x^3 + \cdots$.
For instance, the coefficient of $x^2$ in the product is $(-\frac{1}{2} x^2) \cdot 1 + x \cdot (-x) = -(1 - \frac{1}{2}) x^2$.

A: You must multiply the series
$$\log(1+x)=x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+\frac{x^5}{5}+O\left(x^6\right)$$
$$\frac 1{1+x}=1-x+x^2-x^3+x^4-x^5+O\left(x^6\right)$$
$$\frac{\log(1+x)}{1+x}=\left(x-\frac{x^2}{2}+\frac{x^3}{3}-\frac{x^4}{4}+\frac{x^5}{5}+O\left(x^6\right) \right) \times$$ $$\left(1-x+x^2-x^3+x^4-x^5+O\left(x^6\right) \right) $$
$$\frac{\log(1+x)}{1+x}=x-\frac{3 x^2}{2}+\frac{11 x^3}{6}-\frac{25 x^4}{12}+\frac{137
   x^5}{60}+O\left(x^6\right)$$
In fact, almost as you wrote in the post
$$\frac{\log(1+x)}{1+x}=\sum_{n=1}^\infty (-1)^{n+1} H_n \,x^n$$

A: All the other answers to your question focus on how to compute the Maclaurin series of this function using the known series. I will sketch a strategy to compute it by directly computing Maclaurin coefficients. Let $$(1+x)y=\ln(1+x)$$ for all $x\gt -1. $ Then lets look at higher derivatives to see a possible pattern: $$(1+x)\dfrac{dy}{dx}+y=\dfrac{1}{1+x}\tag1$$
$$(1+x)\dfrac{d^2y}{dx^2}+2\dfrac{dy}{dx}=-\dfrac{1}{(1+x)^2}\tag2$$
$$(1+x)\dfrac{d^3y}{dx^3}+3\dfrac{d^2y}{d^2x}=\dfrac{2}{(1+x)^3}\tag3.$$ By looking at these, it is not difficult to guess that
$$(1+x)\dfrac{d^{n+1}y}{dx^{n+1}}+(n+1)\dfrac{d^ny}{d^nx}=\dfrac{(-1)^{n}n!}{(1+x)^{n+1}}\qquad \forall n\in\mathbb{N}\cup\{0\}.$$ We can use mathematical induction to establishes our claim rigorously. Since coefficients of Maclaurin series are given by
$$a_n=\dfrac{1}{n!}\dfrac{d^ny}{d^nx}\Big\vert_{x=0},$$ we can show that $a_n=(-1)^{n+1}H_n$ by solving the recursive relation $$a_{n+1}+a_n=\dfrac{(-1)^n}{n+1},\qquad a_0=0.$$ (You can easily solve this recursion by multiplying whole equation by $(-1)^n$ and then telescoping). In fact, we can easily use it to compute Taylor coefficients at any point we want.


text:
Q: How can I do a string replacement for words with parenthesis but keep the parenthesis with (s)? I'm trying to do a string replacement for all words in the sentence with parenthesis around the word but keep the pluralized part of the word with the parenthesis E.g. (s)... like keep apple(s) if the pluralized version of the word with (s) is already there.
 //TODO: Remove all parathesis from replaced words but keep (s) in there
 //E.g. remove all parathesis from this sample but keep the (s) in there
 //Mary ran to the (supermarket) to get her (grocerie(s)) but she forgot her (keys) and coin(s)
//So supermarket,grocerie(s) and keys need the outer parenthesis removed so that it should be replaced with:
//Mary ran to the supermarket to get her grocerie(s) but she forgot her keys and coin(s)

var keys = InformationScript.Split(' ');

string scriptWithoutParans = null;

foreach(var key in keys)
{
    if (!key.Equals("(s)"))
    {
        scriptWithoutParans = InformationScript.Replace("(", "").Replace(")", "");
    }
}

InformationScript = scriptWithoutParans;

The issue with the above is, it appears to be replacing everything including the (s) parenthesis with no parenthesis. I want it to be for everything except for (s)... How can do that?
Thanks!

A: This solution will replace all instances of (s) with a token string, then replace all instances of ( or ), and finally replace our token string with (s)
var token = "SAVED_TOKEN";
var InformationScript = "Mary ran to the (supermarket) to get her (grocerie(s)) but she forgot her (keys) and coin(s)";
//replace (s) with a token string that we can replace later
var tokenized = Regex.Replace(InformationScript, "\\((s)\\)", token);
//remove all remaining paranthesis, then replace our token with (s)
InformationScript = Regex.Replace(tokenized, "\\(|\\)", "").Replace(token,"(s)");

Result: Mary ran to the supermarket to get her grocerie(s) but she forgot her keys and coin(s)


text:
Q: Is ''If I knew, I would have told you" a correct use of conditionals I was wondering if one could use if + past simple / would + have + past participle.

A: Yes, you most definitely could.

if + past simple / would + have + past participle.

You have two verbs in the past form (to know and to tell). Therefore, the tense is consistent in the context.
You also begin with a dependent if clause, which is correct. The usage of the auxiliary would in the independent clause is obviously appropriate here as you're using it is a conditional verb.
On another note, would can be replaced with could and might. It will change the meaning, but it's something to keep note of because it is still grammatically correct.


text:
Q: How to remove or change an image in a docx I'm trying to change an image embedded in a docx.  In some circumstances I'll need to replace a default placeholder image on each page with a new one, and in others I'd like to just remove that placeholder image (or hide it? -- or better than hide it, just leave it alone because the placeholder image right now is just a simple almost invisible 1x1 image).  First choice I suppose would be to entirely remove it though.
What are the best ways to do this in TBS?  I figure I could always replace the image whether I really have one to display there or want it removed, and just replace it with a tiny 1x1 white pixel PNG or something.  But is there a cleaner way to do this that's no more difficult than that approach?
I'm trying to use this method right now:
$TBS->PlugIn(OPENTBS_CHANGE_PICTURE, $imageId, "$writeTemp$tmpDirNm\\QR1__$imageId.png");

But thought I'd check in since I didn't yet determine a better way to do this.
Thanks,
John

A: Unfortunately, there is no direct way to delete a picture with OpenTBS.
But you can do it using a magnet field.
Example at the template side :
[my_pic_ok;ope=mok:1;magnet=w:r]
[onshow.my_pic;ope=changepic;tagpos=inside]

PHP side:
$my_pic_ok = 0; // 0 = delete the picture, 1 = keep the picture
$TBS->MergeField('my_pic_ok', $my_pic_ok);


text:
Q: In emacs edit section of file as if it were a separate file For some tasks I prefer single big files over splitting a project (say: a LaTeX report, a medium-sized python script) into separate smaller files, e.g. for easier searching and search-and-replace. However for editing it is often preferable to have separate views of different parts of a project, favoring several small files.
Is the some mode/package for emacs that allows editing parts of files as if they were a separate file, while keeping the buffer synchronized with all other views of the file? I am aware of clone-indirect-buffer, but while it achieves part of the intent, I'd prefer a method that limits the indirect buffer to a specific section of the file. Think e.g. of org-modes C-c ' but implemented with an indirect buffer. Ideally the implementation would support some syntax to define sections.
I think the LEO editor is build around roughly the concept that I want for emacs, though I never tried it (didn't work on my system).

A: One library that provides such behavior is Narrow Indirect (narrow-indirect.el).  It gives you a different view of a portion of
the buffer, or even of the whole buffer (use C-x h C-x 4 n n).
It always has the same text and text properties, but otherwise it
is pretty independent.  In particular, you can kill an indirect buffer without affecting
its base buffer.  You will likely want to kill indirect narrowed
buffers rather than widening them.
You can use indirect buffers for more than you might think.  You
can use clones taken from portions of Dired buffers, for example,
to give you useful (active) views into a directory listing.  There
are only a few keys/commands (such as g to update the listing)
that do not work, because they depend on a view of the whole Dired
buffer.  Experiment, and you will no doubt find interesting new
uses for indirect buffers.
See also the Emacs manual, node Indirect Buffers.


text:
Q: supertest times out on post request i'm trying to use supertest to test some express routes, however the test throws a timeout error when i try to send post requests despite the get requests actually working.
this is the route i'm testing
router.post('/', async (req, res) => {
  try {
    const { command, text } = req.body;

    switch (command) {
      case 'abc': return;
      default:
        console.log('123');
    }
  } catch (error) {
    console.error(error);
  }
});

this is the test
describe('test', () => {
  const app: express.Express = express();
  app.use('/', route);
  app.use(express.urlencoded({ extended: true }));

  it('test', async () => {
    await request(app)
      .post('/')
      .send('command=john')

    expect(handleSurveyListCommand).not.toHaveBeenCalled();
    expect(handleSurveyRespondCommand).not.toHaveBeenCalled();
    expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
    expect(consoleErrorSpy).toHaveBeenCalledWith(new Error('Command not found'));
  });
});

and this is the error thrown
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

this test fails even if the only thing i do inside the route is to log something.

A: This is because you are not responding back with the response while the request in test case is waiting for some response, instead return try sending response
router.post('/', async (req, res) => {
  try {
    const { command, text } = req.body;

    switch (command) {
      case 'abc': res.status(200).send("abc");
      default:
        res.status(200).send("123");
    }
  } catch (error) {
    res.status(500).send("unknown error");
  }
});

Regarding req.body undefined ->use body parsed in app
app.use(express.bodyParser());


text:
Q: lightning/empApi does not handle new record creation Let's say i have custom object LOT__c in my org and LWC from
https://developer.salesforce.com/docs/component-library/bundle/lightning-emp-api/documentation
then I set channel name to /data/LOT__c__ChangeEvent and subscribe channel.
But when I create new lot nothing's happened with channel. (LOT is included into Change Data Capture
What do I do wrong?

A: You will not have __c for change events subscription - Refer to this document

Custom Object
/data/<Custom_Object_Name>__ChangeEvent
For example, the channel to subscribe to change events for Employee__c
  custom object records is:
/data/Employee__ChangeEvent

In your case it should be /data/LOT__ChangeEvent


text:
Q: Compile a project outside of visual studios Is there a way that I can compile an application outside of visual studios from another c# application?
I have an application the requires a unique id coded into a device, I want that build coded for just that device, so instead of me having to change the hardcored ID, build, place on device. I would like to write another application that pulls the devices ID, modifies the needed .cs files then builds the project in release and copied it to the device.
Can this be done?
Also I do have post build code that runs if that matters in the process.

A: You can use either MSBUILD or CSC. MSBuild, which as you mentioned, does use your project and solution files. CSC will compile specific files, or all files in a specific directory tree.
MSBuild is the easiest way to go. For instance:
msbuild /property:Configuration=Release MyFile.vbproj

You should also look at automating your builds with NAnt and/or CruiseControl.net.
Also, here is an example on how to compile your code without visual studio using CSC.
http://blog.slickedit.com/?p=163
Also take a look at this stuff
How can I compile and run c# program without using visual studio?


text:
Q: Equal spacing around UICollectionViewCells I want to have equal amount of spacing between all the cells as well as between the screen border and the closest cell. Basically something like this. Equal spacing in and all around.

I managed to test this in the interface builder by setting values like this. I set the cell size to 110, Min spacing to 0 and all Section Insets to 10.

And it looks perfect in the IB.

However when I run it (in an iPad Air 2), it looks like this.

Notice the spacing in between the cells is bigger. I also tried to do this solely from the code by implementing the following methods from the UICollectionViewDelegateFlowLayout.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 110, height: 110)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

That yielded the same results. Can anybody please tell me how to correct this? I'd prefer to do this by code. But I'm open to anything.

A: Unluckily, this is how UICollectionViewFlowLayout works by default. That's because you specify exact section insets but minimum interitem space.
To do what you're asking, you mainly have two ways to do it depending on the end result you wish for. Both have to be done manually by code.
• Enlarge the cells to leave the exact space (same space, bigger cells)
• Compute the space and change the insets to match it (same cells, bigger space)
Both can be done by either setting the values on the layout object (and invalidating it) or by returning the values through the delegate.


text:
Q: How does the Math.max.apply() work? How does the Math.max.apply() work?.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script>
      var list = ["12","23","100","34","56",
                                    "9","233"];
      console.log(Math.max.apply(Math,list));
  </script>
</body>
</html>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
The above code finds the Max number in the List. Can anyone tell me how does the below code work?. It seems it works if i pass null or Math.
console.log(Math.max.apply(Math,list));

Does all the user-defined/Native functions have call and apply method which we can use?.

A: I will start by saying Math.max(...numbers) and Function.prototype.apply() should only be used for arrays with relatively few elements. (...) and apply will either fail or return the wrong result if the array is too large
Math.max.apply(null | undefined | Math, numbers) is the same as Math.max(...numbers) so I would recommend Math.max(...numbers) for aesthetic reasons.

const numbers = [5, 6, 2, 3, 7];

const max = Math.max(...numbers);

console.log('max:', max);
// expected output: 7

const min = Math.min(...numbers);

console.log('min:', min);
// expected output: 2

If you need to find the maximum element in a numeric array that is very large: use the Array.reduce() method.
Array.reduce() can be used to find the maximum element in a numeric array, by comparing each value:

const numbers = [5, 6, 2, 3, 7];
const getMax = (numbers) => numbers.reduce((a, b) => Math.max(a, b));

const getMin = (numbers) => numbers.reduce((a, b) => Math.min(a, b));

const max = getMax(numbers)
const min = getMin(numbers)

console.log('max:', max)
console.log('min:', min)

Conclusion:
Numeric array that is relatively small: use Math.max(...numbers)
Numeric array that is very large: use the Array.reduce() method

A: On JavaScript ES6 just use the Spread operator:
var list = ["12","23","100","34","56","9","233"];
console.log(Math.max(...list));
//                   ^^^ Spread operator

A: Math.max(val1, val2,...)
Math.max(1, 2, 3); // Math.max([value1[, value2[, ...]]])
value1, value2... are parameters and must be Numbers MDN Math.max
You can't pass array as Math.max parameters. To pass an array you have to use apply.
Apply
The first parameter of apply is this, the second is array.
Math methods are equivalent of static in other languages, which means it doesn't need an object instance unlike to array.prototype.slice so you don't need to pass this in this case.
Example
var arr = [1, 2, 3];

Math.max(1, 2, 3);  // -> 3
Math.max(arr);      // -> NaN (Not a Number)
Math.max.apply(null, arr);  // Math.max.apply(null, [1, 2, 3]) -> Math.max(1, 2, 3) -> 3

arr.slice(1);  // -> returns Array [2, 3]
Array.prototype.slice.call(arr, 1); // Array.prototype.slice.call([1, 2, 3], 1) == [1, 2, 3].slice(1)

When you want to pass an array as parameter you have to use apply, otherwise use call.
apply = array
call = comma separated
More about call & apply

A:
Can anyone tell me how does the below code work?

Math.max.apply(Math,list)

Invokes a Math.max function with Math object to be used as a this reference in the function implementation (body) and list to be passed as an arguments.
So this eventually equals to
Math.max("12","23","100","34","56", "9","233")

It seems it works if i pass null or Math.

Obviously Math.max implementation doesn't use instance variable - there is no reason to do so. The native implementation would just iterate over arguments and find the maximum one.

Does all the user-defined/Native functions have call and apply method which we can use?.

Yes, every single function can be invoked using call or apply
References:

*

*MDN .apply() documentation (credits to @RGraham)

A: apply accepts an array and it applies the array as parameters to the actual function. So,
Math.max.apply(Math, list);

can be understood as,
Math.max("12", "23", "100", "34", "56", "9", "233");

So, apply is a convenient way to pass an array of data as parameters to a function. Remember
console.log(Math.max(list));   # NaN

will not work, because max doesn't accept an array as input.
There is another advantage, of using apply, you can choose your own context. The first parameter, you pass to apply of any function, will be the this inside that function. But, max doesn't depend on the current context. So, anything would work in-place of Math.
console.log(Math.max.apply(undefined, list));   # 233
console.log(Math.max.apply(null, list));        # 233
console.log(Math.max.apply(Math, list));        # 233

Since apply is actually defined in Function.prototype, any valid JavaScript function object, will have apply function, by default.


text:
Q: Host sends Long text emails successfully but they cannot be received by clients I have php application on Hostinger and use mail() function to send emails to my clients.
When I send short text massage they receive it but when I exceed special limitation on my text character Host successfully send it but costumer cannot receive email.
It is very weird because I have exactly this code on another Hostinger account and I don't have the same problem! On that account with exactly this code I send long text emails and costumers receive them.
There is my email testing code which obviously is not problem because it has been working for over 2 years on my other account on Hostinger:

 $content='
        hi admin,

There is a new order to sweet
with the reference number 47 from customer Josef  Saliba

Customer Name	Josef  Saliba

Merchant Name	sweetnfresh

Telephone	sweetnfresh

Address	999 8 St SW Calgary AB T2R1J5

TRN Type	delivery

Payment Type	COD

Reference #	47

TRN Date	Aug 24,2022 3:09:10 am

Delivery Date	Aug 24,2022

Deliver ASAP	Yes

Deliver to	calgary  calgary ALBERTA

Delivery Instruction

Location Name

Contact Number	+1343243242

1 Oldenburger 100% Rye	$8.29

Sub Total:	$8.29

Delivery Fee:	$1.99

Tax 5%	$0.41

Tips 10%:	$1.22

Service Fee:	$1.50

Total:	$13.41

Kind Regards';
        sendEmail(                        //my mailing function
                  's****@gmail.com', //to
                  'info@g**.ca', //from
                  'test', //subject
                 $content,
                  20000
                );