text:
Q: I am getting failed to make TCP connection to port 8080: connection refused 10:07:34.779: [APP/PROC/WEB.0]  * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
10:08:34.562: [HEALTH.0] Failed to make TCP connection to port 8080: connection refused
10:08:34.562: [CELL.0] Timed out after 1m0s: health check never passed.
Though my code is working fine on local machine
class Health (Resource):#this piecc of code is to perform the health check of the application so that it can run successfully without crashing on cf
      def get(self):
        return "UP"

api.add_resource(Health, '/health')

if __name__ == '__main__': #read about uses of main
    app.run(port = '8080')

A: You need to make sure you're listening on something other than 127.0.0.1/localhost. That is not externally accessible so health checks and external traffic won't be able to access your app if you are only listening on 127.0.0.1/localhost.
The easiest way is to listen on 0.0.0.0, which listens on all interfaces. You could  technically listen on a specific IP, but that's more work and it ends up doing the same thing.
In my Python Flask apps which I run on Cloud Foundry, I end up doing something like this:
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5001)))

The second part is not technically necessary as PORT should always resolve to 8080, but that could change in the future so reading the PORT env variable is a good idea.
Hope that helps!


text:
Q: Array copying in PHP I am trying to save my _POST array to a _SESSION array so that I can use that in other pages of the website
when i do
$_SESSION = $_POST;

it didn't worked.
Also the following code also is giving a error and not copying it.
foreach($_POST as $element){
  $_SESSION[] = $element;
}

A: $_SESSION can't handle numeric keys; it must be an associative array. I.e. if you do
$_SESSION[] = "foo";

like you do in your foreach-loop, it'll create a new numeric key like in any other array (e.g. $_SESSION[0] == "foo"), but PHP will skip the key when saving the session. You get an "notice"-level warning like "Skipping numeric key 0". So the next time the $_SESSION array is read, it won't contain any numeric keys.
So you must use a string index, like:
$_SESSION['POST'] = $_POST;

That should work.
You should also be able to do $_SESSION = $_POST and overwrite the entire $_SESSION array. Can't say why that doesn't work. But I can't see why you would want to do it either. If you ever want to use $_SESSION for anything else (like, actual session data), you can't have your code randomly overwriting the entire array with post data here and there. Better to just use a string index like above to store the post data.

A: session_start();

if(!$_SESSION['POST']) $_SESSION['POST'] = array();

foreach ($_POST as $key => $value) {
    $_SESSION['POST'][$key] = $value;
}

var_dump($_SESSION['POST']);

redpajama_set_name: RedPajamaStackExchange


text:
Q: fill data automatically in a relationship table I'm developing a spring boot application which creates student accounts for a given student. The structure has a one to many relationship table created by the annotations. Now, every time I create a new student account, the student_id and student_account_id must be saved (automatically) in this relationship table which only contains the student_id and student_account_id as foreign keys. I don't know how to achieve that. Here's the code:
Student class:
@Entity
@Table(name = "student")
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private int studentId;
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinTable(name = "relationship_table",
               joinColumns =  @JoinColumn(name = "student_id"),
               inverseJoinColumns = @JoinColumn(name = "student_account_id"))
    private StudentAccount studentAccount;

StudentAccount class:
@Entity
@Table(name = "student_account")
public class StudentAccount implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "student_account_id", nullable = false)
private int studentAccountId;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "relationship_table",
           joinColumns =  @JoinColumn(name = "student_account_id"),
           inverseJoinColumns = @JoinColumn(name = "student_id"))
private Collection<Student> students;

Edit:
Here is how I build the student_account_object and save it:
@Override
    public StudentAccount save(StudentAccount studentAccount) {
        return studentAccountRepository.save(studentAccount);
    }

public void createStudentAccount(List<Student> studentsWithoutAccount) {
        for (int i=0; i<studentsWithoutAccount.size(); i++){
            String name = studentsWithoutAccount.get(i).getName();

            String username = name+"student";
            String password = username;

            StudentAccount studentAccount= new StudentAccount(username, password);
            save(studentAccount);

        }
    }

The save method in the repository that I use to save the object is the built-in save method from CrudRepository.
Should I write my own save method and insert the data in the relationship table manually?

A: First of all thanks to @JBNizet and @AlanHay for the support.
The problem was in the @OneToMany annotation, bad mapping. For a good source on how to do the mapping the right way go to this link. As soon as I fixed the bad mapping the project worked, it was inserting the data automatically but with the wrong foreign keys.
This was the result of creating the database from a data.sql file in my project. What i did was to erase this file. I´m using spring boot web mvc so i erased the data.sql file from the templates folder and from target/classes.
Then i persisted the entities to the database the way it should be Student student =new Student(); as well as StudentAccount studentAccount = new StudentAccount(); and all that did the trick.
Here is the code:
Student Class:
@Entity
@Table(name = "student")
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_id")
    private int studentId;
    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
    private Collection<StudentAccount> studentAccounts;

StudentAccount Class:
@Entity
@Table(name = "student_account")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "student_account_id", nullable = false)
    private int studentAccountId;
    @Column(name = "username")
    private String username;
    @Column(name = "password")
    private String password;

    @ManyToOne
    @JoinTable(name = "relationship_table",
            joinColumns =  @JoinColumn(name = "student_id"),
            inverseJoinColumns = @JoinColumn(name = "student_account_id"))
    private Student student;

Implementation method:
@Autowired
private StudentAccountRepository studentAccountRepository;
@Autowired
private StudentRepository studentRepository;
    public void createDatabase(){
            List<Student> students= new ArrayList<Student>();
            List<StudentAccount> studentAccounts= new ArrayList<StudentAccount>();

            Student student1  = new Student ("john");
            Student student2  = new Student ("david");
            Student student3  = new Student ("emma");
            Student student4  = new Student ("sophia");
            Student student5  = new Student ("mia");

            students.add(student1);
            students.add(student2);
            students.add(student3);
            students.add(student4);
            students.add(student5);

            studentRepository.saveAll(students);

            StudentAccount studentAccount1 = new StudentAccount("john", "john", student1);
            StudentAccount studentAccount2 = new StudentAccount("david", "david", student2);
            StudentAccount studentAccount3 = new StudentAccount("emma", "emma", student3);
            StudentAccount studentAccount4 = new StudentAccount("sophia", "sophia", student4);
            StudentAccount studentAccount5 = new StudentAccount("mia", "mia", student5);

            studentAccounts.add(studentAccount1);
            studentAccounts.add(studentAccount2);
            studentAccounts.add(studentAccount3);
            studentAccounts.add(studentAccount4);
            studentAccounts.add(studentAccount5);

            studentAccountRepository.saveAll(studentAccounts)
        }
**StudentRepository class:**

    @Repository
    public interface StudentRepository extends CrudRepository<Student, Integer> {

    }
**StudentAccountRepository class:**

    @Repository
    public interface StudentAccountRepository extends CrudRepository<StudentAccount, Integer> {
    }

And that's it. Thanks for the help!!


text:
Q: Error fixed,efficiency feedback Project Euler 12 This code is supposed to find the value of the first triangular number with 500 divisors. Problem 12 of ProjectEuler. I have used the help of others to fix an integer division by zero error on p. At this point I am wondering if anyone has a tip on how to simplify the problem. (Finding the first triangular number with 100 divisors takes ~1 minute, and the one with 500 never finished). At the moment I am trying to find a mathematical property that I might be able to take advantage of as doing things like attempting to skip prime numbers seems like it will take nearly just as long.
import itertools
count = 0
j = 0
for i in itertools.count():
    count = 0
    if i > 0:
        j = i*(i+1)/2
    for p in range (1, int(j**0.5)+1):
        if j%p == 0:
            count+=1
    if count > 250:
        break
print (int(j))

A: For every divisor of j less than its square root, there is exactly one divisor over its square root.  This fact is very useful and makes it possible to count the divisors of j while only iterating up to its square root.  This drastically reduces the amount of work needed.
Also, if count == 500: should be if count > 500:
I would post my code, but Project Euler discourages posting complete solutions to their problems.

A: You can get a 23 to 25% speed-up if you use xrange instead of range
I learned this concept from codereview
for example:
divisors(n,start):
    if n==1:
        return 1
    for i in xrange(st, int(math.ceil(math.sqrt(n)))+1):
        if n % i == 0:
            cnt=1
            while(n%i==0):
                n/=i
                cnt+=1
            return divisors(n,i+1)*cnt
    return 2

we find p, the first prime factor of n. If p^k is the maximum power of p that divides n, (k+1)*divisors(n/p^k) is the number of divisors of n. start is just a starting point for checking prime divisors.
for n in xrange(1,1000000):
    Tn=(n*(n+1))/2
    if n%2==0:
        cnt=divisors(n/2)*divisors(n+1)
    else:
        cnt=divisors(n)*divisors((n+1)/2)
    if cnt >= 500:
        print Tn
        break


text:
Q: passing function variables to another file python I need to pass data_connection into my main.py engine because that variable is where the data from mysql string is being stored. In main.py it says parameter data_connection unfilled but I can only enter 'data_connection=' I'm confused what I'm supposed to do...
load_file.py
def get_connection():
        cursor = connection.cursor()
        cursor.execute(
            "SELECT ID, Type, Server, Port, User, Password, isActive, FileExtension, FileContains, FileLocation, "
        "ScheduleMinutes, IntervalTime from DataConnection WHERE isActive=True")

        data_connection = cursor.fetchall()

def download_files(data_connection):

        for data_connection_detail in data_connection:
            # type email will be IMAP, POP3, or FTP
            connection_type = data_connection_detail[1]

            # create data_source object
            if connection_type == 'IMAP':
                ez_email.read_email_imap(data_connection_detail)

            elif connection_type == 'POP3':
                ez_email.read_email_pop3(data_connection_detail)

            elif connection_type == 'FTP':
                ez_ftp.easy_ftp(data_connection_detail)

main.py
from load_file import get_connection
from load_file import download_files

def run_engine():
    while True:
        get_connection()
        download_files()

if __name__ == "__main__":
    run_engine()

A: data_connection is a local variable in load_file.py that is destroyed when the function exits. You also have a like-named parameter in download_files. These are two different, unique variables created on each call to the function. They happen to have the same name, but in different namespaces so do not refer to the same thing.
The solution in this case is to return the object from the first function and use it as a parameter in the second.
load_file.py
def get_connection():
        cursor = connection.cursor()
        cursor.execute(
            "SELECT ID, Type, Server, Port, User, Password, isActive, FileExtension, FileContains, FileLocation, "
        "ScheduleMinutes, IntervalTime from DataConnection WHERE isActive=True")

        return cursor.fetchall()

def download_files(data_connection):

        for data_connection_detail in data_connection:
            # type email will be IMAP, POP3, or FTP
            connection_type = data_connection_detail[1]

            # create data_source object
            if connection_type == 'IMAP':
                ez_email.read_email_imap(data_connection_detail)

            elif connection_type == 'POP3':
                ez_email.read_email_pop3(data_connection_detail)

            elif connection_type == 'FTP':
                ez_ftp.easy_ftp(data_connection_detail)

main.py
from load_file import get_connection
from load_file import download_files

def run_engine():
    while True:
        data = get_connection()
        download_files(data)

if __name__ == "__main__":
    run_engine()

Notice that I didn't use the variable data_connection in the first function at all, just returned its data. And when calling download_files I used a different name for the variable. This highlights the difference between a named variable in one context and the object it references in another context.


text:
Q: Win10 starting Python PyQt5 application using shortcut Simply stated I have a simple python application which generates random passwords.  This application was originally written using Tkinter and currently works.  I am trying to improve the GUI interface by employing PyQt5.  My efforts, so far have resulted in an application that runs from within my IDE (Spyder) and can also be run by invoking python from the commandline with the fullpath of the python script.
It should be noted this works for the Tkinter as well as the PyQt implementation.
My next step was to define a shortcut on the desktop to execute this script and have a window appear allowing creation of a password.  The shortcut for the Tkinter script performs as expected and results in a window appearing.  The script for the PyQt5 based script does not work.  The only differences between the scripts are the target files being invoked by the script.  Also both script files are in the same directory.  This is a side by side image of the shortcut properties.

Here is a very simplistic example of the Puqt5 code.  This code exhibits the same characteristics as the original in that it runs in the IDE as well as directly from Python in the CMD window but will not execute from a shortcut icon.
"""
Created on Wed Sep  9 10:37:46 2020

"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget

def main():

    app = QApplication(sys.argv)

    w = QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Has anyone else had this type of problem or can anyone suggest an approach for determining what is the cause and solution

A: everything works on Windows 7

It work when invoked from a shortcut on Win &, hmm that's very strange.

I tested it on Windows 10 also works.

A: Thanks for the helpful suggestions as well as your efforts to test this problem on your own systems.  I finally found an answer that satisfies my needs.  I used pyinstaller to create an executable and then launch the executable from a desktop shortcut.  This works, so I am considering my question closed.


text:
Q: Big O for this recursive algorithm I did the following algorithm involving a Binary Heap structure:
Algorithm: heapMinimum(node)
Input    : Position n
Output   : Sequence minList; containing the postions that hold the minimum value

1. minList <-- sequence
2. if parent(node) == NULL // current node is the root of the tree
3.   minList.insertLast(node)
4. if (leftchild(node).element() == node.element())
5.   concat(heapMinimum(leftchild(node), minList))
6. if(right(node).element() == node.element())
7.   concat(heapMinimum(rightChild(node), minList))
8. return minList

What the algorithm does is basically traverse a Binary Heap given its root to find and store the nodes that hold the minimum value (ie the value that matches that of the root).
Now I'm having trouble calculating the running time, in Big O notation, of my algorithm.  The reason I'm getting confused is because of the recursion that is used to traverse the left and right children of each node.
All of the operations run in constant time, O(1), except concat. But how do I exactly go about in calculating the running time of such a recursive solution ?

A: Looks like O(N) to me, where N is the number of elements. If your heap contains nothing but equal elements, all the elements will be traversed. Also, why isn't concat O(1)? As long as you are "concatenating" numbers, it should also be O(1). If somehow concat is O(N) however (from your pseudocode it looks like it is - but you should reconsider if you really need to concatenate the two returned lists), then the total time would be O(N2) worst case.

A: I assume you are talking about a binary heap?
By definition of the heap properties, you should only be recursing until you find an element larger than what the root is. However, you must also be certain that none of the other elements at the current level of the tree are the same size as the root. Essentially, this yields the rule that once you encounter an element of the heap that is greater than the root, you do not need to recurse into the element's children.
However, in the worst case, each element may be equal to the root. In this case, you must check the entire heap, which yields O(n) time, where n is the number of elements in the heap.
So to answer your question, it is O(n)

A: As others have mentioned, if your concat() is O(1) [and if it's not, you can make it so] then your algorithm is O(N) in the size of the output.
However, if you used a concat() that copies your list (depending on the system, this can be easy to accidentally do), then your worst case is O(N^2) in the size of the output.  A case that causes this behavior is when your minimum nodes go deep into the tree, such that your concat() keeps copying the list at each level.
Note that this depth is bounded by the depth of your heap, so if your tree is balanced, this worst case is also O(M log M) in the size of the datastructure.  You can see this because the maximum number of copies is the depth of the tree.

A: I suppose you have a bug in your solution.
The first check:

if parent(node) == NULL

must be removed, but the check that node != NULL must be added.
Moreover, I suggest to use list as additional parameter, where you will put the answer.
So, that is my implementation:
Algorithm: heapMinimum(node, minList)
if (node != NULL)
{
   if (minList.empty() || minList.getFirst().element() == node.element())
   {
      minList.insertLast(node)

      heapMinimum(left(node),  minList)
      heapMinimum(right(node), minList)
   }
}

Assuming that adding an element to the list take O(1), we get that the function takes O(k), where k is the number of minimal values in the heap.
Enjoy.


text:
Q: Error trigger jquery Este div ,por defecto al pasar el mouse por encima de él se mueve con CSS3, ahora con jquery intento que cada 1000ms, se envié un lanzar como si estuvieran pasando el mouse, con motivo de que se mueva constantemente cada 1 segundo(1000ms)
El problema es que no me funciona y no entiendo que está mal.

<!DOCTYPE html>

  <link href="http://ogar.pw/assets/css/anim.css" rel="stylesheet">

A: Lo que tienes que hacer es adicionar una clase Active, y removerla cada intervalo

<!DOCTYPE html>

<link href="http://ogar.pw/assets/css/anim.css" rel="stylesheet">

A: No puedes simular el evento mouseover debido a que no es un evento de confianza.

Most untrusted events will not trigger default actions, with the
  exception of the click event. This event always triggers the default
  action, even if the isTrusted attribute is false (this behavior is
  retained for backward-compatibility). All other untrusted events
  behave as if the preventDefault() method had been called on that
  event.

La solución más sencilla es crear una clase css que dispare la animación/transición y añadirla/quitarla en cada iteración.
Ejemplo

const animate = () => {
  setTimeout(() => $('#box').addClass('active'), 1000);
  setTimeout(() => {
    $('#box').removeClass('active');
    animate();
  }, 2000);
};

animate();
#box {
  background: linear-gradient(to bottom, turquoise, gold);
  box-shadow: 0 2px 2px 0 rgba(0,0,0,.15);
  height: 150px;
  margin: 25px auto;
  transition: all 1s ease;
  width: 150px;
}

#box.active {
  transform: rotate(180deg);
}


text:
Q: Owl carousel infinite loop What i am trying to achieve is to make my owl carousel infinite loop. after the last image slider revert to first image from right to left but i want my images not to revert back it mean after last image the first image will be came from left to right.
here is my code
$(document).ready(function() {
         $('.five').owlCarousel({
loop:true,
margin:10,
autoPlay:true,
nav:true,
rewindNav:false,
responsive:{
    0:{
        items:1
    },
    600:{
        items:3
    },
    1000:{
        items:4
    }
}
  })
    });

A: When you use responsive class it always overwrite the top options.
So all you need is to add loop option to your responsive items.
responsive:{
  0:{
    items:1,
    loop:true
  },
  600:{
    items:3,
    loop:true
  },
  1000:{
    items:4,
    loop:true
  }
}


text:
Q: Creating a tile layout with overlaying text - are negative margins the wrong approach? I'm trying to create a basic tile layout with text overlaying each tile via negative margins.

.tile{float:left; margin-bottom:185px;}

.tile img{width:280px; height:290px; margin-right:5px; border:1px solid black;  }

h1{margin-top:-150px; background:rgba(0,0,0,.5); color:white; position:relative; max-width:280px;}

Hello world

Goodbye world

Hello world

Hello world

Unfortunately, at certain browser window sizes, the negative margin causes other tiles to overlap. But if I adjust the negative margin for a particular window size, then i'll have problems at other window sizes that were fine before:

What is the solution to this problem?

A:

.tile {
  display: inline-block;
  position: relative;
  width: 280px;
  margin-right: 5px;
  margin-bottom: 5px;
}
.tile img {
  width: 100%;
  height: 290px;
  border: 1px solid black;
}
h1 {
  position: absolute;
  top: 150px;
  left: 1px;
  width: 100%;
  background: rgba(0, 0, 0, .5);
  color: white;
}

Hello world

Goodbye world

Hello world

Hello world


text:
Q: How to conditionally compile a JAR in Android? I'm trying to make a conditional build in Android Studio, where I can reduce the size of the generated APK by removing any superfluous library dependencies if they're not needed for a particular distribution.
I've got some code which roughly approximates to the following:
public class MyClass {

    /* Static Declarations. */
    public static final boolean USE_LIBRARY = false;

    public void doSomething() {
        // Are we using the library?
        if(MyClass.USE_LIBRARY) {
            // Do something with the library that we'd define in my build.gradle.
            com.some.gradle.library.MyLibrary.doSomethingWithLibrary();
        }
        else {
            // Do something else.
        }
    }

}

If I remove com.some.gradle.library from my Gradle dependencies, I receive compilation errors indicating that the above code cannot be compiled. As you can see, provided that USE_LIBRARY remains false, we should never need to make any reference MyLibrary; not even upon instantiation, as it makes no reference to the imports; these are only encroached upon at runtime.
I should probably note that in practice, USE_LIBRARY is a programmatically generated constant pertaining to the app's BuildConfig.java.
Surely the compiler can determine that this code can be optimized? Is this some kind of pre-processor check that I can work around?

A:
I'm trying to make a conditional build in Android Studio, where I can reduce the size of the generated APK by removing any superfluous library dependencies if they're not needed for a particular distribution.

Step #1: Define a product flavor for that "particular distribution". For the purposes of this answer, I will call this foo. You will also need other product flavors for other distributions.
Step #2: Change your compile statement that pulls in this JAR to a fooCompile statement, so it will only be used on foo builds.
Step #3: Have one edition of MyClass in each of the product flavors' source sets (e.g., src/foo/java/), where the one in foo references the library, and the others do not.

A: I think you might be confusing the behavior of the Java runtime and compile time processes.
During runtime, your code can be conditionally executed and a library call can be ignored, but during compile time all the code is processed.
By referencing the library at compile time, the dependency is required at compile time.
However, there is a utility called Proguard that is part of the android build system which can remove unused byte code from the apk.  Also, check @CommonsWare answer, if you aren't using the library at all in a different version then build types allow you to create a separate version of the apk without that library

A: Found the solution. The above approach I've taken is possible, provided that you can guarantee that no library code may be interacted with at runtime; this includes making sure that none of your runtime classes extend any parents or implement interfaces that are a part of the library. I was able to verify that the code had been expunged by using ClassyShark.
The "trick" is to declare the library components as provided for the build variant where you want to pretend the libraries are available to you, and as compile for when you wish to export the libraries.
i.e. Use two Build Variants, libraryVariant and emptyVariant, which programmatically switch the value of USE_LIBRARY via buildConfigField 'boolean', 'USE_LIBRARY', 'X'. Then you may define your dependencies as follows:
dependencies {
    // Actually package the library with the compiled APK.
    libraryVariantCompile  "com.some.gradle.library:-1"
    // Ignore the library; just please the linting process.
    emptyVariantProvided   "com.some.gradle.library:-1"
}


text:
Q: 'Outliers' in a data set I have to use R to analyse a large dataset of ratings from 0 to 10, but the data has the number 99 if the answer is "don't know". When I am trying to analyse the central tendency and dispersion, having these 99s is clearly going to mess up my calculation. I am wondering if there is a good way to get rid of these 99s?
Thank you.

A: This is something that is easier to google than to ask stack overflow. But since were are all here...
How about na_if
dplyr::na_if(c(1,2,5,4,99,2,5,4), 99)

https://dplyr.tidyverse.org/reference/na_if.html
If you make the 99 values into NA, then you can compute whatever without it messing up the calculation. You can also simply remove NA values or 99...


text:
Q: Should I use dependency inversion in this case? I have a Document class and a DocumentItem class. A document creates multiple DocumentItems.
As my project has evolved, I realized that DocumentItem needed some "deep" logic to properly display, first checking a database, then the web. My code ended up looking like this:
class DocumentItem
 ...
    function getValue() {
        $du= new DocumentUtils();
        $possibleValue = $du->LookupValueInDatabaseRecursively();
        if (!$possibleValue)
            $possibleValue = $du->LookupValueOnWeb();
        return $possibleValue;
    }

What I don't like about this is that my DocumentItem class has to "know" all about DocumentUtils and the deeper logic associated with getting this value.
Is there a way to isolate DocumentItem from DocumentUtils and it's logic?
Should dependency inversion be used here so we don't have a "tree" of dependencies?
Is there a better design pattern for this?

A: What you're looking for is encapsulation.  Dependency inversion can help you acomplish that but it's only one of many ways.
What strikes me about getValue() is that it doesn't seem to use anything from DocumentItem.  If that's true it's living in the wrong place.  Methods should live close to what they need.  The logic here boils down to using one of two fucntions on DocumentUtils and that decision is based solely on what one of them returns.  Why is DocumentItem even involved here?
class DocumentUtils {
...
    function getValue() {
        $possibleValue = $du->LookupValueInDatabaseRecursively();
        if (!$possibleValue) {
            $possibleValue = $du->LookupValueOnWeb();
        }
        return $possibleValue;
    }
}

class DocumentItem {
    private $du;

    public function __construct($documentUtils) {
        $this->du = $documentUtils;
    }

    function getValue() {
        return $du.getValue();
    }
}

//and here's your dependency injection.
$value = new DocumentItem(new DocumentUtils())).getValue();

Now DocumentItem doesn't have to know how to get this value.  It makes DocumentUtils do it which knows more about what's going on here anyway.
I must say, these names are not optimal.  Document, DocumentItem, DocumentUtil? No wonder you're not sure where to put anything.
If a Document creates multiple DocumentItems maybe it's a DocumentFactory.  Maybe a DocumentItem is really just a Document. Any maybe this thing that is looking up values in the database or the web is your DocumentGateway.
Note: you normally wont want to mix construction and use like I did when I made the dependency injection into a one liner.  The whole point is that now the stuff before and after the dot can be seperated.


text:
Q: tabledata get id value from checkbox I'm trying to display data using Datatable, whenever I try to get the id value from checkbox I get undefined.
Datatable code
   $(function () {
        $('#reviews_data').DataTable({
            processing: true,
            serverSide: true,
            ajax: url,
            columns: [
                {
                    data: 'id', render: function (id) {
                    return '<input type="checkbox" class="icheckbox_minimal" data-id="'+id+'"> ';
                }
                },
                {data: 'status', render: function (status,data,rowData) {
                    return  '
\n' +
                        '<input id="exampleCheckboxSwitch" type="checkbox" data-id="'+rowData.id+'">\n' +
                        '\n' +
                        '
';
                }},
                {
                    data: 'status', render: function (data, data1, row, meta) {
                    return data + '
' + row.created_at;
                }, "bUseRendered": false
                },
                {data: 'created_at', name: 'created_at'},
            ]
        });
    });

this issue with this one
{data: 'status', render: function (status,data,rowData) {
                    return  '
\n' +
                        '<input id="exampleCheckboxSwitch" type="checkbox" data-id="'+rowData.id+'">\n' +
                        '\n' +
                        '
';
                }},

as you see in the code I'm trying to get the id from
data-id="'+rowData.id+'"

using this Jquery code
   $(document).change('.checkbox',function () {
        var id = $(this).data('id');

        console.log(id);

    });

I tried to use value instead of data-id but did work either
how to fix it ?

A: There is a fundamental mistake here. You cannot use an event delegation like this.
$(document).change('.checkbox',function () {
    var id = $(this).data('id');
    console.log(id);
});

Try this way:
$(document).on('change', '.checkbox', function () {
  var id = $(this).data('id');
  console.log(id);
});


text:
Q: Changing Specific URL / Meta Details For Social Media I have a website, which is split up into various sections, and I'm using facebook to share / promote my content.
The problem is that facebook seems to pick up the primary URL and publish that on all posts that I make - Here's an example:

In this example, facebook picks out that it's on the URL Soundcloud.com, but is there a way of actually changin what is displayed here?
As my website is split into sections, with each section being a sub business, I'd like that to display the relevant business name as opposed to the primary URL. Can this be done?
Currently I use <meta name="author" content="My Name"> to display the name displayed to the right of the URL, so I was wondering if these Meta Tags could be used to change what goes where the URL is!

A: Please use <meta property="og:site_name" content="Your Site Name"> to reflect on all pages that you would want with the site name you want.
If you're planning to share a SoundCloud URL, then you cannot do that unfortunately, you can only do that on your own website where you will have access to change such information.


text:
Q: Calling a function from an html element present inside a typescript file (Angular) I am rendering a button based on a certain condition from the backend. The button is rendered from within the ts file
home.component.ts
if(backendLogic is true)
{
const buttonz = '<button onClick="xyz()"> Click me</button>';
return buttonz;
}

xyz()
{
  console.log("haha");
}

Now when click on the button, it gives an error saying UncaughtReference: xyz is not defined.
xyz() is present in the same typescript file.
How do I call this function from within this html element?
I am using Angular.

A: You should use the *ngIf directive:
component.html:
<button *ngIf="backendLogic" onClick="xyz()">Click me</button>

component.ts:
xyz()
{
  console.log("haha");
}

With this method the button only will be rendered in the DOM when backendLogic is true.


text:
Q: PHP left string concatenation operator? This might be a very simple and easy question to answer, perhaps not.
To concatenate a string (by appending/right concat.) in php you use:
$a = "a";

$a .= "b";
//The value will be: "ab"

How do I do this, but the other way around?
Ej.:
$a = "a";

$a ???? "b";
//I NEED the value to be: "ba"

A: Use the standard concatenation operator; no special assignment operator exists.
$a = "b" . $a;

A: $a = "b" . $a
No shorthand for it that I know of.

A: what about $ba = "b$a"; ? It will return ba!
When string are defined between double quotes, variables are parsed as strings automatically. By using single quotes the variable is not parsed instead! ('b$a' returns b$a).
If you the original string contains a special character that interferes with the variable' parsing, then you can enclose it between curly braces:
echo "b_{$a}";  // returns: 'b_a'

// Recap

echo "b$a"; // => 'ba'

echo 'b$a'; // => 'b$a'

Double quotes plus curly braces (when required) are a very handy solution when you need to do many concatenations (e.g. an html tag with it's properties).

A: The closest thing to a built-in function would be using strpad like
$a = str_pad($a, strlen($a)+strlen("b"), "b", STR_PAD_LEFT);

but as others have pointed out its much simpler to just do $a = "b" . $a;


text:
Q: Problems setting a ReactNative state I made an API with some for a "todo" application
But when I take that data from the water the first time I give a console.log () I will have an empty object and only after the data object
When I want to display them, nothing appears, but when I had them without water before, everything was ok
That's how I take the data
const [todos, setTodos] = useState({});

React.useEffect(() => {
  axios.get('http://localhost:8000/app/todo-data/').then((response) => {
    setTodos(JSON.stringify(response.data));
  });
}, []);

My view
return (
  <View style={styles.container}>
    <Header />
    <View style={styles.header}>
      <View style={styles.content}>
        <View style={styles.list}>
          <FlatList
            data={todos}
            renderItem={({ item }) => (
              <TodoItem item={item} pressHandler={pressHandler} />
            )}></FlatList>
        </View>
      </View>
    </View>
  </View>
);

And todo item view
export default function TodoItem({ item, pressHandler }) {
  return (
    <TouchableOpacity
      onPress={() => {
        pressHandler(item.id);
      }}>
      <Text style={styles.item}>{item.item}</Text>
    </TouchableOpacity>
  );
}

Data from API
[
  { id: 1, item: 'dasdasdasdsa', satisfied: false },
  { id: 2, item: 'To make a tea', satisfied: false },
  { id: 3, item: 'To make a sandwich', satisfied: false },
  { id: 4, item: 'To make a cake', satisfied: false },
  { id: 5, item: 'To make a cake', satisfied: false },
  { id: 6, item: 'To make a cake', satisfied: false },
  { id: 7, item: 'To make a cake', satisfied: false },
  { id: 8, item: 'To make a cake', satisfied: false },
];

Todo state without API
/*const [todos, setTodos] = useState([
    { item: 'buy coffee', id: '1'},
    { item: 'buy tea', id: '2'},
    { item: 'buy hamburger', id: '3'},
    { item: 'buy banana', id: '4'},
  ]);*/

When I wasn't using water data, everything was ok ...
Do you know what the main problem is?

A: I guess that your problem appears because of async flow of JavaScript. I mean, you said that when you try to console.log() your object from axios response, at first time you see empty object and later your data appears. Try this solution:
const [todos, setTodos] = useState({});
const getData = async () => {
  const data = await axios
    .get('http://localhost:8000/app/todo-data/')
    .then((response) => JSON.stringify(response.data));
  setTodos(data);
};

React.useEffect(() => {
  getData();
}, []);

You can find more information in this article


text:
Q: Rails 3: Rake task: Accessing model classes in functions called by custom task code I have a rake task which has a rather long definition. I tried to take the rather long set of instructions and separate them into a function as follows:
#lib/tasks/helpme.rake
require 'rake'
require 'rest-client'
require 'warbler'
task :helpme => :environment do
   # some stuff
   some_function("a","b")
end

# (MyCoolModel < ActiveRecord:Base is defined in app/models/my_cool_model.rb)
def some_function (p1,p2)
   m=MyCoolModel.new
   m.p1=p1
   m.p2=p2
   # 20 more lines of very cool code
end

This didn't work when I ran "rake helpme". It complained that MyCoolModel was not accessible.
I then tried the following, knowing how you can do all kinds of weird stuff in Ruby:
#lib/tasks/helpme.rake
require 'rake'
require 'rest-client'
require 'warbler'
task :helpme => :environment do
   # some stuff
   # (MyCoolModel < ActiveRecord:Base is defined in app/models/my_cool_model.rb)
   def some_function (p1,p2)
      m=MyCoolModel.new
      m.p1=p1
      m.p2=p2
      # 20 more lines of very cool code
   end

   some_function("a","b")
end

When I ran "rake helpme", it worked just fine.
My question: How can I get access to the model classes in a function called by a custom rake task without writing the function within the code of the task code?


text:
Q: Android: can't apply onclick listener to button inside custom arrayadapter I'm trying to dynamically add click listeners to a custom array adapter for a list view. The idea is that I have list objects with text on them (eg "Group 1", "Group 2" etc.), and then when I click on the object a drop down appears ("expandable_section") with two buttons on it ("Members" and "Settings"). When I click on the members button I want to be able to access the specific text on the original group object. For example, clicking "Members" under the "Group 1" tab would give me access to the text "Group 1."
Here is my XML layout for the custom adapter object:
   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- The list element for GROUP SETTINGS tab sub-section -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp" >

        <ImageView
            android:id="@+id/activeIcon"
            android:layout_width="34dp"
            android:layout_height="34dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="-7dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical" />

        <ImageView
            android:id="@+id/modeIcon"
            android:layout_width="34dp"
            android:layout_height="34dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical" />

        <TextView
            android:id="@+id/groupName"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_marginBottom="5dp"
            android:layout_marginTop="5dp"
            android:gravity="center_vertical"
            android:textColor="#000000"
            android:textSize="22dp" />
    </LinearLayout>

     <!-- SPECIAL HIDDEN TOOLBAR FOR DEMO LIBRARY LIST MODES TODO: Change to whitelist/blacklist GROUP TAB! -->
    <!-- EXPANDABLEFOR GROUP-SETTINGS FRAGMENT -->

     <LinearLayout
        android:id="@+id/expandableSubsection"
        android:layout_width="fill_parent"
        android:layout_height="90dp"
        android:layout_marginBottom="-100dp"
        android:background="#dddddd"
        android:gravity="center"
        android:visibility="gone" >

        <Button
            android:id="@+id/groupMembersButton"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:layout_marginRight="20dp"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:text="Members" />
        <Button
            android:id="@+id/groupSettingsButton"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:layout_marginRight="20dp"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:text="Settings" />
    </LinearLayout>

</LinearLayout>

Here is the custom adapter code:
package com.sapphire.view;

import java.util.List;

import com.sapphire.model.Mode;
import com.sapphire.view.ModeAdapter.ModeHolder;

import android.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GroupAdapter extends ArrayAdapter<String>{
private Context context;
private int resource;

public GroupAdapter(Context context, int resource, int textViewResourceId,
        List<String> objects) {
    super(context, resource, textViewResourceId, objects);
    this.context = context;
    this.resource = resource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater vi =(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(this.resource, null);
    }

            Button but= (Button) v.findViewById(R.id.button1);

            if( but!=null){
                but.setId(position);
                but.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        System.out.println("customgroup clicked !");
                    }
                  });

            }
    return v;

}
}

and here is where the custom adapter is actually used to display the list of groups:
    public void displayGroupsOptions(){
    final ListView lView = (ListView) thisView.findViewById(R.id.GroupsView);
final ArrayList<String> groupNameList = new ArrayList<String>();
lView.setAdapter(null); //empty the list view
//Get all groups from database table
System.out.println("customgroup about to get all groups from database");
    List<Group> allGroups = db.getAllGroups();
    if(!allGroups.isEmpty()){
        for (Group g: allGroups){
            groupNameList.add(g.getName());
        }
        //Convert group arraylist to group array for use in adapter for list view
        String[] groupNameArray = (String[]) groupNameList.toArray(new String[0]);

        GroupAdapter adapter = new GroupAdapter(getActivity().getApplicationContext(), R.layout.group_list_row, R.id.groupName, groupNameList);
        lView.setAdapter(adapter);
        // Creating an item click listener, to open/close the mode options toolbar for each item
        lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {

                View groupOptions = view.findViewById(R.id.expandableSubsection);
                // Creating the expand animation for the item
                ExpandAnimation ea = new ExpandAnimation(groupOptions, ANIMATION_DELAY);
                // Start the animation on the toolbar
                groupOptions.startAnimation(ea);

            }
        });

    }
  }

Any help would be appreciated! I just can't figure out for the life of me how to get the proper text to show up on the tab (right now it's blank) and how to make the onclick listener actually attach and work. Thanks!

A: You can set tag for your Button in getView method to pass the position argument, and get the tag in th ClickListener.
btn.setTag(position);

@Override
public void onClick(View v) {
    int position = (Integer)v.getTag();
}

Even you can set other view in the same adapter item as a tag and pass it to the listener.

A: use this piece of code where you used getView in adapter class
public class ViewHolder {
    Button b;
    }

and also this
    @Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
    holder = new ViewHolder();

convertView = mInflater.inflate(R.layout.xyz,
                parent, false);

holder.b = (Button) convertView.findViewById(R.id.button1);
        convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
Item it = item.get(position);
holder.b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                    System.out.println("customgroup clicked !");
                }
              });

return convertView;
}


text:
Q: Subquery within Parametized SQL I am using the following code to add some paramitized values to an SQL table.
'--Connect to datasource
Dim SqlconnectionString As String = "server=inlt01\SQLEXPRESS; database=DaisyServices; integrated security=yes"

'--Import selected file to Billing table and Master Services
Dim strSql As String = "INSERT INTO [" + FileNameOnly + "] (Site,CLI,FromDate,ToDate,Quantity,UnitCost,TotalCost,[Description],[User],Department,Filenameonly,billingmonth) VALUES (@Site,@CLI,@FromDate,@ToDate,@Quantity,@UnitCost,@TotalCost,@Description,@User,@Department,@filenameonly,(SELECT  ( CASE SUBSTRING(@filenameonly,1,3)WHEN 'Jan' THEN 1 WHEN 'Feb' THEN 2 WHEN 'Mar' THEN 3 WHEN 'Apr' THEN 4 WHEN 'May' THEN 5 WHEN 'Jun' THEN 6 WHEN 'Jul' THEN 7 WHEN 'Aug' THEN 8 WHEN 'Sep' THEN 9 WHEN 'Oct' THEN 10 WHEN 'Nov' THEN 11 WHEN 'Dec' THEN 12 END ))); INSERT INTO [DaisyServicesMaster] (Site,CLI,FromDate,ToDate,Quantity,UnitCost,TotalCost,[Description],[User],Department,filenameonly,billingmonth) VALUES (@Site,@CLI,@FromDate,@ToDate,@Quantity,@UnitCost,@TotalCost,@Description,@User,@Department,@filenameonly,(SELECT  ( CASE SUBSTRING(@filenameonly,1,3)WHEN 'Jan' THEN 1 WHEN 'Feb' THEN 2 WHEN 'Mar' THEN 3 WHEN 'Apr' THEN 4 WHEN 'May' THEN 5 WHEN 'Jun' THEN 6 WHEN 'Jul' THEN 7 WHEN 'Aug' THEN 8 WHEN 'Sep' THEN 9 WHEN 'Oct' THEN 10 WHEN 'Nov' THEN 11 WHEN 'Dec' THEN 12 END )))"

        Using connection As New SqlClient.SqlConnection(SqlconnectionString)

        Dim cmd As New SqlClient.SqlCommand(strSql, connection) ' create command objects and add parameters
        With cmd.Parameters
                  .Add("@Site", SqlDbType.VarChar, 30, "Site")
                  .Add("@CLI", SqlDbType.VarChar, 30, "CLI")
                  .Add("@FromDate", SqlDbType.Date, 30, "FromDate")
                  .Add("@ToDate", SqlDbType.Date, 30, "ToDate")
                  .Add("@Quantity", SqlDbType.Int, 3, "Quantity")
                  .Add("@UnitCost", SqlDbType.Float, 5, "UnitCost")
                  .Add("@TotalCost", SqlDbType.Float, 5, "TotalCost")
                  .Add("@Description", SqlDbType.VarChar, 100, "Description")
                  .Add("@User", SqlDbType.VarChar, 30, "User")
                  .Add("@Department", SqlDbType.VarChar, 30, "Department")
                  .AddWithValue("@filenameonly", FileNameOnly)

         End With

For the @CLI value I would like to use a sub query to truncate the first character of the string
SELECT RIGHT(CLI, LEN(CLI) - 1)

How to I incorporate a sub query into my Paramitized SQL?
I am relatively new to VB coding so if you could provide some example code that would be much appreciated.

A: It is not possible to pass code as a parameter.  The purpose of parametarized queries is to prevent code being passed via a parameter in order to protect against SQL injection attacks.
There are two ways to achieve your desired outcome:

*

*Truncate the value before passing as a parameter

*Truncate the value after the parameter has been passed.

The latter would mean changing your sql code to the following:
Dim strSql As String = "INSERT INTO [" + FileNameOnly + "] (Site,CLI,FromDate,ToDate,Quantity,UnitCost,TotalCost,[Description],[User],Department,Filenameonly,billingmonth) VALUES (@Site,RIGHT(@CLI, LEN(@CLI) - 1),@FromDate,@ToDate,@Quantity,@UnitCost,@TotalCost,@Description,@User,@Department,@filenameonly,(SELECT  ( CASE SUBSTRING(@filenameonly,1,3)WHEN 'Jan' THEN 1 WHEN 'Feb' THEN 2 WHEN 'Mar' THEN 3 WHEN 'Apr' THEN 4 WHEN 'May' THEN 5 WHEN 'Jun' THEN 6 WHEN 'Jul' THEN 7 WHEN 'Aug' THEN 8 WHEN 'Sep' THEN 9 WHEN 'Oct' THEN 10 WHEN 'Nov' THEN 11 WHEN 'Dec' THEN 12 END ))); INSERT INTO [DaisyServicesMaster] (Site,CLI,FromDate,ToDate,Quantity,UnitCost,TotalCost,[Description],[User],Department,filenameonly,billingmonth) VALUES (@Site,RIGHT(@CLI, LEN(@CLI) - 1),@FromDate,@ToDate,@Quantity,@UnitCost,@TotalCost,@Description,@User,@Department,@filenameonly,(SELECT  ( CASE SUBSTRING(@filenameonly,1,3)WHEN 'Jan' THEN 1 WHEN 'Feb' THEN 2 WHEN 'Mar' THEN 3 WHEN 'Apr' THEN 4 WHEN 'May' THEN 5 WHEN 'Jun' THEN 6 WHEN 'Jul' THEN 7 WHEN 'Aug' THEN 8 WHEN 'Sep' THEN 9 WHEN 'Oct' THEN 10 WHEN 'Nov' THEN 11 WHEN 'Dec' THEN 12 END )))"

One option you might consider is instead of using parameterized queries, to put the code into a stored procedure and invoke this stored procedure with parameters.  It is common practice in a database application to have a set of CRUD stored procedures - Create, Read, Update, Delete.  There are even scripts out there to generate base templates from the structure of your table.  Here is one example:
http://www.sqlbook.com/SQL-Server/Auto-generate-CRUD-Stored-Procedures-40.aspx


text:
Q: Azure Mobile Apps: How to broadcast a cross platform message to Droid + iOS I know how to send targeted messages from the various tutorials with code like that:
// Get the current user SID and create a tag for the current user.
var claimsPrincipal = this.User as ClaimsPrincipal;
string sid = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value;
string userTag = "_UserId:" + sid;

// Build a dictionary for the template with the item message text.
var notification = new Dictionary { { "message", item.Text } };

// Send a template notification to the user ID.
await hub.SendTemplateNotificationAsync(notification, userTag);

But I struggle to figure out how to send to all my registered UserIds.
I hope there is some method like:
// Send a template notification to all UserIds
await hub.SendTemplateNotificationAsync(notification);

A: Yes, there's an overload of SendTemplateNotificationAsync that looks exactly as you described:
public Task<NotificationOutcome> SendTemplateNotificationAsync(
                                       IDictionary<string, string> properties)

Does it not work for you?
An alternative would be to register your users with an additional tag (e.g. "registered user" for all users or "paid user"/"trial user" if you need to slice them somehow) and then use the method you're currently using to send messages, but to this broader tag.


text:
Q: ExtJS: Ext.Window Prototypal inherited objects cannot be destroy [ExtJS 3.4.0]
I have a class with prototypal intheritance to Ext.Window, something like this:
function Cls_MyWindow() {

    .....

    var SaveButton = new Ext.Button({...});
    var CancelButton= new Ext.Button({...});

    .....

    Cls_MyWindow.prototype.width = Ext.getBody().getWidth() - 800;
    Cls_MyWindow.prototype.height = Ext.getBody().getHeight() - 350;
    Cls_MyWindow.prototype.plain = true;
    Cls_MyWindow.prototype.buttons = [SaveButton, CancelButton];

    .....

}

Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

When this window is shown, it can be closed by pressing the CancelButton or the built-in "x" button of Ext.Window.
When I close it with CancelButton, SaveButton and CancelButton get destroyed normally.
But, if is closed by the "x" button, the buttons cannot be destroyed, the loop is taking forever causing my application to crashed.
After some investigation I found, in ext-all-debug.js, this:
Ext.Panel = Ext.extend(Ext.Container, {

    .....

    if(Ext.isArray(this.buttons)){
        while(this.buttons.length) {
            Ext.destroy(this.buttons[0]);
        }
    }

    .....

}

which invoke Ext.destroy, this:
Ext.apply(Ext, function(){

    .....

    destroy : function(){
        Ext.each(arguments, function(arg){
            if(arg){
                if(Ext.isArray(arg)){
                    this.destroy.apply(this, arg);
                }else if(typeof arg.destroy == 'function'){
                    arg.destroy();
                }else if(arg.dom){
                    arg.remove();
                }
            }
        }, this);
    },

    .....

}());

What appears to be is that, this.buttons -from pressing CancelButton- are Ext.Component thus, it get destroyed normally.
While this.buttons -from pressing "x"- are not, which leads to the questions.

*

*Why this.buttons are not the same objects when it is destroy via different way?

*What are the solution/options I have, if I want/need to retain the inheritance?

Shedding me some lights is most appreciated. Thank you in advance.

A: If we stay within Ext 3.4.0 boundaries, not reaching back to the plain javascript then you haven't done inheritance correctly. Inheritance is already implemented in Ext, so you do not need to go down to prototypes, creating constructors as instances of parent classes, and so on.
Let's suppose you want to define MyWindow class inheriting from Ext.Window:
Ext.define('MyWindow',{
    extend:'Ext.Window'
   ,method:function(){/* some stuff */}
   ,closable:false // don't create close box
   ,closeAction:'hide'
   // etc
});

To create an instance:
var win = Ext.create('MyWindow', {
    width:800
   ,height:600
});
win.show();

For more info see Ext.define docs.

A: After days, I've found an answered from Inheritance using prototype / "new".
The code around my first code block at the bottom part is where I got it wrong.
Cls_MyWindow.prototype = new Ext.Window;
Cls_MyWindow.prototype.constructor = Ext.Window;

The "new" at "new Ext.Window" operator there is my mistake.

*

*Why this.buttons are not the same objects when it is destroy via different way?

Answer:
Because of the new operator, when I created a new instance of Cls_MyWindow total of 2 constructors get called: one of the Cls_MyWindow, another of Ext.Window. Which then cause them to have "their own prototype of buttons" where SaveButton and CancelButton available in Cls_MyWindow as Ext.Button objects and in Ext.Window as a plain Object
Closing Cls_MyWindow with CancelButton -> The buttons can be destroyed in Ext.Window.destroy's way. Closing it with "x" -> The buttons cannot be destroyed.
Solution:
I change my code to
//Cls_MyWindow.prototype = new Ext.Window; the old one
Cls_MyWindow.prototype = Ext.Window.prototype;
Cls_MyWindow.prototype.constructor = Ext.Window;

and everything works perfectly


text:
Q: Proof of vector identity I have a problem proofing following vector identity:
$$
\nabla \times (\vec a \times \vec b) = (\vec b \cdot \nabla) \vec a + \vec a (\nabla\cdot\vec b)-(\vec a \cdot \nabla)\vec b-\vec b(\nabla \cdot \vec a)
$$
We are supposed to use the Levi-Civita symbol and the Kronecker-Delta. I think it should be relatively easy if you can use
$$
\vec a \times (\vec b\times\vec c)=\vec b(\vec a\cdot \vec c)-\vec c(\vec a\cdot\vec b)
$$
but I am not sure if you can because of the Nabla.
Thanks in advance for any help!

A: NOTE: You cannot use that second identity because $\nabla$ is an operator, not a vector.  So the two identities are relations about different types of objects.
I'm going to use index notation with the Einstein summation convention.  I'm also using only subscripts instead of superscripts and subscripts, because that's how it's usually taught the first time.  Looking at this, it might be easier starting from the LHS:
$$[\nabla \times (\vec a \times \vec b)]_p = \epsilon_{pqr}\partial_q(\vec a \times \vec b)_r = \epsilon_{pqr}\partial_q\epsilon_{rst}a_sb_t = \epsilon_{pqr}\epsilon_{rst}\partial_qa_sb_t = \epsilon_{rpq}\epsilon_{rst}\partial_qa_sb_t = (\delta_{ps}\delta_{qt} - \delta_{pt}\delta_{sq})\partial_qa_sb_t = \delta_{ps}\delta_{qt}\partial_qa_sb_t - \delta_{pt}\delta_{sq}\partial_qa_sb_t = \partial_qa_pb_q-\partial_qa_qb_p = \dot\partial_q\dot a_pb_q+\dot\partial_qa_p\dot b_q - \dot \partial_q\dot a_qb_p -\dot\partial_qa_q\dot b_p = [(\vec b\cdot \nabla)\vec a + (\nabla \cdot \vec b)\vec a - (\nabla \cdot \vec a)\vec b -(\vec a \cdot \nabla)\vec b]_p$$
And so, because it is true for the $p$th coordinate, it is true for the vectors. $\ \ \square$
BTW, the $\dot \partial_q \dot a_p b_q$ notation means that $b_q$ is held constant in that term.  If you're not used to that notation, you could just use parentheses -- $(\partial_q a_p)b_q$ -- or reorder the factors -- $b_q\partial_q a_p$.  They are all equivalent.
Let me know if you didn't understand one of the steps here.


text:
Q: Entity Framework (4.3) looking for singular name instead of plural (when entity name ends with "s") Here's my situation:
I have been working on an ASP.NET MVC 3 application for a while. It has a database (built out of a db project; I'm going db-first) for which I have an edmx model and then a set of POCOs. My entities have plural names in the database and POCOs have singular names. Everything maps nicely without a problem.
Or used to until I added a new table (called TransactionStatuses). Now all of the old entities still work but the new one does not. When I try to eagerly load it together with a related entity:
var transactions = (from t in db.Transactions.Include(s => s.TransactionStatus) //TransactionStatus - navigation property in Transactions to TransactionStatuses
                    where t.CustomerID == CustomerID
                    select t).ToList();

I get

Invalid object name 'dbo.TransactionStatus'.

I even did a simpler test:
List<TransactionStatus> statuses = db.TransactionStatuses.ToList();

= same result.
I have updated (and even re-created) edmx from the db and have gone through it back and forth trying to figure out what is different about the mapping for dbo.TransactionStatus*es* which trips the whole thing up.
If somebody can point me in the direction of a fix it'd be wonderful.
P.S. Turning off pluralisation is not an option, thanks.
Update: I figured it out - my answer below.

A: Got it!
Horrible, horrible experience...
In short: EF cannot correctly pluralize entity names that end with "s" (e.g. "status", "campus", etc.)
Here's how I got it and proof.

*

*I've created and re-created my original set up several times with the same result.

*I also tried renaming my table to things like TransStatus and the like - no luck.

*While I was researching about this I came across the pluralization article by Scott Hanselman where he added pluralization rules for words like sheep and goose. This got me thinking "what if he problem is in the actual name of the entity?"

*I did some searching about the word status in particular and found this report of the problem on Connect. I rushed to try renaming my entity...

*Renaming TransactionStatuses to TransactionStates (while even keeping the columns as StatusID) fixed the issue! I can now get List<TransactionState> statuses = db.TransactionStates.ToList();

*I thought the problem was with the particular word status in the name... But after vocally complaining about this to a friend I was suggested that maybe the problem is with the word ending with "s"... So I decided to check it out.

*I set up another table called Campuses and matching POCO Campus (and updated the edmx). Did the simple test List<Campus> test = db.Campuses.ToList(); and got the now expected

Invalid object name 'dbo.Campus'.

So there you go, the mighty EF cannot handle pluralization of words ending with "s". Hopefully, the next poor bugger hitting the problem will find this question and save him- or herself 3-4 hours of pain and frustration.

A: This is probably happening because even though the intention was to use the Database First flow, in actual fact the application is using Code First to do the mapping. Let me explain a bit more because this can be confusing. :-)
When using Database First with the EF Designer and the DbContext templates in Visual Studio three very important things happen. First, the new Entity Data Model wizard adds a connection string to your app containing details of the Database First model (i.e. the EDMX) so that when the application is run it can find this model. The connection string will look something like this:
<connectionStrings>
    <add name="MyEntities"
    connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=MyEntities;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
    providerName="System.Data.EntityClient" />
</connectionStrings>

Second, the generated context class makes a call to the base DbContext constructor specifying the name of this connection string:
public MyEntities()
: base("name=MyEntities")
{
}

This tells DbContext to find and use the "MyEntities" connection string in the config. Using "name=" means that DbContext will throw if it doesn't find the connection string--it won't just go ahead and create a connection by convention.
If you want to use Database First, then you must use a connection string like the one that is generated. Specifically, it must contain the model data (the csdl, msl, ssdl from the EDMX) and you must make sure that DbContext finds it. Be very careful when changing the call to the base constructor.
The third thing that happens is that OnModelCreating is overridden in the generated context and made to throw:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

This is done because OnModelCreating is only ever called when using Code First. This is because OnModelCreating is all about creating the model, but when you are using Database First the model already exists--there is nothing to create at runtime. So if OnModelCreating is called then it is probably because you started using Code First without meaning to, usually because of a change to the connection string or the call to the base constructor.
Now, it might be that you want to use Code First to map to an existing database. This is a great pattern and fully supported (see http://blogs.msdn.com/b/adonet/archive/2011/03/07/when-is-code-first-not-code-first.aspx) but you will need to make sure mappings are setup appropriately for this to work. If the mappings are not setup correctly then you will get exceptions like the one in this question.

A: You mention EDMX but I can't tell if you are doing databse first with EDMX or code first and just using EDMX to see what's going on.
If you are using Code First, then you can use a configuration to specify the table name. Data Annotation is [Table("TransactionStatuses")], fluent is modelBuilder.Entity().ToTable("TransactionStatuses").
(I'm typing the annotation and fluent code from memory so double check references. ;) )
If you are using database first, the SSDL should absolutely be aware of the name of the database table, so I'm guessing that you are using code first & the edmx is just for exploration. (???)
hth

A: Sigh.  Same type of an issue with the class and model Photo and Video; it is looking for the table Photoes and Videoes.  I hate to just change the table name, but not much of a choice it looks like.


text:
Q: How do I check if value exists in both arrays in MongoDB? In MongoDB I have the following document:
directConfigs: [
    {
        id: ObjectId('627279d3ba7aef5d6418c867')
        name: "Config A"
    },
    {
        id: ObjectId('628e32777b9e83619746ee3f')
        name: "Config B"
    }
],
indirectConfigs: [
    {
        id: ObjectId('627279d3ba7aef5d6418c867')
        name: "Config A"
    },
    {
        id: ObjectId('628b4d3ff5b1c1736c0b654a')
        name: "Config C"
    }
]

I want to make a project that says if the config exist in both directConfigs and indirectConfigs then add a field to it called type and set the value to "Both", and if it only exists in one of the fields, add a value called direct or indirect depending on what field it exist in. And this should return an array looking like this:
configs: [
    {
        id: ObjectId('627279d3ba7aef5d6418c867')
        name: "Config A"
        type: "Both"
    },
    {
        id: ObjectId('628e32777b9e83619746ee3f')
        name: "Config B"
        type: "direct"
    },
    {
        id: ObjectId('628b4d3ff5b1c1736c0b654a')
        name: "Config C",
        type: "indirect"
    }
]

A: One option is to use $setIntersection and $setDifference:
db.collection.aggregate([
  {$set: {both: {$setIntersection: ["$directConfigs", "$indirectConfigs"]}}},
  {$set: {
      direct: {$setDifference: ["$directConfigs", "$both"]},
      indirect: {$setDifference: ["$indirectConfigs", "$both"]}
  }},
  {$project: {
    configs: {$concatArrays: [
        {$map: {input: "$both", in: {$mergeObjects: ["$$this", {type: "both"}]}}},
        {$map: {input: "$direct", in: {$mergeObjects: ["$$this", {type: "direct"}]}}},
        {$map: {input: "$indirect", in: {$mergeObjects: ["$$this", {type: "indirect"}]}}}
      ]}
  }}
])

See how it works on the playground example


text:
Q: Spring MVC - JS file interns needs to load backgroundImage using CSS I am using Spring-MVC structure for my project.Where in I have set up the static resource handling and I am able to access the css, js & images in my JSP pages very well.
Now, I am adding 1 js file(linked as external to the JSP) which interns setting one background image for the dynamically created items. The problem is - as it's trying to set backgroundImage as below(It is working fine in the local browser), but it's not allowed on the server(being a static resource).
( function( $ ){

$.fn.speedometer = function( options ){

    var $this = $( this );

    if ( $this.length > 1 ) {
        $this.each( function(){
            $( this ).speedometer( options );

        });
        return $this;
    }

    var def = {
        /* If not specified, look in selector's innerHTML before defaulting to zero. */
        percentage : $.trim( $this.html() ) || 0,
        scale: 100,
        limit: true,
        minimum: 0,
        maximum: 100,
        suffix: ' %',
        animate:true,
        thisCss: {
            position: 'relative', /* Very important to align needle with gague. */
            width: '210px',
            height: '180px',
            padding: '0px',
            border: '0px',
            fontFamily: 'Arial',
            fontWeight: '900',
            backgroundImage : "url('./background.jpg')"

    ---------------
    ---------------

So, similar to JSP (using taglib)- I am trying to set backgroundImage as below :
    backgroundImage : "url(<spring:url value='/images/background.jpg'/>)"

That is not working for me. I am stuck here, tried multiple ways but nothing worked for me. 1 of them is : Setting the BackgroundImage using css class. which also I tried by creating a class as:
    .myClass{
     background-image: url(<spring:url value='/images/background.jpg'/>);
     }

But making a function call to apply this is getting a big challange for me. Here is the complete js code :
( function( $ ){

    $.fn.speedometer = function( options ){

        /* A tad bit speedier, plus avoids possible confusion with other $(this) references. */
        var $this = $( this );

        /* handle multiple selectors */
        if ( $this.length > 1 ) {
            $this.each( function(){
                $( this ).speedometer( options );

            });
            return $this;
        }

        var def = {
            /* If not specified, look in selector's innerHTML before defaulting to zero. */
            percentage : $.trim( $this.html() ) || 0,
            scale: 100,
            limit: true,
            minimum: 0,
            maximum: 100,
            suffix: ' %',
            animate:true,
            thisCss: {
                position: 'relative', /* Very important to align needle with gague. */
                width: '210px',
                height: '180px',
                padding: '0px',
                border: '0px',
                fontFamily: 'Arial',
                fontWeight: '900',
                backgroundImage : "url('./background.jpg')"

            },
            digitalCss: {
                backgroundColor:'black',
                borderColor:'#555555 #999999 #999999 #555555',
                borderStyle:'solid',
                borderWidth:'2px',
                color:'white',
                fontSize:'14px',
                height:'20px',
                left:'72px',
                padding:'0px',
                position:'absolute',
                textAlign:'center',
                top:'65px',
                width:'60px',
                zIndex:'10',
                lineHeight:'20px',
                overflow:'hidden'
            }
        }

        $this.html( '' );

        $this.css( def.thisCss );

        $.extend( def, options );

        /* out of range */
        if ( def.limit && ( def.percentage > def.maximum || def.percentage < def.minimum ) ) {
            /* the glass cracks */
            $this.css( 'backgroundImage' , 'url("./background-broken.jpg")' );
        } else {

            /* call modified jqcanvas file to generate needle line */
            $this.jqcanvas ( function ( canvas, width, height ) {

                var ctx = canvas.getContext ( "2d" ),
                lingrad, thisWidth;

                ctx.lineWidth = 2;
                ctx.strokeStyle = "rgb(255,0,0)";

                /* point of origin for drawing AND canvas rotation (lines up with middle of the black circle on the image) */
                ctx.translate( 105,105 );

                ctx.save(); //remember linewidth, strokestyle, and translate

                function animate(){

                    ctx.restore(); //reset ctx.rotate to properly draw clearRect
                    ctx.save(); //remember this default state again

                    ctx.clearRect( -105, -105, 300, 300 ); //erase the canvas

                    /* rotate based on percentage. */
                    ctx.rotate( i * Math.PI / def.scale );

                    /* draw the needle */
                    ctx.beginPath();
                    ctx.moveTo( -80,0 );
                    ctx.lineTo( 10,0 );
                    ctx.stroke();

                    /* internally remember current needle value */
                    $this.data('currentPercentage',i);

                    if ( i != def.percentage ) {

                        //properly handle fractions
                        i += Math.abs( def.percentage - i ) < 1 ? def.percentage - i : def.increment;

                        setTimeout(function(){
                            animate()
                        },20);
                    }
                }

                /* Are we animating or just displaying the percentage? */
                if (def.animate) {
                    var i = parseInt( $this.data('currentPercentage') ) || 0;
                    def.increment = ( i < def.percentage ) ? 1 : -1;
                } else {
                    var i = ( def.percentage );
                }

                animate();

            }, { verifySize: false, customClassName: '' } );

        }

        /* digital percentage displayed in middle of image */

        var digitalGauge = $( '

' );
        $this.append( digitalGauge );
        digitalGauge.css( def.digitalCss );
        digitalGauge.text( def.percentage + def.suffix );

        return $this;

    }

})( jQuery )

Any suggestions for better way of doing it, would be highly appreciated.

A: I got to fix this!
The JS code, which interns setting the background Images was breaking somewhere. So, I have made it loading the Background image using the CSS class.


text:
Q: Deploy Spring MVC application using GPC: Cloud SQL, Kubernetes (Service and Ingress) and HTTP(S) Load Balancer with Google Managed Certificate Let me explain what the deployment consists of. First of all I created a Cloud SQL db by importing some data. To connect the db to the application I used cloud-sql-proxy and so far everything works.
I created a kubernetes cluster in which there is a pod containing the Docker container of the application that I want to depoly and so far everything works ... To reach the application in https then I followed several online guides (https://cloud.google.com/load-balancing/docs/ssl-certificates/google-managed-certs#console , https://cloud.google.com/load-balancing/docs/ssl-certificates/google-managed-certs#console , etc.), all converge on using a service and an ingress kubernetes. The first one maps the 8080 of spring to the 80 while the second one creates a load balacer that exposes a frontend in https. I configured a health-check, I created a certificate (google managed) associated to a domain which maps the static ip assigned to the ingress.
Apparently everything works but as soon as you try to reach from the browser the address https://example.org/ you are correctly redirected to the login page ( http://example.org/login ) but as you can see it switches to the HTTP protocol and obviously a 404 is returned by google since http is disabled. Forcing https on the address to which it redirects you then ( https://example.org/login ) for some absurd reason adds "www" in front of the domain name ( https://www.example.org/login ). If you try not to use the domain by switching to the static IP the www problem disappears... However, every time you make a request in HTTPS it keeps changing to HTTP.
P.S. the general goal would be to have http up to the load balancer (google's internal network) and then have https between the load balancer and the client.
Can anyone help me? If it helps I post the yaml file of the deployment. Thank you very much!
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    run: my-app # Label for the Deployment
  name: my-app # Name of Deployment
spec:
  minReadySeconds: 60 # Number of seconds to wait after a Pod is created and its status is Ready
  selector:
    matchLabels:
      run: my-app
  template: # Pod template
    metadata:
      labels:
        run: my-app # Labels Pods from this Deployment
    spec: # Pod specification; each Pod created by this Deployment has this specification
      containers:
        - image: eu.gcr.io/my-app/my-app-production:latest # Application to run in Deployment's Pods
          name: my-app-production # Container name
          # Note: The following line is necessary only on clusters running GKE v1.11 and lower.
          # For details, see https://cloud.google.com/kubernetes-engine/docs/how-to/container-native-load-balancing#align_rollouts
          ports:
            - containerPort: 8080
              protocol: TCP
        - image: gcr.io/cloudsql-docker/gce-proxy:1.17
          name: cloud-sql-proxy
          command:
            - "/cloud_sql_proxy"
            - "-instances=my-app:europe-west6:my-app-cloud-sql-instance=tcp:3306"
            - "-credential_file=/secrets/service_account.json"
          securityContext:
            runAsNonRoot: true
          volumeMounts:
            - name: my-app-service-account-secret-volume
              mountPath: /secrets/
              readOnly: true
      volumes:
        - name: my-app-service-account-secret-volume
          secret:
            secretName: my-app-service-account-secret
      terminationGracePeriodSeconds: 60 # Number of seconds to wait for connections to terminate before shutting down Pods
---
apiVersion: cloud.google.com/v1
kind: BackendConfig
metadata:
  name: my-app-health-check
spec:
  healthCheck:
    checkIntervalSec: 60
    port: 8080
    type: HTTP
    requestPath: /health/check
---
apiVersion: v1
kind: Service
metadata:
  name: my-app-svc # Name of Service
  annotations:
    cloud.google.com/neg: '{"ingress": true}' # Creates a NEG after an Ingress is created
    cloud.google.com/backend-config: '{"default": "my-app-health-check"}'
spec: # Service's specification
  type: ClusterIP
  selector:
    run: my-app # Selects Pods labelled run: neg-demo-app
  ports:
    - port: 80 # Service's port
      protocol: TCP
      targetPort: 8080
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: my-app-ing
  annotations:
    kubernetes.io/ingress.global-static-ip-name: "my-static-ip"
    ingress.gcp.kubernetes.io/pre-shared-cert: "example-org"
    kubernetes.io/ingress.allow-http: "false"
spec:
  backend:
    serviceName: my-app-svc
    servicePort: 80
  tls:
    - secretName: example-org
      hosts:
        - example.org
---

A: As I mention in the comment section, you can redirect HTTP to HTTPS.
Google Cloud have quite good documentation and you can find there step by step guides, including firewall configurations or tests. You can find this guide here.
I would also suggest you to read also docs like:

*

*Traffic management overview for external HTTP(S) load balancers

*Setting up traffic management for external HTTP(S) load balancers

*Routing and traffic management
As alternative you could check Nginx Ingress with proper annotation (force-ssl-redirect). Some examples can be found here.


text:
Q: Regular expression to parse word structure I'm trying to build my first non-trivial regular expression (for use in Python), but struggling.
Let us assume that a word in language X (NOT English) is a sequence of minimal 'structures'. Each 'structure' could be:
An independent vowel (basically one letter of the alphabet)
A consonant (one letter of the alphabet)
A consonant followed by a right-attaching vowel
A left-attaching vowel followed by a consonant
(Certain left-attaching vowels) followed by a consonant followed by (certain right-attaching vowels)

For example this word of 3 characters:
<a consonant><a left-attaching vowel><an independent vowel>

is not a valid word, and should not match the regex, because there is no consonant to the right of the left-attaching vowel.
I know all the Unicode ranges - the Unicode ranges for consonants, independent vowels, left-attaching vowels and so on.
Here is what I have so far:
WordPattern = (
ur'('
ur'[\u0985-\u0994]|'
ur'[\u0995-\u09B9]|'
ur'[\u0995-\u09B9(\u09BE|[\u09C0-\u09C4])]|'
ur'[(\u09BF|\u09C7|\u09C8)\u0995-\u09B9]|'
ur'[(\u09BF|\u09C7|\u09C8)\u0995-\u09B9(\u09BE|[\u09C0-\u09C4])]'
ur')+'
)

It's not working. Apart from getting it to work, I have three specific problems:

*

*I need to split the regular expression over multiple lines, or else the code is going to look terrible. How do I do this?

*I would like to use string substitution / templates of some sort to 'name' the Unicode ranges, for code readability and to prevent typing Unicode ranges multiple times.

*(This seems very difficult) The list of permissible minimal 'structures' will have to be extended later. Is there any way to set up a sort of 'loop' mechanism within a regex, so that it works for all permissible structures in a list?

Any help would be appreciated. This seems very complex to a beginner!

A: The appropriate tool for morphological analysis of languages with non-trivial morphology is "finite state transducers". There are robust implementations that you can track down and use (one by Xerox Parc). There's one that has python bindings (for using as an external library). Google it.
FSTs are based on finite-state automata, like (pure) regular expressions, but they are by no means a drop-in replacement. It's complex machinery, so if your goals are simple (e.g., syllabification for purposes of hyphenation) you may want to look for something simpler. There are machine-learning algorithms that will "learn" hyphenation, for example. If you are indeed interested in morphological analysis, you have to make the effort to look at FSTs.
Now for your algorithm, in case you really only need a trivial implementation: Since any vowel or consonant could be independent, your rules are ambiguous: They allow "ab" to be parsed as "a-b". Such ambiguities mean that a regexp approach will probably never work, but you may get better results if you put the longer regexps first, so they are used in preference to the short ones when both would apply. But really you need to build a parser (by hand or using a module) and try different things in steps. It's backwards from what you imagined: Set up a loop that uses different regexps, and "consumes" the string in steps.
However, it seems to me that what you are describing is essentially syllabification. And the near-universal rule of syllabification is this: A syllable consists of a core vowel, plus as many preceding ("onset") consonants as the rules of the language allow, plus any following consonants that cannot belong to the next syllable. The rule is called "maximize onset", and it has the consequence that it's easier to parse your syllables backwards (from the end of the word). Try it out.
PS. You probably know this, but if you put the following as the second line in your scripts you can embed Bengali in your regexps:
# -*- coding: utf-8 -*-

A: *

*I need to split the regular expression over multiple lines, or else the code is going to look terrible. How do I do this?

Use the re.VERBOSE flag when compiling the regex.
pattern = re.compile(r"""(
                            [\u0985-\u0994]  # comment to explain what this is
                          | [\u0995-\u09B9]
                          # etc.
                         )
                      """, re.VERBOSE)

*

*I would like to use string substitution / templates of some sort to 'name' the Unicode ranges

You can construct an RE from ordinary Python strings:
>>> subpatterns = {"vowel": "[aeiou]", "consonant": "[^aeiou]"}
>>> "{consonant}{vowel}+{consonant}*".format(**subpatterns)
'[^aeiou][aeiou]+[^aeiou]*'

*

*The list of permissible minimal 'structures' will have to be extended later. Is there any way to set up a sort of 'loop' mechanism within a regex, so that it works for all permissible structures in a list?

I'm not sure if I get what you mean, but... suppose you have a list of (uncompiled) REs, say, patterns, then you can compute their union with
re.compile("(%s)" % "|".join(patterns))

Be careful with special characters when constructing REs this way and use re.escape where necessary.


text:
Q: Create a view based on three different tables I have a table called Ingredients, with the following fields:
Ingredients - IngredientID (PK), ManufacturerID (FK), CategoryID (FK), BarcodeID (FK), SizeID (FK), Quality.
The way this table works is like this: each ingredient is going to be based on EITHER manufacturer, category, or barcode, only one of the three, and one is always required. So if a record has a ManufacturerID, CategoryID and BarcodeID will both be null, and vice-versa.
There are three other tables in my database:
Manufacturers - ManufacturerID (PK), Name
Categories - CategoryID (PK), Name
Barcodes - BarcodeID (PK), Name
I need a view that looks like this:
View - ViewID (PK), IngredientID (FK), Name, SizeID, Quality
Where ViewID will be the PK,
IngredientID will be the FK to the ingredient record,
Name will be the Name field coming from either the Manufacturers, Categories, or Barcodes table based on which of the three fields had a value in the Ingredients table,
and SizeID and Quality will come directly from the Ingredients table.
My knowledge of SQL is very limited and I would appreciate any guidance. Please let me know if my description of the problem lacks any vital information.
Edit: Updated the view to include the FK IngredientID, which could be useful.

A: Something like this should work using a CASE statement:
SELECT I.IngredientID,
   CASE
      WHEN I.ManufacturerID IS NOT NULL THEN M.Name
      WHEN I.CategoryID  IS NOT NULL THEN C.Name
      WHEN I.BarcodeID IS NOT NULL THEN B.Name
   END Name,
   I.SizeID,
   I.Quality
FROM Ingredients I
   LEFT JOIN Manufacturers M ON I.ManufacturerId = M.ManufacturerId
   LEFT JOIN Categories C ON I.CategoryID = C.CategoryID
   LEFT JOIN Barcodes B ON I.BarcodeID = B.BarcodeID

This uses the IngredientId as your Primary Key -- which is what I assumed you wanted.  There is no need for another Primary Key.  If you really just want an incremental Id, then use ROW_NUMBER -- but I don't see why it would be needed:
SELECT ROW_NUMBER() OVER (ORDER BY I.IngredientID), ...

A: select
  i.IngredientID as ViewID,
  isnull(m.Name, isnull(c.Name, isnull(b.Name, ''))) as Name
  i.SizeID,
  i.Quality
from Ingredients i
  left join Manufacturers m on i.ManufacturerID = m.ManufacturerID
  left join Categories c on i.CategoryID = c.CategoryID
  left join Barcodes b on i.BarcodeID = b.BarcodeID


text:
Q: make JSON array from dynamic form data angular i have a dynamic form in angular. and i want to send the response as json. how do i generate JSON from the form?
here's the complete code,I have to get json, and post it to some api.
    <!DOCTYPE html>

<form name="userFormOne" novalidate>

        {{ x.Field }}
        	<input type="text" class="form-control" placeholder="{{x.Comment}}" required>

{{data}}
    </form>

A:
In AngularJs we use ng-model to bind inputs value to our controller, sample:
This full sample to figure out how to create a simple form, from array and how to send it as JSON to your API.
Note: On submit check your console, and see the objects value.

 var app = angular.module("app", []);

        app.controller("ctrl",
            function ($scope) {

                var options = [
                    { name: "a" },
                    { name: "b" },
                    { name: "c" }
                ];

                $scope.names = [
                    { id: 1, field: "insert name", name: "name", placeholder: "your name is", value:null, type:"text" },
                    { id: 2, field: "insert phone", name: "phone", placeholder: "your phone is", value: null, type: "tel" },
                    { id: 3, field: "insert age", name: "age", placeholder: "your age is", value: null, type: "number", min: 0, max: 20 },
                    { id: 4, field: "select country", name: "country", placeholder: "your country is", value: null, type: "select", options: options }
                ];

                $scope.sendMe = function() {
                    console.log($scope.names);
                }
            });
<!DOCTYPE html>

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

    <form name="userFormOne" novalidate>

                    {{ x.field }}

                    <input type="{{x.type}}" min="{{x.min}}" max="{{x.max}}" ng-model="x.value" name="{{x.name}}" placeholder="{{x.placeholder}}" ng-required="true">
                    {{x.value}}

                    <select  ng-model="x.value" name="{{x.name}}" ng-options="item as item.name for item in x.options">
                    </select>
                    {{x.value}}

        <button ng-disabled="userFormOne.$invalid" ng-click="sendMe()">sendMe</button>
    </form>


text:
Q: Disable ohead on a single page i try to disable the ohead on the first page of a section (and only the first page). I tried a lot of things(e.g. \thispagestyle) but nothing really works.
\documentclass[paper=a4,fontsize=12pt,parskip=half,bibliography=totoc,listof=totoc,headings=normal]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}

\usepackage[headsepline,plainheadsepline,footsepline,plainfootsepline]{scrlayer-scrpage}
\pagestyle{scrheadings}
\automark{section}
\clearscrheadfoot
\ihead{Mr. XY}
\ohead{\headmark}
\ofoot[\pagemark]{\pagemark}

\begin{document}

\section{first}
%here comes a lot of text...
%ein I don't want to have "first" in the header
\section{second}
%here comes a lot of text again...

\end{document}

Hope that someone can give me a solution for that problem. Thanks.

A: The following example uses page style plain.scrheadings, which can be defined using the optional arguments of \ihead and \ohead.
Then, it patches \section to append \thispagestyle{plain.scrheadings} to remove the \headmark in the header from pages with section starts.
\documentclass[
  paper=a4,
  fontsize=12pt,
  parskip=half,
  bibliography=totoc,
  listof=totoc,
  headings=normal
]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{lipsum}

\usepackage[
  headsepline, plainheadsepline,
  footsepline, plainfootsepline
]{scrlayer-scrpage}
\pagestyle{scrheadings}
\automark{section}
\clearscrheadfoot
\ihead[Mr. XY]{Mr. XY}
\ohead[]{\headmark}
\ofoot[\pagemark]{\pagemark}

\let\orgsection\section
\def\section#1#{%
  \auxsection{#1}%
}
\def\auxsection#1#2{%
  \orgsection#1{#2}%
  \thispagestyle{plain.scrheadings}%
}

\begin{document}

\section{first}
\lipsum[2-12]
\section{second}
\lipsum

\end{document}


text:
Q: Increase number of shown related products in the administration (Magento 2) When you edit a product in the magento administration the number of items listed in the related products, up-sells and cross-sells list is limited to 20. Also there is no possibility to change this like in felt every other grid.
I tried to fix this programmatically by creating an observer which sets the default limit to 50. The observer is called correctly (when adminhtml_block_html_before is fired) but nothing changes.
Any thoughts on this?

A: Ok, I could fix this.
If you're interested:
create a new file

app/code/$yourModule/Catalog/etc/adminhtml/di.xml

with the following content
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\HandlerInterface" type="Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Handler\Composite" />
<preference for="Magento\Catalog\Model\Locator\LocatorInterface" type="Magento\Catalog\Model\Locator\RegistryLocator"/>
<virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool" type="Magento\Ui\DataProvider\Modifier\Pool">
    <arguments>
        <argument name="modifiers" xsi:type="array">
            <item name="related" xsi:type="array">
                <item name="class" xsi:type="string">$yourModule\Catalog\Ui\DataProvider\Product\Form\Modifier\Related</item>
                <item name="sortOrder" xsi:type="number">110</item>
            </item>
        </argument>
    </arguments>
</virtualType>

and copy from vendor the Related.php to

/app/code/$yourModule/Catalog/Ui/DataProvider/Product/Form/Modifier/Related.php

and add the pageSize to the config Array in the method getGrid.


text:
Q: Converting an entire column of numbers in pandas to word equivalent I am currently working with a dataset that has a column with the following set up:
'age'
 20
 25
 30
 35
 etc.

I am trying to convert to a column to the following:
'age'
'twenty'
'twenty-five'
 etc.

I tried to accomplish this using num2words imported library and doing a map:
df['age'] = df['age'].map(lambda x: num2words(x))

But I get an attribute error. The data originally in age is stored as an int32 dtype, so I am not to sure what else would cause it. Any help is appreciated!

A: df = pd.DataFrame({"k":[1,2,3,4,5,6]})
df.k.map(lambda x: num2words(x))

0      one
1      two
2    three
3     four
4     five
5      six
Name: k, dtype: object

df = pd.DataFrame({"k":["125","2","3","4",5.0,6.0]})
df.k.map(lambda x: num2words(x))

0    one hundred and twenty-five
1                            two
2                          three
3                           four
4                           five
5                            six
Name: k, dtype: object


text:
Q: Idiomatic in Clojure: (drop 1 str) or (rest str)? Simple question here for Clojure.  Which is more idiomatic when dealing with strings?  Which is more idiomatic when dealing with other data types?  Which is more efficient?
(drop 1 str)

or
(rest str)

A: Whatever you're dealing with, rest will be more efficient, but the difference will be so trivial as to be uninteresting.
Make sure you know whether you want rest or next, because in some cases it matters. rest is lazier, and is probably right more often, but if you use rest when you need next the results can be hard to track down.
For strings...neither! Use subs, the built-in substring operator:
user> (subs "hears" 1)
"ears"

rest is fine, but it would yield a seq of characters instead of a string; usually you'll find a string easier to deal with, and it's simple enough to turn it back into a seq of characters sometime later.


text:
Q: cout permutation of three or more string suppose I have been given strings "abc", "def" and "ghi", I want to generate all the possible combination of word generated by picking from these strings. for eg
for "abc", "def" and "ghi"
we should get
"adg","adh","adi","aeg","aeh","aei","afg","afh","afi",
"bdg","bdh","bdi","beg","beh","bei","bfg","bfh","bfi",
"cdg","cdh","cdi","ceg","ceh","cei","cfg","cfh","cfi"
How to Do it.
my attampt...
        vector<string> wordset;

        for(int i = 0; i < digits.size(); i++ )
        {
            wordset.push_back( latters[digits[i] - '0'] );
        }

        for(int i = 0; i < wordset.size()-2; i++ )
        {
            string word = wordset[i];
            for(int j = 0; j < word.size(); j++ )
            {
                string combn = "";
                combn += word[j];

                for(int k = 0; k < wordset[i+1].size(); k++ )
                {
                    combn += wordset[i+1][k];

                    for(int l = 0; l < wordset[i+2].size(); l++ )
                    {
                        combn += wordset[i+2][l];

                        ans.push_back(combn);
                        combn = "";
                        combn += word[j];
                        combn += wordset[i+1][k];

                    }

                }
            }
        }

A: This is one example where recursion allows simpler code: you just have to combine all characters from the first word with the permutations of the other ones.
In C++ it could be:
#include <vector>
#include <string>

using std::vector;
using std::string;

// using an array will allow to simply process the end of the array
vector<string> permuts(const string* arr, size_t sz) {
    vector<string> ret;
    switch (sz) {
    case 1:   // one single word: return its individual chars as strings
        for (char c : arr[0]) {
            string str(1, c);
            ret.push_back(str);
        }
    case 0:   // empty array gives an empty vector
        return ret;
    default:
        ;
    }
    // combine chars from first word with permuts of others
    vector<string> tmp = permuts(arr + 1, sz - 1);
    for (char c : arr[0]) {
        for (const string& str : tmp) {
            string str2 = string(1, c) + str;
            ret.push_back(str2);
        }
    }
    return ret;
}

// the version using a vector just delegates to the one using an array
vector<string> permuts(const vector<string>& wordset) {
    return permuts(wordset.data(), wordset.size());
}