text:
Q: How to Draw Route Received From MapQuestApi in nutiteq Map? i have some problems creating route directionns on the nutiteq map from MapQuestApi, i Know how to Receive the Information needed
@Override
        public void onSuccess(RouteResponse routeResponse) {
            clearButton.setVisibility(View.VISIBLE);
            if(showItineraryButton.getVisibility()==View.GONE &&
                    showMapButton.getVisibility()==View.GONE){
                showItineraryButton.setVisibility(View.VISIBLE);
            }

            createRouteButton.setEnabled(true);
        }
    });

but i dont know how to use them to create route lines on them nutiteq map, and appearantly its demo sample doesnt say any thing, it has a RouteActivity Interface which does not exists any where in the Sample Codes, if any one has done this , can some one please show me how can i "draw" the route points using received information ? i would really appreciate

A: The RouteActivity is in separate project AdvancedLayers.
From MapQuestRouteActivity.java in AdvancedMap3D project you can find method public void routeResult(Route route) which is called from MapQuestDirections.java (source is also in AdvancedLayers). The MapQuestDirections has already parsed routing result and created a line (which is part of the Route) which can be added to the map.


text:
Q: Templates folder on mac equivalent to in Ubuntu I recently switched from Ubuntu to Mac, but miss the templates folder. I've googled and surprisingly can't find anyone else asking about this. Is there a way to create an equivalent on Mac?
If you're not familiar with Ubuntu, this isn't the same as just creating a folder, I require being able to right-click in any finder/desktop location and have a Templates selection (like New Folder) drop-down, which offers to place any of your pre-configured templates in that location.
This is useful, for example, for creating readme.md files.

A: macOS does not have that exact functionality however you can create a folder with various source documents of the type and kind you need.
If you Get Info on any document in macOS there should be a checkbox under the "General" (first) heading that is called Stationary Pad. Checking that will tell macOS to open a copy of that document, by default (usually) named "____ copy" in that type of document's default application.
So a .docx file will open in MS Word. So not the same as Ubuntu but does that give you similar functionality?

A: This functionality does not exist in macOS. There were a few free utilities to fill the gap, now discontinued. There are a few pay-ware utilities claiming to do this job. As this is quite a simple function I refused to pay anything upfront just for testing whether they do so to satisfaction.
If you want a home-brewed solution you might have to resort to automator.
If you further want this to be activated via right-click you would have to choose a "Service" to program within Automator. This is possible but very inconvenient, though. In browser or list view you will not be able to select "empty space", you have to right-click on an existing file to then have even the "Services"-submenu appear. This will then perform the programmed action, even regardless of the file being clicked. But this is a pointless exercise in an empty folder.
Further, such a service is difficult to find in an overfull and cluttered context-menu, and it allows only one file at a time to be copied. Need two files or more? Then this gets very awkward.

If I understand the wanted process correctly:

*

*create a new folder

*perform action to copy a template file from a template repository on disk into that location
(meaning: "with some flexibility", i.e. it's not always the same set of files to pre-populate such a folder)

Then I propose to use a different approach:

*

*create a ~/Library/Doc-templates folder (path is your choice)

*place your template files in that folder

*create an Automator application (start with the action  setting the path to the current location, then "Ask for Finder items" (set that path to Doc-templates; even allows multiple selections) and copy them to current path.

*compile that "Application"

*Place this in a convenient location, eg ~/Library/Applications

*Cmd-drag this application to the Finder toolbar!

Now you can create a new folder, single left-click into the Finder toolbar, get a file selection dialog to choose any combination of your templates, then get those copied to this folder.
Related
"New Item" in Finder's right-click menu
How to create a service (shown in the context menu on the URL) in Safari?
How to Customize macOS Right-click Menu
Create Context Menu Items in Mac Finder
Applescript Copy file to a new folder
Applescript copy files/folders from a source using a second source
Don't forget: If you develop any such an AppleScript/Automator solution for yourself, then put it somewhere public so that others can benefit from using it as well. And perhaps even improve the code or add capabilities.

redpajama_set_name: RedPajamaStackExchange


text:
Q: operational error 1050 Error "Table already exists" in django makemigrations Hi am getting this wherever i try to make changes to my models or trying to migrate
am using mysql and django 1.8.6
operational error 1050 Error "Table 'products_myproducts' already exists"
just every time i make migrations

class Product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    managers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="managers_product",blank=True)
    media = models.ImageField(blank=True,null=True,
            upload_to=download_media_location,
            storage=FileSystemStorage(location=settings.PROTECTED_ROOT))
    title = models.CharField(max_length=30)
    description = models.TextField(default='',blank=True)
    slug= models.SlugField(blank=True,unique=True)
    price = models.DecimalField(max_digits=60,decimal_places=2,default=9.99)
    sale_active = models.BooleanField(default=False)
    sale_price = models.DecimalField(max_digits=60,decimal_places=2,default=6.99,null=True,blank=True)
    def __str__(self):
        return self.title

also fo my products

class MyProducts(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    products = models.ManyToManyField(Product,blank=True)

    def __str__(self):
        return "%s" %(self.products.count())

    class Meta:
        verbose_name = "My Products"
        verbose_name_plural = "My Products"

A: this error causes when you delete migrations directory from your apps and not dropping the database tables.
if data on the database is important, just backup form data and then drop the database tables.
then delete all migrations directory from each app and makemigration then migrate again and import your data.


text:
Q: How do I print STDERR from a subshell? Using the answer found in How can you diff two pipelines in Bash? I have written some shell scripts that I want to compare the output of:
diff <(script1 | script2) <(script3 | script4)

However, any errors printed to STDERR in any of the scripts in the subshell pipelines disappear. How can I get them to print in my outer level script (that contains the diff)?

A: The error messages from scripts 1..4 shouldn't vanish down a black hole; you only redirected their standard output as the files given to diff.
For example, given these files:
$ cat script1
#!/bin/bash
echo $0 stdout
echo $0 stderr >&2
$ cat script2
#!/bin/bash
echo $0 stdout
cat -
echo $0 stderr >&2
$ cat script3
#!/bin/bash
echo $0 stdout
echo $0 stderr >&2
$ cat script4
#!/bin/bash
echo $0 stdout
cat -
echo $0 stderr >&2
$

The output from your command line is:
$ diff <(script1 | script2) <(script3 | script4)
./script1 stderr
./script3 stderr
./script2 stderr
./script4 stderr
1,2c1,2
< ./script2 stdout
< ./script1 stdout
---
> ./script4 stdout
> ./script3 stdout
$


text:
Q: How to prove that a derivative of a formula equals to another formula. If $u= \ln(\tan x+\tan y+\tan z)$ prove $$\sin 2x \dfrac{du}{dx} + \sin 2y  \dfrac{du}{dy} + \sin 2z   \dfrac{du}{dz}=2 $$
My answwer was like this:
$$u' =\dfrac{ 1}{\tan x+\tan y+\tan z} \cdot( \sec^2 x +\sec^2 y +\sec^2 z )$$
$$   =\dfrac{ 1}{\dfrac{\sin x}{\cos x} + \dfrac{\sin y}{\cos y} + \dfrac{\sin z}{\cos z}}\cdot(\sec^2x + \sec^2y + \sec^2z)$$
$$  =\dfrac{ \cos x+\cos y+\cos z}{\sin x+\sin y+\sin z}\cdot(\sec^2x + \sec^2y + \sec^2z)$$
$$   = \sin 2x (\dfrac{\cos x}{\sin x})+ \sin 2y (\dfrac{\cos y}{\sin y}) + \sin 2z (\dfrac{\cos z}{\sin z})\cdot( \sec^2 x +\sec^2 y +\sec^2 z )$$
$$   =\dfrac{ 2\sin x\cos x}{\sin x} +\dfrac{ 2\sin y \cos y}{\sin x} +\dfrac{ 2\sin z\cos z}{\sin z}\cdot(\sec^2x + \sec^2y + \sec^2z)$$
$$=\dfrac{ \sin 2x}{\sin x} + \dfrac{ \sin 2y}{\sin x} + \dfrac{ \sin 2z}{\sin z}\cdot(\sec^2x + \sec^2y + \sec^2z)$$
I solved until here and I got stuck. Is my answer right until now? How could I finish it to prove that it equals to 2? Sorry for the wrong codes.

A: It seems like you should just compute the relevant partials and then verify that LHS $=$ RHS.
Something like:
$$\frac{\partial u}{\partial x} = \frac{1}{\tan x + \tan y + \tan z} \cdot \sec^2x \\
\frac{\partial u}{\partial y} = \frac{1}{\tan x + \tan y + \tan z} \cdot \sec^2y \\
\frac{\partial u}{\partial z} = \frac{1}{\tan x + \tan y + \tan z} \cdot \sec^2z \\$$
The LHS then becomes
$$\frac{\sin(2x)\sec^2x + \sin(2y)\sec^2y+ \sin(2z)\sec^2z}{\tan x + \tan y + \tan z} = 2\left(\frac{ \tan x + \tan y + \tan z}{\tan x + \tan y + \tan z}\right) = 2$$
Which clearly equals the RHS.

A: We have that
$$u(x,y,z)=\ln(\tan x+\tan y+\tan z)$$
Then
$$\frac{\partial u}{\partial x}=\frac{\sec^2x}{\tan x+\tan y+\tan z}\\
\frac{\partial u}{\partial y}=\frac{\sec^2y}{\tan x+\tan y+\tan z}\\
\frac{\partial u}{\partial z}=\frac{\sec^2z}{\tan x+\tan y+\tan z}$$
Then
$$\sin(2x)\frac{\partial u}{\partial x}+\sin(2y)\frac{\partial u}{\partial y}+\sin(2z)\frac{\partial u}{\partial z}=\\
\frac{\sin(2x)\sec^2x+\sin(2y)\sec^2y+\sin(2z)\sec^2z}{\tan x+\tan y+\tan z}=\\
\frac{2\sin x\cos x\sec^2x+2\sin y\cos y\sec^2y+2\sin z\cos z\sec^2z}{\tan x+\tan y+\tan z}=\\
2\frac{\tan x+\tan y+\tan z}{\tan x+\tan y+\tan z}=2$$


text:
Q: Equivalence between blocks of BGG categories $\mathcal{O}$ which does not preserve highest weight structure Let $\mathfrak{g}$ be a finite-dimensional (complex) semisimple Lie algebra. Then we denote the BGG category for $\mathfrak{g}$ by $\mathcal{O}$ as usual. It is well-known that $\mathcal{O}$ as well as its (indecomposable) blocks are highest weight categories in the sense of the paper "Finite-dimensional algebras and highest weight categories" by Cline, Parshall and Scott.
$\text{My question:}$ Is there any example giving an equivalence $F$ between blocks which does not preserve highest weight structure? That is, $F$ does not send standard objects to standard objects. Thanks!


text:
Q: Python valueError: Couldn't parse datetime string: roving single quotes in sql I'm importing data into a table from a txt file which looks like:
 1,2019-8-24,Broccoli Chinese,17,1.57
 2,2019-8-24,chia seeds,11,0.20
 3,2019-8-24,flax seeds,25,0.20
 4,2019-8-24,sunflower seeds,26,0.30

When I print the table in the python shell I get:
(1, '2019-8-24', 'Broccoli Chinese', 17, 1.57)
(2, '2019-8-24', 'chia seeds', 11, 0.2)
(3, '2019-8-24', 'flax seeds', 25, 0.2)
(4, '2019-8-24', 'sunflower seeds', 26, 0.3)

Later on when using the table I'm getting errors like
valueError: Couldn't parse datetime string: '2019-8-24'

Are those single quotes ' ' actually in the table entry? Like in the actual table is it '2019-8-24' or is it just 2019-8-24, and when I print out the row it adds the ' '.
I'm only asking as I'm having trouble sorting out the valueError, and was wondering if it might be that single quotes ' ' had somehow been entered around dates in the table during import and might need to be removed?
EDIT
this is the actual code which does not run due to the error
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SECRET_KEY'] = 'secret'
db = SQLAlchemy(app)

from app import FoodConsumed_Tb

rows = FoodConsumed_Tb.query.all()

for row in rows:
    consumed_food_entry_to_update = FoodConsumed_Tb.query.get_or_404(row.id)
    consumed_food_entry_to_update.date_created = datetime.strptime(consumed_food_entry_to_update.date_created, "%Y-%m-%d").date()

db.session.commit()

A: My guess is that your SQL version doesn't like the month being a single digit.  You could try to scrub this data yourself using Python, e.g.
def repl(m):
    year = m.group(1)
    month = m.group(2).zfill(2)
    day = m.group(3).zfill(2)

    return year + '-' + month + '-' + day

date = '2019-8-24'
date_new = re.sub('(\d+)-(\d+)-(\d+)', repl, date)
print(date)
print(date_new)

This prints:
2019-8-24
2019-08-24

All I am doing here is to left pad the month and day components to two digits, using zeroes on the left.  I didn't bother to touch the year, assuming you don't expect any data from the Middle Ages.


text: Q: Does only prime numbers attend the form 6p+1 or 6p-1 ?? Some times before in a Numberphile video It was claimed that every prime number is close to a multiple of 6 so they deduced that every prime number can be expressed as 6p+1 or 6p-1 but if we look closely most of the numbers which are a square of prime number(e.g $11^2$,$13^2$,$17^2$ ...)also attend the form 6p+1 so can we still call it a always true statement for creating a function or how to rectify the eror in the code ??


text:
Q: Store BitSet in App Engine What is the best way to store a BitSet in App engine?  They don't allow java.util.BitSet to be a property.

A: BitSet is Serializable.  Datastore can get/put Serializable just fine.

A: Try EnumSet
"A specialized Set implementation for use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if the specified collection is also an enum set."

A: java.math.BigInteger supports common bit set operations and can be serialized to a byte array.


text:
Q: Get DaoSession en proyecto de libreria Buen dia Saludos a todos, actualmente estoy usando aprendiendo a usar greendao 3, he leido varios tutoriales y en todos los ejemplos usan greendao dentro de una app, en cambio yo estoy implementandolo en un proyecto de libreria, mi pregunta es como obtener el DaoSesssion en un proyecto de libreria, por que para hacerlo en los ejemplos hacen lo siguiente:
DaoSession daoSession = ((App) getApplication()).getDaoSession();

y en una libreria no puedo usar la función getApplication.
Gracias de antemano por sus respuestas.

A: mi solucion, aunque no se en realidad si es muy optima, fue no depender de Application, porque una app android solo puede tener una Application class declarado en el manifest de la app principal donde se ejecute la libreria. por lo tanto decidi crear una clase con el patron singleton  y de ahi llamar cuando sea necesario a DaoSession. les dejo el codigo por si les sirve, o si pueden mejorarlo.
Esta es la clase:
    public class DaoHelper {

private static volatile DaoHelper daoInstance;
private DaoSession daoSession;

private DaoHelper(Context context){
    //Prevent form the reflection api
    if(daoInstance!=null){
        throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
    }else{
        CustomDaoMaster.OpenHelper helper = new CustomDaoMaster.OpenHelper(context,
                "db",null);
        SQLiteDatabase db = helper.getWritableDatabase();
        CustomDaoMaster daoMaster = new CustomDaoMaster(db);
        daoSession = daoMaster.newSession();
    }
}

public static DaoHelper getInstance(Context context){
    //Double check locking pattern
    if(daoInstance==null){
        synchronized (DaoHelper.class){//Check for the second time.
            //if there is no instance available... create new one
            if(daoInstance==null)daoInstance = new DaoHelper(context);
        }
    }

    return daoInstance;
}

public DaoSession getDaoSession(){
    return daoSession;
}

y esta la forma de usarla:
DaoSession daoSession = DaoHelper.getInstance(context).getDaoSession();


text:
Q: How to make a parent class object referring to a child class? Like in java or C# where we can create an object like
Account obj = new SavingsAccount();

where Account is the parent class and SavingsAccount is the child class
How do I do the same thing with python?
basically I'm trying to do is this
https://repl.it/@MushfiqurRahma1/Polymorphic-Object

A: Python is dynamically typed: names refer to objects without any notion of type being involved. You just have
>>> class Account: pass
...
>>> class SavingsAccount(Account): pass
...
>>> obj = SavingsAccount()

Each object stores a reference to its own type
>>> type(obj)
<class '__main__.SavingsAccount'>

and each type has a referent to its method resolution order (MRO)
>>> type(obj).__mro__
(<class '__main__.SavingsAccount'>, <class '__main__.Account'>, <class 'object'>)

Instance attributes are not "compartmentalized" according to the class that "defines" them; each attribute simply exists on the instance itself, without reference to any particular class.
Methods exist solely in the classes themselves; when it comes time to call obj.foo(), the MRO is used to determine whose definition is used.

A: Python uses Duck typing, which means you shouldn't really care about the class in the Left side of the assignment. Just instantiate the Child class and you should already be able to use it's parent "interface" to do stuff like dynamic method calls.

A: Python is a loosely typed language. That means you don't have to specify your variable types. You could just do something like:
class Account():
    def deposit():
        pass
class SavingsAccount(Account):
    pass

obj = SavingsAccount()
obj.deposit(20)

EDIT: As chepner pointed out: Python is strongly typed, but also dynamically typed: type is associated with an object, not the name referring to an object.


text:
Q: I don't understand why my google scripts script isn't working I've recently started using google scripts for google sheets and I can't get my onEdit function to work
this is my code:
function onEdit(event) {
  var range = event.range;
  var spreadsheet = event.source;
  var r = event.source.getActiveRange();
  var activesheet = spreadsheet.getActiveSheet();
  var column = range.getColumn();
  var row = range.getRow();
  var spreadsheetname = activesheet.getName();
  var D5LOC = activesheet.getRange("D5").getValue();
  activesheet.getRange("D3").setValue(D5LOC);

  if(D5LOC == "FALSE"){
    activesheet.getRange("D6").setValue(activesheet.getRange("D5").getValue());
    if (!(column == 1)&&!(column == 2)&&event.value == "FALSE")
    {
        activesheet.getRange("D6").setValue(activesheet.getRange("D5").getValue());
        r.setValue("TRUE");

    }
  }
}

It's supposed to check every box that I've unchecked whenever a confirmation box is unchecked, however when I uncheck something it just doesn't do anything. please help

A: As far as I can tell this seems to be what your code currently boils down to:
function onEdit(e) {
  const sh = e.range.getSheet();
  const D5LOC = sh.getRange("D5").getValue();
  if (sh.getName() == 'Sheet1' && e.range.columnStart > 2 && D5LOC == "FALSE" && e.value == "FALSE") {
    sh.getRange("D3").setValue(D5LOC);
    sh.getRange("D6").setValue(D5LOC);
    e.range.setValue("TRUE")
  }
}


text:
Q: How can I activate Collapse Menu in WordPress? Inside the WordPress admin dashboard there is a button for making the left side menu collapse (to show just icons and not the icons + text on left side). How can I add jQuery so that it gets automatically collapsed once my plugin opens up. I tried this but it didn't work for me. I want to give a sort of 'full screen' option inside dashboard. Can anyone help me on this?
I tried adding this jquery script to make it work, but it didn't work for me:
<script>
jQuery(document).ready(function() {
     jQuery("#collapse-menu").click();
});

A: You have to trigger the click event. Try,
jQuery(document).ready(function() { jQuery("#collapse-menu").trigger('click'); });

Update:
Use the following code to check if menu is already folded, if not trigger click event to fold it.
jQuery(document).ready(function() {
    if ( !$(document.body).hasClass('folded') ) {
        jQuery("#collapse-menu").trigger('click');
    }
});

A: None of that worked for me. I had to use jQuery(document.body).addClass('folded');
Wordpress jQuery didnt like $(document.body).hasClass('folded'), I had to modify.
Snippet below.
   jQuery(document).ready(function() {
    if ( !jQuery(document.body).hasClass('folded') ) {
        jQuery(document.body).addClass('folded');
    }
    });


text:
Q: Как передать значение переменной JS в переменную Java в Андроид В Android проекте используется RichEditor, скриптом JS из него получаю значение которое заносится в js-переменную.
Необходимо преобразовать эту переменную с JS в Java.
Понимаю по логике что есть как минимум 2 варианта:
1) Методом Java получить доступ к js-переменной и получив ее значение присвоить java-переменной.
2) Выполнить JS скрипт в котором получаю доступ к java-переменной и передать ей значение из js-переменной.
Пробовал ScriptEngineManage - но в AndroidStudio он не работает.
Какими средствами это можно сделать в AndroidStudio?

A: Если я правильно понял, вопрос сводится к тривиальному взаимодействию JS из WebView с вашим Java-кодом.
RichEditor это простой наследник WebView. Получить что-то из JS-кода в WebView можно разными способами, приведу примеры ниже.

*

*Кастомный клиент:
Передаём значение:
webView.loadUrl("javascript:alert('Hello World')");

Получаем значение:
final class MyWebChromeClient extends WebChromeClient {

    // Также можно использовать и другой метод:
    // boolean onConsoleMessage (ConsoleMessage consoleMessage)

    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        // message = 'Hello World'
        result.confirm();
        return true;
    }
}

*

*JavascriptInterface
Передаём значение:
webView.addJavascriptInterface(this, "android");
webView.loadUrl("javascript:android.onData('Hello World!')");

Получаем значение:
@JavascriptInterface
public void onData(String value) {
    // value = 'Hello World'
}

Вопрос на enSO


text:
Q: Angular ng-file-upload delete Trying to figure best approach to be able to delete a file when using ng-file-upload. I got my list of files with a list. My html is:

Files:

{{f.name}} {{f.$error}} {{f.$errorParam}}

In my controller, I have:
$scope.$watch('files', function () {
    $scope.upload($scope.files);
});
$scope.$watch('file', function () {
    if ($scope.file != null) {
        $scope.files = [$scope.file];
    }
});
$scope.log = '';

$scope.upload = function (files) {
    if (files && files.length) {
        for (var i = 0; i < files.length; i++) {
          var file = files[i];

          if (!file.$error) {

            Upload.upload({
                url: (serviceBase + 'api/ppt/docs/upload/multi?transId=' + [$scope.transId]),
                data: {
                  username: $scope.username,
                  file: file,
                  filename: file.name
                }
            }).progress(function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                $scope.log = 'progress: ' + progressPercentage + '% ' +
                            evt.config.data.file.name + '\n' + $scope.log;
            }).success(function (data, status, headers, config) {
                $timeout(function() {
                    $scope.log = 'file: ' + config.data.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
                });
            }).error(function(data, status, headers, config) {

                var errors = [];
                $scope.errors = data;

                for (var i=0; i<$scope.errors.length; i++)
                {
                    errors.push($scope.errors[i].errMsg);
                }

                $scope.message = "Error uploading files due to: " + errors.join(' ');
            });
          }
        }
    }
};

I see some examples in the documentation, but not seeing best ways to implement, especially if I want individual deletes/remove for each file uploaded rather than just all.
Thanks much.

A: I suppose the straightforward approach will do here.

*

*Add a deleteFile handler to your scope taking array index of the file being deleted.

*Add a link/button/handle for each file to delete it upon clicking and set it's attribute ng-click="deleteFile($index). $index is created by ng-repeat.

*In your deleteFile handler call the backend to delete the file and upon success splice the files array to remove the deleted entry.

HTML:

     {{f.name}} {{f.$error}} {{f.$errorParam}} ×

JS:
$scope.deleteFile = function(idx) {
     var file = $scope.files[idx];
     if (file.isUploaded) {
          $http.delete('/api/files/'+file.id).then(function(response){
               if (response.status == 200) {
                    $scope.files.splice(idx, 1);
               }
         });
      } else {
           $scope.files.splice(idx, 1);
      }
}


text:
Q: How to change Windows color theme? My goal is to make a script to apply a certain bundle of settings all at once to my computer if something specific happens. I am currently stuck, at how to change the Windows color theme. I could figure out how to change the theme from light to dark and reverse using this code:
import subprocess

command = ['reg.exe', 'add', 'HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize',
           '/v', 'AppsUseLightTheme', '/t', 'REG_DWORD', '/d', '0', '/f']
subprocess.run(command)

This code works, and I can use it to change from light to dark theme. But there are also other settings in this settingsboundle:

I want to be able to change color accent, like in this image there is blue selected, to another color (for example red). I could not find any way to do this, nor how to universally change Windows settings.
Do you know any way of changing the Windows color accent using Python?
Do you know of any way to change any Windows setting (such as the background, mouse cursor size, font, font size), perhaps is there even a module to it which can be used like in the following mock example:
import example

setting2 = windows.CURSOR_SIZE
setting2v = 15

example.change.setting(setting2, setting2v)
print("succesfully changed setting " + str(setting2) + " to value " + str(setting2v))

A: You are looking for running PowerShell commands using Python.
First, find out the needed command, there is probably a command for every action you want in Windows.
Then, you can do it as follows:
import subprocess

hideBar = "&{$p='HKCU:SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StuckRects3';$v=(Get-ItemProperty -Path $p).Settings;$v[8]=3;&Set-ItemProperty -Path $p -Name Settings -Value $v;&Stop-Process -f -ProcessName explorer}"

def run(cmd):
    subprocess.run(["powershell", "-Command", cmd])

run(hideBar)

Reference: How to change a certain windows setting using python?

A: There's no Python module that makes it that easy to tweak Windows UI settings programmatically. But you already have a working example of using reg.exe from Python. You can use your working example as a basis for modifying other registry settings. Now it's just a matter of locating the appropriate registry keys for the settings you want to change. You can do this using Google, example search query: registry key for personalize accent color.
Here's a StackExchange post going over the keys for many Personalize settings:
https://superuser.com/a/1395560/54746


text:
Q: Struts 2.0 Download pop up not appearing in browser I am application is based on struts and in one of the module I am generating reports in pdf and excel format .The reports gets generated in system directory  but download pop up dosen't appear on browser .
This is my .xml mapping of action
<action name="report" class="reportAction" method="generateReport">
        <result name="success" type="stream">
            <param name="contentType">application/octet-stream</param>
            <param name="inputName">fileInputStream</param>
            <param name="contentDisposition">attachment;filename=${filename}</param>
            <param name="bufferSize">1024</param>
        </result>
        <result name="error">
        </result>
    </action>

this is my cal to action from jsp :-
function fetchReport()
{
//alert("I am here");
        $.ajax({
               type : "POST",
               url  : "report.action",
               data : jQuery("#parameterGrid").serialize(),
               async : false,
            success : function(dataJSP) {
                //alert("Hi");
                //alert(dataJSP);
                /* jQuery("#showReportDIV").load("Please wait...").html(
                        dataJSP); */

                return true;
            }
        });
    }

Now I have changed my button on whose click event I generate the report to :-
<sj:submit button="true"
                    theme="simple" onclick= "fetchReport();" key="Generate Report" />

now the pop up appears but a flat file is download ,I have to browse to open it either in excel or pdf


text:
Q: How to split this url accept multiple sms gateways I am currently making a script that will be able to send sms via the http api of multiple sms gateways.But my problem is how to extract the api details from the url.
Here is what I am trying to do :
A simple html form where a user can paste the API details given by an sms gateway. eg
http://www.mysmsgateway.com/s/smsapi.php?username=xxx&password=xxx&sender=Mybrand&recipient=234808xxxxxxx,2348030000000&message=yourmessagehere
The url is recieved via  php, and the api details are extracted, for sending sms
The  problem I have is that the HTTP API url format of these gateways are always slightly different from each other.
Lokk at the one below
http://www.estoresms.com/smsapi.php?username=user&password=1234&sender=@@sender@@&recipient=@@recipient@@&message=@@message@@&
Here is the code I'm currently writing
**
   <?php
    if(isset($_POST['url']))
    {

     $url=$_POST['url'];
     $splt=explode('?',$url);
     //var_dump($splt);
     $result=file_get_contents($url);
     echo($result);

     }
    ?>
    <form action="<?php  echo $_SERVER['PHP_SELF']; ?> " method="POST">
    <input type="text" name="url"/>
    <input type="submit" value="submit"/>

    </form>**

I know that the html is not yet complete


text:
Q: derivatives - maximum number of intersections between a polynomial and e^x I am puzzled at the following question: Let p be a polynomial of degree n and let $$E = \{x | e^x = p(x)\}.$$ Prove that the cardinality $|E|$ of E satisfies $|E| \le n+1$.
Known The hint in the question says to use the Generalized Mean Value Theorem, which states: Let $f$ and $g$ be continuous functions on $[a,b]$ and suppose that $f$ and $g$ are differentiable at least on $(a,b)$, with $g'(x) \not= 0$ on $(a,b)$. Then $\exists c \in (a,b)$ such that $$\frac{f(b)-f(a)}{g(b)-g(a)}=\frac{f'(c)}{g'(c)}.$$
Where I am confused I am confused as to were to apply the Mean Value Theorem (i.e. - which functions to pick for $f$ and $g$). I want to use a counting argument, but that is not working either. Any help, hints, guidance, etc. are well appreciated.

A: $f(x)=e^x-p(x)$ is infinitely differentiable, and $f^{(n+1)}(x)= e^x\,$ since the $(n+1)^{th}$ derivative of an $n^{th}$ degree polynomial is identically zero $p^{(n+1)}(x) \equiv 0\,$.
If $\,|E| \ge n+2\,$, that would mean $f(x)$ had at least $\,n+2\,$ distinct zeros. Then, as a consequence of Rolle's theorem, $\,f^{(n+1)}(x)\,$ would need to have at least one real root  (see here for example). But $\,f^{(n+1)}(x)= e^x \gt 0\,$, therefore $\,f(x)\,$ can have at most $\,n+1\,$ distinct roots $\iff |E| \le n+1\,$.

A: Hint: Don't use the GMVT; the MVT will do. Apply it to $e^x-p(x)$ and use induction as @stochasticboy321 suggests.


text:
Q: Apache, importing a python module with mutex and ladon, script hang i have a strange behaviour of a python script running through Apache/mod_wsgi/Ladon, when running it from a python shell, every thing is fine, on one machine everything is fine, but on the other the same script hang and it seems that it is indefinitely doing or waiting something: that is opening the page from 192.168.xxx.xxx/ws/ never end (browser are loading again and again, turning round, ie saying ). I can not find what happen, logging thing to the apache log show me nothing as the script imported seems to never end when used through apache/ladon. (and as both machines are configured the same way, i have plain headache with that :/)
as the script load some data from the filesystem and database, can the hanging be from locking these ressources indefinitely?
can i wrap the module that hang inside something like the lines below to be sure there is nothing locking? actually i have tried to do so, and it change nothing at all, but and this is my first question, is it right to write it like this (as i am a bit confued but different mutex processes)?
[...]
from multiprocessing import Lock
mutex = Lock()

mutex.acquire()
import MyHangingModule
mutex.release()
[...]

is there any case where when serving a page from apache may end with an infinite time out? that is the python mod_wsgi/ladon script is killed by apache or ladon while something is still waiting for a reply from the killed? as when shutting down the server i get some:
[Tue Jul 09 16:07:47 2013] [warn] child process 1676 still did not exit, sending a SIGTERM
[Tue Jul 09 16:07:49 2013] [warn] child process 1676 still did not exit, sending a SIGTERM
[Tue Jul 09 16:07:51 2013] [warn] child process 1676 still did not exit, sending a SIGTERM
[Tue Jul 09 16:07:53 2013] [error] child process 1676 still did not exit, sending a SIGKILL
[Tue Jul 09 16:07:54 2013] [notice] caught SIGTERM, shutting down

(by searching about pid, through mod_status, it is actually the handing script staying in W mode)
EDIT: about wsgi, i have nothing Inside the wsgi.conf, everything is commented # actually, I install it from the default Debian installation. Is there something that i should look? or that I obviously miss?
for the other, it is also default Debian (actually no change inside config file, but specifically install apache2-mpm-worker):
# worker MPM
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

Output of /usr/sbin/apache2ctl -l
Compiled in modules:
  core.c
  mod_log_config.c
  mod_logio.c
  worker.c
  http_core.c
  mod_so.c

about mod for wsgi (without adding WSGIApplicationGroup %{GLOBAL}) to wsgi.conf):

mod_wsgi.process_group = ['']
mod_wsgi.application_group = ['myserver|/mycfg'] # mycfg is actually the name of the python script while i have replaced the server name for posting here
wsgi.multithread = [True]

about mod for wsgi (after adding WSGIApplicationGroup %{GLOBAL}) to wsgi.conf) (thus very slow for my others scripts):

mod_wsgi.process_group = ['']
mod_wsgi.application_group = ['']
wsgi.multithread = [True]

well, if it could help, here is the log part for a sessing using a webservice that may be slow :
(actually i would have liked that the externalDataLoader.py loaded: 0:00:00.394606 (21941 entries loaded) was shared by every one and then occurs only one. Also i have deactivate all others python handled... can this be that the twomod_wsgi (pid=xxxxx): Attach interpreter ''`can then be using some ressources and waiting indefinetly without any response and thus making the whole server and others WS query to end with the "child process not exit" ?
[Wed Jul 24 10:49:20 2013] [notice] caught SIGTERM, shutting down
[Wed Jul 24 10:49:21 2013] [info] mod_wsgi (pid=11199): Initializing Python.
[Wed Jul 24 10:49:21 2013] [notice] Apache/2.2.16 (Debian) mod_wsgi/3.3 Python/2.6.6 configured -- resuming normal operations
[Wed Jul 24 10:49:21 2013] [info] Server built: Mar  3 2013 11:36:06
[Wed Jul 24 10:49:21 2013] [info] mod_wsgi (pid=11203): Initializing Python.
[Wed Jul 24 10:49:21 2013] [info] mod_wsgi (pid=11199): Attach interpreter ''.
[Wed Jul 24 10:49:21 2013] [info] mod_wsgi (pid=11203): Attach interpreter ''.
[Wed Jul 24 10:49:39 2013] [info] [client 192.168.1.130] mod_wsgi (pid=11199, process='', application=''): Loading WSGI script '/var/www/mywebserver/ws/wshandler.py'., referer: http://192.168.1.5/demo/search.html
[Wed Jul 24 10:49:40 2013] [error] externalDataLoader.py loaded: 0:00:00.394606 (21941 entries loaded)
[Wed Jul 24 10:49:42 2013] [error] WSforSearchInsideExternalData. loaded: 0:00:00.000032.
[Wed Jul 24 10:49:42 2013] [error] searched [test] in [External1]: 0:00:00.026233
[Wed Jul 24 10:49:42 2013] [error] searched [test] in [External2]: 0:00:00.067869
[Wed Jul 24 10:49:43 2013] [error] searched [test] in [External3]: 0:00:00.104222
[Wed Jul 24 10:49:43 2013] [error] searching done for [test]: 0:00:00.104222
[Wed Jul 24 10:49:59 2013] [info] [client 192.168.1.130] mod_wsgi (pid=11203, process='', application=''): Loading WSGI script '/var/www/mywebserver/ws/wshandler.py'., referer: http://192.168.1.5/demo/search.html
[Wed Jul 24 10:50:00 2013] [error] externalDataLoader.py loaded: 0:00:00.384349 (21941 entries loaded)
[Wed Jul 24 10:50:02 2013] [error] WSforSearchInsideExternalData. loaded: 0:00:00.000033.
[Wed Jul 24 10:50:02 2013] [error] searched [abjg] in [External1]: 0:00:00.026000
[Wed Jul 24 10:50:02 2013] [error] searched [abjg] in [External2]: 0:00:00.066215
[Wed Jul 24 10:50:02 2013] [error] searched [abjg] in [External3]: 0:00:00.100293
[Wed Jul 24 10:50:02 2013] [error] searching done for [abjg]: 0:00:00.100293
[Wed Jul 24 10:50:40 2013] [error] searched [abjg] in [External1]: 0:00:00.001513
[Wed Jul 24 10:50:40 2013] [error] searched [abjg] in [External2]: 0:00:00.080266
[Wed Jul 24 10:50:40 2013] [error] searched [abjg] in [External3]: 0:00:00.119280
[Wed Jul 24 10:50:40 2013] [error] searching done for [abjg]: 0:00:00.119280
[Wed Jul 24 10:50:48 2013] [error] searched [abje] in [External1]: 0:00:00.001491
[Wed Jul 24 10:50:48 2013] [error] searched [abje] in [External2]: 0:00:00.079586
[Wed Jul 24 10:50:48 2013] [error] searched [abje] in [External3]: 0:00:00.123212
[Wed Jul 24 10:50:48 2013] [error] searching done for [abje]: 0:00:00.123212

A: See and try the solution described in:

*

*http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Python_Simplified_GIL_State_API
You are likely using an extension module which will not work in a sub interpreter.
In short, add to the Apache configuration:
WSGIApplicationGroup %{GLOBAL}


text:
Q: Output files with mixed wildcards I'm stuck on how to do this with Snakemake.
First, say my "all" rule is:
rule all:
    input: "SA.txt", "SA_T1.txt", "SA_T2.txt",
        "SB.txt", "SB_T1.txt", "SB_T2.txt", "SB_T3.txt"

Notice that SA has two _T# files while SB has three such files, a crucial element of this.
Now I want to write a rule like this to generate these files:
rule X:
    output: N="S{X}.txt", T="S{X}_T{Y}.txt"
    (etc.)

But SnakeMake requires that both output templates have the same wildcards, which these don't.  Further, even if SnakeMake could handle the multiple wildcards, it would presumably want to find a single filename match for the S{X}_T{Y}.txt template, but I want that to match ALL files where {X} matches the first template's {X}, i.e. I want output.T to be a list, not a single file.  So it would seem the way to do it is:
def myExpand(T, wildcards):
    T = T.replace("{X}", wildcards.X)
    T = [T.replace("{Y}", S) for S in theXYs[wildcards.X]]
    return T

rule X:
    output: N="S{X}.txt", T=lambda wildcards: myExpand("S{X}_T{Y}.txt", wildcards)
    (etc.)

But I can't do this, because a lambda function cannot be used in an output section.
How do I do it?
It seems to me this argues for supporting lambda functions on output statements, providing a wildcards dictionary filled with values from already-parsed sections of the output statement.

Additions responding to comments:
The value of wildcard Y is needed because other rules have inputs for those files that have the wildcard Y.
My rule knows the different values for Y (and X) that it needs to work with from data read from a database into python dictionaries.
There are many values for X, and from 2 to 6 values of Y for each value of X.  I don't think it makes sense to use separate rules for each value of X. However, I might be wrong as I recently learned that one can put a rule inside a loop, and create multiple rules.
More info about the workflow: I am combining somatic variant VCF files for several tumor samples from one person together into a single VCF file, and doing it such that for each called variant in any one tumor, all tumors not calling that variant are analyzed to determine read depth at the variant, which is included in the merged VCF file.
The full process involves about 14 steps, which could perhaps be as many as 14 rules.  I actually didn't want to use 14 rules, but preferred to just do it all in one rule.
However, I now think the solution is to indeed use lots of separate rules.  I was avoiding this partly because of the large number of unnecessary intermediate files, but actually, these exist anyway, temporarily, within a single large rule.  With multiple rules I can mark them temp() so Snakemake will delete them at the end.
For the sake of fleshing out this discussion, which I believe is a legitimate one, let's assume a simple situation that might arise.  Say that for each of a number of persons, you have N (>=2) tumor VCF files, as I do, and that you want to write a rule that will produce N+1 output files, one output file per tumor plus one more file that is associated with the person.  Use wildcard X for person ID and wildcard Y for tumor ID within person X.  Say that the operation is to put all variants present in ALL tumor VCF files into the person output VCF file, and all OTHER variants into the corresponding tumor output files for the tumors in which they appear.  Say a single program generates all N+1 files from the N input files.  How do you write the rule?
You want this:
rule:
    output: COMMON="{X}.common.vcf", INDIV="{X}.{Y}.indiv.vcf"
    input: "{X}.{Y}.vcf"
    shell: """
        getCommonAndIndividualVariants --inputs {input} \
        --common {output.COMMON} --indiv {output.INDIV}
        """

But that violates the rules for output wildcards.
The way I did it, which is less than satisfactory, but works, is to use two rules, the first of which has the output template with more wildcards, and the second the template with fewer wildcards, and having the second rule create temporary output files which are renamed to the final name by the first rule:
rule A:
    output: "{X}.{Y}.indiv.vcf"
    input: "{X}.common.vcf"
    run: "for infile in {input}: os.system('mv '+infile+'.tmp'+' '+infile)"

rule B:
    output: "{X}.common.vcf"
    input: lambda wildcards: \
        expand("{X}.{Y}.vcf", **wildcards, Y=getYfromDB(wildcards["X"]))
    params: OUT=lambda wildcards: \
        expand("{X}.{Y}.indiv.vcf.tmp", Y=getYfromDB(wildcards["X"]))
    shell: """
        getCommonAndIndividualVariants --inputs {input} \
        --common {output} --indiv {params.OUT}
        """

A: I do not know how the rest of your workflow looks, and what the best solution is is context-dependent.
1
What about splitting up the rule into two, one creating  "SA.txt", "SA_T1.txt", "SA_T2.txt" and another "SB.txt", "SB_T1.txt", "SB_T2.txt", "SB_T3.txt"?
2
Another possibility is to only have the {X} files in the output-directive, but have the rule create the other files, even though they are not in the output-directive. This does not work if the {Y} files are part of the DAG.
3 (Best solution?)
A third and potentially the best solution might be to have aggregated wildcards in the X rule and the rule that requires the output from X.
Then the solution would be
rule X:
    output: N="S{X_prime}.txt", T="S{Y_prime}.txt"

The rule which requires these files can look like:
rule all:
    input:
        expand("S{X_prime}", X_prime="A_T1 A_T2".split()),
        expand("S{Y_prime}", Y_prime="B_T1 B_T2 B_T3".split())

If this does not meet your requirements we can discuss it further :)
Ps. You might need to use wildcard_constraints to disambiguate the outputs of rule X.
list_of_all_valid_X_prime_values = "A_T1 A_T2".split()
list_of_all_valid_Y_prime_values = "B_T1 B_T2 B_T3".split()

wildcard_constraints:
    X_prime = "({})".format("|".join(list_of_all_valid_X_prime_values))
    Y_prime = "({})".format("|".join(list_of_all_valid_Y_prime_values))

rule all:
    ...

A: My understanding is that snakemake works by taking steps that look as follows:

*

*Look at the name of a file it is asked to generate.

*Find the rule that has a matching pattern in its output.

*Infer the values of the wildcards from the above match.

*Use the wildcards to determine what the name of the inputs of the chosen rule should be.

Your rule can generate its output without needing an input, so the problem of inferring the value of wildcard Y is not evident.
How does your rule know how many different values for Y it needs to work with ?
If you find a way to determine the values for Y just knowing the value for X and predefined "python-level" functions and variables, then there may be a way to have Y as an internal variable of your rule, and not a wildcard.
In this case, the workflow could be driven only by files S{X}.txt. The S{X}_T{Y}.txt would just be a byproduct of the execution of the rule, not in its explicit output.


text:
Q: Laravel 5 one to many eloquent relationship I have the following database table structure
users
  id
  name

articles
  id
  about_id
  author_id
  text

And the following users :
1 Alex
2 John

And 2 articles one written by (author_id) John(2) about (about_id)
Alex(1) and other written by (author_id) Alex(1) about (about_id)
John(2).

My question is how should does the model of articles table named "Article", should look like for the relationships mentioned below.
I would like to access the article object for retrieving author object like :
$article = Article::find(1);
$article->author;

And to retrieve the object of the user that the article is about like :
$article = Article::find(1);
$article->about;

I have to mention that i have only two models : Article and User.

A: Your Article model should look like this

class Article extends Model {
    public function author() {
        return $this->belongsTo("App\User", 'author_id');
    }

    public function about() {
        return $this->belongsTo("App\User", 'about_id');
    }
}

A: You can also use hasMany
class Article extends Model {
    public function author() {
        return $this->hasMany("App\Author", 'author_id', 'id');
    }

    public function about() {
        return $this->hasMany("App\About", 'author_id', 'id');
    }
}

A: use App\User;
use App\Article;

class Article extends Model {

    public function author() {
        return $this->belongsTo(Article::class, 'author_id');
    }

    public function about() {
        return $this->belongsTo(User::class, 'about_id');
    }
}


text:
Q: Justification of the $U(1)$ gauge for electromagnetism? Why should we expect or require that there is a $U(1)$-gauge symmetry in the theory of a charged particle (such as QED), namely that its physical properties should not change under local changes of the wavefunction $\psi(x) \rightarrow \psi(x) e^{i \alpha(x)}$? For example, demanding this $U(1)$-symmetry be satisfied justifies the usage of a covariant derivative $D_\mu(x) = \partial_\mu + i q B_\mu(x)$, while $B_\mu$ transforms by $B_\mu(x) \rightarrow B_\mu(x) - \frac1q \partial_\mu \alpha(x)$. Letting $B_\mu$ be the vector potential $A_\mu$ in electromagnetism allows an interaction/coupling between the fermion wavefunction $\psi$ and electromagnetism, although I don't understand why that is indeed the correct thing to do. I heard that this is precisely called the minimal coupling, but I don't understand the exact details.
In summary I have two questions:
Question 1. What is the physical reason why we should require a $U(1)$-gauge symmetry to be present for the wavefunction of a charged fermion?
Question 2. After we impose this gauge symmetry on the Dirac Lagrangian, what is the physical justification that we should let the connection 1-form term to be precisely the vector potential $A_\mu$, and not other terms from electromagnetism (say, $F_{\mu\nu}A^\nu$)?
There are (many) other questions on Physics SE that address a similar concern (such as this and this), but not exactly this.

A: Ultimately, the physical reason for doing this is that it works. There's a fairly natural line of reasoning which leads to this procedure - that's not a proof, because proofs don't exist in physics, but it's suggestive motivation. I'll run through this reasoning, breaking up the narrative with some elaboration that may be helpful.

If you impose a local symmetry under the action of a Lie group $G$, then you are immediately led to the need for a connection, which can be represented by a one-form $\mathbf A$ which takes its values in the Lie algebra $\frak g$ associated to $G$, and a covariant derivative $D = \partial + A$.

Let $\Psi : \mathbb R^3\mapsto \mathbb C^n$ be an $n$-component wavefunction.  We choose a basis $\{\hat e_1,\hat e_2,\ldots,\hat e_n\}$ for $\mathbb C^n$ and express our wavefunction in component form $\Psi = \psi^a \hat e_a$.  If we allow the basis to be position-dependent, then differentiation of the wavefunction yields
$$\partial_{\color{red}{\mu}} \Psi = (\partial_\color{red}{\mu} \psi^a)\hat e_a + \psi^a\partial_\color{red}{\mu}(\hat e_a)$$
where I use the red, Greek subscript to denote the spatial index and Latin super/subscripts to denote the $\mathbb C^n$ indices. The expression $\partial_\color{red}{\mu}(\hat e_a)$ will be some element of $\mathbb C^n$, so we can express it in the local basis as $\partial_\color{red}{\mu}(\hat e_a) = {A_\color{red}{\mu}}^b_{\ \ a} \hat e_b$.  Plugging this back in and relabeling indices yields
$$\partial_\color{red}{\mu} \Psi = (\partial_\color{red}{\mu} \psi^a + {A_\color{red}{\mu}}^a_{\ \ b} \psi^b)\hat e_a$$
This motivates the definition $D_\color{red}{\mu} \equiv \partial_\color{red}{\mu} + A_\color{red}{\mu}$ (where, for each $\color{red}{\mu}$, $A_\color{red}{\mu}$ is interpreted as an $n\times n$ complex matrix), so $\partial_\color{red}{\mu} \Psi = (D_\color{red}{\mu}\psi)^a \hat e_a$.  Under change of basis via some $\Omega \in G$, $\psi^a \mapsto \Omega^a_{\ \ b} \psi^b$ and $\hat e_a \mapsto (\Omega^{-1})^b_{\ \ a} \hat e_b$ to preserve the value of $\Psi$ itself.   Note: From here on, I'll drop the spatial index, because it just sits there and comes along for the ride.  You can always put it back in if you want.

Exercise for the reader: Using the definition $\partial(\hat e_a) = A^b_{\ \ a}\hat e_b$, show that under change of basis, $A \mapsto \Omega(A + \partial) \Omega^{-1}$.  Further, argue that if $\Omega = e^\theta$ for some $\theta \in \frak{g}$, consistency requires that $A \in \frak{g}$.

We now ask whether this connection has any physical meaning.  If it can be uniformly set to zero by appropriate change of gauge, then we can perform all of our calculations in that gauge; since all gauges are physically equivalent, this implies that $A$ cannot manifest any physical effects. Setting the connection to zero means that $\Omega(A + \partial)\Omega^{-1} = 0 \iff A = -(\partial \Omega^{-1})\Omega = \Omega^{-1} \partial \Omega$ for some $\Omega \in G$.

Exercise for the reader: Show that if $A_\mu = \Omega^{-1} \partial_\mu \Omega$, then
$$(dA)_{\mu\nu} \equiv \partial_\mu A_\nu - \partial_\nu A_\mu = -[A_\mu,A_\nu]$$
so the $\frak{g}$-valued(!) 2-form $F$ with components $F_{\mu\nu} \equiv (dA)_{\mu\nu} + [A_\mu,A_\nu] = 0$.  Furthermore, show that under change of gauge, $F \mapsto \Omega F \Omega^{-1}$.

That the connection can be set to zero implies that $F$ (called the curvature form of $A$) vanishes.  The reverse is also true (at least locally), but that's considerably harder to show.
If $F$ doesn't vanish, then we need some way to determine what it should be. One way to do this is to make a scalar (density) out of $\mathbf F$ and use it as a Lagrangian density. Recall that $F$ has two spatial indices which need to be taken care of.  Generically$^\dagger$, the simplest scalar one can make out of $\mathbf F$ is $-\frac{1}{4}\operatorname{Tr}(F^2)$, where $F^2=F_{\mu\nu}F^{\mu\nu}$ and the numerical factor is added for conventional reasons.

Note that $g^{\mu\nu}F_{\mu\nu}$ vanishes identically, so that's no good.  However, $F^2 \equiv g^{\mu\alpha}g^{\nu \beta} F_{\mu \nu} F_{\alpha \beta}$ does not.  But we must be careful - each $F_{\mu\nu}$ is a matrix.  Written properly with all of the relevant indices,
$$F^2 = g^{\mu\alpha}g^{\nu\beta}\left( F^a_{\ \ b}\right)_{\mu\nu} \left( F^b_{\ \ c}\right)_{\alpha\beta} = (F^2)^a_{\ \ c}$$
We still need to get rid of those vector space indices, so we can just trace over them to get a real scalar:
$$\operatorname{Tr}(F^2) = (F^2)^a_{\ \ a} = g^{\mu\alpha}g^{\nu\beta}\left( F^a_{\ \ b}\right)_{\mu\nu} \left( F^b_{\ \ a}\right)_{\alpha\beta}$$

Demanding that the Lagrangian be gauge-invariant rules out terms like $A_\mu A^\mu$, which would give the $A$ fields a mass; as a result, all of the auxiliary fields obtained in this way are massless.
At the end of the day, the coupling to the matter in the theory arises naturally from the presence of the connection in the covariant derivative. The dynamics arise from using the simplest gauge-invariant scalar as a Lagrangian density.

Question 1. What is the physical reason why we should require a $U(1)$-gauge symmetry to be present for the wavefunction of a charged fermion?

There's no particular reason why we should - other than that if we do, then electromagnetism falls into our lap. If we repeat the procedure with different gauge groups, we arrive at different theories, some of which seem to be manifested in reality and others which do not.

Question 2. After we impose this gauge symmetry on the Dirac Lagrangian, what is the physical justification that we should let the connection 1-form term to be precisely the vector potential $A_\mu$, and not other terms from electromagnetism (say, $F_{\mu\nu}A^\nu$)?

I think are imagining that $U(1)$ symmetry is imposed and subsequently married to electromagnetism, but that's not quite right.  $U(1)$ symmetry is imposed and then becomes electromagnetism.  It's not that we find ourselves searching for a connection 1-form and decide that it should be the vector potential; it's that if you follow the procedure above, then the connection 1-form automatically obeys the Maxwell equations and exerts a Lorentz force on charged matter.
In other words, you can call it what you like but the imposition of a local $U(1)$ symmetry requires the introduction of an auxiliary field which behaves exactly like the electromagnetic 4-potential and has exactly the same effect on matter.  If it walks like a duck and quacks like a duck...

$^\dagger$A fun exception to this rule is if the dimension of the underlying space and the dimension of the vector space on which $G$ acts are the same; then the Greek and Latin indices run over precisely the same values.  This is true when we consider $d$-dimensional spacetime and its $d$-dimensional tangent spaces, for example.
In that case, we can contract one Latin index with one Greek index in the expression $(F^a_{\ \ b})_{\mu\nu}$, and then contract the result with the metric.  The only non-trivial way to do this is
$$ g^{\mu \nu} (F^a_{\ \ \mu})_{a \nu}$$
This term is linear in $F$ rather than quadratic, and appears in general relativity; the connection is the Christoffel connection, $F$ is the Riemann curvature tensor, and the above-obtained scalar is the Ricci scalar.


text:
Q: Error message related to package list being shown frequently on Ubuntu 20.04 To the best of my knowledge these errors are because of either 2 gnome-shell extensions or virtualbox. I have removed both now but still getting the problems maybe they have corrupted system configuration. Is there any way to fix it?
Now I don't know what's going but I haven't received a single snap update for quite few days.

A: You have to remove problematic local software lists and install updates by using commands below:
sudo rm -v /var/lib/dpkg/lock* /var/cache/apt/archives/lock
sudo rm -vrf /var/lib/apt/lists/*
sudo apt-get update

sudo apt-get dist-upgrade
sudo apt-get install -f -y
sudo dpkg --configure -a

To update Snaps use
sudo snap refresh


text:
Q: Colon in a lambda function? I don't understand the role of the colon in the following lambda expression:
myFunction :: [Int] -> [Int]
myFunction li = foldr (\x acc -> if x < 10 then x : acc else acc) [last li] li

I'm used to seeing the colon for recursive actions, however it looks like this colon is effectively saying prepend to current accumulator list, is that right?

A: : is a data constructor. It prepends a value of type a to an existing (possibly empty) list of type [a].
let x = 1 : [2,3,4]  -- x == [1,2,3,4]

You can picture the list type constructor as being defined like this:
data [] a = [] | a : [] a     -- : as an infix operator
data [] a = [] | (:) a ([] a) -- : in prefix positino

which might read more easily as
-- [] == List
-- (:) == Cons
data List a = EmptyList | Cons a (List a)

By "recursive action", I assume you mean you see it being used in a pattern matching situation like
head (a:as) = a

This is not unique to (:); pattern matching can be done with any data constructor.


text:
Q: How to implement a function using channels There is a function that is running in goroutine:
func (c *controlUC) WebhookPool() {
    for {
        if len(c.webhookPool) == 0 {
            continue
        }
        for i := 0; i < len(c.webhookPool); i++ {
            if !c.webhookPool[i].LastSentTime.IsZero() && time.Now().Before(c.webhookPool[i].LastSentTime.Add(GetDelayBySentCount(c.webhookPool[i].SendCount))) {
                continue
            }
            var headers = make(map[string]string)
            headers["Content-type"] = "application/json"
            _, statusCode, err := c.fhttpClient.Request("POST", c.webhookPool[i].Path, c.webhookPool[i].Body, nil, headers)
            if err != nil {
                c.logger.Error(err)
                return
            }
            if statusCode != 200 {
                if c.webhookPool[i].SendCount >= 2 {
                    c.webhookPool = append(c.webhookPool[:i], c.webhookPool[i+1:]...)
                    i--
                    continue
                }
                c.webhookPool[i].SendCount++
            } else {
                c.webhookPool = append(c.webhookPool[:i], c.webhookPool[i+1:]...)
                i--
                continue
            }
            c.webhookPool[i].LastSentTime = time.Now()
        }
    }
}
// webhookPool []models.WebhookPoolElem
type WebhookPoolElem struct {
    SendCount    int
    LastSentTime time.Time
    Path         string
    Body         []byte
}

The webhookPoolElem element is added to c.webhookpool, after which a request is sent to the server (the path is taken from WebhookPoolElem.path). If the server returned a non - 200 200, then I need to send the request again, after X seconds (taken from GetDelayBySentCount(), depending on SendCount returns different times). The number of attempts is limited (c.webhookpool[i].SendCount >= 2)
But maybe this function needs to be done through channels? If so, how?

A: Lets say controlUC receiver has a field webhookPool chan WebhookPoolElem and init as webhookPool: make(chan WebhookPoolElem, n) with n as buffer.
You can receive elements and more or less replace c.webhookPool[i] to elem. Rewrite like this:
func (c *controlUC) WebhookPool() {
    for {
        elem, open := <-c.webhookPool
        if !open {
            return
        }

        if !elem.LastSentTime.IsZero() && time.Now().Before(elem.LastSentTime.Add(GetDelayBySentCount(elem.SendCount))) {
            continue
        }
        // I omit http request
        if statusCode != 200 {
            if elem.SendCount >= 2 {
                // drop message from channel, no need to do anything
                continue
            }
            elem.SendCount++
            elem.LastSentTime = time.Now()
            c.webhookPool <- elem // enqueue again
        }
}

I suggest buffered channel so the last send c.webhookPool <- elem does not block, but it's best if you place the send in a select so if the send can not proceed regardless of the buffer, the goroutine doesn't block:
select {
    case c.webhookPool <- elem:
        // success
    default:
        // can not send
}


text:
Q: Titanium Admob keeps on checking for new ads I am using titanium admob module, found here
My app has several pages, so i load ads on several of them.
My problem is that after a few visits, each of the ads doesn't seem to get garbage collected or killed, so in my output I can see a lot of info statements indicating the app is checking for ads. These are not happening every 60 seconds, much closer to every 5 seconds.
I'm assuming this is going to cause some degredation/battery use while the app runs.
Does anybody know how I'm meant to "kill" the refresh of an admob ad? If it is specific to titanium, great. If it is specific to android, well, let me know the method calls and the concept and I'll see if i can translate that across to the js titanium code!
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   APSAnalyticsService: Analytics Service Started
[INFO] :   APSAnalyticsService: Stopping Analytics Service
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.
[INFO] :   Ads: Ad is not visible. Not refreshing ad.
[INFO] :   Ads: Scheduling ad refresh 60000 milliseconds from now.

A: onPause() method of the Activity Life cycle, consider to pause the AdView mGoogleAdView;
           if (mGoogleAdView != null) {
                mGoogleAdView.pause();
            }

In onDestroy method of Life cycle consider to
 mGoogleAdView.destroy();

P.S: I have not used Titanium.


text:
Q: How do you find out if a mutex object already exists in Linux? I'm currently attempting to port a Multithreading library written for WIN32 to Android/Linux and I seem to have run into a bit of a problem trying to map over a particular feature that WIN32 mutexes have.
From the documentation for Windows Mutex Objects:

Threads in other processes can open a handle to an existing mutex
  object by specifying the object name in a call to CreateMutex. If a
  mutex object with that name already exists, GetLastError returns
  ERROR_ALREADY_EXISTS.

I was not able to find any info on something in the Linux man pages that is similar to what the Windows API offers.
The main reason for my asking this question is that the mutex creation code I'm porting over contains:
isCreator = !(::GetLastError() == ERROR_ALREADY_EXISTS);

where isCreator is a boolean data type.  (Not sure what it's used for , but I think its important).
edit:
mutex = PTHREAD_MUTEX_INITIALIZER;
// attributes??

if (pthread_mutex_init(&mutex, NULL) != 0) {
 throw Nv_EXCEPTION(XCPT_ResourceAllocationFailure, GetLastError());
}

A: Your easiest analog to a named, interprocess mutex is probably a named realtime semaphore initialized to a value of one (1).  Try to sem_open("/the_sem", O_CREAT|O_EXCL, mode, 1).  O_EXCL will fail with EEXIST if you aren't the first, and a subsequent sem_open with no flags ought to succeed if you aren't the first:
sem_t *sem;
int isCreator = 0;

if ((sem = sem_open("/the_sem", O_CREAT|O_EXCL, mode, 1)) != SEM_FAILED) {
  // We got here first
  isCreator = 1;
} else {
  if (errno != EEXIST) uh_oh_goodbye();

  // We're not first.  Try again
  sem = sem_open("/the_sem", 0);
  if (sem == SEM_FAILED) uh_oh_goodbye();
}

Note:  you can share pthread mutexes (and anonymous realtime semaphores, for that matter) between processes, if the synchronization object is initialized in shared memory.  POSIX shared memory realtime extensions permit shared memory to be named, too.  There's then a bit of a race between creating the shared memory and initializing the mutex, but in this case attempting to call pthread_mutex_init() should fail with EBUSY for all but the race winner.


text:
Q: Parts of Speech Tagging NLTK SVM I am trying to write one Parts of Speech(PoS) Tagger in NLTK with Support Vector Machine (SVM). I could write upto a classifier as given in
>>> #CLASSIFICATION USING SUPPORT VECTOR MACHINE
>>> import nltk
>>> from nltk.classify import SklearnClassifier
>>> from sklearn.naive_bayes import BernoulliNB
>>> from nltk.tokenize import word_tokenize
>>> from sklearn.svm import SVC
>>> #TRAINING AND TEST DATA
>>> train = [('I love this sandwich.', 'pos'),
('This is an amazing place!', 'pos'),
('I feel very good about these beers.', 'pos'),
('This is my best work.', 'pos'),
("What an awesome view", 'pos'),
('I do not like this restaurant', 'neg'),
('I am tired of this stuff.', 'neg'),
("I can't deal with this", 'neg'),
('He is my sworn enemy!', 'neg'),
('My boss is horrible.', 'neg')]
>>> test = [
        ('The beer was good.', 'pos'),
        ('I do not enjoy my job', 'neg'),
        ("I ain't feeling dandy today.", 'neg'),
        ("I feel amazing!", 'pos'),
        ('Gary is a friend of mine.', 'pos'),
        ("I can't believe I'm doing this.", 'neg')]
>>> test_sentence = "This is the best band I've ever heard!"
>>> #FEATURESETS
>>> all_words = set(word.lower() for passage in train for word in word_tokenize(passage[0]))
>>> t = [({word: (word in word_tokenize(x[0])) for word in all_words}, x[1]) for x in train]
>>> testf=[({word: (word in word_tokenize(x[0])) for word in all_words}, x[1]) for x in test]
>>> test_sent_features = {word.lower(): (word in word_tokenize(test_sentence.lower())) for word in all_words}
>>> #CLASSIFICATION
>>> #SUPPORT VECTOR MACHINE
>>> classif1 = SklearnClassifier(SVC(), sparse=False).train(t)
>>> classif1.classify(test_sent_features)
'neg'

I have tried to use
from nltk.tag.sequential import ClassifierBasedPOSTagger

and also,
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

but without much help.
It seems NLTK also has one SVM classifier as given in,
from nltk.classify import svm

but somehow failing to connect.
I tried them as follows and received the corresponding error reports.
>>> import nltk
>>> from nltk.classify import SklearnClassifier
>>> from sklearn.naive_bayes import BernoulliNB
>>> from nltk.tokenize import word_tokenize
>>> from sklearn.svm import SVC
>>> from nltk.corpus import brown
>>> brown_trd=brown.tagged_sents()[:300]
>>> from nltk.tag.sequential import ClassifierBasedPOSTagger
>>> clf = SklearnClassifier(SVC(),sparse=False)
>>> svm_tagger = ClassifierBasedPOSTagger(train=brown_trd,
classifier_builder=clf.train)

Traceback (most recent call last):
  File "<pyshell#9>", line 2, in <module>
    classifier_builder=clf.train)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 630, in __init__
    self._train(train, classifier_builder, verbose)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 667, in _train
    self._classifier = classifier_builder(classifier_corpus)
  File "C:\Python27\lib\site-packages\nltk\classify\scikitlearn.py", line 115, in train
    X = self._vectorizer.fit_transform(X)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 226, in fit_transform
    return self._transform(X, fitting=True)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\dict_vectorizer.py", line 174, in _transform
    values.append(dtype(v))
TypeError: float() argument must be a string or a number

>>> from nltk.classify import svm
>>> svm_tagger = ClassifierBasedPOSTagger(train=brown_trd,
classifier_builder=svm.train)

Traceback (most recent call last):
  File "<pyshell#11>", line 2, in <module>
    classifier_builder=svm.train)
AttributeError: 'module' object has no attribute 'train'

>>> from sklearn.feature_extraction import DictVectorizer
>>> from sklearn.feature_extraction.text import TfidfTransformer
>>> train_data=TfidfTransformer(brown_trd)
>>> train_data1=DictVectorizer(brown_trd)
>>> svm_tagger = ClassifierBasedPOSTagger(train=train_data,
classifier_builder=svm.train)

Traceback (most recent call last):
  File "<pyshell#16>", line 2, in <module>
    classifier_builder=svm.train)
AttributeError: 'module' object has no attribute 'train'

>>> svm_tagger = ClassifierBasedPOSTagger(train=train_data1,
classifier_builder=svm.train)

Traceback (most recent call last):
  File "<pyshell#17>", line 2, in <module>
    classifier_builder=svm.train)
AttributeError: 'module' object has no attribute 'train'
>>> svm_tagger = ClassifierBasedPOSTagger(train=train_data,
classifier_builder=clf.train)

Traceback (most recent call last):
  File "<pyshell#18>", line 2, in <module>
    classifier_builder=clf.train)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 630, in __init__
    self._train(train, classifier_builder, verbose)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 656, in _train
    for sentence in tagged_corpus:
TypeError: 'TfidfTransformer' object is not iterable
>>> svm_tagger = ClassifierBasedPOSTagger(train=train_data1,
classifier_builder=clf.train)

Traceback (most recent call last):
  File "<pyshell#19>", line 2, in <module>
    classifier_builder=clf.train)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 630, in __init__
    self._train(train, classifier_builder, verbose)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 656, in _train
    for sentence in tagged_corpus:
TypeError: 'DictVectorizer' object is not iterable
>>> svm_tagger=ClassifierBasedPOSTagger(train=train_data,classifier_builder
= lambda train_feats: clf.train(train_data))

Traceback (most recent call last):
  File "<pyshell#20>", line 2, in <module>
    = lambda train_feats: clf.train(train_data))
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 630, in __init__
    self._train(train, classifier_builder, verbose)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 656, in _train
    for sentence in tagged_corpus:
TypeError: 'TfidfTransformer' object is not iterable
>>> vm_tagger=ClassifierBasedPOSTagger(train=train_data1,classifier_builder
= lambda train_feats: clf.train(train_data1))

Traceback (most recent call last):
  File "<pyshell#21>", line 2, in <module>
    = lambda train_feats: clf.train(train_data1))
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 630, in __init__
    self._train(train, classifier_builder, verbose)
  File "C:\Python27\lib\site-packages\nltk\tag\sequential.py", line 656, in _train
    for sentence in tagged_corpus:
TypeError: 'DictVectorizer' object is not iterable
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> count_vect = CountVectorizer()
>>> X_train_counts = count_vect.fit_transform(brown_trd)

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    X_train_counts = count_vect.fit_transform(brown_trd)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 817, in fit_transform
    self.fixed_vocabulary_)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 752, in _count_vocab
    for feature in analyze(doc):
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 238, in <lambda>
    tokenize(preprocess(self.decode(doc))), stop_words)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 204, in <lambda>
    return lambda x: strip_accents(x.lower())
AttributeError: 'list' object has no attribute 'lower'
>>> X_train_counts = count_vect.fit_transform(train_data)

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    X_train_counts = count_vect.fit_transform(train_data)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 817, in fit_transform
    self.fixed_vocabulary_)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 751, in _count_vocab
    for doc in raw_documents:
TypeError: 'TfidfTransformer' object is not iterable
>>> X_train_counts = count_vect.fit_transform(train_data1)

Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    X_train_counts = count_vect.fit_transform(train_data1)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 817, in fit_transform
    self.fixed_vocabulary_)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 751, in _count_vocab
    for doc in raw_documents:
TypeError: 'DictVectorizer' object is not iterable
>>> X_new_counts = count_vect.transform(brown_trd)

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    X_new_counts = count_vect.transform(brown_trd)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 863, in transform
    self._check_vocabulary()
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 275, in _check_vocabulary
    check_is_fitted(self, 'vocabulary_', msg=msg),
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 678, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
NotFittedError: CountVectorizer - Vocabulary wasn't fitted.
>>> X_new_counts = count_vect.transform(train_data)

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    X_new_counts = count_vect.transform(train_data)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 863, in transform
    self._check_vocabulary()
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 275, in _check_vocabulary
    check_is_fitted(self, 'vocabulary_', msg=msg),
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 678, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
NotFittedError: CountVectorizer - Vocabulary wasn't fitted.
>>> X_new_counts = count_vect.transform(train_data1)

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    X_new_counts = count_vect.transform(train_data1)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 863, in transform
    self._check_vocabulary()
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 275, in _check_vocabulary
    check_is_fitted(self, 'vocabulary_', msg=msg),
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 678, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
NotFittedError: CountVectorizer - Vocabulary wasn't fitted.
>>>

I feel I need to convert brown.tagged_sents() into sklearn format which I am failing and NLTK SVM is not fully developed.
If anyone may kindly suggest how to fix this issue.


text:
Q: Does asmack has the extension jar similar to smackx? I am trying to create multi user google talk client for android. With asmack i am able to set it up to run user-user chat. Now when i am trying to create a group chat i am getting exceptions related to smackx missing.
When i try adding smackx jar I am getting the following error,
"Conversion to Dalvik format failed with error 1"

A: There are many incarnations of asmack. Which one did you use? But IIRC all include the extensions provided by smackx. Sounds like you forgot to register the extensions with the ProviderManager. See the section "ProviderManager" in the Readme.


text:
Q: Can we prove that a bounded closed subset of $\mathbb R^n$ is compact without Axiom of Choice? Can we prove that a bounded closed subset of $\mathbb R^n(n \ge 1)$ is compact without using Axiom of Choice?
This is a related question which was closed.

A: First, closed and bounded intervals in $\Bbb R$ are compact: It suffices to prove for $[0,1]$. Let $\mathcal B$ be an arbitrary open cover of $[0,1]$, simply consider $$x=\sup\{y\in[0,1]\mid [0,y]\text{ has a finite subcover in }\mathcal B\},$$ deduce that $[0,x]$ is finitely covered as well, and then argue that we have to have $x=1$ (by the same reason).
Next, show that the product of finitely many compact sets is compact (done by induction, and the only interesting case is the case for product of two compact sets, the argument is quite straightforward by considering an open cover of the product and finding a finite subcover). Therefore closed and bounded boxes in $\Bbb R^n$ are compact, as products of closed intervals.
Finally, closed subsets of a compact space are compact. The proof is the same as with the axiom of choice.
Now we have that every closed and bounded set in $\Bbb R^n$ can be bounded by a product of closed intervals. So it is a closed subset of a compact set, so it is compact.


text:
Q: Why does adding rights to User group affect an Administrator (Server 2008)? User Foo is logged and a member of Administrators, but not a member of Users - I removed that group and even rebooted. In c:\inetpub\www Foo cannot modify any files even though the Administrators group has full rights to the file.
If I give full rights directly to Foo, edit works. If I give full rights to the Users group, edit works. File and parent folder owner is System. What is going on?


text:
Q: Creating multiple models from one model in CakePHP I have a users and a clients table.
They are linked as follows:
-- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(45) NOT NULL,
  `password` VARCHAR(255) NOT NULL,
  `usertype` CHAR(2) NOT NULL,
  `created` DATETIME NOT NULL,
  `modified` DATETIME NULL DEFAULT NULL,
  `firstname` VARCHAR(45) NOT NULL,
  `lastname` VARCHAR(45) NOT NULL,
  `phonenumber` VARCHAR(45) NOT NULL,
  `suburb` VARCHAR(45) NOT NULL,
  `state` VARCHAR(10) NOT NULL,
  `businessname` VARCHAR(45) NULL DEFAULT NULL,
  `image` BLOB NULL DEFAULT NULL,
  `valid` INT NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `clients`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `clients` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `user_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `CLIENTS_FK_idx` (`user_id` ASC),
  CONSTRAINT `CLIENTS_FK`
    FOREIGN KEY (`user_id`)
    REFERENCES `users` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

I have baked these two tables and I have created a users registration page. Upon form submission I want the database to create both a user and a client object.
Here is my UsersController method form CakePHP:
  public function clientregistration()
    {
      //Register a new client. Client enters all details and the system sets usertype=CL
      $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            $user->usertype = 'CL';
            $user->valid = 1;

            if ($this->Users->save($user) && $this->Coaches->($coach)) {
                $this->Flash->success(__('You have successfully registered.'));

                return $this->redirect(['action' => 'login']);
            }
            $this->Flash->error(__('Registration failure. Please, try again.'));
        }
        $this->set(compact('user'));
        $this->set('_serialize', ['user']);

I want the code to automatically pre-fill all data in the clients table as well.
How do I do this?

A: I do not know what you want to prefill, you have only user_id field to save. So if your associations are set correctly in UsersTable.php, you can save Client entity after you saved User:
$client = $this->Users->Clients->newEntity();
$client->user_id = $user->id;
$this->Users->Clients->save($client);


text:
Q: Problem with login session I have installed Ubuntu 16.10 and I tried to start a session with the both options (default and unity8) and after I enter my password and hit enter the screen turns black and then it returns to the login screen again. I can't access the desktop, the system does not leave the login screen.
This same Ubuntu works perfectly when we running it live(directly from the usb drive).
the result of sudo lshw -c video:
  *-display
       descrição: VGA compatible controller
       produto: C61 [GeForce 6150SE nForce 430]
       fabricante: NVIDIA Corporation
       ID físico: d
       informações do barramento: pci@0000:00:0d.0
       versão: a2
       largura: 64 bits
       clock: 66MHz
       capacidades: pm msi vga_controller bus_master cap_list rom
       configuração: driver=nouveau latency=0
       recursos: irq:22 memória:fc000000-fcffffff memória:d0000000-dfffffff memória:fb000000-fbffffff memória:c0000-dffff

A: First you'll have to disable loading drivers during your normal boot.  Then after you get in, change your video drivers to a supported driver for your video card from the repository.
Run these steps:

*

*At the Grub menu hit e to edit the grub commandline.

*Add nomodeset to the grub (linux) command that has quiet splash.

*Hit F10 to save the changes and reboot.

Now Login

*

*Bring up a command prompt with Ctrl+Alt+T
At the prompt run these commands:
$ sudo apt update
$ sudo apt upgrade
$ sudo apt install nvidia-304

Now reboot.


text:
Q: Maintaining a reference to an NSFormatter in a view-based NSTableViews I have a project that currently uses cell-based NSTableViews WITH bindings. I am updating the project to use views instead. With cells, I could instantiate a NSFormatter in code, add it to an NSTableColumn's datacell's formatter property, maintain a reference to that formatter, and change the formatter's properties programmatically. I don't see a strategy to do the same thing with view-based tableviews.
With view-based tableviews, I can set a formatter on a prototype views' textfield, but that formatter is a prototype as well. This formatter will be instantiated several times so I can't maintain a reference to a prototype formatter. As another solution, I created a custom formatter object with my formatter's class, dragged my tablecellview's outlet to the formatter, but this doesn't work at all.
I need to be able to programmatically adjust how my formatter works in a view-based tableview.

A: You can set the formatter in the delegate's tableView:viewForTableColumn:row: method.


text:
Q: npm / node automate directory structure creation? I have googled this and nothing seems to be what I am looking for.
I tried bower, yeoman etc...
So I have a directory structure that I use frequently
How can I automate this?

*

*PROJECT FOLDER

*\app

*\app\assets\

*\app\assets\css

*\app\assets\fonts

*\app\assets\img

*\app\assets\js

*\compile\

*\compile\js

*\compile\js\vendor

*compile\scss\

*compile\scss... several folders here

A: Take a look at this
http://joakim.beng.se/blog/posts/slush-replacing-yeoman-with-gulp.html
and then get slush from https://www.npmjs.com/package/slush
You can then easily create your own generator for your own structure.
There is a fairly good example of slush generator for angular that I used as a guide for mine
https://github.com/slushjs/slush-angular

A: Grunt has the grunt-mkdir plugin. I'm not exactly sure what you're looking for though.
Using that, you can create a configuration for the folders you need:

    makeDirectories: {
        options: {
            mode: 0700,
            create: ['reports', 'reports/coverage']
        }
    }

And then use grunt to make them:

grunt mkdir:makeDirectories


text:
Q: Removing parent and all children I have a problem removing the parent entity from the database. The code looks like this:
public class Parent implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Long id;

  @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(name="parentId")
  private Set<Child> children = new HashSet<Child>();
}

public class Child implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  private Long id;

  private String name;
}

Query q = em.createQuery("delete from Parent");
q.executeUpdate();

But I get "ERROR: update or delete on table "parent" violates foreign key constraint "fk2f04da924aeb47d8" on table "child"". Is it not possible to cascade the delete of all children? How should you clear the tables otherwise?

A: The bulk delete operation is not cascaded. From the JPA 1.0 specification:

4.10 Bulk Update and Delete Operations
(...)
A delete operation only applies to
  entities of the specified class and
  its subclasses. It does not cascade to
  related entities.
(...)

So if you want to use a bulk delete, you'll have to do handle relations "manually" (i.e. to delete related entities first).
The other option would be to loop on the parent entities and to call em.remove() (and cascading would work).
Choosing one option or the other will depend on the number of entities to delete and the expected performances.


text:
Q: Security Concerns of Entirely Localized Password Manager I'm creating a Chrome extension to autofill username and password for one specific site, "example.com". I would like to make EVERYTHING localized to prevent any security concerns. My process is as follows:

*

*on Options page, user can input username/password, which is saved in chrome.storage.local

*on "example.com", the extension autofills the username and password with chrome.storage.local.get(() => ...)
What are the security concerns of this?
What I've Considered

I'm concerned about

*

*Chrome says storage.local is not safe, but they do not provide reasons. Liability?

*Chrome also says storage.local is unique per chrome extension / site. So the ONLY way for an attacker to steal a password is by hacking me and / or my source code, and pushing malicious changes to my extension, correct? (if there's any other way it's a definite no-go)

*Ideally, I would have the password / username be encrypted, with e.g. AES-256. But if everything's local, there's either one master key (which any attacker could find) or a unique key that's stored "securely somewhere" in the app, maybe created at install. << but where to store that? If there's a "secure somewhere" in the app, I should just put the password / username there.

I'd like to do this without a server, however if that's not possible I'm open to suggestions.


text:
Q: How many tags we are allow to register per device for Azure push notification hub I am using the Azure Push Notification Hub. Somewhere I saw there are limit of tags can register per device. Is it right?
My scenario is each device will have numerous of sites which user can go into. The push notification will send to message to the device who have registered of that site.
e.g. Device A may have 100 Sites so the Device A may need to add 100 of tags when register to Notification Hub (May not be adding all the tags at the same time). When push notification required to push notification to devices, I can send e.g. SiteA to whoever device have registered a tag called SiteA will receive it.
Am I using it in a wrong way?
On the website :

Azure Push Notification

All new registrations against any hubs within the namespace of whose Active Device quota is reached will be interrupted.
Does that mean once it reached number of devices registered to that Notification Hub, no additional devices can register....
At the moment, my Xamarin form application will call to my server and register to the notification hub.
How do I know when the device needs to unregister from the notification hub when user uninstall the application? Can't remember where I read it, it will automatically unregistered when expired so no need to detect whether user have uninstalled the application or not.

A:
I am using the Azure Push Notification Hub. Somewhere I saw there are limit of tags can register per device. Is it right?

According to Notification Hub Service limits

So each device can have up to 60 tags, and each tag can be up to 120 characters.
One device couldn't have 100 website's tags.


text:
Q: Django update settings in Celery's async task I am using celery to load Neural Network models and would like to store the loaded model in settings for fast prediction.
so in django.conf.settings I have:
MODELS = {}

and in celery task, I have the following snippet:
@app.task
def load_nn_models(model_name):
     from django.conf import settings
     ...
     settings.MODELS[model_name] = {'model': net, 'graph': sess}

However, I noticed that the tasks are running in another thread that launches different Django Environment and any changes in the settings will not be reflected back to the main thread.
Is there a workaround for this?
EDIT
The parameters I am storing in settings are:

*

*net: keras Model

*sess: Tensorflow Session

A: Django settings are not the right place for this, obviously. First because the settings object is not a shared resource (there's one instance per process), then because the doc explicitely mentions that this object is to be considered as immutable.
If your point is to have a celery task computing those objects so that other tasks and / or the front can use them, you will have to find a way to serialize them and store the serialized version in a shared resource (database, cache, etc).

A: you can try to use the configparser
    import configparser
def dict_from_file():
    config = configparser.ConfigParser()
    config.read("config.ini")
    models = config['models']
    for x in models.values():
        print(x)

set file config.ini:
[models]
var_a: home
var_b: car
var_c: Next

call dict_from_file the output is:
home
car
Next

update the file config.ini:
[models]
var_a: home
var_c: New

call dict_from_file the output is:
home
New

ypu can read more for the supported-datatypes


text:
Q: codesniffer not working with php 7.0 and netbeans 8.1 I have installed code sniffer with below steps ,
Download phpcs.phar file from below link
https://github.com/squizlabs/PHP_CodeSniffer
Go to NetBeans -> Tools -> plugins .
install PHPCSMD.
Now go to Tools -> options -> PHP, Find "Code Analysis".
Put phar file path here.
Closed netbeans
open again netbeans.
right click on my project file and click on check for violation.
but it not gives me any result.


text:
Q: Discontinuous integral $\frac1{2\pi i}\int_{c-i \infty}^{c+i\infty}y^s\frac{ds}{s}$ The book tells me to use the following integral,
$$
\frac{1}{2\pi i}\int_{c-i \infty}^{c+i\infty}y^s\frac{ds}{s}=
\begin{cases}
0\quad&\text{if }0<y<1,\\
\frac{1}{2}&\text{if }y=1,\\
1&\text{if }y>1,
\end{cases}
$$
where $c>0$. I don't need to prove this but I wanted to make sense of this integral. Here's my (pseudo)proof for the first case.
Consider a rectangular path consisting of $c+iT$, $c-iT$, $c+S-IT$ and $c+S+IT$ for some $T,S>0$. Call each path, starting from $c+iT$, $C_1,C_2,C_3$ and $C_4$ respectively - so $C_1$ and $C_3$ are two vertical paths and the other two are horizontal paths. If we integrate $\frac{y^s}{s}$ over this rectangle, the result is 0 since there is no pole or zero inside. As $S,T\to\infty$, integrals along $C_2,C_3,C_4$ vanish since $\left|\frac{y^s}{s}\right|\to0$. Therefore, integral along $C_1$ is also 0 as $S,T\to\infty$.
Now, I know I can use pretty much the same proof for $y>1$ case just by taking a rectangle extending to the left this time. However, I'm having a little bit if of difficulty to prove the case $y=1$ Can anyone help me? (Also, it'd be great if someone can tell me my proof is right)

A: When $y=1$ you just have $\frac{1}{2\pi i} \left. \ln(s) \right |_{c-i\infty}^{c+i\infty}$. In the sense of Cauchy principal value at least, this evaluation is just $\pi i$ giving an overall result of $1/2$. Without some such regularization you could have a real part persisting, which is not a surprise because the integral is not absolutely convergent.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
When $\large\ds{\color{red}{y = 1}}$, you can write $\ds{\pars{~\mbox{with}\ s \equiv c + \ic t~}}$:
\begin{align}
\mc{I} &\equiv \left.{1 \over 2\pi\ic}\int_{-a}^{b}{\ic\,\dd t \over c + \ic t}
\,\right\vert_{\ a,b,c\ >\ 0} =
{1 \over 2\pi}\int_{-a}^{b}{c - \ic t \over t^{2} + c^{2}}\,\dd t =
{1 \over 2\pi}\int_{-a/c}^{b/c}{1 - \ic t/c \over t^{2} + 1}\,\dd t
\\[5mm] & =
{\arctan\pars{b/c} + \arctan\pars{a/c}\over 2\pi} - {\ic \over 4\pi c}
\ln\pars{b^{2} + c^{2} \over a^{2} + c^{2}}
\end{align}

Note that $\ds{\Re\pars{\mc{I}} \to {1 \over 2}}$ as $\ds{a,b \to \infty}$. However, the imaginary part diverges in such case.