text:
Q: i don't know why happens this: AttributeError: 'NoneType' object has no attribute 'append' my code in python have this error, i'm listen python and don't know why happens, in the console the python interpreter print this:
Introdusca el titulo del libro> crisal
introdusca el autor del libro> roijari
introdusca la editorial del libro> tor
introdusca el precio del libro> 456
Traceback (most recent call last):
 File "/home/crisal/programas-en-python/tadcomp_clase3.py", line 32, in <module>
   cargar_en_libreria(lr,l)
 File "/home/crisal/programas-en-python/tad_comp_libre.py", line 10, in cargar_en_libreria
   libreria.append(libro)
AttributeError: 'NoneType' object has no attribute 'append'

the problem happens when import the funtion that load the data in abstact data type(ADT) in the list that is allocated in the ADT with the name  'tad_comp_libre' and the code in python is this(main):

## EJERCICIO PRACTICO ##

#cargar cuatro libros

#imprimir los datos de todo los libros

#eliminar el 2º libro

#imprimir libros restantes

# estructura intrer de los libros
## nombre
## editorial
## autor
## precio
from tad_libro import*
from tad_comp_libre import*

#creo un for carador de los libro
l=crear_libro() #crea los libros
lr=crear_libreria() #crea la libreria

#introdusco los datos que van a tener los libros y los pone en la libreria
for i in range(0,3):
    nom=input("Introdusca el titulo del libro> ")
    aut=input("introdusca el autor del libro> ")
    edi=input("introdusca la editorial del libro> ")
    prec=float(input("introdusca el precio del libro> "))

    cargar_libro(l,nom,aut,edi,prec)
    cargar_en_libreria(lr,l)

#imprime los datos de los libros
for i in range(0,tamanio(lr)):
    b_l=buscar_libro(lr,i)
    print("--------------------------\n")
    print("titulo: ",Vernombre(l))
    print("autor: ",Verautor(l))
    print("Ediorial: ",Vereditorial(l))
    print("Precio: ",Verprecio(l))
    print("--------------------------\n")

opc=1
##elimino el segundo libro:
opc=int(input("desea eliminar un libro?: Si(1)/No(0)>>"))
while opc==1:
    nom=input("elija el libro que desea eliminar(nombre)")

    b_l=buscar_libro2(lr,nom)

    borrar_libro(lr,b_l)

    opc=int(input("desea eliminar otro libro?: Si(1)/No(0)>>"))
else:
    print("se a terminado el proceso de eliinacion de libros")

#imprime de nuevo la lista
for i in lr:
    print("--------------------------\n")
    print("titulo: ",Vernombre(i))
    print("autor: ",Verautor(i))
    print("Ediorial: ",Vereditoria(i))
    print("Precio: ",Verprecio(i))
    print("--------------------------\n")

(tad_libro)

def crear_libro():
    libro=["","","",0]
    return libro

def cargar_libro(libro,n,a,e,p):

    libro[0]=n
    libro[1]=a
    libro[2]=e
    libro[3]=p

def Vernombre(libro):
    return libro[0]

def Verautor(libro):
    return libro[1]

def Vereditorial(libro):
    return libro[2]

def Verprecio(libro):
    return libro[3]

def modifNom(libro,nom1):
    libro[0]=nom1

def modifaut(libro,aut1):
    libro[1]=aut1

def modifpre(libro,pre1):
    libro[2]=pre1

(tad_comp_libre)
in this ADT happens the problem when load the data
from tad_libro import*

#crea el tipo de dato libreria
def crear_libreria():
    libreria=[]

#carga los datos de los libros en la libreia
def cargar_en_libreria(libreria,libro):
    libreria.append(libro)

#libro elimina un libro puntual de la libreria
def borrar_libro(libreria,l):
    libreria.remove(l)

#devuelve el tamanio de la libreria
def tamanio(libreria):
    return len(libreria)

#busca un libro dentro de la libreria
def buscar_libro(libreria,i):
    return libreria[i]

def bucar_libro2(libreria,nombre):
    for i in libreia:# el parametro libreria transforma el indice de tipo tad_libro porque es el tipo de dato que hay alojado en libreria
        if Vernombre(i)==nombre:
            return i

if you can help my, i'm will really thanks they, sorry for the code in spanish

A: crear_libreria needs to return its result.  Right now, it stored in a variable that is immediately destroyed.  As a result, the lr global is set to None.
Do this:
#crea el tipo de dato libreria
def crear_libreria():
    return []


text:
Q: Why ML involves trial and error and no overarching rules? I am a beginner to ML and working on some traditional classification problems as of now.
I see that some of the results/decisions made by ML are a result of trial and error by the data scientists. Meaning, there is no proper logic or theory/guideline to the way how an ML works. So, the behavior of model (if not most) at least sometimes it is purely driven trial and error approach. So, we don't know why it does what it does. we keep tweaking until we get a result that works well for our data.
For example, from this post here, we can see that there is no proper guideline/theory as to which is the right approach to do feature selection.
Similarly, in this post here, we can see that some LIME explanations are random (and doesn't make sense). Again, it could be drawback of the LIME approach. But each approach has its pros and cons. Even if I choose another explainable AI appraoch like Shap etc, it will also have some issues and may not be consistent for all rows. I also understand some issues could be due to data (but for the sake of this discussion let's restrict only to the behavior of ML models)
Is it because ML tries to find an estimate/approaximation of real behavior, we have to settle with things (that cannot always be drilled down to specific reason but rather accept it because thats what the model outputs)? How do we convince business users in that case?
My question is mainly on why ML behavior is random (that its working/results/decisions etc cannot always 100% proven by evidence/theory etc).
Is there any simple example that you can give to explain this?
Hope my question is clear. I sincerely hope you get the idea of my question. Sorry, for my poor language if unable to communicate clearly

A: If I understand correctly, I think you are noticing a general tendency in machine learning - that everything is guided by "trial and error", by "experimentation" rather than some overarching rules.
In many cases, when asked "Why did you do X or Y", you might not be able to give an answer any better than "well, that just works best on the data".
If I understand your question correctly, I think it's super interesting, philosophical and probably doesn't have a single, straightforward reason. I will give my thoughts on the subject, though.
I think there are a huge number of possible perspectives, but here is one. Our world is an insanely complex interaction of an innumerable quantity of various physical laws. The results of these interactions often have noticeable distributions, correlations etc.
Machine learning is not specific to any field - it is simply a "universal"/general set of methods which attempt to extract patterns from data (of any kind). Machine learning isn't built to incorporate laws of physics, or to take into account the physical/chemical/psychological/geological reason for observations. It is simply built for "put in distributions of data" and get predictions/structure as an output.
There are any number of possible variable interactions, correlations and otherwise "informational structure" in the world, and so machine learning attempts to capture this structure - but it is blind to the "reason" behind it. The job of RandomForest isn't to discover why people are clicking on Facebook ads. It's just to optimize a function which represents the predictive accuracy of this algorithm on whether a person will click or not, for example.
As a result, it is (in many ways) an "art" - because as long as you're not violating a very small number of core assumptions (data leakage etc.), it simply doesn't matter what you do with the data as long as it delivers a good result. Want to do feature selection first, then hyperparam tuning? Try it. Want to do it the other way around? Try it! There are no laws to break here - there is only good and bad predictive results. You get bad results when the process doesn't allow the ML algorithm to capture useful patterns in the data (if there are any). Good results happen when (for any number of reasons), the algorithm was given information in a way that allowed it to capture enduring patterns/dependencies.
"Why is the algorithm doing this?" . On a most base level, the answer will always just be "because of how the algorithm is designed to work + the data it was given". Any interpretation beyond that will involve subject matter expertise and careful and deep dives into the data. The algorithm doesn't care about that interpretation - it's just optimizing a function for the data that you give it. Any interpretation on top of that is your attempt at understanding the process that generated the data, and how that could have led to the algorithm noticing X or Y.
I know this was a big vague and hand-wavy, but I hope it gives some space to think about ML broadly and why it is so experimentally focused.
At the moment, a huge amount of ML is focused on prediction - so as long as the model gives good predictions, anything else is irrelevant, in a way. You just know "The particular way that I'm digesting the data and feeding it to the algorithm results in real world information being combined in such a way that there are noticeable informational/mathematical dependencies that are being captured by this sequence of optimization steps I call 'my ML model' ".
Important Addition: I think feature engineering (for predictive purposes) is a great illustration of the point. When engineering features, you don't necessarily need to be guided by any principles. Take the log() of the feature, normalize it, take a moving average, take a Z score. You can do all these things, and when you do (and if it works) you are left asking the same question - but why did taking a Z score help? You might find an interpretable answer. But part of the answer will always be something like "Because for whatever reason, because of whatever physical laws are governing this complex interaction you're observing, digesting the information in that particular way makes the pattern in the data more clear and so your model can pick it up easier". I think that kind of thinking can be applied generally to this whole question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery onclick not firing on dynamically inserted HTML elements? My onclick event works.
However, when that onclick event is on dynamic HTML, it no longer works. As in: nothing happens.
$(document).ready(function () {
    $("#guestlist .viewguestdetails").click(function () {
        $(".guestdetails[data-id='18']").toggle();
    });
});

I'm then dynamically adding this HTML to a page:

    (add your data)

            some data

However, when I then click on "(add your data)" nothing happens. When I have the HTML staticly in my page, this toggling of the 'guestdetails' div does work.
It seems that there is no event attached to dynamically inserted HTML?
UPDATE:
The new dynamic HTML I'm inserting i a row in an existing table. The other rows already have events attached to the onclick events, like:
$("span.guestattendance").click(function () {
    if ($(this).hasClass('checkbox-on')) {
        $(this).removeClass('checkbox-on').addClass('checkbox-off');
        $("#guestday").removeClass('checkbox-on').addClass('checkbox-off');
    }
    else {
        $(this).removeClass('checkbox-off').addClass('checkbox-on');
        if ($("#guestceremony").hasClass('checkbox-on') && $("#guestreception").hasClass('checkbox-on') &&
        $("#guestdiner").hasClass('checkbox-on') && $("#guestparty").hasClass('checkbox-on')) {
            $("#guestday").removeClass('checkbox-off').addClass('checkbox-on');
        }
    }
});

Since a user can insert more than 1 row, I didn't use the id, but rather added a wrapper around the  element I'm inserting:
and then in ready() function:
$('.newrow_wrapper').on('click', 'span', function () {
    $(".guestdetails[data-id='" + $(this).attr('data-id') + "']").toggle();
});

The first problem however, is that apparently when I wrap a div around a tr tag, all tr and td tags are removed from the inserted HTML!
Also when I click the span to view guestdetails nothing happens.

A: jQuery.on() is used to  bind any event on dynamically inserted HTML elements. Use it like this :
$(document).ready(function () {
    $(document).on('click',"#guestlist .viewguestdetails",function () {
        $(".guestdetails[data-id='18']").toggle();
    });
});

A: Do this:
 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.

A: Use .on() to attach event handlers which dynamically binds the html elements.Here is the link for documentation http://api.jquery.com/on/
write something like this
      $( '#someid' ).on( 'click', function () { ... });

or something like this.
          $(document).on( 'click', 'tag_name', function () { ... });


text:
Q: Simplifying the if-else condition using Java Functional Style Programming Any suggestion to simplify the following code block using Java 8 features?
int[] ans = new int[2];
list.forEach(i -> {
    if (i > 0) {
        ans[0] += 1;
    } else if (i < 0) {
        ans[1] += 1;
    }
});

P.S. Not sure if I should post this here

A: If you don't want to count zeros, you code is as simple as it can get. If you wanted to count zeros as positive, however then you could shorten it to this.
int[] ans = new int[2];
for (int i : list) ans[i < 0 ? 1 : 0] += 1;

A:  ans[0] = (int)list.stream().filter(x -> x < 0).count();
 ans[1] = (int)list.stream().filter(x -> x > 0).count();

but I hardly think this is a simplification as such, your solution is already as simple as it can get.
In case you do want to count zeros, this could be simplified to:
 list.forEach(x -> ++ans[x >>> 31])

A: I'd suggest
int[] ans = new int[2];
list.forEach(i -> ans[i >>> 31] += i==0 ? 0 : 1);

where i >>> 31 discards all but the sign bit (i.e., is the same as i<0 ? 1 : 0) and the second conditional handles zero.
I don't claim, it's really better than the original.

A: To distinguish two cases like i > 0 and i < 0  we can use Stream.partition:
Map<Boolean, List<Integer>> partitioned = list.stream()
  .filter(i -> i != 0)
  .collect(Collectors.partitioningBy(i -> i > 0));
ans[0] = partitioned.get(true).size();
ans[1] = partitioned.get(false).size();

Is it simplified? At least it's still readable and easy to understand.
EDIT
Or as @saka1029 suggests:
Map<Boolean, Long> partitioned = list.stream()
  .filter(i -> i != 0)
  .collect(Collectors.partitioningBy(i -> i > 0, Collectors.counting()));
ans[0] = partitioned.get(true);
ans[1] = partitioned.get(false);

EDIT
And a further Stream solution which returns the desired array. But I would argue it's not simpler. So it's about to compare.
int[] ans = list.stream().filter(i -> i != 0).collect(
  () -> new int[2],
  (arr, i) -> arr[i > 0 ? 0 : 1]++,
  (l, r) -> {  l[0] += r[0]; l[1] += r[1]; });

A: Here's a way that counts zeroes as well:
int[] ans = new int[3];
list.forEach(i -> ans[Integer.signum(i) + 1] += 1);

The ans array now holds 3 values: index 0 for negative count, index 1 for zero count and index 2 for positive count.
i.e. for the following input: [1, 2, 3, 0, -4, -5], the output would be: [2, 1, 3].

A more functional way, excluding zeroes:
Map<Integer, Long> bySignum = list.stream()
    .filter(i -> i != 0)
    .collect(Collectors.groupingBy(Integer::signum, Collectors.counting()));

Which produces this output: {-1=2, 1=3}.


text:
Q: selecting row in a dataframe according to defined values I have an annual record of temperature. I need to select special row (days) with five rows before them (to take the mean of five days) and then take the mean of the selected groups. here is my data frame and the following code that i applied but didn't work.
Day  T.m
1      22
2      21
3      34
4      28
5      14
6      7
7      12
8      22
9      11
10     12
11     14
12     3
13     4
14     11
15     16

a <- c(8, 12,14)

apply(DF [c((a-5):a),2], 1, mean)

A: We can use mapply
mapply(function(x, y) mean(DF[[2]][x:y]), a-5, a)
#[1] 19.500000 12.333333  9.166667

Or a vectorized approach would be
tapply(DF[[2]][rep(a-5 , each = 6) + 0:5], rep(1:3, each = 6), FUN = mean)
#        1         2         3
#19.500000 12.333333  9.166667


text:
Q: Продукт не сохраняется в БД Django Всем привет. Есть код в models.py, по которому часть номера продукта попадает в checker, и checker возвращает информацию по этому продукту. Эта информация попадает в ту же таблицу в БД, что и номер продукта.
class Product(models.Model):
    name = models.CharField(max_length=255)
    state = models.CharField(max_length=255)
    b_info = models.CharField(max_length=255)

    def save(self, *arg, **kwarg):
        r = requests.get(f'https://system-one.uno/api/cli/bln_check/?card={self.name[:6]}')
        if r.status_code == 200:
            _r = r.json()
            self.b_info = _r.get('reason')

При добавлении продукта, через админ панель, продукт не сохраняется в БД. Почему?

A: Вы переопределили метод save,но забыли "включить" в него функционал этого же метода наследуемого класса. Добавьте в конец метода save : return super().save(*args,**kwargs)


text:
Q: Type erasure of command object using generics in Spring MVC In a Spring 3.1 MVC app with Hibernate 4.1, the scenario is:

*

*a webpage displays a list of records where the user is able to select records with a checkbox

*on POST, the selected records will be deleted

Since this functionality also appears in other places, i would like to use generics in order to avoid replicating the similar code.
The logic is:

*

*on GET, i populate a list using generics which holds the hibernate object and a boolean and i am adding that list to the model

*on POST, i obtain that list from the model and i am passing it to a service in order to delete the selected records

The code is:
/* list item */
public class SelectionListItem<T> {

    /* holds the hibernate object */
    private T item;
    /* whether the record is selected */
    private boolean selected;

    public SelectionListItem() {

    }

    public SelectionListItem(T item, boolean selected) {
        this.item = item;
        this.selected = selected;
    }

    public T getItem() {
        return item;
    }

    public void setItem(T item) {
        this.item = item;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}

/* list that holds the records */
public class SelectionList<T> {

    private List<SelectionListItem<T>> list = new ArrayList<SelectionListItem<T>>();

    public SelectionList() {

    }

    public List<SelectionListItem<T>> getList() {
        return list;
    }

    public void setList(List<SelectionListItem<T>> list) {
        this.list = list;
    }
}

/* Controller for GET */
@RequestMapping(value = "/xxx", method = RequestMethod.GET)
public String functionGET(Model model) {
    // Retrieve data from database and prepare the list
    SelectionList<MyDomainObject> selectionList = someService.getRecordsAndPrepareList();

    // Add command object to model
    model.addAttribute("selectionListCommand", selectionList);

    return "xxx";
}

/* Service that retrieves the records and prepares the list */
public SelectionList<MyDomainObject> getRecordsAndPrepareList() {
    List<MyDomainObject> result = sessionFactory.getCurrentSession().createCriteria(MyDomainObject.class).list();

    SelectionList<MyDomainObject> selectionList = new SelectionList<MyDomainObject>();
    for (MyDomainObject item : result) {
        SelectionListItem<MyDomainObject> e = new SelectionListItem<MyDomainObject>(item, false);
        selectionList.getList().add(e);
    }

    return selectionList;
}

/* Controller for POST */
@RequestMapping(value = "/xxx", method = RequestMethod.POST)
public String functionPOST(
    @ModelAttribute("selectionListCommand") SelectionList<MyDomainObject> selectionListCommand,
    BindingResult result, Model model) {

    // Delete record
    someService.deleteSelectedRecords(selectionListCommand);

    return "xxx;
}

/* Service that deletes the selected records*/
public void deleteSelectedRecords(SelectionList<MyDomainObject> selectionList) {
    for (SelectionListItem<MyDomainObject> item : selectionList.getList()) {
        if (item.isSelected()) {
            sessionFactory.getCurrentSession().delete(item.getItem());
        }
    }
}

At GET request, the SelectionList is populated correctly and the "T item" is of type "MyDomainObject".
At POST, the "T item" is of type "java.lang.Object" and when the "sessionFactory.getCurrentSession().delete(item.getItem())" is executed i am getting "org.hibernate.MappingException: Unknown entity: java.lang.Object"
Can someone please explain what is causing it and how it can be solved?
Thank you in advance.

A: Hibernate does "some magic things" and often uses reflections to get access to variables and determine the types. The types are important for Hibernate to decide which mapping to use.
In the get request you provide with MyDomainObject.class the correct class. This seems to be sufficient for Hibernate to find the mapping.
This is not the case for the post request. There Hibernate in the statement delete(item.getItem()) only gets the information getItem() returns an object (the type T is removed due to the type erasure and not available for Hibernate). The information 'object' does not allow Hibernate to find the mapping for item.
You can try to cast the item like delete((MyDomainObject)item.getItem()) or to put it in a well typed variable first
   MyDomainObject mdoItem = item.getItem();
   sessionFactory.getCurrentSession().delete(mdoItem);

(I'm not sure which of the two possibilities will work.)

A: As i mentioned, the problem was when the @ModelAttribute("selectionListCommand") was returned at POST.
Solution is:

*

*Add to the controller -> @SessionAttributes("selectionListCommand")

*Modify class SelectionList to -> public class SelectionList implements java.io.Serializable
I hope that will save someone's else time in the future.


text:
Q: How to check if elements in an array are sorted according to number of occurences? I want to check if the elements in an array are sorted according to the number of their occurrences in. This is assuming they are already grouped if elements are the same.
int [] y = {7, 7, 7, 8, 8, 5, 5, 5, 5} should return false while int [] y = {5, 5, 5, 5, 7, 7, 7, 8, 8} should return true. There are four 5s, three 7s and two 8s, so it should be arranged that way.
This is what I have so far:
import java.io.*;
import java.util.*;

public class testing2 {

  public static void main(String[] args){
    int [] y = {7, 7, 7, 8, 8, 5, 5, 5, 5};
    System.out.println(isSorted(y));  // should return false

  }

  public static boolean isSorted(int[] y){

    HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();

    for(int i=0; i<y.length; i++){
      if(hash.containsKey(y[i])){
        hash.put(y[i], hash.get(y[i]) + 1);
      } else {
        hash.put(y[i], 1);
      }
    }
    System.out.println(hash);
    return true;  // code is not complete yet
  }
}

It would print:
{5=4, 7=3, 8=2}
true

So now I have the number of occurrences for each element. What do I do next?

A: You can solve this in a single pass of the array; here are some hints:
While you are iterating through the array, keep track of the current number (e.g. 5, 7 or 8) and the quantity. When you finish the next group of numbers, compare it the previous number/quantity. Then, return true or false appropriately.

A: If you prefer keeping your direction of using HashMap, there is one way to continue:

*

*Use LinkedHashMap instead, so when you iterate thru the map, you are iterating in the order you put that in the map

*Iterate thru the map, and see if each entry is having count < prev entry. Pseudo  Code:
int prevCount = MAX_INT;
for (entry : map) {
    currentCount = entry.getValue()
    if (currentCount > prevCount) {
        return false
    }
    prevCount = currentCount
}
return true;

Or, you can have one single-pass on the array (pseudo-code):
 prevCount = MAX_INT
 currentCount = 0;
 for (i = 0...array.length) {
     increment currentCount

     // if i points to last number in group
     if (i is the last element of array, OR
             next element is not equals to current element) {
         if currentCount > prevCount {
             return false;
         }
         prevCount = currentCount;
         currentCount = 0;
     }
}


text:
Q: Creating a dropdown menu which opens upwards I am trying to create a dropdown menu which opens upwards like bottom to top. So, far this is what I have created and I am encountering the following issues.
1) I want the Dropdown to be of the same width as the button on which we are hovering.
2) The whole are of the first element which is a link in the dropdown is not taking to the desired mailTo link.
Here is the Fiddle: https://jsfiddle.net/s4tr2/gcoh62o6/
    <!DOCTYPE html>

            <title>Up Dropdown</title>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Report Issues

Feedback

mailTo

A: Two things. You are setting the width of the submenu manually. You don't have to. Your second error was because of a typo, you wrote targer instead of target.

.menu {
    display: block;
    position: absolute;
    bottom: 0;
    right: 220px;
    padding: 0px;
    margin: 0px;
    text-align: center;
}
.menu ul{
    list-style-type: none;
    margin: 0px;
    padding: 0px;
}
.menu li {
  display: inline-block;
  position: relative;
  cursor: pointer;
  background-color: #BDC3C7;
/*  margin-right: -4px;*/
    width: 155px;
    height: 40px;
    line-height: 40px;
    text-align: center;
}
.menu .sub-menu li a{
    display: block;
    text-decoration: none;
    color: #000;
}

.menu li:hover {
  background-color: #ABB7B7;
}
.menu li:hover .sub-menu {
  max-height: 300px;
  visibility: visible;
  bottom: 100%;
  transition: all 0.4s linear;
    color: #000;
}
.menu .sub-menu {
  display: block;
  visibility: hidden;
  position: absolute;
  left: 0;
  box-shadow: none;
  max-height: 0;
  overflow: hidden;
}
.menu .sub-menu li {
  display: block;
}
        #mainBtn{
            background-color: #0000FF;
            color: #fff;
        }
<!DOCTYPE html>

        <title>Up Dropdown</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Report Issues

Feedback

mailTo


text:
Q: how does one describe/impolements contraints and tables relations in Zend_DB 2.0 (zf2 beta5) mappers classes In zend_db 1.x we used reference_map to implements constaints and relations in the data mapper classes. In zend_db 2.0 where should the reference map go?

A: There is no referencing possible in ZF 2.0
You can see from my previous question that in ZF 2 you'll be either using a full blown ORM like Doctrine 2 or Propel for these kind of purposes or to write your own SQL Queries. The Zend DB Component is seen as a lightweight abstraction to handle simple task related stuff.


text:
Q: Renamed project failing I have taken a copy of an existing project (Door), with the expectation of using some of the core features for a supervisor application (Mgmt).
I have renamed the project from Door to Mgmt.
I have visited every visible file and changed references to the old application name.
I have done a global search and replace for the old app name.
I have also opened project.pbxproj and found over 10 references to the old project name and changed them. I have also edited xcschemes .xcscheme file name and the cxschememanagement.plist file. As I wish to use push, I have a new certificate for the new app
Everything appears fine, however.......
When I run the application it fails because it cannot find the view controller under the old applications name. (DoorViewController). For the life of me, I cannot see where this is referenced from. the error message is shown below....
[Switching to process 7171 thread 0x1c03]
Re-enabling shared library breakpoint 1
2011-11-30 12:18:17.128 mgmt[9706:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </var/mobile/Applications/EE73FFD1-5392-41F6-A8CB-706D042EF134/mgmt.app> (loaded)' with name 'DoorViewController''

Obviously there is one more thing missing, however it is not something I can see. Any suggestions?

A: I wonder if you tried this:
Open MainWindow.xib
On left column, under objects:
Do you see "Door View Controller"?
What is its class as per the identity inspector? (alt command 3)
If it's still DoorViewController, change it to the new one.
If this doesn't work, delete "Door View Controller", drag & drop a new one from the library and then change its identity.

A: ./mgmt.xcodeproj/project.xcworkspace/xcuserdata/user.xcuserdatad/UserInterfaceState.xcuserstate and buried in the mainwindow.xib
        <object class="IBUIViewController" id="578626022">
            <string key="IBUINibName">DoorViewController</string>

Manually edited the xib file using a text editor and deleted the xcuserstate file got the app started. I am surprised that the IBUIViewController setting was not visible with a global search, nor within IB, however.......
Thanks sanjay.


text:
Q: Add / Remove from XMLList while in a loop I am trying to parse some XML i have retrieved via e4x in an HTTPService. The loop works and for each episode in the list it goes through the loop. However i get the following error when it is trying to append to an XMLList.
TypeError: Error #1009: Cannot access a property or method of a null object reference.

I am trying to query the local SQLite database and see if the episode exists (working) and if it does append to one xmllist and if not then append to the other xmllist.
public static function seasonFavHandler(evt:ResultEvent):void {
    Application.application.ManagePage.selectedShow =
        Application.application.ManagePage.gridFavourites.selectedItem as XML;
    episodeNumber = XML(evt.result).descendants("episode");
    var episode:Object = episodeNumber;
    for each(episode in episodeNumber) {
        currentEpisode = episode as XML;
        achkStatement = new SQLStatement();
        achkStatement.sqlConnection = dbconnection;
        achkStatement.text = "select :episodename from episodes where episodename = :episodename";
        achkStatement.parameters[":episodename"] = episode.title;
        achkStatement.addEventListener(SQLEvent.RESULT, episodeHandler);
        achkStatement.execute();
        trace(episode.title);
    }
   //Application.application.ManagePage.episodeList = episodeNumber;
   seasonHttpService.removeEventListener(ResultEvent.RESULT, seasonFavHandler);
   CursorManager.removeBusyCursor();
}

private static function episodeHandler(event:SQLEvent):void {
    var result:SQLResult = achkStatement.getResult();
    var episodeNewT:XMLList;
    var episodeWatchedT:XMLList;
    if (!result.data) {
        episodeNewT.appendChild(currentEpisode);
        //Application.application.ManagePage.gridUnwatched.addChild(currentEpisode);
    } else {
        episodeWatchedT.appendChild(currentEpisode);
        //Application.application.ManagePage.gridWatched.addChild(currentEpisode);
    }
    Application.application.ManagePage.episodeNew = episodeNewT;
    Application.application.ManagePage.episodeWatched = episodeWatchedT;
    achkStatement.removeEventListener(SQLEvent.RESULT, episodeHandler);
}

A: You have declared episodeNewT and episodeWatchedT, but you haven't instantiated them yet.  I would also suggest you use XMLListCollection instead of XMLList, since it's easier to modify at runtime.
Try this:
var episodeNewT:XMLListCollection = new XMLListCollection();
var episodeWatchedT:XMLListCollection = new XMLListCollection();

if (!result.data) {
    episodeNewT.addItem(currentEpisode);
} else {
    episodeWatchedT.addItem(currentEpisode);
}

Application.application.ManagePage.episodeNew = episodeNewT.copy();
Application.application.ManagePage.episodeWatched = episodeWatchedT.copy();

Now your variables won't be null, and you can append to them.  Note that you'll be converting the XMLListCollection back to an XMLList at the end of it all by using copy().

A: this is my solution to add xml nodes to xmllist dynamically.
private function addXmlChild(xmlList:XMLList, xmlNode:XML):void
{
    try
    {
        if(xmlList.children().length() != 0)
        {
            xmlList[xmlList.length() + 1] = xmlNode;
        }
        else
            xmlList[0] = xmlNode;
        }
        catch(error:Error)
        {
            LogWriter.ErrorLog("addXmlChild, " + error.message);
        }
}

A: But if you want work with XMLList, you can try the next:
var episodeNewT:XMLList;
var episodeWatchedT:XMLList;
if (!result.data) {
    episodeNewT= XMLList(currentEpisode);
    //Application.application.ManagePage.gridUnwatched.addChild(currentEpisode);
} else {
    episodeWatchedT = XMLList(currentEpisode);
    //Application.application.ManagePage.gridWatched.addChild(currentEpisode);
}


text:
Q: How to find coordinates of opposite vertices in a boundingbox I have two sets of coordinates (in WGS84) which describes a rectangle
ontop a map (openstreetmap). The coordinates in this box are the bottom-left vertice and the top-right vertice.
Coordinates:
                LATITUDE    LONGITUDE
bottom-left:    53.869605   9.3191648
top-right:      69.4197068  29.7990631

However I need to find out the correct coordinates on the opposite
vertices, top-left and bottom-right.
The naive approach I took initially (knowing nothing about this) was
to simply swap the lat,lon coordinates as one might do in a regular 2d plane.
To get this:
                LATITUDE    LONGITUDE
top-left:       69.4197068  9.3191648
bottom-right:   53.869605   29.7990631

This does not seem to work though, because the new box becomes a bit squashed compared to the original box, which I figured ought to be due to the curvature of the earth.
So how could I find out these two opposite vertices (top-left, bottom-right)? preferrably in python.
As per comment below here are the images showing whats going on:
If one looks closely you can see that the radar spheres are distorted.
top-left, bottom-right

bottom-left, top-right


text:
Q: Why doesn't it add a new TableHeaderCell? So I would like to add an a new TableHeaderCell. Because I don't have the time to learn vb, I only used a converter, so I don't know if the fault happened there. This is my code so far. It does execute this section but it won't add the header to the ASP.NET GridView. I'm using asp:BoundField.
if (grdvProductChurn != null)
{
    GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
    TableCell left = new TableHeaderCell();
    left.ColumnSpan = 2;
    row.Cells.Add(left);

    TableCell totals = new TableHeaderCell();
    totals.ColumnSpan = grdvProductChurn.Columns.Count - 2;
    totals.Text = "Anzahl";
    row.Cells.Add(totals);
}


text:
Q: Laravel 4 getting information from database for drop-down form I am trying to make a simple authentication application and I have the login/signup form in place and it is working correctly. However, I am having issues with populating the drop-down field for a zip-code from another table. I am not really sure how i should approach this. Most of the time i would just use straight mysql query but I am assuming there is an easier way.
Controller: (would love for the zip_code table to go here.)
        public function getSignUp() {
            $userdata = array(
            'email' => Input::get('email'),
            'password' => Hash::make(Input::get('password'))
            );
            $user = new User($userdata);
            $user->save();

            return Redirect::to('dashboard');
    }

Route
Route::post('signup', 'LoginController@getSignUp');

signup.blade.php
            {{ Form::label('email', 'Email:') }}

        {{ Form::text('email') }}

        {{ Form::label('password', 'Password:') }}

        {{ Form::password('password') }}

        {{ Form::label('zip_code', 'Zip Code:') }}

        {{ Form::select('zip_code', array('zip_code' => '', 'city' => '')); }}

        {{ Form::submit() }}

{{ Form::close() }}

This is how I would normally call database information before this
        public function showHome()
{
            $testimonials = DB::select('SELECT * FROM `testimonials` WHERE `id`=' . mt_rand(1, 2));
            return View::make('home.index', array('pageTitle' => 'Home'))->with('testimonials', $testimonials);
}

but with me not returning a view and therefor no variables are going to be passed I am not sure how to achieve this
Any advice would be highly appreciated!

A: You can easily list out data from an Eloquent model for a select field using the lists() function.
Testimonial::lists('content', 'id');


text:
Q: Working with parameters in SSRS 2008 I have an (either or) situation in regards to parameters in SSRS 2008. I currently have my report working with a date range but I've been asked to add a drop down for the user to select the weekending date. I've got that drop down working but how can I switch between parameters (Date Range and the use of the Weekending Date drop down) for sending parameters to my report?

A: The way I allways fix this is by setting the parameters as nullable.
Then in my sql script I select all dates on the weekending date or between the daterange:
So whatever the user specifies, your sql script is filtered based on their parameters.
select *
from [table] t
   where t.[date] = @WeekendingDate
      or t.[date] is between @DateRangeFrom and @DateRangeTo

A: I usually handle this situation by creating an Internal Parameter(s) to sit between the UI and the query or stored procedure. The Internal Parameters are driven by expression depending on the user selection.
so lets say you want the user to either select a  begin and end date range(Begin: 2012-01-01 End: 2012-01-31), or a month (Jan 2012).
If they select a value for Month. I convert that to an equivalent date range in the internal parameter expression. If they enter a date range I just pass through the begin and end values to the internal parameters.
Hopefully this makes sense. with a little work and imagination I think the approach can handle most scenarios.

A: One possibility would be to use the version control system of your choice to make another branch for the second report, change that one to use Week Ending, and then just make sure you merge changes every time you make a change to the main report.
I'm sure someone will come up with a cleaner way to handle it, though...


text:
Q: How do I get the variables in a column from java and sql? So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example:
Names
Test
Test1
Test3
River
World
Etc

I want to get all of that into an array list. Thanks for the help!

A: You're not giving much information in your question (e.g. what is the table you'd like to query), so here's a somewhat generic solution:
 public List<String> retrieveAllColumnValues(Connection connection) throws SQLException {

    String query = "SELECT Names FROM MyTable";
    List<String> values = new ArrayList<>();

    try (Statement stmt = connection.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            values.add(rs.getString("Names"));
        }
        rs.close();
    }
    return values;
}

Getting data from the database through JDBC roughly consist of the following parts:

*

*You have a Connection which you use for creating SQL Statements

*When you execute the Statement, you get a ResultSet, which contains the values returned by your query

*You iterate through the ResultSet and do what you need to with the values


text:
Q: Couchbase Lite Java: Creating View & Query with Exact Keys I am trying to query base on my own custom view, but it did not turn out what I expected.
I would like to query with keys example like ["2017", "5", "26"], endDateTime is the column in my Json Data which storing millisecond.
I have emitted with List to store date.
When I ran my query by today date (database do have data for the date that I am searching), I have debugged with breakpoint to check the List that stored the date in view and query both is identical.
I can't find the reason why queryEnumerator return no row.
Please help my issue, I have been tried many ways but still no luck.
Appreciate for the help.
public View getViewTransactionByEndDate() {
    View view = this.getDatabase().getView("Transaction");

    if (view.getMap() == null) {
        view.setMap(new Mapper() {
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                if (document.get("type") != null) {
                    if (document.get("type").equals("Transaction")) {
                        Calendar dataCalendar = Calendar.getInstance();

                        /* due to too long the code, */
                        /* I have break it to 2 lines */
                        Long endDateTime =
                        Long.parseLong(document.get("endDatetime"));

                        dataCalendar.setTimeInMillis(endDateTime);

                        List<Object> key = new ArrayList<>();
                        key.add(dataCalendar.get(Calendar.YEAR));
                        key.add(dataCalendar.get(Calendar.MONTH) + 1);
                        key.add(dataCalendar.get(Calendar.DAY_OF_MONTH));

                        HashMap<String, Object> value = new HashMap<>();
                        value.put("_id", document.get("_id"));

                        emitter.emit(key, value);
                    }
                }
            }
       }, "1");
    }

    return view;
}

/* The query part */
Query query = getViewTransactionByEndDate().createQuery();

Calendar todayCalendar = Calendar.getInstance();
todayCalendar.setTime(new Date());

List<Object> key = new ArrayList<>();
key.add(todayCalendar.get(Calendar.YEAR));
key.add(todayCalendar.get(Calendar.MONTH) + 1);
key.add(todayCalendar.get(Calendar.DAY_OF_MONTH));

query.setKeys(key);

QueryEnumerator queryEnumerator = query.run();

A: I managed to find the answer myself:
For those who looking the solution for the similar question, please refer below:
Query multiple keys in couchbase lite view


text:
Q: How to do a subtraction in a stored procedure in SQL Server 2008 R2 I am a beginner when it comes to stored procedures, the database of my job is SQL Server 2008 R2 and I don't know how to do a simple subtraction of two values.
For example:
Excel table:

In this table, the third column is equal to the subtraction of the first column and the second column
On the column of a table of my database, the first and the second columns are in one column:
Table:

So, the third column should be the difference between the first and the second column, but I need to calculate the subtraction of the two values, I can bind the values with the article, that have the same number.
How can I do this in a stored procedure? I don't know how to do that, doing a While, declaring variables, all of that.
Any help will be really grateful, Thanks.

A: Select Articulo
      ,Col1     = sum(case when Cantidad>0 then Cantidad else 0 end)
      ,Col2     = sum(case when Cantidad<0 then Cantidad else 0 end)*-1
      ,Col3     = sum(Cantidad)*-1
 From  YourTable
 Group By Articulo

Returns
Articulo    Col1    Col2    Col3
1003        64000   338464  274464
1004        43200   271921  228721
3002        8411    11082   2671
3007        57600   57238   -362

A: You need to use a full self join
 Select p.canditad Positive, -n.canditad Negative,
    p.canditad+n.canditad Difference
 From table p          -- <-- p for positive values
    full join table n  -- <-- n for negative values
       on n.articulo = p.articulo
          and p.canditad > 0
          and n.canditad < 0


text:
Q: Spring Security login Twitter return 403 Forbidden I have a trouble with Logging in Spring Security by Twitter. My project have run OK for 2 years, but we have just gotten this issue for a few days without change any code line. I have no idea what cause is and how to resolve yet. Please give me a recommendation. Thank you very much
Below lines are exception's stacktrace.
21-Jun-2018 11:08:52.661 SEVERE [http-nio-8080-exec-10] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [bookstore-dispatcher] in context with path [] threw exception
 org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.social.support.LoggingErrorHandler.handleError(LoggingErrorHandler.java:49)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:572)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:493)
    at org.springframework.social.oauth1.OAuth1Template.exchangeForToken(OAuth1Template.java:192)
    at org.springframework.social.oauth1.OAuth1Template.fetchRequestToken(OAuth1Template.java:117)
    at org.springframework.social.security.provider.OAuth1AuthenticationService.getAuthToken(OAuth1AuthenticationService.java:91)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthService(SocialAuthenticationFilter.java:266)
    at org.springframework.social.security.SocialAuthenticationFilter.attemptAuthentication(SocialAuthenticationFilter.java:173)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:133)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1533)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

A: I resolved it. Thank @john so much.

*

*Go to apps.twitter.com and select your app

*"Settings" > Callback URLs

*Add a callback urk that looks like https://your-domain/auth/twitter

*Click "Add a Callback URL

*Click Update Settings


text:
Q: Cisco ASA Command length Whenever I write some command in ASA , it hides the full command and show the bit of command . What is the way to increase the length of Commands I write in ASA, so it doesn't hide the command written on the Terminal Session? I tried to google it but not able to find the solution
(ASA)#sho run object-group id $

A: You'd need to modify the terminal width parameter on the ASA to a value greater than the default of 80 columns.

A: make sure you are in config mode
(config)# terminal ?

configure mode commands/options:
  width  Set terminal width, default is 80 columns

exec mode commands/options:
  monitor  Syslog monitor
  no       Turn off syslogging to this terminal
  pager    Control page length for pagination. The page length set here is not saved to configuration.


text:
Q: Ubuntu 16.10 bar objects not opening Since upgrading there is an annoying behaviour which sometimes happens and sometimes doesn't. On the top of the screen there are icons for skype, language choice etc. I am used to that when I bring the cursor over one of these, down comes a menu and I can choose what to do.
With 16.10 it happens (and is currently happening) that the cursor just sits on the icon and nothing happens. I am not aware of what causes this. Usually I can reboot to fix the problem, until it happens again.
Just now I upgraded Virutalbox running Windows, and I see on the view menu of virtualbox that I can do nothing, where I can normally use full screen for example. So the problem shows up in virtualbox as well.
I'm sorry that I can't put my finger on what causes the problem. Has anyone else seen such a thing and are there any suggestions on what can be done to fix it?
Thanks,
Ilan
P.S. I noticed that one of my cores was at 100% approximately 80% of the time. I looked at the processes and the unity-panel-service was taking the most CPU time.
This starts to make sense. Something is causing the unity-panel-service to go into saturation, so that it has no time to respond to my requests. The question is if I can figure out which program is demanding all the time from the unity-panel-service. It sounds like a bug in that some program is able to make excessive demands and that unity allows the program to get away with it.
Perhaps there is a log file somewhere which will give a hint as to what is going on?

A: When the problem occurred I turned off one service after another.
Finally I turned off owncloud and unity-panel-service came back to life.
Apparently this is a know issue:
https://github.com/owncloud/client/issues/4985


text:
Q: Parentheses size on mathpazo I noticed that using the font mathpazo the parentheses done with \big(,\big) or with \left( and \right) on a mid sized expression are larger than necessary and definitely larger than the corresponding ones with the default math font.

Similarly, other delimiters are too large as well. For example, the f(x)\big|_{x\to 0} gives a nice looking expression with the default font, whereas it has a vertical bar too big in mathpazo. There's no in between: by removing \big the bar is of normal size and thus too small.

Is there any way to manually choose the size of the delimiters? Or, alternatively, do you know a font that looks similar to mathpazo but doesn't have this issue?

A: You could use newpxmath and mathalpha with option bb=pazo.
\documentclass{article}
\usepackage{amsmath}
\usepackage{newpxtext}
\usepackage{newpxmath}
\usepackage[bb=pazo]{mathalpha}
\begin{document}
\[
\mathbb{T}_1 = 8 \bigl( \mathbb{T}_1^0 + \mathbb{T}_{16}^0 \bigr),
\qquad
f(x) \bigr\rvert_{x\to 0}
\]
\end{document}

To compare the size of delimiters, where's the output of the same document, but without newpxtext, newpxmath and mathalpha, and with amssymb for the blackboard bold alphabet.

Note also that you should not use \big, but instead you should use \bigl and \bigr for left and right delimiters respectively.

A: I'll add an alternative way for whomever will come across the same problem and want to stick with the mathpazo font.
The problem is that mathpazo does not have the characters for the sizes that I want, but it suffices to apply a rescaling by hand. This, by the way, only solves the issue for \big, \bigl etc. and not for \left/\right.
I took this code from Stefan Kottwitz's answer on this forum.. Basically one can define a new parenthesis size as follows
\newcommand*{\bigs}[1]{\scalebox{1.1}{\ensuremath#1}} %1.1 is the scale factor


text:
Q: twitter regex breaking, thinking syntax issue My syntax for regex is breaking the  links somehow around the "rel=" lines.
Here it is:
<?php
function parseTweet($text) {
   $pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';
    '@([A-Za-z0-9_]+)';

   $tweet = preg_replace('/(^|\s)#(\w+)/', '\1#\2', $text);
   $tweet = preg_replace('/(^|\s)@(\w+)/', '\1@\2', $tweet);
   $tweet = preg_replace('#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is', '\\1
                      [link]', $tweet);
   return $tweet;
}

$username='stephenfry'; // set user name
$format='json'; // set format
$tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}")); // get tweets and decode them into a variable

$theTweet = parseTweet($tweet[0]->text);

echo $theTweet;
?>

Link parsed HTML:
Great deal: Jot by Adonit, a precise capacitive touch stylus, today 15% off with coupon code: 'Jot' -
[link]

Hash tag parsed HTML:
I'm so sorry - that last #
GameOfShadowsUK
tweet should hav 3been sent at 2:21 - my f****d up arsing w**k-mess of a life disallowed it :-(

Binned the dodgy code and went with a better method. See Answer.

A:             <?php

            function getLastXTwitterStatus($userid,$x){
            $url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$x";

            $xml = simplexml_load_file($url) or die('could not connect');
                echo '
';
                   foreach($xml->status as $status){
                   $text = twitterify( $status->text );
                   echo '
'.utf8_decode($text).'
';
                   }
                echo '
';
             }

             function twitterify($ret) {
              $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1\\2", $ret);
              $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1\\2", $ret);
              $ret = preg_replace("/@(\w+)/", "@\\1", $ret);
              $ret = preg_replace("/#(\w+)/", "#\\1", $ret);
            return $ret;
            }

            //my user id kenrick1991
            getLastXTwitterStatus('simonpegg',1);

            ?>


text:
Q: Detect if user is logged in This is some coding in my nav bar. I am trying to detect whether there is a user logged in or not. What's supposed to happen is when there is a user logged in then it shows a little dropdown menu with options for the user to edit their account or logout, but it's not working.
            <?php
            function loggedIn(){
            $_SESSION['loggedin'] = true;
            $_SESSION['username'] = $username;
            if(isset($_SESSION['username'])!="")
            { echo '

                    '. $_SESSION['username'] .'

Action

Another action

Something else here

Separated link

One more separated link

';
            }else{
                echo '
 Login
';
                }
            }
            loggedIn();
            ?>

A: The minute you set the $_SESSION['username'] variable, your test at if(isset($_SESSION['username'])!="") will always execute because the variable is set.
For my login process, I usually have a doLogin.php script that authenticates the user against the database and if the authentication passes, it sets the necessary $_SESSION variables. If it fails, its sets a $_SESSION['loginAttemptCount'] variable, and unsets the $_SESSION['username'] and associated variables.
This way, each PHP page simply executes the if(isset($_SESSION['username'])) test and configures itself accordingly.
Hope that helps.

A: The normal process is :

*

*Login script creates something in the session

*Scripts that want to know if a user has logged in, check for that value in the session.
login.php
<?php
session_start();
// do all your login checks for userid / password

$_SESSION['username'] = $username;

. . . .

any_other.php
<?php
    session_start();

    function AddForLoggedInUsers(){

        if( !empty($_SESSION['username']) ) {
           $htm = '

                '. $_SESSION['username'] .'

Action

Another action

Something else here

Separated link

One more separated link

';
        }else{
            $htm = '
 Login
';
        }

        return $htm;
    }

    // other code

    echo AddForLoggedInUsers();

Its also a better idea to place the html you generate in a function into a variable then when you call the function you have the option of adding to the functions result or just echoing it straight out, or possibly even modifying it.


text:
Q: What are some architectural issues you have faced in cloud-focused designs? When you decided to deploy a cloud setup what are the architectural/implementation issues you have faced and how did you resolve them?
Some examples include:

*

*(architectural) design patterns when you plan to move your existing application in to cloud

*what non-functional requirements should be give priority?

*how do you overcome the cloud overhead ?  (because of virtualization - like resource metering, etc)

A: The biggest issue I faced, were local fallbacks. In a typical cloud scenario you are moving your resources that once lived in a traditional data storage (database, filesystem, etc) to something behind an API, that you can't easily replicate locally. For our application we moved a few typical queues from MySQL to Amazon's SQS. Problems:

*

*Currently Amazon charges $0.01 per 10,000 SQS request, a cost that might seem extremely small, but there's absolutely no reason to pay when developing locally (or for your test server, assuming you have a  separate one).

*If you don't have a local queue fallback, you need a separate queue per development / testing environment. You really don't want messages from different queues getting mixed up.

*There isn't a simple way to emulate SQS locally for our environment (that I know of).
Architecturally, I dealt with the transition to SQS with simple adapters:

*

*An abstract adapter that did most of the work, with abstract functions for the storage specific stuff,

*A SQS adapter that inherited the abstract adapter, and utilized the SQS SDK,

*A MySQL adapter that was more or less exactly what we had before,

*A factory method that created Queue models, decided what adapter to use, fed it to the models.

The same architecture (more or less) worked pretty nicely when we moved our images to S3, with a filesystem local fallback. Simple, small and easy enough to explain, and, more importantly, it works. If you are migrating an application to the cloud, chances are you'll be writing quite a few adapters for your back end services, other than having a simple fallback mechanism, you don't want to be vendor locked to a specific service.
Obviously if you are building an application with the cloud in mind, you may not necessarily need local fallbacks, especially if your platform has an easy way of emulating the cloud environment. Something like Stratosphere, if you are developing on .Net / Mono or if you are targeting Amazon's services. But if you have a mature application, you already have an infrastructure set up locally, keep using it makes a bit more sense.
The cloud "overhead" is not really something you need to worry about if you are using the cloud as a fancy data store. But if you are looking for cloud computing, then there's no answer, it always depends on what you are doing exactly.
A few relevant questions:

*

*What should I do to scale out an high-traffic website?

*What are common pitfalls of Cloud Development that you have run into?

*Are there any examples of implementing and effectively responding to a "Chaos Monkey"?


text:
Q: Luis python SDK Utterance addition we are trying to create a Chatbot using Luis framework and Python SDK using the Azure documentation as a reference. We have been able to add Intent, entity and pre-built entities using the same. These changes show up on the portal verifying the addition.
But the code for Utterance addition is not showing on the portal or being listed on the terminal.
def create_utterance(intent, utterance, *labels):
    """
    Add an example LUIS utterance from utterance text and a list of
    labels.  Each label is a 2-tuple containing a label name and the
    text within the utterance that represents that label.
    Utterances apply to a specific intent, which must be specified.
    """
    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value), role=None)

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                               ("Flight", "economy to Madrid"),
                               ("Location", "Madrid"),
                               ("Class", "economy")),
              create_utterance("FindFlights", "find flights to London in first class",
                               ("Flight", "London in first class"),
                               ("Location", "London"),
                               ("Class", "first")),
              create_utterance("FindFlights", "find flights from seattle to London in first class",
                               ("Flight", "flights from seattle to London in first class"),
                               ("Location", "London"),
                               ("Location", "Seattle"),
                               ("Class", "first"))]

client.examples.batch(appId, appVersion, utterances, raw=True)
client.examples.list(appId, appVersion)

This code does not return any error but does not list the Utterances either.


text:
Q: Retrieve cached jquery elements I am caching jquery elements like this
var $stepList = $('#stepList > li');
var $tableRowList = $('.tablesorter-js tbody > tr');

//and use them in the function
pages = {
    buildDetail: function ($stepList, $tableRowList) {
          console.log($stepList, $tableRowList)
    });
}
// this function is invoked many times
pages.buildDetail($stepList, $tableRowList);

Is there a more efficient way to cache and retrieve elements, since I will have many more cached elements in buildDetail() ?


text:
Q: Unallocated space cannot be used for other partitions Some weeks ago I installed the latest Ubuntu OS version on my PC. I gave it 12GB of space and then 4GB for the hibernation temp storage. Yesterday I realized that I wasn't going to use it any more so I went to "Disk Management" in Windows 7 and deleted both partitions. When I restarted I got a boot error that I fixed using a command in my Windows Repair Disk. So since I had free space I want it to extend that space to my storage partition that I created by shrinking C, however it doesn't let me extend. I also deleted my Storage partition to see if both unallocated space united but nothing.
What can I do to make use of this free space?


text:
Q: Overriding only some virtual funtion of base class with the same name I have a base class with a virtual fonction foo(int i) and foo() (same name, not same arguments).
The derived class override only foo().
Now the derived class doesn't knows foo(int i) anymore.
class Base
{
public:
  virtual void foo(int i) {
    std::cout << "Base::foo(int i)" << std::endl;
  }
  virtual void foo() {
    std::cout << "Base::foo()" << std::endl;
  };
};

class Derived : public Base
{
public:
  void foo() override {
    std::cout << "Derived::foo()" << std::endl;
  }
};

int main(const int ac, const char* const av[])
{
  Base base;
  base.foo();
  base.foo(42);

  Derived derived;
  derived.foo();
  derived.foo(42);//ERROR : Function unknown
}

Should output :
Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)

Where does the problem come from and what would be the solutions?
The derived class will sometimes override foo(), sometimes foo(int i) and sometimes both.
Note
If I go through the base class it works, but this solution is not ideal in my program :
Derived derived;
Base* pBase = &derived;
pBase->foo();
pBase->foo(42); //WORK

Edit
Okay, I found on geeksforgeeks.org that you need to use using Base::foo; in derivate class to import other foo functions.
Someone know why and what's going one in the backgourd? I don't like to not understand somethings.

A: Just add a using declaration inside derived class as shown below. In particular, a using declaration for a base-class member function (like foo) adds all the overloaded instances of that function to the scope of the derived class. Now you can override the version that takes an argument of type int and use the implementation of others that were added in the derived class' scope using the using declaration.
class Derived : public Base
{
public:
   //added this using declaration
   using Base::foo;
  void foo() override {
    std::cout << "Derived::foo()" << std::endl;
  }
};

Working demo
The output of the above modified program is as you wanted:
Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)


text:
Q: Exception while index view render This exception thrown while index view render:
"InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first."

This is index view :
@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.pageGroup.GroupTitle)

        @Html.DisplayFor(modelItem => item.Title)

        @Html.DisplayFor(modelItem => item.ShortDescription)

        @Html.DisplayFor(modelItem => item.Text)

        @Html.DisplayFor(modelItem => item.ShowInSlider)

        @Html.DisplayFor(modelItem => item.ImageName)

        @Html.DisplayFor(modelItem => item.Visit)

        @item.CreateData.ToShamsi();

        @Html.ActionLink("Edit", "Edit", new { id=item.PageID }) |
        @Html.ActionLink("Details", "Details", new { id=item.PageID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PageID })

 }

and the exeption thrown in this line :
@Html.DisplayFor(modelItem => item.pageGroup.GroupTitle)

where is the problem ?
If you are confused, tell me to put the codes of the section you want
this is my connection string :
<connectionStrings>
<add name="MyCmsContext" connectionString="data source=.;    initial catalog=MyCmsDB;persist security info=True;     Integrated Security=True; " providerName="System.Data.SqlClient" MultipleActiveResultSets="true"  />

A: You need to allow MARS in your connection string. Add MultipleActiveResultSets=true to the provider part of your connection string.
"Server=xxxx;Database=xxxxx;xxxxx MultipleActiveResultSets=true"


text:
Q: ASP.NET MVC 5 - Disable AntiForgeryToken refresh on every page load I wanted to Disable AntiForgeryToken refresh on every page load. Instead it show come up with unique AntiForgeryToken for every browser session. Like CSRF in PHP Laravel.
I am clueless if there is any option to disable it on every page load or enable it to throw unique token for every broswer session.
Reason is i am using it in one of my SPA application which ultimately never reloads any page because of angular and ajax requests and the problem is when i successfully submit the form once to the server then AntiForgeryToken Expires and gives error.


text:
Q: What is the indicator in vimrc for when using vim as git mergetool? I would like to make some specific settings in vimrc for then I use vimdiff as git mergetool. Normal vimdiff has an indicator &diff but it doesn't seem to work for the mergetool setup.
What is the vimrc indicator for when in the mergetool filemode?

A: If you have configured either vimdiff or gvimdiff, :set diff should be on in the merge buffers (but not any other buffers you might have edited).
Other means to detect would be:

*

*checking the number and paths of the command-line arguments via argc() and argv()

*passing a variable to Vim: vim -c 'let g:isDiff = 1'; note that you need to define a custom Git mergetool if you go this route


text:
Q: How to move Ubuntu SDK data? I have a very small partition where / is installed (on an SSD).
I would like to start programming something for Ubuntu Phone via the SDK.
Unfortunately I do not have enough space to install the necessary "Kit" to program for the armhf architecture (my disk fill up and then the installation of the kit fails).
So, how can I tell to Ubuntu SDK to move these data (the ones linked to the chroots that it makes) to somewhere else?
I could also use some symlinks and manually move the folders, but I do not know which they are.

A: After looking carefully at the outputs from du and similar tools, I discovered that the big directory is /var/lib/schroot.
So I moved it to another place
sudo mv /var/lib/schroot ~/Dati/SDK

and the symlinked it
sudo ln -s ~/Dati/SDK/schroot /var/lib/

Until now, it works.


text:
Q: from hapi to a http-server image my knowledge in backend is not the best...
I am having issues wrapping my head around this.
I have an ng2 upload image, from there it will do a post req to the api, however I would like to have a server (http-server from node) just to add the files there, but I have no idea how to go from here :(
so ng2 (FE) -> Hapi (API) -> http-server (files storage)
These are my files
upload.provider.js
    const fs = require('fs');
class UploadProvider {
  constructor(path, request, reply) {
    this.path = path;
    this.data = request.payload;
    this.reply = reply;
    this.image();
  }

  image() {
    if (this.data.uploadFile.hapi.filename) {
      const name = this.data.uploadFile.hapi.filename.replace(/\ /g,'-');
      const path = this.path + name;
      const file = fs.createWriteStream(path);

      file.on('error', (err) => {
        console.error(err)
      });

      this.data.uploadFile.pipe(file);

      this.data.uploadFile.on('end', (err) => {
        var ret = {
          filename: this.data.uploadFile.hapi.filename.replace(/\ /g,'-'),
          headers: this.data.uploadFile.hapi.headers
        }
        this.reply(JSON.stringify(ret));
      })
    }
  }
}

module.exports = UploadProvider;

teaser.controller.js
const upload = require('../providers/upload.provider');
const Teaser = require('../model/teaser.model');

var teaser = {
  upload: (request, reply) => {
  new upload('http://127.0.0.1:8080/teaser-images/', request, reply);
},

....

I keep getting this output:

{ Error: ENOENT: no such file or directory, open 'http://192.168.33.1:8080/teaser-images/IX4A6789.jpg'
    errno: -2,
    code: 'ENOENT',
    syscall: 'open',
    path: 'http://127.0.0.1:8080/teaser-images/IX4A6789.jpg' }

Would really appreciate any help, this has been bugging me.
And I would really like to understand better the concept around stream buffers.
Best,
Joe

A: I forgot one of the most important facts of browsers... they are based on GET.
I was trying to send the images to a place where it was not a server. after creating an http-server on a folder:
new upload('../images', request, reply);

then adding an http-server on that folder I was able to access the images I wanted.


text:
Q: C error: prototype function declaration not in scope  I don't understand what my error is:
 void main(char string[])
 {
   strcpy(command_E,string);
   processCMD(); /*FIRST ERROR:  prototype function declaration not in scope */
 }

 void processCMD(void) /*SECOND ERROR: external item attribute mismatch */
 {
  .... /*rest of code not displayed*/

A: At the point where you use processCMD(), you haven't declared a prototype for it, so it gets a default one.
The fact that you haven't declared it causes the first error.
The fact that your actual definition conflicts with the default one created because you hadn't declared it is the cause of your second error.
The solution is to either define the function before use:
void processCMD(void) {
    blah blah blah
}

void main (char string[]) {  // not really a good definition for main, by the way.
    strcpy(command_E,string);
    processCMD();
}

or provide a prototype before use:
void processCMD(void);

void main (char string[]) {  // not really a good definition for main, by the way.
    strcpy(command_E,string);
    processCMD();
}

void processCMD(void) {
    blah blah blah
}

As to the declaration of main, the two canonical forms are:
int main (void);
int main (int argc, char *argv[]); // or char **argv.

Others are allowed by the standard (implementation defined) but those two are required (at least for hosted implementations - freestanding implementations like embedded systems or operating systems can pretty well do whatever they want).

A: You need a prototype before the the first use of the function to declare it so the compiler knows what kind of arguments the function takes (if any) and what it returns:
void processCMD(void); // prototype

void main(char string[])
 {
   strcpy(command_E,string);
   processCMD();
 }

 void processCMD(void)
 {
  .... /*rest of code not displayes*/

Alternatively, you could defined the function before it's first use (since the definition will provide the information the compiler wants.
Typically, the prototype will go in a header file so other modules can use the function since function definitions can only be in one source file (barring such things as making the function static, which makes each instance of the function 'private' to a module,  or marking the function as inline, which enables multiple definitions).
Some additional prototype trivia:

*

*Generally in C, the lack of a protoype is not an error in itself - if the compiler sees a function call without having seen a prototype it will assume that you're passing the right parameters, it will apply 'default promotions' to paramters (basically convert things to int ot double as appropriate), and will assume the function returns an int.  If those assumptions are wrong, then the program is incorrect and will have undefined behavior.  Compilers can often be configured to emit warnings or errors for calling functions that don't have prototypes (apparently yours has). In C++, calling a function without a previous protoype being seen (or the full function definition) is always an error.

*In C, there's a difference between:
void processCMD();

and
void processCMD(void);

The first is a function declaration, but not a prototype - it tells the compiler that processCMD is a function and that it returns void instead of int.  But it doesn't tell the compiler anything about the arguments. The compiler will still allow function calls to be made with arguments passed and will apply the default promotions. (Again, this feature might be disabled by compiler configuration).
The second is a prototype that specifically tells the compiler that the function takes no arguments.
In C++, both are equivalent and specifically tell the compiler that the function takes no arguments.


text:
Q: Preventing a Shortcut on the Start Menu from Being Highlighted installshield 2012 My Basic MSI project aims to install two different shortcuts in the Windows startup menu:

*

*one advertised shortcut which proceeds to repair if something is wrong whith the software installation (reset accidentaly removed DLLs for example). This shortcut is only used by the support team if something gone wrong.

*one not-advertised shortcut which is the mainly used by the user

After installation, the repair shortcut is highlighted in the startup menu but the main shortcut isn't.
I specify here having tested these manipulations on a Windows Seven operating system with Windows Installer version> = 5.0

*

*I tried the solution from the Installshield Documentation which consists to add a spécific Shell Shortcut Property

Repair Shortcut settings:
Shell Shortcut Property
Key Name = System.AppUserModel.ExcludeFromShowInNewInstall
value = 1

It doesn't work. The repair Shortcut is still highlighted after install.

*

*I tried to set the System.AppUserModel.ID property first like this link indicates

Repair Shortcut settings:
Shell Shortcut Property
Key Name = System.AppUserModel.ID
value = 1
Key Name = System.AppUserModel.ExcludeFromShowInNewInstall
value = 1

It doesn't work,The repair Shortcut is still highlighted after install on the same configuration.
My main objective is to prevent the repair shortcut from being Highlighted and to activate shortcut highlighting for the main shortcut only.
Thank you for your help.


text:
Q: How can I set up the pivot_table options to get total and percentage? I am practicing the pivot_table. I want to calculate the numbers of "good" and "bad" and also get the percentage of each.
This is the image that I would like to have.
How can I set up the pivot_table options?

A: In this instance, you wouldn't need a pivot table because you're just summing over one variable. An easy way to achieve what you're after would be:
A = ['good','good','bad','good',np.nan]
Data = pd.DataFrame(A)
Data.columns = ['Status']
Data.index=['x1','x2','x3','x4','x5']

counts = Data.Status.value_counts().to_frame('total')
counts['percentage'] = counts.total /
counts.total.sum()

To do the same thing with a pivot table, I think you'd need to introduce a dummy variable to sum over. And either way, you'd still have to calculate the percentage afterwards:
Data['total'] = 1
piv = Data.pivot_table(
    index='Status',
    values='total',
    aggfunc='sum'
)
piv['percentage'] = piv.total/piv.total.sum(axis=0)


text:
Q: get the value of sales_order_address table custom column value in rest/V1/orders/ I'm unable to get the value of sales_order_address table custom column value in
rest/V1/orders/?searchCriteria[filter_groups][0][filters][0][field]=status&searchCriteria[filter_groups][0][filters][0][value]=processing");

A: If you append the searchCriteria to the url, the API tries to us the api call
 <route url="/V1/orders/:id" method="GET">
        <service class="Magento\Sales\Api\OrderRepositoryInterface" method="get"/>
        <resources>
            <resource ref="Magento_Sales::actions_view" />
        </resources>
    </route>

The below will returns the data your are looking for. It is more advanced and has the constraint to require Zend dependency. Fortunately, Magento uses Zend and so do most frameworks.
<?php
    $token = 'yourtoken';
            $httpHeaders = new \Zend\Http\Headers();
            $httpHeaders->addHeaders([
                'Authorization' => 'Bearer ' . $token,
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

            $request = new \Zend\Http\Request();
            $request->setHeaders($httpHeaders);
            $request->setUri('http://<magentoroot>/index.php/rest/V1/orders');
            $request->setMethod(\Zend\Http\Request::METHOD_GET);

            $params = new \Zend\Stdlib\Parameters([
                'searchCriteria' => [
                    'filterGroups' => [
                        0 => [
                            'filters' => [
                                0 => [
                                    'field' => 'status',
                                    'value' => $input->getArgument('status'),
                                    'condition_type' => 'eq'
                                ]
                            ]
                        ]
                    ],
                    'current_page' => 1,
                    'page_size' => 10
                ],
            ]);

            $request->setQuery($params);

            $client = new \Zend\Http\Client();
            $options = [
                'adapter'   => 'Zend\Http\Client\Adapter\Curl',
                'curloptions' => [CURLOPT_FOLLOWLOCATION => true],
                'maxredirects' => 0,
                'timeout' => 30
            ];
            $client->setOptions($options);

            $response = $client->send($request);

            $response = $response->getBody();


text:
Q: Can you explain why there's a lot of TCP connections openned when running multiple requests? I try to understand why there's a lot of openned TCP connection when I running a lot of synchronous requests.
In Windows, I use Python 3 to open a HTTP test server in a console:
python -m http.server 9000

In a Git Bash console, I launch a lot of requests with a loop:
for i in $(seq 1000); do curl http://localhost:9000/; done

During the requests, I see a lot of TCP connections related to the curl client and the Python server. The number of openned TCP connections increases over time as you can see in the screenshot.
After some times, connections are closed.
Screenshot of Windows Ressource Monitor
Why the connections are still opened ?
Edit 1:
With one curl command, I can see a openned connection during 2 minutes with netstat -n | grep :9000:
  TCP    127.0.0.1:64301        127.0.0.1:9000         TIME_WAIT

Changing the TTL does not change the duration of the openned request.


text:
Q: Apple dictation missing commands in web browser I am dealing with physical problems from the keyboard/mouse, so discovering Apple dictation has been amazing. However, I work a lot in Google Docs and Gmail... and Google Chrome (or any web browser) does not let me use all of the commands that Apple's dictation provides. It's missing essential selection, navigation and editing commands that are available when using an Apple app like TextEdit. Those commands are essential for moving the cursor around and making fixes without the keyboard. The only solution that's been working for me has been to type in TextEdit, and then to copy and paste into the browser. But this is not a real solution.

It would be nice to stick with the native (and free) Apple dictation software on the mac, so does anyone have an idea to get these dictation commands to work in a web browser for use with gmail and google docs?
Edit: I found that Safari lets you use Apple's dictation with gmail, but still not with Google Docs.

A: Google docs uses a custom javascript application that disables the services component of the Mac (that lets the built in Mac voice dictation work.). If you want to use voice dictation in Google Docs, you have to use there build in functionally, and you MUST use Google Chrome.
From Google:

For an easy way to put words on a page, you can type with your voice in a document. At the moment, this feature is only available in Chrome
  browsers.

Here's how to activate the type with your voice function for Google Docs.

*

*In a Chrome browser, open a Google Docs document.

*Click the Tools menu -> Voice typing...

*A pop-up microphone box will appear. When you are ready to speak your text, click the microphone or press Cmd + Shift + S on your keyboard.

*If this is the first time you've let Chrome use your microphone you will get a little pop-up from the top of the screen asking to OK Chrome using your microphone. Hit Allow to enable the microphone in Chrome.

*Once you click in the Click to Speak box, the mic icon will turn orange and appear in a circle.

*You can now dictate into your Google Docs. As you do the mic icon will show when it detects sound with an outer ring.

*When you're finished, click the microphone again.

From Google:

While voice typing in Google Docs is only available on computers, many Android and iOS phones and tablets have built-in microphones that
  you can use with a document. Look for the microphone icon on your
  mobile keyboard.

For more information you can check out the Google Help Documentation here:
Typing With Your Voice.

A: You can make custom commands for any key bindings you would use in Gmail and Google Docs. For example, here is a command for moving the cursor to the end of the line in Gmail.

You can find this menu under Accessibility>Dictation>Dictation commands>+
So, so long as you have key bindings for the stuff that you want, you will be able to manually create voice commands. There are lots of key bindings for Gmail, and I believe with some investigation you could find Chrome add-ons for navigating links within pages.


text:
Q: Error fetching Azure AD B2C token I am using Azure AD B2C for my web application's user identity requirements. I'm using ASP.NET Core 2.0 Razor Pages project to build the web application.
If the user is not authenticated when trying to access a web page they are routed to the Azure AD B2C login page. They are then returned to my web app if successfully authenticated.
I am trying to get hold of the returned JWT token using this document https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-access-tokens
I keep getting the following error:

I am using the following code to retrieve the token.
string url = $"https://login.microsoftonline.com/{this._options.Domain}/oauth2/v2.0/authorize?";
            string policy = this._options.SignUpSignInPolicyId;
            string clientid = this._options.ClientId;
            string grantType = "authorization_code";
            Random random = new Random();
            int nonce = random.Next();
            string redirectUri = WebUtility.UrlEncode("https://localhost:44315/");
            string scope = WebUtility.UrlEncode($"https://{this._options.Domain}/notes/openid");
            const string responseType = "code";

            string request =
                $"{url}p={policy}" +
                $"&client_id={clientid}" +
                $"&grant_type={grantType}" +
                $"&nonce={nonce}" +
                $"&redirect_uri={redirectUri}" +
                $"&scope={scope}" +
                $"&response_type={responseType}";

            var response = await GetData(request);

A: It would seem that the claims returned from Azure AD B2C are contained within the User.Claims object.
if (User.Identity.IsAuthenticated)
{
    Claim emailClaim = User.Claims.FirstOrDefault(claim => claim.Type == "emails");
    Claim isNewClaim = User.Claims.FirstOrDefault(claim => claim.Type == "newUser");
}


text:
Q: How do I remove this vertical space? Here's my code -
\documentclass[12pt]{book}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{syntonly}
\usepackage{amsthm}
\usepackage{parskip}
\usepackage{tabularray}
%xparse package needed for physics package to work properly
\usepackage{xparse}

% Font encoding
\usepackage[T1]{fontenc}
\usepackage[version=4]{mhchem}
\usepackage{chemfig}
%For colours
\usepackage[x11names]{xcolor}

%Defining colours
\definecolor{Rust}{HTML}{BF3100}
\definecolor{Orange yellow}{HTML}{EEB902}

\definecolor{Vermillion}{HTML}{D52D0B}
\definecolor{Imperial Red}{HTML}{E63946}
\definecolor{Honeydew}{HTML}{F1FAEE}
\definecolor{Powder Blue}{HTML}{A8DADC}
\definecolor{Atomic Tangerine}{HTML}{F39C6B}
\definecolor{Selective yellow}{HTML}{FFB703}
\definecolor{Prussian blue}{HTML}{033063}
\definecolor{Raisin black}{HTML}{272838}

%%%%%%%%%%%%%%%%%%%%COLOURSCHEME%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%COLOURSCHEME%%%%%%%%%%%%%%%%%%%
%Definitions header
\definecolor{Yale blue}{HTML}{084B83}
% definition boxes colour [colback=Powder blue!50!white, colframe=Powder blue!50!white]
\definecolor{Powder blue}{HTML}{BBE6E4}

%Examples header
\definecolor{Indian red}{HTML}{DB5461}
%Examples box [colback=Unbleached silk!65!white, colframe=Unbleached silk!65!white]
\definecolor{Unbleached silk}{HTML}{FFD9CE}

%Margin notes colour (Linen!60!white)
\definecolor{Linen}{HTML}{F9EAE1}
%%%%%%%%%%%%%%%%%%%%COLOURSCHEME%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%COLOURSCHEME%%%%%%%%%%%%%%%%%%%

%Package for fixing bugs when using marginnotes
\usepackage{mparhack}

%For Garmond font
\usepackage{garamondlibre}

%Float package
\usepackage{float}

%Continue to enumerate
\usepackage{enumitem}

\usepackage{tcolorbox}

%layout package
\usepackage{layout}

%geometry package
\usepackage{geometry}
\geometry{papersize={23cm,28cm}, right=9.3cm, left=3cm, top=2.5cm, bottom=3cm, marginparwidth=4.8cm, marginparsep=1.5cm, headheight=0cm}

%marginparpush=2cm

%fancyheaders
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[LO,RE]{\chaptername\ \thechapter}
\fancyfoot{}
\fancyfoot[LO,RE]{\thepage}

%Packages for Maxwell-Boltzmann distribution
\usepackage{pgfplots,siunitx}

%Wrapping lines of text package
\usepackage{seqsplit}

%For the unit of rate constant table
\usepackage{tabularray}
\UseTblrLibrary{amsmath, siunitx}

%Package for striking out terms in a calculation
\usepackage{cancel}

\usepackage{xfrac}

%Package for inserting figures in margin notes
\usepackage{sidenotes}

%packages required for sidenotes package to work correctly
\usepackage{marginnote}
\usepackage{xparse}
\usepackage{caption}
\usepackage{l3keys2e}
\usepackage{changepage}

%package for landscape tables
\usepackage{rotating}
\usepackage{array}
\newcolumntype{L}{>{\centering\arraybackslash}m{3cm}}

%Defining a new column type for the alkyl groups table
\newcolumntype{A}{>{\centering\arraybackslash}m{2cm}}
\newcolumntype{B}{>{\centering\arraybackslash}m{3.4cm}}
\newcolumntype{C}{>{\centering\arraybackslash}m{1.7cm}}
\newcolumntype{D}{>{\centering\arraybackslash}m{4cm}}

%Defining a new column type for the cis-trans isomers table
\newcolumntype{E}{>{\centering\arraybackslash}m{7cm}}
\newcolumntype{F}{>{\centering\arraybackslash}m{3cm}}

\newcolumntype{G}{>{\centering\arraybackslash}m{8cm}}

%For the free radical substitution reaction
\newenvironment{f}{$\displaystyle\aligned}{\endaligned$}

%to fix overlflowing margin notes
\usepackage{marginfix}

% Diagrams from mathcha
\usepackage{physics}
\usepackage{tikz}
\usepackage{mathdots}
\usepackage{yhmath}
\usepackage{cancel}
\usepackage{color}
\usepackage{siunitx}
\usepackage{array}
\usepackage{multirow}
\usepackage{gensymb}
\usepackage{tabularx}
\usepackage{extarrows}
\usepackage{booktabs}
\usetikzlibrary{fadings}
\usetikzlibrary{patterns}
\usetikzlibrary{shadows.blur}
\usetikzlibrary{shapes}

\usetikzlibrary{arrows.meta}

\begin{document}
For example -
\begin{tcolorbox}[colback=Powder blue!50!white, colframe=Powder blue!50!white]
\begin{align*}
    \ce{\textstyle\frac{1}{2}Br2(l) & ->[\Delta H_{at}^{\ominus}]Br(g)}\\
    \ce{\textstyle\frac{1}{2}Cl2(g) & ->[\Delta H_{\text{at}}^{\ominus}] Cl(g)}\ \ \ \ \Delta H_{at}^{\ominus}=+121\ \unit{kJ\ mol^{-1}}\\
    \ce{Na(s) & ->[\Delta H_{at}^{\ominus}] Na(g)}\ \ \ \ \Delta H_{\text{at}}^{\ominus}=+109\ \unit{kJ\ mol^{-1}}\\
     \ce{\textstyle\frac{1}{2}H2(g) & ->[\Delta H_{\text{at}}^{\ominus}] H(g)}\ \ \ \ \Delta H_{at}^{\ominus}=+218\ \unit{kJ\ mol^{-1}}
\end{align*}
\end{tcolorbox}
\end{document}

This generates the following -

Any ideas on how I can remove the extra blue vertical space?

A: Use option ams align* in tcolorbox options and avoid using ams align* environment inside.
\documentclass[12pt,x11names]{book}
\usepackage[T1]{fontenc}
\usepackage[version=4]{mhchem}
\usepackage{chemfig}
\usepackage{xcolor}

\definecolor{Powder blue}{HTML}{A8DADC}

\usepackage{garamondlibre}

\usepackage[most]{tcolorbox}

%geometry package
\usepackage{geometry}
\geometry{papersize={23cm,28cm}, right=9.3cm, left=3cm, top=2.5cm, bottom=3cm, marginparwidth=4.8cm, marginparsep=1.5cm, headheight=0cm}

\usepackage{siunitx}

\begin{document}
For example -
\begin{tcolorbox}[colback=Powder blue!50!white, colframe=Powder blue!50!white, ams align*]
%\begin{align*}
    \ce{\textstyle\frac{1}{2}Br2(l) & ->[\Delta H_{at}^{\ominus}]Br(g)}\\
    \ce{\textstyle\frac{1}{2}Cl2(g) & ->[\Delta H_{\text{at}}^{\ominus}] Cl(g)}\ \ \ \ \Delta H_{at}^{\ominus}=+121\ \unit{kJ\ mol^{-1}}\\
    \ce{Na(s) & ->[\Delta H_{at}^{\ominus}] Na(g)}\ \ \ \ \Delta H_{\text{at}}^{\ominus}=+109\ \unit{kJ\ mol^{-1}}\\
     \ce{\textstyle\frac{1}{2}H2(g) & ->[\Delta H_{\text{at}}^{\ominus}] H(g)}\ \ \ \ \Delta H_{at}^{\ominus}=+218\ \unit{kJ\ mol^{-1}}
%\end{align*}
\end{tcolorbox}
\end{document}

A: Use the array environment
\documentclass[12pt,x11names]{book}
\usepackage[T1]{fontenc}
\usepackage[version=4]{mhchem}
\usepackage{chemfig}
\usepackage{xcolor}
\definecolor{Powder blue}{HTML}{A8DADC}
\usepackage{garamondlibre}
\usepackage[most]{tcolorbox}
\usepackage{geometry}
\geometry{papersize={23cm,28cm}, right=9.3cm, left=3cm, top=2.5cm,
     bottom=3cm, marginparwidth=4.8cm, marginparsep=1.5cm, headheight=0cm}
\usepackage{siunitx}

\begin{document}
\noindent
For example -
    \begin{tcolorbox}[colback=Powder blue!50!white, colframe=Powder blue!50!white]
        \arraycolsep=1.6pt
        $\begin{array}{rl>{\qquad}l}
        \ce{\textstyle\frac{1}{2}Br2(l) & ->[\Delta H_{at}^{\ominus}]Br(g)}\\
        \ce{\textstyle\frac{1}{2}Cl2(g) & ->[\Delta H_{\text{at}}^{\ominus}] Cl(g)} & \Delta H_{at}^{\ominus}=+121\ \unit{kJ\ mol^{-1}}\\
        \ce{Na(s) & ->[\Delta H_{at}^{\ominus}] Na(g)} & \Delta H_{\text{at}}^{\ominus}=+109\ \unit{kJ\ mol^{-1}}\\
        \ce{\textstyle\frac{1}{2}H2(g) & ->[\Delta H_{\text{at}}^{\ominus}] H(g)} & \Delta H_{at}^{\ominus}=+218\ \unit{kJ\ mol^{-1}}
        \end{array}$
    \end{tcolorbox}
\end{document}


text:
Q: REST API Call via Python requests does not work on VPN I am calling a REST API to Informatica from POSTMAN and Python (requests library) and find the behavior quite funny.
When I am on VPN I can only make a successful call from POSTMAN, however if I switch VPN off both Python and POSTMAN calls work perfectly.
Python script generated automatically by POSTMAN.
Error:
ConnectionError: HTTPSConnectionPool(host='use4-mdm.dm-us.informaticacloud.com', port=443): Max retries exceeded with url: /rdm-service/external/v2/export (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000002393AB297C0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

Any ideas what the reason might be?
UPD
To make my question more clear:

*

*This is a corporate VPN on work laptop

*My system does not have *_PROXY variables

*No default proxy in requests library
 import requests
 session = requests.Session()
 session.proxies
 >>> {}

*http.client library - same result

*Settings in POSTMAN are in screenshot below

A: you may want to have a look at the "proxies" parameter of python requests :)


text:
Q: Regex grab numbers after dollar sign I have dynamic strings that sometimes will have a price in them and sometimes not. Its for craigslist so there is really no set format there can be commas, dashes, etc. Here are some examples of a typical string:

Xbox 360 (black) Elite Console 120GB (Mason City Illinois ) $200
$200 2013 North Trail Camper (RT 202. Manchester, Maine) $224/mo.
Snowmobile Bike trailers (Winthrop / Augusta) $40 Monthly
"Great Xmas Gift" XBox 360 Guitar Hero (Springfied) $80

I am trying to split up the string into title, location, and price. I can grab the location with:
Pattern p = Pattern.compile("\(([^]*)\)");
Matcher m = p.matcher(title);

Having trouble figuring out how to separate the title and price out. Any help would be appreciated.

A: To grab number after $ use: \$[0-9]+ regex.

A: Personally I would use:
 \$[-0-9.,]+[-0-9.,a-zA-Z]*\b

It will take quite a few non-numbers, but it will also glob up stuff like negative values, $1,000, $1mil and so on. The \b at the end will ensure it globs up as much as possible before a space or new line or something.

A: To grab number after $ use \$(\d+) regex.
Regex Demo
Note the capturing parentheses, the desired value will be accessible via m.group(1).
Double escape backslashes in Java code, too.
See snippet below:
Pattern p = Pattern.compile("\\$(\\d+)");
Matcher m = p.matcher(title);
String output = "";
if (m.find()) {
    output = m.group(1);
}


text:
Q: How to parse date into the array?
11.06.2012 17:40

All what I need it's to put in array values
mydate.day = 11;
mydate.month = 6;
mydate.year = 2012;
mydate.hours = 17;
mydate.minutes = 40;

A: "11.06.2012 17:40".split(/[.: ]/).map(Number);
//[11, 6, 2012, 17, 40]