text:
Q: How to disable log4j logging from Java code I use a legacy library that writes logs using log4j. My default log4j.properties file directs the log to the console, but in some specific functions of my main program, I would like to disable logging altogether (from all classes).
I tried this:
Logger.getLogger(BasicImplementation.class.getName()).setLevel(Level.OFF);

where "BasicImplementation" is one of the main classes that does logging, but it didn't work - the logs are still written to the console.
Here is my log4j.properties:
log4j.rootLogger=warn, stdout
log4j.logger.ac.biu.nlp.nlp.engineml=info, logfile
log4j.logger.org.BIU.utils.logging.ExperimentLogger=warn

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-5p %d{HH:mm:ss} [%t]: %m%n

log4j.appender.logfile = ac.biu.nlp.nlp.log.BackupOlderFileAppender
log4j.appender.logfile.append=false
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern = %-5p %d{HH:mm:ss} [%t]: %m%n
log4j.appender.logfile.File = logfile.log

A: If you wanna achieve perfect silence (like for a quiet command line tool), you can  always use the NullAppender.
Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

A: You can use
Logger.getRootLogger().setLevel(Level.OFF);

to disable any logging in java code

A: So, you have 3 loggers defined, including the root:
log4j.rootLogger=warn, stdout
log4j.logger.ac.biu.nlp.nlp.engineml=info, logfile
log4j.logger.org.BIU.utils.logging.ExperimentLogger=warn

Unfortunately, to disable them programatically, you need to specify ALL OF THEM in the code:
Logger.getLogger("ac.biu.nlp.nlp.engineml").setLevel(Level.OFF);
Logger.getLogger("org.BIU.utils.logging.ExperimentLogger").setLevel(Level.OFF);
Logger.getRootLogger().setLevel(Level.OFF);

Here's how to reset it back to what's set in the config file.

A: In the version 1.8 of java.util.logging.Logger the correctly form is:
Logger.getLogger("").setLevel(Level.OFF);

A: Perhaps like that:
Logger.getRootLogger().shutdown();

A: For newer log4j versions, you may consider to call:
LogManager.shutdown();
Instead of:
Logger.shutdown();
which is deprecated. But it still makes the same thing:

Calling this method will safely close and remove all appenders in all the categories including root contained in the default hierachy.

A: You could try TO disable it changing your log4j.properties:
log4j.rootLogger=off, stdout
#log4j.logger.ac.biu.nlp.nlp.engineml=info, logfile
#log4j.logger.org.BIU.utils.logging.ExperimentLogger=warn

...

Ref:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html#OFF

A: Add the following to your log file
log4j.logger.com.class.with.package.BasicImplementation = off, logfiledata

log4j.appender.logfiledata = ac.biu.nlp.nlp.log.BackupOlderFileAppender
log4j.appender.logfiledata.append=false
log4j.appender.logfiledata.layout = org.apache.log4j.PatternLayout
log4j.appender.logfiledata.layout.ConversionPattern = %-5p %d{HH:mm:ss} [%t]: %m%n
log4j.appender.logfiledata.File = logfiledata.log

If the above will not stop if from logging, it will at least log all the data from BasicImplementation class to a separate file.


text:
Q: Return Id of selected row in sql server 2012 i have below table and i want to select the total Quantity 20 of SKU 001A and also want to return the ids of rows from where quantity will be selected.
Id   SKU    QtyRec  QtyDispatch
 1    001A    5          0
 2    001B    5          0
 3    001C    10         0
 4    001A    8          0
 5    001G    5          0
 6    001A    6          0
 7    001F    5          0
 8    001A    25         0
 9    001A    9          0

The quantity 5 of SKU 001A will be selected from id 1, 8 quantity from id 4, 6 Quantity from id 6 and 1 quantity from id 8 to complete the require quantity 20.
I try to explain the whole scenario and in case of any concern please let me know. Thanks in advance for help.

A: DECLARE @Data table (Id int identity(1,1), SKU varchar(10), QtyRec int)
DECLARE @Qty int = 20

INSERT @Data VALUES
('001A', 5 ),
('001B', 5 ),
('001C', 10),
('001A', 8 ),
('001G', 5 ),
('001A', 6 ),
('001F', 5 ),
('001A', 25),
('001A', 9 )

;WITH sumqty AS
(
  SELECT *, SUM(QtyRec) OVER (PARTITION BY SKU ORDER BY Id) AS TotalQty
  FROM @Data WHERE SKU = '001A'
)
,takeqty AS (
  SELECT *,
    CASE
      WHEN @Qty >= TotalQty THEN QtyRec
      ELSE @Qty - ISNULL(LAG(TotalQty) OVER (PARTITION BY SKU ORDER BY Id), 0) -- for single entry of SKU
    END AS TakeQty
   FROM sumqty
)
SELECT * FROM takeqty WHERE TakeQty > 0

SQL Fiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Route [admin.settings.edit] not defined laravel this is my web route php:
Route::get('settings', 'Settings\SettingsController@edit')->name('admin.settings.edit');

and I call this route name like below:

                Settings

but I got this error:

Route [admin.settings.edit] not defined. (View:
  C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
  (View:
  C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)
  (View:
  C:\xampp7\htdocs\template\resources\views\layouts\admin\sidebar.blade.php)

rouet:list returns this error message: `Class App\Http\Controllers\Admin\Settings\SettingsController does not exist
but I have this controller:

namespace App\Http\Controllers\Admin\SettingsController;

use App\Http\Controllers\Controller;
use App\Shop\Brands\Repositories\BrandRepository;
use App\Shop\Brands\Repositories\BrandRepositoryInterface;
use App\Shop\Brands\Requests\CreateBrandRequest;
use App\Shop\Brands\Requests\UpdateBrandRequest;

class SettingsController extends Controller
{

    public function __construct(){}

    public function index()
    {}

    public function create(){}

    public function store(){}

    /**
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit()
    {
        dd("milad");
        return view('admin.brands.edit', ['brand' => '']);
    }

    /**
     * @param UpdateBrandRequest $request
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     * @throws \App\Shop\Brands\Exceptions\UpdateDiscountCodesErrorException
     */
    public function update(UpdateBrandRequest $request, $id)
    {
//        $brand = $this->brandRepo->findBrandById($id);
//
//        $brandRepo = new BrandRepository($brand);
//        $brandRepo->updateBrand($request->all());
//
//        return redirect()->route('admin.brands.edit', $id)->with('message', 'Update successful!');
    }

    public function destroy()
    {}
}

`
updated
all my web route php:
/**
 * Admin routes
 */
Route::namespace('Admin')->group(function () {
    Route::get('admin/login', 'LoginController@showLoginForm')->name('admin.login');
    Route::post('admin/login', 'LoginController@login')->name('admin.login');
    Route::get('admin/logout', 'LoginController@logout')->name('admin.logout');
});
Route::group(['prefix' => 'admin', 'middleware' => ['employee'], 'as' => 'admin.' ], function () {
    Route::namespace('Admin')->group(function () {
        Route::group(['middleware' => ['role:admin|superadmin|clerk, guard:employee']], function () {
            Route::get('/', 'DashboardController@index')->name('dashboard');
            Route::namespace('Products')->group(function () {
                Route::resource('products', 'ProductController');
                Route::get('remove-image-product', 'ProductController@removeImage')->name('product.remove.image');
                Route::get('remove-image-thumb', 'ProductController@removeThumbnail')->name('product.remove.thumb');
            });
            Route::namespace('Customers')->group(function () {
                Route::resource('customers', 'CustomerController');
                Route::resource('customers.addresses', 'CustomerAddressController');
            });
            Route::namespace('Categories')->group(function () {
                Route::resource('categories', 'CategoryController');
                Route::get('remove-image-category', 'CategoryController@removeImage')->name('category.remove.image');
            });
            Route::namespace('Orders')->group(function () {
                Route::resource('orders', 'OrderController');
                Route::resource('order-statuses', 'OrderStatusController');
                Route::get('orders/{id}/invoice', 'OrderController@generateInvoice')->name('orders.invoice.generate');
            });
            Route::resource('addresses', 'Addresses\AddressController');
            Route::resource('countries', 'Countries\CountryController');
            Route::resource('countries.provinces', 'Provinces\ProvinceController');
            Route::resource('countries.provinces.cities', 'Cities\CityController');
            Route::resource('couriers', 'Couriers\CourierController');
            Route::resource('attributes', 'Attributes\AttributeController');
            Route::resource('attributes.values', 'Attributes\AttributeValueController');
            Route::resource('brands', 'Brands\BrandController');
            Route::resource('discounts', 'DiscountCodes\DiscountCodesController');
            Route::resource('comments', 'Comments\CommentsController');
            Route::resource('messages', 'Messages\MessagesController');
            Route::resource('pages', 'Pages\PagesController');
            Route::resource('blog-categories', 'BlogCategories\BlogCategoriesController');
            Route::resource('blog-posts', 'BlogPosts\BlogPostsController');
            Route::resource('scores-categories', 'ScoresCategories\ScoresCategoriesController');
            Route::resource('scores-levels', 'ScoresLevels\ScoresLevelsController');
            Route::resource('affiliate-categories', 'AffiliateCategories\AffiliateCategoriesController');
            Route::resource('products-codes', 'ProductsCodes\ProductsCodesController');
            Route::get('settings', 'SettingsController@edit')->name('admin.settings.edit');

        });

A: Your controller namespace is wrong.
namespace App\Http\Controllers\Admin\SettingsController;

Change it to:
namespace App\Http\Controllers\Admin\Settings;

and your route to:
Route::get('settings', 'Admin\Settings\SettingsController@edit')->name('admin.settings.edit');


text:
Q: Custom Evaluator during cross validation SPARK My aim is to add a rank based evaluator to the CrossValidator function (PySpark)
cvExplicit = CrossValidator(estimator=cvSet, numFolds=8, estimatorParamMaps=paramMap,evaluator=rnkEvaluate)

Although I need to pass the evaluated dataframe into the function, and I do not know how to do that part.
class rnkEvaluate():
def __init__(self, user_col = "user", rating_col ="rating", prediction_col = "prediction"):
    print(user_col)
    print(rating_col)
    print(prediction_col)

def isLargerBetter():
    return True

def evaluate(self,predictions):
    denominator =
    predictions.groupBy().sum(self._rating_col).collect()[0][0]
    TODO
    rest of the calculation ...
    return numerator / denominator

Somehow I need to pass the predictions dataframe at every fold iteration, but I could not manage it.

A: I've solved this issue, here follows the code:
import numpy as np

from pyspark.ml.tuning import CrossValidator, CrossValidatorModel
from pyspark.sql.functions import rand

result = []
class CrossValidatorVerbose(CrossValidator):

    def writeResult(result):
        resfile = open('executions/results.txt', 'a')
        resfile.writelines("\n")
        resfile.writelines(result)
        resfile.close()

    def _fit(self, dataset):
        est = self.getOrDefault(self.estimator)
        epm = self.getOrDefault(self.estimatorParamMaps)
        numModels = len(epm)

        eva = self.getOrDefault(self.evaluator)
        metricName = eva.getMetricName()

        nFolds = self.getOrDefault(self.numFolds)
        seed = self.getOrDefault(self.seed)
        h = 1.0 / nFolds

        randCol = self.uid + "_rand"
        df = dataset.select("*", rand(seed).alias(randCol))
        metrics = [0.0] * numModels

        for i in range(nFolds):
            foldNum = i + 1
            print("Comparing models on fold %d" % foldNum)

            validateLB = i * h
            validateUB = (i + 1) * h
            condition = (df[randCol] >= validateLB) & (df[randCol] < validateUB)
            validation = df.filter(condition)
            train = df.filter(~condition)

            for j in range(numModels):
                paramMap = epm[j]
                model = est.fit(train, paramMap)

                predictions = model.transform(validation, paramMap)
                #print(predictions.show())
                metric = eva.evaluate(spark=spark, predictions=predictions)
                metrics[j] += metric

                avgSoFar = metrics[j] / foldNum

                res=("params: %s\t%s: %f\tavg: %f" % (
                    {param.name: val for (param, val) in paramMap.items()},
                    metricName, metric, avgSoFar))
                writeResult(res)
                result.append(res)
                print(res)

        if eva.isLargerBetter():
            bestIndex = np.argmax(metrics)
        else:
            bestIndex = np.argmin(metrics)

        bestParams = epm[bestIndex]
        bestModel = est.fit(dataset, bestParams)
        avgMetrics = [m / nFolds for m in metrics]
        bestAvg = avgMetrics[bestIndex]
        print("Best model:\nparams: %s\t%s: %f" % (
            {param.name: val for (param, val) in bestParams.items()},
            metricName, bestAvg))

        return self._copyValues(CrossValidatorModel(bestModel, avgMetrics))

evaluator = RankUserWeighted("user","rating","prediction")

cvImplicit = CrossValidatorVerbose(estimator=customImplicit, numFolds=8, estimatorParamMaps=paramMap
                            ,evaluator=evaluator)


text:
Q: Couchdb with Clouseau plugin is taking more storage than expected I've been using an AWS instance with CouchDb as a backup to IBM's Cloudant database of my application (using replication).
Everything seems to work fine but I've been noticing the permanent increase of Volume size in the AWS instance (it gets full all the time with the annoying problem of increasing a volume when there's no space in the partition).
Actual use of storage
The data in the screenshot is using almost 250 GB. I would like to know the possible reason for this issue, my guess is that the Clouseau plugin is using more space to enable the search index queries.
As I'm not an expert with this database, Anyone could explain to me why this is happening and how could I mitigate the issue?
My best regards!

A: If you are only backing up a Cloudant database to a CouchDB instance via replication, you should not need Clouseau enabled.
Clouseau is only required for search indices and if you are not doing queries on your backup database you can disable Clouseau in there. The indices are not backed up in the replication.


text:
Q: How can I set a custom Content-Type to jax-rs client? I am running some JAX-RS resources declared like this:
public interface MyEntityServiceV2 {
    @PUT
    @Consumes({"application/myentity-v2+json"})
    @Produces({"application/myentity-v2+json"})
    @Path("/{uuid:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}")
    Response putMyEntity(@PathParam("uuid") String uuid, MyEntityDto myEntity);
}

Now I want to test them using the Jersey-Client (or any other client if it helps to fix my issue):
MyEntityDto dto = new MyEntityDto();
Entity<MyEntityDto> entity = Entity.entity(dto, MediaType.APPLICATION_JSON_TYPE);

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7001/path/" + UUID.randomUUID().toString());
Invocation.Builder builder = target.request("application/myentity-v2+json");
builder.header("Content-Type", "application/myentity-v2+json");
Response response = builder.put(entity);

Unfortunately this does not work. The request always contains a content type of application/json. And this does not match the interface on the server.
As an alternative I can create the entity with my custom MediaType which also leads to an error because it can't find the MessageBodyWriter for that type.
Oh and I can't change the service declaration.
What do you think is the best way to test this resource?

A: Create an entity with your custom MediaType, and then register a custom MessageBodyWriter with your Client. It could be as simple as extending an existing MessageBodyWrite to return true when isWritable is called, or you may have to implement the writeTo method.


text:
Q: Faster way to compute a sum within a sum? I would like a time efficient way to calculate a sum of the following form:
y = ConstantArray[0,5];
x = {x1, x2, x3, x4, x5};
j = 2;

For[i = 1, i <= 5, i++,
 y[[i]] = x[[i]] + Sum[x[[n - 1]]*Exp[Sum[x[[m - 1]], {m, n, i}], {n, j, i}]
 ]

This produces an output of the following form:
{x1,
 x1*Exp[x1] + x2,
 x1*Exp[x1 + x2] + x2*Exp[x2] + x3,
 x1*Exp[x1 + x2 + x3] + x2*Exp[x2 + x3] + x3*Exp[x3] + x4,
 x1*Exp[x1 + x2 + x3 + x4] + x2*Exp[x2 + x3 + x4] + x3*Exp[x3 + x4] + x4*Exp[x4] + x5}

I would like to perform this sort of calculation for an array of about 300,000 data points to simulate cumulative decay. I am aware of the limitations of the Sum function with regards to computational speed, but I am struggling to recreate this sort of output structure with other functions such as Total or Accumulate. Can anyone suggest a better way?

A: @HenrikSchumacher's iteration expressed with FoldList:
n = 300000;
x = RandomReal[{-1, 1}, n];
y = FoldList[#1*E^#2[[1]] + #2[[2]] &, x[[1]], Partition[x, 2, 1]]; //AbsoluteTiming//First
(*    0.139428    *)

Unfortunately, the more natural FoldPairList is ten times slower:
n = 300000;
x = RandomReal[{-1, 1}, n];
y = FoldPairList[(#1 + #2) {1, E^#2} &, 0, x]; //AbsoluteTiming//First
(*    1.37965    *)

A: An iterative algorithm can compute this in about a second on my machine.
n = 300000;
x = RandomReal[{-1., 1.}, n];
y = ConstantArray[0., n];

y = ConstantArray[0., Length[x]];
y[[1]] = x[[1]];
Do[
  y[[i + 1]] = Exp[x[[i]]] y[[i]] + x[[i + 1]],
  {i, 1, Length[x] - 1}]; // AbsoluteTiming // First

0.758239

As many exponentials are involved, it is not unlikely that floating point over- or underflows occur. These would slow down the process a little.


text:
Q: Where to place the stack and load the kernel I'm new to operating system development and I'm curious about a problem I've run into while developing my own bootloader. My operating system is going to be written in assembly and will run in 16-bit real mode.
I know what the stack is and I have the impression that it grows downwards into the memory. Correct me if I'm mistaken. I know how to load a basic kernel into the memory from a floppy disc and I don't believe that is the problem.
The problem I'm running into is that I'm unsure where to place the stack and load my kernel into memory. I've tried creating my stack like this and I'm running into problems:
mov ax, 0x0000
mov ss, ax
mov sp, 0xFFFF

I'm loading my kernel at 0x1000:0x0000. When I PUSH and later POP the volatile registers in my print function, my kernel just hangs the second time I do call print. This is my print function:
print:
    push ax
    push bx
    push cx

    mov al, [si]
    cmp al, 0
    je p_Done

    cmp al, 9
    je p_Tab

    mov ah, 0xE
    int 0x10

    cmp al, 10
    je p_NewLine
   p_Return:
    inc si
    jmp print
  p_Tab:
    xor cx, cx
   p_Tab_Repeat:
    cmp cx, 8
    je p_Return
    mov ah, 0xE
    mov al, " "
    int 0x10
    inc cx
    jmp p_Tab_Repeat
  p_NewLine:
    xor bx, bx
    mov ah, 0x3
    int 0x10

    mov dl, 0x00
    mov ah, 0x2
    int 0x10
    jmp p_Return
  p_Done:
    pop cx
    pop bx
    pop ax
    ret

These are the lines I want to display:
db "Kernel successfully loaded!", 10, 0
db 9, "Lmao, just a tab test!", 10, 0

This is the output I get when my kernel runs (the _ is the cursor):
Kernel successfully loaded!
_

It successfully prints the first line, but hangs while printing the second. If I remove the PUSH and POP statements it works just fine. Why does my kernel hang when I attempt save and restore registers in my print function? Where should I place my stack and where should I load my kernel?

A: It doesn't help that this isn't a Minimal Complete Verifiable Example but your question suggests possible things to look for. Usually if code works by removing PUSHes and POPs in function prologue and epilogue, it usually means the stack was becoming unbalanced during the execution of the body of the function. An unbalanced stack will cause the RET instruction to return to whatever semi-random location is on the top of the stack. This will likely lead to apparent hangs and/or reboots. The behaviour will be undefined.
I haven't followed the logic in your code, but this stands out:
print:
    push ax
    push bx
    push cx

    ... snip out code for brevity

    jmp print

At some point it is possible for your print function to be restarted at a point before all the pushes. This will cause more PUSHes onto the stack without corresponding POPs at the end. I think you might have been trying to get behavior like this:
print:
    push ax
    push bx
    push cx

.prloop:
    ... snip out code for brevity

    jmp .prloop

The .prloop label appears at the top of the function but after the pushes. This prevents excess values being placed on the stack. .prloop can be any valid label of your choice.

The stack can be placed anywhere in memory that isn't being used by the system and doesn't interfere with your bootloader and/or kernel code. As @RossRidge points out, using an SP of 0xFFFF misaligns the stack because it is an odd address (0xFFFF=-1). The x86 won't complain (absent the Alignment Check flag) but it can hurt stack performance on some x86 architectures.
Note: setting SS:SP to 0x1000:0x0000 will cause the stack to run from 0x1000:0xFFFF down to 0x1000:0x0000. The first 16-bit value pushed will be at 0x1000:0xFFFE.

Your kernel and stack are generally safe anywhere between physical address 0x00520 and 0x90000 as long as they don't conflict with one another. On some systems the upper part of the memory region between 0x90000 and 0xA0000 may not be available. If you want to use this memory area I would avoid the area between 0x9C000 and 0xA0000. This area can be used by the BIOS as part of the Extended BIOS Data Area (EBDA).
The exact amount of usable Low Memory Area (LMA) space can be learned by calling the ROM-BIOS's interrupt 12h service, or directly reading the word at 0x00413. In either case, the result is the amount of KiB of usable memory. If there is less than 640 KiB of actual memory, and/or some of the memory at the LMA's top is used by the EBDA or other software, then the result will be lower than 640 (that is, 0x0280). Technically the result can be higher than 640 too. By multiplying or left-shifting the amount in KiB, the equivalent amount in paragraphs or bytes can be calculated.
The region between 0x00000 and 0x00520 should not be used as it contains the real mode interrupt vector table, the BIOS Data Area (BDA) and 32 bytes of memory that is considered to be reserved.


text:
Q: Are unions, sums (...) of quasiconvex functions again quasiconvex? for a project I need to prove quasiconvexity of several general functions. Can I argue that the union (or sum, or difference...) of quasiconvex functions is again quasiconvex?
I do know that the sum of convex functions is again convex, does this apply to quasiconvexity?
My functions may include the log-function, which is quasiconvex but not convex (for example).
Thank you very much for your help.
Best wishes,
Britta

A: Sum of two quasiconvex functions need not to be quasiconvex. Have you seen this http://en.wikipedia.org/wiki/Quasiconvex_function?


text:
Q: Is $d(xdx)=dx^2$? There's a problem in my book that says to find the second-order derivative of $$u=f(\sqrt{x^2+y^2})$$
This is what I did
$$d^2u=f''(\sqrt{}x^2+y^2)(\frac{xdx+ydy}{\sqrt{x^2+y^2}})^2+f'(\sqrt{}x^2+y^2)d(\frac{xdx+ydy}{\sqrt{x^2+y^2}})$$
$$d(\frac{xdx+ydy}{\sqrt{x^2+y^2}})=\frac{d(xdx+ydy)\sqrt{x^2+y^2}-d(\sqrt{x^2+y^2})(xdx+ydy)}{x^2+y^2}$$
The result of my book shows that $$d(\frac{xdx+ydy}{\sqrt{x^2+y^2}})=\frac{(ydx-xdy)^2}{\sqrt{(x^2+y^2)^3}}$$
To reach that result I used that $d(xdx)=dx^2$ and I got the same result. But is that equality true? If so why is that?

A: In order to find $$d(xdx)$$ you apply the product rule of differentiation.
$$d(xdx)= dxdx + xd^2x = (dx)^2 + xd^2x$$

A: You seem to be on the right path to show
$$  \mathrm{d}\left( \frac{x \,\mathrm{d} x+y \,\mathrm{d}y}{\sqrt{x^2 + y^2}} \right) = \frac{\left(x^2+y^2\right) (x \,\mathrm{d}^2 x+y \,\mathrm{d}^2 y)+x^2 (\mathrm{d}y)^2+y^2 (\mathrm{d}x)^2-2 x y \,\mathrm{d}x \,\mathrm{d}y}{\left(x^2+y^2\right)^{3/2}}  \text{.}  $$
Then
$$  \frac{(y \,\mathrm{d}x - x \,\mathrm{d}y)^2}{(x^2 + y^2)^{3/2}} = \frac{x^2 (\mathrm{d}y)^2+y^2 (\mathrm{d}x)^2-2 x y \,\mathrm{d}x \,\mathrm{d}y}{\left(x^2+y^2\right)^{3/2}}  \text{.}  $$
To find conditions for these two left hand sides to be equal, we set them equal, then cancel matching terms, and then cancel the $(x^2 + y^2)$ between the numerator and the denominator, leaving
$$  0 = \frac{x \,\mathrm{d}^2 x+y \,\mathrm{d}^2 y}{\left(x^2+y^2\right)^{1/2}}  \text{.}  $$
Maybe it's unclear what is happening when $x = y = 0$, but away from that point, the denominator is positive, so this requires $x \,\mathrm{d}^2 x+y \,\mathrm{d}^2 y = 0$.  For that to hold for every choice of $x$ and $y$, we must have $\mathrm{d}^2 x = \mathrm{d}^2 y = 0$ (and with that choice, the limit as $(x,y) \rightarrow (0,0)$ of the right hand side of the previous display becomes zero as well).

A: If this is related to the differential operator $d$ from differential geometry, then a property of $d$ is that $d(dx) = 0$ and $d(uv) = (du)v + u(dv)$.


text:
Q: Is set S is field? Under the matrix addition and multipliaction  ,the set $S= \left\{ \begin{bmatrix}  x & y \\ -\overline x & \overline y \end{bmatrix} : x, y \in
 \mathbb{C}\right\}$ is
Choose the correct option
$1.$ Division ring
$2$ Field
I thinks  both option 1)  and 2)  are correct   because   all propeties of field are satisfies  i have checked its
Is its true ?

A: That question makes no sense, because $M=\left[\begin{smallmatrix}i&0\\i&0\end{smallmatrix}\right]$ belongs to $S$, but $M^2$ doesn't.


text:
Q: How to make custom hatching range in matplotlib? The Issue
I have two 100x100 arrays- one with data (which I'll call array1) and one with some smaller, scaled data (which I'll call array2). I created a test array to see where array2 + array1 is above or below certain thresholds, and the results for each point should be one of three results- array1 + array2 for that point is >5, >10, or neither (<5). Depending on the result, I created a new 100x100 array (array3) and assigned a 1., 2., or 0. to that point, respectively.
Now I want to plot array1 & array3 using plt.contourf(), and I want the latter subplot to have hatching. I want the range of that hatching to be x=0, x=1, and x=2. Looking at the documentation I know I probably can't do it that way, so instead I'll say x<1, 1<=x,<2, and x=>2. Only problem is I don't know how to specify those ranges.
The code (working example)
Here's the full code of the problem.
#Make data array1
array1 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        array1[i,j] = i+j
print array1

#Make data array2
array2 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        array2[i,j] = (i*0.25)+(j*0.25)
print array2

#Make range test array3
array3 = np.empty([10,10])
for i in range(10):
    for j in range(10):
        if array1[i,j]+array2[i,j] > 5 and array1[i,j]+array2[i,j] > 10:
            array3[i,j] = 2
        elif array1[i,j]+array2[i,j] > 5:
            array3[i,j] = 1
        else:
            array3[i,j] = 0
print array3

#Plot
from matplotlib.patches import Ellipse, Polygon
xgrid = np.arange(0,10)
ygrid = np.arange(0,10)
n_levels=2
plt.contourf(xgrid, ygrid, array1)
stip = plt.contourf(xgrid, ygrid, array3, n_levels, colors='none',
              hatches=[None,'.', '/'],
              extend='lower')
#create a legend for the contour set
artists, labels = stip.legend_elements()
plt.legend(artists, labels, handleheight=2)
plt.show

Note the legend. I want the ranges to be x<1, 1<=x,<2, and x=>2, not what the package automatically assigns.
The Question
How can I assign custom ranges to my hatching? I plan to get this example working so I can translate it to a Basemap plot where I have lat-lon data, and on top of that a stippled array of where that lat-lon data is compared to the data+S.D. of two other arrays. I wanted various stippling depending on, for each grid point, if that lat-lon data is > one data+S.D. array, the other data+S.D. array, or both arrays.

A: For more control on the contour levels use the levels keyword.
stip = plt.contourf(xgrid, ygrid, array3, levels=[-1, 0, 1, 2],
                    colors='none', hatches=[None,'.', '/'])
artists, labels = stip.legend_elements()
plt.legend(artists, labels, handleheight=2)


text:
Q: Calculating totalCost Ok below is my code for a class I am taking... I need to know how to properly code the totalCost for this product and I can not for the life of me figure out how to properly do this. The price per product is $1 and I need to calculate a 7% sales tax as well. Help!!!
import javax.swing.JOptionPane;
/**
 * @author bary
 */
public class CocaCola1 {
    public static void main(String[] args)
    {

        String openingMsg = "*** Welcome to CocaCola Online Ordering System ***\n"
                   + "Do yourself a favor and order some Cola... NOW!";
        JOptionPane.showMessageDialog(null, openingMsg);
        System.out.println(0);

        String name = getUserInput("What is your name?");
        System.out.println(name);

        String returnCustomer = getUserInput("Are you a returning customer? (yes/no)");
        System.out.println(returnCustomer);

        String orderType = getUserInput("Would you like to purchase Dasani, Coke, Diet Coke, or Cherry Coke?");
        System.out.println(orderType);

        String orderAmount = getUserInput("How many units would you like to purchase?");
        System.out.println(orderAmount);
        Integer.parseInt(orderAmount);
        // each unit costs $1.00 so orderAmount is equal to cost per unit

        double salesTax = 0.7;

        // create and display output string
                String outputMsg
                = "Hello " +  name + ".\n\n" +
                    "Your return customer status is " + returnCustomer + ".\n" +
                    "You ordered " + orderAmount +
                    " units of " + orderType + ".\n" +
                    "Your total cost is $" + orderAmount + salesTax + ".\n" +
                    "Thank you for visiting CocaCola" + ".\n\n" +
                    "Your order will be proccessed ASAP.\n";
                JOptionPane.showMessageDialog(null, outputMsg);
    }

    private static String getUserInput(String prompt)
    {
        int failCount = 0;
        do
        {
            String answer = JOptionPane.showInputDialog(prompt);
            if (answer == null)
            {
                System.exit(0);
            }

            answer = answer.trim();
            if (answer.isEmpty())
            {
                JOptionPane.showMessageDialog(null, "You must provide a non-blank answer");
                failCount = failCount + 1;
            } else
            {
                return answer;
            }
        } while (failCount < 3);

        JOptionPane.showMessageDialog(null, "You failed three times to provide input... Try again later!");
        System.exit(0);
        return null; // means nothing, as I just exited on the prior line, but need it to compile

} // end main()

} // end class CocaCola1

A: orderAmount + salesTax would only be if the sales tax was static. You need to multiply the orderAmount by the sales tax and add salestax
ex: orderAmount*salesTax+prderAmount
or set salesTax to 1.7 and it would be
orderAmount*salesTax


text:
Q: OSX password issue with special chars in recovery mode I had an issue with my MacBook (latest version) and I tried restarting in recovery mode (cmd+r).
The issue is that my password contains a special character (umbreakable space) for security reasons  with an alt+Space combination.
However the recovery mode does not consider the alt key and the default space is typed instead, therefore the password is incorrect.
Now I'm stuck in recovery mode when booting anyhow with the black screen and a grey lock and I don't know how to get out of there.
Note that my hard disk is encrypted if that has any impact.

A: What happens if you go in to terminal and type resetpassword?  That should take you to a dialog to reset your password.  You have to select your disk and your user account along the way...
Warning:  Changing your password like this might break your keychain.


text:
Q: create json representation for decimal logical type and byte types for avro schema I am trying to create JSON string as per below avro schema, for decimal value.
https://avro.apache.org/docs/1.8.2/spec.html#Logical+Types
{
 "name": "score",
 "type": "bytes",
 "logicalType": "decimal",
 "precision": 10,
 "scale": 5
 }

value
"score":3.4,

I am getting exception
Caused by: org.apache.avro.AvroTypeException: Expected bytes. Got VALUE_NUMBER_FLOAT.

Instead of 3.4 if I give "\u0000" then it works but this is representation of 0, how I will get representation for 3.4?
For now I am creating hard-coded JSON String, but in future I have to convert output into Decimal, how I can do that in scala.
Is there any way to convert value into decimal logical format?

A: Java code:
byte[] score = new BigDecimal("3.40000").unscaledValue().tobyteArray();
for (byte b : score) {
    System.out.println(String.format("\\u%04x", b));
}

Will print out following:
\u00fa
\u00cf
\u00e0

You then need to write json score value like this:
"score":"\u00fa\u00cf\u00e0",

And it should translate to 3.40000.
The reason why 3.40000 is because 'scale' in your schema has value 5. If scale would have value 2, then we would have new BigDecimal("3.40")
Scala function for converting BigDecimal to json so avro will understand it
def toJsonString(value: java.math.BigDecimal): String = {
    val bytes = value.unscaledValue().toByteArray
    bytes
      .map(_.formatted("\\u%04x"))
      .mkString
}


text:
Q: What is special about the numbers 9801, 998001, 99980001 ..? Just saw this post, and realized that

1/9801 =
0.(000102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969799)(repeat)

Similar properties are also exhibited by numbers 998001, 99980001, .. and so on.
Edit: fixed periodic start and end
It is not very obvious to me why this happens. Is there some simple explanation to this property?

A: There is actually a straightforward reason.   As $99$ is $1$ less than $100$, we get a fairly simple expression for its decimal $$\frac{1}{99}=0.01010101010101\overline{01}\dots$$  Now, $$\frac{1}{9801}=\left(\frac{1}{99}\right)^2,$$ and the decimal expansion follows from the formula for general power series $$\left(\sum_{n=1}^\infty x^n\right)^2= x\sum_{n=1}^\infty nx^n.$$
Letting $x=\frac{1}{100}$, the decimal expansion for $\frac{1}{99}$ given above is exactly the same thing as writing $\frac{1}{99}=\sum_{n=1}^\infty x^n$.  Applying our identity, the $x$ in front accounts for the double zero.  Once $n$ is around $99$ we expect to miss a number because we are forcing things to be in decimal, and there will be carrying, which is why the number 98 is missed.
A similar pattern will occur for $\frac{1}{998001}=\left(\frac{1}{999}\right)^2,$ since as before $$\frac{1}{999}=0.001001\overline{001}.$$

A: Since this was recently brought back to the front page, I wanted to point out a particular numberphile blog video on this exact question.
In this video, Brady Haran interviews Dr. James Grime and they discuss why this happens and how to generalize the result.
If I were to briefly summarize the key idea: in the video, they show that this boils down to considering $\dfrac{12345679}{999999999} = \dfrac{1}{81}$, or to evaluating $\dfrac{1}{(1-x)^2}$ at $x = \frac{1}{10}$ and considering a sort of generating functions.

A: It happens in every base that $1/(n-1)^2$ is equal to the series of numbers in increasing order, dropping just the number n-2
  1/5²  = 0.0 1 2 3 5 0 1 2 3 5 0 ...    base 6
 1/15²  = 0.0 1 2 3 4 5 6 7 8 9 A B C D F 0 1 2  ... base 16

The examples quoted are for bases 10, 100, 1000 &c.
Similar series occur with eg these.  These are calculated in base 1000, with leading zeros in each place suppressed.  It's true for all bases and their powers.
 1/(n-1)³ =   0. 0 0  1 3 6 10,15 21 28,36 45 55,66 78 91,105 ... (trianguar numbers)
 1/(n²-n-1) = 0. 0 1 1 2 3 5 8 13 21 34 55 89 144 &c.
 1/(n²-2n-1) = 0.0 1 2,5 12 29,70 169 408,987   (approxmates to sqrt(2)).

A: $1/9801$ and the other numbers are all in the form of $$\frac{1}{999...9^2}.$$  You can see similar results for things like $1/9.9$ squared (only you get fewer zeros after the decimal).  You can also try things like $1/9.999$ squared ($1/(9.999^2)$) and get more zeros between the magic numbers.
Now try $1/9800$ or $1/998000$ and see the magic number sequences that you get. :)  I'm still not understanding that one.

A: I was about to say:
Let's not forget that 9801 is a fundamental solution for x in $x^2-29y^2=1$
When I saw that there is an error in Wolframalpha's treatment of this equation. While 9801 which the program offers, is indeed a solution for x, is it not the fundamental solution (which is x=70 and y=13). This solution combined with itself Brahmagupta style gives x=9801 and y=1920
That is a special cirumstance in itself, I guess.

A: This number "998001" is very interesting but it has 2997 repeating digits and "99980001" has 39996 repeating digits they are too large. The three numbers above and the next next one all have a factor of 3^4 which you will see next in my two examples also have powere of 3's.
The number 81 is 3^4.
1/ 81 = 0.012345679012345679} { 18 repeating digits in brackets}
1/ 8181 = 0.000122234445666788901112333455567779} { 36 repeating digits in brackets}
1/ 818181 = 0.000001222223444445666667888890111112333334555556777779} { 54 repeating digits in brackets}
The number 243 is 3^5.
1/243=0.004115226337448559670781893} { 27 repeating digits in brackets}
1/243243=0.000004111115222226333337444448555559666670777781888893} { 54 repeating digits in brackets}
1/243243243=0.000000004111111115222222226333333337444444448555555559666666670777777781888888893} { 81 repeating digits in brackets}
Ok the number 729 is look a lot like your number 998001 not as systematic as these two numbers. Of all the other poweres of 3's I did not find any other numbers that worked like these two. If you would like to see other examples go to "engert.us/erwin/miscellaneous/Four%20families%20of%20numbers.pdf".
Erwin


text:
Q: Is this series $\sum\limits_{n=0}^\infty \frac{1+\sin n}{10^n}$ divergent or convergent? I've been stuck with this problem for a couple of days trying to solve it but got no where till now. The problem states that we have to prove if the series given below is convergent or divergent, if possible use the limit comparison test.

$$\sum_{n=0}^\infty \frac{1+\sin n}{10^n}$$

I'm honestly stuck with this, I managed to pass the limit comparison test by assuming $b_n=\frac{n}{10^n}$ but then stuck with trying to find if the series $b_n$ is convergent. Can someone please help me out? Thanks!

A: Use the fact that if a series absolutely converges then it converges, and use the fact that you have:
$$\left|\frac{1+\sin n}{10^n}\right|\leq \frac{2}{10^n}$$

A: HINT: Both $$\sum_{n=1}^\infty \frac{1+1}{10^n}$$ and $$\sum_{n=1}^\infty \frac{1-1}{10^n}$$ converge. This is applicable because $-1\leqslant\sin x\leqslant1$


text:
Q: How to handle malformed json for a route with 'defaults: {format: :json}'? I have a url which is supposed to accept only json:
put "/my_url" => "my_controller#my_actio", defaults: {format: :json}

When I send malformed json to it, it doesn't make to an "action" at all and instead it throws an exception  somewhere in Rails and thus my app ends up returning the error 500. Namely, that's an unhandaled exception.
How can I fix that?

A: For you to raise those exception and return 422.
You'll have to create a file under app/middleware, let's call it json_parse_errors.rb
# app/middleware/json_parse_errors.rb
class JsonParseErrors
  def initialize(app)
    @app = app
  end

  def call(env)
    begin
      @app.call(env)
    rescue ActionDispatch::ParamsParser::ParseError => error
      if env['HTTP_ACCEPT'] =~ /application\/json/
        error_output = "There was a problem in the JSON you submitted: #{error}"
        return [
          400, { "Content-Type" => "application/json" },
          [ { status: 422, error: error_output }.to_json ]
        ]
      else
        raise error
      end
    end
  end
end

In your application.rb, add the following line
config.middleware.use JsonParseErrors

A: I have used the following middleware for this use case:
In lib/detect_non_json_labeled_json.rb:
class DetectNonJsonLabeledJson
  def initialize(app, opts = {})
    @app = app
    @opts = opts
  end

  def call(env)
    if(
        middleware_applies_to_this_request?(env) &&
        request_contains_non_json_labeled_as_json?(env)
    )
      [
        415,
        { 'Content-Type' => 'application/json' },
        [ { message: 'Invalid POST body.  Must be parseable as JSON' }.to_json ]
      ]

    else
      @app.call(env)
    end
  end

  private

  def middleware_applies_to_this_request?(env)
    env['PATH_INFO'].start_with?( @opts[:target_prefix] )
  end

  def request_contains_non_json_labeled_as_json?(env)
    labeled_as_json?(env) && contains_non_json?(env)
  end

  def labeled_as_json?(env)
    env['CONTENT_TYPE'] == 'application/json'
  end

  def contains_non_json?(env)
    JSON.parse( ActionDispatch::Request.new(env).raw_post )
    false

  rescue JSON::ParserError
    true
  end
end

In application.rb:
require 'detect_non_json_labeled_json'

module YourApplication
  class Application < Rails::Application
    # ...
    config.middleware.insert_before(
      ActionDispatch::Static,
      DetectNonJsonLabeledJson,
      { target_prefix: '/' }
    )
  end
end

Note this returns a status 415 - unsupported media type.  If you'd like to return 422, just replace the code in the call method.


text:
Q: How to rotate a stack from element's center in flutter? I have a following code:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:math' as math;

void main() {
  debugPaintSizeEnabled = true;
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.grey,
        body: SafeArea(
          child: ImageRotate(),
        ),
      ),
    );
  }
}

class ImageRotate extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Transform.rotate(
      angle: (math.pi / 180) * 45,
      child: Stack(
        children: [
          Positioned(
            top: 100,
            left: 50,
            child: Image.network(
              "https://via.placeholder.com/300x200",
              height: 200,
              width: 300,
            ),
          ),
        ],
      ),
    );
  }
}

Now what I expect is the rotation to be executed from center of the image like so,

Instead it rotates like so,

I also tried looking into transform origin. But I couldn't figure out the origin's offset by myself. Any help would be appreciated.

A: You were in the right direction while trying to get the position of the image (you also need it's size in order to rotate in function of the center).
In order to do this, the classic method in flutter is to use keys.
Here is your problem with the use of this method:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:math' as math;

void main() {
  debugPaintSizeEnabled = true;
  return runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          backgroundColor: Colors.grey,
          body: ImageRotate(),
        ),
      ),
    );
  }
}

class ImageRotate extends StatefulWidget {
  @override
  _ImageRotateState createState() => _ImageRotateState();
}

class _ImageRotateState extends State<ImageRotate> {
  final GlobalKey imageKey = GlobalKey();
  Size imageSize = Size(0, 0);
  Offset imagePos = Offset.zero;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      imageSize = (imageKey.currentContext.findRenderObject() as RenderBox).size;
      imagePos =
          (imageKey.currentContext.findRenderObject() as RenderBox).localToGlobal(Offset.zero);
      setState(() {});
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(imagePos);
    print(imageSize);
    return Transform.rotate(
      angle: imagePos == Offset.zero ? 0 : (math.pi / 180) * 45,
      origin:
          -Offset(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height) / 2 +
              (imagePos + Offset(imageSize.width / 2, imageSize.height / 2)),
      child: Stack(
        children: [
          Positioned(
            top: 200,
            left: 300,
            child: Image.network(
              "https://via.placeholder.com/300x200",
              key: imageKey,
              height: 100,
              width: 100,
            ),
          ),
        ],
      ),
    );
  }
}

Calculus explanation: The origin is the offset of the center. That's why you have to shift it by -Offset(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height)/2. It places the center on the top left of the screen. And then you move to go to the center of the image so here you use the dimensions that you got from the GlobalKey: (imagePos + Offset(imageSize.width / 2, imageSize.height / 2))
imagePos == Offset.zero ? 0 : (math.pi / 180) * 45 explanation: You have to first get the position of the image when their is no rotation, so you first set the rotation to zero, then the imagePos is calculated, then you can apply the rotation angle that you want.


text:
Q: Regular expression in C# to replace these string checks I wish to convert the following code to a regex test where path is a string.
path.Contains(".git") || path.Contains("_ReSharper") || path.Contains("\\Bin\\")
|| path.Contains("\\obj\\") || path.Contains("\\bin\\") || path.Contains("\\ipch\\")
|| path.Contains("\\.git") || path.EndsWith("\\bin") || path.EndsWith("\\obj")
|| path.EndsWith("\\Bin") || path.EndsWith("\\ipch");

Any help would be much appreciated.
Cheers

A: (\.git|_ReSharper|\\[bB]in\\|\\obj\\|\\ipch\\|\\\.git|\\[bB]in$|\\obj$|\\ipch$)
A full explanation of all the operators in this regex can be found at http://www.regular-expressions.info/reference.html
But basically:
-Metacharacters like . and \ need to be escaped with a backslash to interpret them literally
-| means 'match the left OR match the right'. It's like OR for regexes.
-$ means 'the end of the string must occur right here' (or in multiline regex mode, the end of the line or string)
If you paste this into a C# string, make sure it is either an @"" string (to escape backslashes having special meaning) or double up all the backslashes (akin to what you are doing right now).
edit: shorter version, after noticing that contains .git and contains \.git are redundant
(\.git|_ReSharper|\\[bB]in(\\|$)|\\obj(\\|$)|\\ipch(\\|$))


text:
Q: (more_)itertools function to group (predicate true/false) tuples with group borders at first item in group I'm looking for an iterator preferably from itertools or more_itertools that groups my_list such that each group starts at the first even digit that follows after an odd digit (or has no predecessor).
The single yielded groups shall also contain the odd digits trailing after 1 or multiple even digits.
is_even = lambda x: x % 2 == 0
my_list = [2, 8, 7, 6, 4, 2, 4, 5, 3, 4, 1, 2]
# is_even:[t, t, f, t, t, t, t, f, f, t, f, t] # t = true, f = false
# needles:

for group in magic_iterator(my_list, is_even):
    sub_list = list(group)
    # expected results:
    # first sub_list: [2,8,7]
    # second sub_list:[6,4,2,4,5,3]
    # third sub_list: [4,1]
    # fourth sub_list:[2]

I'm optimistic that there is a suitable iterator in more_itertools and I don't have to write it myself (see below) but I cannot find it.
I already tried partition but that splits my list into only two distinct sub groups. I also tried for _, group in groupby(my_list, key=is_even) with the usual groupby from itertools but it splits even and odd digits leading to ~twice as many groups as expected.
Code with similar result, but ugly
I came up with some dirty code that leads the expected result for comparison:
from itertools import groupby
from typing import List

result: List[List[int]] = []
last_group_has_been_added = False
for group_key, group in groupby(my_list, key=is_even):
    sub_list = list(group)
    if group_key is True:
        sub_group = sub_list
        last_group_has_been_added = False
    else:
        try:
            sub_group += sub_list
        except NameError:  # name 'sub_group' is not defined
            # occurs if the first item in my list is odd
            sub_group = sub_list
        result.append(sub_group)
        last_group_has_been_added = True
if not last_group_has_been_added:
    result.append(sub_list)

but that's not very pretty; I'm looking for a one-line solution ideally ;)

A: The more_itertool you're looking for is split_when:
from more_itertools import split_when

is_even = lambda x: x % 2 == 0
my_list = [2, 8, 7, 6, 4, 2, 4, 5, 3, 4, 1, 2]

for group in split_when(my_list,lambda x,y: is_even(y) and not is_even(x)):
    sub_list = list(group)
    print(sub_list)

Prints as expected:

*

*[2, 8, 7]

*[6, 4, 2, 4, 5, 3]

*[4, 1]

*[2]
It also works if first item is odd.


text:
Q: Accessing list-of-lists returned from tcl procedure I have a procedure that returns a list of lists. I can't figure out how to access the inner lists without splitting them first. I'm sure there must be a cleaner way.
For example, this:
proc return_l_of_l {} {
  set x {a b c}
  set y {d e f}
  return [list [list $x] [list $y]]
}
set l [return_l_of_l]
set x_list [lindex $l 0]
set y_list [lindex $l 1]

foreach x $x_list { puts $x }
foreach y $y_list { puts $y }

outputs:
a b c
d e f

not:
a
b
c
d
e
f

A: The problem is this line:
return [list [list $x] [list $y]]

Since x and y already hold lists, it makes a list of lists of lists. You should instead do:
return [list $x $y]

or possibly:
return [list [list {*}$x] [list {*}$y]]

A: proc return_l_of_l {} {
  set x {a b c}
  set y {d e f}
  return [list [list $x] [list $y]]
}

returns a list of two lists each consisting of a single element — a b c and d e f. That's because {a b c} and {d e f} are already constructs which can be interpreted as lists.
Supposedly you'd just need
return [list $x $y]


text:
Q: Cocoa iPhone SDK development - touchesBegan method not working if the UIImageView has CABasicAnimation attached I've created a class derived from UIImageView (class name Customer).
Within this Customer class I implemented the method "touchesBegan" .
Also, I applied a CABasicAnimation to the layer of the Customer class .
(the animation simply moves the imageview. it's neccessary because i want to track the animationDidStop event) .
the problem is that the touchesBegan doesn't work when i touch the current position of the imageview. it works only when i touch the original frame (where it was created).
My suggestion is that touchesBegan not applying on the presentationLayer, but on the original frame .
Do you have a way of solving this issue ??
I really would like to solve this from within the Customer class , and not from the main UIViewController .
Thanks a lot,
  Shahar.

A: Have you enabled userInteraction flag to YES for Customer class.
Thanks,


text:
Q: How add select element to Bootstrap's modal? In my template, there are two parts. The first part contains the list of choices and the second part is a modal window.
I would like to add in my input (modal window) the selected element from my list of choices.
Here is my template:
{% block content %}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<select name="name_id" size="1">
{% for i in list_utilisateur %}
  <option value={{ i.user_id }}>{{ i.username }}</option>
{% endfor %}
</select>

<button class="btn btn-primary" id="btn-confirm" name="fdts" type="submit">CONFIRMATION</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

CONFIRMEZ

      <button type="button" class="btn btn-secondary" id="modal-btn-no">Cancel</button>
      <form class="form-signin" id="login_envoi" method="get" action=".">

        <input type="text" name="fdts"   value = "@name_id"  >
        <button class="btn btn-success btn-lg" type="submit">
 SEND </button>
      </form>

{% endblock %}


text:
Q: Cucumber: how can you create a BaseSteps class if you can't use inheritance with Cucumber? Cucumber: how can you create a BaseSteps class if you can't use inheritance with Cucumber?
Login Steps inherits the CommonSteps class:
    public class LoginSteps extends CommonSteps {

    WebDriver driver = getDriver();

    @Given("^User navigates to the \"([^\"]*)\" website$")
    public void user_navigates_to_the_website(String url) throws Throwable {
        basePage.loadUrl(url);
    }

    @And("^User entered the \"([^\"]*)\" username$")
    public void user_entered_the_username(String username) throws Throwable {
        loginPage.setUsername(username);
    }

public class CommonSteps  {
    @After
    public void close_browser_window(Scenario scenario) throws Exception {
        if (scenario.isFailed()) {
            scenario.embed(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES), "image/png");
        }
    }
}

A: The idiomatic solution in Java, end therefore Cucumber-JVM, is use dependency injection when you want to share state between steps implemented in different classes.
Cucumber support many different dependency injection frameworks. If your project already uses one, it is very likely that your dependency framework is supported.
If you don't use a dependency injection framework, I suggest that you use PicoContainer. If you need to know how to use it, I wrote a blog post describing how to share state between steps.

A: You can use inheritance, just not with steps for the reason's cited in Roberto Pegoraro's link.  I like to organize my steps into different step def files.  But this leads to interoperability problems.  If you use class variables to communicate between steps then those steps have to be in the same file; unless you use inheritance.  I create a UiCommon class to contain the shared class variables (e.g. page file instance variables) that the steps use to communicate between themselves.  Each step definition file extends UiCommon.  Now it doesn't matter how I refactor the steps definitions between the various step definition files.  They can still communicate.
For small projects this isn't usually an issue.  But for a large project with multiple test automation engineers who need to minimize git merge conflicts it matters.


text:
Q: Mobile First 7.1 FWLSE0376E: JWS signed ClientId signature does not match the client ID Intermittent issue occurs, While handshake between iOS Native Application to MobileFirst 7.1.0.00.20180425-1124
Findings

*

*Found out the "scope" query parameter is sent to the server as an empty string.

Here i am trying to WWW-authenticate, based Custom authrealm.
Actual URL
    http://localhost:8080/BA/authorization/v1/authorization?client_id=rr4a6042193a89c44a8d2415874ef6d279123456
 &isAjaxRequest=true&redirect_uri=http%3A%2F%2Fmfpredirecturi&response_type=code&scope=

Excpected URL
    http://localhost:8080/BA/authorization/v1/authorization?client_id=rr4a6042193a89c44a8d2415874ef6d279123456
&isAjaxRequest=true&redirect_uri=http%3A%2F%2Fmfpredirecturi&response_type=code&scope=UserAuthRealm

*As per worklight-jee-library.jar --
com.worklight.authorization.endpoint.token.TokenEndpoint
public key is not matched.
if (!Bytes.areEqual(clientPublicKey, jwsParts.getPublicKey().getEncoded())){
   logger.debug(method, "JWS signature does not match the client ID");
   return false;
 }

 return true;

*So far issue occurred in iOS 12 devices. not in other version of OS

And please find configuration used..
application-descriptor.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <nativeIOSApp xmlns="http://www.worklight.com/native-ios-descriptor" applicationId="**App" bundleId="com.xxx.mobile" id="**App" platformVersion="7.1.0.00.20160528-1648" securityTest="CustomAppAuthenticityAutoProvTest" version="7.2">

    <displayName>iOS</displayName>
    <description>iOS Mobile App</description>

    <accessTokenExpiration>1800</accessTokenExpiration>
    <userIdentityRealms>UserAuthRealm</userIdentityRealms>
    <pushSender password="*********"/>
    <licenseAppType>APPLICATION</licenseAppType>
    <targetCategory>B2C</targetCategory>
</nativeIOSApp>

conf/authenticationConfig.xml
<realm name="UserAuthRealm" loginModule="CustomAuthLoginModule">
   <className>com.ibm.mfp.CustomUserAuthenticator</className>
</realm>

worklight.properties
mfp.session.independent=true
mfp.attrStore.type=database

Device Details
 {
    "x-wl-clientlog-env":"iOSnative",
    "x-wl-clientlog-appversion":"7.0","
    "x-wl-clientlog-model":"iPhone8,2",
    "x-wl-clientlog-osversion":"12.0",
    "x-wl-clientlog-appname":"iOSWLApp"
  }

Response
{
   "error_description":"Client authentication failed",
   "error":"invalid_client"
}

Message.log
00002171 com.worklight.core.auth.impl.AuthorizationFilterUtils
E FWLSE0376E: JWS signed ClientId signature does not match the client ID
0000285b com.worklight.oauth.validation.Validator
I OAuthTAI Authentication failed with Status = 401, WWW-Authenticate: Bearer realm="imfAuthentication", scope=""
Trace.log
[1/27/19 19:08:25:434 GST] 0000285b id=         com.worklight.oauth.validation.Validator                     > validate ENTRY
[1/27/19 19:08:25:434 GST] 0000285b id=         com.worklight.oauth.validation.Validator                     1 validate missing_authorization
[1/27/19 19:08:25:434 GST] 0000285b id=         com.worklight.oauth.validation.Validator                     I processErrorCode OAuthTAI Authentication failed with Status = 401, WWW-Authenticate: Bearer realm="imfAuthentication", scope=""
[1/27/19 19:08:25:434 GST] 0000285b id=         com.worklight.adapters.rest.WLShouldCompressPredicat         1 shouldCompress Request: http://localhost:8080/MA/adapters/AccessAdapter/getDetails disableCompressionAttr=null
[1/27/19 19:08:25:434 GST] 0000285b id=         com.worklight.adapters.rest.WLShouldCompressPredicat         1 shouldCompress Request: http://localhost:8080/MA/adapters/AccessAdapter/getDetails acceptGZipEncoding=true
[1/27/19 19:08:25:435 GST] 0000285b id=         com.worklight.common.util.BaseProjectLocal                   1 unset unset ProjectLocal
[1/27/19 19:08:25:435 GST] 0000285b id=         com.worklight.common.util.BaseProjectLocal                   3 unset java.lang.Throwable
        at com.worklight.common.util.BaseProjectLocal.unset(BaseProjectLocal.java:114)
        at com.worklight.core.auth.impl.MFPRequestListener.requestDestroyed(MFPRequestListener.java:24)
        at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletRequestDestroyed(WebApp.java:2747)


text:
Q: When does covering preserve rational cohomology? Let $X$ and $Y$ be compact manifolds. $p:X \rightarrow Y$ is a covering. Generally it is not true that
$$ H^* (X , \mathbb{Q} ) = H^* (Y , \mathbb{Q} )$$
For instance, if $Y$ is a sphere with $y$ handles (let $y > 1$), then $X$ is a sphere with $x$ handles. Moreover if it is not trivial covering then $x > y$.
But if $X$ and $Y$ are Lie groups and $p$ is homomorphism, then $ H^* (X , \mathbb{Q} ) = H^* (Y , \mathbb{Q} )$. It seems a bit like a miracle.
To prove it you have to consider Chevalley-Eilenberg complex. It counts the cohomology of Lie group. On the other hand it is formulated purely in terms of Lie algebra.
Question: I want a purely topological condition on $p$, $X$ and $Y$ to keep isomorphism $$ H^* (X , \mathbb{Q} ) = H^* (Y , \mathbb{Q} )$$.
For instance, what about condition "$Y$ has trivial tangent bundle"?

A: If $X \to Y$ is a finite Galois cover with Galois group $G$ then it's known that the induced map $H^{\bullet}(Y, \mathbb{Q}) \to H^{\bullet}(X, \mathbb{Q})$ is injective and induces an isomorphism
$$H^{\bullet}(Y, \mathbb{Q}) \cong H^{\bullet}(X, \mathbb{Q})^G.$$
(This has nothing to do with $X$ and $Y$ being compact or manifolds.) So here the answer is that the natural map is an isomorphism iff the action of $G$ on $H^{\bullet}(X, \mathbb{Q})$ is trivial. (This has nothing to do with the tangent bundle of $X$ or $Y$.)
If $p : X \to Y$ is a finite covering map of connected Lie groups (both "finite" and "connected" are essential to what follows; I leave it to you to find counterexamples if either is dropped), then it is Galois with Galois group $G = \text{ker}(p)$, and the covering map is given by quotienting by $G$. The action of $G$ on $H^{\bullet}(X, \mathbb{Q})$ is trivial because it factors through the action of $X$, which is trivial because $X$ is connected. No need to pass to Lie algebras.
So you can expect the action of $G$ to be trivial if it factors through the action of a connected Lie group; for example, you might know that $G$ acts by isometries of some Riemannian metric on $X$ with respect to which the isometry group of $X$ is a connected Lie group. Other than that, all bets are off.
Edit: Note also that if $X, Y$ are compact manifolds then they have Euler characteristics which satisfy $\chi(X) = n \chi(Y)$ where $n$ is the degree of the cover, so a necessary condition in this case (if $n \neq 1$) is that $\chi(X) = \chi(Y) = 0$, which is of course always satisfied for compact Lie groups so no problem there. The way this is reflected in the above argument is that if $G$ is a nontrivial group acting freely on $X$ but trivially on the cohomology of $X$, then by the Lefschetz fixed point theorem $\chi(X) = 0$.


text:
Q: Number of possible marriage arrangements if Marriage Condition is satisfied Suppose I have a set of $n$ boys and each subset of $1\leqslant k \leqslant n$ boys knows at least $k$ girls then this means that the set of boys $B$ satisfies the marriage condition.
I am doing an exercise from a Graph Theory book and it says we can show by induction on $n$ that the number of possible marriage arrangements is $\geqslant t!$ if every individual boy knows at least $t \leqslant n$ girls or there are $\geqslant t!/(t-n)!$ possible marriages if each individual boy knows at least $t>n$ girls.
I am struggling to see how the induction hypothesis can be implemented to prove the $n+1$ case. When you swap from the $n$ to $n+1$ case the conditions change and I can't see the link between them.
Would anyone be able to point me in the right direction?


text:
Q: How do i prevent changing multiple lists? I have this script that should make two different lists. but instead, it changes both of them so they're the same.
from random import shuffle

my_list = [1,2,3,4]
second_list = []
shuffle(my_list)
second_list.extend(my_list)

print(my_list,second_list)

How do I prevent this from happening?

A: Assuming you want the original and the shuffled list at the output, you have to shuffle after saving the original list
from random import shuffle

my_list = [1,2,3,4]
second_list = []
second_list.extend(my_list)
shuffle(my_list)

print(my_list,second_list)

Or if you want 2 shuffled lists:
from random import shuffle

my_list = [1,2,3,4]
second_list = []
second_list.extend(my_list)
shuffle(my_list)
shuffle(second_list)

print(my_list,second_list)


text:
Q: Any lightweight alternatives to PHPMailer? We have an old version of PhpMailer using class.phpmailer.php on shared hosting and need to upgrade to a secure version. It looks like version 6 needs SSH access to install via composer, however version 5.2.26 includes PHPMailerAutoload.php so can this version be simply uploaded and then include PHPMailerAutoload.php or must this version also be installed with composer? The json file for v5.2.26 shows 18 dependancies!
Or is there a lighter weight free alternative to PHPMailer?
UPDATE1: Reading here it seems there is a minimal install option with simple example for version 5.2.stable (currently 5.2.26) if using reduced functionality or specifically including required libraries.
UPDATE2: I'm testing a minimal install using the latest version 6 using:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-6/src/Exception.php';
require 'PHPMailer-6/src/PHPMailer.php';
require 'PHPMailer-6/src/SMTP.php';

$mail = new PHPMailer;
$mail->IsHTML(true);

A: It would probably help if you read the readme which tells you how to deal with this under "Installation and loading". Composer does not require SSH access on your server; you can simply run it locally and upload the vendor folder like you do all your other scripts.
As standard, PHPMailer has no dependencies unless you want to use XOAUTH2, and no new ones have been introduced in 6.0.


text:
Q: Answer draft deleted without warning when signing up I recently saw a question I wanted to answer, so I typed out an answer in the answer box. After I finished writing it, I realized I couldn't post it because I hadn't created an account on that stack yet. I clicked the button to create an account on that stack and got no warning about navigating away from the page. When I returned to the question I found about 2/3 of my answer text was deleted from the text box.
Usually, I get a warning when navigating away from a page with an unposted answer, so I assumed here when I got no such warning that my answer would be saved for me. So it seems like something is not working right in this instance. Either I should have gotten a warning when clicking to create an account, or else my answer should have been properly saved as a draft before I left the page.
I'm running Chrome (version 79.0.3945.130) on Windows 10.


text:
Q: Are all numbers representable as the sum or difference of the products of prime powers of a finite set of primes? If we take the first $k$ primes, are there always going to be natural numbers not representable as:
$$p_1^{a_1} p_2^{a_2} \cdots p_k^{a_k} \pm p_1^{a_1} p_2^{a_2} \cdots p_k^{a_k}\ ?$$
Assume non-negative $a_i$, in case that matters.
e.g. It seems to me as though no $2^a3^b \pm 2^c3^d=11^2$.

A: The answer to your question seems to be that, for the first $k$ primes, there'll always be natural numbers which are not representable as
$$p_1^{a_1} p_2^{a_2} \cdots p_k^{a_k} \pm p_1^{b_1} p_2^{b_2} \cdots p_k^{b_k} \tag{1}\label{eq1}$$
The journal Archiv der Mathematik, published by SpringerLink since $1948$, has an article in June $2012$, Volume $98$, Issue $6$, pp $527$–$533$, with an introductory page at Representing integers as linear combinations of power products. It gives a preview, with the introduction starting with

Let $P$ be a nonempty finite set of at least two prime numbers, and let $A$ be the set of positive integers that are products of powers of primes from $P$. Put $A_{\pm} = A \cup (−A)$. Then there does not exist an integer $k$ such that every positive integer can be represented as a sum of at most $k$ elements of $A_{\pm}$. This follows e.g., from Theorem $1$ of Jarden and Narkiewicz ...

This indicates that even a considerably more general result than what you asked about holds, i.e., not all positive integers can be represented by any fixed number of sums and/or differences of elements of a finite set of powers of primes.

A: This is immediate from results on $S$-unit equations. Indeed, let $p_{k+1}$ be the next prime after $p_1,\dots,p_k$. Any solution to
$$p_1^{a_1}\dots p_k^{a_k}\pm p_1^{b_1}\dots p_k^{b_k}=p_{k+1}^c,$$
upon division by $p_{k+1}^c$, gives a different solution to the $S$-unit equation for $S=\{p_1,\dots,p_{k+1}\}$. General theory implies that there are only finitely many such solutions, hence in particular there are only finitely many $c$ for which a solution exists.
There are extensive tables which list all solutions of the $S$-unit equation for some small $S$, see for instance here. Looking at the fifth file and for solutions with radical $22,33,66$ (there are none for the former two, and for the latter there are a couple, but none involving $11^2$) we see that there indeed isn't a solution to $2^a3^b\pm 2^c3^d=11^2$.


text:
Q: Tomcat HttpSession Cookie Shared I have several separate instances of the same web application running on different servers (all have different public facing IPs).  I make use of sessions to store currently logged in user's information.
HttpSession session = req.getSession(true);

User user = (User)session.getAttribute("user");
if (user == null) {
  // get my user
  session.setMaxInactiveInterval(....);
  session.setAttribute("user", user);
}

The problem is that when I log in to one instance (call it instance 1) and then log in to another (instance 2) then when I switch to instance 1 it picks up the cookie for instance 2 and obviously creates a problem when the user which such an id doesn't exist on instance 1 and even worse when it silently just finds the user that matches that id..
I've looked at the cookies and only one JSESSIONID cookie is created with domain of "localhost" and it is shared with all instances. Is there a way to set Tomcat to set the domain to be the domain of the machine?
I'm running Tomcat 6.0.35
Any help would be appreciated. Thank you!

A: You can change defaultHost to the hostname (or network name) of the server.
Have a look at Tomcat's conf/server.xml configuration file:
<Engine ... defaultHost="myserver">

Then you'll also need to change:
<Host ... name="myserver">

See:
http://tomcat.apache.org/tomcat-6.0-doc/config/engine.html
http://tomcat.apache.org/tomcat-6.0-doc/config/host.html
As another possible solution you can define jvmRoute as the "unique name" for each instance.
<Engine ... jvmRoute="instance1">

This will generate a JSESSIONID like:
C85262796BE5F656BD8EF58A96F03C96.instance1


text:
Q: Wordpress + fancybox . How to list wordpress posts and use fancybox to display the post Im new to wordpress and also javascript and need a bit of help from you experts.
Im trying to make a wordpress page where it contains a slider that shows all the post, but then when you click it, it'll display the image of the post (featured image) as a popup(fancybox), I do not want it to go to the post URL.
I tried playing around with fancybox but still unable to do it. how can i achieve this?

A: <?php $posts_array = get_posts( $args ); ?>

Read more.
You can show those posts in the fancy box easily. In the fancy box plugin, Make the query and retrive posts data where the link is created. There you can add an  tag


text:
Q: Create a CFRunLoopSourceRef using IOPSNotificationCreateRunLoopSource in Swift I am trying to subscribe to changes in power state on macOS. I discovered there is a way using IOKit, though it is a bit convoluted. I need to import it using #import <IOKit/ps/IOPowerSources.h> in an ObjC Bridging header. Then I get access to the function IOPSNotificationCreateRunLoopSource, which has the signature:
IOPSNotificationCreateRunLoopSource(_ callback: IOPowerSourceCallbackType!, _ context: UnsafeMutablePointer<Void>!) -> Unmanaged<CFRunLoopSource>!

I got some help from the answer in Callback method to Apple run loop, but still doesn't manage to create a function of type IOPowerSourceCallbackType in Swift. What is the missing piece to have this compile?

A: The issue is that IOPowerSourceCallbackType is a C function.
According to Apple's documentation these functions are available as closures:

C function pointers are imported into Swift as closures with C function pointer calling convention
https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID148

So the easiest way is to use a closure:
IOPSNotificationCreateRunLoopSource({ (context: UnsafeMutableRawPointer?) in
    debugPrint("Power source changed")
}, &context)

A second option is to use a top-level function:
func powerSourceChanged(arg: UnsafeMutableRawPointer?) {
    debugPrint("Power source changed")
}
IOPSNotificationCreateRunLoopSource(powerSourceChanged, &context)

For reference the complete implementation of how I'm using this:
class WindowController: NSWindowController {
    static var context = 0

    override func windowDidLoad() {
        super.windowDidLoad()
        let loop: CFRunLoopSource = IOPSNotificationCreateRunLoopSource({ (context: UnsafeMutableRawPointer?) in
            debugPrint("Power source changed")
        }, &WindowController.context).takeRetainedValue() as CFRunLoopSource
        CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
    }
}

UPDATE
To let it interact with the instance the loop was setup from, you have to pass self as context, however self isn't a pointer.
When you try to pass self as pointer by prepending it with & (&self), you'll get an error that self is immutable.
To convert it a to an opaque pointer you can use the Unmanaged class:
let opaque = Unmanaged.passRetained(self).toOpaque()

Which then can be used as an UnsafeMutableRawPointer:
let context = UnsafeMutableRawPointer(opaque)

What we can use as the context for IOPSNotificationCreateRunLoopSource.
And then in the callback, by using the Unmanaged class again, we can resolve this pointer back to its initiating instance:
let opaque = Unmanaged<WindowController>.fromOpaque(context!)
let _self = opaque.takeRetainedValue()

Full example:
func PowerSourceChanged(context: UnsafeMutableRawPointer?) {
    let opaque = Unmanaged<WindowController>.fromOpaque(context!)
    let _self = opaque.takeRetainedValue()
    _self.powerSourceChanged()
}

class WindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()
        let opaque = Unmanaged.passRetained(self).toOpaque()
        let context = UnsafeMutableRawPointer(opaque)
        let loop: CFRunLoopSource = IOPSNotificationCreateRunLoopSource(
            PowerSourceChanged,
            context
        ).takeRetainedValue() as CFRunLoopSource
        CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
    }

    func powerSourceChanged() {
        debugLog("Power source changed")
    }
}

Bonus
A related article about CFunction pointers


text:
Q: Formal proof that for distinct $A_i$ and $B \subset \bigcup A_i$, $\sum P(B\cup A_i) = P(B)$ What is a formal proof that for distinct $A_i$ and $\displaystyle B \subset \bigcup_{i\in I} A_i,$ $\sum_{i\in I} P(B\cap A_i) = P(B)?$
Is it just obvious?

A: The formula you mention holds if any pair of $A_i$ satisfies $A_i\cap A_j=\emptyset.$ If not, it is false in general. Also we need to assume that the family of $A_i$'s (that is, the set $I$) is finite or countable.
If  $A_i\cap A_j=\emptyset,$ for any $i\neq j,$ then the collection $B\cap A_i$ is a family of disjoints events.  Then, it follows from the third axiom of probability that
$$\sum_i P(B\cap A_i)= P(\bigcup_{i\in I} (B\cap A_i))=P(B),$$ where in the last equality we have used that $\displaystyle B\subset \bigcup_{i\in I} A_i.$

A: use latex in your posts please. as to the question - the sets $B\cap A_i$ are, by definition of $A_i$ are disjoint and sum up to $B$. then you just apply definition of probability measure which is additive on disjoint, measurable sets.


text:
Q: Update user to avoid duplicate (devise+omniauth:twitter) I created a rails app where users were able to signed up with devise ! But I just added omniauth-twitter - So now users can signed up with Twitter.
The problem is that some users already has their email adresses in the DB, so when they logged in using twitter, they are redirected to the final registration step, where they are supposed to add their email adress (because twitter doesn't give you the email adresses of their users).
What is the best way to deal with this concern ?
Should I reset my DB? so users will have to create a new account from scratch ? (easy steps with the twitter login)
Or is there a way to update the DB to allow duplicate of email for users who are already in the DB?
if someone can help me with this,  I would highly appreciate!

A: This is the best guide out there for that. It worked for me.
http://www.orhancanceylan.com/rails-twitter-and-facebook-authentications-with-omniauth-and-devise/#comment-198


text:
Q: Can not input line with Scanner I have two classes: Pizza and PizzaOrder. PizzaOrder allow for user create a new order with 1-3 pizzas in his's order. After input the number of Pizza, It will continue to input the information of each pizza. But I have error with Scanner, I can't not input anymore after input the number of Pizza.
Here is my code:
class Pizza:
public class Pizza {

    public static void main(String[] args){
        Pizza pizza1 = new Pizza("Large", 1, 1, 2);
        Pizza pizza2 = new Pizza("Small", 3, 0, 1);
        Pizza pizza3 = new Pizza("Medium", 1, 1, 3);

        System.out.println(pizza1.getDescription());
        System.out.println(pizza2.getDescription());
        System.out.println(pizza3.getDescription());
    }

    private String size;
    private int numberOfCheese, numberOfPepperoni, numberOfHam;

    public Pizza(String size, int numberOfCheese, int numberOfPepperoni,
            int numberOfHam) {
        super();
        this.size = size;
        this.numberOfCheese = numberOfCheese;
        this.numberOfPepperoni = numberOfPepperoni;
        this.numberOfHam = numberOfHam;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public int getNumberOfCheese() {
        return numberOfCheese;
    }

    public void setNumberOfCheese(int numberOfCheese) {
        this.numberOfCheese = numberOfCheese;
    }

    public int getNumberOfPepperoni() {
        return numberOfPepperoni;
    }

    public void setNumberOfPepperoni(int numberOfPepperoni) {
        this.numberOfPepperoni = numberOfPepperoni;
    }

    public int getNumberOfHam() {
        return numberOfHam;
    }

    public void setNumberOfHam(int numberOfHam) {
        this.numberOfHam = numberOfHam;
    }

    public double calcCost(){
        if(size.equals("Small"))
            return 10 + numberOfCheese*2 + numberOfPepperoni*2 + numberOfHam*2;
        else if(size.equals("Medium"))
            return 12 + numberOfCheese*2 + numberOfPepperoni*2 + numberOfHam*2;
        return 14 + numberOfCheese*2 + numberOfPepperoni*2 + numberOfHam*2;
    }

    public String getDescription(){
        return "Pizza size: "+size +
                "\nNumber Of Cheese Topping: " + getNumberOfCheese()
                +"\nNumber Of Pepperoni Topping: "+ getNumberOfPepperoni()
                +"\nNumber Of Ham Topping: "+ getNumberOfHam()
                +"\nPizza cost: " + calcCost()+"$\n";
    }
}

class PizzaOrder:
import java.util.Random;
import java.util.Scanner;

public class PizzaOrder {

    public static void main(String[] args){
        PizzaOrder pizzaOrder = new PizzaOrder();
        pizzaOrder.setNumPizzas(pizzaOrder.numPizzas);
    }

    private Pizza pizza1, pizza2, pizza3;
    private int numPizzas;
    private int id;

    public PizzaOrder(){
        System.out.println("Enter the number of Pizza: ");
        Scanner scanner = new Scanner(System.in);
        this.numPizzas = scanner.nextInt();
        scanner.close();
        Random random = new Random();
        int range = 100 - 0 + 1;
        this.id =  random.nextInt(range) + 0;
    }

    public void setNumPizzas(int numPizzas){
        if(numPizzas == 1){
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
        }
        else if(numPizzas == 2){
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
            System.out.println("-----------Enter Pizza2's Information-----------");
            enterInformation(pizza2);
        }
        else if(numPizzas == 3){
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
            System.out.println("-----------Enter Pizza2's Information-----------");
            enterInformation(pizza2);
            System.out.println("-----------Enter Pizza3's Information-----------");
            enterInformation(pizza3);
        }
    }

    public double calcTotal(){
        return pizza1.calcCost() + pizza2.calcCost() + pizza3.calcCost();
    }

    public void enterInformation(Pizza pizza){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the pizza's size: ");
        String size = scanner.nextLine();
        pizza.setSize(size);
        System.out.println("Enter the number of Cheese topping: ");
        int numberOfCheese = scanner.nextInt();
        pizza.setNumberOfCheese(numberOfCheese);
        System.out.println("Enter the number of Pepperoni topping: ");
        int numberOfPepperoni = scanner.nextInt();
        pizza.setNumberOfPepperoni(numberOfPepperoni);
        System.out.println("Enter the number of Ham topping: ");
        int numberOfHam = scanner.nextInt();
        pizza.setNumberOfHam(numberOfHam);
        scanner.close();
        System.out.println("This pizza cost: " + pizza.calcCost() +"$");
    }
}

When I input the number of Pizza == 1 in PizzaOrder class, it show error:
Enter the number of Pizza:
1
-----------Enter Pizza1's Information-----------
Exception in thread "main" java.lang.NullPointerException
    at bai2.PizzaOrder.enterInformation(PizzaOrder.java:69)
    at bai2.PizzaOrder.setNumPizzas(PizzaOrder.java:30)
    at bai2.PizzaOrder.main(PizzaOrder.java:10)

How to solve this?

A: You should first create Pizza instances and then access it's member functions like pizza.setSize in enterInformation
In each if statement you can;
pizza1 = new Pizza()
System.out.println("-----------Enter Pizza1's Information-----------");
enterInformation(pizza1);

Also you already has pizzaOrder.numPizzas in setNumPizzas so passing it again is redundant ;
pizzaOrder.setNumPizzas(pizzaOrder.numPizzas);

I suggest you to use array for multiple Pizza instances.

A: You shouldn't use multiple instances of Scanner wrapping the input stream System.in, because once you close it, it is not supposed to be used again.
Instead declare a single instance of Scanner with System.in. You can declare a Utils class holding a global instance of scanner. Or just put a public static instance of Scanner in either Pizza or PizzaOrder. - As long as it is accessible globally, either way works.
public InputUtil {
    public static Scanner scanner = new Scanner(System.in);
}

Use as
InputUtil.scanner.nextInt();

A: Along with not initializing instances of pizza1,2,3, problem is that you are closing stream
Here
public static void main(String[] args){
    PizzaOrder pizzaOrder = new PizzaOrder();
    pizzaOrder.setNumPizzas(pizzaOrder.numPizzas);
}

public PizzaOrder(){
    ...
    scanner.close();
    ...
}

Then from setNumPizza which calls enterInformation
public void enterInformation(Pizza pizza){
    Scanner scanner = new Scanner(System.in);
    ...
}

Once you call scanner.close, it will close the underlying stream. Create a single instance

A: I fixed it by replace scanner.close() by scanner.nextLine()
Here is my code in PizzaOrder class:
import java.util.Random;
import java.util.Scanner;

public class PizzaOrder {

    public static void main(String[] args){
        PizzaOrder pizzaOrder = new PizzaOrder();
        pizzaOrder.setNumPizzas(pizzaOrder.numPizzas);
        pizzaOrder.getPizzaOrderDescription();
    }

    private Pizza pizza1, pizza2, pizza3;
    private int numPizzas;
    private int id;

    public PizzaOrder(){
        System.out.println("Enter the number of Pizza: ");
        Scanner scanner = new Scanner(System.in);
        this.numPizzas = scanner.nextInt();
        scanner.nextLine();
        Random random = new Random();
        int range = 100 - 0 + 1;
        this.id =  random.nextInt(range) + 0;
    }

    public void setNumPizzas(int numPizzas){
        if(numPizzas == 1){
            pizza1 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
        }
        else if(numPizzas == 2){
            pizza1 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
            pizza2 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza2's Information-----------");
            enterInformation(pizza2);
        }
        else if(numPizzas == 3){
            pizza1 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza1's Information-----------");
            enterInformation(pizza1);
            pizza2 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza2's Information-----------");
            enterInformation(pizza2);
            pizza3 = new Pizza("", 1, 1, 1);
            System.out.println("-----------Enter Pizza3's Information-----------");
            enterInformation(pizza3);
        }
    }

    public double calcTotal(){
       if(numPizzas == 1)
          return pizza1.calcCost();
       else if(numPizzas == 2)
          return pizza1.calcCost() + pizza2.calcCost();
       return pizza1.calcCost() + pizza2.calcCost() + pizza3.calcCost();
    }

    public void enterInformation(Pizza pizza){
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the pizza's size: ");
        String size = scanner.nextLine();
        pizza.setSize(size);
        System.out.println("Enter the number of Cheese topping: ");
        int numberOfCheese = scanner.nextInt();
        pizza.setNumberOfCheese(numberOfCheese);
        System.out.println("Enter the number of Pepperoni topping: ");
        int numberOfPepperoni = scanner.nextInt();
        pizza.setNumberOfPepperoni(numberOfPepperoni);
        System.out.println("Enter the number of Ham topping: ");
        int numberOfHam = scanner.nextInt();
        pizza.setNumberOfHam(numberOfHam);
        scanner.nextLine();
        System.out.println("This pizza cost: " + pizza.calcCost() +"$");
    }

    public void getPizzaOrderDescription(){
        System.out.println("Your total cost is: " + calcTotal() +"$");
    }
}

The output:
Enter the number of Pizza:
3
-----------Enter Pizza1's Information-----------
Enter the pizza's size:
Large
Enter the number of Cheese topping:
1
Enter the number of Pepperoni topping:
1
Enter the number of Ham topping:
1
This pizza cost: 20.0$
-----------Enter Pizza2's Information-----------
Enter the pizza's size:
Large
Enter the number of Cheese topping:
1
Enter the number of Pepperoni topping:
1
Enter the number of Ham topping:
1
This pizza cost: 20.0$
-----------Enter Pizza3's Information-----------
Enter the pizza's size:
Small
Enter the number of Cheese topping:
2
Enter the number of Pepperoni topping:
2
Enter the number of Ham topping:
2
This pizza cost: 22.0$
Your total cost is: 62.0$


text:
Q: Is there an extension that would show info about current file? I'd like a way to easily see the timestamp of the current file - and possibly more info. Have searched all around, but couldn't find something like this. OTOH, this seems such a basic feature that I can't believe it doesn't exist...
(Ctrl+O doesn't help, since the list of files might be inconveniently long...)


text:
Q: Gradel Sync Failed Unexpectedly
I was using the studio and i imported firebase auth dependencies and my gradle sync failed

Log cat
  `Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:`

Event Log
1:00 AM Gradle sync failed: Cause: startup failed:
            build file 'C:\Users\Abhi\Desktop\DESKTOP\MY BOOK\BscIt\build.gradle': 1: unexpected token: < @ line 1, column 1.
            <component name="libraryTable">
            ^
            1 error

A: Have a look at your build.gradle file. The error message indicates that something is wrong there. Most likely the text <component name="libraryTable"> should not be in there.


text:
Q: Weird Network Behavior of Home Router First of all I would like to apologize because what you are going to read will be long and confusing but I am fighting this issue for 3 days now and am out of ideas.
At home I have the following setup

*

*50Mbps Internet connects into a home router A

*2 desktop computers connect to router A via standard FTP LAN cables including one where the cable is ~20m long.

*a second router B connects to router A via standard FTP LAN cable X (~20m long).

*several devices connect to the wireless network of router B and there are a couple of desktop computers connected to it through FTP LAN cables.
For some reason computers connected to router B when it is connected via cable X have very slow Internet connection. It is like 5 times slower than what is expected. This is the actual problem I am trying to solve.
Interesting facts

*

*If a computer is connected to cable X directly instead of through router B the Internet speed is just fine (up to the 50Mbps I get from the ISP). Tested with two computers.

*I have tried replacing router B with another router C and the problem persists.

*If I connect router B via another cable to the same ports with the same settings everything seems to work fine and computers connected to router B have quite fast Internet

*I have tested mainly via Speedtest.net but I have also achieved similar speeds when downloading a file

*The upload speed is quite higher than the download speed in all cases. Note that my ISP usually has higher upload speed (unless it manages to hit the 50Mbps cap)

*It seems like the speed when connecting through router B with cable X is reduced 4-5 times no matter what the original speed is. For example via router B I get 10Mbps speed to local servers where I get 50Mbps when connected on router A. If I use a distant server where the ISP is only able to provide 25Mbps I get 4-5Mbps on router B. WiFi is slower than LAN on both routers (which is normal) but the reduced speed is reduced proportionally for WiFi. In addition the upload speed is normally higher from the ISP and it is also reduced proportionally.

*I have tried two different network configurations. One where I have NAT behind NAT where router B connects to router A via the WAN port and has its own DHCP. Second where router B connects to router A via standard LAN port and has DHCP disabled. In this configuration router B serves as a switch and the Network Gateway for computers connected to router B is the internal IP address of router A. Both configurations work just fine but both manifest the reduced speed issue.

*pings seem to work just fine

*As far as I can tell none of the cables is crossed

The RJ45 setup for cable X
orange
orange-white
brown
brow-white
blue
blue-white
green
green-white
This is a big problem for me since cable X passes through walls and floors and is very hard to replace. I also may have gotten some of the facts wrong because I am almost going crazy with this issue and testing includes going several floors up and down the staircase. One hypothesis I came up with is that the cable is defective in such a way that the voltage from the router affects its performance. When it is connected to a computer it performs just fine but the router has less power. Related hypothesis includes the cable being affected by electricity cables in the walls when the voltage is low. (I know nothing about electricity)
So any ideas what to do, what to test or what the issue may be?

A: Your pair ends are not right for Ethernet usage.  From what you've said, it seems like they are wired straight-through, when the lines need a certain arrangement for Ethernet to work.
Both ends should either be done to the TIA 568A or TIA 568B (more commonly B) spec.
586B order: Orange-white, Orange, Green-white, Blue, Blue-White, Green, Brown-White, Brown.

A: Normal pin/color (numerical order 1-8, left to right looking at the gold pin side, end up):
1 White Orange
2 Orange
3 White Green
4 Blue
5 White Blue
6 Green
7 White Brown
8 Brown
The blue pair is reversed and the green pair is split to either side of it. Other than following standards there's no particular significance to the colors, but due to historical battiness in the way things are wired, that arrangement needs to be followed (for gigabit.) For 10Mbit or 100Mbit, only the orange and green pairs (Pins 1,2,3 & 6) are used (power over ethernet schemes may alter that - but for data, only those two pairs are needed for 10/100 Mbit.)


text:
Q: Converting Images with Python I'm having problems getting images to convert out of bytes/strings/etc. I can turn an image into a string, or a byte array, or use b64encode on it, but when I try decode/revert it back to an image, it never works. I've tried a lot of things, locally converting an image and then reconverting it, saving it under a different name. However, the resulting files will never actually show anything. (black on Linux, "can't display image" on windows)
My most basic b64encoding script is as follows:
import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()
    string = base64.b64encode(data)
    convertit = base64.b64decode(string)

    t = open("Puppy2.jpg", "w+")
    t.write(convertit)
    t.close()

if __name__ == "__main__":
    convert("Puppy.jpg")

I've been stuck on this for a while. I'm sure it's a simple solution, but being new to Python, it's been a bit difficult trying to sort things out.
 If it helps with any insight, the end goal here is to transfer images over a network, possibly MQTT.
Any help is much appreciated. Thanks!
Edit** This is in Python 2.7.
Edit 2** Wow, you guys move fast. What a great intro to the community - thanks a lot for the quick responses and super fast results!

A: For python3, you need to open and write in binary mode:
def convert(image):
    f = open(image,"rb")
    data = f.read()
    f.close()
    string = base64.b64encode(data)
    convert = base64.b64decode(string)
    t = open("Puppy2.jpg", "wb")
    t.write(convert)
    t.close()

Using python 2 on linux, simply r and w should work fine. On windows you need to do the same as above.
from the docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn't hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

You can also write your code a little more succinctly by using with to open your files which will automatically close them for you:
from base64 import b64encode, b64decode

def convert(image):
    with open(image, "rb") as f, open("Puppy2.jpg", "wb") as t:
        conv = b64decode(b64encode(f.read()))
        t.write(conv)

A: import base64

def convert(image):
    f = open(image)
    data = f.read()
    f.close()
    return data

if __name__ == "__main__":
    data = convert("Puppy2.jpg")
    string = base64.b64encode(data)
    convert = base64.b64decode(string)

    t = open("Puppy2.jpg", "w+")
    t.write(convert)
    t.close()


text:
Q: Is it possible to make a type-safe collection of functions in TS? I'm writing a small library to simplify working with redux, but I got stuck with typings.
What I am trying to do basically boils down to the following:

*

*parent class processes action descriptors into actions

*child class provides said descriptors

Problem is, type information defined in child is lost in the process.
Smallest test case is as follows:
type callable = (...args: any[]) => any
interface CallableCollection {
    [s: string]: callable
}

class Parent {
    functions: CallableCollection
    constructor() {
        this.functions = this.a;
    }
    get a(): CallableCollection {
        return {};
    }
}

class Child extends Parent {
    get a() {
        return {
            a: (x: string) => x,
            b: (x: number) => x,
        }
    }
}

const test = new Child();
test.a.a(5);//type error
test.functions.a(5);// no type errors

I could make it work properly by making class generic and supplying all needed types as type arguments, but it looks extremely lame from a class user's perspective.
Is there a way to make it work nicely in TS without supplying typings as arguments in generic class?

A: I guess it depends on your actual use case, but you can sometimes use polymorphic this to take the place of generics when the particular type in question is derivable from a subclass's other properties:
interface CallableCollection {
  [s: string]: (...args: any[]) => any;
}

class Parent {
  functions: this["a"]; // polymorphic this and a lookup of "a"
  constructor() {
    this.functions = this.a;
  }
  get a(): CallableCollection {
    return {};
  }
}

class Child extends Parent {
  get a() {
    return {
      a: (x: string) => x,
      b: (x: number) => x
    };
  }
}

const test = new Child();
test.a.a(5); //type error
test.functions.a(5); // type error

Does that work for you?  Hope that helps; good luck!