text:
Q: Fading pixels[] will not completely fade black (with bitshifting algorithm). How can I make it completely? I want to copy faded pixels from pixels[] to f.pixels[] (of my PGraphics object) and then draw the f image back onto the display. Doing this over and over in draw() is intended to fade the white rectangle to black to match the background, but it is not fading all the way.
It is fading smoothly a little bit, but then it stops fading at some grey color. The lower the fade_amount, the less it ultimately fades.
How can I get the white square to fade all the way to black? Why is it not doing that with this code?
Thanks!
P.S. I have the Pgraphics f object there because I want an off screen drawing buffer later in this project so I can create a feedback loop including transformations during the copying to make something like when you point a camera showing on a tv into the tv.
Also, this is written in processing 1.5.1, it's the latest version that works on my computer.
PGraphics f;
int win_size = 1000;

void setup(){
  size(win_size, win_size);
  f = createGraphics(width, height, P2D);
  background(0,0,0);
  stroke(255,255);
  rect((win_size/2) -40, (win_size/2) -40, 80, 80);
}

void draw(){
  fade_and_copy_pixels(f); //fades window pixels and then copies pixels to f
  background(0,0,0);
  image(f,0,0);
}

void fade_and_copy_pixels(PGraphics f){
  loadPixels();  //load windows pixels
  f.loadPixels(); //loads 2nd layer pixels

  // Loop through every pixel in window
  for (int i = 0; i < pixels.length; i++) {
      color p = pixels[i];
      // get alpha value
      int a = (p >> 24) & 0xFF ;
      // reduce alpha value
      int fade_amount = 5;//at 2 it fades about half way to black, the higher the fadeamount the more it fades. weird
      a = max(0, a-fade_amount);
      // assign color with new alpha-value
      p = (a<<24 | p & 0xFFFFFF) ;
      f.pixels[i] = p;
  }
  updatePixels(); //dont need because I am not wanting to directly edit pixels[]
  f.updatePixels();
}


text:
Q: How to avoid unchecked cast warning when cloning a HashSet? I'm trying to make a shallow copy of a HashSet of Points called myHash. As of now, I have the following:
HashSet<Point> myNewHash = (HashSet<Point>) myHash.clone();

This code gives me an unchecked cast warning however. Is there a better way to do this?

A: You can try this:
HashSet<Point> myNewHash = new HashSet<Point>(myHash);

A: A different answer suggests using new HashSet<Point>(myHash). However, the intent of clone() is to obtain a new object of the same type. If myHash is an instance of a subclass of HashSet, any additional behavior added by subclassing will be lost by using new HashSet<Point>(myHash).
An unchecked cast warning is just a warning. There are many situations in which the cast is safe, but the compiler just isn't smart enough to determine that it is safe. You can, however, isolate the warning into a single method that can be annotated with @SuppressWarnings("unchecked"):
@SuppressWarnings("unchecked")
static <T implements Cloneable> clone(T o) { return (T)(o.clone()); }

redpajama_set_name: RedPajamaStackExchange


text:
Q: in ADF how can i insert data in multiple table if they have foreign key I have started working on ADF and can anybody inform me in ADF how can i insert data in multiple table if they have foreign key,please?
Thnak you very much.

A: When you say that you're inserting data to multiple tables, do you mean ADF Tables? af:table? Or do you mean ViewObject (viewInstance) defined in your datamodel?
You should read more regarding Master-Child relationship in ADF by using ViewLinks and EntityAssociation. Especially these business components are the foundation on how to fully utilize the cascading insert in ADF.
I am using the word "cascading" since if I have a ViewObject which has a child ViewObject and both has a viewLink, which of course would make sense to have them be linked by their foreign keys. On insert of the child assuming that your current row in the parent is set, the child will inherit right away the parent keys as its foreign as well as extended keys.
I hope that helps.
-Marvin


text:
Q: Handling Eventsource using PHP and C# I have created a fileWatcher(running as a service) in C# which calls PHP script through URL whenever there is a change in Folder.
I want to load the web page with new data when there is change in file.
I have tried doing this using javascript Eventsource by calling PHP and echoing by C# whenever there is change in file but no luck.
Any suggestions how would I tackle this problem.

A: I have solved this problem by checking file size every minute and responding to event source. Only overhead is checking file every 1 minute.


text:
Q: Android remoteviews in notification I am developing a music player application. The player is in a service. When a song starts to play i want to show a custom notification with remoteViews.
What i designed for the layout is:

but unfortunately the textviews are gone when the notification is built:

the code for the layout is as follows:
notification_player.xml
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:id="@+id/album_art" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/wrapper"
        android:layout_toRightOf="@+id/album_art"
        android:layout_alignBottom="@+id/album_art">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:id="@+id/player"
            android:layout_marginBottom="10dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/prev"
                android:layout_marginRight="5dp"
                android:src="@drawable/ic_fast_rewind"
                android:layout_gravity="center_vertical" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="1dp"
                android:layout_height="fill_parent"
                android:background="#82c7c7c7"></LinearLayout>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/play"
                android:layout_marginRight="5dp"
                android:layout_marginLeft="5dp"
                android:layout_gravity="center_vertical"
                android:background="@drawable/ic_play_arrow" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="1dp"
                android:layout_height="fill_parent"
                android:background="#82c7c7c7" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/next"
                android:layout_marginLeft="5dp"
                android:layout_gravity="center_vertical"
                android:background="@drawable/ic_fast_forward" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:id="@+id/divider_horizontal"
            android:layout_above="@+id/player"
            android:background="#82c7c7c7"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="10dp"></LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_above="@+id/divider_horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:id="@+id/title"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="25dp"
                android:text="Title"
                style="@style/NotificationTitle"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="singer"
                android:id="@+id/singer"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                style="@style/NotificationText"/>
        </LinearLayout>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/close"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_marginTop="5dp"
            android:layout_marginRight="5dp"
            android:background="@drawable/ic_close" />

    </RelativeLayout>
    </RelativeLayout>

Code in service that is showing the notification:
NotificationCompat.Builder builder;
RemoteViews rv = new RemoteViews(getPackageName(),R.layout.notification_player);
        rv.setImageViewBitmap(R.id.album_art,aq.getCachedImage(item.getImage()));
rv.setTextViewText(R.id.title, item.getTitle());
rv.setTextViewText(R.id.singer, item.getSinger());
rv.setOnClickPendingIntent(R.id.close, delete);

builder = new NotificationCompat.Builder(getApplicationContext())
.setContent(rv)
.setSmallIcon(ir.farzamhabibi.moozik.R.drawable.ic_launcher);

startForeground(10, builder.build());

Any idea what the problem is?
EDIT:
I tried setting the LinearLayout height to wrap content and removing the margins
I even tried adding a textView in all the layouts even in the parent of all but it seems the notification is removing all the textviews.

A: I found out what was wrong.
In my case i was trying to show a layout which was greater than the default notification layout and as the result it was compressing my layout to fit the size of default notification.
I changed the views like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/album_art" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/wrapper"
        android:descendantFocusability="blocksDescendants"
        android:layout_toRightOf="@+id/album_art">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="false"
            android:gravity="center_vertical"
            android:orientation="vertical"
            android:id="@+id/info"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="title"
                android:textStyle="bold"
                />

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="singer"
                />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:descendantFocusability="blocksDescendants"
            android:layout_alignParentBottom="false"
            android:layout_centerHorizontal="true"
            android:id="@+id/player"
            android:layout_below="@+id/divider_horizontal"
            android:layout_marginTop="10dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/prev"
                android:layout_marginRight="20dp"
                android:src="@drawable/ic_fast_rewind"
                android:layout_gravity="center_vertical" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="1dp"
                android:layout_height="fill_parent"
                android:background="#82c7c7c7"></LinearLayout>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/play"
                android:layout_marginRight="20dp"
                android:layout_marginLeft="20dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_pause" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="1dp"
                android:layout_height="fill_parent"
                android:background="#82c7c7c7" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/next"
                android:layout_marginLeft="20dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_fast_forward" />

        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:id="@+id/divider_horizontal"
            android:background="#82c7c7c7"
            android:layout_below="@+id/info"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"></LinearLayout>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/close"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_marginTop="5dp"
            android:layout_marginRight="5dp"
            android:background="@drawable/ic_close" />

    </RelativeLayout>

</RelativeLayout>

And in the notification method i added the following lines which solved the problem:
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification_player);

        builder = new NotificationCompat.Builder(getApplicationContext())
                .setContent(rv)
                .setTicker("IranGrammy playing")
                .setAutoCancel(true)
                .setSmallIcon(ir.farzamhabibi.moozik.R.drawable.ic_launcher);

        rv.setImageViewBitmap(R.id.album_art, aq.getCachedImage(item.getImage()));
        rv.setTextViewText(R.id.title, item.getTitle());
        rv.setTextViewText(R.id.text, item.getSinger());
        rv.setOnClickPendingIntent(R.id.close, delete);
        rv.setOnClickPendingIntent(R.id.play, playPI);
        rv.setOnClickPendingIntent(R.id.next, nextPI);
        rv.setOnClickPendingIntent(R.id.prev, prevPI);
        Notification notif = builder.build();
        notif.bigContentView = rv;
        startForeground(10, notif);


text:
Q: Magento: Auto-change inventory_stock_availability on quantity update In our Magento Shop we're updating our Stock with the extension "Barcode Shipping"(http://www.magentocommerce.com/magento-connect/barcode-shipping.html) or the custom Productgrid from the extension "Enhanced Admin Grids (+ Editor)" (http://www.magentocommerce.com/magento-connect/enhanced-admin-grids-editor.html).
If a product is sold and the stock quantity reaches 0, the attribute inventory_stock_availability is set to "Out of Stock". If the stock is updated, we always have to set the attribute inventory_stock_availability manually to "In Stock".
Is there a way to automatically set the stock availability to "In Stock" when the stock level updates to a value greater than 0? Maybe a custom extension listening to a triggered event?

A: I found a suitable approach by using a combination of @DWils answer and cronjob.
In my extension config (app/code/local/My/UpdateStockAvailability/etc/config.xml):
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <My_UpdateStockAvailability>
            <version>1.0.0</version>
        </My_UpdateStockAvailability>
    </modules>
    <global>
         <models>
            <my_updatestockavailability>
                <class>My_UpdateStockAvailability_Model</class>
            </my_updatestockavailability>
        </models>
        <events>
            <catalog_product_save_after>
                <observers>
                    <my_updatestockavailability>
                        <class>my_updatestockavailability/observer</class>
                        <method>updateStockAvailability</method>
                        <type>singleton</type>
                    </my_updatestockavailability>
                </observers>
            </catalog_product_save_after>
        </events>
    </global>

    <crontab>
        <jobs>
            <updatestockavailabilitycronjob>
                <schedule>
                    <cron_expr>*/15 7-19 * * *</cron_expr>
                </schedule>
                <run>
                    <model>my_updatestockavailability/observer::updateCronAction</model>
                </run>
            </updatestockavailabilitycronjob>
        </jobs>
    </crontab>
</config>

My observer (app/code/local/My/UpdateStockAvailability/Model/Observer.php):
<?php

class My_UpdateStockAvailability_Model_observer {

    public function updateStockAvailability(Varien_Event_Observer $observer) {
        $product = $observer->getProduct();
        $stockData = $product->getStockData();

        if ( $product && $stockData['qty'] ) {
            $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product->getEntityId()); // Load the stock for this product
            $stock->setData('is_in_stock', 1); // Set the Product to InStock
            $stock->save(); // Save
        }
    }

    public function updateCronAction() {
        $collection = Mage::getResourceModel('cataloginventory/stock_item_collection');
        $outQty = Mage::getStoreConfig('cataloginventory/item/options_min_qty');
        $collection->addFieldToFilter('qty', array('gt' => $outQty));
        $collection->addFieldToFilter('is_in_stock', 0);

        foreach ($collection as $item) {
            $item->setData('is_in_stock', 1);
        }
        $collection->save();

        $bundleCollection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect('type')
            ->addAttributeToFilter('type_id', 'bundle')
            ->joinField('is_in_stock', 'cataloginventory/stock_item', 'is_in_stock', 'product_id=entity_id', '{{table}}.stock_id=1', 'left')
            ->addAttributeToFilter('is_in_stock', array('eq' => 0));

        foreach ($bundleCollection as $bundle) {
            $selectionCollection = $bundle->getTypeInstance(true)->getSelectionsCollection($bundle->getTypeInstance(true)->getOptionsIds($bundle), $bundle);

            $allInStock = true;
            foreach ($selectionCollection as $option) {
                $stockItem = $option->getStockItem();
                if ($stockItem->getQty() <= 0 || $stockItem->getIsInStock() <= $outQty) {
                    $allInStock = false;
                }
            }

            if ($allInStock) {
                $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($bundle);
                $stockItem->setData('is_in_stock', 1);
                $stockItem->save();
            }
        }
    }
}

Finally the module xml (app/etc/modules/My_UpdateStockAvailability.xml):
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <My_UpdateStockAvailability>
            <active>true</active>
            <codePool>local</codePool>
        </My_UpdateStockAvailability>
    </modules>
</config>

A: You could handle this by adding an observer to watch for catalog_product_save_before and tell it to check the product Qty, and if > 0 (or the minimum value for out of stock to be triggered)
Then set the flag inventory_stock_availability to 1 and return. That would change the flag before the product save happens.
Bear in mind that this may have other impacts on the store's functionality if the qty and in stock flags were managed separately, depending on how your shop was set up. For instance on one store we have, we hide the buy now if it's set to out of stock and any qty on hand is reserved for someone already, but has not yet shipped.
Here is one article detailing how one would create such an observer
http://blog.chapagain.com.np/magento-event-observer-with-save-before-and-save-after/


text:
Q: In Drupal 7 include a php file in block from a custom module I am new to Drupal and PHP. I am trying to create a module that when activated creates a page, then creates a block, configures block to only show on the created page, and then display an included PHP file. The PHP file that is included is for accessing an off site database.
I have managed to code the module to create the page, and create the block. But the following is my issue.
In the hook_block_view, for content I have input a function name, below I defined the function to include testpage.inc. that page loads but the content does not load in the block's specified region. If I just input text for the content, it loads in the region no problem.
When I define the include as the output value, the block loads the file path, and the included file loads at the top of the page outside of the block.
The Included file is a PHP file that accesses an off site web-service to display a company's Inventory.

<?php

//////////////////////////////////////////////////////////////////
/** using hook_menu to create a page for the module - hook_menu**/
/////////////////////////////////////////////////////////////////
function sps_webconnect_menu() {
  $items['products']=array(
      'title' => 'Products',
      'type' => MENU_NORMAL_ITEM,
      'page callback' => 'sps_webconnect_products',
      'access callback' => TRUE,
      );
  return $items;
}

/** This function defines the page callback from above**/
function sps_webconnect_products() {
  return "&nbsp";
}

////////////////////////////////////////////////////////////////
/** Creates and Defines Block - hook_block_info**/
////////////////////////////////////////////////////////////////
function sps_webconnect_block_info() {
  $blocks['sps_webconnect_block'] = array(
      'info' => t('Products Page - SPS Web Connect'),
      'cache' => DRUPAL_NO_CACHE,
      'status' => TRUE,
      'region' => 'content',
      'visibility' => BLOCK_VISIBILITY_LISTED,
      'pages' => 'products',
  );
  return $blocks;
}

//////////////////////////////////////////////////////////////////////
/* This function defines the content of the block - hook_block_view */
/////////////////////////////////////////////////////////////////////
function sps_webconnect_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'sps_webconnect_block':
      $block['subject'] = t('SPS Product Page');
      $block['content'] = sps_webconnect_file();
      break;
  }
  return $block;
}

function sps_webconnect_file(){
  $output = '';
  module_load_include('inc', 'sps_webconnect', 'testpage');
  return $output;
}

A: You did not provide the content of the inc file but I am pretty sure it outputs (echo/print) data/html and it should not since the last function is supposed to return output.
So you could have a function inside your inc file that returns some html and then call it from your last function to populate $output.

A: Correct, The inc File did include an Echo. When I included a function the inc file and called that function for Output the inc file was loaded in the block. I found out that the reason for this is that Drupal uses Output Buffering, which compiles all of the markup before sending it to the browser. The File I was trying to include was not output buffer friendly.


text:
Q: Prove an inequality involving frame operator $S$ Let $\mathcal{H}$ be a separable Hilbert space with inner product $\langle\cdot, \cdot\rangle$.
A sequence $\left\{f_k\right\}_{k=1}^{\infty}$ of elements in $\mathcal{H}$ is a frame for $\mathcal{H}$ if there exist constants $A, B>0$ such that
$$
A\|f\|^2 \leq \sum_{k=1}^{\infty}\left|\left\langle f, f_k\right\rangle\right|^2 \leq B\|f\|^2, \quad \forall f \in \mathcal{H} .
$$
Let $\left\{f_k\right\}_{k=1}^{\infty}$ be a frame with frame operator $S$ and frame bounds $A, B$. Then it is easily to prove that $S$ is bounded, invertible, self-adjoint, and positive.
We can also prove that
$$A\|f\|^2 \leq\left\langle S f, f\right\rangle\leq B\|f\|^2, \quad \forall f \in \mathcal{H} .$$
Let now $u=Sf\in\mathcal H$.
Is it possible to infer, from the previous inequality, that
$$\frac{\|u\|^2}{B} \leq\left\langle u, S^{-1} u\right\rangle \leq \frac{\|u\|^2}{A}$$
for each $u \in \mathcal{H}$?

A: Let $T=S^{1/2}.$ The inequalities are equivalent to $$A\|v\|^2\le \|Tv\|^2\le B\|v\|^2$$ Let $v=T^{-1}u.$ Then $$A\|T^{-1}u\|^2\le \|u\|^2\le B\|T^{-1}u\|^2$$ Equivalently
$$ B^{-1}\|u\|^2\le \|T^{-1/2}u\|^2\le A^{-1}\|u\|^2$$ The conclusion follows as $\langle u, S^{-1}u\rangle =\|T^{-1/2}u\|^2.$


text:
Q: save,load and update win count using NSUserDefaults in objective c I have two scenes - in GameScene I get win count and save it to BonusScene, every thing works fine, but I want to display win count on GameScene every time, I restart app in BonusScene it show up right count, but in GameScene it starts with 1. Here are what I have been using:   GameScene.m
-(void)winCount{
win++;
winningCount =winningCount +win;
NSLog(@"%i",win);
NSUserDefaults *scoreprefs = [NSUserDefaults standardUserDefaults];
[scoreprefs setInteger:winningCount forKey:@"winningCount"];

winLabel = [SKLabelNode labelNodeWithFontNamed:@"ROTORcapExtendedBold"];
winLabel .fontSize = 70.f;
winLabel .position = CGPointMake(CGRectGetMidX(self.frame)+(CGRectGetMidX(self.frame)/2),CGRectGetMidY(self.frame));
winLabel .zPosition = 5;
winLabel .text = [NSString stringWithFormat:@"%ld",(long)winningCount];
[self addChild:winLabel];

And in BonusScene.m
@implementation BonusScene
@synthesize winningCount;
-(id)initWithSize:(CGSize)size{
NSUserDefaults *scoreprefs = [NSUserDefaults standardUserDefaults];
self = [super initWithSize:size];
if (self){
winningCount =[scoreprefs integerForKey:@"winningCount"];
    SKLabelNode *wins = [SKLabelNode labelNodeWithFontNamed:@"ROTORcap Extended Bold"];
    wins.text =[NSString stringWithFormat:@"%ld",(long)winningCount ];
    wins.position = CGPointMake(CGRectGetMidX(self.frame) + 100,(CGRectGetMidY(self.frame)) + self.frame.size.height/4 );
    wins.fontSize = 15.f;
    [self addChild:wins]

How can I update it in GameScene so it will show same result as in BonusScene?

A: Update your game scene with
-(void)winCount{
   // get previous count first
    winningCount =[scoreprefs integerForKey:@"winningCount"];
    win++;
    winningCount = winningCount + win;
    NSLog(@"%i",win);
    // other code of the function


text:
Q: How to generate an pdf invoice in a NodeJs, Express and JQuery? I have made a program based on the stack NodeJs + Express + MongoDB. It is following salesorders in the process of handling. The program works fine.
Now I like to add an option to take the data of a specific salesorder (MongoDB database) and generate a .pdf invoice. Where to start?
Are there programs/options to generate a sort of dynamic fields?
How to fill a certain pdf with data from a database in NodeJs/Express? Preferably with MongoDB?

A: There are several options available to solve your problem.
Process

*

*Generate and HTML using dynamic values

How to generate?
You can use template engines like handlebars/EJS etc.
They accept JSON and render the HTML page dynamically

*Generate PDF

How to generate?
There are many npm modules available which take a screenshot of HTML page and generates image or pdf.
Suggestion: Use Puppeteer
alternative: phantomjs, jsonToPdf etc.

A: You can create HTML and store it into a variable. Then there are lots of npm package available to convert HTML to pdf.


text:
Q: Foreign Key in Django - second Form I have a second form that have to be filed after the first.
However I'm not able to save the relation between both models, unless I give the option for the person that have filing the forms chose the email for the first form.My idea is to give this information directly on the back end, but I cant do that.
My models are too big to post all here, so if any can help me with a generic idea I will be glad.
I'm using in both forms a ModelForm in Django.
my Models:
                                           User
                                         Person
                    Volunteer  -  Client - Staff
Than I have 3 types of volunteers: Admin; Program; Committee;
After I fill the Volunteer-Person-User model, I need to go to the next form for Volunteer Admin or Volunteer Program or Volunteer Committee;
because the user uses the email as a primary key also, thats the value when I create the foreign key from my admin program and the modelform give me the choices to the email. but on the database, only keeps the id for the reference.
my first view that's handling the first form:
def volunteer_form(request):

if request.method == 'POST':
    form = VolunteerForm(request.POST)
    if form.is_valid():
        saving = form.save(commit=False)
        saving.password = make_password(form.cleaned_data['password'])
        saving.save()
        item = saving.id
        if saving.person_volunteer_type == 'Program':
            return HttpResponse('<script language="JavaScript"> location.href="http://127.0.0.1:8000/login/volunteer_program?id=' + str(item) + '" </script>')

        elif saving.person_volunteer_type == 'Admin"]':
            return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

        elif saving.person_volunteer_type == 'Committee':
            return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

else:
    form = VolunteerForm()

return render(request, 'loginPortal/volunteer_form.html', {'form' : form})

the on handling the 2nd form:
def volunteer_program(request):
if request.method == 'POST':
    form = VolunteerProgramForm(request.POST)
    if form.is_valid():
        saving = form.save(commit=False)
        saving.pvolunteer_personid_id = form.cleaned_data.get('id_pvolunteer_personid_id')
        saving.save()
        return HttpResponse('<script language="JavaScript"> alert("You have sucessful created a new Volunteer"); location.href="http://127.0.0.1:8000/login/clock_in/" </script>')

elif request.method =='GET':
    item = request.GET['id']
    form = VolunteerProgramForm()

    return render(request, 'loginPortal/volunteer_program.html', {'form' : form , 'item' : item })

else:
    form = VolunteerProgramForm()

return render(request, 'loginPortal/volunteer_program.html', {'form' : form })

A: Generic answer, asuming that your second model has a ForeignKey to the first model. Do this in your view's post:
1) Validate the first form, if it won't validate, return with errors.
2) Validate the second form, if it won't validate, return with errors.
3) If both validate, save the instance from the first form:
first_instance = first_form.save()

4) Save the instance from the second form without commiting changes to database:
second_instance = second_form.save(commit=False)

5) Update the foreign key on the second model instance:
second_instance.fk_to_first_model = first_instance

6) Save the second instance to database
second_instance.save()

7) Return success!


text:
Q: Как изменять текст menu в popupmenu программно popupmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/menugroup1" >
        <item
            android:id="@+id/menu1"
            android:title="Урок 1"/> //хочу программно менять эти тексты
        <item
            android:id="@+id/menu2"
            android:title="Урок 2"/> //хочу программно менять эти тексты
        <item
            android:id="@+id/menu3"
            android:title="Урок 3"> //хочу программно менять эти тексты
        </item>
        <item
            android:id="@+id/menu4"
            android:title="Урок 4"> //хочу программно менять эти тексты
        </item>
    </group>
</menu>

MainActivity
private void showPopupMenu(final View v) {
        PopupMenu popupMenu = new PopupMenu(this, v);
        popupMenu.inflate(R.menu.popup);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menu1:
                                Intent intent = new Intent(Lessons.this, LearnWordsFamily.class);
                                startActivity(intent);
                                return true;
                            case R.id.menu2:
                                Intent intent2 = new Intent(Lessons.this, LearnWordsFamily.class);
                                startActivity(intent2);
                                finish();
                                return true;
                            case R.id.menu3:
                                return true;
                            case R.id.menu4:
                                return true;
                            default:
                                return false;
                        }
                    }
                });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {

            @Override
            public void onDismiss(PopupMenu menu) {
            }
        });
        popupMenu.show();
    }

A: Примерно как-то так:
popup.getMenu().findItemById(R.id.ITEM_ID).text = "newText";


text:
Q: How do I convert Q format integers to float (or vice versa)? I searched around and couldn't find a good SO question with a general answer to this question:
Given an integer using Q Format, how do I convert that number to a normal floating point type?
Or vice versa: how do I convert a floating point type into a Q Format integer?
For example, the Q2 integer 5 should be 1.25 in floating point, and the floating point number 1.25 should be the integer 5 in Q2 format.

A: The following is a general C++ solution:
template<class IntegerType>
float qToFloat(IntegerType q, int fractional_bits)
{
    return ((float) q) * std::pow(2, -fractional_bits);
}

template<class IntegerType>
IntegerType floatToQ(float q, int fractional_bits)
{
    return (int) (q * std::pow(2, fractional_bits));
}

Example usage:
qToFloat<uint16_t>(5, 2);     //1.25
floatToQ<uint16_t>(1.25f, 2); //5


text:
Q: How can I find the indices in a numpy array that meet multiple conditions? I have an array in Python like so:
Example:
>>> scores = numpy.asarray([[8,5,6,2], [9,4,1,4], [2,5,3,8]])
>>> scores
array([[8, 5, 6, 2],
   [9, 4, 1, 4],
   [2, 5, 3, 8]])

I want to find all [row, col] indices in scores where the value is:
1) the minimum in its row
2) larger than a threshold
3) at most .8 times the next largest value in the row
I would like to do it as efficiently as possible, preferably without any loops. I've been struggling with this for a while, so any help you can provide would be greatly appreciated!

A: It should go something along the lines of
In [1]: scores = np.array([[8,5,6,2], [9,4,1,4], [2,5,3,8]]); threshold = 1.1; scores
Out[1]:
array([[8, 5, 6, 2],
       [9, 4, 1, 4],
       [2, 5, 3, 8]])

In [2]: part = np.partition(scores, 2, axis=1); part
Out[2]:
array([[2, 5, 6, 8],
       [1, 4, 4, 9],
       [2, 3, 5, 8]])

In [3]: row_mask = (part[:,0] > threshold) & (part[:,0] <= 0.8 * part[:,1]); row_mask
Out[3]: array([ True, False,  True], dtype=bool)

In [4]: rows = row_mask.nonzero()[0]; rows
Out[4]: array([0, 2])

In [5]: cols = np.argmin(scores[row_mask], axis=1); cols
Out[5]: array([3, 0])

At that moment if you're looking for actual coordinate pairs, you can just zip them:
In [6]: coords = zip(rows, cols); coords
Out[6]: [(0, 3), (2, 0)]

Or if you're planning to look those elements up, you can use them as is:
In [7]: scores[rows, cols]
Out[7]: array([2, 2])

A: I think that you're going to have a hard time doing this with out any for loops (or at least something that performs such a loop but might be disguising it as something else), seeing as how the operation is only dependent on the row and you want to do it for each row. It's not the most efficient (and what is may depend on how frequently conditions 2 and 3 are true) but this will work:
import heapq
threshold = 1.5
ratio = .8
scores = numpy.asarray([[8,5,6,2], [9,4,1,4], [2,5,3,8]])

found_points = []
for i,row in enumerate(scores):
    lowest,second_lowest = heapq.nsmallest(2,row)
    if lowest > threshold and lowest <= ratio*second_lowest:
        found_points.append([i,numpy.where(row == lowest)[0][0]])

You get (for the example):
found_points = [[0, 3], [2, 0]]


text:
Q: CoreStore offline mode sync features I import unique objects from the server and at the same time create offline local objects with iOSLocalId which is my offline local id.
I use this func for unique import:
public class func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -> UniqueIDType? {
        return source["id"] as? UniqueIDType
    }

my question is can I specify few uniqueIDs like
public class func uniqueID(from source: ImportSource, in transaction: BaseDataTransaction) throws -> UniqueIDType? {
        return source["iOSLocalId"] as? UniqueIDType
    }

I need this for binding two objects. Local (which was created offline) and the same received from server.
So the workflow is next:

*

*Cerate local object which contains only iOSLocalId but does not contain server id as we work offline for example

*When connection appears to be online push local object to server.

*When API return back created object on the server sync local and server object.

In this case I need somehow tells CoreStore that I have two unique ids, one is local which server also pass back to me and one is server id for the same object.
But maybe there is another approach as well.
For sure I can write my own Service which will search for already exist local object and update them.
Maybe I can use some of this function:
public static func shouldInsert(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool {
        return shouldUpdate(from: source, in: transaction)
    }

    public static func shouldUpdate(from source: ImportSource, in transaction: BaseDataTransaction) -> Bool {
        return true
    }

But as I said I need to update every time I found server id, but in case of offline sync, I also have local id and then there is a problem of determining unique id.


text:
Q: Consistent timeouts on AWS IoT I'm trying to get a raspberry pi to communicate to the IoT service. At this point, I'm just running the sample script. I've got a cert generated, a liberal access policy and stole the endpoint from a device I created. When I try to run the script, here's what happens:
2016-08-06 23:30:56,282 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Paho MQTT Client init.
2016-08-06 23:30:56,283 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - ClientID: basicPubSub
2016-08-06 23:30:56,283 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Protocol: MQTTv3.1.1
2016-08-06 23:30:56,283 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Register Paho MQTT Client callbacks.
2016-08-06 23:30:56,283 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - mqttCore init.
2016-08-06 23:30:56,284 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load CAFile from: certs/iot-root-cert.pem
2016-08-06 23:30:56,284 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Key from: certs/xxxxx-private.pem.key
2016-08-06 23:30:56,284 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Load Cert from: certs/xxxxx-certificate.pem.crt
2016-08-06 23:30:56,285 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: baseReconnectTime = 1 sec
2016-08-06 23:30:56,285 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: maximumReconnectTime = 32 sec
2016-08-06 23:30:56,285 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for backoff timing: minimumConnectTime = 20 sec
2016-08-06 23:30:56,286 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: queueSize = -1
2016-08-06 23:30:56,286 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for publish queueing: dropBehavior = Drop Newest
2016-08-06 23:30:56,286 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Custom setting for draining interval: 0.5 sec
2016-08-06 23:30:56,287 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum connect/disconnect timeout to be 10 second.
2016-08-06 23:30:56,287 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Set maximum MQTT operation timeout to be 5 second
2016-08-06 23:30:56,288 - AWSIoTPythonSDK.core.protocol.mqttCore - INFO - Connection type: TLSv1.2 Mutual Authentication
2016-08-06 23:30:57,124 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Disconnect result code 1
2016-08-06 23:30:58,525 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Disconnect result code 1
2016-08-06 23:31:00,973 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Disconnect result code 1
2016-08-06 23:31:05,463 - AWSIoTPythonSDK.core.protocol.mqttCore - DEBUG - Disconnect result code 1
2016-08-06 23:31:07,079 - AWSIoTPythonSDK.core.protocol.mqttCore - ERROR - Connect timeout.
Traceback (most recent call last):
  File "basicPubSub.py", line 153, in <module>
    myAWSIoTMQTTClient.connect()
  File "/usr/local/lib/python2.7/dist-packages/AWSIoTPythonSDK/MQTTLib.py", line 355, in connect
    return self._mqttCore.connect(keepAliveIntervalSecond)
  File "/usr/local/lib/python2.7/dist-packages/AWSIoTPythonSDK/core/protocol/mqttCore.py", line 291, in connect
    raise connectTimeoutException()
core.exception.AWSIoTExceptions.connectTimeoutException

same thing happens when i try websockets. Doesn't seem to be a reachability issue, I can curl that URL fine (though get no response). Ideas?

A: Turns out the issue is that you need to:

*

*have both a policy and a certificate in the console

*explicitly associate them to each other


text:
Q: Automator workflow not running on schedule I have a workflow set up to download backups of my websites.
The workflow itself works fine, but i am having trouble scheduling it with iCal.
When the iCal event triggers, the workflow opens in automator, but does not run.
I dont understand why it wont run.

A: You save the Workflow as an Application, then run THAT with iCal. Opening a workflow does not make it run; that's only for editing the workflow.


text:
Q: Animate a path? I have a set of coordinates. I would like to take, for instance, the first 5 and draw a line connecting 1 to 2 to 3 to 4 to 5. Then after a pre-determined duration, I'd like to remove the first point and add the 6th point. In doing that, I'd like the line to animate in such a way as the "beginning" of the line moves from point 1 to point2, while the end of the line moves from point 5 to point 6.
The effect here would look a lot like the old game Nibbles with the snake that moves around eating stuff.
What would be the most efficient way to approach this in WPF?
Thanks in advance!

A: I would use the Polyline and manipulate the Points collection by simply adding and removing the points.
See msdn for example code.

A: Going to post a rough outline of my solution here. I actually ended up using a PathGeometry object and a set of DoubleAnimationUsingPath animations to get what I wanted. Polyline (suggested by Damokles) got me going in the right direction, but it wasn't until I found the DoubleAnimationUsingPath class that I was able to take it where I wanted to go.


text:
Q: Reading PDF file using javascript I'm currently developing an application that would Copy/Transfer a sentence/paragraph from a PDF file to my program. I'm using Javascript to develop my program but I have not found any idea how to read a PDF file.
I want to know how to Copy/Transfer a sentence/paragraph from a PDF file to my program?
Thanks.

A: Check out PDF.js, it's a commonly used JavaScript library that contains a lot of methods for PDF manipulation.
Check out this answer to see a demonstration of how to extract text using pdf.js.

A: I know that the question is old, but if you find PDF.js too complex for the job, npm install pdfreader. (I wrote that module)
It would take 5 lines of code to extract text from your PDF file:
var PdfReader = require("pdfreader").PdfReader;
new PdfReader().parseFileItems("sample.pdf", function(err, item){
  if (item && item.text)
    console.log(item.text);
});


text:
Q: onBlur function not executing I've been searching for an answer for why this isn't working for several hours, and I'm stumped.
Here's the script including the javascript and form involved.

<FORM METHOD="POST" NAME="frmMain" ACTION=<?php echo $_SERVER["PHP_SELF"]; ?>>

            Name:

                <input type="text" name="txtSender" size="30" value=""/> Your Name

            Attorney:

                <input type="text" name="txtAtty" size="30" value="" onblur = "complete(this.value)">

The two PHP echo statements are the parameters for the Arrays. The complete(this.value) function is supposed to take a 3 letter code (in the iList array) and substitute it with a name. The alerts are in there for debugging purposes, but i don't get either alert when i run the page. Any ideas?

A: this.frmMain
is not defined anywhere
change
onblur = "complete(this.value)"

to
onblur = "complete(this)"

and use
function complete(field){
  var init = field.value;
        alert ("in function with " + init);
        var aList = new Array(<?php echo $aList; ?>);
        var iList = new Array(<?php echo $iList; ?>);
        for (var i = 0; i < iList.length; i++){
            if (init == iList[i]){
                alert ("replacing " + init + " with " + aList[i]);
                field.value = aList[i];
            }
        }
    }


text:
Q: why does gnome 3 lag in all distributions? For some reason every single animation in gnome 3 lags a lot on my laptop (lenovo e330). I have tried the most recent version of a lot of different distros: ubuntu gnome, debian, centos, antergos, fedora, opensuse, zorin, arch but they have the same performance problem with gnome. My laptop is reasonably powerful: core i3, 8gb ram and intel 3000 graphics. I have no lag whatsoever in windows 10, ubuntu with unity, any kde distro so this seems to be a gnome problem.
How can I fix this?

A: Thats simply how it is. Gnome has laggy animations. Partial solution is to install impatience and remove all other extensions.


text:
Q: How do you create a transactional stream in C++? I need to create "transactional stream" in C++. What I mean by "transactional stream" is a stream that will rewind if there is an error at some point in the processing. For example,
if a stream's consumer somehow fails to process the stream's data, I want the stream to be reverted to its state before producing that data.
Perhaps a lazy stream would achieve this? Is this a common situation with a common solution or am I bound to writing my own custom implementation for my specific problem?

A: Well, the first thing that comes to mind is to combine a range interface (for laziness and composability) with a transactional interface (for backtracking):
#include <iostream>
#include <stack>
#include <sstream>

struct transaction_failure {};

class transactional_istream_range {

  std::istream& stream;
  std::stack<std::streampos> states;

public:

  transactional_istream_range(std::istream& stream)
    : stream(stream) {}

  // Transaction interface.

  template<class R, class T>
  R transaction(R(*body)(T&)) {
    try {
      begin();
      R result = body(*this);
      commit();
      return result;
    } catch (const transaction_failure&) {
      rollback();
    }
    return R();
  }

  void begin() {
    states.push(stream.tellg());
  }

  void commit() {
    states.pop();
  }

  void rollback() {
    stream.seekg(states.top());
    states.pop();
  }

  // Range interface.

  bool empty() const {
    return stream.peek() == EOF && stream.eof();
  }

  char front() const {
    return stream.peek();
  }

  void pop_front() const {
    stream.ignore(1);
  }

};

You can then easily write template functions operating on transactional ranges:
#include <cctype>

template<class R>
std::string parse_integer(R& input) {
  std::string result;
  while (!input.empty()) {
    if (std::isdigit(input.front())) {
      result += input.front();
      input.pop_front();
    } else {
      throw transaction_failure();
    }
  }
  return result;
}

int main() {
  std::istringstream stream("1234a");
  typedef transactional_istream_range tir;
  tir input(stream);
  std::string result = input.transaction(parse_integer<tir>);
  std::cout << "Result: " << result;
}

This is just a first approximation; you could probably get around having to specify the type of range to the transactional function (i.e., just parse_integer rather than parse_integer<...>). It's pretty straightforward to write many kinds of lazy streams and lazy algorithms in range form.
As for extending this, you could parameterise the transaction handling to invoke a user-specified commit or rollback function, or just implement each type of rollback individually. It might also be beneficial to decouple the range interface from the transaction interface using mixins. I can't think of a good way to do it right now without resorting to virtual functions, though.

A: If you're working on Windows there's something called Structured Storage which provides a form of transactions. You might have to break your problem up into separate streams.
Here's more info:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa380369(v=vs.85).aspx
Alternatively you could look at using something like SQLite or Firebird to provide a back-end transactional storage.


text:
Q: Import JSON file into MongoDB I have a MongoDB instance on a Virtual Machine and I can connect using Compass.  I have manually uploaded a JSON file using command line on that virtual machine without issue.  The import creates two documents and works as expected using the command line:
mongoimport --jsonArray --db Historian_ManyDocs --collection TagValues --file historianData1.json

The json has the following format in the historianData1.json file:
[
    {
      "tagname": "99CalcTrigger",
      "engunits": "",
      "value": "2",
      "quality": "Good NonSpecific",
      "timestamp": "2018-12-13T10:45:05Z"
    },
    {
      "tagname": "Blank",
      "engunits": "",
      "value": "0",
      "quality": "Good NonSpecific",
      "timestamp": "2018-12-13T10:45:00Z"
    }
]

I want to automate this process somewhat and I have been playing with c# to do this using the following code:
    string line;
    using (StreamReader reader = new StreamReader(@"C:\historianData1.json")){
        line = reader.ReadLine();
    }

    var client = new MongoClient("mongodb://mongoserverIP:27017");
    var database = client.GetDatabase("Historian_ManyDocs");
    dynamic array = Newtonsoft.Json.JsonConvert.DeserializeObject(line);
    foreach (var item in array)
    {
        var document = BsonSerializer.Deserialize<BsonDocument>(item);
        var collection = database.GetCollection<BsonDocument>("TagValues");
        await collection.InsertOneAsync(document);
    }

This errors with the following error on the var document line with the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best
  overloaded method match for
  'MongoDB.Bson.Serialization.BsonSerializer.Deserialize(MongoDB.Bson.BsonDocument,
  System.Action)'
  has some invalid arguments'

Can anyone offer some suggestions please as I have been on this for 4 hours now.

A: You have to insert a POCO class into MonngoDB, so please create it like this:
public class POCOData
{
  public string tagname;
  public string engunits;
  public string value;
  public string quality;
  public TimeOffset timestamp;
}

after you can use it in Deserialize:
foreach (var item in array)
{
    var document = BsonSerializer.Deserialize<POCOData>(item);
    var collection = database.GetCollection<BsonDocument>("TagValues");
    await collection.InsertOneAsync(document);
}


text:
Q: Jekyll Localized Host I'm pretty sure it's not possible but does anyone know of a configuration that can localize the exported files in Jekyll so that the _site content can run independent of a web host?
I want to use Jekyll to develop a site, and deliver the contents of the _site folder for hosting, but I will not have the hosting information ahead of time. So I would like to be able to run the index.html file in the _site folder directly from the Desktop and have the site work properly. That way I can deliver the files and the site will run using relative paths/links regardless of where the files end up being hosted.

A: This possible but you need to know where your generated site will be located on the filesystem. This, because of the relative links pointing to resources (js, css, images).
For example a site generated at /home/user/www/_site, index page will be serve in your brower at file:///home/user/www/_site/index.html, so you'll have to set baseurl in _config.yml to baseurl: /home/user/www/_site in order to have you site working.
On windows it can be baseurl: /C:/Users/New/www/_site


text:
Q: AngularJS + webpack hot module replace ignores changes in app.controllers I have implemented the Webpack HMR to my AngularJS 1.7.2 project.
If I change something in the .js files and save I have the update hot without refresh.
However, everything resides under app.controller or anything else made by AngularJS, is doesn't working.
For example:
module.exports = app => {

 console.log(1); // will be hot updated

 app.controller("myCtrl", () => console.log(2)); // will not update in case I change the 2 to 3, or something else.

}

This is the webpack.config.js file:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = (env, argv) => {
  return {
    entry: './src/webpack.entry.js',
    output: {
      filename: 'bundle.js',
      chunkFilename: '[name].bundle.js',
      path: path.resolve(__dirname, './www')
    },
    plugins: [
      // new HtmlWebpackPlugin({
      //   template: "./src/index.html"
      // }),
      new webpack.HotModuleReplacementPlugin()
    ],
    devServer: {
      contentBase: path.resolve(__dirname, './www'),
      hot: true,
      inline: true
    },
    // devtool: argv.mode == "development" ? 'inline-source-map' : false,
    module: {
      rules: [
        {
          test: /\.(html)$/,
          exclude: /node_modules/,
          use: {
            loader: 'html-loader',
            options: {
              attrs: [':data-src']
            }
          }
        },
        {
          test: /\.(woff(2)?|ttf|eot|svg|jpg|jpeg|png|jpg|gif)$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'file-loader',
              options: {}
            }
          ]
        },
        {
          test: /\.css$/,
          exclude: /node_modules/,
          use: [
            'style-loader',
            'css-loader',
          ]
        },
        // {
        //   test: /\.scss$/,
        //   exclude: /node_modules/,
        //   use: [
        //     'sass-loader'
        //   ]
        // }
      ]
    },
    optimization: {
      minimize: false
    }
  };
}

And I would like to provide with the webpack.entry.js file too:
// angularjs app first initialization
var app = require('./app/app');

// ionic core css
require('./assets/css/ionic.bundle.css');

// app scripts
require('./app/index')(app);

// screens scripts
require('./screens/index')(app);

// assets
require('./assets/css/custom-both.css');

// NOTE: without this, it fully reloads the webpage instead of making it hot reload - even when the config sets with hot:true
if (module.hot) {
  module.hot.accept();
}


text:
Q: How to modify number using NSNumberFormatter? I have values such as:
5.1M (5100000)
80M (80000000)
300.5M (300500000)

5K (5000)
2000K (2000000)
200.5K (200500)

(Values I need to turn them into are in parenthesis behind the numbers).
Basically, a number can have a decimal point or no decimal point, can end with K (for thousand) or M (for million), but ONLY when it's a whole number (i.e. 0.5M needs to be 500000; no commas).
I also need to be able to convert numbers back to their original form.
How do I do this, and what's the best way to do it?

A: A while back I wrote and open-sourced a custom NSNumberFormatter called SQSMetricFormatter (https://github.com/shultzc/SQSMetricFormatter) that, well, formats numbers using metric prefixes.
It might do what you need, or at least provide a jumping off point for implementing your own solution.

A: So you're saying you have an NSString that starts with a number and ends with K or M? And you want to see what it consists of, and convert it to an actual numeric value? This is a job for NSScanner.
Though, to be quite honest, NSScanner was around long before regular expressions became available in Objective-C; nowadays I might just use NSRegularExpression.
Or, if you know for a fact that it really is a number followed by K or M, then you don't even have to do that. Just pull the last character off the end. That's the K or the M and you now know which it is. And what's left is a numeric string and you can just convert it to a number.
Pseudocode (not tested):
NSString* s = @"5.1M";
NSUInteger len = s.length;
NSString* numPart = [s substringToIndex: len-2];
NSString* unitPart = [s substringFromIndex: len-1];
int multiplier = 1000;
if ([unitPart isEqualToString: @"M"])
    multiplier = 1000000;
float result = numPart.floatValue * multiplier;


text:
Q: component visible if boolCheckBox is checked I have a web page, which contains several components, when I click on boolCheckbox, I want to disappear some other components, I tried to use the rendered attribute but it's doesn't work.
is there a visible attribute (or its equivalent) for simple component like : boolCheckBox, inputText, ... ?
<p:selectBooleanCheckbox value="#{Bean.check}" >
    <p:ajax update="check2" listener="#{Bean.function()}"/>
</p:selectBooleanCheckbox>

<p:selectBooleanCheckbox id="check2" value="#{Bean.check2}" rendered="#{Bean.check}">
</p:selectBooleanCheckbox>

thank you.

A: You're updating the component that should not be displayed after the value change. You should update the parent component. For example:
<p:selectBooleanCheckbox value="#{Bean.check}" >
    <p:ajax update="check2-parent" listener="#{Bean.function()}"/>
</p:selectBooleanCheckbox>

<p:panel id="check2-parent">
    <p:selectBooleanCheckbox id="check2" value="#{Bean.check2}" rendered="#{Bean.check}"/>
</p:panel>

A: Use:
$('checkbox').on('click', function() {
 if($(this).is(':checked')) {
  // checked do something
  $('.classname').hide();
 }
 else {
  // not checked do something else
  $('.classname').show();
 }
});


text:
Q: How to join tables resulting in JSON with Rails 4? Having the following entities, Rent and Region:
class Rent < ActiveRecord::Base
  belongs_to :region

  validates :region, presence: true
end

class Region < ActiveRecord::Base
  has_many :rents
end

To get a Rent object is simple doing the following:
  def show
    rent = Rent.find(params[:id])
    render json: rent
  end

This will successfully return the Rent:
{
  "id": 1,
  "title": "blah",
  "region_id": 1,
  "created_at": "2014-12-16T04:09:00.407Z",
  "updated_at": "2014-12-16T04:09:00.407Z"
}

Now, I want to join this result with the Region. The ideal result would be similar to this:
{
  "id": 1,
  "title": "blah",
  "region_id": 1,
  "created_at": "2014-12-16T04:09:00.407Z",
  "updated_at": "2014-12-16T04:09:00.407Z"
  "region": {
    "id": 1,
    "title": "blah",
    "created_at": "2014-12-16T04:09:00.507Z",
    "updated_at": "2014-12-16T04:09:00.507Z"
  }
}

In order to accomplish this, the official RoR documentation mention the use of the join clause which should solve this issue. So this is what I did:
  def show
    rent = Rent.joins(:region).find(params[:id])
    render json: rent
  end

Unfortunately the result of this last snipe is exactly the same that getting the rent by it self. There is not region object included on the JSON response.
What am I doing wrong and what should I do instead?

A: Try
rent = Rent.find(params[:id])
render :json => rent.to_json(:include => :region)

This will include the object data from the relationship when it is creating the JSON for your object.


text:
Q: RegEx help for IIS URL Rewrite I need to take request for
www.domain.com/123456/Catalog.aspx

and rewrite to
www.domain.com/Products/Catalog.aspx?ItemID=123456

where 123456 will always be numbers.
Any help is appreciated. Thanks.

A: You want to match this pattern:
^(\d+)/([^/]+)$

And then rewrite to this URL:
Products/{R:2}?ItemId={R:1}


text:
Q: browser for creating mobile game app I don't know whether my question belongs here but I am asking it anyways. Why is there not a lot of shift in creating the game using HTML5 rather than creating a native  game app, especially for mobile application? While I understand completely and assuming my understanding to be correct, for desktop games, a native game can use the graphics card in the computer taking the hefty load of graphics processing off from the CPU. What is the case for mobile browser? Does the mobile browser allowed to have the equal amount of processing resources as the native app? As far as I think, the processor is all and all in mobile phones. If this is correct then, I would think it would be more easier to create game with browser.
Is my understanding correct? Am I missing something here? What is the catch if I want to create game app using HTML and javascript?

A: A game as a native app would usually be written in a much more efficient language than javascript, for example Java on Android or Objective-C on iOS. Javascript is usually interpreted as it is run (as far as I know), and this affects the performance. Also, while you can obfuscate javascript to hide the implementation (if you want to protect your code), it isn't as effective as compiling a native app (I don't know how hard it is to reverse-engineer Java though).
However, WebGL is becoming more popular, and lets javascript code use hardware acceleration to accelerate graphics. When this is well supported on mobile devices, it might be feasible to make a complex game in the web browser. It certainly makes it more portable, and you could put it in a native WebView (or similar), for it to act like a native app.
Some examples here: http://www.chromeexperiments.com/webgl/

A: There's a couple potential drawbacks for HTML 5, one of which has already been pointed out, is a potential performance hit.  This is sorta a big one, especially for devices that aren't capable of using WebGL.  The other really big one for me anyways, is bandwidth use.  Most phones (at least in the USA) are on fairly restrictive data plans, and thus if you're accessing the game via HTML 5, you're potentially eating into your bandwidth use every time you play, meanwhile a native app is downloaded once, and that's the last of the data usage...input lag is another biggie, particularly if your game requires specific timing.  Granted, as speeds get faster on mobile devices this becomes less and less of an issue, but it will never be equal to what can be done locally on a native app.  Lastly, as was pointed out, code hiding, you may or may not care about, but it's easier to do on a native app.


text:
Q: Using setTimeout to avoid re-renders in React There is a pattern that I use often that I feel must be an anti-pattern but I don't know a better alternative.
Occasionally my components may receive one or more events that mean that a re-render is necessary.  Sometimes it is the case that I do not know how many times the event handlers will be called.  To prevent multiple re-renders as a result of many calls to the handlers I do something like this:
 _myEventHandler() { // may be called multiple times between renders
   if (!this._updateQueued) {
     this._updateQueued = true;
     this._updateTimer = setTimeout(() => {
       this._updateQueued = false;
       this.forceUpdate();
     }, 0);
   }
 }

The problem here is I feel it can't be performant due to the latency between code stopping and the event loop starting.
A real world example of this is when I am using react-visibility-sensor and I have multiple elements change their visibility at once, I don't want to re-render for each element, instead I want just one re-render once all the updates have been received.
Is there another better way to deal with multiple calls?
BTW: if you are going to use the above hack don't forget to call clearTimout(this._updateQueued) in your componentWillUnmount

A: A debounce will reduce the number of times a certain piece of code is run, regardless of how often it is called. Here is a rather simple implementation.
const debounce = (callable, time) => {
  let timeout;

  return function() {
    const functionCall = () => callable.apply(this, arguments);

    clearTimeout(timeout);
    timeout = setTimeout(functionCall, time);
  };
};

And this is how to use it.
const debouncedIteration = debouce(() => {
   console.log("Iteration"); // This will be called once every 1000 milliseconds.
}, 1000);

while (true) {
   debouncedIteration();
}

A: You can avoid re-renders using this lifecycle method shouldComponentUpdate (as also mentioned by @fungusanthrax). Keep this inside your react component :
shouldComponentUpdate(nextProps, nextState) {
  return !isEqual(this.props, nextProps) || !isEqual(this.state, nextState);
}

using isEqual from lodash here, make sure to include it.
This will only re-render your component when there's a change in props or state value.
To install lodash:
npm install -S lodash

and import isEqual in your component file :
import isEqual from 'lodash/isEqual';


text:
Q: Proactive messaging with prompt buttons - Microsoft Bot Framework I've been playing around with proactive messaging, but I'm not sure how to achieve something like this. I've got a service that messages users products on a daily basis. Using a resumption cookie I call an end point, build a response by setting the .Text property and create the carousel of products by populating the .Attachments property. I want to add buttons to this message to allow a user to stop the alerts, but the only event a CardAction button allows is opening an URL in a web browser. Is there a way of creating a button which can trigger a method, or call a new dialog?
Any help will be greatly appreciated.

A: You can just use the ImBack or PostBack ActionTypes on the CardAction. Clicking on a button when using any of those, will send a message to the conversation with the Value of the action that will end up arriving to the method you are "waiting" (by doing context.Wait(...));
Then, in that method you can do whatever you want: call a new dialog or any other logic you want to trigger.
In the ContosoFlowers sample you can see how a card with buttons is used in that way.


text:
Q: dynamic table row creation in html/Javascript I have html table with 1 row to fill in job details for a position.Now If a user wants to fill in job details for another position,on clicking a link, a new row should be created dynamically each time the user clicks the link.Can any one please help me with the code in html
I'm using frontpage.
Thanks,
Vix

A: I would suggest looking into jQuery, the most powerful javascript framework.  It is popular and you can find lots of references, resources, plugins, code etc. to help you do lots of this stuff.
Here is a stackoverflow question covering adding a table row to a table using jQuery.
Add table row in jQuery

A: in simple Dom-Javascript without any frameworks you could use something like this
var tr  = document.createElement('tr');

var td1 = document.createElement('td');
var someDivToAppend = document.createElement('div');
someDivToAppend.innerHTML = "Some basic text content";

td1.appendChild(someDivToAppend);
tr.appendChild(td1);
...

But I guess that's probably too much handy work, a library like jQuery could help you there.
You could look at: http://api.jquery.com/append/

A: Also look at the YUI Datatable. Very full featured, and well documented.


text:
Q: User control with a client side API Maybe I've picked a totally inappropriate/bad example.
What I have is a user control that contains a bunch of dynamically created Telerik RadGrids.
My user control is added to a couple of Telerik RadPageViews that are part of a RadMultiPage that is used alongside a RadTabStrip.
What I need to do is call a Javascript function in my usercontrol to update it's display whenever it's parent RadPageView is selected.
So basically I have the following Javascript code:
function OnClientTabSelected(sender, args)
{
    // Get the MyControl that is on this tab
    var myControl = $find("whatever");

    // Call a method that updates the display
    myControl.doSomething();
}

Thanks,
David

A: You can add a wrapper div in your User Control and then extend that div using jQuery to add your desired methods and properties.  The trick is to set the div's id='<%=this.ID%>' - that way the div has the same ID as the User Control (which is fine because the User Control doesn't actually render anything - only its contents).
Then back on your containing page, you can just reference your UserControl's ID using $get('whatever') - and you'll actually select your extended div.. which will have all your methods and properties on it.
The nice thing about this approach is that all of your methods and properties and neatly scoped and nothing is in the global namespace.
I have a full demo solution and details here if you want more info:
http://programmerramblings.blogspot.com/2011/07/clientside-api-for-aspnet-user-controls.html

A: Just make a call to javascript method in input button if you are sure about the name of that function.
<input type="button" value="test" onclick="doSomething()" />

If you place any javascript code in the control that will be spit on the page and it will be available for calling provided both of them are in the same form.
for example your code will look like this if you look into the source of that page.

  Dummy label

<input type="button" value="test" onclick="doSomething()" />

Edit: This is not a good way to access these methods in my opinion. When you are putting some javascript code inside a control then it should be used in that control only (There is no rule as such, its just a design suggestion). If you are trying to access javascript code of a control from outside that control then you need to revisit your design.
If you can give us more details on why you want to access that method, may be we can suggest some better way to do that.
Update: (As you have modified your question): Bit tricky to answer this as I dont have hands on experience with Rad controls. I guess there should be some feature which will help you to update the controls in that page without using javascript, may be have a look at clientside-API provided for Rad.
May be somebody who knows about RAD controls will help you.

A: You should make the control method public
public void doSomething

and call this from the page
myControl1.doSomething();


text:
Q: Detecting mouse/stylus clicks with C# on a combobox in .NET CF I´m trying to detect when a combobox in my Windows Mobile application is hit by a mouse click. Unfortunately this component in .NET CF2.0 doesn´t have a MouseClick event (whereas Desktop .NET does). Does someone have an idea of how to catch mouse/stylus clicks over the items list of a combobox using C#?
Thank you!

A: You should be able to use the MouseDown/MouseUp events to get the same behavior as MouseClick.  You will just have to make sure the object is the same is both cases and store some state between events.


text:
Q: Is there a way to get arrows() in R to plot to plot 'T' shaped arrow heads rather than reverse arrow? I would like to use the arrows function in R to plot different shaped arrow heads onto a network graph (I'm using NetworkD3 and iGraph which both use the arrows function). This works great at the moment but I would like some to be normal triangular arrow heads and others to be 'T' shaped arrow heads. The arrows function says:
arrows(x0, y0, x1 = x0, y1 = y0, length = 0.25, angle = 30,
       code = 2, col = par("fg"), lty = par("lty"),
       lwd = par("lwd"), …)

code = integer code, determining kind of arrows to be drawn.
If code = 1 an arrowhead is drawn at (x0[i], y0[i]) and if code = 2 an arrowhead is drawn at (x1[i], y1[i]). If code = 3 a head is drawn at both ends of the arrow. Unless length = 0, when no head is drawn.
Currently I'm using code to determine what direction the arrows are drawn in, all well and good, but I was wondering if it was possible to change code = 1 to result in a "T" shaped arrow head, rather than an arrow going in the opposite direction.
I tried looking for packages that might change this but I had no luck and I couldn't seem to figure out how to edit the arrows function by myself, if anyone could give me some pointers that would be wonderful!


text:
Q: Error adding Nuget packages in visual studio I am new to Windows Universal development and am trying to add the restsharp using visual studio nugget package manager but whenever I click on install, I get this error:

The process cannot access the file 'System.Security.Cryptography.Primitives.dll' because it is being used by another process.

I have started Visual Studio as administrator and yet this didn't solve my issue.
I have also tried clearing Nuget cache via
 debug->options->nugget manager->clear

but also this doesn't solve it.
How do I solve this to enable add on nuget packages to my project?

A: Tried this method? Adding Reference in VS is complicating
https://learn.microsoft.com/en-us/nuget/tools/package-manager-ui


text:
Q: Using encrypted web.config file My aim is to make the web.config not readable by external users, but my application should be able to access it. Is there any way to do this?
I have tried the following way, but how to set the application to use string instead of web.config?
I want to encrypt my web.config file so that others do not open the file using any editor like notepad. But my application should be able to use the same web.config file. I could encrypt the web.config file and decrypt it inside the application and I saved the entire web.config to a string file. Now I want to use this string variable instead of web.config(now in encrypted form, which cannot be accessed by the application).

A: There's an inbuilt mechanism for doing this, please see the tutorial:
http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx

A: Use the Aspnet_regiis.exe utility to do this.


text:
Q: On Covering a Planar Region with Copies of a Tile of Different Shape Background: Consider trying to cover the largest possible scaled copy of a planar region $C$ with specified shape with n instances of a tile $T$ of specified shape and size. Several families of this question - the largest disk that can be covered by n unit squares, largest square that can be covered with n unit disks and so on - are shown here: (https://erich-friedman.github.io/packing/index.html)
Question: In the best covering layout for a given $C$ with n $T$'s, consider regions where where more than one $T$ unit overlap. Observation: when tile $T$ is convex, no known best covering layout of any convex $C$ seems to have regions where more than 3 unit $T$s overlap. [Eg: see https://erich-friedman.github.io/packing/circovsqu/ - it shows covering largest possible squares with n unit circles: . For n = 3, 8 , 9, 11,... there are regions where three unit circles overlap but nowhere where more than 3 overlap]. Is 3 a provably strict bound for convex $T$s?
Note 1: When tile T is non convex, it appears that there can be regions in the best layout where arbitrarily large number of tiles overlap. An example is shown here: http://nandacumar.blogspot.com/2018/09/doubts-on-covering.html. This page also lists some related questions.
Note 2: And after the comments below, one can note that our question has a natural higher dimensional equivalent.


text:
Q: Protractor tests - how to define import and consts once instead of repeating them in each test specification file? I'm trying to prepare end to end tests using the Page Object Model pattern. I write my tests in TypeScript, using Protractor.
I noticed that the first few lines of each test specification file looks very similar:
// repeated in almost every test spec file
import { protractor, browser, element, by, promise } from 'protractor';
const EC = protractor.ExpectedConditions;
const until = protractor.until;

// this is changing from test to test
const SomePage = require('./pages/99-SomePage');

// code with `describe` and `it`

Is it possible to not repeat those imports and const?
I've tried to require separate file that contains them, but it seems they're not included in my file. It is also not possible to include Export modifier to import

A: On the cucumber.conf file, you can use the onPrepare() function to add those dependencies to the node global object, being accessible all around.
I only suggest this for EC and other recurrent dependencies, not for Page Objects. I use something like this:
...,
 onPrepare: function(){

    global.EC = protractor.ExpectedConditions;
    global.until = protractor.until;

    var Logger = require('./Logger.js');
    global.logger = new Logger();

    global.data = require('./test.data.json');
 },
...


text:
Q: Select Point From Which to Preview a Flash File I am working a video in Flash CS5 that is roughly 11 minutes long.
I am at the 6 minute mark at the moment and whenever I want to preview the latest changes I click F12 to I press 'alt+enter'. The problem is I have to watch 6 minutes of the SWF to eventually get to the latest part I edited.
This is slowing me down tremendously and I would hate to still be doing this when I am 10 minutes into the video!!!!
Is there a more efficient way to preview?
Perhaps open it in a player that has some proper controls? or even if I could select the starting point of the preview?
If I press 'enter' I see a preview but the sound file does not play so that option is out too.

A: You are editing in the timeline, right? Add the actionscript `gotoAndPlay(164);' in the first frame where 164 is the frame you want to skip to. You can also add a function that makes you do this runtime.


text:
Q: How to make 3 separate columns on page? This is what I'm trying to achieve:

So far, this is the code I have.
The columns work like they should. The problem is that whatever I place after the columns in my HTML is actually behind the columns on the page, not beneath them like I want.
Would it be a problem with the css that I'm using for the "test-box" div?
.test-box{
    background:red;
    width:100%;
    height:300px;
}

Is there a better way of doing this?

A: .test-box{
background:red;
width:100%;
height:300px;
clear:both;
}

clear: both will clear your other div from being affected by the floats, therefore placing it after

A: It can be done by adding a clear: both; to the CSS of the test-box:
.test-box{
    clear: both;
    background:red;
    width:100%;
    height:300px;
}

A: Add clear: both; or float: left; (if the 3 column divs take up the entire width.

A: you need to add
.test-box{clear:both;}
The jsFiddle

A: adding more always keep this at the end of a css
.clearfix {
  clear:both;
}

and call it
<div class="test-box clearfix">

A: in this class
.three-columns div{
    ...
    display:table-cell;

}

just remove the float:left and add display:table-cell

A: I personally wouldn't set the height in px unless you are 100% sure that the text will never change. there are different ways to achieve this, one way would be:
1) give a single class to each box ".box" for example
.box{
  width:33.33%;
  margin:20px 0 0 20px;
  float:left;
}

also remember to clear:both what comes after these boxes.
This would be a responsive solution, although you can use a px based solution. It really depends on what the requirements are.


text:
Q: Using Spark window function lead to create column in dataframe I would like to create a new column with value of the previous date(date less the current date) for group of ids for the below dataframe
+---+----------+-----+
| id|      date|value|
+---+----------+-----+
|  a|2015-04-11|  300|
|  a|2015-04-12|  400|
|  a|2015-04-12|  200|
|  a|2015-04-12|  100|
|  a|2015-04-11|  700|
|  b|2015-04-02|  100|
|  b|2015-04-12|  100|
|  c|2015-04-12|  400|
+---+----------+-----+

I have tried with lead window function .
val df1=Seq(("a","2015-04-11",300),("a","2015-04-12",400),("a","2015-04-12",200),("a","2015-04-12",100),("a","2015-04-11",700),("b","2015-04-02",100),("b","2015-04-12",100),("c","2015-04-12",400)).toDF("id","date","value")

 var w1=Window.partitionBy("id").orderBy("date".desc)
 var leadc1=lead(df1("value"),1).over(w1)
 val df2=df1.withColumn("nvalue",leadc1)

+---+----------+-----+------+
| id|      date|value|nvalue|
+---+----------+-----+------+
|  a|2015-04-12|  400|   200|
|  a|2015-04-12|  200|   100|
|  a|2015-04-12|  100|   300|
|  a|2015-04-11|  300|   700|
|  a|2015-04-11|  700|  null|
|  b|2015-04-12|  100|   100|
|  b|2015-04-02|  100|  null|
|  c|2015-04-12|  400|  null|
+---+----------+-----+------+

But as we can see when I have same date in id "a" I am getting wrong result.The result should be like
+---+----------+-----+------+
| id|      date|value|nvalue|
+---+----------+-----+------+
|  a|2015-04-12|  400|   300|
|  a|2015-04-12|  200|   300|
|  a|2015-04-12|  100|   300|
|  a|2015-04-11|  300|  null|
|  a|2015-04-11|  700|  null|
|  b|2015-04-12|  100|   100|
|  b|2015-04-02|  100|  null|
|  c|2015-04-12|  400|  null|
+---+----------+-----+------+

I already have a solution using join although I am looking for a solution using window function.
Thanks

A: The issue is you have multiple rows with the same date.  lead will take value from the next row in the result set, not the next date.  So when you sort the rows by date in descending order, the next row could be the same date.
How do you identify the correct value to use for a particular date?  for example why are you taking 300 from (id=a, date=2015-04-11), and not 700?
To do this with window functions you may need to do multiple passes - this would take the last nvalue and apply it to all rows in the same id/date grouping - but I'm not sure how your rows are initially ordered.
 val df1=Seq(("a","2015-04-11",300),("a","2015-04-12",400),("a","2015-04-12",200),("a","2015-04-12",100),("a","2015-04-11",700),("b","2015-04-02",100),("b","2015-04-12",100),("c","2015-04-12",400)).toDF("id","date","value")

var w1 = Window.partitionBy("id").orderBy("date".desc)
var leadc1 = lead(df1("value"),1).over(w1)
val df2 = df1.withColumn("nvalue",leadc1)
val w2 = Window.partitionBy("id", "date").orderBy("??? some way to distinguish row ordering")
val df3 = df1.withColumn("nvalue2", last_value("nvalue").over(w2))


text:
Q: Dropdown Menu - Float Values I am trying to create a dropdown with ipywidgets, it needs to return a variable value, this variable value may change depending on other slider input values. When I try to return the variable I get the error: NameError: 'adjustment_one' Not Defined.

calculated_area = input_slider / numstorey_input_slider * 0.7
revised_area = input_slider - calculated_area
adjustment_one = revised_area / input_slider

location = ipywidgets.Dropdown(
    options=[('Internal', 1), ('Roof', adjustment_one), ('External', 2) ],
    value=1,
    description='Plant Space Location: ',
)

The above method is solved and was an indenting error however I have now found that I can't pass a float value using the ipywidget dropdown. Below is the code - based on what is selected in the drop down this will be mapped to a dataframe as a multiplier. However when I open the excel document it only every returns the value '0'. This value should actually be 0.87 when Roof is selected, and will change depending on slider input values.
    calculated_roof_area = gia_input_slider / numstoreys_input_slider * 0.7
    revised_gia_roofinput = gia_input_slider - calculated_roof_area
    gia_adjustment_rooftop = revised_gia_roofinput / gia_input_slider

    plantspace = ipywidgets.Dropdown(
    options=[('Internal', 1), ('Roof', gia_adjustment_rooftop), ('External', 2) ],
    value=1,
    description='Plant Space Location: ',
    )

    print(plantspace)

    df = pd.read_excel(r'dataframe_final.xlsx', sheet_name='sheet1')

    # below recalculates the adjusted qty when the slider position changes

    multipliers = {
        'Building Footprint Factor': bldg_footprint_factor,
        'CAT A Fitout Yes / No': fitout_cat_dropdown,
        'GIA Factor': gia_factor,
        'GIA Adjustment - Rooftop': plantspace_dropdown
    }

    df['QP1 Multiplier'] = df['QP1'].map(multipliers)
    df['QP2 Multiplier'] = df['QP2'].map(multipliers)
    df['QP3 Multiplier'] = df['QP3'].map(multipliers)
    df['QP4 Multiplier'] = df['QP4'].map(multipliers)
    df['QP5 Multiplier'] = df['QP5'].map(multipliers)
    df['QP6 Multiplier'] = df['QP6'].map(multipliers)
    df['QP7 Multiplier'] = df['QP7'].map(multipliers)
    df['QP8 Multiplier'] = df['QP8'].map(multipliers)
    df['QP9 Multiplier'] = df['QP9'].map(multipliers)

Can anybody help?


text:
Q: Not working drawing on MapKit? I'm new to iOS programming. I am trying to draw one line between two points not more than one line. This is what I tried so far;

@property (nonatomic, strong) MKPolylineView *lineView;
@property (nonatomic, strong) MKPolyline *line;

Create a polyline all location ;
-(void)allLocationRoute {

CLLocationCoordinate2D coordinates[record.toMoments.count];

int i = 0;
for (MomentEntity *currentEntity in record.toMoments.allObjects) {

    coordinates[i].latitude = [currentEntity.latitude doubleValue];
    coordinates[i].longitude = [currentEntity.longitude doubleValue];
    i++;
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:record.toMoments.allObjects.count];
[self.mapView addOverlay:polyline];
line = polyline;

}

MapView:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay {

if ([overlay isKindOfClass:[MKPolyline class]]) {
    self.lineView = [[MKPolylineView alloc]initWithPolyline:(MKPolyline*)overlay] ;
    self.lineView.strokeColor = [[UIColor redColor] colorWithAlphaComponent:1];
    self.lineView.lineWidth = 1;
    return self.lineView;
}
return nil;
}

But as you can see from first picture red line makes zig-zag. Any help appreciated.


text:
Q: R: Recursive function in deeply nested list: Accessing level of hierarchy Out of interest and as a thought exercise, I was aiming to replicate the
tree
function
from the windows command line in R. tree generates ASCII trees similar
to the following example (taken from
here
and modified). If n is the hierarchical level, note that each file or
folder has (n-1)*3 spaces, followed by +---
+---Desktop
+---Documents
    +---Custom Office Templates
    +---Fiddler2
        +---Captures
            +---Requests
            +---Responses
        +---Scripts
+---Favorites
    +---Links

I use list.files() to extract the filenames (albeit this function
ignores empty directories) and the recursive function dir_tree()
(inspired by this
answer) to capture the
hierarchy in a nested list.
library(purrr)
library(stringr)
dirs <- list.files(recursive = TRUE)

# To create a reproducible example, I create dirs manually
dirs <- c("Desktop",
          "Documents",
          "Documents/Custom Office Templates",
          "Documents/Fiddler2",
          "Documents/Fiddler2/Captures",
          "Documents/Fiddler2/Captures/Requests",
          "Documents/Fiddler2/Captures/Responses",
          "Documents/Fiddler2/Scripts",
          "Documents/Favorites",
          "Documents/Favorites/Links"
)

dir_tree <- function(dirs) {
  first <- map_chr(str_split(dirs,"/"),~.x[1])
  rest  <- map_chr(str_split(dirs,"/"),~paste(.x[-1],collapse = "/"))
  zi    <- nchar(dirs) == 0L
  myli <- split(rest[!zi], first[!zi])
  map(myli, ~dir_tree(.x))
}

# creates a nested list
dir_nl <- dir_tree(dirs)

str(dir_nl)

## List of 2
##  $ Desktop  : Named list()
##  $ Documents:List of 3
##   ..$ Custom Office Templates: Named list()
##   ..$ Favorites              :List of 1
##   .. ..$ Links: Named list()
##   ..$ Fiddler2               :List of 2
##   .. ..$ Captures:List of 2
##   .. .. ..$ Requests : Named list()
##   .. .. ..$ Responses: Named list()
##   .. ..$ Scripts : Named list()

All I need to do now is to walk recursively through the nested list and
print the names, prepending it with (n-1)*3 spaces and +---. The
Question I have is: How do I retrieve n, i.e. the hierarchical
level!?
recursive_print <- function(dir_nl){
  imap(dir_nl,function(x,y){
    if(is.list(x)){
      print(paste("+---",y))
      recursive_print(x)
    }
  })
}

recursive_print(dir_nl) %>% invisible()

## [1] "+--- Desktop"
## [1] "+--- Documents"
## [1] "+--- Custom Office Templates"
## [1] "+--- Favorites"
## [1] "+--- Links"
## [1] "+--- Fiddler2"
## [1] "+--- Captures"
## [1] "+--- Requests"
## [1] "+--- Responses"
## [1] "+--- Scripts"

A: I haven't been able to solve it myself, but found a package that does it for me. This kind of defeats the purpose of learning recursive functions, but I'll place this here in case anyone lands here.
library(data.tree)

tree <- FromListSimple(dir_nl)

print(tree)

##                          levelName
## 1  Root
## 2   ¦--Desktop
## 3   °--Documents
## 4       ¦--Custom Office Templates
## 5       ¦--Favorites
## 6       ¦   °--Links
## 7       °--Fiddler2
## 8           ¦--Captures
## 9           ¦   ¦--Requests
## 10          ¦   °--Responses
## 11          °--Scripts

And for the record, data.tree has a method to directly parse a string of filepaths into a tree, so dir_tree() becomes obsolete.
as.Node(data.frame(paths = dirs),pathName = "paths")

##                     levelName
## 1 Desktop
## 2  ¦--Custom Office Templates
## 3  ¦--Fiddler2
## 4  ¦   ¦--Captures
## 5  ¦   ¦   ¦--Requests
## 6  ¦   ¦   °--Responses
## 7  ¦   °--Scripts
## 8  °--Favorites
## 9      °--Links


text:
Q: frequency multiplier I need to generate a sine wave with freq of the order of GHz. I have generated a sine wave of around 20-30 MHz. So I am thinking of using a frequency multiplier circuit. Any ideas how I should proceed ?

A: Look in the product ranges by Analog Devices, Maxim or TI (analog.com, maximintegrated.com or ti.com) for RF PLL synthesisers. Buy one, or better still buy an evaluation board with a chip on.
It's very unlikely that a frequency multiplier will do what you want, whatever you want.


text:
Q: How to keep AS3 code simple This is my original pseudo code:
function1();

function1():void{
   //do something
   after mouseclick do function2
}
function2():void{
   //do something
   after animationfinish do function3
}
etc..

Can I get it into something like this?:
function1();
after mouseclick do function2()
after animationfinish do function3()

What is an easy way to get listeners on the top level?

A: If I understand your question correctly, when function1 is called you want to addEventListener(MouseEvent.CLICK, function2);
Are you using Actiosncript to animate or Keyframes?
I know with TweenMax you can add a function to call at the end of the tween. If using fl.Transtions.Tween you can listen for TweenEvent.MOTION_FINISH and then call function3. I don't mess much with the timeline in Flash, since I feel more in control with coding it, but I know you can add code at the last frame of an animation to call function3.
If I am completely missing you question feel free to clarify what exactly you are seeking.

A: If i good understand - You like to create functions chain .
I depends what You like to do , problem is in many possibilities.
For call few functions i use this class :
https://github.com/turbosqel/as3SupportLib/blob/master/as3SupportLib/src/turbosqel/utils/CountCall.as
You can also use deeper and more elastic way and add next callbacks to function :
var func:Function = function():void { // declare new function
   ... function body // your class actions
   for each(var call:Function in arguments.callee){ // get functions
      call(); // call function
   }
}

func["someFunction"] = someFunction; // add function as dynamic value
func["otherFunction"] = anotherFunctionToCall; // add another function

func(); // call function


text:
Q: Is there a word for "divulging unintentionally"?
The President * information to an unauthorized staff of the White
  House.

I am wondering if there's a word for divulging unintentionally like as in a person leaking corporate information to a person who's not supposed to have that information unintentionally. Is there such a word?

A: For a one word option, there's "blab" which means

to reveal a secret especially by indiscreet chatter

but it's not a particularly formal word--I wouldn't expect to read it in a news article.
I would expect to see something like "let slip."

He let privileged information slip to an unauthorized member...

If formality isn't an issue at all, there are also variations like "spill the beans."


text:
Q: Handling back button in template with v-if (vue.js, vue-router)? I have a Vue.js component which shows a list of customers. When the use clicks on one, it switches to an edit view for the individual customer. This is done using v-if, testing a data field, 'editMode' (set to true or false). So the template has a listing table and an edit form and which is shown is dependent on the state of 'editMode'. When the user clicks on a customer, a method is called which switches the editMode to true (thus hiding the list and displaying the form), and when they save or cancel, a method is called which switches editMode back, thus hiding the form and displaying the list.
It works OK as a system, but I need to handle the back button better. At the moment, when the user is editing a customer, they would naturally expect that clicking the back button would take them back to the list they came from, but it doesn't, at the moment it takes them back to whatever route they came from before. But the edit environment for the customer isn't a different route, it's just a different part of the template, displayed using v-if/v-else. How can I get the back button to work as desired? Do I need to use history.pushState somehow? I know that I can probably control where the user goes by the use of a navigation guard, but this seems like the wrong approach to me.
LATER: In response to Richard Matsen's suggestion below, I've thought of another way to do this which doesn't require as much refactoring. I've been going about this the wrong way. I should always be thinking in terms of routes, if I want the back (and forward) buttons to work as I want them, so if I want the user to be able to go back to the list, I have to push the edit state on to the history so they can back out of it. But different routes can use the same component. Instead of directly changing 'editMode' in the component methods for when the user selects a customer row, or completes a customer edit, I should instead use router.push with a parameter, and have a watch (or beforeRouteUpdate navigation guard) which sets 'editMode' in response to the route change, with the parameter passed. That way a move to edit mode is a route change (which the user can go back from), even though it's using the same component. I think this should work - I'll have a play.

A: I recently changed a sub-component display from v-if to child routes (for purposes of webpack lazy loading, but that's another story).
It used to be

Now the template is

  <router-view></router-view>

and the child routes are configured like so
const routes = [
  {
    path: '/maincomponent', name: 'MainComponent', component: MainComponent,
    children: [{ path: '/subcomponent', name: 'SubComponent', component: SubComponent }]
  },

The sub component route is activated from a method using
this.$router.push('subcomponent')

and deactivated with
this.$router.push('maincomponent')

I can confirm the browser back button works to take the page back, and sub component is 'inserted' into the page a it was with v-if.