text:
Q: How to refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed
*

*How to refactor this function to reduce the complexicity

*When I am using switch case at that time code complixity is more so how to reduce it

How to achive this

var has = Object.prototype.hasOwnProperty

var toString = Object.prototype.toString

function isEmpty(val) {

  if (val == null) return true
  if ('boolean' == typeof val) return false
  if ('number' == typeof val) return val === 0
  if ('string' == typeof val) return val.length === 0
  if ('function' == typeof val) return val.length === 0
  if (Array.isArray(val)) return val.length === 0
  if (val instanceof Error) return val.message === ''
  if (val.toString == toString) {
    switch (val.toString()) {
      case '[object File]':
      case '[object Map]':
      case '[object Set]': {
        return val.size === 0
      }
      case '[object Object]': {
        for (var key in val) {
          if (has.call(val, key)) return false
        }

        return true
      }
    }
  }
  return false
}
module.exports = isEmpty

A: I recently gave an answer to a very similar question going a little more into detail about how cognitive complexity works (see https://stackoverflow.com/a/62867219/7730554).
But in general, I think it is important to understand that cognitive complexity is increased even more if there are nested conditions. This calculation is done this way because the human brain can deal a lot better with statements written in sequence rather than with nested conditions. So for each conditional statement (if, switch, for loop, etc.) there will be a +1 added to the complexity value. But for each nested condition another +1 is added on top of the last level. That means, an if inside an if will not only add +1, but +2. An if, inside an if, inside an if will than result in +1 for the first if, +2 for the second and +3 for the third if condition. If you want to dig deeper into this I recommend taking a look at: https://www.sonarsource.com/docs/CognitiveComplexity.pdf
So let's analyze where the high complexity values from your method originate first:
function isEmpty(val) {
    if (val == null) return true // +1
    if ('boolean' == typeof val) return false // +1
    if ('number' == typeof val) return val === 0 // +1
    if ('string' == typeof val) return val.length === 0 // +1
    if ('function' == typeof val) return val.length === 0 // +1
    if (Array.isArray(val)) return val.length === 0 // +1
    if (val instanceof Error) return val.message === '' // +1
    if (val.toString == toString) { // +1
        switch (val.toString()) { // +2
            case '[object File]':
            case '[object Map]':
            case '[object Set]': {
                return val.size === 0
            }
            case '[object Object]': {
                for (var key in val) { // +3
                    if (has.call(val, key)) return false // +4
                }

                return true
            }
        }
    }
    return false
}

If you look at the comments I added you can easily see where the most problematic code concerning cyclomatic complexity is located. This also relates to the human readabilty of the code.
So one simply step to increase readability and at the same time reduce congnitive complexity is to look for options of "early returns".
To illustrate this, I simply inverted the statement *if (val.toString == toString)" to immediately return false if *val.toString != toString":
function isEmpty(val) {
    if (val == null) return true // +1
    if ('boolean' == typeof val) return false // +1
    if ('number' == typeof val) return val === 0 // +1
    if ('string' == typeof val) return val.length === 0 // +1
    if ('function' == typeof val) return val.length === 0 // +1
    if (Array.isArray(val)) return val.length === 0 // +1
    if (val instanceof Error) return val.message === '' // +1
    if (val.toString != toString) { // +1
        return false;
    }

    switch (val.toString()) { // +1
        case '[object File]':
        case '[object Map]':
        case '[object Set]': {
            return val.size === 0
        }
        case '[object Object]': {
            for (var key in val) { // +2
                if (has.call(val, key)) return false // +3
            }
            return true
        }
    }
}

Now the last switch statement can be executed outside the if statement and we reduced the nesting level by one. With that simple change the cognitive complexity has now dropped to 14 instead of 17.
You could then even go a step further and change the last case statement by extracting the return value into a variable and either extract a separate method out of the code block. This would reduce the complexity of the isEmpty() method even more.
And besides from extracting a method you can also use a declarative approach and use, for instance the Array method find() which would reduce the cognitive complexity even more.
To illustrate the idea I did both:
function isEmpty(val) {
    if (val == null) return true // +1
    if ('boolean' == typeof val) return false // +1
    if ('number' == typeof val) return val === 0 // +1
    if ('string' == typeof val) return val.length === 0 // +1
    if ('function' == typeof val) return val.length === 0 // +1
    if (Array.isArray(val)) return val.length === 0 // +1
    if (val instanceof Error) return val.message === '' // +1
    if (val.toString != toString) { // +1
        return false;
    }

    return checkForComplexTypes(val)
}

function checkForComplexTypes(val) {
    var result = null
    switch (val.toString()) { // +1
        case '[object File]':
        case '[object Map]':
        case '[object Set]': {
            result = val.size === 0
        }
        case '[object Object]': {
            result = Object.keys(val).find(key => has.call(val, key))
        }
        return result
    }
}

This should bring down the cognitive complexity of the isEmpty() method to 8 and the whole code including the extracted checkForComplexTypes() function to a complexity score of 9.
Note: JavaScript is not my major language at the moment so I cannot fully guarantee the correctness of the last refactoring step.

A: If you cannot split the function or use OOP approach, you can use array of functions and iterate over it:

const has = Object.prototype.hasOwnProperty;
const toString = Object.prototype.toString;

function isEmpty(val) {
    let isEmpty = null;

    const checkFunctions = [
        (val) => 'boolean' === typeof val ? false : null,
        (val) => 'number' === typeof val ? val === 0 : null,
        (val) => ['string', 'function'].includes(typeof val) ? val.length === 0 : null,
        (val) => Array.isArray(val) ? val.length === 0 : null,

        (val) => val instanceof Error ? val.message === '' : null,

        (val) => val.toString == toString && ['[object File]', '[object Map]', '[object Set]'].includes(val.toString()) ? val.size === 0 : null,
        (val) => {
            if (val.toString == toString && val.toString() === '[object Object]') {
                for (var key in val) {
                    if (has.call(val, key)) return false
                }
                return true;
            }
        }
    ];

    for (let i = 0; i < checkFunctions.length; i++) {
        isEmpty = checkFunctions[i](val);
        if (isEmpty !== null) {
            return isEmpty;
        };
    }
}

console.log(isEmpty(''), true);
console.log(isEmpty('Hallo'), false);
console.log(isEmpty(0), true);
console.log(isEmpty(1), false);
console.log(isEmpty({}), true);
console.log(isEmpty({a: 1}), false);

You can also extend core types of JS and then instead of isEmpty(val) write val.isEmpty(). For example:

String.prototype.isEmpty = function() {return this.length === 0}
Array.prototype.isEmpty = function() {return this.length === 0}

console.log("".isEmpty(), true);
console.log("foo".isEmpty(), false);
console.log([].isEmpty(), true);
console.log([1,2,3].isEmpty(), false);


text:
Q: Filter elements from a list instance (or object) in a single expression While using os.walk which needs me to alter the generated list of directories in order to filter them I wonder whether there is a nice way to do it:
for path, dirs, files in os.walk("."):
    for excl in EXCLUDES:
        if excl in dirs:
            dirs.remove(excl)

I know I can generate a new dirs with list comprehension like [e for e in dirs if e not in EXCLUDES] but this would not work when I need to modify the original instance.
Writing s.th. like [dirs.remove(e) for e in dirs if e in EXCLUDES] does work but I'm abusing list comprehension - pylint does not like it (for a reason) and future versions of Python might even omit this expression because generated values are not used.
So in the provided scenario - is there a way to operate on a list like
dirs.remove_items(e for e in EXCLUDES if e in dirs)

Or more generally: is there a (recommended) way to run a command in a "for each" semantic, like
fn(e) for e in container

A: You can do this just fine with a list comprehension, you just use empty slice assignment to replace the contents of the original dirs:
dirs[:] = [e for e in dirs if e not in EXCLUDES]
#   ^^^ Replaces contents       ^^^ flip condition so you only keep not-excluded

This doesn't violate any rules of proper listcomp use; the listcomp has no side-effects, it just produces a new list, which you then use to replace the original contents of dirs in bulk.
Aside from that, to your question, "is there a (recommended) way to run a command in a "for each" semantic", that's a for loop, like you already wrote:
 for x in iterable:
     fn(x)

A:
So in the provided scenario - is there a way to operate on a list like
dirs.remove_items(e for e in EXCLUDES if e in dirs)

No. There is no built-in remove_items or remove_all function for lists. For sets, you have intersection_update or -= that does the job:
>>> EXCLUDES = {"a", "b", "c"}
>>> dirs = {"a", "x", "y"}
>>> dirs -= EXCLUDES
>>> dirs == {'x', 'y'}
True

Or more generally: is there a (recommended) way to run a command in a "for each" semantic, like fn(e) for e in container

Yes: if fn(e) is pure, use a list comprehension, but else, write:
for e in container:
    fn(e)

Some remarks
EDIT following @ShadowRanger comment below.
The doc states:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

I didn't understand that the OP goal was to prune the search. The following remarks do not apply to this situation, but remain true in general. See @ShadowRanger's answer to prune the search using a slice assignment.
END OF EDIT
As you stated, it's a bad idea to use a list comprehension (or map) to produce a side effect. A list comprehension returns a list, period.
But nothing prevents you from assigning the list comprehension you wrote to dirs itself:
dirs = [e for e in dirs if e not in EXCLUDES]

You are not removing items but creating a new list (that's the point of list comprehensions if I'm not mistaken). If you are afraid of the cost of creating a new list, you can use a generator:
>>> EXCLUDES = {"a", "b", "c"}
>>> dirs = ["a", "x", "y"]
>>> dirs = (e for e in dirs if e not in EXCLUDES)
>>> dirs
<generator object <genexpr> at ...>
>>> list(dirs)
['x', 'y']

The generator is lazy, hence the elements will be read from dirs and filtered on the fly. No new list will be created. The same goes for filter:
>>> dirs = filter(lambda f: f not in EXCLUDES, dirs)
>>> dirs
<filter object at ...>
>>> list(dirs)
['x', 'y']

But not for reduce:
>>> from functools import reduce
>>> dirs = reduce(lambda acc, f: acc if f in EXCLUDES else acc + [f], dirs, [])
>>> dirs
['x', 'y']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limit access using ajax and .htaccess I'va got a jquery file processing some mysql-data changes using ajax-calls (jQuery api) within php handler file.
This is my javascript:
$('#control1').click(function() {
    $('#control2').dialog({
        show: "blind",
        hide: "explode",
        width: "auto",
        draggable: false,
        modal: true,
        resizable: false,
        buttons: [
                  {
                      text: "Save",
                      click: function() {
                          $.ajax({
                             cache: false,
                             type: 'POST',
                             url: 'handler/some.handler.php',
                             data: $('#Form1').serialize(),
                             dataType: 'json',
                             beforeSend: function() {
                                 $('#Control3').fadeIn('fast');
                             },
                             success: function (data) {
                                 if (data.success) {
                                     alert(data.message);
                                     $(this).dialog("close");
                                     location.reload();
                                 } else {
                                     alert("Error occurred: " + data.message);
                                 }
                             },
                             error: function(xhr, ajaxOptions, thrownError) {
                                 alert("Error during process: " + thrownError);
                             },
                             complete: function () {
                                 $('#Control3').fadeOut('fast');
                             }
                          });
                      }
                  },
                  {
                      text: "Cancel",
                      click: function() { $(this).dialog("close"); }
                  }
                  ]
    });
});

Inside the handler directory i placed a .htaccess file for managing file access and limit exception:
<LimitExcept GET POST HEAD>
    Order deny, allow
    Deny from all
</LimitExcept>

But Apache always return 500: Internal sever error. If I delete the .htaccess file everything works fine... How to configure the .htaccess file correctly?
Thx!!!

A: Kind of dumb, but apache flips out if Order is given more than one parameter. You have a space in yours:
# here ----v
Order deny, allow

You just need to remove it:
Order deny,allow


text:
Q: How to pass non-primitive types into Fragment factory method's Bundle I have an object with non-primitive attributes that will be initialized with information from an API call:
class object(
    val attribute1: String
    val attribute2: Date
)

I want to build a Fragment with these attributes as parameters, like so:
 private var param1: String? = null
 private var param2: Date? = null

The key-value pairs in the Fragment's factory and onCreate methods require primitive types as values
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

fun newInstance(param1: String, param2: String) =
            PaymentMethodFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }

What is the best way to pass this data into a new instance of a fragment?


text:
Q: NLTK Naive bayes Classifier weird results I'm trying to use a nltk naive classifier to classify genres of movies. I am however getting some weird results. Currently it only guesses based on amount of genre inputted.
If I input two action movies, and one comedy every guess will be action. Naturally I want it to based on inputted text:
def RemoveStopWords(wordText):
   keep_list = []
   for word in wordText:
        if word not in wordStop:
            keep_list.append(word.lower())

   return set(keep_list)

def getFeatures(element):

   splitter=re.compile('\\W*')
   f = {}
   plot = [s for s in RemoveStopWords(splitter.split(element['imdb']['plot']))
   if len(s)>5 and len(s) < 15]

   for w in plot:
           f[w]= w

   return f

def FindFeaturesForList(MovieList):
    featureSet = []
    for w in MovieList:
        print w['imdb']['title']
        try:
            for genre in w['imdb']['genres']:
                featureSet.append((getFeatures(w), genre))
        except:
            print "Error when retriving genre, skipping element"

    return featureSet

featureList = FindFeaturesForList(trainset)
cl = nltk.NaiveBayesClassifier.train(featureList)

So whenever I do a cl.classify(movie) it returns the most frequent inputted genre, what am I doing wrong?

A: In the movie review classification example in the nltk book notice that the frequency of all the words from all the movies was collected, and then only the most common words were chosen to be feature keys.
all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())
word_features = all_words.keys()[:2000]

I think it is important to note that this is a choice. It is not mandatory that the feature keys be chosen this way. Some other clever choice of features could possibly lead to an even better classifier. Choosing good features is the art behind the science.
Anyway, perhaps try using the same idea in your classifier:
def getFeatures(text, word_features):
    text = text.lower()
    f = {word: word in text for word in word_features}
    return f

def FindFeaturesForList(MovieList):
    featureSet = []
    splitter = re.compile('\\W*')
    all_words = nltk.FreqDist(
        s.lower()
        for w in MovieList
        for s in RemoveStopWords(splitter.split(w['imdb']['plot']))
        if len(s) > 5 and len(s) < 15)
    word_features = all_words.keys()[:2000]
    for w in MovieList:
        print w['imdb']['title']
        try:
            for genre in w['imdb']['genres']:
                featureSet.append(
                    (getFeatures(w['imdb']['plot'], word_features), genre))
        except:
            print "Error when retriving genre, skipping element"

    return featureSet


text:
Q: error booting the custom compiled kernel 2.6.37 on ubuntu 10.04 : gave up waiting on root device
Possible Duplicate:
Kernel can't find /dev/sda file during boot

Hi,
    I know this is very common problem and there are many threads discussing it. However after trying many solutions my problem still persists :(
I have installed ubuntu Lucid which works fine.Then I  downloaded and compiled kernel 2.6.37 from git tree and compiled it using normal compilation process.I created initrd image and called

update-grub

It detects my initrd image. However,I get following error while booting:

Gave up waiting for root device.
  Common problems:
  -Boot args (cat /proc/cmdline)
  -Check rootdelay= (did the system wait long enough?)
  -Check root= (did the system wait for the right device?)
  -Missing modules (cat /proc/modules; ls /dev)
  ALERT! root=UUID=/... does not exist

And then control falls onto  initramfs prompt.
I tried following solutions:

*

*Write GRUB_DISABLE_LINUX_UUID=true in /etc/default/grub

*compile kernel using CONFIG_DEVTMPFS=y

Still I am unable to boot from the boot the compiled kernel.
Could someone please suggest me some solution . Thank you :)


text:
Q: Configuration path "security.access_control" cannot be overwritten I'm busy trying to configurate Fouserbundle on Symfony 2.6.9. But doesn't work, i got this message:
ForbiddenOverwriteException in BaseNode.php line 223: Configuration path "security.access_control" cannot be overwritten. You have to define all options for this path, and any of its sub-paths in one configuration section.
(i did configurate, appkernel, config,composer)
user.php
<?php

namespace FLY\UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="FLY_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}

app/Resources/config/security.yml
imports:
- { resource: "@FLYUserBundle/Resources/config/security.yml" }

security:
    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

UserBundle/Resources/config/security.yml
security:
encoders:
    FOS\UserBundle\Model\UserInterface: sha512

providers:
        fos_userbundle:
            id: fos_user.user_manager

firewalls:

    main:
                pattern: ^/
                form_login:
                    provider: fos_userbundle
                    csrf_provider: form.csrf_provider
                logout:       true
                anonymous:    true
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

    login:
        pattern:  ^/demo/secured/login$
        security: false

    secured_area:
        pattern:    ^/demo/secured/
        form_login:
            check_path: /demo/secured/login_check
            login_path: /demo/secured/login
        logout:
            path:   /demo/secured/logout
            target: /demo/
        #anonymous: ~
        #http_basic:
        #    realm: "Secured Demo Area"

app/Resources/config/routing.yml
FLY_Platform:
resource: "@FLYPlatformBundle/Resources/config/routing.yml"
prefix:   /

mremi_contact_form:
    resource: "@MremiContactBundle/Resources/config/routing.xml"

genemu_base64:
        resource: "@GenemuFormBundle/Resources/config/routing/base64.xml"

_user_bundle:
    resource: "@UserBundle/Resources/config/routing.yml"

UserBundle/Resources/config/routing.yml
fos_user_security:
resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

Thank you

A: Had the same error because of having used separate security.yaml for dev (config/dev/security.yaml) and test (config/test/security.yaml) environments (besides config/security.yaml).
After removal of these files, error message disappeared.

A: In symfony, as the error message says, you ca't override most security options. You should define all your security related configuration in app/config/security.yml.

A: i think the security file that is imported is app/Resources/config/security.yml
this is my app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: security.yml }

framework:
    #esi:             ~
    translator:      ~
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    templating:
        engines: ['twig']
        #assets_version: SomeVersionScheme
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~
    fragments:       ~
    http_method_override: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Assetic Configuration
assetic:
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [ ]
    java: /usr/bin/java
    filters:
        cssrewrite: ~
        cssembed:
          jar: %kernel.root_dir%/Resources/java/cssembed-0.4.5.jar
        yui_js:
          jar: %kernel.root_dir%/Resources/java/yuicompressor.jar
        lessphp:
          file: %kernel.root_dir%/../vendor/leafo/lessphp/lessc.inc.php
          apply_to: "\.less$"
    assets:
        jquery_js:
            inputs:
                - '%kernel.root_dir%/../components/jquery/jquery.min.js'
            filters: [?yui_js]
        bootstrap_js:
            inputs:
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/transition.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/alert.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/modal.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/dropdown.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/scrollspy.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/tab.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/tooltip.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/popover.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/button.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/collapse.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/carousel.js'
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/js/affix.js'
            filters: [?yui_js]
        bootstrap_less:
            inputs:
                - '%kernel.root_dir%/../vendor/twitter/bootstrap/less/bootstrap.less'
            filters: [lessphp,cssembed]

# Doctrine Configuration
doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #     path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport:  "%mailer_transport%"
    host:       "%mailer_host%"
    encryption: "%mailer_encryption%"
    username:   "%mailer_user%"
    password:   "%mailer_password%"
    spool:     { type: memory }

mremi_contact:
    store_data:            false
    contact_class:         Mremi\ContactBundle\Model\Contact

    form:
        type:              mremi_contact
        name:              contact_form
        validation_groups: [Default]
        subject_provider:  mremi_contact.subject_provider.noop
        captcha_type:      genemu_captcha

    email:
        mailer:            mremi_contact.mailer.twig_swift
        from:              [{ address: xxxxxx@gmail.com, name: "Webmaster" } ]
        to:                [{ address: xxxxxx@hotmail.fr } ] # Required
        template:          MremiContactBundle:Contact:email.txt.twig

genemu_form:
    captcha: ~
# fouser Configuration
fos_user:
        db_driver: orm
        firewall_name: main
        user_class: FLY\UserBundle\Entity\User

A: I had the same problem. I have commented in config_dev.php the line concerning the fos_user db_driver and it helped

A: I got the same error after symfony upgrade

Configuration path "security.access_control" cannot be overwritten. You have to define all options for this path, and any of its sub-paths in one configuration section.

In my case I patched old AppKernel.php and had duplicate configuraton load command
public function registerContainerConfiguration(LoaderInterface $loader)
{
    // this is old code
    $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');

    // code above is new and copy-pasted from clean symfony 3.4 install
    $loader->load(function (ContainerBuilder $container) {
        $container->setParameter('container.autowiring.strict_mode', true);
        $container->setParameter('container.dumper.inline_class_loader', true);

        $container->addObjectResource($this);
    });
    $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}

After removing first one - everything works ok.

A: Might be a simple reason: i had this error because i backuped the config file security.yaml to _security.yaml. Symfony reads both...


text:
Q: Python using open(file) variable more than once? Is it possible to define a variable as open("file.txt", "a") and call it more than once so you don't have to keep typing open("file.txt", "a")?
I tried, but it doesn't seem to work for me. I keep getting the error message:

ValueError: I/O operation on closed file.

My code looks like:
x = open("test.txt", "a")
with x as xfile:
    xfile.write("hi")

#works fine until I try again later in the script

with x as yfile:
    yfile.write("hello")

Question: Is there a way to do this that I'm missing?
(My apologies if this question is a repeat, I did search google and SO before I posted a new question.)

A: If you don't want to close the file right away, don't use a with statement and close it yourself when you're done.
outfile = open('test.txt', 'w')

outfile.write('hi\n')

x = 1
y = 2
z = x + y

outfile.write('hello\n')

outfile.close()

Typically you use the with statement when you want to open a file and do something with that file immediately, and then close it.
with open('test.txt', 'w') as xfile:
    do something with xfile

However, it is best practice to take care of all your I/O with a single file at once if you can. So if you want to write several things to a file, put those things into a list, then write the contents of the list.
output = []

x = 1
y = 2
z = x + y
output.append(z)

a = 3
b = 4
c = a + b
output.append(c)

with open('output.txt', 'w') as outfile:
    for item in output:
        outfile.write(str(item) + '\n')

A: The with statement closes the file automatically. It is good to do everything related to the file inside the with statement (opening a file multiple times is also not a good idea).
with open("test.txt", "a") as xfile:
    # do everything related to xfile here

But, if it doesn't solve your problem then don't use the with statement and close the file manually when the work related to that file is done.
From docs:

It is good practice to use the with keyword when dealing with file
  objects. This has the advantage that the file is properly closed after
  its suite finishes, even if an exception is raised on the way.

A: You example doesn't make much sense without more context, but I am going to assume that you have a legitimate need to open the same file multiple times.  Answering exactly what you are asking for, you can try this:
x = lambda:open("test.txt", "a")

with x() as xfile:
    xfile.write("hi")

#works fine until I try again later in the script

with x() as yfile:
    yfile.write("hello")

A: The usual way to use with statements (and indeed I think the only way they work) is with open("text.txt") as file:.
with statements are used for handling resources that need to be opened and closed.
with something as f:
    # do stuff with f

# now you can no longer use f

is equivalent to:
f = something
try:
    # do stuff with f
finally:    # even if an exception occurs
    # close f (call its __exit__ method)
# now you can no longer use f


text:
Q: Does the intermediate axis theorem violate angular momentum conservation? According to the intermediate axis theorem, an object rotating about its intermediate axis with a very slight perturbation will undergo periodic flips in its orientation in the absence of external forces. Initially, almost all the angular momentum is directed along the intermediate axis. However, during the flip, some of the angular momentum must be transferred to the other two principal axes to allow the flip to occur. As far as my understanding goes, angular momentum conservation says that in the absence of external torque, both the magnitude and direction of angular momentum must be conserved. According to simulations I've created, the magnitude of angular momentum is conserved, but the direction changes during a flip as described above. How does this mesh with angular momentum conservation?
Edit to clarify: By slight perturbation, I mean that the object begins rotating about an axis that is ever so slightly tilted from its intermediate axis. There is no torque at any point during the simulation. What I mean by angular momentum not being conserved is this: Let's say the intermediate axis is initially along the y-axis. Then $\omega_y$ is on the order of 1, while $\omega_x$ and $\omega_z$ are on the order of 1e-5. Likewise, $L_x=I_x\omega_x$ and $L_z=I_z\omega_z$ are tiny compared to $L_y$. Yet, at fixed intervals, the object will rapidly flip its orientation. After the flip, angular momentum is the same as before, yet during the flip, the object must rotate about the x and/or z axes with high $\omega_x$ and/or $\omega_z$. This has been observed in experiments and computer simulations and is the part that I believe violates angular momentum conservation, not its rotation after the flip.

A: The angular and linear momenta are both conserved. This is the reason why a stable rotation about a non-easy and non-hard axis is not possible.
A continuous rotation about any other axis requires periodic torque to be maintained.
This is because when a body spins about such an axis, its angular moment will be not aligned with its rotation axis. As a result, the rotational axis will precess around the angular momentum vector.
This short clip nicely demonstrates this behavior for a rotational axis that is almost along the intermediate axis. The body reverses its own sense of rotation, but it also flips over at the same time, conserving its angular momentum.

A: First off: recommendation of the following two resources:
2018 Article by Nicholas Mecholsky Analytic formula for the geometric phase of an Asymmetric top
2020 Youtube video by David Brown The Dzhanibekov effect, equations and simulations

The video by David Brown is particularly clarifying.
David Brown has set up simulation of the most symmetric case where there are still three different moments of inertia:

Screenshot from the first video (of 2 videos) about the intermediate axis theorem

The implementation of the simulation makes the following clear: when the object is rotating there are internal stresses. If the struts would be flexible they would flex, dissipating kinetic energy. (In the equations for the simulation the object is for simplicity treated as perfectly rigid, of course.)
These internal forces are continuously relocating momentum from one part of the asymmetric top to another. The orientation and magnitude of the global angular momentum is constant (since there is no external torque). The continuous internal relocation of momentum gives the pattern of continuous change of the orientation of the angular velocity vector with respect to the asymmetric top.
David Brown points that there are only two circumstances where (internal) relocation of momentum does not occur: when the rotation is exactly along the axis of largest moment of inertia, and when the rotation is exactly along the axis of smallest moment of inertia.
In all other circumstances internal relocation of momentum does occur. That is: when the rotation is just a little bit off the axis of largest/smallest moment of inertia there is continuous relocation of momentum too, it's just less vivid.

Pendulum with a rigid rod
David Brown offers the following comparison: a pendulum with a rigid rod. When the pendulum amplitude is very small the motion is to a close approximation harmonic oscillation. The motion pattern of an asymetric top that is rotating just slightly off the axis of smallest/largest moment of inertia looks like just a slight wobble, analogous to a pendulum swinging with small amplitude.
The other end of the spectrum is that the pendulum is released from a close to completely inverted position. Let me refer to that as being released at 175 degrees away from hanging vertically down. The pendulum will then swing back and fort between 175 degrees and minus 175 degrees. Visually that looks as if the pendulum is lingering in the inverted orientation, with an apparently sudden swing to the other inverted orientation.
Being released from close to completely inverted is a release with the potential energy of the pendulum maxed out. (As in: you cannot release with more inital potential energy than that.)
In the case of the asymmetric top:
Setting up the initial rotation state very close to the axis of intermediate moment of inertia is like the case of releasing an inverted pendulum from close to completely inverted.

Dissipation of kinetic energy
I think it is also very instructive to consider what happens when the system does have significant dissipation of kinetic energy. (Here I mean with dissipation of kinetic energy: internal dissipation due to flexing of the structure, not dissipation due to friction from something external.)
Angular velocity around the axis of largest moment of inertia has the masses furthest away from the center of rotation. So: for the same angular momentum the rotation rate will be the slowest.
In the presence of dissipation of kinetic energy:
If the initial state of rotation is that the angular velocity vector is close to the axis of intermediate moment of inertia then the asymmetric top will over time proceed to a state where the rotation is along the axis of largest moment of inertia.
The initial state of rotation being close to the intermediate moment of inertia is in a sense a maxed out state.
There is an end state such that all the kinetic energy that can dissipate has dissipated. That end state is rotation around the axis of largest moment of inertia. (There is still kinetic energy at that point, but it has no opportunity to dissipate.)
An initial state of rotation close to the axis of intermedite moment of inertia is a state that is the most charged with additional kinetic energy, as compared to state of rotation around the axis of largest moment of inertia.

A: The intermediate axis theorem only states that this rotation is unstable, i.e., IF there is a perturbation, the axis will become another. The perturbation produces a slight non-conservation of angular momentum (it will be produced by an external force and, therefore, we do not expect strict conservation in that situation).
However, if the perturbation the alteration of the angular momentum will also be small and there will be a quasi-conservation. Although the angular momentum will be almost the same, the axis of rotation will perform a precession around the direction of the angular momentum. Although the axis will be radically different, the energy and angular momentum will be almost the same as without the existence of the perturbation.

A: The moment of inertia of an axis is denoted as $I$
Energy of rotation about an axis is $E = Iw^2 / 2$
Angular momentum   about an axis is $L = Iw$
Each axis has a characteristic ratio $L^2/E = 2I$
Given an object that has axes with three different moments of inertia $I_1 < I_2 < I_3$, and no way dissipate rotational energy :
If you initiate a spin around the axis with the largest moment of inertia, then you have provided AM and Energy that meets $L^2/E = 2I_3$ .
This ratio is too high to transfer any momentum or energy to an axis with a lower ratio, while conserving both.
If you initiate a spin around the axis with the smallest moment of inertia, then you have provided AM and Energy that meets $L^2/E = 2I_1$ .
This ratio is too low to transfer any momentum or energy to an axis with a higher ratio, while conserving both.
If you provided 99% $I_3$, and 1% $I_2$, it could never transfer any more or less .
But if you initiate 99% $I_2$, and 1% $I_3$, then you have provided AM and Energy with an intermediate ratio. The object can find endless combinations
of $I_1, I_2, I_3$ that can satisfy conservation of AM and Energy. It is free to follow whatever path $\vec F=m\vec a$ takes .
It is nearly impossible to set up a purely intermediate axis spin, and it can transfer to $I_1$ and $I_3$ simultaneously, thus the transfer, thus the flip. Conserved all the way, always.


text:
Q: connect a postgresql database in node js Here is my code:
index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

app.get('/js/client_world.js', function(req, res){
res.sendFile(__dirname + '/js/client_world.js');
});

io.on('connection', function(socket){
console.log("A user is connected");

socket.on('disconnect', function(){
    console.log("User disconnected");
});
});

http.listen(3000, function(){
console.log("Listenng to port 3000")
});

index.html:
<!DOCTYPE html>

<meta charset="UTF-8">
<title></title>

and a third file, client_world,js, where I want to read data from a database.
The first line
var {Pool,Client} = require('pg');

causes an error.
Is this way to access the DB wrong? Thanks in advance for a hint.


text:
Q: A little bit confusion with C# Generics, T, Abstraction ? I am a C# game maker with Unity. I have collectable management system.
CollectableManager
public List<CollectableParent<Collectable>> collactableParentsList;

CollectableParent
public class CollectableParent<T> : CollectableRelatedMonoBehaviour where T : Collectable

SpawnPointDefinedCollectableParent
public class SpawnPointParentDefinedCollectableParent<T> : CollectableParent<T> where T : Collectable

Collectable
public abstract class Collectable : CollectableRelatedMonoBehaviour, IHasPlayableSound

Collectable_Money
public class Collectable_Money : Collectable

CollectableParent_Money
public class CollectableParent_Money : SpawnPointParentDefinedCollectableParent<Collectable_Money>

PROBLEM
"collactableParentsList" in CollectableManager does not accept SpawnPointParentDefinedCollectableParent<Collectable_Money> as item when T is defined as "Collectable_Money", it is derived from "Collectable". If I do this SpawnPointParentDefinedCollectableParent<Collectable>, it is accepted as item into list.

A: The problem here is that even though Collectable_Money is a sub-class of Collectable, that does not make SpawnPointParentDefinedCollectableParent<Collectable_Money> a sub-class of CollectableParent<Collectable>.
It may be possible to fix this by using generic interfaces. If we change CollectableParent<T> to be an interface, and define it to be covariant in T via the out modifier. (You haven't provided the definition for CollectableRelatedMonoBehaviour, but it will also need to be converted to an interface):
public interface ICollectableParent<out T> : ICollectableRelatedMonoBehaviour where T : Collectable

If you then define the list as:
public static List<ICollectableParent<Collectable>> collectableParentsList;

Then you can successfully add items of type SpawnPointParentDefinedCollectableParent<Collectable_Money> to it.
The critical part here is that the ICollectableParent<T> interface is covariant in T. This makes it possible to pass an instance that implements ICollectableParent<Collectable_Money> where an ICollectableParent<Collectable> is expected.
Defining the interface as covariant in T does introduce some restrictions, specifically (and as implied by the out modifier used to indicate covariance), the type T must only be used as a return value on the interface's methods. For example:
public interface ICollectableParent<out T> : ICollectableRelatedMonoBehaviour where T : Collectable
{
    // This is allowed - T is used as a return type
    T GetChild();
    // This is *not* allowed - T is used as a parameter
    void SetChild(T child);
}

You can read more about covariance, and its inverse (contravariance) here: Difference between Covariance & Contra-variance


text:
Q: More Efficient Way To Merge Unique Values From Dynamically Selected Tables using Oracle PLSQL Given a declared PLSQL Procedure
PROCEDURE GET_DISTINCT_TIMES(dtypes IN VARCHAR2, start IN NUMBER, end IN NUMBER
   distinct_times_cursor OUT SYS_REFCURSOR)

Where:

*

*'Dtypes' is a comma delimited string, with each value corresponding to a general type of data I want to retrieve.  One data type may correspond to one or many different tables where distinct times need to be retrieved

*'Start' & 'End' are the two times I am querying between

I have written implementations that dynamically create the SQL using Unions to pull out only unique time values from each table.  However, due to the dynamic nature of the 'Dtypes' argument, I am forced to generate this SQL in a loop control, and have not been able to figure a way to implement bind variables.
I believe that losing the benefit of bind variables may have caused the queries to take longer than necessary
So I am wondering, is there a way to either:

*

*Associate bind variables with a dynamically created SQL string when the number of bind variables is completely variable with the arguments passed in to the procedure.

*Take a different approach, where for each dtype - execute another stored procedure, or SQL Statement, store the recordset for each query, then merge the unique results and assign a cursor to the new results

Admittedly, I am quite new with PLSQL programming and haven't had the opportunity yet to grab a good reference/book on the language.  Any comments, insights, or suggested readings would be appreciated too.

A: See this SO question.  You can use the DBMS_SQL package to bind a varying number of bind variables.
One other possibility is to use a pipelined table function.  For each dtype, you would execute a stored procedure or SQL statement and use PIPE ROW to output the results.  If you still need the results in a ref cursor, you can do SELECT * FROM TABLE(pipelined_function()).

A: I asked around and one of my friends came up with a solution that I successfully implemented today.
Basically, I dynamically create the entire PLSQL block as a VARCHAR2 then assign the bind variables using EXECUTE IMMEDIATE.  The benefit of this method provides is that I can now assign bind variables by name, instead of by position.
Here is an example of what I mean:
var rs_cursor refcursor

DECLARE
  start_tm CONSTANT PLS_INTEGER := 989452800;
  end_tm CONSTANT PLS_INTEGER := 989452820;
  plsql_block VARCHAR(1024);
BEGIN
  plsql_block := 'BEGIN ' ||
    'OPEN :rs_cursor FOR ' ||
    '  SELECT TIME ' ||
    '  FROM TBL_1 ' ||
    '  WHERE TIME BETWEEN :start_tm AND :end_tm ' ||
    '  UNION ' ||
    '  SELECT TIME ' ||
    '  FROM TBL_2 ' ||
    '  WHERE TIME BETWEEN :start_tm AND :end_tm ' ||
    '  ORDER BY TIME; ' ||
    'END;';
  EXECUTE IMMEDIATE plsql_block USING IN OUT :rs_cursor, IN start_tm, IN end_tm
END;
/

print rs_cursor

start_tm and end_tm are only needed to be passed in once, but apply to multiple binds within the PLSQL block
My actual implementation is quite different than this, but it is using that specific functionality of EXECUTE IMMEDIATE binding variables by name to allow me to dynamically create SQL blocks based on whatever data types are provided to the procedure.


text:
Q: Do i have to write in shader language to create a FX file? Is there a program out there, that would create a FX file instead of having to code it?

A: If you are wanting to create shaders without coding at all, I don't know of any such software.
But, FX Composer and RenderMonkey are good programs to create shaders in!


text:
Q: How to integrate multiple imputation into Donna Spiegelman's SAS Subtype Macro? I am trying to analyse the HRs for different disease subtypes in a nested case-control study using the dataset with a high proportion of missing values for two variables that I need for adjusted risk model. For non-adjusted model I used Donna Spiegelman's Subtype macro https://www.hsph.harvard.edu/donna-spiegelman/software/subtype/.
Now I want to run an adjusted model using the dataset with Multiply imputed Data for categorical variables a and b. My idea was to first run Proc MI :
proc mi data=Subtype nimpute=100 out=ImputSP seed=1305468 ;
class a b disease_sub infection ;
fcs plots=trace (  std mean );
var  a  b  age disease_sub infection;
fcs discrim( a b /classeffects=include)  nbiter=100;

run;

And then run the edited version of the subtype macro in which I've added "by imputation" option in 3 parts of the macro code.
/* get list of values of outcometype */
     proc sort data=newdatname;  by outcometype ;  run;
     proc means noprint data=newdatname;  var outcometype;
         output  out=_expblist_  mean=m_outcometype;
         by outcometype;
         where outcometype ne . ;
     run;

     data _expblist_;
        set _expblist_  end=_end_;
        call symput('_eb_'||trim(left(_n_)), trim(left(m_outcometype)));
        if _end_ then call symput ('_neb_', trim(left(_n_)));
      run;

%if &studydesign eq CACO %then %do; %let reftype=0; %end;

ods listing close;
proc logistic data=newdatname outest=LL;
by _imputation_;
    model outcometype(ref="&reftype")=&exposureND &exposureD_ &unconstrvar /link=glogit covb;

    %if &studydesign eq CACA %then %do;
        %do j=1 %to &_nexpND;

*variables for pair-wise LRT of heterogeneity test;

%do j=1 %to &_nexpND;
       %do i=1 %to &_neb_;
           if outcometype=&i then _expND_&j=&&_expND_&j._&i..;
       %end;
       rename _expND_&j=&&_expND_&j;
   %end;

   %do j=1 %to &_nexpD;
      %do k=1 %to &&_nexpD_&j;
          %do i=1 %to &_neb_;
             if outcometype=&i then _expD_&j._&k=&&_expD_&j._&k._&i..;
          %end;
      rename _expD_&j._&k=&&_expD_&j._&k..;

     %end;
   %end;

    %do j=1 %to &_nexpND;
    %do i=1 %to %eval(&_neb_-1);
        %do k=%eval(&i+1) %to &_neb_;
            _expND_&j._&i._vs_&j._&k.= _expND_&j*(outcometype=&&_eb_&i|outcometype=&&_eb_&k);
        %end;
    %end;
    %end;

    %do j=1 %to &_nexpD;
    %do i=1 %to %eval(&_neb_-1);
        %do k=%eval(&i+1) %to &_neb_;
             %do m=1 %to &&_nexpD_&j;
               _expD_&j._&m._&i._vs_&j._&m._&k.=_expD_&j._&m.*(outcometype=&&_eb_&i|outcometype=&&_eb_&k);
             %end;
        %end;
    %end;
    %end;
run;

%end;

ods listing close;

proc phreg data=newdatname outest=LL %if "&covs" eq "YES" %then %do; covs %end; nosummary;
        model (entrytime,time)*censoring(0)=

        %do j=1 %to &_nexpND;
          %do i=1 %to &_neb_;
             _expND_&j._&i
            %end;
        %end;
        %do j=1 %to &_nexpD;
             %do k=1 %to &&_nexpD_&j;
                  %do i=1 %to &_neb_;
                       _expD_&j._&k._&i
                   %end;
               %end;
         %end;

%if "&augmented" eq "NO" %then %do;
            %do j=1 %to &_nunconstrvar;
               %do i=1 %to &_neb_;
                _ucv_&j._&i
            %end;
         %end;
%end;

%else %if "&augmented" eq "YES" %then %do;
    &unconstrvar
%end;

      &constrvar / covb  %if "&studydesign" eq "MCACO" | "&studydesign" eq "CACO" %then %do; ties=discrete %end; ;
     %if "&studydesign" eq "COHORT" | "&studydesign" eq "CACO"  %then %do;  strata outcometype &stratavar; %end;
     %if "&studydesign" eq "MCACO" %then %do;   strata &matchid; %end;

    by _imputation_;

After running the subtypeBY_macro my intention is to run this code to obtain the final estimates:
proc print data=&PamEst (obs=8) ;
title "Logistic Model Coefficients First 8 Obs  ";
var _Imputation_ Variable Estimate StdErr;
run;

TITLE "MULTIPLE IMPUTATION LOG REFRESSION-FCS";
proc mianalyze parms (classvar=ClassVal)=&PamEst  ;
class &classmi  ;
MODELeffects &modelvar ;
ods output ParameterEstimates=mianalyze_&PamEst;
run;

title;

data OR_&PamEst;
set mianalyze_&PamEst;
OR=exp (estimate);
LCL_OR=exp (LCLMean);
UCL_OR=exp(UCLMean);
proc print;
var parm &classmi OR LCL_OR UCL_OR;
run;

Sadly the program crushes on the SubtypeBY step and I do not know how to best proceed to integrate multiple imputation into the adjusted model. Any tips would be much appreciated!


text:
Q: How to get all network printers in C# I have written the following code it didnot get the Remote printers name Can any one please help me?
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM
                                             Win32_Printer");

var results = searcher.Get();

IList<ManagementBaseObject> printers = new List<ManagementBaseObject>();
`enter code here`
foreach (var printer in results) `enter code here`{
    if ((bool)printer["Network"]) `enter code here`{`enter code here`
        printers.Add(printer);`enter code here`
    }
}

A: If you are looking to find list of all Installed Network Printers then you can simply use the following function.
Try to run the following in by creating a Console Application.
You need to reference System.Printing Namespace. You need to manually add reference to its library by right-clicking on Add References and checking the same as shown below in the snapshot.

Once you are done with that then use the following code for your console application. I have added code here to show BOTH Network and Local Printers. You can pick your particular selection.
using System.Printing;
namespace GetPrinters
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new PrintServer();
            Console.WriteLine("Listing Shared Printers");
            var queues = server.GetPrintQueues(new[]
            { EnumeratedPrintQueueTypes.Shared, EnumeratedPrintQueueTypes.Connections });
            foreach (var item in queues)
            {
                Console.WriteLine(item.FullName);
            }
            Console.WriteLine("\nListing Local Printers Now");
            queues = server.GetPrintQueues(new[]
            { EnumeratedPrintQueueTypes.Local });
            foreach (var item in queues)
            {
                Console.WriteLine(item.FullName);
            }
            Console.ReadLine();

        }
    }
}

A: I think you have to update your code like below.
private void btnGetPrinters_Click(object sender, EventArgs e)
{
    // Use the ObjectQuery to get the list of configured printers
    var oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");

    var mosearcher = new System.Management.ManagementObjectSearcher(oquery);

    System.Management.ManagementObjectCollection moc = mosearcher.Get();

    foreach (ManagementObject mo in moc)
    {
        System.Management.PropertyDataCollection pdc = mo.Properties;

        foreach (System.Management.PropertyData pd in pdc)
        {
            if ((bool)mo["Network"])
            {
                cmbPrinters.Items.Add(mo[pd.Name]);
            }
        }
    }
}

I copied it from Retrieve a List of Installed Printers on the Network Using WMI, C# and VB.NET


text:
Q: Find the number of positive integers that are divisors of at least one of $10^{10}, 12^{12}$ or $15^{15}$. Find the number of positive integers that are divisors of at least one of $10^{10}, 12^{12}, 15^{15}$.
As far as I have reached is the number of factors are 121,325,256 respectively

A: Hint:
Use the inclusion-exclusion formula.  It shouldn't be very long, as each pair of numbers has only one common prime factor.


text:
Q: Restructuring HTML using jQuery I have some HTML that I need to toggle between two structures - one nested, and one un-nested - to make it easier for users to sort page components in a cms.
Here's the before html...

Toggle Structure

Some text

Some text

Some text

Some text

and after html...

Toggle Structure

Some text

Some text

Some text

Some text

I can strip out the extra divs, no trouble, but putting them back afterwards - I just don't get how to build up html from plain text and existing DOM elements. Here's the code I have so far...

Any help in getting the second function of the toggle to work (or in a more idiomatic version of the working code) would be much appreciated...

A: You should use wrapAll in your case since your wrapping multiple elements at once into the same element.

A: Give this a try:
  $(document).ready(function(){
    $('#restructure').toggle(
      function() {
        alert('removing structure');
        $("#modules .column_left, #modules .column_right").moveToGrandparent();
        $(".two_column_box").remove();
      },
      function() {
        alert('replacing structure');

        var next = $('#modules > .column_left:first, #modules > .column_right:first');
        while (next.length > 0)
        {
            var wrapper = $("
").addClass("two_column_box");
            next.wrapAll(wrapper);
            next = $('#modules > .column_left:first, #modules > .column_right:first');
        }
      }
    );
  });

  (function($) {

    $.fn.moveToGrandparent = function() {
        return $(this).each(function() {
            $(this).parent().parent().append($(this));
        });
    };

  })(jQuery);

Although you're removing structure code worked, I re-wrote it to use a plugin.  As for the replacing structure, I'm using the jQuery wrapAll method with a loop that gets the first elements until there aren't any elements remaining.
HTH,
Ben

A: Once slight addendum to gradbot's suggestion: the point is that the elements will be sorted using UI sortable, so I needed to re-class the items depending on where they were in the list - odd being lefthand side, even being righthand side. There's probably a quicker way to do it but...


text:
Q: Enable a software MIDI output for use with pygame I want to be able to play MIDI notes from the pygame.midi module, similar to Windows. I believe this means setting up some sort of software/virtual MIDI out device. Fluidsynth appears to be able to do what I need, but I'm not sure how to configure it. I am using KDE Neon.
Edit: Here is how I would set up MIDI with Pygame normally.
from pygame import midi
midi.init()
t=midi.Output(midi.get_default_output_id())

A: You should first make sure that the kernel is appropriately configured. (provision is made for necessary drivers), and that things were appropriately configured for your user.
Under whatever terminal, fire amidi-l, a couple of devices should be list. Like on mine :
acoswt@Tux ~ $ amidi -l
Dir Device    Name
IO  hw:1,0    Virtual Raw MIDI (16 subdevices)
IO  hw:1,1    Virtual Raw MIDI (16 subdevices)
IO  hw:1,2    Virtual Raw MIDI (16 subdevices)
IO  hw:1,3    Virtual Raw MIDI (16 subdevices)
IO  hw:2,0    M Audio Audiophile 24/96 MIDI

Then, you are correct, you'll need some software synthetizer like fluidsynth. So just install it (together with whatever sf2 compatible soundfount, preferably at least some general midi compatible font).
I suggest you also install qsynth (a gui that will ease your experience on fluidsynth)
Then after having launched fluidsynth, then your pygame, you'll have to use aconnect to connect some pygame midi output port (obtain the port number thanks to aplaymidi -l) to some fluidsynth midi input port. (obtain port number thanks to arecordmidi -l)
Of course, since you'll be playing with alsa directly, I warmly suggest not to be polluted by any sort of sound server.


text:
Q: VB.NET Dynamically creating variables at runtime I would like to create variables at run time when my application launches, or when called from within. The situation for this requirement is that I am reading data from various devices across the site and currently this is hard coded within the application. What I would like to do is create an application that loads a list from a database of the required variables and creates and assign them as required.
I am using the INGEAR driver package to read the data, I will require to declare multiple PLC's and for each of those PLC's I will need to declare Multiple ScanGroups and each ScanGroup will have multiple Tags for it. The read data will then be written to a database on each read.
Declaring each of this at design time (from a sample application INGEAR provides) is
    ' *****************************
' * Initialize Controller class
Public MyPLC As New Controller

' ******************************
' * Initialize TagGroup class
Public scanGroup As New TagGroup

' ******************************
' * un-initialized Tag class
Dim WithEvents newTag As Tag

Using the "WithEvents" they are able to create the tag's dynamically, but not 100% sure on how that works and how to implement this further.
When they add the tag when the application is running, they do something along:
newTag = New Tag(MyPLC, _tagName.Text)

and also
AddHandler newTag.Changed, AddressOf newTag_Changed

Which I assume is used to capture the change (and invoke from the thread)
Is there anyone who can give me some guidance on:

*

*How can I declare my PLC's at runtime from a list/array/structure

*How can I Declare the scangroups for each PLC at runtime (these are known as there will be a set for each PLC)

*How can i add the Tags at runtime.

I assume that the example is going down the right track, but was not 100% sure what each item is trying to achieve.
If anyone would like some more details on the application/sample please let me know.
ADDITIONAL
So working through this code, I'll assume that in my database I have 3 tables.
PLC Table - PLC_ID, PLC Name, PLC_IPaddress
SCAN Group - GROUP_ID, Group_Name, Group_Time
TAGS - TAG_ID, PLC_ID, GROUP_ID, Tag_Value

Variables:
Dim ALLPLCs As New Dictionary(Of String, Controller)
Dim ScanGroups As New Dictionary(Of String, TagGroup)
Dim AllTags As New Dictionary(Of String, Tag)

Creating the "Controllers" is simple enough using:
    For Each row In PLCTable.Rows
        ALLPLCs.Add(row("PLC_ID"), New Controller(row("PLC_IP"), 1000))
    Next

Creating my Groups is below, but starting to get worried about the tracking of items. This will create it with a name like '1_1', '2_4' with the first number being the PLC_ID and the second the GROUP_ID
    For Each row In ScanGroupTable.Rows
        For Each thePLC In ALLPLCs
            Dim tg As New TagGroup
            tg.Controller = thePLC.Value
            tg.ScanningMode = TagGroup.SCANMODE.ReadOnly
            tg.Interval = Convert.ToInt16(row("GROUP_TIME"))
            ScanGroups.Add(thePLC.Key & row("GROUP_ID"), tg) 'Add the 1 second scangroup
        Next
    Next

Now the next query is how to add my Tags to the dictionary for each PLC_ID and GROUP_ID. Any Direction on this? When creating a static tag, i would do something along the lines of below, but how to do this correctly by selecting the correct PLC and Scangroup?
 Dim tg As New Tag
    tg.Controller = "CONTROLLER"
    tg.Name = "TAG_NAME"
    ScanGroups.Add(tg)

after that, the system scangroups will automatically do the threads to update on it's interval. In the sample project, when adding a tag dynamically, the use the following:
AddHandler newTag.Changed, AddressOf newTag_Changed

This is where i'm a little stuck. How to add the handler for each of the tags at runtime correctle and capture their changes

A: You could use a dictionary or similar structure to keep track of all of the items you create.
public Dictionary<string, Controller> AllPLCs { get; set; }
public Dictionary<string, TagGroup> ScanGroups { get; set; }
public Dictionary<string, WithEvents> AllNewTags { get; set; }

From here, you can load from the database and add to the dictionaries in a loop, using the name as the string key.
foreach(var foundItem in LoadedData)
{
    AllPLCs.Add(foundItem.Name, new Controller());
    ScanGroups.Add(foundItem.Name, new TagGroup());
    AllNewTags.Add(foundItem.Name, new WithEvents());
}

Later you can access each one as follows:
foreach(var foundItem in LoadedData)
{
    Controller currentController = AllPLCs[foundItem.Name] as Controller());
    TagGroup currentGroup = ScanGroups[foundItem.Name] as TagGroup;
    WithEvents currentEvent = AllNewTags[foundItem.Name] as WithEvents;
}

My code examples are in C#, but they should get you on the right track.


text:
Q: how to run word count program in hadoop 2.6.0 installed on ubuntu 14.04? sudo javac -classpath /usr/local/hadoop/share/hadoop/common/hadoop-common-2.6.0.jar:/usr/local/hadoop/share/hadoop/common/lib/hadoop-annotations-2.6.0.jar:/usr/local/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.6.0.jar WordCount.java

I do not understand the command that I need to write in place of javac -classpath.

A: You should also add output destination folder path for class files in your command.
Follow these steps.

*

*Create the destination directory for the class files. For Example, it is called intersect_classes.
mkdir intersect_classes

*Compile the program.
sudo javac -classpath /usr/local/hadoop/share/hadoop/common/hadoop-common-2.6.0.jar:/usr/local/hadoop/share/hadoop/common/lib/hadoop-annotations-2.6.0.jar:/usr/local/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-client-core-2.6.0.jar -d intersect_classes WordCount.java

*Create the jar "intersect.jar"
jar -cvf intersect.jar -C intersect_classes/ .

*Copy the input file from the local source to the hadoop file system
bin/hadoop dfs -put <path of input in localFileSystem>/inputfile <path of input in HDFS FileSystem>/inputfile

*Run the application :
bin/hadoop jar intersect.jar Intersect <path of input in HDFS FileSystem>/inputFile <paht of output in HDFS FileSystem>/output

*Output:
bin/hadoop dfs -cat <path of output in HDFS FileSystem>/output/*

The output folder may contain more than one output files depending on the number of reducers. The contents of the exact file can be viewed by replacing '*' with the filename present inside the output folder.

*

*Retrieve the output file from the hadoop file system to the local destination:
bin/hadoop dfs -get <path of output in HDFS FileSystem>/output <path of output in HDFS FileSystem>/output


text:
Q: what is the change a value of a string Variable ina static-Method ?What is the scope of the String variable in java method.if(h=="abc") -an invalid if I have a simple Java method here Below , which passes a string , but inside the method another string variable is to be assigned a value.
But its not assigning new value- based on the String Input. Instead returning "NA".
Kindly have a Look and help me find the fault in the code.
Suppose if h is "NRM" even then aId = "NA", not "01"
 private static String getAID(String h) {

    System.out.print("AId : 01 to 25 for "+h);
     String aId = "NA";
     if(h == "NRM") {
        aId= "01";
        System.out.print("inside Nrm of fn"+aId);
     }
     Scanner scanner = new Scanner(System.in);
     if(h=="EPB") {
            System.out.print("Emergency ON/OFF press 1 or 0  - ");
             String in= scanner.next();
             if(in == "0") aId="11";
             else if(in=="1") aId="10";
             else { aId="10";}
        }
     if (h=="CRT") {
            aId="16";
            System.out.print("Critical Alert Enter 16/03/17/22/23/20/21 - ");
            String in= scanner.next();
            String[]  arr = {"16","03","17","22","23","20","21","13","14","15","06","04","05","09","18","19"};
            for(String i : arr) {
                if( i.equals(in) ) aId=in;
            }   //aId="04";
    }
    if(h=="BTH" || h=="ALT") {
            aId="13";
            System.out.print("AId Enter :/13/14/15/06/04/05/09/18/19 - ");
            String in= scanner.next();
            String[] arr = {"16","03","17","22","23","20","21","13","14","15","06","04","05","09","18","19"};
            for(String i : arr) {
                if( i.equals(in) ) aId=in;
            }

    }
    switch(aId) {
    case "01":System.out.println("Normal 2");
        break;
    case "02":System.out.println("l History");
    // remaining cases

    // remaing cases //

    case "23":System.out.println("IMPACT");

    default: System.out.println(" Wrong Entry -is"+aId );
    }

    return aId;

}

Here when I checked , It s never Entering the If Statements at all... But instead entering default part of the Switch case and return aId = "NA" ;


text:
Q: Allowing form post across subdomains while using anti-forgery token I'm wondering if it's possible to allow a form post from a subdomain to the main domain while still using the MVC anti-forgery token. A client has just moved a content section from within their WWW site to a dedicated subdomain. The sites still share the same navigation but the content and URL are unique. The navigation component, which is shared, contains the general site search.
The current site search is via a form post, which utilizes an Anti-Forgery Token. However, when posting from subsite.domain.com to www.domain.com we receive an error that

The anti-forgery cookie token and form field token do not match

From what I can see the generated tokens for each domain are unique and therefore, I believe they won't match when trying to decrypt on the receiving end.
Typically, I've always done site search like this using a GET with a query string, but they were originally looking to prevent any malicious usage of the site search, I believe.


text:
Q: Do python packages (multi-file modules) behave exactly as one big module? I've just read an article that supposedly introduced me to a new concept: Up to now I was sure that python packages (i.e directories with an __init__.py file) behave exactly the same as java packages, that is - little namespaces to help arrange the code (minus java's "package" scoping).
But, according to this link:
A Short Digression Into Multi-File Modules, if I put all my files in the same "package":

the entire collection of files is presented to other Python code as a single module — as if all the functions and classes were in a single .py

So now I thought that my whole understanding of the python "package" thing was wrong. Moreover - it's entirely not a package, rather a "multifile module" as the author refers to it.
So, from what I understood, no matter to how many files I divide my funcs and classes inside a package, from the outside that package should appear as though I took all the code from all the files inside the package and put it in one big file with the same name as the package instead, i.e as one module.
e.g, if I have the following file structure:
/base
    /animals
        /__init__.py
        /dog.py

and in dog.py:
def bark():
    print "woof"

it should be exactly the same as having:
/base
    /animals.py

and in animals.py:
def bark():
    print 'woof'

thus, this next piece of code should run fine on both cases:
from base import animals
animals.bark()

This of course yields in the first case:
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'bark'

What am I missing here? I see by the exception that "animals" is indeed treated as a module, but it appears i still have to explicitly state animals.dog.bark, i.e the internal file structure of the package isn't abstracted from the outside.
Am I missing the author's point, or just not implementing it correctly?
=== EDIT ===
Just to make sure no one misses this line in the quote:

as if all the functions and classes were in a single .py

regardless of how to actually access this funcs and classes, the above quote explicitly states that if you have a func1 in file a and func2 in file b, regardless of which path will they be accessible from, if we denote this path as X then, according to the aforementioned quote, both X.func1 and X.func2 should work.

A: Maybe the point is simply that a package is just a specific type of module.
/base
    /animals
        /__init__.py
        /dog.py

It just means that anything that you define in or import into __init__.py will be visible inside the animals module.
So animals is a module (that is a package) and animals.dog is a module that is a submodule of animals, but not a package.
It also means that if you have a simple module animals you can supercede it by a package by the same name in the next version, and arrange so that your users won't notice the difference.
If you want that all classes from the package's submodules make up one single user-visible module (namespace), you have to define a line like this for each submodule, in __init__.py:
from animals.dog import *

A: The author has oversimplified things. He's saying that everything under animal can be seen as being in the same module, although the fact is that names in animal.dog will be in their own namespace.

A: Not a real answer, but as I'm not yet allowed to comment (sigh!):
Since diveintopython is much used/cited/referenced resource for Python programmers (at least when they begin with), you should really contact the author about this flaw as it will be misleading also to others. There is some contact information on the home page of diveintopython3 and you can also file it as an issue on github.

A: I can't really explain it well, but maybe the following code will help. If I leave your first file structure as it is, and instead modify the second to have the following in the animals.py file:
class Dog:
    def bark(self): pass
dog=Dog()

Then in both cases,
from base import animals
animals.dog.bark()

will work.


text:
Q: O que define uma boa lógica? Estava pensando sobre algumas questões de códigos que alterei e me lembrei do que o meu professor do curso de desenvolvimento android falava e fazia: "Uma boa lógica tem poucas linhas de código". Perguntei para algumas pessoas que me disseram que isso depende. Mas depende do que? Claro que quanto menos código, mais rápido o processamento. Alguém pensa o contrario disso e tem um exemplo concreto disto?

A: O que o seu professor comentou está certo, de um modo geral.
Um problema que ocorre é alguns entendem de forma errada o trecho "quanto menos código melhor".
Então fazem "códigos espagueti" para justificar menor quantidade de linhas.
Ter uma menor quantidade de códigos não quer dizer melhor performance em determinados casos.
Depende dos recursos da linguagem com a qual está trabalhando e qual o objetivo.
Um exemplo simples com JavaScript:
Com Jquery, podemos selecionar um elemento dessa forma
elemento = $('#id_do_elemento');

Simples, não ?
Vamos ver como fica sem JQuery
elemento = getElementByID('id_do_elemento');

Simples, porém, usa maior quantidade de caracteres.
Então isso quer dizer que usando JQuery é mais performático?
Não, pois foi necessário carregar uma library de 400kb para poder ter esse tipo de recurso.
Logicamente, se o uso da library for necessário para tarefas mais complexas ou mesmo um uso relativamente grande mesmo de funções muito pequenas, recomenda-se o uso da library.
Aí que entra a lógica em determinar, ter bom senso de discernir o que pode ser melhor empregado.

A: Vamos assumir que sua lógica ou algoritmo é quasi-ótima (i.e. matematicamente falando, não existe um procedimento ou prova diferente que chegue ao mesmo resultado com um número substancialmente menor de passos). Ou seja, sua lógica conceitual está bem definida. Resta então realizar essa lógica através de código - um problema de engenharia, vamos dizer - o que demanda um tipo diferente de estratégia. É nesse contexto, acredito, que se enquadra a afirmação do seu professor.
Um código não existe no vácuo. Ele está inserido em um ambiente que possui suas próprias rotinas, bibliotecas built-in ou externas, além de código que você mesmo escreveu. Tudo isso são recursos que você pode ou não utilizar a seu favor ao planejar uma solução.
Reutilização de Código
Em geral, se você pode reutilizar um código já pronto sua solução será mais simples/concisa. Nem sempre isso é verdade (ex.: se o código pronto exige uma infinidade de parâmetros e configuração, e você só pretende usar um subconjunto ínfimo de sua funcionalidade), mas via de regra será. E embora a solução completa tenha mais código, há uma separação de responsabilidades entre sua lógica e cada uma de suas dependências.
Portanto, para se conseguir uma lógica simples, o primeiro passo é conhecer bem seu ambiente, saber quais recursos estão à disposição e se eles se aplicam ou não ou seu caso.
Performance
Contrário ao senso comum, menos código não significa necessariamente melhor performance. Mesmo quando bibliotecas externas não estão envolvidas. Um exemplo clássico são os algoritmos de ordenação, em que os mais simples normalmente são os menos eficientes. Para se atingir a melhor performance muitas vezes é preciso complicar, explorar peculiaridades do seu domínio, e abandonar a "pureza" do seu modelo conceitual em prol da solução mais adequada ao contexto.
A pergunta é: isso é mesmo necessário? Na grande maioria dos casos, a resposta é não - você não precisa que a performance do seu programa seja a melhor possível. Citando o exemplo do Daniel Omine, ok, carregar uma biblioteca de 400kB para salvar uns poucos caracteres parece uma má ideia, mas será que é? Em primeiro lugar, o código jQuery é mais limpo, mais fácil de escrever, e com menos problema de incompatibilidade entre browsers. Em segundo lugar, o código JavaScript costuma ser pequeno, e ser ativado em resposta a uma ação do usuário, de modo que a performance não é crítica. Em terceiro, com caching você pode carregar essa biblioteca uma vez e usar em diversos pontos diferentes do seu sistema.
Ou seja, se* sacrificando um pouco a performance pode-se ter um código mais simples e conciso, é bom considerar essa possibilidade.
* se e somente se - quando seu código for servir de base para diversos outros sistemas (ex.: você está desenvolvendo uma biblioteca que poderá ser usada em cálculos pesados), vale a pena sacrificar a simplicidade em nome da performance.
Nível de Abstração
Por fim, para se ter um código conciso é necessário se programar no nível de abstração certo. Se você precisa ler uma estrutura de dados de um arquivo, fazer alguma coisa com ela, e salvar os resultados em outro arquivo, não é bom misturar no mesmo código responsabilidades diferentes (ex.: abrir o arquivo e ler seus bytes; interpretar esses bytes como tipos de dados da linguagem; colocar esses dados na estrutura que você vai usar; usar a estrutura).
Muitas vezes isso significa reutilizar código pronto, como abordado anteriormente. Em outras, é questão de quebrar seu problema em problemas menores (i.e. "dividir para conquistar", como mencionado por Zanoldor), resolver cada um deles e então compor a solução final fazendo uso das soluções individuais.
Em outras palavras, o código total que você escreve pode até ser grande, mas cada função ou módulo individual deve preferencialmente ser conciso.
Conclusão
Uma boa lógica não precisa necessariamente ter poucas linhas de código, mas um código extenso pode ser sinal de que há problemas com sua lógica (onde há fumaça, pode ter fogo). Pode ser caso de reinventar a roda, ter otimização prematura, não estar no nível correto de abstração. Em uma outra pergunta eu dei uma resposta detalhando um pouco mais a questão da concisão do código. E com a ressalva que há muitos casos em que um bom algoritmo demanda sim código extenso.

A: Acredito que a velha máxima dividir para conquistar é uma boa prática. Fazer códigos com tamanho razoável, bem modularizado, bem orientado a objetos ajuda no gerencialmente de memória, mas acima de tudo, ajuda na manutenção do código. Quando a aplicação se torna grande e com muitas pessoas usando, os problemas e/ou novas implementações surgem e é neste momento que você descobrirá se vai ficar louco ou se simplesmente adicionará um módulo.


text:
Q: Is CollectionUtils.isNotEmpty() better than a null check? Many advice to use CollectionUtils.isNotEmpty(coll) rather then coll != null in the below use case also.
if (CollectionUtils.isNotEmpty(coll)) {
    for (String str : coll) {
    }
}

instead of
if (coll != null) {
    for (String str : coll) {
    }
}

Is there any reason/advantage to use CollectionUtils.isNotEmpty(coll) instead of other here? Thanks.

A: No real advantages here. Even if there is, it would be extremely small. It just prevents the creation of an Iterator and executing a branch instruction, that's all there is to it.
This small advantage occurs only when the collection is empty. The following loop:
for (String str : coll) {
   ...
}

is equivalent to:
for (Iterator<String> iterator = col.iterator(); iterator.hasNext();) {
   String str = iterator.next();
   ...
}

When the collection is empty, the check on CollectionUtils.isNotEmpty(coll) prevents the loop from executing. Hence no Iterator is created in memory and no call to hasNext() is done. This is at the expense to a O(1) call to coll.isEmpty().

A: Decompiling reveals
public static boolean isEmpty(Collection coll) {
    return coll == null || coll.isEmpty();
}

A: As explained above it depends, what you want to test and how is your logic constructed.
Suppose your example
if (CollectionUtils.isNotEmpty(coll)) {
  for (String str : coll) {
     System.out.println("Branch 1. Collection is not empty.");
  }
}
else {
  System.out.println("Branch 2. Collection is empty.");
}

In this example, we can see, that always Branch1 or Branch2 is executed.
If we use null expression, the result will be different if coll is not null but empty
if (coll != null) {
  for (String str : coll) {
     System.out.println("Branch1. Collection is not empty.");
  }
}
else {
  System.out.println("Branch2. Collection is empty.");
}

If the collection coll is not null but it is empty, nor Branch1 either Branch2 is executed, because the condition coll != null is true, but in loop for there is not even one pass.
Of course, if expression coll != null && coll.isNotEmpty() doing the same work as CollectionUtils.isNotEmpty(coll).
Therefore it not advisable programming manner to use test on null in case of collections coll != null only. This is a case of poorly treated extreme conditions, which may be a source of unwanted result.

A: The issue is, that the collection can still be empty, when it is not null. So, in your case it depends on your preferences what you choose.


text:
Q: Dockerfile attempting to 'apk add composer' failing? I am attempting to learn Docker, and have run into a snag. My docker file is as follows
# Base image of a nginx box
FROM richarvey/nginx-php-fpm:latest

ARG VERSION=0.0.0
ENV APP=jewel
ENV WEBROOT=/var/www/html/JEWEL_WEB_ROOT/

WORKDIR /var/www/html
COPY ./ ./

# Install composer libs
RUN echo "ipv6" >> /etc/modules
#RUN ["apk","update"]
RUN ["apk","add","composer", "--no-cache"]
RUN ["composer","install"]

ENV PORT=80
EXPOSE 80

When the build process gets to the apk add, I get the following:
Step 8/11 : RUN apk add composer --no-cache
 ---> Running in ffa506b1a07f
fetch http://dl-cdn.alpinelinux.org/alpine/v3.4/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.4/community/x86_64/APKINDEX.tar.gz
fetch http://nl.alpinelinux.org/alpine/edge/testing/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  composer-1.5.2-r0:
    masked in: @testing
    satisfies: world[composer]
ERROR: Service 'web' failed to build: The command 'apk add composer --no-cache' returned a non-zero code: 1

I've checked the package listings (on pkgs.alpinelinux.org), and there is a package that seems to meet the criteria, which it seems to be finding?

I am confused why it seems to find the package, but won't install it for me.

A:
composer-1.5.2-r0:
    masked in: @testing

It seems that author of that (horribly outdated!) Dockerfile pinned testing repository, so you have to append @testing to the package name:
apk add composer@testing

However, I'd not expect it to work due to different PHP versions (v3.4 is very old release).


text:
Q: finding part of a string and using it as its own value in php In the example below can someone tell me how can i remove the number after no. and use it as a value?
No.311 11/12ozs

A: $string = 'No.311 11/12ozs';
preg_match('/No\.([0-9]+)/is', $string, $matches);
// result would be in $matches[1]


text:
Q: jQuery: Switch from submit buttons to -tag I am trying to change a lot of button controls to a-href and keep the functionality:
Thus I decided to create a hidden tag based on the id of the a-tag and use this to decide how to process the request:
var $hidden = $("<input type='hidden'/>", { name: $(this).attr("id") });
$("form").append($hidden).submit();

Unfortunately, the above-mentioned code just creates an empty input tag of type hidden but without the "name"-tag.
The following code works, but is ugly:
var $timeVar = $("<input type='hidden' name='"+$(this).attr("id")+"'/>");

What's goind on there?
Thanks a lot!

A: I believe you can do this:
var $hidden = $("<input type='hidden'/>").attr({ name: $(this).attr("id") });

You can also just append it straight to the form by chaining:
$("<input type='hidden'/>").attr({ name: $(this).attr("id") }).appendTo("form");

A: Apparently you can't mix adding attributes directly in the string of the tag as well as in the 2nd parameter.  Just move all attributes into the same place:
var $hidden = $("<input/>", {
                  name: $(this).attr("id"),
                  type: "hidden"
              });


text:
Q: Excel Count /Unique Dynamic Array I need to count unique values between two columns I have tried count(Unique())formula.
Results entered all values instead of separate value with column
Input :
Date       Name
1/1/2022    A
1/1/2022    A
1/1/2022    B
1/2/2022    B

Output :
Column D  Column E
A          1
B          2

A: Use LET with BYROW and LAMBA in a FILTER:
=LET(dt,A2:A5,nme,B2:B5,unqnme,UNIQUE(nme),unqall,UNIQUE(CHOOSE({1,2},dt,nme)),cnt,BYROW(unqnme,LAMBDA(a,COUNT(FILTER(unqall,INDEX(unqall,0,2)=a)))),CHOOSE({1,2},unqnme,cnt))

A: UNIQUE DISTINCT COUNT
Well, earlier the query was bit confusing, although it was clear that OP needed Unique Distinct Count, but wasn't sure whether needed those colons : in between and Name in beginning or not . However here is another way you may also try.
• Formula used in cell D2
=UNIQUE(B2:B5)

• Formula used in cell E2
=COUNTA(UNIQUE(FILTER($A$2:$A$5,D2=$B$2:$B$5)))

Alternative formula to get unique distinct counts
• Formula used in cell F2
=SUM(--(FREQUENCY(IF($B$2:$B$5=D2,MATCH(A$2:A$5,A$2:A$5,0)),ROW(B$2:B$5)-ROW(B$2)+1)>0))

A: If i understand your question, maybe this can help you:
=COUNTA(UNIQUE(A2:A5&B2:B5))
A column is date and B column is Name


text:
Q: Is there any easier way to test release steps then this cycle I am testing SQL scripts deployment automation using VSTS, the cycle I am following to test if my release cycle is working for different scenarios is as follow,

*

*Make changes to SQL Project in VS, build and push to VSTS repo

*Make changes to release steps for deploy dacpac if required

*Create a new release

*Deploy and repeat for redeploy

I have to test lots of scenarios including but not limited to followings,

*

*Add a new table to sql project and test if it works

*Delete a column and rollback changes if something goes wrong

*Modify column and check if any data loss happens...

*etc..

A: Refer to these steps:

*

*Create database unit test project to do test with database: Walkthrough: Creating and Running a SQL Server Unit Test

*Refer to this article to deploy Database: Deploy your database to Azure SQL Database using DACPACs (If you are not using azure DB, using WinRM - SQL Server Database Deployment instead)

*Add Visual Studio Test to run database unit test


text:
Q: MYSQL delete duplicates values from a select concat Hello i created a query for get the titles of columns (for import in vba)
SELECT CONCAT( GROUP_CONCAT(column_name)) as columns
FROM information_schema.columns
WHERE table_name = 'trans_int_prix_gen'
   OR table_name = 'trans_int_prix_module'
   OR table_name = 'matrice_sigma'
ORDER BY column_name ASC;

I want improve the request by deleting values which are equal to 2 fields in this request. Or delete duplicated values of thoses 2 fields
thanks
the result look like this
SIGMA, UV, TOP, EAN, CM, SIGMA, UV, 1, 2, 3 ,4 ,5, SIGMA, UV, 3, 4, 5

I want display in the result SIGMA, UV only one time

A: Use GROUP_CONCAT with DISTINCT:
SELECT GROUP_CONCAT(DISTINCT column_name) AS columns
FROM information_schema.columns
WHERE table_name = 'trans_int_prix_gen'    OR
      table_name = 'trans_int_prix_module' OR
      table_name = 'matrice_sigma';

Note that the ORDER BY clause in your current query doesn't do anything, since there will always be just a single record in the result set.  What you wanted to do is this:
SELECT GROUP_CONCAT(DISTINCT column_name ORDER BY column_name) AS columns
...

But by default column_name will be used for sorting the CSV string, so we don't need to explicitly use an ORDER BY clause with GROUP_CONCAT in this case.


text:
Q: npm install not working: EADDRINUSE I am unable to use npm install no way how much i tried.
npm: 2.14.12
node: v4.2.4
This is the error i get:
$ npm install --no-bin-links
npm ERR! fetch failed https://registry.npmjs.org/gulp/-/gulp-3.9.0.tgz
npm WARN retry will retry, error on last attempt: Error: connect EADDRINUSE 23.235.43.162:443 - Local (undefined:undefined)
npm ERR! fetch failed https://registry.npmjs.org/gulp/-/gulp-3.9.0.tgz
npm WARN retry will retry, error on last attempt: Error: connect EADDRINUSE 23.235.43.162:443 - Local (undefined:undefined)
npm ERR! Windows_NT 10.0.10586
npm ERR! argv "E:\\Program Files\\nodejs\\node.exe" "E:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--no-bin-links"
npm ERR! node v4.2.4
npm ERR! npm  v2.14.12
npm ERR! code EADDRINUSE
npm ERR! errno EADDRINUSE
npm ERR! syscall connect

npm ERR! connect EADDRINUSE 23.235.43.162:443 - Local (undefined:undefined)
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     E:\xampp\htdocs\projects\??????\intern\npm-debug.log

I have tried npm install, npm install --production, and npm install --no-bin-links also i tried to remove node_modules folder and npm cache clear before i tried any of those commands.
I tried to lookup the IP and this was the result.
$ nslookup 23.235.43.162
*** 23.235.43.162 wurde von google-public-dns-a.google.com nicht gefunden: Non-existent domain.
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

This is my package.json
{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8",
    "laravel-elixir-sass-compass": "^0.5.0"
  },
  "dependencies": {
    "laravel-elixir": "^4.0.0",
    "bootstrap-sass": "^3.0.0"
  }
}

This is part of the --verbose output
...
npm info retry fetch attempt 1 at 15:19:47
npm info attempt registry request try #1 at 15:19:47
npm http fetch GET https://registry.npmjs.org/laravel-elixir/-/laravel-elixir-4.2.0.tgz
npm info retry will retry, error on last attempt: Error: connect EADDRINUSE 23.235.43.162:443 - Local (undefined:undefined)
...

I have this problem for a month now but at that time i was running on Windows 7 i recently upgraded to Windows 10.
I hope someone is able to help me.


text:
Q: Python max() takes no keyword arguments I have a script that I wrote on a machine running Python 2.7.3 that utilizes the max function with a key along with glob to find the youngest file of a specific type in a directory. I tried to move this onto another machine only to discover that it's running Python 2.4.3 and the script doesn't work as a result.
The problem arises with the following line:
newest = max(glob.iglob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)

I've looked up the documentation and can see that both iglob and max with a key aren't available until Python 2.5 >
I can change the iglob reference to just glob and get rid of the case insensitivity which works fine. But I'm not sure how to rewrite the above without using max along with a key?

A: I'm not certain what tools Python 2.4 has access to, but I'm pretty sure you still have list comprehensions, so you could tuple your list together with the key you want to use, compare, and then unpack. This works because tuples compare element-wise, so if you put the "key" at the front of your tuples, it'll act as the primary comparator.
# Note: untested
times_files = [(os.path.getctime(f),f) for f in glob.glob(bDir+'*.[Dd][Mm][Pp]')]
newest = max(timed_files)[1] # grab the filename back out of the "max" tuple

Alternately (and likely faster, if it matters for your use case), as @jonrsharpe pointed out, the sorted function does allow a key argument, so you could also sort your list and grab the last item:
newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]

A: In Python 2.4.x, sorted does take a key; you can apply this to your glob and take the last item, for example:
newest = sorted(glob.glob(bDir + '*.[Dd][Mm][Pp]'), key=os.path.getctime)[-1]

A: Just write your own, using the classic DSU method:
try:
    # At least give it a chance, in case a modern version of Python is running,
    # it would be faster
    my_max = max(my_list, key=my_func)
except:
    my_decorated = [(my_func(x), x) for x in my_list]
    my_max = max(my_decorated)[1]

You could even do something that the top, that overrides the built-in max function for your version, if you need to do this a lot in the code and don't want to put this in every location...


text:
Q: TMDb redirect to website after user is logged in I have a website using TMDB's api. When the user wants to log in he is redirected from my website to TMDb's website to do it. I'd like to redirect him to my website once he's logged in. I'm using javascript to redirect him to TMDb's website :
function load(){
        data_from_django = "{{ my_data }}";
        window.location.href = data_from_django;
    }

Any idea ?
Thanks !

A: The doc you included in your question tells you that you need to pass a redirect_to parameter

You can also pass in a redirect_to param when making this call which will redirect the user once the authentication flow has been completed.

So just do that, I presume this is a get parameter in which case you'd need to add
?redirect_to=www./myurl/

to wherever you construct the authenticate url
https://www.themoviedb.org/authenticate/REQUEST_TOKEN?redirect_to=www./myurl/


text:
Q: APIs to handle the app resume in RecyclerView in android I have a RecyclerView :
class MyCustomRecyclerView @JvmOverloads constructor(...) : RecyclerView(...)
{
    override fun onSaveInstanceState(): Parcelable? {
        Log.i("MY_TAG", "onSaveInstanceState")
        return super.onSaveInstanceState()
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        Log.i("MY_TAG", "onRestoreInstanceState")
        super.onRestoreInstanceState(state)
    }

    override fun onDetachedFromWindow() {
        Log.i("MY_TAG", "onDetachedFromWindow")
        super.onDetachedFromWindow()
    }

    override fun onAttachedToWindow() {
        Log.i("MY_TAG", "onAttachedToWindow")
        super.onAttachedToWindow()
    }
}

And I am using this RecyclerView in a Fragment
class MyCustomFragment: Fragment()
{
    override fun onResume()
    {
        super.onResume()
        startSomeWork()
    }

    override fun onPause()
    {
        super.onPause()
        stopSomeWork()
    }
}

On clicking the "home" button and launching the app again from the recent apps, the onPause() and onResume() APIs of the fragment are getting called and I am able to startSomeWork() and stopSomeWork().
But I want to do the same thing from my RecyclerView instead. I tried to capture the logs of  some APIs mentioned above. On clicking the "home" button,onSaveInstanceState() is getting called. But when launching the app again from the recent apps, none of these APIs is getting called.
I would like to know if there are any such APIs which I can use for my purpose?


text:
Q: maven applying proxy to nonProxyHost I have the following proxy set up in my settings.xml file
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>someusername</username>
  <password>somepassword</password>
  <host>some.proxy.host.com</host>
  <port>5150</port>
  <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>

But it still applies the proxy to my localhost, everytime I have to do something with localhost I have to change active to false.

A: According to the docs[1] you can set
<useProxy>false</useProxy>

to prevent this from happening.
[1] http://dev.day.com/docs/en/cq/current/core/how_to/how_to_use_the_vlttool/vlt-mavenplugin.html#Common%20Parameters

A: if you are looking to deploy on localhost
try this
<nonProxyHosts>*localhost*</nonProxyHosts>

should work


text:
Q: How to bind fields dynamically to the Angular Controller?
My form has dropdown lists in the below fashion.
Main category : |Dropdown A|
First sun-category : |Dropdown B|
Second sub-category : |Dropdown C|
Based on |Dropdown C|futher I will populate dropdowns
dropdowns=|Dropdown e| |Dropdown f| |Dropdown g| and so on..
So, based on Dropdown C dropdowns will change.
I can bind Dropdown A| |Dropdown B| |Dropdown C| like this ng-model="main-category",ng-model="sub-category", & ng-model="sub-sub-category" respectively.
But how can I bind |Dropdown e| |Dropdown f| |Dropdown g| , because they keeps on changing whenever there Dropdown C changes?

Sample  Code :
Main category:
<select>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>

</select>

Sub-category
<select>
  <option value="d">d</option>
  <option value="e">e</option>
  <option value="f">f</option>
  <option value="g">g</option>
</select>

Sub-sub category
<select>
  <option value="h">h</option>
  <option value="i">i</option>
  <option value="j">j</option>
  <option value="k">k</option>
</select>

Based on sub-sub category selection I want to show/hide dropdowns.
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

So, out of above mentioned, few dropdowns will be hidden/shown.
I am saying hidden/shown, because I don't know another way to manage this scenario.

Please help.