Q: 500 Error When Adding Custom Django App With mod_fcgid I've been following the official Django 1.3 tutorial on their website. My issue comes when I add my custom app (polls) to the INSTALLED_APPS list in settings.py like such:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'polls',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

However, when I go back and look at the stack trace I get this:
mod_fcgid: stderr: TemplateSyntaxError: Caught ImportError while rendering: No module named polls

What am I doing wrong? Here is the entire stack trace:
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: Traceback (most recent call last):
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 574, in run
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "build/bdist.linux-i686/egg/flup/server/fcgi_base.py", line 1159, in handler
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 272, in __call__
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: response = self.get_response(request)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 169, in get_response
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 203, in handle_uncaught_exception
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return debug.technical_500_response(request, *exc_info)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 59, in technical_500_response
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: html = reporter.get_traceback_html()
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 151, in get_traceback_html
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return t.render(c)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 123, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self._render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 117, in _render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.nodelist.render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 744, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: bits.append(self.render_node(node, context))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 73, in render_node
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: result = node.render(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 90, in render
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: output = self.filter_expression.resolve(context)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/base.py", line 536, in resolve
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: new_obj = func(obj, *arg_vals)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/template/defaultfilters.py", line 695, in date
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return format(value, arg)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 285, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return df.format(format_string)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: pieces.append(force_unicode(getattr(self, piece)()))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 191, in r
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.format('D, j M Y H:i:s O')
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: pieces.append(force_unicode(getattr(self, piece)()))
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/encoding.py", line 71, in force_unicode
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: s = unicode(s)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 206, in __unicode_cast
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return self.__func(*self.__args, **self.__kw)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/__init__.py", line 81, in ugettext
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return _trans.ugettext(message)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 286, in ugettext
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: return do_translate(message, 'ugettext')
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 276, in do_translate
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: _default = translation(settings.LANGUAGE_CODE)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 185, in translation
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: default_translation = _fetch(settings.LANGUAGE_CODE)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 162, in _fetch
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: app = import_module(appname)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: File "/usr/lib/python2.4/site-packages/django/utils/importlib.py", line 35, in import_module
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: __import__(name)
[Sat Aug 04 07:16:55 2012] [warn] [client 74.202.255.243] mod_fcgid: stderr: TemplateSyntaxError: Caught ImportError while rendering: No module named polls

Edit...here is my sys.path:
/home/andydefo/andydeforest
/usr/lib/python2.4/site-packages/MySQL_python-1.2.3-py2.4-linux-i686.egg
/usr/lib/python2.4/site-packages/setuptools-0.6c12dev_r88846-py2.4.egg
/usr/lib/python2.4/site-packages/flup-1.0.3.dev_20110405-py2.4.egg
/usr/lib/python2.4/site-packages/pip-1.1-py2.4.egg
/usr/lib/python24.zip
/usr/lib/python2.4
/usr/lib/python2.4/plat-linux2
/usr/lib/python2.4/lib-tk
/usr/lib/python2.4/lib-dynload
/usr/lib/python2.4/site-packages
/usr/lib/python2.4/site-packages/Numeric
/usr/lib/python2.4/site-packages/gtk-2.0

And my urls.py:
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'andydeforest.views.home', name='home'),
    # url(r'^andydeforest/', include('andydeforest.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

A: Is your app on the PYTHONPATH? You can check it in the shell by
$ python manage.py shell

and in the shell, check it using
> import sys
> print sys.path

If the app is not on PYTHONPATH, you can add it using project's settings.py.
In settings.py:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, "polls"))

If that is not the issue, could you also show the urls.py and views.py part of where the template is being invoked?

A: Had the same problem, solved it, try this in the settings.py:
import sys
sys.path.insert(0, "/home/user/django_projects/myproject/")

from here: http://www.bluehostforum.com/showthread.php?21680-DJANGO-Can-t-import-own-module


Q: Automatically fill in values in excel How do I achieve the following in Excel behavior?
A1 = 123 and in A2 = 56.
56 fits 2.19x times in in 123, e.g., =123/56. It fits via the sequence 56, 56 and 11 (=MOD(123,56)). Now how do I obtain that those values are shown in cells C1...C7
C1: 56
C2: 56
C3: 11
C4: 0
C5: 0
C6: 0
C7: 0

And when A1 is 173
C1: 56
C2: 56
C3: 56
C4: 5
C5: 0
C6: 0
C7: 0

Et cetera

A: In C1 enter:
 =A2

In C2 enter:
=IF(SUM($C$1:C1)=$A$1,"",IF(SUM($C$1:C1)<$A$1,MIN($A$1-SUM($C$1:C1),C1)))

and copy downwards.

A: This solution does not use helper cells, has simple and short expressions, and uses the question's exact cell distribution.

*

*Set C1 to
=MIN(A1, A2)

*Set C2 to
=MIN($A$1-SUM($C$1:C1), $A$2)

*Now drag/copy C2 down as long as you want.

A: I would do it via an IF cause
 A1 Start value  B1 Divisor
A2:   =IF(A1>=$B$1;A1-$B$1;IF(B1=$B$1;$B$1;0))  B2: =IF(A2<$B$1;A2;$B$1)

then pull down as far as you need and in column B you have all you need


Q: Reference for bicategories I've learned a bit of bicategories from Jean Bénabou's "Introduction to Bicategories". Now I'm looking for some more comprehensive references concerning this subject this subject. I'm in particular interested the limits, colimits, Yoneda Lemma of bicategories, the structure we can define on the functor category or pseudofunctor category of bicategories, and the model structures on bicategories.

A: The recent book 2-Dimensional Categories by Johnson and Yau is a comprehensive introduction to 2-categories and bicategories. I believe it has all the topics you are interested in, save for a discussion of model structures: however, it gives several references to the literature where you can read more about this topic.
One should also mention Lack's A 2-categories companion, which is a more informal introduction, and which covers many of the same topics.


Q: How to exclude moment locales from angular build? In my angular 5 application, when I create build using
ng build --prod --sm

and open source map explorer, moment takes lot of space in the main.js file. I have found all the locales gets loaded when I use
import * as moment from 'moment';

I have used material-moment-adapter to some functionality in the application that requires the moment package also.
I have created the application using angular-cli. I have found many links that excludes locales using settings in webpack.config.js
Is there any way to exclude locales using angular-cli ?

A: If you don't want to use any third party libraries the simplest way to do this is to add the following in compilerOptions of your tsconfig.json file
"paths": {
  "moment": [
    "../node_modules/moment/min/moment.min.js"
  ]
}

A: There is another solution in this Angular Issue:
https://github.com/angular/angular-cli/issues/6137#issuecomment-387708972
Add a custom path with the name "moment" so it is by default resolved to the JS file you want:
"compilerOptions": {
    "paths": {
      "moment": [
        "./node_modules/moment/min/moment.min.js"
      ]
    }
}

A: This article describe good solution:
https://medium.jonasbandi.net/angular-cli-and-moment-js-a-recipe-for-disaster-and-how-to-fix-it-163a79180173
Briefly:

*

*ng add ngx-build-plus

*Add a file webpack.extra.js in the root of your project:
const webpack = require('webpack');
module.exports = {
    plugins: [
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ]
}

*Run:
npm run build --prod --extra-webpack-config webpack.extra.js

enter code here
Warning
moment.js has been deprecated officially
https://momentjs.com/docs/#/-project-status/ (try use day.js or luxon)

A: For anyone on angular 12 or latest
This does not work for me
const webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ]
}

However this does
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    })
  ]
};

A: In Angular 12, I did the following:
npm i --save-dev @angular-builders/custom-webpack

to allow using a custom webpack configuration.
npm i --save-dev moment-locales-webpack-plugin
npm i --save-dev moment-timezone-data-webpack-plugin

Then modify your angular.json as follows:
    ...
    "architect": {
        "build": {
            "builder": "@angular-builders/custom-webpack:browser",
                "options": {
                    "customWebpackConfig": {
                        "path": "./extra-webpack.config.js"
                    },
                    ...

and in the extra-webpack.config.js file:
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin');

module.exports = {
    plugins: [
        new MomentLocalesPlugin({
            localesToKeep: ['en-ie']
        }),
        new MomentTimezoneDataPlugin({
            matchZones: /Europe\/(Belfast|London|Paris|Athens)/,
            startYear: 1950,
            endYear: 2050,
        }),
    ]
};

Modify the above options as needed, of course. This gives you far better control on which exact locales and timezones to include, as opposed to the regular expression that I see in some other answers.

A: the solutions above didn't work for me because they address the wrong path (don't use ../ ) in the tsconfig.app.json
{
...
   "compilerOptions": {
      "paths": {
        "moment": [
          "node_modules/moment/min/moment.min.js"
        ]
      }
   }
}

Works for me in Angular 12.2.X. The changes must be done in the tsconfig.app.json, than also the type information of your IDE will work.

Don't change it in the tsconfig.json or your IDE will lose type information.

This fix the usage in the app as in the lib. I used source-map-explorer to verify it.
ng build --sourceMap=true --namedChunks=true --configuration production && source-map-explorer dist/**/*.js

A: I had the same problem with momentjs library and solve it as below:
The main purpose of this answer is not to use IgnorePlugin for ignoring the library but I use ContextReplacementPlugin to tell the compiler which locale files I want to use in this project.

*

*Do all of the configurations mentioned in this answer: https://stackoverflow.com/a/72423671/6666348

*Then in your webpack.config.js file write this:
const webpack = require("webpack");

module.exports = {
    plugins: [
        new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /(en|fr)$/)
    ]
};

This configuration will add only en and fr locale in your application dist folder.

A: You can try to use moment-mini-ts instead of moment
npm i moment-mini-ts

import * as moment from 'moment-mini-ts'

Don’t forget to uninstall moment
npm uninstall moment

I’m using angular 9


Q: The animated text not working as the Javascript function I have coded a function to animate a texts by manipulating the ID and set animation delay to change the ID and start the animation again. The animation started well, however, after few minutes the animation delay does not work or take more time instead of was set.

setInterval(controlAninmation_A, 100);

function controlAninmation_A() {
  var getId = document.getElementById('AA');
  getId.setAttribute("id", "A");
  var removeId = document.getElementById('A'),
    setClass = removeId;
  setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");

    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 30000);

  function changeId() {
    removeId.setAttribute("id", "AA");
    console.log("The function was executed 100% ");
  }

  clearTimeout(changeId);
}

clearInterval(controlAninmation_A);
setInterval(controlAninmation_B, 4000);

function controlAninmation_B() {

  var getId = document.getElementById('BB');
  if (getId != "B") {
    getId.setAttribute("id", "B");
  }

  var removeId = document.getElementById('B'),
    setClass = removeId;
  setTimeout(changeClass, 34000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");

    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 27000);

  function changeId() {
    removeId.setAttribute("id", "BB");
  }

  clearTimeout(changeId);
}

clearInterval(controlAninmation_B);
setInterval(controlAninmation_C, 11000);

function controlAninmation_C() {

  var getId = document.getElementById('CC');
  if (getId != "C") {
    getId.setAttribute("id", "C");
  }

  var removeId = document.getElementById('C'),
    setClass = removeId;
  setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");

    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 41000);

  function changeId() {
    removeId.setAttribute("id", "CC");
  }

  clearTimeout(changeId);

}

clearInterval(controlAninmation_C);
setInterval(controlAninmation_D, 17000);

function controlAninmation_D() {
  var getId = document.getElementById('DD');
  if (getId != "D") {
    getId.setAttribute("id", "D");
  }

  var removeId = document.getElementById('D'),
      setClass = removeId;
  setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");
    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 47000);

  function changeId() {
    removeId.setAttribute("id", "DD");
  }

  clearTimeout(changeId);

}

clearInterval(controlAninmation_D);
setInterval(controlAninmation_E, 20000);

function controlAninmation_E() {

  var getId = document.getElementById('EE');
  if (getId != "E") {
    getId.setAttribute("id", "E");
  }

  var removeId = document.getElementById('E'),
      setClass = removeId; setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");

    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 50000);

  function changeId() {
    removeId.setAttribute("id", "EE");
  } clearTimeout(changeId);
}

clearInterval(controlAninmation_E);
setInterval(controlAninmation_F, 24000);

function controlAninmation_F() {
  var getId = document.getElementById('FF');
  if (getId != "") {
    getId.setAttribute("id", "F");
  }

  var removeId = document.getElementById('F'),
      setClass = removeId; setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");

    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 54000);

  function changeId() {
    removeId.setAttribute("id", "FF");
  }
  clearTimeout(changeId);
}

clearInterval(controlAninmation_F);
setInterval(controlAninmation_G, 27000);

function controlAninmation_G() {
  var getId = document.getElementById('GG');
  if (getId != "") {
    getId.setAttribute("id", "G");
  }
  var removeId = document.getElementById('G'),
    setClass = removeId;
  setTimeout(changeClass, 20000);

  function changeClass() {
    var checkClass = setClass.getAttribute("class");
    if (checkClass != "change") {
      setClass.setAttribute("class", "change");
      console.log("changed class");
    }
  }

  clearTimeout(changeClass);
  setTimeout(changeId, 57000);

  function changeId() {
    removeId.setAttribute("id", "GG");
  }
  clearTimeout(changeId);
}

clearInterval(controlAninmation_G);
setInterval(controlAninmation_H, 30000);

    function controlAninmation_H() {

      var getId = document.getElementById('HH');
      if (getId != "") {
        getId.setAttribute("id", "H");
      } moveId = document.getElementById('H'),
        setClass = removeId;
      setTimeout(changeClass, 20000);

      function changeClass() {
        var checkClass = setClass.getAttribute("class");

        if (checkClass != "change") {
          setClass.setAttribute("class", "change");
          console.log("changed class");
        }
      }

      clearTimeout(changeClass);
      setTimeout(changeId, 60000);

      function changeId() {
        removeId.setAttribute("id", "HH");
      }
      clearTimeout(changeId);
}

clearInterval(controlAninmation_H);
#A{ animation-name: wave;animation-duration: 20s;  animation-iteration-count: 1;animation-timing-function:linear;  }
    #B{ animation-name: QQQ;animation-duration: 20s;  animation-iteration-count: 1;animation-timing-function:linear;  }
    #C{ animation-name: EEEE;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
    #D{ animation-name: RRRR;animation-duration: 20s;  animation-iteration-count: 1; animation-timing-function:linear; }
    #E{ animation-name: AAAA;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
    #F{ animation-name: DDDDDD;animation-duration: 20s;  animation-iteration-count: 1;animation-timing-function:linear;  }
    #G{ animation-name:GGGGGGG;animation-duration: 20s; animation-iteration-count: 1; animation-timing-function:linear; }
    #H{ animation-name:KKKKKKKK;animation-duration: 20s; animation-iteration-count: 1;animation-timing-function:linear;  }

    .hidden{
    position: relative;
    top: 160px;}
    .change{
     position: relative;
    top: 160px;}
    @keyframes A{0%{transform: translateX(0%); top:17px; margin-left: 10px;margin-right: 10px;visibility: visible;  }100%{transform: translateX(100%); top:17px; margin-left: 10px;margin-right: 10px;visibility: visible; }}
    @keyframes B{0%{transform: translateX(0%);top:0px; margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:0px; margin-right: 10px; visibility: visible; }}
    @keyframes C{0%{transform: translateX(0%);top:-17px;  margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-17px; margin-right: 10px;visibility: visible; }}
    @keyframes D{0%{transform: translateX(0%);top:-34px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-34px;margin-right: 10px;visibility: visible; }}
    @keyframes E{0%{transform: translateX(0%);top:-51px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-51px;margin-right: 10px;visibility: visible; }}
    @keyframes F{0%{transform: translateX(0%);top:-68px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-68px;margin-right: 10px;visibility: visible; }}
    @keyframes G{0%{transform: translateX(0%);top:-85px;margin-right: 10px;visibility: visible; }100%{transform: translateX(100%);top:-85px;margin-right: 10px;visibility: visible; }}
    @keyframes H{0%{transform: translateX(0%);top:-102px;margin-right: 10px;margin-left: 10px;visibility: visible; }100%{transform: translateX(100%);top:-102px;margin-right: 10px;margin-left: 10px;visibility: visible; }}

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow

Welcome to StackOvervlow


Q: Finding perpendicular projection of the vector In the space $\mathbb{R}^3$ find perpendicular projection  of the vector $\alpha =(1,1,1)$ on the space $V= \{ (x_1,x_2,x_3) \in \mathbb{R}^3 | x_1+2x_2-x_3=0 \}$ and find perpendicular projection of $\alpha$ on a line $L=((1,2,3))$. How to do this because i have utterly no idea even how to start?

A: So you know that a vector $v$ can be expressed as the sum
$v = v_\parallel + v_\perp$
where $v_\parallel$ is in the subspace $V$ and $v_\perp$ is orthogonal to $V$.
The vector $v_\parallel$ is what we generally mean by the orthogonal
or perpendicular projection of $v$ onto $V$.
In general, if $v \in \mathbb R^n$
and $\{e_1,\ldots,e_n\}$ is an orthonormal basis of $\mathbb R^n$,
then $v$ is the sum of $n$ orthogonal vectors of the form
$(v\cdot e_i)\, e_i$ for $1 \leq i \leq n$.
Given an $m$-dimensional subspace of $\mathbb R^n$,
if you can choose $\{e_1,\ldots,e_n\}$ so that $\{e_1,\ldots,e_m\}$
is an orthonormal basis of $V$, then
$\{e_{m+1},\ldots,e_n\}$ is an orthonormal basis of the orthogonal complement of $V$,
and you then have the necessary tools to represent both $v_\parallel$ and $v_\perp$
as sums of vectors of the form $(v\cdot e_i)\, e_i$.
For $n=3$ the task is simplified, since there are only four possibilities:
$V=\mathbb R^3$, $V=\{0\}$, $V$ is one-dimensional,
or the orthogonal complement of $V$ is one-dimensional.
Orthogonal projections in the first two cases are trivial, and in the other
two cases, either $v_\parallel$ or $v_\perp$ are easily found if you can identify
one unit vector in the relevant one-dimensional subspace.
And of course once you find one of $v_\parallel$ or $v_\perp$ you can use
$v = v_\parallel + v_\perp$ to find the other.
In the particular case  $V= \{ (x_1,x_2,x_3) \in \mathbb{R}^3 | x_1+2x_2-x_3=0 \}$,
you may notice that $x_1+2x_2-x_3=(x_1,x_2,x_3)\cdot(1,2,-1)$,
from which we can deduce the identity of one vector orthogonal to $V$.
Now if you consider how you can find $(v\cdot e_i)\, e_i$ when you have
$v$ and a vector $u = ce_i$, for some scalar constant $c$,
you can derive the general formulas for finding the orthogonal projection of
$v$ onto a planar subspace of $\mathbb R^3$ given any vector orthogonal to the plane,
and the orthogonal projection of $v$ onto a linear subspace of $\mathbb R^3$
given any vector in that subspace.


Q: Import styles into react-native I'm stying how to import styles from other sources into react native. I see that there are options like using styled-component or even importing scss files.
Anyway, Do you have any particular recommentations?
I'm currently exploring [this option] (https://github.com/kristerkari/react-native-sass-transformer/) but I'm getting a syntax error (Unexpected token), so I guess something in the loader is missing. Not sure.
I'd like to be able to serve styles into a react native project from an outside library.


Q: Magnetic field due to a current carrying wire at the wire Why do we take zero magnetic field at a point on the axis of a current carrying wire.
When i use $B =\frac{\mu_0 I}{2\pi r}$ formula for magnetic field calculation at a distance $r$ from the wire then for $r\to 0$, $B$ becomes infinity. What I am missing here?
I am assuming that wire has  zero thickness which we normally use for problem solving.

A: Complementing jim's answer in order to explicitly address the questions that possibly motivated the original post:

*

*does the field intensity diverge at the wire?

*where does it point to?

The answer is that in practice we have a current density ($I(A)/A$); and, as long as this density is finite, considering a position $r\to 0$ necessarily leads to the magnetic field at this position being that generated by a vanishing amount of current and, thus, having vanishing intensity: $\mathbf{B}\to 0$.
That is, instead of diverging, the magnetic field is zero and, in particular, has no defined direction.
What about $B =\frac{\mu_0 I}{2\pi r}$, then? Well, if you try to apply it for $r\to 0$, you approach the limit of the wire being a mathematical line, with zero radius and area, and that implies, if the current is finite, an infinite current density (finite $I$ going through a vanishing cross-section area). So you're assuming a diverging physical situation, it's then not surprising you get other divergences.

A: For an infinitely long wire of infinitesimal thickness carrying a steady current $I$ the magnetic field at a distance $r$ from the wire is $$B =\frac{\mu_0 I}{2\pi r}.$$ This result can be derived from Ampere's Law $$\int {\bf B . d s} = \mu_0 \times \text{current enclosed by path},$$ where the current enclosed by the path (for infinitesimal thickness the enclosed current is always the total current $I$ flowing through the wire. For a wire of finite thickness you can still make use of Ampere's Law though for a distance $r \lt s$ the enclosed current is now only a fraction of the total current flowing through the wire. Typically this is taken to be $$I \frac{r^2}{s^2}.$$ You can then determine the magnetic field for the two cases (i) $r \le s$ (current = $I \frac{r^2}{s^2}$) and (ii) $r \ge s$ (current = $I$).
For distances inside the wire you only have a fraction of the current that contributes to the magnetic field and the magnetic field has a finite value at a point on the wire itself.


Q: check whether a string exists in list using for loop in c# I have a list arrString that contains string values. I need to check a string lookupvalue.Longname whether it exists in the list using for loop in C#.
 for(int i = 0 ;i < ResoCustomFields.LongnameNotToBeTaken.Count ;i++)
 {
    string myStringList = ResoCustomFields.LongnameNotToBeTaken[i].ToString();
    var arrString = myStringList.Trim('(',')').Split(',').ToList();
    if(arrString.Contains(resoField))
    {
    // if(!arrString[i].Any(str=>str.ToString().Contains(lookupValue.LongName)))
    // if(lookupValue.LongName.Contains(arrString.ToString()))
    //(!arrString.Any(str => str.Equals(lookupValue.LongName)))
    // if(!arrString.Equals(lookupValue.LongName))
    {
    }
}

A: You can try the following code :
int pos = Array.IndexOf(arrString, lookupValue.LongName);
if (pos > -1)
{
//// DO YOUR STUF
}

Following is the reference:
Checking if a string array contains a value, and if so, getting its position


Q: lambda function to start aws workspaces - overcome client.start_workspaces limitation i have a lambda function to start all the workspaces machines in my env
Lambda Function :
import boto3
client = boto3.client('workspaces')

def lambda_handler(event,context):
     workspaces = client.describe_workspaces()['Workspaces']
     for workspace in workspaces:
          if workspace['WorkspaceProperties']['RunningMode'] == 'AUTO_STOP':
               if workspace['State'] == 'STOPPED':
                   workspaces_id = (workspace['WorkspaceId'])
                   client.start_workspaces(
                       StartWorkspaceRequests=[
                           {
                               'WorkspaceId': workspaces_id
                           },
                        ]
                     )

The client.start_workspaces has a limitation of 25 workspaces per request , any idea how to overcome this ? im trying to build a robust solution for more then 25 workspaces .
https://docs.aws.amazon.com/workspaces/latest/api/API_StartWorkspaces.html#API_StartWorkspaces_RequestSyntax
Thanks in advance to the helpers

A: Probably you can use Paginator. Then call the client, to start the workspace workspaces."WorkSpaces.Paginator.DescribeWorkspaces"


Q: How to change a button shape style at runtime? I am developing an app in java, android studio, where the user can choose the style color of the app.
With most components just use the .setBackground(colorUser);
The problem is in my buttons.
My buttons are all rounded, I created a shape for that.
My shape is in other file...
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="@color/colorJetway" />

    <corners
        android:bottomLeftRadius="80dp"
        android:bottomRightRadius="80dp"
        android:topLeftRadius="80dp"
        android:topRightRadius="80dp" />

</shape>

<Button
            android:id="@+id/btnAdc"
            android:layout_width="84dp"
            android:layout_height="84dp"
            android:layout_marginTop="12dp"

            android:layout_marginEnd="205dp"
            android:background="@drawable/btns_border"
            android:onClick="btnAdicionar_click"
            android:text="+"
            android:textColor="#FFFFFF"
            android:textSize="40dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txtQuantidade" />

That way if at runtime I make mybutton.setBackground(colorUser) my button loses its style ... it will have no rounded edges.
How can I do it?

A: It is not exactly what you are looking for.
However using the MaterialButton component it is very simple to have rounded buttons.
Just use app:cornerRadius to define the corner radius and app:backgroundTint to change the background color.
<com.google.android.material.button.MaterialButton
    app:backgroundTint="@color/myselector"
    app:cornerRadius="xxdp"
    .../>

You can programmatically change these values using:
button.setCornerRadius(...);
button.setBackgroundTintList(..);

A: if your colors is limited you can create some drawables with the colors you want.
for example :
blackButton.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">

<solid android:color="@color/black" />

<corners
    android:bottomLeftRadius="80dp"
    android:bottomRightRadius="80dp"
    android:topLeftRadius="80dp"
    android:topRightRadius="80dp" />

whiteButton.xml :
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">

<solid android:color="@color/white" />

<corners
    android:bottomLeftRadius="80dp"
    android:bottomRightRadius="80dp"
    android:topLeftRadius="80dp"
    android:topRightRadius="80dp" />

and when you want change your button's background just use button.setBackground(getResources().getDrawable(R.drawable.blackButton)) or button.setBackground(getResources().getDrawable(R.drawable.whiteButton))


Q: Computing the Multivariate Normal density gives sometimes different values from in-built function I'm trying to define the density of the Multivariate Normal distribution, since it will be faster to compute for greater dimensions (vectors of size 50 or more), specially when I have to do those computations many times (10,000).
I've defined the density as :
multinormalDens[x_, mean_, var_] := Module[{},
   Det[2*Pi*var]^(-0.5)*Exp[-0.5*(x - mean).Inverse[var].(x - mean)]
   ];

I use the Wishart to provide with several positive definite covariance matrices.
varmat = RandomVariate[
   WishartMatrixDistribution[52, IdentityMatrix[50]], 10000];
meanmat = Table[RandomReal[{0, 5}, 50], {i, 1, 10000}];

They will all be evaluated for the same point:
x0 = RandomReal[{0, 5}, 50];

Now running the comparison for 10,000 tries, I get:
In[43]:= Table[
  multinormalDens[x0, meanmat[[i]], varmat[[i]]] ==
   PDF[MultinormalDistribution[meanmat[[i]], varmat[[i]]], x0], {i, 1,
    Length[varmat]}] // Total

Out[43]= 6643 False + 3357 True

How come I have 6643 different outcomes? Are they from the matrix inversion?
Edit:
data = Table[
   multinormalDens[x0, meanmat[[i]], varmat[[i]]] -
    PDF[MultinormalDistribution[meanmat[[i]], varmat[[i]]], x0], {i,
    1, Length[varmat]}];

ListPlot[data]
ListPlot[data, PlotRange -> All]

A: This is less about accuracy (it is already good) but about getting rid of the General::munfl messages. Before the final number is computed, we should check whether the logarithm of the result is below (a multiple of) Log[$MinMachineNumber]; if yes, we simply set the result to 0.
multinormalDens[x_, mean_, var_] := Module[{t, det},
   t = 0.5*(x - mean).LinearSolve[var, (x - mean)];
   det = Det[2*Pi*var]^(0.5);
   If[-t - Log[det] < 10. Log[$MinMachineNumber], 0., Exp[-t]/det]
   ];


Q: I want to control dynamic subMenu auto column in wpf. if 5 row auto break 1 column. how? I want to control dynamic subMenu auto column in wpf. if 5 row auto break 1 column. how?
I think if control grid in code bihinde but i dont' know. can you help me.


Q: imagemagick doesn't delete tmp files I have an app that uses Carrierwave, S3 and rmagci.
more or less following http://railscasts.com/episodes/253-carrierwave-file-uploads but just upload to S3 instead of local.
I noticed the temp files in public/uploads/ does not get deleted after an image gets created. This causes my computer to feel up over time and crash.
I looked around and the only solution i found was to write a cron job to delete them http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=15960
any idea if there is a better way to do this in the code rather than a cronjob?

A: As of January 2013, there is no official way to delete temporary files, so imagemagic leaves you to do it yourself. I also use a cron job that runs every 20 minutes since the temporary files are 10+ GB in size.

A: It means your ImageMagick installation is NOT functioning properly!
The fact that it leaves magick-* files in tmp says that ImageMagick process died and that's why it didn't delete those files. You should configure memory limits etc. Refer http://www.imagemagick.org/script/resources.php

A: I've had this problem for a period of time, my code issue was that I didn't use the destroy function:
$im->destroy();

When calling the destroy function it will delete the temp files that are made under the /tmp directory.
This is for PHP and maybe it will help someone.

A: It is always better to use a task based approach and not to clog up the runtime with deleting stuff. just run the task once a day.


Q: Tkinter Scrollbar question (independent scrollable length indexed to custom range) I'm having trouble wording this properly.  What I'm looking to do is create a scrollbar that is indexed to a range I set that will return its position when it's moved/updated.  In the simplest form, let's just say I print the position of the bar each time it's updated.  Is there a way to accomplish this?  I assume it involves setting a custom range and some sort of sensitivity.
The ultimate plan is to use the scrollbar to scroll through a matplotlib chart with a time series as the x-axis, but I believe that will be easy enough once I get the scrollbar setup.
Thanks!
self.scroll = ttk.Scrollbar(self, orient="horizontal",
                            command=lambda e1, e2, e3=None:
                                self.scroll_update(e1, e2))

def scroll_update(self, action, val):
    if action == "moveto":
        print(val)
    elif action == "scroll":
        pass

A: As @jasonharper pointed out, it's much easier to use a Scale in your case:
from tkinter import *

on_update = lambda e: print(e)

#                          |in pixels| |resolution| |the slider, pixels| |switch value display
s=Scale(command=on_update, length=250, to=1000,     sliderlength=50,     showvalue=False)
s.pack()

print(s.get())
s.set(20) #  note, this also executes the "command" property

Hope that's helpful!


Q: Тормозит сервер, как определить и устранить причину? Сегодня в 11:30 на сервере появились тормоза, скрипты стали работать в 5-10 раз медленнее (никаких кардинальных изменений не вносилось). Временами отпускает, все возвращается на короткое время в норму, потом снова все начинает тормозить.
По статистике в Munin есть подозрение, что это из-за сетевой активности, но точно не могу сказать, нужна помощь знающего человека.
Какие нужны скриншоты и данные, чтобы понять в чем дело?
Данные с atop:

Данные с htop:

Данные netstat из Munin (спецэффекты начались с 11:30)

Данные с htop, память:

А это при вырубленном апаче

A: Установите atop, там наглядно будет видно. А вообще есть замечательная, наглядная схема.


Q: How to get range partition details from system catalogs I am looking for a solution that lists all the range partition information. Tried the below query.
 SELECT c.relname as partition_list,p.relname as parent_tbl FROM pg_inherits i JOIN pg_class p ON i.inhparent = p.oid
JOIN pg_class c ON i.inhrelid = c.oid WHERE  p.relkind IN ('r', 'p');

output
"testpartpartition_1"    "parentpartiontbl"
"testpartpartition_2"    "parentpartiontbl"

But since I created a range partition, want to know the range values for eg:
CREATE TABLE testpartpartition_1 PARTITION OF parentpartiontbl FOR VALUES FROM (1) TO (5)
CREATE TABLE testpartpartition_2 PARTITION OF parentpartiontbl FOR VALUES FROM (6) TO (10)

Want the output also which states startvalue and endvalue for each partition like below
child_partition            parent_tbl           min_rangeval      max_rangeval
 ---------------------------------------------------------------------------------
 "testpartpartition_1"    "parentpartiontbl"         1                  5
 "testpartpartition_2"    "parentpartiontbl"         6                  10

A: Since the partition boundaries are stored in binary parsed form, all you can do is deparse them:
SELECT c.oid::regclass AS child_partition,
       p.oid::regclass AS parent_tbl,
       pg_get_expr(c.relpartbound, c.oid) AS boundaries
FROM pg_class AS p
   JOIN pg_inherits AS i ON p.oid = i.inhparent
   JOIN pg_class AS c ON i.inhrelid = c.oid
WHERE p.relkind = 'p';

 child_partition │ parent_tbl │                                boundaries
═════════════════╪════════════╪══════════════════════════════════════════════════════════════════════════
 part_2022       │ part       │ FOR VALUES FROM ('2022-01-01 00:00:00+01') TO ('2023-01-01 00:00:00+01')
(1 row)

Analyzing the boundary string is left as exercise to the reader.

A: You can find the information in the relpartbound column of the system catalog pg_class. Use the function pg_get_expr() to get the data readable:
select
    relname as partition_table,
    pg_get_expr(relpartbound, oid) as partition_range
from pg_class
where relispartition
and relkind = 'r';

   partition_table   |       partition_range
---------------------+-----------------------------
 testpartpartition_1 | FOR VALUES FROM (1) TO (5)
 testpartpartition_2 | FOR VALUES FROM (6) TO (10)
(2 rows)

Use regexp_matches() to extract the numbers in parentheses
select
    relname as partition_table,
    matches[1] as min_rangeval,
    matches[2] as max_rangeval
from pg_class
cross join regexp_matches(pg_get_expr(relpartbound, oid), '\((.+?)\).+\((.+?)\)') as matches
where relispartition
and relkind = 'r';

   partition_table   | min_rangeval | max_rangeval
---------------------+--------------+--------------
 testpartpartition_1 | 1            | 5
 testpartpartition_2 | 6            | 10
(2 rows)

A: Here's the query that gets generated by \d+:
edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid)
        FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i
        WHERE c.oid = i.inhrelid AND i.inhparent = '33245'
        ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;
         oid         | relkind | inhdetachpending |         pg_get_expr
---------------------+---------+------------------+-----------------------------
 testpartpartition_1 | r       | f                | FOR VALUES FROM (1) TO (5)
 testpartpartition_2 | r       | f                | FOR VALUES FROM (6) TO (10)
(2 rows)

Looks like you need to use pg_get_expr() to decode the stuff in pg_class.relpartbound to reconstruct the range partition parameters.
You can also replace i.inhparent = '33245' with a subquery to query by parent table name:
edb=# SELECT c.oid::pg_catalog.regclass, c.relkind, false AS inhdetachpending, pg_catalog.pg_get_expr(c.relpartbound, c.oid)
        FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i
        WHERE c.oid = i.inhrelid AND i.inhparent = (SELECT oid from pg_class where relname = 'parentpartitiontbl')
        ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT', c.oid::pg_catalog.regclass::pg_catalog.text;


Q: Replace a full line every Nth line in a text file I'm trying to perform something that should be simple but I'm not quite understanding how to do it. I have a file that looks like this:
@A01182:104:HKNG5DSX3:3:1101:3947:1031 1:N:0:CATTGCCT+NATCTCAG
CNTCATAGCTGGTTGCACAGTTAACGTCGTTCAGGCCACGTTCCAGACCGTAGTTTGCCAGCGTCAGATCATAAACGGTGGTCACCAGGGCGGTGCTGCCA
+
F#FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFF,FFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:7997:1031 1:N:0:CATTGCCT+NATCTCAG
GNCGATCCCTTCGCTGCTGCTGGCAATTATCGTTGTAGCGTTTGCCGGACCGAGTTTGTCTCACGCCATGTTTGCTGTCTGGCTGGCGCTGCTGCCGCGTA
+
F#FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:5547:1047 1:N:0:CATTGCCT+NATCTCAG
GGTGATGATTGTCTTTGGCGCAACGTTAATGAAAGATGCGCCGAAGCAGGAAGTGAAAACCAGCAATGGTGTGGTGGAGAAGGACTACACCCTGGCAGAGT
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFF:FFFFFFFFFFFFFFFFFFFFFFFFFF
@A01182:104:HKNG5DSX3:3:1101:20726:1063 1:N:0:CATTGCCT+GATCTCAG
GGGACGCCCATTACGCTGGTGAATCTGGCAACCCATACCAGCGCCCTGCCCCGTGAACAGCCCGGTGGCGCGGCACATCGTCCGGTATTTGTCTGGCCAAC
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:FFFFFFFFFFFFFFF

and goes on for a lot of lines (The actual file is 2.5 Gb). What I want to do is to replace every fourth line (all those that have a lot of F's) for another string, the same for all.
I have tried with sed but I don't seem to be able to get the script right since I produce and output without changes.
Any help would be really appreciated!

A: This might work for you (GNU sed):
sed -i '4~4s/.*/another string/' file(s)

Starting at the 4th line and every 4 lines thereafter, replace the whole line with another string.

A: I'd use awk for this
awk '
    NR % 4 == 0 {print "new string"; next}
    {print}
' file > file.new && mv file.new file


Q: Getting error 'Microsoft.ACE.OLEDB.12.0' provider is not registered, however i was loading files earlier I am getting an error The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. However, I have loaded many files using same service two days earlier. Why this issue has started occuring.
My machine is 64 bit window 7 OS. Every project in .NET solution is configured for ANY CPU.

A: In the properties of your project try targeting x86 instead of AnyCPU:

Alternatively if you want to target AnyCPU you need to install the x64 bit Access OLEDB provider. You can download it from here.


Q: How to use and OR inside an AND operator for a where clause I would like my WHERE clause to evaluate the AND and the OR inside of an AND.
 SELECT
    ID,
    Name,
    CASE
        WHEN EXISTS (SELECT * FROM date_hired dh WHERE id = e.id
                                AND (
                                        (dh.datehired <= e.interview_start_date)
                                        OR
                                        (dh.datehired BETWEEN e.interview_start_date AND e.last_job_date)
                                    )
                    AND dh.office = 'Med-office'
                    )
    THEN 0 ELSE 1 END AS decision
FROM new_table n
JOIN old_table e ON e.id=n.id

A: Vertica is a mass data database, and it prefers more efficient joins and existence checks than correlated sub-selects - what an EXISTS predicate boils down to - and what results in a slowing-down nested loop.
Put the datehired check into a LEFT JOIN predicate with a Common Table Expression - in a WITH clause. If the joined table's columns are NULL, the matching id does not exist, so finally just check for being NULL.
WITH
dh AS (
  SELECT
    id
  , datehired
  FROM date_hired
  WHERE dh.office = 'Med-office'
)
SELECT
  id
, nam
, CASE WHEN dh.id IS NOT NULL
    THEN 1
    ELSE 0
  END AS decision
FROM new_table n
JOIN old_table e USING(id)
LEFT JOIN dh
  ON e.id = = dh.id
 AND (
   dh.datehired <= e.interview_start_date
  OR
   dh.datehired BETWEEN e.interview_start_date AND e.last_job_date
 )


Q: Node.js - Infinite Loop in Custom Code (Custom business logic) Hi I'm making a business application in which user can write his custom code and execute it.
How can i handle situations when the custom code generates infinite loops ?
A way is to handle each request in separate child process and kill that process on request completion but if there are  thousands of users this doesn't seem to be appropriate. What else can be done in such cases ?


Q: Which preposition to choose for referring to the means of doing an action (by, with, using, via, over)? What is the best option to say that I will send you an update and I will use email in order to do it? What sound more natural?

*

*I will send you an update later via email

*I will send you an update later over email

*I will send you an update later by email

*I will send you an update later with email

*I will send you an update later using email
The same question, but to say that a file was compressed, and rar was used to do it

*

*The file should be compressed via rar

*The file should be compressed by rar

*The file should be compressed with rar

*The file should be compressed using rar
Is there any rule?

A: Though all the prepositions you are suggesting  are used, the most common ones are by email and via email as shown here.
file compressed with is commonly used, other options like by  or using are fine.


Q: opencv user drawing rectangle to crop I am trying to get a user to be able to draw a rectangle around an object and crop it-
with this code--
def click_and_crop(event, x, y, flags, param):

global refPt, drawing, cropping

if event == cv2.EVENT_LBUTTONDOWN:
    drawing = True
    refPt = [(x, y)]
    cropping = True

elif event == cv2.EVENT_MOUSEMOVE:
    if drawing == True:
        cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)

elif event == cv2.EVENT_LBUTTONUP:
    drawing = False
    refPt.append((x, y))
    cropping = False

    cv2.rectangle(closeres, refPt[0], refPt[1], (0, 255, 0), 2)
    cv2.imshow("image", closeres)

it draws multiple rectangles not just one that changes size, it ends up looking like this-

anyone know how to fix this so it changes size instead?
if I change code to this-
elif event == cv2.EVENT_MOUSEMOVE:
    if drawing == True:
        closeres = cloneclone
        cv2.rectangle(closeres, refPt[0], (x,y),(0,255,0),2)

to try to erase the rectangle each time it changes i end up seeing nothing , no rectangle and get this message-
Traceback (most recent call last):
  File "project2.py", line 38, in click_and_crop
    cv2.rectangle(closeres, refPt[0], refPt1, (0, 255, 0), 2)
UnboundLocalError: local variable 'closeres' referenced before assignment

A: You have to draw the image each time at the start of your event hanling routine instead of inside the last if condition.
THEN draw the sizer rectangle. Otherwise the previous rectangle is not deleted. Image is progressively destroyed.
The higher the refresh rate, the greener your image becomes.
A possible optimization is to use a XOR mode so if you draw previous rectangle again it restores the image (but rectangle cannot be plain green in that case) but it is more complex


Q: Web caching when retrieving lists of documents We have a need to leverage client side resources for lists containing tasks.
The client needs to:

*

*be notified of updates to the list

*be able to re-order/filter the list (requesting an update from the server with tasks that the client does not know of/have in cache)

The problem comes on initial load or large list updates (changing from "tasks assigned to me" to "tasks regarding x")
The fastest thing to do is get all the tasks back in a list, instead of individual (10+) requests.
But E-tags will not help when I request an update to a task in the list, as it was not downloaded individually.
Is there some way of getting the browser to cache items in a list against their individual urls?
Or a way of creating a javascript cache that will survive a navigation away?

*

*If I navigate away, and go to the task url, will my js objects survive? I suspect no.

*If I navigate away, then hit back, will my javascript objects survive? I suspect yes.

*

*If so, is it possible to have a "task list load" page that will inspect the history and go back to the existing task list? I think no - security.

I'm thinking I'll just have to take the initial loading hits and individually retrieve tasks, so that later requests are fast (and take the load off the server).

A: In HTML5, there is the Window.sessionStorage attribute that is able to store content against a specific session within a tab/window (other windows will have their own storage, even when running against the same session).
There is also localStorage, and database Storage options available in the spec as well.

A: HTML5 is still a bit far away from being implemented, but you might be able to use Google Gears for your local storage needs.
Also, I've no idea how many simultaneous clients and tasks we're talking about, how big the tasks are and what strain such a request might put on the database, but I'd think you should be able to run smooth without any caching, 10+ requests doesn't seem that much.  If traffic is not the bottleneck, I would put caching on the server and keep the client 'dumb'.


Q: git add only some changed files I have a remote branch in Git called development and also local development branch. I modified lets say 3 files:
git status
modified file1
modified file2
modified file3

now I want to add and commit only file1 and push it to remote branch(file2 and file3 will be added later but not now). I try to push it but git doesn't allow to push because remote head is ahead than my local. Then I tried doing git fetch and git rebase but then, git says I have untracked files. Git suggested to stash them. I am new to git and what I know so far is git stash is to save the working changes in case of switching another branch. In my case I am not switching my branch. Is it safe to do proceed with git stash? or are there some other ways? I appreciate your explanations.

A: Before push, you need to commit your changes. It's done locally by:
#add files to specific commit
git add file1

# commit added files
git commit -m "init commit"

# stash file2 file3
git stash

# now, when working dir is clean you can safly pull updates from remote repo
git pull

# push your changes (your commit) to remote repo
git push origin master

#return file2 file3 changes
git stash apply

A: You can selectively stage files.
For example, let's say in the first commit you only wanted to use file1 and push only that:
git add file1
git commit -m "first bit of changes"
git push

With Git, you can stage files at a very granular level which allows you craft your commits in a logical way.
As for the other part of the question...

I try to push it but git doesn't allow to push because remote hed is
  ahed than my local

Yes, this is definitly a good use-case for stash.
Do this:
git stash
git pull
git stash pop


Q: Wireless connection error on windows xp professional I have windows xp professional. I installed and afterwards updated all network drivers but i still cannot connect to wifi (Ethernet works). Is there any way to solve this? Is there some problem with drivers itself, but when i updated them they remained same, that means that they are the one needed for wifi connection to be possible. Maybe I didn't install all drivers that are needed for wireless connection. Can someone give me a list all of them?

A: I have HP 530(Windows xp professional version 2002 service pack 3).
When I go to Network adapters this is what write there:

*

*Broadcom 802.11 b/g WLAN

*INTEL(R) PRO/100 VE Network Connection
When I try to connect to internet only thing that works is ethernet. And I can't connect wirelessly. It can't even see any wifi network in range(on the list of wireless networks, even when I refresh it).


Q: Finding the physical size of the touch digitizer in Windows 8.1 Question
How does one go about determing the physical size of the touch (or pen) digitizer in Windows 8.1 using the WinAPI?
Scenario
I'm using the GetPointerFrameTouchInfo() API which returns a POINTER_TOUCH_INFO struct with an embedded POINTER_INFO struct.
The POINTER_INFO struct has a ptHimetricLocation member which indicates the physical location of a touch with 10 uM resolution (which is way more consistent to work with for gesture recognition).
But, after doing some calculations using the ptHiMetricLocation, it's not possible to accurately find the corresponding pixel location without knowing the physical size of the digitizer.
Qualifier
To clarify, this is not a question about the physical screen size. It's about the touch digitizer (or the pen digitizer).

A: Okay, it turns out this is actually really easy, as long as you have a handle to the device. Just use the GetPointerDeviceRects() function =]


Q: Render observable in component while waiting for next value? I have a scenario were certain data may need to be refreshed on the server, but is a long running task.
What i need is to get the current state of the data and render it while I wait for the refreshed data from the server. I have a component that will render the obserable, while sending another call to refresh it. my getData service method looks like the following sudo code (creates a behavior subject with a false initial value, and then emits true to do the refresh)
behaviorsubject = new BehaviorSubject(false);

data$ = behaviorsubject.pipe(
  refresh => swichMap(httpclientcall?refresh=${refresh})
  .pipe(
    tap(res => {
     if(res.needsRefresh) behaviorsubject.next(true)
  })
)
return data$

This sort of works. However, my page does not render until the second http call is returned. In my componet, I use the following to determine if the component will render. I see the spinner until the refresh call completes.
<div *ngIf="data$ | async as data; else spinner">

The desired result
Component after inital http call:
Data from server: (status loading)

Component after refresh http call:
Data from server: up-to-date

What is the best way to have the first call in the observable complete so the component can render without waiting for the second. Hopefully I explained this well enough.

A: You can use merge to return an observable that has two sources that emit independently into the same stream.
In this case, you don't even need to use a subject:
data$ = http.get(url_1).pipe(
  switchMap(response1 => {
    const call1 = of(response1);
    const call2 = response1.needsRefresh ? http.get(url_2) : EMPTY;

    return merge(call1, call2);
  })
)


Q: get out data from promise function in angular I have this service file part of angular project , issue is I cant back value to main function from promise.then function .. here is the code
angular.module('starter.services', [])

.factory('Services', function ($http,$q) {

    var def = $q.defer();
  // Might use a resource here that returns a JSON array
    $http.get('JSONFILE').then(function (data) {
        def.resolve(data.data);
    });

this.result ={};
    var var1 = def.promise;
            var1.then(function (data){
                this.result = data;
                console.log(this.result);
            });

    // Some fake testing data
  console.log(this.result);

        return {
            all: function () {
                return var1;
            },
            remove: function (service) {
                var1.splice(var1.indexOf(service), 1);
            },
            get: function (serviceId) {
                for (var i = 0; i < var1.length; i++) {
                    if (var1[i].id === parseInt(serviceId)) {
                        return var1[i];
                    }
                }
                return null;
            }
        };

});

this.result will return empty object outside promise.then but get right data inside it.

A: Actually, if you are talking about this log statement here:
// Some fake testing data
console.log(this.result);

The reason why this.result doesn't have the same data is because the Promise is probably still pending (fulfilling the promise).
I suspect when you see these console logs, you see the one outside the Promise display first. This is to be expected.

Also, your block scope is different, meaning this.result can be different inside that Promise context.
Try changing:
this.result = {};

to:
var result = {};

And also change
var1.then(function (data){
    result = data;
    console.log(result);
});


Q: How do I turn this oddly formatted looped print function into a data frame with similar output? There is a code chunk I found useful in my project, but I can't get it to build a data frame in the same given/desired format as it prints (2 columns).
The code chunk and desired output:
import nltk
import pandas as pd
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')

# Step Two: Load Data

sentence = "Martin Luther King Jr. (born Michael King Jr.; January 15, 1929 – April 4, 1968) was an American Baptist minister and activist who became the most visible spokesman and leader in the American civil rights movement from 1955 until his assassination in 1968. King advanced civil rights through nonviolence and civil disobedience, inspired by his Christian beliefs and the nonviolent activism of Mahatma Gandhi. He was the son of early civil rights activist and minister Martin Luther King Sr."

# Step Three: Tokenise, find parts of speech and chunk words

for sent in nltk.sent_tokenize(sentence):
  for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
     if hasattr(chunk, 'label'):
        print(chunk.label(), ' '.join(c[0] for c in chunk))

Clean Output of tag in one column and entity in another:
PERSON Martin
PERSON Luther King
PERSON Michael King
ORGANIZATION American
GPE American
GPE Christian
PERSON Mahatma Gandhi
PERSON Martin Luther

I tried something like this, but the results are not nearly as clean.
for sent in nltk.sent_tokenize(sentence):
  for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
     if hasattr(chunk, 'label'):
        df.append(chunk)

Output:
    [Tree('PERSON', [('Martin', 'NNP')]),
 Tree('PERSON', [('Luther', 'NNP'), ('King', 'NNP')]),
 Tree('PERSON', [('Michael', 'NNP'), ('King', 'NNP')]),
 Tree('ORGANIZATION', [('American', 'JJ')]),
 Tree('GPE', [('American', 'NNP')]),
 Tree('GPE', [('Christian', 'JJ')]),
 Tree('PERSON', [('Mahatma', 'NNP'), ('Gandhi', 'NNP')]),
 Tree('PERSON', [('Martin', 'NNP'), ('Luther', 'NNP')])]

Is there a easy way to change the print format to df with just 2 columns??

A: Create nested lists and convert to DataFrame:
L = []
for sent in nltk.sent_tokenize(sentence):
  for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
     if hasattr(chunk, 'label'):
        L.append([chunk.label(), ' '.join(c[0] for c in chunk)])

df = pd.DataFrame(L, columns=['a','b'])
print (df)
              a               b
0        PERSON          Martin
1        PERSON     Luther King
2        PERSON    Michael King
3  ORGANIZATION        American
4           GPE        American
5           GPE       Christian
6        PERSON  Mahatma Gandhi
7        PERSON   Martin Luther

In list comperehension solution is:
L= [[chunk.label(), ' '.join(c[0] for c in chunk)]
     for sent in nltk.sent_tokenize(sentence)
     for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent)))
     if hasattr(chunk, 'label')]

df = pd.DataFrame(L, columns=['a','b'])


Q: Use an external database in Django app on Heroku I am trying to deploy a Django REST API on Heroku. Normally I wouldn't have any issues with this but for this app, I am using a legacy database that exists on AWS. Is it possible for me to continue to use this remote database after deploying Django to Heroku? I have the database credentials all set up in settings.py so I would assume that it should work but I am not sure.

A: It should not pose any problem to connect with an database on AWS.
But be sure that the database on AWS is configured to accept external access, so that Heroku can connect.
And I would sugest that you take the credentials out of the source code and put it in the Config Vars that Heroku provide (environment variables).

A: Will it work? I think yes, provided you configure your project and database for external access.
Should you want it? How may queries does an average page execute? Some applications may make tens of queries for every endpoint and added wait can combine into seconds of waiting for every request.


Q: How to handle user comments in a database I was planning to store user comments in a database and was wondering how to store the raw text that users will provide since it could contain anything. What is a common/good practice in regards to this? Do I need to parse the text or is there a special storage type that I should be using? It seemed like a lot of overhead to be parsing user comments that could potentially be quite long and I don't want to be tampering with the intended meaning of a message etc. It seemed strange to be treating a comment/forum post in the same manor as say a username/password and sanitize.
I am using sqlite3 and some scripts to query the db and was planning on implementing something along the lines of:
page_id    post_number    username    content
-------    -----------    --------    -------
1          1              user_23     blah there's blah "quote" blah;':".,-=.

But, of course, if I was to just expand my content param into my INSERT query, there is going to be all kinds of problems with ' " etc.
How should I be handling the content in this table; should it even be in the table like this? What data type should I be using etc.

A: To avoid SQL injection attacks, to make formatting of query strings easier, and to make handling of blob data possible, all databases support parameters.
In Python, it would look like this:
id = 1
text = "blah ..."
cursor.execute("INSERT INTO mytable(id, content) VALUES(?, ?)", (id, text))

A: The data type to use depends on the overall size of the input.
Text would be my first choice.
for more on sqlite3 datatypes see
http://www.sqlite.org/datatype3.html
I would recommend you
Sanitize the input, only allow necessary markup.
Encode the content so it's safe to insert into the database.
If security is a serious concern this processing should be done server side. It won't hurt to put some of this processing load to javascript this will reduce the work done at the server. Tho it would still catch user(s) trying to circumvent the feature.

A: I'm not into python, but doesn't your DB driver take care of it already? Otherwise, you have to replace escape those characters manually.
Take a look at this thread:
How to string format SQL IN clause with Python


Q: Дерево из таблицы Есть таблица вида id, name, parent_name. Как по ней построить дерево, или хотя бы отсортировать по иерархии сверху-вниз? Заранее спасибо!

A: Иерархию в SQL можно организовывать множеством методов. Один из простых - добавления поля пути http://www.onlamp.com/pub/a/onlamp/2004/08/05/hierarchical_sql.html


Q: Android custom camera issue in some devices Hi, I have a custom camera where I have click button, when clicked it captures the image... Everything is fine but in some devices the preview is stretching and also the preview is overlaying half the screen and flickering... some wierd unwanted effect. How to fix this?
This is my code:
Camera Activity:
preview = new Preview(this, (SurfaceView) findViewById(R.id.surfaceView));

preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

((FrameLayout) findViewById(R.id.preview)).addView(preview);

preview.setKeepScreenOn(true);

buttonClick = (Button) findViewById(R.id.buttonClick);

buttonClick.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
        camera.takePicture(shutterCallback, rawCallback, jpegCallback);
        // camera.setDisplayOrientation(90);
        }
});

Preview class:
class Preview extends ViewGroup implements SurfaceHolder.Callback {
    private final String TAG = "Preview";

    SurfaceView mSurfaceView;
    SurfaceHolder mHolder;
    Size mPreviewSize;
    List<Size> mSupportedPreviewSizes;
    Camera mCamera;

    @SuppressWarnings("deprecation")
    Preview(Context context, SurfaceView sv) {
        super(context);

        mSurfaceView = sv;
        // addView(mSurfaceView);

        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {

            // get Camera parameters
            Camera.Parameters params = mCamera.getParameters();

            mSupportedPreviewSizes = params.getSupportedPreviewSizes();
            requestLayout();

            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                // set the focus mode
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                // set Camera parameters
                mCamera.setParameters(params);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // We purposely disregard child measurements because act as a
        // wrapper to a SurfaceView that centers the camera preview instead
        // of stretching it.
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2);
            }
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        if (mCamera != null) {
            mCamera.stopPreview();
        }
    }

    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null)
            return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        if (mCamera != null) {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            requestLayout();

            mCamera.setParameters(parameters);
            mCamera.startPreview();
        }
    }

}

A: There is a known bug happening on some devices for the image captures described here:
https://code.google.com/p/android/issues/detail?id=1480
Not sure if your problem is the same, but you should try the code explained in this answer from another question:
https://stackoverflow.com/a/1932268/2206688

A: McAfee Antivirus may be the culprit in this case.
In which case, uninstalling it should solve the issue.


Q: Is this set a manifold?.... Let $A=\{x\in\mathbb{R}^n:x=cy, y\in M, c\in\mathbb{R}\setminus \{0\}\}$, where $M\subset\mathbb{R}^n$ is a manifold of dimension $d$. Note that $A$ determines the geometric shape that is always proportional to a shape determined by $M$, the scaling factor can be arbitrary. For example, if $M$ denotes the set of triangles with three prescribed edge lengths, then $A$ is the set of all triangles that are similar to triangles determined by $M$.
I think $A$ may have $d+1$ degrees of freedom since the geometric shape determined by $A$ can be magnified or reduced. I want to make sure that whether $A$ is a manifold of dimension $d+1$, how to prove it?

A: I think $x=ca$ is not well-defined , so you could rather write
$A =(\mathbb{R}\setminus0)\times M$ where you interpret the ordered pair $(c,m)$ as the object you originally wrote as $cm$.
Now observe, that $\mathbb{R}\setminus$ 0 and $M$ are manifolds and thus their cartesian product is too.
Hope that helps you!


Q: How to get the number of tasks that need to be executed right now on celery? I am using celery with two types of tasks

*

*Tasks that need to be executed with 0 delay

*Tasks that need to be executed with some delay (countdown or eta)

I am trying to autoscale my celery cluster and I need to know how many tasks are present in the queue right now to be executed.
When I inspect rabbitmq, I get both tasks to be executed and tasks scheduled.
I am not able to figure out the current load on celery so that I can decide on the number of worker nodes.
Only thing I can think of is to use the API /api/queues/vhost/name/get - this will alter the queue and I do not want that.


Q: Sqlite 3 on Windows, records not viewable to other users when stored as Administrator? we use Sqlite 3 on windows to store our sync applications logs and state. Applications are written in c#, .net 4.5 and executed as windows services and/or console. We also use sqlite3.exe for debugging / log viewer.
Recently we found a odd thing, records generated by the windows services was not viewable from the sqlite3.exe tool, unless started as "Administrator". Services are running as "Local System".
I'v also tested to generate records by starting our console app as "Administrator". These records can then only be viewed in sqlite3.exe when started as "Administrator", otherwise they are "invisible". The same occurs when application is started as "normal" user (not as "Administrator" that is).
All application use the same database file, and during this testing file/folder security is set to "Everyone has full control".
Is this behavior by design, or I'm missing something here?


Q: Regex - Match word/letters underneath a specific pattern Very unusual one but I'm trying to match output from an SSH session that may collapse view and fall underneath the output required (like a collapsed column)...
Take a look at the example output:
      System Id     Interface          Circuit Id        State HoldTime Type     PRI
--------------------------------------------------------------------------------
rtr1.lab01.some GE0/0/1            0000000001         Up   22s      L2       --
thing
rtr2.lab01.some GE0/0/2            0000000002         Up   24s      L2       --
thingelse

I can match the the first line with:

^([a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9])

which returns (rtr1.lab01.some and rtr2.lab01.some) but I'm trying to find the easiest way to match it based on the full hostname (rtr1.lab01.something and rtr2.lab01.somethingelse)
I'm also matching the rest of the output perfectly fine and able to extract the data but really can't find a way to achieve what I'm trying... Can someone point me in the right direction? To expand further (for more context... I'm using the Google TextFSM in Python to match all this data from an SSH session)

A: import re

text = """System Id     Interface          Circuit Id        State HoldTime Type     PRI
--------------------------------------------------------------------------------
rtr1.lab01.some GE0/0/1            0000000001         Up   22s      L2       --
thing
rtr2.lab01.some GE0/0/2            0000000002         Up   24s      L2       --
thingelse
rtr2.lab01.abcd GE0/0/4            0000000003         Up   24s      L2       --
rtr2.lab01.none GE0/0/24           0000000004         Up   24s      L2       --
sense
rtr2.lab01.efgh GE0/0/5            0000000003         Up   24s      L2       --
"""

lines = text.rstrip().split('\n')[2:]
n_lines = len(lines)
current_line = -1

def get_next_line():
    # Actual implementation would be reading from a file and yielding lines one line at a time
    global n_lines, current_line, lines
    current_line += 1
    # return special sentinel if "end of file"
    return  lines[current_line] if current_line < n_lines else '$'

def get_system_id():
    line = None
    while line != '$': # loop until end of file
        if line is None: # no current line
            line = get_next_line()
            if line == '$': # end of file
                return
        m = re.search(r'^([a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9])', line)
        id = m[1]
        line = get_next_line() # might be sentinel
        if line != '$' and re.match(r'^[a-zA-Z0-9]+$', line): # next line just single id?
            id += line
            line = None # will need new line
        yield id

for id in get_system_id():
    print(id)

Prints:
rtr1.lab01.something
rtr2.lab01.somethingelse
rtr2.lab01.abcd
rtr2.lab01.nonesense
rtr2.lab01.efgh

See Python Demo


Q: Sync plugin settings (wp_options table) on multiple environments How do you guys handle database changes, more specifically the settings (wp_options)?
Im looking for something like, having a JSON file (or migration files bit similar like Laravel) with settings, that I can run after a deployment.
For example once I install WooCommerce I have a list with default settings (presets) I want to use and import at once. But also once I add a new feature or plugin that I can migrate those settings across multiple environments.
Would be cool if that JSON file (or settings file) is environment based. So I can use test payment method settings on local and live settings on production. And just run a command like wp migrate options or something in my deployment script, which sets all the correct settings for that environment.
Is there something like that?
Thanks in advance :)

A: This is a tricky one since even if you might get it to work with Core with plugins you never know if they also store data in files, custom tables, post types and so in. If you then only sync the options table you might get inconsistent/partial/broken states.
Also you probably don't want to sync everything since some things like transients are on the options table but aren't really settings.
This is a general problem with systems that store configuration in the database and even more so with WP since the data storage formats are somewhat fragile.
If you search the web or this site you'll see that there have been plenty of questions and attempts of approaching this. But there is no general best practice solution to it.
Having said that, concerning your specific request you can have a look at https://github.com/danielbachhuber/dictator which looks like it is unmaintained but might give you a head start on one possible approach.


Q: System.IO.File.Delete throws "The process cannot access the file because it is being used by another process" Every time I save a file and delete it right away using the function below, I keep getting this error message: "System.IO.IOException: The process cannot access the file because it is being used by another process".
Waiting for a couple of minutes or closing visual studio seems to only unlock the files that you uploaded previously.
public static bool DeleteFiles(List<String> paths)
{ // Returns true on success
    try
    {
        foreach (var path in paths)
        {
            if (File.Exists(HostingEnvironment.MapPath("~") + path))
                File.Delete(HostingEnvironment.MapPath("~") + path);
        }
    }
    catch (Exception ex)
    {
        return false;
    }
    return true;
}

I think that the way I'm saving the files may cause them to be locked. This is the code for saving the file:
            if (FileUploadCtrl.HasFile)
            {
                filePath = Server.MapPath("~") + "/Files/" + FileUploadCtrl.FileName;
                FileUploadCtrl.SaveAs(filePath)
            }

When looking for an answer I've seen someone say that you need to close the streamReader but from what I understand the SaveAs method closes and disposes automatically so I really have no idea whats causing this

A: After some testing, I found the problem. turns out I forgot about a function I made that was called every time I saved a media file. the function returned the duration of the file and used NAudio.Wave.WaveFileReader and NAudio.Wave.Mp3FileReader methods which I forgot to close after I called them
I fixed these issues by putting those methods inside of a using statement
Here is the working function:
public static int GetMediaFileDuration(string filePath)
{
    filePath = HostingEnvironment.MapPath("~") + filePath;

    if (Path.GetExtension(filePath) == ".wav")
        using (WaveFileReader reader = new WaveFileReader(filePath))
            return Convert.ToInt32(reader.TotalTime.TotalSeconds);

    else if(Path.GetExtension(filePath) == ".mp3")
        using (Mp3FileReader reader = new Mp3FileReader(filePath))
            return Convert.ToInt32(reader.TotalTime.TotalSeconds);

    return 0;
}

The moral of the story is, to check if you are opening the file anywhere else in your project

A: I think that the problem is not about streamReader in here.
When you run the program, your program runs in a specific folder. Basically, That folder is locked by your program. In that case, when you close the program, it will be unlocked.
To fix the issue, I would suggest to write/delete/update to different folder.
Another solution could be to check file readOnly attribute and change this attribute which explained in here
Last solution could be using different users. What I mean is that, if you create a file with different user which not admin, you can delete with Admin user. However, I would definitely not go with this solution cuz it is too tricky to manage different users if you are not advance windows user.


Q: Form в Laravel 5.7, как отследить какая кнопка была нажата в контроллере? Есть форма, содержащая 3 Кнопки Submit. Можно ли, в контроллере, отследить какая кнопка была нажата?
Пробовал с помощью if ($request->Block) {}, но ничего не вышло.

<form action="" method="POST">
@csrf

    <button type="submit" class="btn btn-outline-info" name="Block">Block</button>
    <button type="submit" class="btn btn-outline-success" name="Unlock">Unlock</button>
    <button type="submit" class="btn btn-outline-danger delete" name="Del">Del</button>

                Select
                    <input type="checkbox" class="form-check-input" id="All" style="margin-left: 5px;">

                Name
                Date Online
                Date Register

    @foreach ($users as $user)

                    <input type="checkbox" class="form-check-input" id="{{$user->id}}" name="selectuser{{$user->id}}" style="margin-left: 5px;">

                {{$user->name}}
                {{$user->last_entrance}}
                {{$user->created_at}}

    @endforeach

</form>

A: В форме сделайте следующие изменения:

        <button type="submit" class="btn btn-outline-info" name="submit_key" value="block">Block</button>
        <button type="submit" class="btn btn-outline-success" name="submit_key" value="unlock">Unlock</button>
        <button type="submit" class="btn btn-outline-danger delete" name="submit_key" value="del">Del</button>

В контроллере это можно будет обработать следующим образом:
switch(request('submit_key')) {
    case 'block': // нажата кнопка Block
    break;
    case 'unlock': // нажата кнопка Unlock
    break;
    case 'del': // нажата кнопка Del
    break;
}


Q: Infer typescript function arguments Given the following
const action1 = (arg1: string) => {}
const action2 = (arg1: string, arg2: {a: string, b: number}) => {}
const actions = [action1, action2]
handleActions(actions)

... elsewhere ...

const handleActions = (actions: WhatTypeIsThis[]) => {
  const [action1, action2] = actions;
  action1(/** infer string */)
  action2(/** infer string and object */)
}

How can I define the WhatTypeIsThis type in order for the action args to be inferable inside handleActions?
Is it possible to define it in such a way that actions can be any number of functions with varying argument lists?
Is it possible using generics?
My solution:
I've marked the accepted answer because it was the inspiration for my solution.
// get the types of the actions, defined in outer scope
type GET = typeof api.get;
type CREATE = typeof api.create;
...

// in controller
handleActions([api.getSomething, api.create])

...

// in service handler
const handleActions = (actions: [GET, CREATE]) => {
  const [action1, action2] = actions;
  // now we have all input / output type hints
}

This approach lets me isolate my logic from the http server, auth, and everything else I didn't write, so I can test the complexity within my service handlers in peace.

A:
Is it possible to define it in such a way that actions can be any number of functions with varying argument lists?

With a dynamic list, you need runtime checking. I don't think you can do runtime checking on these functions without branding them (I tried doing it on length since those two functions have different lengths, but it didn't work and it really wouldn't have been useful even if it had — (arg1: string) => void and (arg1: number) => void are different functions with the same length).
With branding and a runtime check, it's possible:

*

*Define branded types for the functions

*Create the functions

*Define the action list as an array of a union of the function types

*Have handleActions branch on the brand

Like this:
type Action1 = (
    (arg1: string) => void
) & {
    __action__: "action1";
};

type Action2 = (
    (arg1: string, arg2: {a: string, b: number}) => void
) & {
    __action__: "action2";
};

const action1: Action1 = Object.assign(
    (arg1: string) => {},
    {__action__: "action1"} as const
);
const action2: Action2 = Object.assign(
    (arg1: string, arg2: {a: string, b: number}) => {},
    {__action__: "action2"} as const
);

const actions = [action1, action2];

type ActionsList = (Action1 | Action2)[];

const handleActions = (actions: ActionsList) => {
    const [action1, action2] = actions;
    if (action1.__action__ === "action1") {
        action1("x");   // <==== infers `(arg: string) => void` here
    }
};

handleActions(actions);

Playground link

Before you added the text quoted at the top of the answer, it was possible with a readonly tuple type. I'm keeping this in the answer in case it's useful to others, even though it doesn't apply to your situation.
Here's what that looks like:
type ActionsList = readonly [
    (arg1: string) => void,
    (arg1: string, arg2: { a: string; b: number; }) => void
];

To make it readonly, you'll need as const on actions:
const actions = [action1, action2] as const;
//                                ^^^^^^^^^

A tuple  is a kind of "...Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions." (from the link above)
Playground link


Q: Python Selenium CAN't scroll down users anymore             browser.execute_script("""
                var scrollt = document.querySelector('div[role="dialog"] ._aano')
                scrollt.scrollTop = scrollt.scrollHeight
                """)

This code for scrolling down a user followers at instagram is not working anymore.
I made it for a python selenium instagram code and after i access the user followers, on a pop up winddow, instagram changed something and this broke up :(
Any recomendation?


Q: Using Trusted Web Activity to link multiple websites with native application I've managed to link my native application to a website and launch the same on a button click. As the website is trusted, the URL bar is not visible. In the launched website there is a button which then further redirects to another website. I've created a digital asset link for both and have added the JSON file in <websitename>/.well-known/<json-file>.
Both the websites have also been referenced in strings.xml under
asset_statements. However, on launching the first website and then redirecting to the second website from the first, the second website launches as a regular custom chrome tab with the URL bar visible.
Is it possible to hide both the URL's? If so, how?

A: To enable multi-domain, you need to check 3 things

*

*Each origin has a .well-known/assetlinks.json file

*The android asset_statements contains all origins

*Tell the Trusted Web Activity about additional origins when launching.

It seems you have the first two points covered, but not the last one.
Using the support library LauncherActivity:
If using the LauncherActivity that comes with the library, you can provide additional origins by updating the AndroidManifest:

*

*Add a list of additional origins to res/values/strings.xml:

<string-array name="additional_trusted_origins">
    <item>https://www.google.com</item>
</string-array>

*Update AndroidManifest.xml:

<activity android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"
    android:label="@string/app_name">

    <meta-data
        android:name="android.support.customtabs.trusted.ADDITIONAL_TRUSTED_ORIGINS"
        android:resource="@array/additional_trusted_origins" />

    ...
</activity>

Using a custom LauncherActivity
If using your own LauncherActivity, launching with additional origins can implemented like this:
public void launcherWithMultipleOrigins(View view) {
  List<String> origins = Arrays.asList(
      "https://checkout.example.com/"
  );

  TrustedWebActivityIntentBuilder builder = new TrustedWebActivityIntentBuilder(LAUNCH_URI)
      .setAdditionalTrustedOrigins(origins);

  new TwaLauncher(this).launch(builder, null, null);
}

Resources:

*

*Article with more details here: https://developers.google.com/web/android/trusted-web-activity/multi-origin

*Sample multi-origin implementation: https://github.com/GoogleChrome/android-browser-helper/tree/master/demos/twa-multi-domain


Q: my caption on my image goes out of position each time i uses $.(class).loaded(); i have a thumbnail image, on hover it will transit out the caption.
HTML

jane
Featured Portfolio1

CSS
.caption{
height:90px;
margin:0px;
margin-left:-30px;
}

.container .img_thumb_holder h2 span {
    color: white;
    font: bold 20px/30px Helvetica, Sans-Serif;
    letter-spacing: -1px;
    padding: 10px;
}

.container .img_thumb_holder h2 span.spacer {
    padding:0 5px;
}

JS
$(function() {
    $("h2")
    .wrapInner("")
    $("h2 br")
    .before("")
    .after("");
});

i am using ajax to load 3 different pages, all are showing thumbnails, and this code is shared among 3 pages, but each time i $.load another page my caption position will be off, the more pages i load, the more it goes off. Any idea?

A: It's hard to see without getting a look on the complete code. But every time your JS runs, you wrap every h2 element with a span. And then for every br-tag that is inside a h2-tag, it adds spans before and after.
A more robust way to do this would be to have the captions already in place and and with the correct CSS. But the captions are hidden (display:none;). Then you can load your data in to them and just do $(".caption").show(); on completion/success of your ajax callback.
Good luck :)


Q: WPF Button Command not firing, what am I missing? I feel bad posting this because I see a ton of similar posts, but after going through them all I can't quite diagnose my issue still. What I have is a WPF app designed with the MVVM pattern and using a RelayCommand() implementation for commands.
In my user control's XAML I set the data context here :
<UserControl.DataContext>
    <viewModel:SidePanelViewModel />
</UserControl.DataContext>

Then further down in the XAML I have this snippet where I assign a button's command
<TextBlock FontWeight="Bold" Margin="0,0,0,10">Service List</TextBlock>
<ListBox MaxHeight="100"
        ItemsSource="{Binding ServiceList}"
        SelectedItem="{Binding ServiceToRemove}">
</ListBox>
<Button HorizontalAlignment="Left" Width="60" Margin="0,10"
        Command="{Binding RemoveServiceCommand}">Remove</Button>

I am binding the button to the Command RemoveApplicationCommand which I define in the SidePanelViewModel here :
public ICommand RemoveServiceCommand
{
    get { return new RelayCommand(RemoveService, CanRemoveService); }
}

private void RemoveService()
{
    ServerList.Remove(ServiceToRemove);
}

private bool CanRemoveService()
{
    return true;
}

The problem
If I debug, the getter for RemoveServiceCommand will be reached when the button starts up, but when I click the button the code doesn't reach it. I had a very similar implementation (or so I think) working before, so this is really puzzling me. How can I get the command to fire on click?

A: Command="{Binding RemoveApplicationCommand}"

Did you mean RemoveServiceCommand?

A: Turns out the debugger was going over RemoveService the entire time but I had not put a breakpoint there. I had a wrong name in my RemoveService implementation ServerList.Remove() should have been ServiceList.Remove(). I assumed the debugger would hit a breakpoint in the RemoveServiceCommand property's getter but it turns out it doesn't hit that when you click the button.

A: You're returning a new RelayCommand in your getting, but not saving / caching the instance. Save it in a member variable.
if (_cmd == null)
   _cmd = new ....

return _cmd;

A: Try implementing like this
   private ICommand finishCommand;

        public ICommand FinishCommand
        {
            get
            {
                if (this.finishCommand == null)
                {
                    this.finishCommand = new RelayCommand<object>(this.ExecuteFinishCommand, this.CanExecutFinishCommand);
                }

                return this.finishCommand;
            }
        }

private void ExecuteFinishCommand(object obj)
        {
}
 private bool CanExecutFinishCommand(object obj)
        {
            return true;
        }


Q: How to view hidden files in Nautilus in Debian 9 I'm getting up and running with Debian 9, but can't find a way to view hidden files (files that begin with a period) in folders via the default Debian file manager. With Ubuntu it was as simple as checking a box in the Nautilus preferences, but I can't find that option in Debian 9:

Note: Please don't answer that I should use ls -a, i want to be able to quickly see hidden files in the GUI. Also, I'd prefer not to completely change my file manager to, say, KDE. thanks!

A: Just click (ctr+h) on keyboard.