问:
Writing stream of inputted Byte Arrays to file over several minutes (C#)
I'm creating a GUI tool that extracts data from a microprocessor via Serial.  I want to save the byte arrays that I am extracting into a .dat file in chunks as they are extracted.  I tried using a filestream, but the process takes several minutes so the GUI freezes while the filestream is open.

How can I save to a filestream multiple times over a long period without freezing the GUI?

Should I just store the extracted byte arrays and then write to the file after?  I was going to do this but it would require a byte array with over 8 million elements so I thought it wasn't the best idea.

答:
If you are using the .NET Framework 4 or later you can use tasks. Then you can also make use of the ContinueWith method to update the UI on completion:

```<code>Task writeTask = Task.Factory.StartNew(() =>
{
    // Write to file
}).ContinueWith(previousTask =>
{
    // Update the UI
});
</code>```

If you are using an older version of the .NET Framework you can either use the Task Parallel Library or explicitly use a thread.

You can do this by either creating a new one or using the thread pool:

```<code>Thread thread = new Thread(() =>
{
    // Write to file
});
// Make the thread a background thread if you want it to be aborted
// when the main thread is stopped, i.e. the application is closed:
thread.IsBackground = true;
thread.Start();
</code>```

-

```<code>ThreadPool.QueueUserWorkItem(state =>
{
    // Write to file
});
</code>```

IMHO I prefer using tasks over threads and the thread pool over creating new threads. However, you have to keep in mind that using the thread pool does not guarantee to execute directly, but when a thread pool thread becomes available.

Body:
If you are using the .NET Framework 4 or later you can use tasks. Then you can also make use of the ContinueWith method to update the UI on completion:

Task writeTask = Task.Factory.StartNew(() =>
{
    // Write to file
}).ContinueWith(previousTask =>
{
    // Update the UI
});

If you are using an older version of the .NET Framework you can either use the Task Parallel Library or explicitly use a thread.

You can do this by either creating a new one or using the thread pool:

Thread thread = new Thread(() =>
{
    // Write to file
});
// Make the thread a background thread if you want it to be aborted
// when the main thread is stopped, i.e. the application is closed:
thread.IsBackground = true;
thread.Start();

-

ThreadPool.QueueUserWorkItem(state =>
{
    // Write to file
});

IMHO I prefer using tasks over threads and the thread pool over creating new threads. However, you have to keep in mind that using the thread pool does not guarantee to execute directly, but when a thread pool thread becomes available.


来源: stackexchange

问:
How to make a Model with a Many-to-Many relationship as Categories (i.e) rock ,Country, Blues, and Pop
```<code>from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.models import User

class Album(models.Model):
    creator = models.CharField(max_length=250)
    album_name = models.CharField(max_length=250)
    category = models.CharField(max_length=250)
    album_photo = models.FileField()
    author = models.ForeignKey (User,on_delete=models.CASCADE, related_name='album', default='1')

    def get_absolute_url(self):
        return reverse('post:detail',kwargs={'pk': self.pk})

    def __str__(self):
        return self.creator + ' - ' + self.album_name

class Song(models.Model):
    Album = models.ForeignKey(Album, on_delete=models.CASCADE)
    song_name = models.CharField(max_length=250)

    def __str__(self):
        return  self.song_name
</code>```

Edit:

I would like to have another model to categorize all of my albums in which would  take multiple categories. The categories would be pre specified choices that would make the queries more robust and easier to handle.

答:
I think what you want to do is define Category as a Model with a Many-to-Many relationship with Album. That way, you can do things like: Album.objects.filter(category__name='country') or you could take an instance of Category and do category.album_set.all()

Try this above your Album model:

```<code>class Category(models.Model):
    name = models.CharField(max_length=50)
    desc = models.TextField()
</code>```

Then add to your Album model:

```<code>category = models.ManyToManyField(Category)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.models import User

class Album(models.Model):
    creator = models.CharField(max_length=250)
    album_name = models.CharField(max_length=250)
    category = models.CharField(max_length=250)
    album_photo = models.FileField()
    author = models.ForeignKey (User,on_delete=models.CASCADE, related_name='album', default='1')

    def get_absolute_url(self):
        return reverse('post:detail',kwargs={'pk': self.pk})

    def __str__(self):
        return self.creator + ' - ' + self.album_name

class Song(models.Model):
    Album = models.ForeignKey(Album, on_delete=models.CASCADE)
    song_name = models.CharField(max_length=250)

    def __str__(self):
        return  self.song_name

Edit:

I would like to have another model to categorize all of my albums in which would  take multiple categories. The categories would be pre specified choices that would make the queries more robust and easier to handle.

Body:
I think what you want to do is define Category as a Model with a Many-to-Many relationship with Album. That way, you can do things like: Album.objects.filter(category__name='country') or you could take an instance of Category and do category.album_set.all()

Try this above your Album model:

class Category(models.Model):
    name = models.CharField(max_length=50)
    desc = models.TextField()

Then add to your Album model:

category = models.ManyToManyField(Category)


问:
Correct way to insert button value into my input (jQuery)
I have some sort of calculator, and I need to insert .num-pad_number.html() into my input. Is that correct way to do this:

```<code>$("#num-pad").on("click", ".num-pad_number", function (event) {
    $("#calc-input").val($("#calc-input").val() + $(this).html());
});
</code>```

Or it may be more convinient and correct way? Cuz I have some bug with that solution. After some manipulations with websockets, "calculator" starts to duplicate every number, for example I need "5" but it insert "55".

答:
Slightly modified. Using .text() instead of .html(). Shorter event function. Working example below:

$('#num_pad .num-pad_number').click(function() {
  $("#calc-input").val($("#calc-input").val() + $(this).text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="calc-input" type="text"/>

<div id="num_pad">
  <button class="num-pad_number">1</button>
  <button class="num-pad_number">2</button>
  <button class="num-pad_number">3</button>
  <button class="num-pad_number">4</button>
  <button class="num-pad_number">5</button>
  <button class="num-pad_number">6</button>
  <button class="num-pad_number">7</button>
  <button class="num-pad_number">8</button>
  <button class="num-pad_number">9</button>
</div></code>```

Body:
I have some sort of calculator, and I need to insert .num-pad_number.html() into my input. Is that correct way to do this:

$("#num-pad").on("click", ".num-pad_number", function (event) {
    $("#calc-input").val($("#calc-input").val() + $(this).html());
});

Or it may be more convinient and correct way? Cuz I have some bug with that solution. After some manipulations with websockets, "calculator" starts to duplicate every number, for example I need "5" but it insert "55".

Body:
Slightly modified. Using .text() instead of .html(). Shorter event function. Working example below:

$('#num_pad .num-pad_number').click(function() {
  $("#calc-input").val($("#calc-input").val() + $(this).text());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="calc-input" type="text"/>

<div id="num_pad">
  <button class="num-pad_number">1</button>
  <button class="num-pad_number">2</button>
  <button class="num-pad_number">3</button>
  <button class="num-pad_number">4</button>
  <button class="num-pad_number">5</button>
  <button class="num-pad_number">6</button>
  <button class="num-pad_number">7</button>
  <button class="num-pad_number">8</button>
  <button class="num-pad_number">9</button>
</div>


问:
Can i undo ALTER table in - MySQL?
Don't know if it's possible, I Altered VARCHAR column to Decimal Type which i want to Rollback. Because it blended all floating values as integer. like 2.00 became 200. Is there any way to undo my last table Alteration? Please advise.</p>

答:
No, you can't roll back ALTER TABLE statements.

https://dev.mysql.com/doc/refman/5.7/en/cannot-roll-back.html

Some statements cannot be rolled back. In general, these include data definition language (DDL) statements, such as those that create or drop databases, those that create, drop, or alter tables or stored routines.

(emphasis mine)

As Chris Peters comments above, you can do the reverse ALTER TABLE operation, and then clean up your data using UPDATE statements.

Title: Can i undo ALTER table in - MySQL?


问:
Invoke and control GDB from Python
I am running a Python GUI application. I want to invoke and control GDB from it, like load an executable file, set breakpoints etc. I see that GDB has a command line interface which can be used by sending strings to the GDB process, but I want to do it the Python way. Is there a gdb.py? I see that "archer" branch has something like "import gdb", but it doesn't work in Ubuntu's default installation of Python. Where do I get this module or is there any other method to control GDB from Python?

答:
pygdbmi is what you want.

With it I was able to reset an embedded target from Python using the following:

```<code>from pygdbmi.gdbcontroller import GdbController
if __name__ == '__main__':
    gdbmi = GdbController()
    response = gdbmi.write('b main')
    response = gdbmi.write('target remote localhost:2331')
    response = gdbmi.write('mon reset 0')
    response = gdbmi.write('c')
</code>```

gdbgui provides a much cooler example.

ContentLicense: CC BY-SA 2.5

Title: Invoke and control GDB from Python

Body:
pygdbmi is what you want.

With it I was able to reset an embedded target from Python using the following:

from pygdbmi.gdbcontroller import GdbController
if __name__ == '__main__':
    gdbmi = GdbController()
    response = gdbmi.write('b main')
    response = gdbmi.write('target remote localhost:2331')
    response = gdbmi.write('mon reset 0')
    response = gdbmi.write('c')

gdbgui provides a much cooler example.


问:
Laravel Cors (Middleware NOT working)
I recently tries enabling CORS in Laravel 5.4 but unfortunately it doesn't want to work. I have included the code and the error that it's giving me below. Can anyone help finding out why it isn't working? I have passed the required headers.

I have renamed my domain to domain.uk just for example purposes and I don't wan't to expose the domain of my site just yet as its under development.

Routes (Made the one route ::any for testing purposes while developing, usually on production it would be post):

```<code>Route::group(['domain' => 'api.domain.uk', 'namespace' => 'Api'], function() {
    Route::group(['middleware' => ['cors'], 'prefix' => 'call'], function() {
        Route::get('/rooms/{id}/get-locked-status', 'ApiController@getRoomLockStatus');
        Route::any('/rooms/{id}/update-locked-status', 'ApiController@updateRoomLockStatus');
    });
});
</code>```

Error:

```<code>XMLHttpRequest cannot load http://api.domain.uk/ajax/rooms/1/update-locked-status. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ice.domain.uk' is therefore not allowed access. The response had HTTP status code 500.
</code>```

Middleware:

```<code>namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }
}
</code>```

Ajax:

```<code>function toggleDoors(roomId) {
    $.ajax({
        url: 'http://api.domain.uk/ajax/rooms/' + roomId + '/update-locked-status',
        type: "POST",
        success: function(data) {
            alert(data);
        }
    });
}
</code>```

ApiController:

```<code><?php
namespace App\Http\Controllers\Api;

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\Other\Rooms;

class ApiController extends Controller
{
    public function getRoomLockStatus($id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        }
        else {
            return $room->rp_locked;
        }
    }

    public function updateRoomLockStatus(Request $request, $id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        }

        $room->rp_locked = $room->rp_locked == '1' ? '0' : '1';
        $room->save();

        $responseText = $room->rp_locked == '1' ?
            'Your doors have been locked.' : 'Your doors have been unlocked.';

        return response($responseText, 200);
    }
}
</code>```

答:
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#Preflighted_requests_in_CORS

If your problem in OPTIONS method.

Kernel::$routeMiddleware not working in Laravel 5.4 for request method OPTIONS, see https://github.com/laravel/framework/blob/v5.4.0/src/Illuminate/Routing/RouteCollection.php#L214.
For use CORS middleware, enable it in Kernel::$middleware array. It is not good, but no other way.

For example, I use next middleware class for SPA and API, attention, it is not middleware 'cors' for routes

```<code><?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * OptionsCorsResponse middleware - add CORS headers if request method OPTIONS
 */
class OptionsCorsResponse
{
    /**
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        /* @var $response Response */
        $response = $next($request);
        if (!$request->isMethod('OPTIONS')) {
            return $response;
        }
        $allow = $response->headers->get('Allow'); // true list of allowed methods
        if (!$allow) {
            return $response;
        }
        $headers = [
            'Access-Control-Allow-Methods' => $allow,
            'Access-Control-Max-Age' => 3600,
            'Access-Control-Allow-Headers' => 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept',
        ];
        return $response->withHeaders($headers);
    }
}
</code>```

and enable it in App\Http\Kernel

```<code>protected $middleware = [
    // ...
    \App\Http\Middleware\OptionsCorsResponse::class,
];
</code>```

Origin 'http :// ice . domain . uk' is therefore not allowed
  access. The response had HTTP status code 500.

Debug your code, because it generate some exception. Use any REST client with OPTIONS method.

Title: Laravel Cors (Middleware NOT working)

Body:
I recently tries enabling CORS in Laravel 5.4 but unfortunately it doesn't want to work. I have included the code and the error that it's giving me below. Can anyone help finding out why it isn't working? I have passed the required headers.

I have renamed my domain to domain.uk just for example purposes and I don't wan't to expose the domain of my site just yet as its under development.

Routes (Made the one route ::any for testing purposes while developing, usually on production it would be post):

Route::group(['domain' => 'api.domain.uk', 'namespace' => 'Api'], function() {
    Route::group(['middleware' => ['cors'], 'prefix' => 'call'], function() {
        Route::get('/rooms/{id}/get-locked-status', 'ApiController@getRoomLockStatus');
        Route::any('/rooms/{id}/update-locked-status', 'ApiController@updateRoomLockStatus');
    });
});

Error:

XMLHttpRequest cannot load http://api.domain.uk/ajax/rooms/1/update-locked-status. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ice.domain.uk' is therefore not allowed access. The response had HTTP status code 500.

Middleware:

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }
}

Ajax:

function toggleDoors(roomId) {
    $.ajax({
        url: 'http://api.domain.uk/ajax/rooms/' + roomId + '/update-locked-status',
        type: "POST",
        success: function(data) {
            alert(data);
        }
    });
}

ApiController:

<?php
namespace App\Http\Controllers\Api;

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\Other\Rooms;

class ApiController extends Controller
{
    public function getRoomLockStatus($id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        }
        else {
            return $room->rp_locked;
        }
    }

    public function updateRoomLockStatus(Request $request, $id) {
        $room = Rooms::find($id);

        if ($room == null) {
            return response('bad request', 400);
        }

        $room->rp_locked = $room->rp_locked == '1' ? '0' : '1';
        $room->save();

        $responseText = $room->rp_locked == '1' ?
            'Your doors have been locked.' : 'Your doors have been unlocked.';

        return response($responseText, 200);
    }
}

Body:
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#Preflighted_requests_in_CORS

If your problem in OPTIONS method.

Kernel::$routeMiddleware not working in Laravel 5.4 for request method OPTIONS, see https://github.com/laravel/framework/blob/v5.4.0/src/Illuminate/Routing/RouteCollection.php#L214.
For use CORS middleware, enable it in Kernel::$middleware array. It is not good, but no other way.

For example, I use next middleware class for SPA and API, attention, it is not middleware 'cors' for routes

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * OptionsCorsResponse middleware - add CORS headers if request method OPTIONS
 */
class OptionsCorsResponse
{
    /**
     *
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle($request, Closure $next)
    {
        /* @var $response Response */
        $response = $next($request);
        if (!$request->isMethod('OPTIONS')) {
            return $response;
        }
        $allow = $response->headers->get('Allow'); // true list of allowed methods
        if (!$allow) {
            return $response;
        }
        $headers = [
            'Access-Control-Allow-Methods' => $allow,
            'Access-Control-Max-Age' => 3600,
            'Access-Control-Allow-Headers' => 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept',
        ];
        return $response->withHeaders($headers);
    }
}

and enable it in App\Http\Kernel

protected $middleware = [
    // ...
    \App\Http\Middleware\OptionsCorsResponse::class,
];

Origin 'http :// ice . domain . uk' is therefore not allowed
  access. The response had HTTP status code 500.

Debug your code, because it generate some exception. Use any REST client with OPTIONS method.


问:
Iterate over all files in a directory using BOOST_FOREACH
Can you iterate over all files in a directory using boost::filesystem and BOOST_FOREACH?
I tried

```<code>path dirPath = ...
int fileCount = 0;
BOOST_FOREACH(const path& filePath, dirPath)
    if(is_regular_file(filePath))
        ++fileCount;
</code>```

This code compiles, runs, but does not produce the desired result.

答:
So I guessed I missed the boat on this one, but I was having a similar issue even after I found code that theoretically should work. The issue is the boost::filesystem::path data type takes the last char off of a string.

I was reading from a file and my path was "c:\one\two\three". But when i made it a path data type, the string was changed to "c:\one\two\thre". No idea what that is, but due to this the file location wasn't found and blah blah blah. What i did to fix it was just add another '\' to the end. That way it removes the '\' instead of the 'e'.

worked just fine after that. But as stated before, I have no idea why it did this. Hope this helps someone.

Body:
Can you iterate over all files in a directory using boost::filesystem and BOOST_FOREACH?
I tried

path dirPath = ...
int fileCount = 0;
BOOST_FOREACH(const path& filePath, dirPath)
    if(is_regular_file(filePath))
        ++fileCount;

This code compiles, runs, but does not produce the desired result.


问:
Scrapy run javascript script in specific parse
I'm recently starting using scrapy, and when i crawl a page,i have the problem of the currency that is showed. This is the part of the page that i need to click to change the actual currency:

I can do the same, but using the next script of javascript:
    setCurrency(1)
And i have to do this in all the pages, to make sure that every product uses the same currency. From what i've read, i can use splash with scrapy to do this, but, and correct me if i am wrong, but the code runs only one time with the constructor of the spider.
Is there a way to run this only on the parse that extracts the product?. My code is like this now:

```<code>def parse(self, response):
    rutas = response.xpath("//a[@class='nonblock nontext rounded-corners rgba-background clip_frame grpelem']/@href").extract()
    for ruta in rutas:
        ruta_abs = response.urljoin(ruta)
        yield scrapy.Request(url=ruta_abs, callback=self.parse_producto)

def parse_producto(self, response):
    #Se debe ejecutar antes un script para cambiar la divisa
    nombre = response.xpath("//h1/text()").extract_first()
    #También conocido como "Referencia" por la página:
    codigo = response.xpath("//p[@id='product_reference']/span/text()").extract_first()
    descripcion = response.xpath("//div[@id='short_description_block']/div/p/text()").extract_first()
    url_foto = response.xpath("//div[@id='image-block']/span/img/@src").extract_first()
    precio = '.'.join(response.xpath("//span[@id='our_price_display']/text()").re(r"\d+"))
    categorias = response.xpath("//span[@class='navigation_page']/span/a/span/text()").extract()
    categoria_actual = ''
    num_categorias = len(categorias)
    if num_categorias > 1:
        num_categorias = (num_categorias-1)*-1
        categoria_actual = categorias[num_categorias]
    url_producto = response.url
    caract = response.xpath("//section[@class='page-product-box']/table[@class='table-data-sheet']/tr/td/text()").extract()
    ficha_tecnica = []
    if len(caract) > 1:
        ficha_tecnica = list(zip(caract[0::2],caract[1::2]))
    #Genero objeto producto:
    producto = Producto_tienda()
    producto['nombre'] = nombre
    producto['descripcion'] = descripcion
    producto['url_foto'] = url_foto
    producto['precio'] = precio
    producto['id_tienda'] = 2
    producto['tienda'] = 'ARTEC'
    producto['url_producto'] = url_producto
    producto['codigo'] = codigo
    producto['categoria'] = categoria_actual
    producto['ficha_tecnica'] = ficha_tecnica
    yield producto
</code>```

I ommited the beggining of the code, where you set the name, allowed domains and start_urls to avoid legal issues.

I need to execute the javascript code everytime the spider is crawling the parse_producto function. Is there a way to do it?. If you need more information, i can give it you.

Thanks in advance!

答:
You could use selenium + phantomJS and a DownloaderMiddleware
Here is a snippet from a quick crawler I wrote for crawling google. You could do all you have to do here(like clicking on the currency button) before returning the HtmlResponse with the driver page_source.

```<code># -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from scrapy.http import HtmlResponse
from scrapy.exceptions import IgnoreRequest
import time

class SeleniumMiddleware(object):
    def __init__(self):
        self.driver = webdriver.PhantomJS()

    def process_request(self, request, spider):
        self.driver.get(request.url)
        try:
            WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "r")))
            body = self.driver.page_source
            return HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=request)
        except Exception as e:
            # Timeout on WebDriverWait
            raise IgnoreRequest
</code>```

You also need to set the DownloaderMiddleware in settings.py, for example:

```<code>DOWNLOADER_MIDDLEWARES = {
    'selenium_downloader_middleware.middlewares.SeleniumMiddleware': 723,
}
</code>```

Body:
I'm recently starting using scrapy, and when i crawl a page,i have the problem of the currency that is showed. This is the part of the page that i need to click to change the actual currency:

I can do the same, but using the next script of javascript:
    setCurrency(1)
And i have to do this in all the pages, to make sure that every product uses the same currency. From what i've read, i can use splash with scrapy to do this, but, and correct me if i am wrong, but the code runs only one time with the constructor of the spider.
Is there a way to run this only on the parse that extracts the product?. My code is like this now:

def parse(self, response):
    rutas = response.xpath("//a[@class='nonblock nontext rounded-corners rgba-background clip_frame grpelem']/@href").extract()
    for ruta in rutas:
        ruta_abs = response.urljoin(ruta)
        yield scrapy.Request(url=ruta_abs, callback=self.parse_producto)

def parse_producto(self, response):
    #Se debe ejecutar antes un script para cambiar la divisa
    nombre = response.xpath("//h1/text()").extract_first()
    #También conocido como "Referencia" por la página:
    codigo = response.xpath("//p[@id='product_reference']/span/text()").extract_first()
    descripcion = response.xpath("//div[@id='short_description_block']/div/p/text()").extract_first()
    url_foto = response.xpath("//div[@id='image-block']/span/img/@src").extract_first()
    precio = '.'.join(response.xpath("//span[@id='our_price_display']/text()").re(r"\d+"))
    categorias = response.xpath("//span[@class='navigation_page']/span/a/span/text()").extract()
    categoria_actual = ''
    num_categorias = len(categorias)
    if num_categorias > 1:
        num_categorias = (num_categorias-1)*-1
        categoria_actual = categorias[num_categorias]
    url_producto = response.url
    caract = response.xpath("//section[@class='page-product-box']/table[@class='table-data-sheet']/tr/td/text()").extract()
    ficha_tecnica = []
    if len(caract) > 1:
        ficha_tecnica = list(zip(caract[0::2],caract[1::2]))
    #Genero objeto producto:
    producto = Producto_tienda()
    producto['nombre'] = nombre
    producto['descripcion'] = descripcion
    producto['url_foto'] = url_foto
    producto['precio'] = precio
    producto['id_tienda'] = 2
    producto['tienda'] = 'ARTEC'
    producto['url_producto'] = url_producto
    producto['codigo'] = codigo
    producto['categoria'] = categoria_actual
    producto['ficha_tecnica'] = ficha_tecnica
    yield producto

I ommited the beggining of the code, where you set the name, allowed domains and start_urls to avoid legal issues.

I need to execute the javascript code everytime the spider is crawling the parse_producto function. Is there a way to do it?. If you need more information, i can give it you.

Thanks in advance!

Body:
You could use selenium + phantomJS and a DownloaderMiddleware
Here is a snippet from a quick crawler I wrote for crawling google. You could do all you have to do here(like clicking on the currency button) before returning the HtmlResponse with the driver page_source.

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from scrapy.http import HtmlResponse
from scrapy.exceptions import IgnoreRequest
import time

class SeleniumMiddleware(object):
    def __init__(self):
        self.driver = webdriver.PhantomJS()

    def process_request(self, request, spider):
        self.driver.get(request.url)
        try:
            WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "r")))
            body = self.driver.page_source
            return HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=request)
        except Exception as e:
            # Timeout on WebDriverWait
            raise IgnoreRequest

You also need to set the DownloaderMiddleware in settings.py, for example:

DOWNLOADER_MIDDLEWARES = {
    'selenium_downloader_middleware.middlewares.SeleniumMiddleware': 723,
}


问:
How can I dynamically resize my iframe, avoiding the browser security crossdomain restrictions?
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

```<code>window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';
</code>```

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?

答:
Depending on the simplicity of the page you're trying to load, you could try loading it with PHP and exposing some variables while building the HTML (if this is even an option, of course).

For example, you could load it with file_get_contents, use some regular expressions to find the img width and height, and then use those values when echo'ing the iframe.

Body:
We have an embeddable badge that creates an iframe. It needs to be a dynamic size; it changes size based on data loaded from a 3rd party API or our database. So it's not known what height it will be before it loads.

It's invoked with a  tag that loads a script from our server, which creates an iframe set to a specific src.

On my own machine, within the iframe I can do

window.parent.document.getElementById('my_frame').style.height=new_calculated_height+'px';

but of course when it's embedded in a page different than the iframe src, that fails due to crossdomain restrictions ('unsafe access attempt' error in FF, etc.).

As we're already loading a script into the host page with full access, this is kind of silly.

Basically, I need to get a variable, the new height, from the iframe into the host page.

Could I do it in reverse maybe? Have a function on the host page ask the iframe for it's an element's offsetHeight?


问:
Angular http request retry causes multiple insert
I have built an angular app which calls a REST API to insert data into MySQL DB.

The logic is if the app doesn't get response within 10 seconds, it retries the same request.

At the server, there are some logic applied to calculate some values which are required to insert the data. So when the number of insert records passed by the client is more, the request cannot be completed within 10 seconds. The client aborts the request and retries the same. This causes multiple records insert.

Could someone suggest a proven solution for the same?

Thanks in advance.

答: Only do a retry on an error, otherwise you are getting duplicates for responses don't error (eventually giving you a response).</p>


问:
How to set WCF Tracing to long only Warnings, Erros and Fatals?
I'm trying to set the Tracing in my WCF server in production, so it logs only "issues". Not information. I looked at Microsoft docs, here, but it doesn't work for me.

There is Recommended Settings for Deployment or Debugging

I've tried that, and looks like it works. I'm getting every message logged (I think).

There's also Recommended Settings for a Production Environment, here:

```<code><configuration>
 <system.diagnostics>
  <sources>
    <source name="System.ServiceModel"
            switchValue="Warning"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Warning, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="xml"
         type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
 </system.diagnostics>

<system.serviceModel>
  <diagnostics wmiProviderEnabled="true">
  </diagnostics>
 </system.serviceModel>
</configuration>
</code>```

I pasted it to my config file and.. there is a typo I think. They wrote:

switchValue="Warning" (with that the log is not created)

So I changed it to: switchValue="Warning, ActivityTracing"
Now I'm getting the log, but.. I'm getting the same results as with the Debugging version. Why?

I was trying:

1)

```<code><diagnostics>
  <messageLogging
       logEntireMessage="false"
       logMalformedMessages="false"
       logMessagesAtServiceLevel="false"
       logMessagesAtTransportLevel="false"
       maxMessagesToLog="5" />
</diagnostics>
</code>```

2)

```<code>  <sources>
    <source name="System.ServiceModel"
            switchValue="Off, ActivityTracing"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Off, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  </sources>
</code>```

3)

```<code>  <system.diagnostics>
  <sources>
    <source name="System.ServiceModel"
            switchValue="Off, ActivityTracing"
            propagateActivity="true" >
      <listeners>
        <add name="TraceLog"/>
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging"
            switchValue="Off, ActivityTracing"
            propagateActivity="true">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Off, ActivityTracing">
      <listeners>
        <add name="TraceLog"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceLog"
          type="System.Diagnostics.XmlWriterTraceListener"
                initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
  </system.diagnostics>
</code>```

Didn't work://

答:
WCF tracing is built on top of System.Diagnostics and every WCF assembly emits different Trace messages. System.ServiceModel is the most common WCF trace source and it emits traces for most of the WCF activities. The level of information emitted is controlled via the switchValue attribute in the config files.

You are seeing the start/stop/transfer trace messages also because the ActivityTracing trace level is added to the switchValue. If you leave only Warning it should work just fine.

Sometimes the svclog file generated might look empty when the service's host is running (for example if hosted under IISExpress). Stop the site and you'll see the messages generated only for warnings & above.

For example, the diagnostic config below captured only the ArgumentNullException

```<code><system.diagnostics>
    <sources>
      <source propagateActivity="false" name="System.ServiceModel"
        switchValue="Warning">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelTraceListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="traces.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        name="ServiceModelTraceListener" traceOutputOptions="None">
        <filter type="" />
      </add>
    </sharedListeners>
  </system.diagnostics>
</code>```

Configuring Tracing doc from MS lists different Trace Levels that can be used with trace sources.

Body:
I'm trying to set the Tracing in my WCF server in production, so it logs only "issues". Not information. I looked at Microsoft docs, here, but it doesn't work for me.

There is Recommended Settings for Deployment or Debugging

I've tried that, and looks like it works. I'm getting every message logged (I think).

There's also Recommended Settings for a Production Environment, here:

<configuration>
 <system.diagnostics>
  <sources>
    <source name="System.ServiceModel"
            switchValue="Warning"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Warning, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="xml"
         type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
 </system.diagnostics>

<system.serviceModel>
  <diagnostics wmiProviderEnabled="true">
  </diagnostics>
 </system.serviceModel>
</configuration>

I pasted it to my config file and.. there is a typo I think. They wrote:

switchValue="Warning" (with that the log is not created)

So I changed it to: switchValue="Warning, ActivityTracing"
Now I'm getting the log, but.. I'm getting the same results as with the Debugging version. Why?

I was trying:

1)

<diagnostics>
  <messageLogging
       logEntireMessage="false"
       logMalformedMessages="false"
       logMessagesAtServiceLevel="false"
       logMessagesAtTransportLevel="false"
       maxMessagesToLog="5" />
</diagnostics>

2)

  <sources>
    <source name="System.ServiceModel"
            switchValue="Off, ActivityTracing"
            propagateActivity="true" >
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Off, ActivityTracing">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
  </sources>
  </sources>

3)

  <system.diagnostics>
  <sources>
    <source name="System.ServiceModel"
            switchValue="Off, ActivityTracing"
            propagateActivity="true" >
      <listeners>
        <add name="TraceLog"/>
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging"
            switchValue="Off, ActivityTracing"
            propagateActivity="true">
      <listeners>
        <add name="xml"/>
      </listeners>
    </source>
    <source name="myUserTraceSource"
            switchValue="Off, ActivityTracing">
      <listeners>
        <add name="TraceLog"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add name="TraceLog"
          type="System.Diagnostics.XmlWriterTraceListener"
                initializeData="C:\logs\Traces.svclog" />
  </sharedListeners>
  </system.diagnostics>

Didn't work://

Body:
WCF tracing is built on top of System.Diagnostics and every WCF assembly emits different Trace messages. System.ServiceModel is the most common WCF trace source and it emits traces for most of the WCF activities. The level of information emitted is controlled via the switchValue attribute in the config files.

You are seeing the start/stop/transfer trace messages also because the ActivityTracing trace level is added to the switchValue. If you leave only Warning it should work just fine.

Sometimes the svclog file generated might look empty when the service's host is running (for example if hosted under IISExpress). Stop the site and you'll see the messages generated only for warnings & above.

For example, the diagnostic config below captured only the ArgumentNullException

<system.diagnostics>
    <sources>
      <source propagateActivity="false" name="System.ServiceModel"
        switchValue="Warning">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelTraceListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="traces.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        name="ServiceModelTraceListener" traceOutputOptions="None">
        <filter type="" />
      </add>
    </sharedListeners>
  </system.diagnostics>

Configuring Tracing doc from MS lists different Trace Levels that can be used with trace sources.


问:
Terraform State path
I'm trying to create a resource group with Terraform.io with this example.tf file:

```<code># Configure Azure provider
provider "azurerm" {
  subscription_id = "${var.azure_subscription_id}"
  client_id       = "${var.azure_client_id}"
  client_secret   = "${var.azure_client_secret}"
  tenant_id       = "${var.azure_tenant_id}"
}

# Create a resource group
resource "azurerm_resource_group" "terraform-rg" {
  name     = "terraform-rg"
  location = "ukwest"
}
</code>```

All goes well it seems, but I'm slightly worried about this message at the end:

```<code>Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path:
</code>```

So "Stage path" is empty and it seems important. Is there an argument I should pass to "terraform apply" or put somewhere else in the tf file so that I get a state path?

答:
state path: is empty because you didn't configure the backend in your config above. In this case terraform will keep the state file called terraform.tfstate in same location as the rest of .tf file

That said, if you want the state path: to have the full path to your terraform.tfstate file after running terraform apply then configure the local backend as follow:

```<code>terraform {
  backend "local" {
    path = "/path_to_statefile_location/terraform.tfstate"
  }
}
</code>```

https://www.terraform.io/docs/backends/types/local.html

Title: Terraform State path

Body:
I'm trying to create a resource group with Terraform.io with this example.tf file:

# Configure Azure provider
provider "azurerm" {
  subscription_id = "${var.azure_subscription_id}"
  client_id       = "${var.azure_client_id}"
  client_secret   = "${var.azure_client_secret}"
  tenant_id       = "${var.azure_tenant_id}"
}

# Create a resource group
resource "azurerm_resource_group" "terraform-rg" {
  name     = "terraform-rg"
  location = "ukwest"
}

All goes well it seems, but I'm slightly worried about this message at the end:

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

The state of your infrastructure has been saved to the path
below. This state is required to modify and destroy your
infrastructure, so keep it safe. To inspect the complete state
use the `terraform show` command.

State path:

So "Stage path" is empty and it seems important. Is there an argument I should pass to "terraform apply" or put somewhere else in the tf file so that I get a state path?

Body:
state path: is empty because you didn't configure the backend in your config above. In this case terraform will keep the state file called terraform.tfstate in same location as the rest of .tf file

That said, if you want the state path: to have the full path to your terraform.tfstate file after running terraform apply then configure the local backend as follow:

terraform {
  backend "local" {
    path = "/path_to_statefile_location/terraform.tfstate"
  }
}

https://www.terraform.io/docs/backends/types/local.html


问:
Android: Firebase token is null at first run
I am using FCM to provide notifications in my app. Everything worked well, but now I realised that, when I install my application using Android Studio (not from GooglePlay) the token is null at first run. When I close my app and restart it, the token is not null anymore. What cause this problem and how can I avoid it?

InstanceIDService:

```<code>public class InstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
    }

    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("url_to_registration_script")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In MainActivity:

```<code>FirebaseMessaging.getInstance().subscribeToTopic("topic");
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("TOKEN", token);
</code>```

Last log returns null when app is installed and started for the first time

Registration script:

```<code> <?php
 if (isset($_POST["Token"])) {

       $_uv_Token=$_POST["Token"];
       $conn = mysqli_connect("localhost","user","pass","db") or die("Error connecting");
       $q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "
          ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";

  mysqli_query($conn,$q) or die(mysqli_error($conn));
  mysqli_close($conn);
}
?>
</code>```

答:
Just replace:

```<code>String token = instanceID.getToken();
</code>```

with:

```<code>String token = instanceID.getToken($SENDER_ID, "FCM");
</code>```

and it will work.

Body:
I am using FCM to provide notifications in my app. Everything worked well, but now I realised that, when I install my application using Android Studio (not from GooglePlay) the token is null at first run. When I close my app and restart it, the token is not null anymore. What cause this problem and how can I avoid it?

InstanceIDService:

public class InstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();
        registerToken(token);
    }

    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("url_to_registration_script")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In MainActivity:

FirebaseMessaging.getInstance().subscribeToTopic("topic");
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("TOKEN", token);

Last log returns null when app is installed and started for the first time

Registration script:

 <?php
 if (isset($_POST["Token"])) {

       $_uv_Token=$_POST["Token"];
       $conn = mysqli_connect("localhost","user","pass","db") or die("Error connecting");
       $q="INSERT INTO users (Token) VALUES ( '$_uv_Token') "
          ." ON DUPLICATE KEY UPDATE Token = '$_uv_Token';";

  mysqli_query($conn,$q) or die(mysqli_error($conn));
  mysqli_close($conn);
}
?>

Body:
Just replace:

String token = instanceID.getToken();

with:

String token = instanceID.getToken($SENDER_ID, "FCM");

and it will work.


问:
How flatten a list of lists one step
I have a list of lists of tuples

```<code>A= [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ]
</code>```

The outer list can have any number of inner lists, the inner lists can have any number of tuples, a tuple always has 3 integers.

I want to generate all combination of tuples, one from each list:

```<code>[(1,2,3),(7,8,9),(2,1,0)]
[(1,2,3),(7,8,9),(1,3,5)]
[(1,2,3),(8,7,6),(2,1,0)]
...
[(4,5,6),(5,4,3),(1,3,5)]
</code>```

A simple way to do it is to use a function similar to itertools.poduct()
but it must be called like this

```<code>itertools.product([(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)])
</code>```

i.e the outer list is removed. And I don't know how to do that. Is there a better way to generate all combinations of tuples?

答:
Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

```<code>def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]
</code>```

Seems to work. Test:

```<code>A = [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ]

flatten(A)
</code>```

Result:

```<code>[(1, 2, 3), (4, 5, 6), (7, 8, 9), (8, 7, 6), (5, 4, 3), (2, 1, 0), (1, 3, 5)]
</code>```

Note: the line car,*cdr=lst only works in Python 3.0

Title: How flatten a list of lists one step

Body:
I have a list of lists of tuples

A= [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ]

The outer list can have any number of inner lists, the inner lists can have any number of tuples, a tuple always has 3 integers.

I want to generate all combination of tuples, one from each list:

[(1,2,3),(7,8,9),(2,1,0)]
[(1,2,3),(7,8,9),(1,3,5)]
[(1,2,3),(8,7,6),(2,1,0)]
...
[(4,5,6),(5,4,3),(1,3,5)]

A simple way to do it is to use a function similar to itertools.poduct()
but it must be called like this

itertools.product([(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)])

i.e the outer list is removed. And I don't know how to do that. Is there a better way to generate all combinations of tuples?

Body:
Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

A = [ [(1,2,3),(4,5,6)], [(7,8,9),(8,7,6),(5,4,3)],[(2,1,0),(1,3,5)] ]

flatten(A)

Result:

[(1, 2, 3), (4, 5, 6), (7, 8, 9), (8, 7, 6), (5, 4, 3), (2, 1, 0), (1, 3, 5)]

Note: the line car,*cdr=lst only works in Python 3.0


问:
Revisions list and get missing information
Using the Google APIs Explorer as well as the official C# library for Google Drive API v3, the response is missing most of the documented fields. I specifically need access to who did the revisions, which should be accessible via $.lastModifyingUser.

I've tried this on my domain admin account as well as a service account, so it shouldn't be a permission issue, at least not that I can see. What am I doing wrong, if anything?

List:

```<code>{
 "kind": "drive#revisionList",
 "revisions": [
  {
   "kind": "drive#revision",
   "id": "1",
   "mimeType": "application/vnd.google-apps.spreadsheet",
   "modifiedTime": "2016-11-16T18:29:29.527Z"
  },
  {
   "kind": "drive#revision",
   "id": "14",
   "mimeType": "application/vnd.google-apps.spreadsheet",
   "modifiedTime": "2016-11-16T18:35:49.184Z"
  },
  ...
</code>```

Single get:

```<code>{
 "kind": "drive#revision",
 "id": "134088",
 "mimeType": "application/vnd.google-apps.spreadsheet",
 "modifiedTime": "2017-05-24T11:48:00.788Z"
}
</code>```

答: You need to add fields="*", or fields="permissions(id,lastModifyingUser)" to your request to instruct Drive to return the full resource. By default, only a minimal set of properties is returned.

Body:
Using the Google APIs Explorer as well as the official C# library for Google Drive API v3, the response is missing most of the documented fields. I specifically need access to who did the revisions, which should be accessible via $.lastModifyingUser.

I've tried this on my domain admin account as well as a service account, so it shouldn't be a permission issue, at least not that I can see. What am I doing wrong, if anything?

List:

{
 "kind": "drive#revisionList",
 "revisions": [
  {
   "kind": "drive#revision",
   "id": "1",
   "mimeType": "application/vnd.google-apps.spreadsheet",
   "modifiedTime": "2016-11-16T18:29:29.527Z"
  },
  {
   "kind": "drive#revision",
   "id": "14",
   "mimeType": "application/vnd.google-apps.spreadsheet",
   "modifiedTime": "2016-11-16T18:35:49.184Z"
  },
  ...

Single get:

{
 "kind": "drive#revision",
 "id": "134088",
 "mimeType": "application/vnd.google-apps.spreadsheet",
 "modifiedTime": "2017-05-24T11:48:00.788Z"
}


问:
Randomly Sample Panel Data by Users in a manner Agnostic to User Key
Summary:

How do I perform random sampling at the group level from a large panel dataset without loading to memory?

Note that because I do not load to memory, I do not want to
  validate the id key. I am also not necessarily certain of the format of the id. Is random sampling possible under these conditions?

Note: I use python-3.x.

Detail:

I have a large dataframe/csv file (>20GB) which is impractical to fit in memory. The structure of the data is a panel, which means it consists of groups of observations with the same id. For example, there are 20 million people with 100 observations each.

I want to sample at the user level, which means for any sample, it should include all the observations for each user.

Ideas:

Make a hash of the id in a way that is agnostic to the format of the id (within reason). For example, the id could be the list of users by number or some alphanumeric sequence.

I would then filter this hash with a filter function that accepts a % of them.

Then run the filter across each observation, building a dataframe.

The problem is that I'm not confident about steps 1 or 2. I'm not sure how to create a hash that is random for all reasonable statistical purposes.

I'm sure this is a solved problem. Does anyone have any ideas?

答:
There are a lot of ways to go about this. One of the most straightforward is using the random module to generate random numbers without repetition. Then you can use these numbers to pull the rows (people) corresponding to these numbers:

```<code>import random

random_list = random.sample(range(20000000), 100)
# From your 20 million people, grab the indices for 100 of them.

random_people = []

with open(file.txt) as f:
    idx = 0
    for line in f:
        if idx in random_list:  # Check if the person matches one of the random ones.
            random_people.append(line.strip())
</code>```

Of course, you can adjust the numbers to your actual number of rows, number of people you want in the sample, etc.

Body:
There are a lot of ways to go about this. One of the most straightforward is using the random module to generate random numbers without repetition. Then you can use these numbers to pull the rows (people) corresponding to these numbers:

import random

random_list = random.sample(range(20000000), 100)
# From your 20 million people, grab the indices for 100 of them.

random_people = []

with open(file.txt) as f:
    idx = 0
    for line in f:
        if idx in random_list:  # Check if the person matches one of the random ones.
            random_people.append(line.strip())

Of course, you can adjust the numbers to your actual number of rows, number of people you want in the sample, etc.


问:
Is it possible to insert an HTML tooltip within Matrix Statements in Qualtrics across all browsers?
This is my first post, so apologies if this question is not specific enough. I am creating a long survey in Qualtrics (most of the items of which are contained within matrix style questions) that will sometimes be taken by young teens. Because the questions being asked sometimes contain confusing wording, I have created tooltips in HTML to give additional context to the questions, so that younger respondents who may be confused by the wording can hover over a question mark icon to get additional information if desired.

Currently, there are several tool tips in the survey. Sometimes, the tool tip is inserted in the "Question" section of the matrix (i.e., the quetsion text at the top of the matrix), and sometimes, the tool tip is inserted in one of the statements of the matrix (i.e., the statements on the left hand side of the matrix).

My issue is that even when using the same exact code for the different tool tips, only the ones that are found in the question section of the matrix show the span title when using Internet Explorer and Safari. However, when using Chrome, both types of tool tips display the hoverover text. So, my question is, is there a way to get the span title to show regardless of the browser being used?

I am very new to HTML and am unsure why this is happening. I've included a preview survey for others to try, as well as the HTML I used to create the tool tip below.

Preview Survey Link:
https://co1.qualtrics.com/jfe/preview/SV_025DzNles8BNYQR

HTML:

```<code>Test <span title="Hoverover text.">
<img src="https://qualtrics.com/(//this is the file path of the question mark icon uploaded to Qualtrics)" style="width: 15px; height: 20px;"/></span>
</code>```

Any advice would be greatly appreciated. Thanks so much!

答:
Edit the survey -> Look and Feel -> Advanced -> + Add Custom CSS

```<code>.myExpandItem
{
    text-decoration: underline;
    position: relative;
}

.myExpandItem:hover .myExpandBox {
    display: block;
}

.myExpandBox
{
    position: absolute;
    background-color: rgba(0,0,0,0.8);
    min-height: 50px;
    width: 250px;
    display: none;
    left: -30px;
    top: 14px;
    padding: 10px;
    color: white;
    border-radius: 15px;
    font-size: 9.000000pt;
    font-family: 'ArialMT';
}
</code>```

Then edit the question HTML and add this HTML in your question text where you want the hover-over tooltip:

Sample text about some kittenA Kitten is a cute animal! that we all love!

Body:
This is my first post, so apologies if this question is not specific enough. I am creating a long survey in Qualtrics (most of the items of which are contained within matrix style questions) that will sometimes be taken by young teens. Because the questions being asked sometimes contain confusing wording, I have created tooltips in HTML to give additional context to the questions, so that younger respondents who may be confused by the wording can hover over a question mark icon to get additional information if desired.

Currently, there are several tool tips in the survey. Sometimes, the tool tip is inserted in the "Question" section of the matrix (i.e., the quetsion text at the top of the matrix), and sometimes, the tool tip is inserted in one of the statements of the matrix (i.e., the statements on the left hand side of the matrix).

My issue is that even when using the same exact code for the different tool tips, only the ones that are found in the question section of the matrix show the span title when using Internet Explorer and Safari. However, when using Chrome, both types of tool tips display the hoverover text. So, my question is, is there a way to get the span title to show regardless of the browser being used?

I am very new to HTML and am unsure why this is happening. I've included a preview survey for others to try, as well as the HTML I used to create the tool tip below.

Preview Survey Link:
https://co1.qualtrics.com/jfe/preview/SV_025DzNles8BNYQR

HTML:

Test

Any advice would be greatly appreciated. Thanks so much!

Body:
Edit the survey -> Look and Feel -> Advanced -> + Add Custom CSS

.myExpandItem
{
    text-decoration: underline;
    position: relative;
}

.myExpandItem:hover .myExpandBox {
    display: block;
}

.myExpandBox
{
    position: absolute;
    background-color: rgba(0,0,0,0.8);
    min-height: 50px;
    width: 250px;
    display: none;
    left: -30px;
    top: 14px;
    padding: 10px;
    color: white;
    border-radius: 15px;
    font-size: 9.000000pt;
    font-family: 'ArialMT';
}

Then edit the question HTML and add this HTML in your question text where you want the hover-over tooltip:

Sample text about <span class="myExpandItem">some kitten<span class="myExpandBox">A Kitten is a cute animal!</span></span> that we all love!


问:
Is there a way to change desktop screen color with ElectronJS
I have a simple Electronjs app and I wanted to change the desktop screen color somehow, but I can't find a way to access the VGA or Monitor settings, so I was wondering is this posible and how?</p>

答:
Simply create a fullscreen browser window and set the background color to your given color using the options to BrowserWindow. Just change #ABABAB in the example given.

```<code>const electron = require('electron');
const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize

let win = new BrowserWindow({ fullscreen: true, backgroundColor:
"#ABABAB" })

});
</code>```

If you don't want to make a "fullscreen" window, you can create a window that is the same size as the screen and place that over everything. This will not cover the menu bar in OSX, though.

```<code>const electron = require('electron');
const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().size
console.log(width + "|" + height);
let win = new BrowserWindow({
        width: width,
        height: height,
        x:0, y:0,
        alwaysOnTop: true,
        frame: false,
        resizable: false,
        backgroundColor: "#ABABAB"
})
win.setAlwaysOnTop(true, "screen-saver");
});
</code>```

Body:
Simply create a fullscreen browser window and set the background color to your given color using the options to BrowserWindow. Just change #ABABAB in the example given.

const electron = require('electron');
const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize

let win = new BrowserWindow({ fullscreen: true, backgroundColor:
"#ABABAB" })

});

If you don't want to make a "fullscreen" window, you can create a window that is the same size as the screen and place that over everything. This will not cover the menu bar in OSX, though.

const electron = require('electron');
const { app, BrowserWindow } = require('electron');

app.on('ready', () => {
const {width, height} = electron.screen.getPrimaryDisplay().size
console.log(width + "|" + height);
let win = new BrowserWindow({
        width: width,
        height: height,
        x:0, y:0,
        alwaysOnTop: true,
        frame: false,
        resizable: false,
        backgroundColor: "#ABABAB"
})
win.setAlwaysOnTop(true, "screen-saver");
});


问:
How to compare two different times using an if else statement?
I'm trying to compare two different times to see which comes before the other, but I'm having trouble coming up with an else if statement that compares their suffixes (am and pm) and outputs the order of the first time relative to the other time.

EDIT: the date type of suffix1 and suffix2 are strings, the data type of time1 and time2 are int

So far, I have this piece of code that checks if the periods are equal:

```<code>if (suffix1.equals(suffix2))
  {
       if (time1 > time2)
       {
          System.out.print("After");
       }
       .....
  }
</code>```

is there a way to see which times' suffix comes before the other?

答:
Use Date to represent time in application: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html

The string representation, should be used only when displaying the time.
When you use dates you can compare them like this myDate.compareTo(anotherDate).

You can print the date in whichever form you want, here is how: Change date format in a Java string

Body:
I'm trying to compare two different times to see which comes before the other, but I'm having trouble coming up with an else if statement that compares their suffixes (am and pm) and outputs the order of the first time relative to the other time.

EDIT: the date type of suffix1 and suffix2 are strings, the data type of time1 and time2 are int

So far, I have this piece of code that checks if the periods are equal:

if (suffix1.equals(suffix2))
  {
       if (time1 > time2)
       {
          System.out.print("After");
       }
       .....
  }

is there a way to see which times' suffix comes before the other?


问:
Why does Visual Studio give you Page_Load for WebForms as a default?
When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool.  So for years, I have always put code for doing things like set properties of controls in Page_Load.  Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event).  So I started to wonder, where is the best place really to set the properties of controls, in OnLoad or Page_Load?  Or in a different method altogether?  And if not Page_Load, why does Studio add that to the code behind?

My final thought:  Although I know that putting logic in OnLoad works fine, I will probably stick with Page_Load for now because that's conventional.  I asked the question really to find out if I had been missing out on something new after I started seeing OnLoad come up in other people's code.  Thank you all for your thoughtful answers!

答:
You don't want to use OnLoad, the reason they use that is because it's a wrapper for raising the Page_Load event.  They put logic in there because they're not handling the Page_Load event.

In short, continue using Page_Load.

OwnerDisplayName: Barneytron

LastEditorDisplayName: Barneytron

OwnerDisplayName: Chad Moran


问:
Firebase session expiration
It looks like Firebase, when they moved from the v2 to v3.x SDKs (and now into v4), decided to remove the option for automatic session expiration in favor of the always-authenticated model.

Firebase 3.x - Token / Session Expiration

https://groups.google.com/forum/#!topic/firebase-talk/uYMlQny1Jb4

This is a nice feature to offer, but from a cybersecurity perspective, I see some problems as this is the only option for the Firebase SDKs with Firebase-generated tokens such as email and password authentication (some of which are explained well in the linked google group discussion).

The commonly-provided suggestion to call user.signOut() on page exit has some holes. Namely, if the client crashes, then this code is never executed and therefore the strategy falls apart. The "sign out on page load" suggestion also has holes in it:

Forces all users to log in every time the page loads/reloads (not the goal)

As Firebase pushes most everything to the client, there is nothing stopping someone for creating a script that attempts to access a targeted Firebase without having the user.signOut()

I'm looking for a strategy that does a better job, from a cybersecurity perspective, that allows a user to opt in to the "always-authenticated" strategy if he/she so chooses, rather than it being the default (i.e. with a "Remember Me" button).

One strategy I came up with is as follows:

User signs in

Get the generated JWT for that session and write it to Firebase

If the user didn't select "remember me" on sign in, set up an onDisconnect handler that clears the token from the list of that users tokens

In Firebase security rules, ensure that the JWT for the user making the request is in the list of tokens for that user

This feels more secure because the onDisconnect method will still execute even if the browser crashes. But, the JWT is not available as a Firebase rules variable (only the contents of the token)!

In light of these issues/flawed approaches, how can I invalidate a session after the browser closes/crashes (or even after a pre-determined period of time) with a Firebase-generated token?

答:
here is a suggestion:
The ID token has an auth_time field. This is the time the user authenticated, you can force whatever session length you want. You can enforce that if you validate the token on your server or via database rules using https://firebase.google.com/docs/reference/security/database/#now and auth.token.auth_time. Check https://firebase.google.com/docs/reference/security/database/#authtoken.

You would require the user reauthenticate to access the data. Reauthentication will update the auth_time in the token.

This is a better approach since keeping track of all ID tokens will not scale well and ID tokens expire after an hour and new ones will be refreshed after the user returns to the app but will maintain the same auth_time.

Not sure if this will alleviate your concerns but Firebase is looking into the following features:

The ability to specify persistence for web authentication. This is similar to how sessionOnly auth worked in Firebase 3.x. This will make "Remember Me" functionality easy to implement.

The ability to revoke sessions.

Title: Firebase session expiration


问:
Grouping Elements on criteria and Finding difference between The Highest and Lowest of Group
I have a dataframe like the following.

```<code>   Best Bid  Best Offer  Best Offer Sign  Lone Time
0     197.0         0.0                1          1
1     198.0         0.0                1          2
2     199.0         0.0                1          3
3     197.0       221.0                0          0
4     221.0       221.0                0          0
5     221.0         0.0                1          1
6     222.0         0.0                1          2
</code>```

I want to make groups of each situation where Lone time is numbers in increasing order before they hit 0(they will always be in increasing order never decreasing) and find the difference between the highest and lowest best bid values in each group. So as an example

```<code>  Best Bid     Best Offer     Best Offer Sign  Lone Time    diff
0     197.0         0.0                1          1          0
1     198.0         0.0                1          2          0
2     200.0         0.0                1          3          3
3     197.0       221.0                0          0          0
4     221.0       221.0                0          0          0
5     221.0         0.0                1          1          0
6     250.0         0.0                1          2          29
</code>```

Here if you notice index 2 and 6 have values of 3 and 39 respectively. For index 2 i have taken the diff of best bid of (index 2 - index 0) and for index 6 i have taken the diff of the best bid of (index 6 - index 5). How do i achieve this?

答:
I think this here will do what you're looking for:

```<code>dat = pd.read_csv('dat.csv', sep=';')

dat['jump'] = (dat['Lone Time'].shift(-1) - dat['Lone Time']).fillna(-1)
dat['jump'] = map(int, (1-np.sign(dat['jump']))/2.)
dat['series'] = dat['jump'].shift(1).fillna(0).cumsum()
dat['diff'] = 0

for s, df in dat.groupby('series'):
    dat.loc[df.index[-1], 'diff'] = (df['Best Bid'].max() - df['Best Bid'].min())

dat = dat.drop(['jump', 'series'], axis=1)
print dat
</code>```

1) find the magnitude of the change in Lone Time

2) mark the last row in the series, shift it by one and fill the missing value with a zero

2.1) distinguish between series by a cumulative sum, every sequence now has its own "identifier"

3) group by series and find the span between the min/max values

4) cleanup: drop the intermediate columns

Body:
I have a dataframe like the following.

   Best Bid  Best Offer  Best Offer Sign  Lone Time
0     197.0         0.0                1          1
1     198.0         0.0                1          2
2     199.0         0.0                1          3
3     197.0       221.0                0          0
4     221.0       221.0                0          0
5     221.0         0.0                1          1
6     222.0         0.0                1          2

I want to make groups of each situation where Lone time is numbers in increasing order before they hit 0(they will always be in increasing order never decreasing) and find the difference between the highest and lowest best bid values in each group. So as an example

  Best Bid     Best Offer     Best Offer Sign  Lone Time    diff
0     197.0         0.0                1          1          0
1     198.0         0.0                1          2          0
2     200.0         0.0                1          3          3
3     197.0       221.0                0          0          0
4     221.0       221.0                0          0          0
5     221.0         0.0                1          1          0
6     250.0         0.0                1          2          29

Here if you notice index 2 and 6 have values of 3 and 39 respectively. For index 2 i have taken the diff of best bid of (index 2 - index 0) and for index 6 i have taken the diff of the best bid of (index 6 - index 5). How do i achieve this?

Body:
I think this here will do what you're looking for:

dat = pd.read_csv('dat.csv', sep=';')

dat['jump'] = (dat['Lone Time'].shift(-1) - dat['Lone Time']).fillna(-1)
dat['jump'] = map(int, (1-np.sign(dat['jump']))/2.)
dat['series'] = dat['jump'].shift(1).fillna(0).cumsum()
dat['diff'] = 0

for s, df in dat.groupby('series'):
    dat.loc[df.index[-1], 'diff'] = (df['Best Bid'].max() - df['Best Bid'].min())

dat = dat.drop(['jump', 'series'], axis=1)
print dat

1) find the magnitude of the change in Lone Time

2) mark the last row in the series, shift it by one and fill the missing value with a zero

2.1) distinguish between series by a cumulative sum, every sequence now has its own "identifier"

3) group by series and find the span between the min/max values

4) cleanup: drop the intermediate columns


问:
Can the Java 9 jshell be used to run code in another JVM?
Java 9 has a read-eval-print loop for Java, called jshell. I've seen it work in it's basic mode, from the command line. Can it also be used in a remote process? In other words, can I connect to another Java process and enter code snippets to run within that runtime?  This would be a nice way to change configuration state in an app server without having to write an admin tool with a UI.

答:
There is no official way of doing so.

Yet, it is not to difficult to rebundle the code and run it on another VM via a Java agent. This would however not work as well as you expect it as it is unclear what class loader the shell should use and how it should interact with the running program.


问:
how access function in try block of external javascript file
I have external js file having following script:

```<code>try {
callback({x: 'abc', y: 'cde' });
}
catch(e) {
}
</code>```

I have inject this script dynamically using following method:

```<code>const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/external.js';
document.getElementsByTagName('head')[0].appendChild(script);
</code>```

I m able to inject the script but I m not able to access the values passed in the callback() of external js.

I have some limitations as well:

The external js file cannot be modified.

This needs to be done in javascript only. I cannot use jQuery for this.

Thanks in advance

答:
I was able to achieved this using following code block

```<code>const src = function callback(data) {
    console.log(data);
};
const injectFunc = () => {
    window.callback = src;
};
const injectScript = () => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'http://example.com/external.js';
    document.getElementsByTagName('head')[0].appendChild(script);
};
</code>```

call the function after init of app.js in following manner:

```<code>init () {
injectFunc();
injectScript();
}
</code>```

In this way you will get the values in the data variable of callback which can be used in further in application if needed.

Body:
I have external js file having following script:

try {
callback({x: 'abc', y: 'cde' });
}
catch(e) {
}

I have inject this script dynamically using following method:

const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://example.com/external.js';
document.getElementsByTagName('head')[0].appendChild(script);

I m able to inject the script but I m not able to access the values passed in the callback() of external js.

I have some limitations as well:

The external js file cannot be modified.

This needs to be done in javascript only. I cannot use jQuery for this.

Thanks in advance

Body:
I was able to achieved this using following code block

const src = function callback(data) {
    console.log(data);
};
const injectFunc = () => {
    window.callback = src;
};
const injectScript = () => {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'http://example.com/external.js';
    document.getElementsByTagName('head')[0].appendChild(script);
};

call the function after init of app.js in following manner:

init () {
injectFunc();
injectScript();
}

In this way you will get the values in the data variable of callback which can be used in further in application if needed.


问:
How to recover a specific user password in jenkins
I m new with jenkins and i want to  know if it s possible to recover jenkins password for a specific user or reinitialis it?

i found a hashed password of the user in config.xml file but i don t know if it s possible to decrypt it

i m using windows server  and jenkins is deployed in my tomcat server

thnks

答:
It's not a hashed password but an encrypted one. Jenkins stores the secrets on its master node.

You could enter the Groovy console in Jenkins (accessible via /script added to your root URL) and try the following:

```<code>println(hudson.util.Secret.decrypt("<EXTRACTED_CIPHERTEXT_FROM CONFIG.XML"))
</code>```

Explanation

Using the decrypt directly within Jenkins will give the method trusted access to the secret, so it should be possible to decrypt it.

Hope that works for you!

Body:
It's not a hashed password but an encrypted one. Jenkins stores the secrets on its master node.

You could enter the Groovy console in Jenkins (accessible via /script added to your root URL) and try the following:

println(hudson.util.Secret.decrypt("<EXTRACTED_CIPHERTEXT_FROM CONFIG.XML"))

Explanation

Using the decrypt directly within Jenkins will give the method trusted access to the secret, so it should be possible to decrypt it.

Hope that works for you!


问:
What's the purpose of a settable md5Hash in UploadMetadata?
See https://firebase.google.com/docs/storage/web/file-metadata#file_metadata_properties

I tried just setting it to bob to see if it did anything.

Nope, when upload finishes, it seems to be set to the actual file hash.

I could imagine a world where if the provided md5Hash doesn't match the file contents the upload fails – but that doesn't seem to be the case either.

Help?

答:
[Firebase Storage Web SDK dev here]

I could imagine a world where if the provided md5Hash doesn't match the file contents the upload fails – but that doesn't seem to be the case either.

Yeah, that's the idea. We built the SDK to support that, but the hash verification functionality isn't currently implemented.

As you observed, setting the md5Hash property doesn't do anything (at time of writing).


问:
AngularJs: controller is called twice by using $routeProvider
Module routes:

```<code>var switchModule = angular.module('switchModule', []);

switchModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/build-content', {templateUrl: 'build-content.html', controller: BuildInfoController});
}]);
</code>```

Controller:

```<code>function BuildInfoController($http, $scope){
    alert("hello");
}
</code>```

Html:

```<code><html ng-app="switchModule">
...
<body>
    <ul>
        <li><a href="#build-content"/></a></li>
    </ul>
    <div class="ng-view"></div>
</body>
...
</code>```

Each time when i click the hyperlink '', the 'BuildInfoController' will be called twice. Am i missing something here?

答:
I too had a similar problem with a customDirective and unitentionally duplicated my controller.

```<code><html>
   <body ng-app="MyApp" ng-controller="MyDirectiveCtrl">
      <my-directive></my-directive>
   </body>
</html>

angular.directive('myDirectivie', [function() {
   return {
         restrict: 'E',
         controller: 'MyDirectiveCtrl',

         ...

   }
}]);
</code>```

I resolved it by removing ng-controller tag at body level

Body:
Module routes:

var switchModule = angular.module('switchModule', []);

switchModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/build-content', {templateUrl: 'build-content.html', controller: BuildInfoController});
}]);

Controller:

function BuildInfoController($http, $scope){
    alert("hello");
}

Html:

...

...

Each time when i click the hyperlink '', the 'BuildInfoController' will be called twice. Am i missing something here?

Body:
I too had a similar problem with a customDirective and unitentionally duplicated my controller.

<html>
   <body ng-app="MyApp" ng-controller="MyDirectiveCtrl">
      <my-directive></my-directive>
   </body>
</html>

angular.directive('myDirectivie', [function() {
   return {
         restrict: 'E',
         controller: 'MyDirectiveCtrl',

         ...

   }
}]);

I resolved it by removing ng-controller tag at body level


问:
Want to do a fade in if a function() is active/called | Javascript
I have the following function in an external Javascript file:

```<code>function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        //dialog("Press N to start a new game");
    }
}
</code>```

And here the codes in my html file:

```<code><div id="pacman">
      <a id="startbutton" type="button" class="btn btn-start" value="">Start new game</a>
      <script src="/pacman/pacman.js" type="text/javascript"></script>
      <script src="/pacman/modernizr-1.5.min.js" type="text/javascript"></script>
    </div>
</code>```

Javascriptcode in html file ("#startbutton" fade out by starting a new game):

```<code>var game = document.getElementById("pacman");

    if (Modernizr.canvas && Modernizr.localstorage &&
        Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
      window.setTimeout(function () { PACMAN.init(game, "<?php echo $root; ?>", 100); }, 0);
     }

    document.getElementById("startbutton").onclick = function(){
        PACMAN.startNewGame();
        $("#startbutton").fadeOut();

    }
</code>```

But now i want if someone is Game Over (function waiting() is active) that the "#startbutton" fade in (instead of the dialog("Press N to start a new game");from the function waiting()), so he can play again by clicking again the "#startbutton". I tried different combinations but nothing works. How can i handle it? Thanks for help.

答:
You could probably get away with jamming it into the external JS file:

```<code>function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        //dialog("Press N to start a new game");
        $("#startbutton").fadeIn();
    }
}
</code>```

Or, if you want it to be super tidy, you can abstract the jQuery stuff with a function defined in your html file:

```<code>var game = document.getElementById("pacman");
// rest of your code

function fadeInStartButton() {
  $("#startbutton").fadeIn();
}
</code>```

and then your external JS calls that function (no "untidy" jquery calls in the external js):

```<code>function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        if (fadeInStartButton) fadeInStartButton();
        else dialog("Press N to start a new game"); // if no function is defined, use the old way
    }
}
</code>```

Body:
I have the following function in an external Javascript file:

function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        //dialog("Press N to start a new game");
    }
}

And here the codes in my html file:

      Start new game

Javascriptcode in html file ("#startbutton" fade out by starting a new game):

var game = document.getElementById("pacman");

    if (Modernizr.canvas && Modernizr.localstorage &&
        Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
      window.setTimeout(function () { PACMAN.init(game, "<?php echo $root; ?>", 100); }, 0);
     }

    document.getElementById("startbutton").onclick = function(){
        PACMAN.startNewGame();
        $("#startbutton").fadeOut();

    }

But now i want if someone is Game Over (function waiting() is active) that the "#startbutton" fade in (instead of the dialog("Press N to start a new game");from the function waiting()), so he can play again by clicking again the "#startbutton". I tried different combinations but nothing works. How can i handle it? Thanks for help.

Body:
You could probably get away with jamming it into the external JS file:

function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        //dialog("Press N to start a new game");
        $("#startbutton").fadeIn();
    }
}

Or, if you want it to be super tidy, you can abstract the jQuery stuff with a function defined in your html file:

var game = document.getElementById("pacman");
// rest of your code

function fadeInStartButton() {
  $("#startbutton").fadeIn();
}

and then your external JS calls that function (no "untidy" jquery calls in the external js):

function waiting() {
    if (state === WAITING && stateChanged) {
        stateChanged = false;
        map.draw(ctx);
        if (fadeInStartButton) fadeInStartButton();
        else dialog("Press N to start a new game"); // if no function is defined, use the old way
    }
}


问:
How to iterate over multiline variable in bash?
Given

```<code># this is programmatically generated... hard-coded here for this example
commands="\nthing1@this is thing 1!\nthing2@this is thing 2!"

while read -r line; do
  cmd=$(printf "$line" | cut -d'@' -f1 | tr -d '\n')
  desc=$(printf "$line" | cut -d'@' -f2 | tr -d '\n')

  printf '  %-20s %s\n' "$cmd" "$desc"
done <<< "$commands"
</code>```

I'd expect that to output

```<code>  thing1        this is thing1!
  thing2        this is thing2!
</code>```

Instead I get

```<code>  thing1thing2        this is thing1!this is thing2!
</code>```

What am I doing wrong?

I want to read over the newlines, so I can then cut on @ and printf accordingly.

答:
```<code>#!/bin/bash

input="\nthing1@this is thing 1!\nthing2@this is thing 2!"

# echo replaces '\n's with real new-lines
# readarray -t loads the multiline string into an array
readarray -t array <<< $(echo -e "${input}")

# loop it
for command in "${array[@]}"; do
    echo "${command}"
done
</code>```

Body:
Given

# this is programmatically generated... hard-coded here for this example
commands="\nthing1@this is thing 1!\nthing2@this is thing 2!"

while read -r line; do
  cmd=$(printf "$line" | cut -d'@' -f1 | tr -d '\n')
  desc=$(printf "$line" | cut -d'@' -f2 | tr -d '\n')

  printf '  %-20s %s\n' "$cmd" "$desc"
done <<< "$commands"

I'd expect that to output

  thing1        this is thing1!
  thing2        this is thing2!

Instead I get

  thing1thing2        this is thing1!this is thing2!

What am I doing wrong?

I want to read over the newlines, so I can then cut on @ and printf accordingly.


问:
Wait until all Ajax finish processing inside another Ajax, then send data
I'm trying to send data off with data from multiple other Ajax requests. The issues comes when sendDataOffAjax() is called, no actual data was sent, because it fires off before any of the other functions have a change to add data. I could easily fix this by just using asyn: false everywhere, but from what I read, that's bad practice.

Here is my code:

```<code>let requests = [];
$.ajax({
    url: someUrl,
    method: 'GET',
    dataType: 'json',
    complete: function (data) {
        if (data.exists) {
            if (condition) {
                requests.push(anotherAjax());
            }
            if (condition) {
                requests.push(someDifferentAjax());
            }
        }
        requests.push(alwaysRunAjax());
    }
}).done(function () {
    $.when.apply($, requests).done(function () {
        sendDataOffAjax();
    });
});
</code>```

Heres what anotherAjax() looks like (All the other Ajax requests also look like this):

```<code>function anotherAjax() {
    return $.ajax({
        url: someUrl,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        complete: function (data) {
            if (data.exists) {
                toSendData.data['NEW_DATA'] = {
                    'data': data.responseJSON
                }
            }
            //send complete signal?
        }
    })
}
</code>```

How could I make it wait until all the data is added through the other Ajax requests, then launch sendDataOffAjax().

The log looks like this:

```<code>Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added
</code>```

答:
No this isn't possible without async:false.
The reason it doesn't count as a good thing to use is becuase it is against the idea of a Ajax which is Asynchronous.
async:false baisiclly "lock" your application to the user until your request is done and when you put it on too much ajax calls in the same time it will make your apllication seems very very slow.
In your case you it will be fine if you'll use async:false on the 2 functions as long as they don't take long to execute.

Body:
I'm trying to send data off with data from multiple other Ajax requests. The issues comes when sendDataOffAjax() is called, no actual data was sent, because it fires off before any of the other functions have a change to add data. I could easily fix this by just using asyn: false everywhere, but from what I read, that's bad practice.

Here is my code:

let requests = [];
$.ajax({
    url: someUrl,
    method: 'GET',
    dataType: 'json',
    complete: function (data) {
        if (data.exists) {
            if (condition) {
                requests.push(anotherAjax());
            }
            if (condition) {
                requests.push(someDifferentAjax());
            }
        }
        requests.push(alwaysRunAjax());
    }
}).done(function () {
    $.when.apply($, requests).done(function () {
        sendDataOffAjax();
    });
});

Heres what anotherAjax() looks like (All the other Ajax requests also look like this):

function anotherAjax() {
    return $.ajax({
        url: someUrl,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        method: 'GET',
        dataType: 'json',
        complete: function (data) {
            if (data.exists) {
                toSendData.data['NEW_DATA'] = {
                    'data': data.responseJSON
                }
            }
            //send complete signal?
        }
    })
}

How could I make it wait until all the data is added through the other Ajax requests, then launch sendDataOffAjax().

The log looks like this:

Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added


问:
Does it hurt performance to dynamically link a shared library that won't be used?
I have a C++ program (in fact it is a dll) which dynamically links to another shared library (python dll), this program has two occasions to be used.

In occasion A, the program will make function calls to that dynamically linked shared library while in occasion B, the program will not.

My question is if I build the program specially for occasion B without linking to the shared library, will I gain performance comparing to the case where I link the shared library without actually using it?

答:
It's really dependent on several factors: What OS, what shared library, and what the application actually does. Possibly also how the shared library is built.

In general, it's not a particularly large penalty, since shared libraries are demand-loaded and use position independent addressing [PIC] (PC-relative, and similar). What this means is that the shared library is being loaded only when it actually is used, and that there's "no work" to load the library. This is something that OS designers and system architects think a lot about, because for many applications that are performance sensitive (for example compilers or web-services), a badly designed shared library system will make performance BAD.

It is of course possible to configure when building the shared library. At least the use of PIC aspect of this, so if the person/company configuring the build of the shared library "wants to", it could be badly configured and worse than zero effect.

To this you have to add any initialization that the shared library does. Well designed shared libraries does "on demand" or "lazy" initialization, in other words, doesn't do much initialization until it's actually required. Again, the details of exactly which library - including how that was configured when it was built - can make a huge difference here.

The only REAL way to tell, in any particular use-case, is to build "with" and "without" the extra shared library, and measure the actual performance.


问:
koa2 ctx.render can't render in a function
I want to render docs to list page, but in the browser, list page is not found.

This is the code:

```<code>router.get('/', function(ctx){
    let type = getURLParm(ctx.url).type;
    var article = {};
    var content = {};
    mongoService.find('col', { type: type, id: { $gte: 0 } },
     function(docs) {
       ctx.render('list',{data:docs});
    });
});
</code>```

答:
Koa (unlike Express) does not wait for any callbacks, so, if the function ended, and the response body is empty, then the request will return Not Found.

To do the trick you must promisify your mongoService.find function, write the middleware as an async function, then await for the mongoService.find

Code for Koa2:

```<code>router.get('/', async function(ctx){
  let type = getURLParm(ctx.url).type;
  var article = {};
  var content = {};
  let docs = await mongoService.find('col', { type: type, id: { $gte: 0 } })
  ctx.render('list',{data:docs});
});
</code>```

And one advice: use a library to parse the request data, for example koa-body

Body:
I want to render docs to list page, but in the browser, list page is not found.

This is the code:

router.get('/', function(ctx){
    let type = getURLParm(ctx.url).type;
    var article = {};
    var content = {};
    mongoService.find('col', { type: type, id: { $gte: 0 } },
     function(docs) {
       ctx.render('list',{data:docs});
    });
});

Body:
Koa (unlike Express) does not wait for any callbacks, so, if the function ended, and the response body is empty, then the request will return Not Found.

To do the trick you must promisify your mongoService.find function, write the middleware as an async function, then await for the mongoService.find

Code for Koa2:

router.get('/', async function(ctx){
  let type = getURLParm(ctx.url).type;
  var article = {};
  var content = {};
  let docs = await mongoService.find('col', { type: type, id: { $gte: 0 } })
  ctx.render('list',{data:docs});
});

And one advice: use a library to parse the request data, for example koa-body