text:
Q: Using external script in Views.py I have a file that sends a request to an API and retrieves information. Let's call this file get_info.py.  I am now building a GUI that uses Django and the views.py file, with methods 'GET' and 'POST'.
I am now importing the function from get_info.py into views.py and using it as follows
from get_info import get_info
@api_view(['GET'])
def generate_route(request):
    """
    :param request:
    1. lat: posx
    2. lng: pos,
    3. r: radius in km
    4. strategy,
    5. edge_num,
    6. deep,
    :return:
    """
    posx = request.query_params.get('lat', None)
    posy= request.query_params.get('lng', None)

    r= request.query_params.get('r', None)
    strategy = request.query_params.get('strategy', None)
    strategy = strategy if strategy else 3
    edge_num = request.query_params.get('edge_num', None)
    edge_num = edge_num if edge_num else 3
    deep = request.query_params.get('deep', None)
    deep = deep if deep else 3
    print("BEFORE", posx, posy, r, strategy, edge_num, deep)
    route = get_info(posx, posy, r)
    print("AFTER", route)
    if request.query_params.get('lat', None) is not None \
            and request.query_params.get('lng', None) is not None \
            and request.query_params.get('r', None) is not None:
        return Response({}, status=status.HTTP_200_OK)
    else:
        return Response({
            "Error": 'Need lat, lng, and r {}'.format(request.query_params.get('lat', None))
        }, status=status.HTTP_400_BAD_REQUEST)
```

However, I get the response
> (u'BEFORE', u'112.34', u'14.55', u'300.3', 3, 3, 3)
  Internal Server Error: /app/api/v1/get_info/
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/decorators.py", line 53, in handler
    return func(*args, **kwargs)
  File "/home/user/Projects/app/views.py", line 750, in generate_route
    route = get_info(posx, posy, r)
  File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 466, in dispatch
    request = self.initialize_request(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py", line 370, in initialize_request
    parser_context=parser_context
  File "/usr/local/lib/python2.7/dist-packages/rest_framework/request.py", line 159, in __init__
    .format(request.__class__.__module__, request.__class__.__name__)
AssertionError: The `request` argument must be an instance of `django.http.HttpRequest`, not `__builtin__.unicode`.

But when I use from django.http import HttpRequest to build my request, it tells me 'maximum depth exceeded'.
The get_info method is quite long, but in a nutshell it looks like this:
def get_info(posx, posy, r, strategy=3, edge_num=0.8, deep=0):
    req_url = "http://api.map.baidu.com/direction/v2/driving?origin=posx..."
    trip = requests.get(req_url).json()
    return trip

When I run this get_info method in my python shell, it returns the desired trip.

A: If you look closely rest framework is the one which is causing the problem, If the getinfo is an APIView then it might need request as its first argument not posx which is a string.


text:
Q: How can I make/patch php source (c code) to read an array from php.ini? I'm experienced with php but I'm a novice to the php source and php extensions. I want to extend php so that it randomly chooses an upload_tmp_dir from an array, rather than one fixed dir.
It doesn't look like php and the ini-file reading code has any natural ability to parse arrays in the ini file.
Is there any existing code or extension (either in the tree or outside it) that allows for mapping an ini-defined array to a global array val in php?
Otherwise I guess I'll introduce ini vals like "num_upload_dirs" and then "upload_tmp_dir_1" and "upload_tmp_dir_2" etc. and then explicitly check for all vals.
OR write the line-parsing and global-array-creating routines myself into the ini-file reader. Neither are very appealing. Any other suggestions?

A: The ini file format doesn't support arrays.
You will be best served by doing uplaod_tmp_dir_1 etc. You get no benefit from using array syntax.
It is actually fewer bytes if you think about it. ;)

A: PHP supports arrays in ini files by default. There is no need to patch anything
The ini
key[] = value1
key[] = value2

with this php
var_dump(parse_ini_file('my.ini'));

returns
array(1) {
  ["key"]=>
  array(2) {
    [0]=>
    string(6) "value1"
    [1]=>
    string(6) "value2"
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: after rotating image on matlab..then results go on bad:( I am intersted with determining branchpoints of retinal images and then registering these images. First of all I am using a algorithm for extracting of vessels from image then skeletization and finding branchpoints. At first operation all things were ok but if I rotate same image by randomize angle, number of branchpoints are very increase. what are your opinions about this problem...
related links of images :
http://e1204.hizliresim.com/w/6/449m6.jpg
http://e1204.hizliresim.com/w/6/449by.jpg

A: imrotate's standard interpolation algorithm is nearest neighbor, that tends to transform your image in a beautiful saw.
If you rotate your image with imrotate, try passing as the third parameter a better method, like bicubic or bilinear, both will be much better.
The syntax is simple:
imrotate(img, degrees, 'bicubic');


text:
Q: Pyramid .bat not finding PSERVE I have a web system developed in Pyhton 2.7.7 with Pyramid 1.5.1 (I know it's quite old, but it's an enterprise system), and I'm trying to install the same system in another server.
I have installed all the libraries and created the project, but when I call the pserve command (call ..\Scripts\pserve production.ini --reload), it says:
Starting subprocess with file monitor
c:\v2\Scripts\python.exe: can't open file 'C:\v2\Scripts\pserve': [Errno 2] No such file or directory

I don't know what to do because the path is correct.
I appreciate any help.
Thanks


text:
Q: second order coupled odes solving for double spring dampener system I am working on a spring dampener system and have managed to get the coupled odes:
$$\begin{pmatrix}m_1&0\\0&m_2\end{pmatrix}\frac{d^2}{dt^2}\begin{pmatrix}x_1\\x_2\end{pmatrix}+\begin{pmatrix}c_1+c_2&-c_2\\-c_2&c_2\end{pmatrix}\frac{d}{dt}\begin{pmatrix}x_1\\x_2\end{pmatrix}+\begin{pmatrix}k_1+k_2&-k_2\\-k_2&k_2\end{pmatrix}\begin{pmatrix}x_1\\x_2\end{pmatrix}=0$$
In terms of constants and initial conditions:
$$\begin{pmatrix}x_1\\x_2\end{pmatrix}(t=0)=\begin{pmatrix}5\\10\end{pmatrix},\frac{d}{dt}\begin{pmatrix}x_1\\x_2\end{pmatrix}(t=0)=\begin{pmatrix}0\\0\end{pmatrix}$$
I would like to try and keep the constants open if possible to model different situations but if they are needed for a method then I can provide a sample for them. I would just like some advice and a starter on how to begin solving a system like this so that I can work it out for myself. Thanks :)

As suggested by changing this into a system of four equations I get:
$$\begin{pmatrix}z_1\\z_2\\z_3\\z_4\end{pmatrix}'=\begin{pmatrix}0&1&0&0\\-\frac{k_1+k_2}{m_1}&-\frac{c_1+c_2}{m_1}&\frac{k_2}{m_1}&\frac{c_2}{m_1}\\0&0&0&1\\\frac{k_2}{m_2}&-\frac{k_2}{m_2}&\frac{c_2}{m_2}&-\frac{c_2}{m_2}\end{pmatrix}$$
subject to:
$$\begin{pmatrix}z_1\\z_2\\z_3\\z_4\end{pmatrix}(0)=\begin{pmatrix}5\\10\\0\\0\end{pmatrix}$$


text:
Q: How to use variable in xpath xslt? i have the following xml properties file as input,
<Service>
    <Provider>
        <TEST1>http://example1.com</TEST1>
        <TEST2>http://example2.com</TEST2>
        <TEST3>http://example3.com</TEST3>
    </Provider>
</Service>

in my xslt, based on the incoming request host name (example: https://test2service.example.com) ; using contains function i am saving environment value to a variable.
<xsl:variable name="Environment">
            <xsl:choose>
                <xsl:when test="contains($ConsumerHost, 'test1')">
                    <xsl:text>TEST1</xsl:text>
                </xsl:when>
                <xsl:when test="contains($ConsumerHost, 'test2')">
                    <xsl:text>TEST2</xsl:text>
                </xsl:when> ..........

Now based on the environment variable value, i have to choose the backend server. below code is not working. Please suggest.
<xsl:variable name="HOST" select="//Provider/($Environment)/text()" />

Any other solutions are welcome! Thanks.

A: Try this expression instead...
<xsl:variable name="HOST" select="//Provider/*[local-name() = $Environment]/text()" />


text:
Q: GoogleAppEngine: Python Files are Cached, HTML are fine I've read through GAE documentation and other Stack Overflow questions and i'm not seeing anything similar to my issue and it's driving me crazy.
When I start app engine and make some changes to my report.py file, I then go to my browser and load /r with the URL variables and everything loads fine.
I then go back to my report.py and make a change and nothing shows up. I tried adding in a logging.info() which didn't show up in the logging area of GAE, then even tried hard coding once of the variable i pass to HTML. nothing updates. I then straight up moved the python file to reportKEEP.py and the request still runs fine. I.e. GAE is caching my .py file and there's nothing I can do to un-cache besides stopping the app and then running it again. When I do reset the app via the launcher the changes show up fine (or the error that no report.py found).
I also tried updating the html file and that updates fine so I know that's working, it's just the .py file getting cached.
Please let me know what else I can provide to help you help me.
Everything i've read in the docs about caching is about static files and the py is not one of those.
Thanks!

A: Well i have no idea what was causing this but at least i figured out a workaround.
I did look at the link from vlad and I knew this wasn't a timestamp issues. I basically rebuilt my entire app engine environment from scratch including uninstalling and reinstalling GAE launcher, running from command line, and even eventually got my wife's macbook pro and did a completely fresh install. Still no luck, everytime i edited that damn report.py file, the changes wouldn't be reflected on the front end. Could even remove the file and the request would generate fine, meanign the file was cached somewhere deep in GAE.
Eventually i just said screw it, copied the .py into a new file (reports.py) and edited the main.py to point to the new file. VIOLA! works perfectly, updating the front end with new data and print outs instantly.
If i had to guess it may have been because in my main.py i had a forwarding handler for both /r and /report pointing to the same report.py file, but i'm too scared to mess with it.


text:
Q: Photorec not letting me recover files, prompting me with [process completed], why is it not detecting my SD card?
I am running MacOS Monterey version 12.0.1

A: "Bad CPU type in executable" should tell you something.
Looks like you have downloaded a version of the program that is not for your computer CPU architecture.
Is your Mac M1-based? or Intel-based? MacOS 12.0.1 would not run on the (respectably old) PowerPC-based Macs, so they are out of question.
As far as I can tell, PhotoRec has no official binary package for MacOS ono M1 CPU and in order to use the program, you have to compile it yourself.


text:
Q: Python Pandas styling changing background color of whole row based on value in column I would like to change the background color to green, yellow and red based on the lastupdate column below:
Reproducible code:
testdf = pd.DataFrame({'title': {0: 'Test1',
  1: 'Test2',
  2: 'Test3',
  3: 'Test4',
  4: 'Test5',
  5: 'Test6',
  6: 'Test7',
  7: 'Test8'},
 'url': {0: 'link',
  1: 'link',
  2: 'link',
  3: 'link',
  4: 'link',
  5: 'link',
  6: 'link',
  7: 'link'},
 'status': {0: 'In_progress',
  1: 'In_progress',
  2: 'In_progress',
  3: 'In_progress',
  4: 'In_progress',
  5: 'In_progress',
  6: 'In_progress',
  7: 'In_progress'},
 'age': {0: 12, 1: 14, 2: 31, 3: 42, 4: 81, 5: 104, 6: 105, 7: 138},
 'lastupdate': {0: 6,
  1: 18,
  2: 20,
  3: 20,
  4: 20,
  5: 19,
  6: 90,
  7: 111}})

Data:
    title   url status  age lastupdate
0   Test1   link    In_progress 12  6
1   Test2   link    In_progress 14  18
2   Test3   link    In_progress 31  20
3   Test4   link    In_progress 42  20
4   Test5   link    In_progress 81  20
5   Test6   link    In_progress 104 19
6   Test7   link    In_progress 105 90
7   Test8   link    In_progress 138 111

The logic for green, yellow, red is as follows:
def highlight(s):
    '''
    highlight the maximum in a Series yellow.
    '''
    if s <= 14:
        return 'background-color: green'
    elif (s > 14 & s < 30):
        return 'background-color: yellow'
    elif s > 30:
        return 'background-color: red'

I am struggling to apply to the testdf. I can use testdf.style.apply but it tends to apply to the whole table. Is there a way to modify this function and apply on one column and change the background of all the rows ?
The output should look as follows:

Eventually I will use this to send email.

A: Since you use lastupdate to determine the whole row, you want to apply on row and return the format css for each cell. Something like this:
def highlight(row):
    '''
    highlight the maximum in a Series yellow.
    '''
    s = row['lastupdate']
    if s <= 14:
        css = 'background-color: green'
    elif (14 < s < 30):
        css = 'background-color: yellow'
    else:
        css = 'background-color: red'

    return [css] * len(row)

df.style.apply(highlight, axis=1)

Output:


text:
Q: Where does LogCat's Log.x() output go when running Android JUnit tests? I noticed that when testing plain Java classes via test classes derived from TestCase and AndroidTestCase, LogCat output disappears.
Is it possible to still capture the output of these messages? or my only recourse is to use the much more sluggish ActivityInstrumentationTestCase2<> as a base class?

A: Both of these statements produce log in logcat:
    android.util.Log.d(TAG, "This is Log.d");
    System.out.println("This is System.out.println");

A: Just for anyone using Android Studio. You can open the Android DDMS tool window (Cmd + 6) and turn off any filters using the dropdown box in the top right. It seems to use app:com.your.package.name as a default, which filters test output.

A: I had similar issue... The point here is that the logcat view available in Eclipse does not show anything when running the project in Android Junit mode. At least, in the Android 2.1 that I was using, that's the behavior.
You can workaround this issue by checking the logcat from command line (terminal window):
# check the device name you are using
# It gives something like this:
$ ./adb devices
List of devices attached
emulator-5554   device

# open logcat of the device
$ ./adb -s emulator-5554 logcat
D/AndroidRuntime(  943):
D/AndroidRuntime(  943): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
D/AndroidRuntime(  943): CheckJNI is ON
.
.
.

A: Simply using Log.v("MyIdentifier","MyMessage") statements seems to log everything for me, both from the Unit test classes themselves and from my Android application under test.
This info may help someone using Android jUnit for the first time:
Android jUnit testing will only actually start an activity when getActivity() is called from within a test class. If get Activity is not called you will not see the results of any of the logging calls you have written in for example onCreate or onResume. There seems to be an exception to this rule though when the Activity marked as "Main" and "Launcher" in the Android Manifest is under test.


text:
Q: Does not it affect the efficiency to declare a function variable as local instead of global? I've actually seen some results by testing it, but I want to know which way is better and why.
Question #1: Do local variables get declared every time when I call that function again and again? I know that it is better to declare variables in the narrowest scope possible. But I can not stop myself thinking about declaring it as a global variable and make it get declared only once, not in every function call. Or, does it get declared again in every function call? I know that the scope of a local variable is only that function. So when it leaves that function, it must forget that variable as it is going out of its scope right?
Question #2: When I have some function variables which need to store its previous content(e.g. timer counter variables), which way is better: to declare them as a global variable or to declare them as a static local variable? I don't need them to get their initial values whenever I call that function, I am already setting them to zero or etc whenever I need.

A:
Question #1: Do local variables get declared every time when I call that function again and again?

A1: Yes, but it's not an issue really.
Declaring a local variable means that space is made for that variable on the stack, within the stack frame of that function. Declaring a variable global means that space is made for that variable in the data section of the executable (if the variable is initialized), or the BSS section (if not).
Allocating on the stack comes at zero cost. At function entry, the stack frame is sized to make room for all local variables of the function. One more or less does not matter. Statically allocating (for a global variable) is a tad quicker, but you only get that one variable. This can become a huge issue at some later point, e.g. if you want to make your program multithreaded, your function re-entrant, or your algorithm recursive. It can also become a major hassle during debugging, wasting hours of unproductive time while you are hunting down that bug.
(This is the main point of it all: The performance difference is really negligible. The time you can waste on a suboptimal design riddled with globals, on the other hand, can be quite significant.)

Question #2: [...] which way is better: to declare them as a global variable or to declare them as a static local variable?

A2: From an architectural standpoint, avoid globals wherever possible. There are a few specific cases where they make sense, but you know them when you see them. If you can make it work without globals, avoid them. (The same is true, actually, for static locals. They are better than globals as they are limited in scope, and there are cases where they make sense, but local variables should really be the "default" in your mind.)

A:
Global variable - declared at the start of the program, their global scope means they can be used in any procedure or subroutine in
  the program

It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.

Local variable - declared within subroutines or programming blocks, their local scope means they can only be used within the
  subroutine or program block they were declared in

Local variables are initiated within a limited scope, this means they are declared when a function or subroutine is called, and once the function ends, the memory taken up by the variable is released. This contrasts with global variables which do not release memory.

Question #1: YES. Local variables get declared every time when you call that function again and again. After it leaves the function it forgots the variables that you declared in that scope. You must also remember that when some variable faced, the program will start to search for it. So when it is closer like declaring in the same scope, it will find faster and be able to continue. Also this will be more efficent while you are coding and will cause less bugs and mistakes etc.
Question #2: If you use the same variable with different functions, I strongly suggest you to declare them as global or define, this will lead the program to carry your "counter" with it. So it can be fastly use it when you need between the scopes you travel.
But after these conditions I must strongly suggest you to:

avoid globals wherever possible (as @DevSolar said)

A: Q2:
It is usually more preferable to use static variables in your function. The main reason is that since all functions can access global variables, it is very hard to keep track of and debug your program.
Q1:
Yes, local variables are created every time the function it belongs to is run, and deleted when the ends.
Suppose your program has 5 functions (that are rarely used), and each function uses 6 local variables. If you change them all to global variables, you will have all 30 variables taking up space for the entire duration of your program, instead of only have 5 variables occasionally being created and destroyed. Moreover, allocation does not really take much time.


text:
Q: Is there a difference between Newtonian mechanics and classical mechanics? I have heard the terms "Newtonian mechanics" and "classical mechanics" used interchangeably, but is there a difference between them? If so, what is it?

A: The term "Classical mechanics" sometimes describes brunch of physics or a course, which focuses on Lagrange and Hamiltonian formalism. This are a little bit advanced tools, which are widely used (Euler-Lagrange equations etc...).
Because this (mathematical) tools are a little bit harder, they are often taught on the example of something, which we understand very good and it's quite simple and this is simple mechanic (pendulums, objects on slopes, spinning-tops...). This course at uni is often titled "Classical mechanics". It focuses on describing Newtonian mechanics, but with different tools, which can be than applied on other fields of physics (often quantuum etc). Notable classical mechanics problems are spinning-top (precession, nutation), all components of Couriolis force, shape of pendulum, central potenitals, Euler-Lagrange equations, Hamilton's formalism, double pendulum...

A: In advanced physics circles, "classical mechanics" always means something very specific, and it doesn't mean "Newtonian." Classical means not quantum. Newton's theory of gravity is just one example of a classical theory. Einstein's general relativity is also a classical theory. Any theory which says gravitation is due to the exchange of gravitons would be a quantum theory. In this usage of the term, all theories are either classical or quantum. The quantum theories are the more fundamental ones, and the classical theories are in some sense approximations of them.

A: Generally speaking, the term "classical physics" means "the physics laid down before a particular, more 'advanced', form of physics is considered". It signifies a conceptual change of some form from the preceding physics in terms of its basic assumptions.
For example, in the transition from Newtonian to relativistic mechanics, the relevant conceptual change is that information propagation speed is no longer unlimited ($c < \infty$). From Newtonian to quantum mechanics, that information content is no longer unlimited ($\hbar > 0$). Hence with respect to either one, Newtonian mechanics is "classical mechanics". But then when you get to relativistic quantum field theory (RQFT), where both of these conceptual changes are incorporated, both Newtonian and non-quantum special/general relativity become "classical mechanics"! And finally, if and when we get to quantum gravity, then all preceding physics will be "classical" in that context.
That said, you are not wrong to think that the term can also have more than one meaning, and so if "classical mechanics" or "physics" is referred to generally as a subdiscipline in physics as opposed to being used in a more specialized context, then yes, it means Newtonian mechanics and related theories that operate with the same background conceptual framework, such as continuum mechanics (fluid and solid statics and dynamics), and relativistic, quantum, RQFT and QG physics all belong to so-called "modern physics".

A: Newtonian mechanics is valid for single-particle systems but classical mechanics is valid for both single as well as n-particle systems.
Newtonian mechanics is the part of classical mechanics


text:
Q: DropDown menu with QtQuickControls2 on Qt application on qt quick controls 2, how can I configure a button Item with a dropdown menu of others buttons. When the user click on this button is triggered onClicked signal and under the button should be open a dropdown menu with other buttons. I have try with ButtonGroup but I don't know if this is the best practice. There is some Controls2 item to be use? Thanks in advice
Best Regards
Daniele

A: There is Menu  from QtQuick.Controls 2.0 that can do what you want.
Example taken from the documentation :

Button {
    id: fileButton
    text: "File"
    onClicked: menu.open()

    Menu {
        id: menu
        y: fileButton.height

        MenuItem {
            text: "New..."
        }
        MenuItem {
            text: "Open..."
        }
        MenuItem {
            text: "Save"
        }
    }
}


text:
Q: R - A loop comparing elements in common between two hierarchical lists I have been trying, for some time, to build a matrix populated by the counts of elements in common between two herarchical lists.
Here is some dummy data:
site<-c('A','A','A','A','A','A','A','A','A','B','B','B','B','B','B')
group<-c('A1','A1','A2','A2','A2','A3','A3','A3','A3',
'B1','B1','B2','B2','B2','B2')
element<-c("red","orange","blue","black","white", "black","cream","yellow","purple","red","orange","blue","white","gray","salmon")
d<-cbind(site,group,element)

I created a list structure, assuming it would be procedural due to the different number os elements in each list. Also, since I don´t want every possible comparison between groups, but only between sites.
#first level list - by site
sitelist<-split(nodmod, list(nodmod$site),drop = TRUE)
#list by group
nestedlist <- lapply(sitelist, function(x) split(x, x[['mod']], drop = TRUE))

My intention is to create a table, or matrix with the number of element in common between groups from the two sites (my original data has additional sites). Like such:
    A1  A2  A3
B1  2   0   0
B2  0   2   0

The nested nature of this problem is challenging to me. I am not as familiar with lists, as I´ve solved problems mostly using dataframes. My attempt boiled down to this. I felt it got close, but have many shortcomings with the correct syntax for loops.
t <- outer(1:length(d$A),
         1:length(d$B),
         FUN=function(i,j){
           sapply(1:length(i),
                  FUN=function(x)
                    length(intersect(d$A[[i]]$element, d$B[[j]]$element)) )
         })

Any help would be much appreciated. Apologies if a similar problem has been solved. I have scoured the internet, but have not found it, or did not comprehend the solution to make it transferable to mine.

A: Consider matrix multiplication x %*% y (see ?matmult) by creating a helper matrix of unique element values by unique group values assigning ones in each corresponding cell. Then run the matrix multiplication as the transpose with itself, followed by subset of rows and columns:
# EMPTY MATRIX
helper_mat <- matrix(0, nrow=length(unique(element)), ncol=length(unique(group)),
                     dimnames=list(unique(element), unique(group)))

# ASSIGN 1's AT SELECT LOCATIONS
for(i in seq_along(site)) {
  helper_mat[element[i], group[i]] <- 1
}

helper_mat
#        A1 A2 A3 B1 B2
# red     1  0  0  1  0
# orange  1  0  0  1  0
# blue    0  1  0  0  1
# black   0  1  1  0  0
# white   0  1  0  0  1
# cream   0  0  1  0  0
# yellow  0  0  1  0  0
# purple  0  0  1  0  0
# gray    0  0  0  0  1
# salmon  0  0  0  0  1

# MATRIX MULTIPLICATION WITH SUBSET
final_mat <- t(helper_mat) %*% helper_mat
final_mat <- final_mat[grep("B", rownames(final_mat)), grep("A", colnames(final_mat))]

final_mat
#    A1 A2 A3
# B1  2  0  0
# B2  0  2  0

Even shorter version thanks to @Lamia:
helper_mat <- table(element, group)

final_mat <- t(helper_mat) %*% helper_mat # ALTERNATIVELY: crossprod(helper_mat)

final_mat <- final_mat[grep("B", rownames(final_mat)), grep("A", colnames(final_mat))]

final_mat
#      group
# group A1 A2 A3
#    B1  2  0  0
#    B2  0  2  0

A: # example dataset
site<-c('A','A','A','A','A','A','A','A','A','B','B','B','B','B','B')
group<-c('A1','A1','A2','A2','A2','A3','A3','A3','A3',
         'B1','B1','B2','B2','B2','B2')
element<-c("red","orange","blue","black","white", "black","cream","yellow","purple","red","orange","blue","white","gray","salmon")
d<-cbind(site,group,element)

library(tidyverse)

# save as dataframe
d = data.frame(d)

expand.grid(groupA = unique(d$group[d$site=="A"]),
            groupB = unique(d$group[d$site=="B"])) %>%               # get all combinations of A and B columns
  rowwise() %>%                                                      # for each row
  mutate(counts = length(intersect(d$element[d$group==groupA],
                                   d$element[d$group==groupB]))) %>% # count common elements
  spread(groupA, counts) %>%                                         # reshape data
  data.frame() %>%
  column_to_rownames("groupB")

#    A1 A2 A3
# B1  2  0  0
# B2  0  2  0

Instead of rowwise you can use a vectorised function that will be (automatically) applied to each row, like this:
# create a function and vectorise it
CountCommonElements = function(x, y) length(intersect(d$element[d$group==x], d$element[d$group==y]))
CountCommonElements = Vectorize(CountCommonElements)

expand.grid(groupA = unique(d$group[d$site=="A"]),
            groupB = unique(d$group[d$site=="B"])) %>%
  mutate(counts = CountCommonElements(groupA, groupB)) %>%
  spread(groupA, counts) %>%
  data.frame() %>%
  column_to_rownames("groupB")

#    A1 A2 A3
# B1  2  0  0
# B2  0  2  0

A: A similar approach to @Parfait's using matrix multiplication. You may need to play around with the data generation to extend it to your application:
site<-c('A','A','A','A','A','A','A','A','A','B','B','B','B','B','B')
group<-c('A1','A1','A2','A2','A2','A3','A3','A3','A3',
         'B1','B1','B2','B2','B2','B2')
element<-c("red","orange","blue","black","white", "black","cream","yellow","purple","red","orange","blue","white","gray","salmon")

d<-data.frame(group, el = as.factor(element), stringsAsFactors = FALSE)

As <- d[group %in% paste0("A", 1:3), ]
Bs <- d[group %in% paste0("B", 1:2), ]

A_mat <- as.matrix(table(As))
B_mat <- as.matrix(table(Bs))

Results:
> A_mat
         el
group black blue cream gray orange purple red salmon white yellow
   A1     0    0     0    0      1      0   1      0     0      0
   A2     1    1     0    0      0      0   0      0     1      0
   A3     1    0     1    0      0      1   0      0     0      1

> B_mat
         el
group black blue cream gray orange purple red salmon white yellow
   B1     0    0     0    0      1      0   1      0     0      0
   B2     0    1     0    1      0      0   0      1     1      0

> B_mat %*% t(A_mat)
     group
group A1 A2 A3
   B1  2  0  0
   B2  0  2  0


text:
Q: How to pass `directory` arg to Python 3 `http.server`? So this works fine -
$ python3 -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

And I can see that http.server takes a directory argument -
https://github.com/python/cpython/blob/master/Lib/http/server.py
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    {...}
    parser.add_argument('--directory', '-d', default=os.getcwd(),
                        help='Specify alternative directory '
                        '[default:current directory]')
    {...}

But I can't find any kind of syntax that will accept that directory argument -
$ python3 -m http.server -d site 8000
usage: server.py [-h] [--cgi] [--bind ADDRESS] [port]
server.py: error: argument port: invalid int value: 'site'
$ python3 -m http.server 8000 -d site
usage: server.py [-h] [--cgi] [--bind ADDRESS] [port]
server.py: error: unrecognized arguments: -d site
$ python3 -m http.server 8000 --directory site
usage: server.py [-h] [--cgi] [--bind ADDRESS] [port]
server.py: error: unrecognized arguments: --directory site

What am I doing wrong ?

A: I suspect it's a problem with your Python version. Here's the same command on 3.7.4:
▶ python3 -m http.server -h
usage: server.py [-h] [--cgi] [--bind ADDRESS] [--directory DIRECTORY] [port]

positional arguments:
  port                  Specify alternate port [default: 8000]

optional arguments:
  -h, --help            show this help message and exit
  --cgi                 Run as CGI Server
  --bind ADDRESS, -b ADDRESS
                        Specify alternate bind address [default: all
                        interfaces]
  --directory DIRECTORY, -d DIRECTORY
                        Specify alternative directory [default:current
                        directory]

~
▶ python3 --version
Python 3.7.4

The directory argument is only added in version 3.7 according to the docs:

New in version 3.7: --directory specify alternate directory


text:
Q: Android Studio Firebase How To Insert A Long List In Firebase Realtime Database? I am trying to insert a long list of products in real time database using the following code. The list has about 90 products, but when I try to add them I am getting a few products less, like 2-3 products are missing. Is there any way to insert all products? I believe I am getting less products because I am using timestamp.
Here is my code

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
String[] productTitles = {length of array is 93};
String[] productQuantities = {length of array is 93};
String[] productIcons = {length of array is 93};
String[] productCategories = {length of array is 93};

        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("discountAvailable","false");
        hashMap.put("discountNote","");
        hashMap.put("discountPrice","0");
        hashMap.put("isAvailable","Available");
        hashMap.put("isApproved","Approved");
        hashMap.put("productType","Default");
        hashMap.put("originalPrice","");
        hashMap.put("productDescription", "");
        hashMap.put("uid",""+firebaseAuth.getUid());
        String timestamp;
        for (int i = 0; i < productTitles.length; i++) {
            timestamp = "" + System.currentTimeMillis()+1;
            hashMap.put("timestamp", "" + timestamp);
            hashMap.put("productTitle", "" + productTitles[i]);
            hashMap.put("productCategory", "" + productCategories[i]);
            hashMap.put("productQuantity","" + productQuantities[i]);
            hashMap.put("productIcon",""+productIcons[i]);
            hashMap.put("productId",""+timestamp);
            reference.child(firebaseAuth.getUid()).child("Products").child(timestamp).setValue(hashMap);

        }

A: You can replaced the timestap with a firebase key.
for (int i = 0; i < productTitles.length; i++) {
        timestamp = "" + System.currentTimeMillis()+1;
        hashMap.put("timestamp", "" + timestamp);
        hashMap.put("productTitle", "" + productTitles[i]);
        hashMap.put("productCategory", "" + productCategories[i]);
        hashMap.put("productQuantity","" + productQuantities[i]);
        hashMap.put("productIcon",""+productIcons[i]);
        hashMap.put("productId",""+timestamp);
        String uniqueID = reference.push().getKey();
        reference.child(firebaseAuth.getUid()).child("Products")
        .child(uniqueID).setValue(hashMap);

    }

I am not sure if this works or not.


text:
Q: How to append dictionary with objects to an array using FIrebase I'm working with firebase i'm able to get as response a dictionary that look's like this:
▿ 0 : 2 elements
    - key : "maskForHair"
    ▿ value : 3 elements
      ▿ 0 : 2 elements
        - key : id
        - value : 1
      ▿ 1 : 2 elements
        - key : name
        - value : Hair Mask
      ▿ 2 : 2 elements
        - key : note
        - value : asd
  ▿ 1 : 2 elements
    - key : "hairShampo"
    ▿ value : 3 elements
      ▿ 0 : 2 elements
        - key : id
        - value : 0
      ▿ 1 : 2 elements
        - key : name
        - value : hairShampo
      ▿ 2 : 2 elements
        - key : note
        - value : asd

now i'm trying to populate a tableView using this dictionary, But i cant find a way to append this dict to an array, Any ideas?
This is how my getCategories function looks like:
func getCategories(){

    dbHandle = dbRefernce?.child("categories").observe(.value, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String : Any]{

            print(dictionary)

            let category = Categories(dictionary: dictionary)
            self.categoriesArr.append(category)

            DispatchQueue.main.async {
                self.categoriesTableView.reloadData()
            }
        }
    })
}

And here how my Categories class looks like:
import Foundation
import UIKit

class Categories: NSObject {

    var name : String? = nil
    var id : Int? = nil
    var note : String? = nil

    init (dictionary: [String: Any]) {
        super.init()
        name = dictionary["name"] as? String
        id = dictionary["id"] as? Int
        note = dictionary["note"] as? String
    }

}

A: I would start by renaming you model into something singular like HairCategory.
You need to iterate the children of the snapshot that you receive from the database. Each child should be a [String : Any] dictionary that could then be turned into a HairCategory.
Something like this:
let children = snapshot.children.compactMap { $0 as? DataSnapshot }
let cateroryDictionaries = children.compactMap { $0.value as? [String:Any] }
let categories = cateroryDictionaries.map { dict -> HairCategory in
    return HairCategory.init(dictionary: dict)
}

Then categories is of type: [HairCategory]. If also you make your self.categoriesArr of type [HairCategory] you can append the newly fetched categories :)
Edit:
I can also recommend taking a look at this library: CodableFirebase
. It makes conversion from DataSnapshot to you Models and the other way, really easy..
Edit
Just to clarify... You can't "append dictionary ... to an array", you need to convert the dictionary to an array, and then you can append that array to another array of the same type :)

A: This is how i worked it out:
 for index in 1...self.numberOfProducts{

        dbHandle = dbRefernce?.child("categories").child("\(index)").observe(.value, with: { (snapshot) in
            guard let value = snapshot.value as? [String: Any] else { return }
            guard let name = value["name"] as? String,
                let imageURL = value["imageURL"] as? String,
                let desc = value["description"] as? String,
                let price  = value["price"] as? Int,
                let id = value["subCategoryID"] as? Int
                else {return}

            let category = Product(name: name, imageURL: imageURL, description: desc, price: price,subCategoryID: id)

            self.productsArr.append(category)
            self.tblProducts.reloadData()
        })
    }

Just created an object and then append it to the array,
you can do this in a loop


text:
Q: EMgucv save multiple face detected from webcam I have window application which will detect multiple face and capture the face and save as image.  I use the EMGU CV to do the face detection,  I learn from the sample code and tutorial.  When it need to capture the face as a trained dataset, it only able to store one face although it detected 2 faces.  I try to modify the code but it seem like not work as expected.  Below is the code:
 gray = grabber.QueryGrayFrame().Resize(320, 240,
 Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
            face,
            1.2,
            10,
            Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
            new Size(20, 20));

foreach (MCvAvgComp f in facesDetected[0])
{
    TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();

    TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
    trainingImages.Add(TrainedFace);

    for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
    {
        trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/TrainedFaces/face" + i + ".bmp");

    }
}

The foreach loop will loop twice when 2 faces detected, but the face save is the same.  Any idea what's go wrong?

A: please try the following way
For Each of the faces detected, you will have to add it to training images
and you need to loop it out side of the for each loop
gray = grabber.QueryGrayFrame().Resize(320, 240,
Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);

MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
        face,
        1.2,
        10,
        Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
        new Size(20, 20));

foreach (MCvAvgComp f in facesDetected[0])
{
TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();

TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
trainingImages.Add(TrainedFace);
}

 for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
    trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/TrainedFaces/face" + i + ".bmp");

 }

I think the for loop could be changed to
int i=1;
foreach(TrainedFace Tface in trainingImages)
  {
   Tface.Save(Application.StartupPath + "/TrainedFaces/face" + i + ".bmp")
    i++;
   }

Please try this way,it might work ..


text:
Q: JS Promise: Return mapped data I have a function "mapTranslations" which gets data from a server and then maps it. At the moment I use a callback to return the data. I wan't to use promises though - I don't have a approach on how I could return the mapped data and not the data from the "somePromiseReturningFunction".

function mapTranslations(callback){
    somePromiseReturningFunction(...).then(function (languageData) {
        var translations = {};
        languageData.d.results.forEach(function (obj) {
            translations[obj.key] = obj[browserLang];
        });
        callback(translations);
    });
}

Using it like this:
mapTranslations(function(translations){
    console.log(translations);
});

Goal:
mapTranslations().then(function(translations){
    console.log(translations) //Example, wouldn't be an anonymous function
});

A: I'd suggest you return the original promise and return a value from your .then() handler like this (more explanation below):
function mapTranslations(){
    return somePromiseReturningFunction(...).then(function (languageData) {
        var translations = {};
        languageData.d.results.forEach(function (obj) {
            translations[obj.key] = obj[browserLang];
        });
        return translations;
    });
}

// usage
mapTranslations().then(function(results) {
     // access results here
}).catch(function(err) {
     // handle error here
});

When you return a value from a .then() handler that becomes the resolved value of the returned promise and the caller will see that value.  Thus you can modify the returned value from the original promise and return it in your own .then() handler.
In addition, you really don't want to ever wrap a promise in a callback.  That just throws away all the advantages of promises (ability to chain, automatic async error propagation, ability to manage/coordinate multiple async operations, interoperability with other async operations, etc...).  Instead, just return the promise and let the caller use .then() on the returned promise to get access to the data or errors.  FYI, in your proposed callback code, you were silently eating any errors from somePromiseReturningFunction().  If it rejected the promise it returns, you had no handler so the caller would never know.  If you just return the promise from your function, that error handling comes for free.

FYI, you may want to use .reduce() instead of .forEach() as it aligns a little better with what you're doing:
function mapTranslations(){
    return somePromiseReturningFunction(...).then(function (languageData) {
        return languageData.d.results.reduce(function(translations, obj) {
            translations[obj.key] = obj[browserLang];
            return translations;
        }, {});
    });
}

A: Something like this should do, the then can return a value and it returns a new promise you can use.
function mapTranslations(){

    return somePromiseReturningFunction(...).then(function (languageData) {
        var translations = {};
        languageData.d.results.forEach(function (obj) {
            translations[obj.key] = obj[browserLang];
        });
        return translations;
    });

}

mapTranslations().then( .... ).catch( ... );


text:
Q: MS Word: fix for old version of header displayed on some clients? I have an MS Word document that was first created a long time ago (like 20 years). Over the subsequent years the document has been altered and now has the company's current branding in its header. However, when viewed with certain clients, e.g., the iPhone Outlook app, the document is displayed with a previous version of the headers with outdated company branding.
Is there some way I can view and remove this older version of the header? When I open the document in the version of Word that's on my Win 10 laptop (MS365 Enterprise v2211), I see only the current correct header.
(I'm sure that I can solve the problem in this specific instance by creating a new document and copy-pasting or something, but I'm looking for a solution that's repeatable and understandable by non-technical staff so that they can find and correct the same issue in other documents of the same vintage [before the company president stumbles on them, which is how the problem at hand was discovered].)

A: Using a Visual Studio plugin called OOXML Viewer I opened the doc. There are multiple headers, including one with an image called "US Logo 2009", which is my troublemaker.
Next, I renamed the .docx file as a .zip and opened it with 7-zip where I deleted the old header. Then I changed the name back to a .docx and viewed it with the iPhone Outlook app. The document is now displayed with the correct current header.
This isn't a real answer to my initial question because none of the above is replicable by non-tech staff, but I'm confident that I can at least write a little tool to comb through the corp doc library and at least identify files that have the issue.


text:
Q: Short code: map, filter, lambda I use Python 3.4 and I have this code:
result = []
    for i in r['resp']:
        for id in self.all_dicts:
            if i == id['id']:
                result.append(id)

Its very long, so I want to short:
result = list(map(filter(lambda x: x == i,self.all_dicts),r['resp']))

But I have an error:
TypeError: 'filter' object is not callable

How to fix that? Thanks

A: I think you want:
result = [id for id in self.dicts if id['id'] in r['resp']]


text:
Q: Traversing back to the previous node using XPath in asp.net I have asked a question about Traversing back to parent node in xpath
i got expected reply, however i have one more doubt with the further development. With below HTML:

BROADCASTING

STATION BREAK

Labor pains, hunger pangs

Wake-up call for Dream Team

News crew turns rescuer

Chopper safety had been challenged

Nielsen adds Dayton..

Mondale watch

Those 70s clearances

Oscar goes to ABC

Hearst-Argyle gives a green light

Finding Geena Davis

Syndication Wrap-up

CBS TV news pioneer dies at 86

New York anchor remembered

News sharing in West Virginia

News dropping in Orlando

Null

GET WITH THE PROGRAM

PEOPLE'S CHOICE

Syndication as branding

with the help of @Alex now i can get all the sections and subsections. then i wanted the articles inside the subsection, i tried that myself and received expected output, however my problem is now after the
 tag we have individual
 tag which contains the information of the article inside anchor tag, now as the class="circle" tag is itself the individual node (not inside the class="subsection" node), i cannot just gets article inside the particular subsection, it fetches all the articles in first subsection and then, in second sub-section it also fetches the articles from the third sub-section, it only works fine in the last sub-section as it does not have any more sub-sections.
Can anyone tell me how shall i limit the articles within the particular sub-section, i mean when it gets the class="subsection" tag, it should stop fetching for articles further for that subsection, and start fetching for another sub-section.

A: You could use something like:
//ul/ul[preceding::li[@class='section' and .=\"BROADCASTING\"]]/li[@class='subsection' and .=\"\"]/following::li[@class='circle' and following::li[@class='subsection' and .=\"Null\"]]/a
to get all the anchors between

 and
Null
. To get links between
Null
 and
PEOPLE'S CHOICE
 you need to replace necessary values here: li[@class='subsection' and .=\"{...}\".
To get anchors under the last subsection, the next expression will be enough:
//ul/ul[preceding::li[@class='section' and .=\"BROADCASTING\"]]/li[@class='subsection' and .=\"PEOPLE'S CHOICE\"]/following::li[@class='circle']/a".
I hope you've caught the idea.


text:
Q: how to access method of parent class with instance of child class in c# I have this code
class parent
{
  public void sleep()
   {
     // Some Logic
   }
}

class Child : Parent
{
  public void sleep()
  {
    // some logic
  }
}

class Implement
{
  Child ch = new Child();
  ch.sleep();
}

But now I want to access sleep() method of parent class by using instance of child class which is created already.

A: You can cast your object to parent type.
Child ch = new Child();
var parent = (Parent)ch;
parent.sleep();

A: You just need to cast the created Child object to Parent:
((Parent)ch).sleep();

As @Thorsten commented below, this works because Parent.sleep is a non-virtual method and it is not overridden in the Child class. If it were overriden, then there would be no way for you to call the Parent.sleep implementation using ch. (For virtual methods, the method that is invoked is the "most derived implementation", that is the most derived implementation of this method within the class hierarchy with the override keyword.)

A: To access parent member you must cast the object.
public class A
{
   public virtual void One();
   public void Two();
}

public class B : A
{
   public override void One();
   public new void Two();
}

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B

Source: new keyword in method signature
Suggestion: you're hidding an inherited member. You should use "new" keyword like this:
    class Parent
    {
        public void MethodA()
        {
            Console.WriteLine("Parent");
        }
    }

    class Child : Parent
    {
        public new void MethodA()
        {
            Console.WriteLine("Child");
        }
    }

A: You could create a new method on Child called ParentSleep like so:
class Child : Parent
{
  public void sleep()
  {
    // some logic
  }

  public void ParentSleep()
  {
     base.sleep();
  }
}

Then call it like so:
Child ch = new Child();
ch.ParentSleep();

A: if you want to implement this with interface as well as Parent Class you can do something like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExplicitInterfaceImplementation
{
    class Program
    {
        static void Main(string[] args)
        {
            SampleClass sc = new SampleClass();
            var mc = (MainSampleClass)sc;
            IControl ctrl = (IControl)sc;
            ISurface srfc = (ISurface)sc;

            mc.Paint();
            sc.Paint();
            ctrl.Paint();
            srfc.Paint();
            Console.ReadKey();
        }
    }

    /// <summary>
    /// Interface 1
    /// </summary>
    interface IControl
    {
        void Paint();
    }

    /// <summary>
    /// Interface 2
    /// </summary>
    interface ISurface
    {
        void Paint();
    }

    /// <summary>
    /// Parent/Main Class
    /// </summary>
    public class MainSampleClass
    {
        /// <summary>
        /// Parent class Paint Method.
        /// </summary>
        public void Paint()
        {
            Console.WriteLine("Paint method in - Parent MainSampleClass");
        }
    }

    /// <summary>
    /// SampleClass is the Child class inherited from Parent/Main Class and two interfaces
    /// Parent/Main class having a Paint() method and two interfaces having
    /// Paint() method - each of them having same name but they are not same(different from each other).
    /// </summary>
    public class SampleClass : MainSampleClass,IControl, ISurface
    {
        /// <summary>
        /// new method(Paint()) for Child class, separate from parent class(Paint() method)
        /// </summary>
        public new void Paint()
        {
            Console.WriteLine("Paint method in - Child SampleClass");
        }

        /// <summary>
        /// Implementing IControl.Paint() method.
        /// </summary>
        void IControl.Paint()
        {
            System.Console.WriteLine("Paint method in - IControl Interface");
        }

        /// <summary>
        /// Implementing ISurface.Paint() method.
        /// </summary>
        void ISurface.Paint()
        {
            System.Console.WriteLine("Paint method in - ISurface Interface");
        }
    }
}

A: class Implement
{
    Parent parentChild = new Child();
    parentChild.sleep();
}


text:
Q: openstreetmap response - importance and place_rank fields What is the meaning of the 'importance' and 'place_rank' fields in a openstreetmap response ? I can't find it anywhere in the documentation :/
For example the response of this url:
http://nominatim.openstreetmap.org/search?q=135+pilkington+avenue,+birmingham&format=xml&polygon=1&addressdetails=1

is:
<place place_id="62311100" osm_type="way" osm_id="90394480" place_rank="30" ...OMISSIS... importance="0.701">
In the above response I have removed all the XML part I'm not interested in.

A: As far as I know:

*

*The importance is used for ordering search results according to their relevance. The importance value is calculated/estimated using various attributes including the place's popularity on Wikipedia and its rank.

*The rank is based on a rather complex algorithm taking the place type and various other attributes into account. For example it seems checks whether this object is a village, a city, a country, a continent, a highway, a lake and similar other properties.
Unfortunately these attributes lack proper documentation. So all you can do is try to look at Nominatim's source code if you need more detailed information. From there I tried to extract the information mentioned above.


text:
Q: Python regex - extract name before phone number I have a raw text object with the following:
Bryar Pitts
5543 Aliquet St.
Fort Dodge GA 20783
(717) 450-4729
Rahim Henderson
5037 Diam Rd.
Daly City Ohio 90255
(453) 391-4650
Sheila Mcintosh
P.O. Box 360 4407 Et Rd.
Santa Monica FL 30309
(746) 679-2470

I could retrieve all the phone numbers with the function below.
data=re.findall(r'\(\d{3}\)\s\d{3}-\d{4}',text)

Next thing is how do I go about extracting the names Bryar Pitts, Rahim Henderson and Sheila Mcintosh? Do I have to specify new lines and objects before a phone number is reached?
Thanks.

A: Not sure if this is the correct approach. But might help.
import re
s = """Bryar Pitts
5543 Aliquet St.
Fort Dodge GA 20783
(717) 450-4729
Rahim Henderson
5037 Diam Rd.
Daly City Ohio 90255
(453) 391-4650"""

print(re.findall("[a-zA-Z\s]+(?=\s+\d{4,4})", s, flags=re.MULTILINE)[::2])
#or
print(re.findall("[a-zA-Z\s]+(?=\n)", s, flags=re.MULTILINE))

Output:
['Bryar Pitts', '\nRahim Henderson']
['Bryar Pitts', '\nRahim Henderson']

A: You might use capturing groups if you want to match the name and the phonenumber in the 1st and 4th row (Assuming that this order does not change)
([a-zA-Z ]+)\n(?:.*\n){2}(\(\d{3}\)\s\d{3}-\d{4})
Details

*

*([a-zA-Z ]+)\n Capture in group 1 lowercase or uppercase  or a whitespace using a character class followed by a newline

*(?:.*\n){2} Match 2 whole lines

*(\(\d{3}\)\s\d{3}-\d{4}) Capture in group 2 your phonenumber regex

Demo

A: https://regexper.com
I find this helpful when working with RegEx.
I think it depends on whether you work on your text char by char, then you might have to do that.
If you go line by line, the name lines should not have any numbers in them, so you could work with that, maybe.
It also depends on the data that you work with and how sure you are that it is free of errors.
If it is always 4 lines per person, you could check line by line and use RegEx to also make sure it matches your expectation so that if you find a number in a name you throw an exception or at least log it somewhere.
Hope this helps, good luck!


text:
Q: GWT CK EDITOR - Rendering issue I am using gwt-ckeditor in my application. I am using GWT 2.5 and I have embedded CKEDITOR in GWT. I have some fields in form containing CKEditor as well. When I navigate from one form to another, it does not sustain its value. I dont want to save it. But I want to sustain it atleast for my validations to get complete. How can I acheive this functionality ? Please let me know. As Whenever it is getting detached it is losing its values.

A: Yeah I was also facing the same issue. CKeditor is actually extended from IFrame and that is why when it is detached from the form or widget, it will loose all the information. To sustain its value , you have to manually code it.
private String ckValue ;

CkEditor ckeditor = new CkEditor(new CkConfig());
ckeditor.addAttachHandler(new AttachHandler(){
       public void onAttach(Event value){
             setCkValue(value);
       }
});

public void setCkValue(String ckValue){
      this.ckValue = ckValue;
}

public String getCkValue(){
      return ckValue;
}


text:
Q: How to get colors from dendrogram in MATLAB? I have generated the dendrogram of some examplary data and I want to get colors assigned to my observations.
Here below is the example on how to match colors from dendrogram to observations.
clear; close all; clc;

%% Generate example data
rng('default') % For reproducibility
N = 10; % number of observations
X = rand(N,3);

%% Get linkage
tree = linkage(X, 'average');

%% Get desired number of clusters
nClusters   = 2;
cutoff      = median([tree(end-nClusters+1,3) tree(end-nClusters+2, 3)]);

%% plot tree
figure
h = dendrogram(tree, 'ColorThreshold', cutoff); % h contains Line objects with the 'Color' property

A: Here what you need to add to your code:
%% get colors

linesColor = cell2mat(get(h,'Color')); % get lines color;
colorList = unique(linesColor, 'rows');

% NOTE that each row is single line corresponding to the same row in tree
% variable. I use that property below.
X_color     = zeros(N,3);
X_cluster   = zeros(N,1);
for iLeaf = 1:N
    [iRow, ~] = find(tree==iLeaf);
    color = linesColor(iRow,:); % !

    % assign color to each observation
    X_color(iLeaf,:) = color;
    % assign cluster number to each observation
    X_cluster(iLeaf,:) = find(ismember(colorList, color, 'rows'));
end


text:
Q: WP7 (windows phone 7) HttpWebRequest losing POST data I'm sending a lot of POST data (over 5000 chars) and it seems that WP7 HttpWebRequest is losing some of the content in the process...
The data is a png converted to a byte array and after to a base64 string.
If my data is 4941 characters long, it will send only 1448 chars, the content length (verified with wireshark) of the request is fine (Content-Length: 4991).
How i send the data :
void SendPost()
{
    // Create the web request object
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    // Start the request
    webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);

}

void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
    // End the stream request operation
    Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);

    // Create the post data
    // Demo POST data (length = 3762)
    string postData = "data=iVBORw0KGgoAAAANSUhEUgAAAFoAAAASCAYAAADbo8kDAAAKyElEQVR4nG2YB3TNVxzHm5eEDHuF2GJUjVRqb2okiMRWqtG0KKI4aq8mUQQ5FRWrhNi1Z6lWazSrRm1iVBDESiIxEkH6Pu/069zzTt857/zv//5/e9/73tu3bx3s/2/evLHk5eU5vX792pG19vT91atXzlo/f/7cTWtweL58+dLFpGWPb/+HT25ubgHzXbTs8SSbKQvv7IOnPf56t8fn+eLFC1d4Sn6TD+ucnJyCpjw87WU06UoO7UtOyWZ5779ffn6+g5U4BrI4ODjkOzo6Wr9a3rLmO/tWYjCysC88Z2fnPPZZWwk68ixYsGBudnZ2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GcYcUETymNEVqe5LsMDp4Gdwll3sDpEGJeVbJnRrkizbxatTeGIg85dKGliNI1KU/JaO8gXcVqXyVEcsiYkkcThmZ98DViSm+VJt7/BbjvID507t6TAAAAAElFTkSuQmCC";

    //Actual code used
    /*for (int i = 0; i < paramNames.Count; i++)
    {
        // Parameter seperator
        if (i > 0)
        {
            postData += "&";
        }

         // Parameter data
         postData += paramNames[i] + "=" + paramValues[i];
    }*/

    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    // Add the post data to the web request
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();

    // Start the web request
    webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}

void GetResponseCallback(IAsyncResult asynchronousResult)
{

    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
        HttpWebResponse response;

        // End the get response operation
        response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(streamResponse);
        Response = streamReader.ReadToEnd();
        streamResponse.Close();
        streamReader.Close();
        response.Close();

    }
    catch (WebException e)
    {
            // Error treatment
            // ...
    }
}

How can I send my data entirely ?
Thank you !

A: In RunSat I send plenty more bytes than that using the code below - its similar to the code you've shown and it works fine (although I admit I mainly test on a real device)
            Stream requestStream = CurrentWebRequest.EndGetRequestStream(async);
            byte[] encodedBytes = Encoding.UTF8.GetBytes(payload);
            requestStream.Write(encodedBytes, 0, encodedBytes.Length);
            requestStream.Flush();
            requestStream.Close();

Depending on how expert you are with WireShark, it might not be telling you the whole truth - when you're looking at wireshark you will see the TCP level packets which (for ip4) commonly have 1448 bytes of payload - http://en.wikipedia.org/wiki/TCP_segmentation_offload - and I find it easy to miss the continuation packets. (I'm not a wireshark user, but have used ethereal a bit)

Update: I've run this code below
It works fine - you can see the upload at http://posttestserver.com/data/2011/05/12/03.29.331923823079
I recommend you stop messing about at the ethernet and TCP/IP packet levels with WireShark and take a look at your webservice.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace DemoProject
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            SendPost();
        }

        void SendPost()
        {
            var url = "http://posttestserver.com/post.php";

            // Create the web request object
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";

            // Start the request
            webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
        }

        void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the stream request operation
            Stream postStream = webRequest.EndGetRequestStream(asynchronousResult);

            // Create the post data
            // Demo POST data
            string postData = "data=iVBORw0KGgoAAAANSUhEUgAAAFoAAAASCAYAAADbo8kDAAAKyElEQVR4nG2YB3TNVxzHm5eEDHuF2GJUjVRqb2okiMRWqtG0KKI4aq8mUQQ5FRWrhNi1Z6lWazSrRm1iVBDESiIxEkH6Pu/069zzTt857/zv//5/e9/73tu3bx3s/2/evLHk5eU5vX792pG19vT91atXzlo/f/7cTWtweL58+dLFpGWPb/+HT25ubgHzXbTs8SSbKQvv7IOnPf56t8fn+eLFC1d4Sn6TD+ucnJyCpjw87WU06UoO7UtOyWZ5779ffn6+g5U4BrI4ODjkOzo6Wr9a3rLmO/tWYjCysC88Z2fnPPZZWwk68ixYsGBudnZ2YdbgWw3vKjpWxs5WgVHCIrqio7VVWCf428smeiZ/Jyen18BqHxmAZ593aCEf+/x5B8/FxSUHnq6uri/FE9mQAXyTh2hqj3dzLRllM8nJ+zvZBMQf5gKEMQYRc/YLFCjwinfWPIGRouDwXQYuVKjQMwmq7xIGR4gPe3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

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamReader = new StreamReader(streamResponse);
                var Response = streamReader.ReadToEnd();
                streamResponse.Close();
                streamReader.Close();
                response.Close();

            }
            catch (WebException e)
            {
                // Error treatment
                // ...
            }
        }
    }
}


text:
Q: Inductive proof, algebra step I have to prove by induction that
$$1^2+2^2+3^2+ \cdot \cdot \cdot + n^2 = {n(n+1)(2n+1)\over 6}$$
Base step: $$1^2 = {1(1+1)(2\bullet1 +1)\over 6}$$
$$1^2= {6\over 6} = 1$$
Then I use this  $$1^2+2^2+3^2+ \cdot \cdot \cdot + n^2 +(n+1)^2 = {n(n+1)(2n+1)\over 6}+(n+1)^2$$
to show that
 $$1^2+2^2+3^2+ \cdot \cdot \cdot + n^2 + (n+1)^2 = {(n+1)((n+1)+1)(2(n+1)+1)\over 6}$$
$$=$$
$$1^2+2^2+3^2+ \cdot \cdot \cdot + n^2 + (n+1)^2 = {(n+1)(n+2)(2n+3)\over6}$$
I'm stuck with the algebra part, could someone go through the steps of how
$${n(n+1)(2n+1)\over 6}+(n+1)^2 = {(n+1)(n+2)(2n+3)\over 6}$$

A: \begin{align}\frac{n(n+1)(2n+1)}{6}+(n+1)^2 &= \frac{n(n+1)(2n+1)}{6}+\frac{6(n+1)^2}{6}\\
&=\frac{1}{6}\left[(n+1)[n(2n+1)+6(n+1)]\right]\\
&=\frac{1}{6}(n+1)(2n^2+7n+6)\\
&=\frac{1}{6}(n+1)(2n^2+4n+3n+6)\\
&=\frac{1}{6}(n+1)(2n(n+2)+3(n+2))\\
&=\frac{1}{6}(n+1)(n+2)(2n+3)\\
&=\frac{(n+1)((n+1)+1)(2(n+1)+1)}{6}\\
\end{align}

A: $${n(n+1)(2n+1)\over 6}+(n+1)^2 = (n+1){(2n^2+n+6n+6)\over 6}=(n+1){(2n^2+7n+6)\over 6}={(n+1)(n+2)(2n+3)\over 6}$$

A: ${n(n+1)(2n+1)\over 6}+(n+1)^2=\frac{(n+1)}{6}(2n^2+7n+6)=\frac{(n+1)(n+2)(2n+3)}{6}$


text:
Q: Getting an unordered list to wrap around like in the picture here I need to create a section that mimics the pictured mockup below

Because I'm using a content management system, I can only control the CSS of the elements in that section. So, for instance, I can't divide the ul into 2 uls in separate divs (without using some fancy JavaScript hack).
What I need to work with is basically

Off the top of your head, do you know an easy way to achieve the desired behavior?

A: You can accomplish this with a bunch of floating.
.inner-left {
    float: left;
    width: 33.33%; // the first column width
}
.inner-right{
    float: left;
    width: 66.66%; // the container of the next 2 columns
}

Then we make the ul create the next 2 columns, but first you need to reset the ul by removing margin and padding, and then float the li and give them a width of 50%;
.inner-right ul {
    padding: 0;
    margin: 0;
}

.inner-right ul li {
    float: left;
    width: 50%;
}

This should give you 3 evenly spaced columns.

A: Try with this code:
.inner-right ul li {
   display:inline-block;
   width:49%;
}


text:
Q: Issues transforming tuple to denormalized dataframe I have a tuple which is a list of 200 dicts:
eg:
mytuple= ([{'reviewId': '1234', 'userName': 'XXX', 'userImage': 'imagelink', 'content': 'AAA', 'score': 1, 'thumbsUpCount': 1, 'reviewCreatedVersion': '3.31.0', 'at': datetime.datetime(2022, 12, 1, 11, 49, 34), 'replyContent': "replycontent", 'repliedAt': datetime.datetime(2022, 12, 1, 12, 19, 51)},
           {'reviewId': '5678', 'userName': 'S L', 'userImage': 'imagelink2', 'content': "content2", 'score': 1, 'thumbsUpCount': 0, 'reviewCreatedVersion': '3.31.0', 'at': datetime.datetime(2022, 11, 29, 12, 27, 46), 'replyContent': "replycontent2", 'repliedAt': datetime.datetime(2022, 11, 29, 12, 30, 40)}])

Ideally, I'd like to transform this into a dataframe with the following column headers:

reviewId
userName
userImage

1234
XXXX
imagelink

5678
S L
imagelink2

and so on with the column headers as the key and the columns containing the values.
mytuple was initially of size 2, from which I removed the second index and brought it down to just a list of dicts.
I tried different possibilities which include:
df=pd.DataFrame(mytuple)
df=pd.DataFrame.from_dict(mytuple)
df=pd.json_normalize(mytuple)
However, in all these cases, I get a dataframe as below

1
2
3
4

{'reviewId':..}
{'reviewId':..}
{}
{}

I'd like to understand where I'm going wrong. Thanks in advance!


text:
Q: CLLocationManager startUpdatingLocation causing a lag I've noticed that in my app, when I call startUpdatingLocation, my UI locks up briefly while i presume the device gathers the location data. Is this typical and is there any way to limit this? heres what my code looks like
    -(void)getUserLocation {
    if (!locationManager)
    {
        locationManager = [[CLLocationManager alloc]init];
    }

    [locationManager setDelegate:self];
    [locationManager startUpdatingLocation];

}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    self.userCoordinate = newLocation.coordinate;

    NSLog(@"user coordinate in location manager: %f,%f",self.userCoordinate.latitude,self.userCoordinate.longitude);
    [locationManager stopUpdatingLocation];
    locationManager = nil;

    userLocationAvailable = YES;
    [self getDataForScrollView];

}

any ideas? Thanks!

A: That's because you are getting the location in the main thread, whereas the main thread is used to responsible for UI stuff . i.e. user touch events. that's why u feel your app has a bit of lag.
That's quite normal if you do a large task ( e.g. get data from web server) in main thread. You could put a "Loading" spin view to indicate the user instead of make your UI frozen.
Alternatively, you could try to get the location in another thread . I was trying to do this too but i have not succeeded yet. So i am currently doing with the first approach.

A: You may benefit from looking at my use of the location services in the background. Essentially, I set up the location manager in main thread but all the processing on receipt of the location events is done on background thread.
That will allow your main thread to continue without blocking.
See code here TTLocationHandler GitHub Repository


text:
Q: Xcode 7.3 wont attach to simulator to debug So I upgraded to Xcode 7.3.1 and now my Xcode will build, and deploy my apps (yes every app, even a brand new blank one) to the simulator but the app never launches on the simulator and the debugger never attaches, Xcode just hangs and has to be force quit.  I've completely wiped out Xcode and all simulators and re-installed to no avail.  I've scoured Stack Overflow and Google trying every piece of advice and still no luck.  Anyone anywhere have any idea how to solve this issue?  If I downgrade to 7.2.1 I'm able to debug in the simulator just fine.
Let me know if you need more information.
My Apps run just fine on the simulator, and if I try to attach the debugger to a running app it wont and Xcode hangs in the attempt, when attempting to attach this way at least Xcode doesn't have to be force quit.
FYI, I can debug on a device this is only a simulator issue.

A: I had this same issue, and tried fixing my projects and reinstalled Xcode twice before I was able to get Simulator to crash and give me an error report that called out Cylance.  Luckily I have access to administer our Cylance portal, so I was able to work through the issue to narrow down the problem.
Symptoms:

*

*When running an app from Xcode, the Simulator launches but the application does not launch within the Simulator

*Trying to stop the application from within Xcode does not work, and generates no messages

*Trying to re-run the application from within Xcode generates the following message: 'An instance of "APPLICATION NAME" is already running.  Choose "Stop" to terminate and launch a new instance.'  But pressing Stop does nothing.

*Xcode will not quit, and eventually the user must Force Quit to exit Xcode

*Within the OS X console, the following messages are displayed:

6/3/16 7:35:38.000 PM kernel[0]: AMFI: com.apple.dt.ins(pid 2239) - [deny-mmap] main process is a platform binary, but mapped executable file is not: /Library/Application Support/Cylance/Desktop/CyMemDef.dylib
6/3/16 7:35:38.000 PM kernel[0]: AMFI: com.apple.dt.ins(pid 2239) - [deny-mmap] mapped file has team identifier XXXX: /Library/Application Support/Cylance/Desktop/CyMemDef.dylib

Resolution:
The problem is caused by Memory Protection being turned on within the policy assigned to the Mac within the Cylance portal.
To resolve the issue, place the Mac into a zone/policy that does not have Memory Protection turned on.  Auto Quarantine and Protection Settings can be left on.
During my testing, I was not able to come up with a list of exclusions that allowed me to leave Memory Protection on, so I ended up disabling it completely.


text:
Q: New line formatting using xml in python 3 I am trying to write a program which will get information from an xml in the form of questions and answers. When getting the data from the xml below and putting the data into a dictionary I get this
XML:
<data>
    <subject name="Geography">
        <easy>
            <question>What is the capital of England?
                <option1>London</option1>
                <option2>Bristol</option2>
                <answer>1</answer>
            </question>
        </easy>
    </subject>
</data>

Dictionary made:
{'What is the capital of England?\n                ': ['London', 'Bristol', '1']}

Is there any way to eliminate the new line and the white space from within the xml file while being able to keep the same indentation on the file, or must I remove the extra line and whitespace in python?
The code I am currently using to import the data is as follows:
def getQuestions(topic, difficulty, xmlFile):
    tree = et.parse(xmlFile)
    root = tree.getroot()
    questions={}
    for i in root.findall('.//*[@name="'+topic+'"]/'+difficulty+'/question'):
            #print(i.text)
            questions[i.text]=[]
            for j in i:
                questions[i.text].append(j.text)
    return questions

Any help is greatly appreciated


text:
Q: What is the difference between "dnf history rollback" and "dnf history undo"? Let's read the official documentation:

dnf history rollback <transaction-spec>
  Undo all transactions performed after the specified transaction. If it is not possible to undo any transaction due to the current state of RPMDB, do not undo any transaction.

Emphasis is mine. So this command refers to the undo command. Okay, let's read the documentation concerning undo:

dnf history undo <transaction-spec>
  Perform the opposite operation to all operations performed in the specified transaction. If it is not possible to undo any operation due to the current state of RPMDB, do not undo any operation.

It sounds that those two commands do the same things with the exception that the former can undo several transactions, and the later just one.
Is this understanding correct? (I would appreciate answers from first-hand experience, not from the point of view how you interpret the manual, I'm interested in facts, not guesses.)
Context: I need to write a script that runs dnf upgrade -y and then runs some tests and then reverse the dnf changes if the tests fail. I'm looking for the best way of achieving this.

A: undo only undoes that specific transaction, while rollback undoes everything between that transaction and the current state of the system.
Example: you install htop, then later install ncdu and glances, followed by mc the next day.
You later want to undo installing htop, so you use the undo function to try to undo installing htop, but still keep the other programs you installed later.
If you rolled back to the transaction that installed htop, you'd instead undo  the installation of ncdu, glances and mc, while still keeping htop.


text:
Q: Why does Wildfly read the same JPA persistence unit twice? I use Wildfly 18 to deploy ear of my JavaEE application. My ear consists of ejb.jar and war. JPA stuff with persistence.xml is situated in separated jar which is a dependency of war.
The problem is when I deploying ear, Wildfly reads the same persistence unit twice.
18:40:48,730 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 37) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'ear-1.0-SNAPSHOT.ear/org.example-webapp-1.0-SNAPSHOT.war#FriendPU'
18:40:48,730 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 38) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'ear-1.0-SNAPSHOT.ear/org.example-persistence-1.0-SNAPSHOT.jar#FriendPU'
18:40:48,946 INFO  [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 38) HHH000204: Processing PersistenceUnitInfo [
name: FriendPU
...]
18:40:48,946 INFO  [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 37) HHH000204: Processing PersistenceUnitInfo [
name: FriendPU
...]

It seems Wildfly reaches persistence unit through persistence.jar as war dependency in the first time and then directly through this jar.
Why does it happen and how can it be fixed?
Thanks!


text:
Q: apache2 server not starting I am new to apache2 (server management in general). When I am running the command apachectl start from: /apache2/bin, I am getting the error:
(13)Permission denied: make_sock: could not bind to address [::]:80
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs

When I do netstat -an | grep ":80", I can see that there is no process/webservice running on port 80.
tcp        0      0 ::ffff:127.0.0.1:8005       :::*                        LISTEN
tcp        0      0 :::8009                     :::*                        LISTEN

This is very weird and I cannot find a solution as to how to start the apache2 server. Please Help!

A: try with sudo apachectl start ?

A: Depends.
There can be multiple reasons. First of them is an application is using Port 80.
Second is that you might have Web Deployment Agent Service on or World Wide Web Publishing Service. So stop these by going to control panel and typing administrative tools and click component services then click services (local) in side bar then scroll to the "W" section till you see the Web Deployment Agent Service and the World Wide Web Publishing service and click stop!
That should free Port 80.

A: try
sudo service apache2 start


text:
Q: Add Access Point to Sonicwall TZ100 I have a SonicWall TZ-100 configured with two private networks, 192.168.1.x LAN and 192.168.10.x WLAN. The WLAN is bridged to the WAN so traffic goes direct out through the WLAN and never access our internal LAN. SonicWall DHCP is enabled for the WLAN.
I have a Ubiquiti UniFi AP that I'd like to add to extend the coverage of the WLAN.
How can I configure the TZ100 to get the AP on the 192.168.10.x network?

A: I setup an additional zone (LAN2) and assigned that to x4. the W0 WLAN interface was set to layer 2 bridge mode to the x4. Now both the WLAN and the x4 were on the same network.
The next issue I had was getting traffic from LAN 2 to flow to the WAN. First, I disabled any firewall access between WLAN/LAN2 -> LAN/VPN/DMZ. Then I added Any to Any access between LAN2 <-> WAN. After than I had to add a static route for the x4 interface to the W


text:
Q: Find hours between post_date and post_date_gmt I'd like to find the time difference -preferably in hours- between post_date and post_date_gmt.
I tried $age = date_diff(get_post_time(),get_post_time($gmt = true));
but this returns
Warning: date_diff() expects parameter 1 to be DateTimeInterface, int given in C:\xampp\htdocs\t\wp-content\themes\i\single.php on line 23
I didn't really understand the official WP documentation on this function -do they refer to just "time" or "timestamps"?
The basic reason is that I abused the post_date to store the last update date while the gmt field still contains the original publication date. I know that's wrong but I needed a quick and dirty solution some time ago for a different problem.

A: If all you need to do is check the difference, rather than display or modify anything, then you don't need to do anything complicated with date_diff(). All you need to do is compare the number of seconds returned by get_post_time() for each date.
get_post_time() returns the Unix timestamp for the date, which is simply the number of seconds since January 1 1970. So if the difference between the two timestamps is greater than 86400 seconds, the difference is greater than 24 hours.
$difference = get_post_time( 'U', true ) - get_post_time( 'U', false );

if ( $difference > DAY_IN_SECONDS ) {
    // GMT date is over 24 hours more than post date.
}

The 'U' in this code tells get_post_time() to return the value as a Unix timestamp. It's the default value, but we need to set it to be able to set the second argument, which tells it whether to use the post_date or post_date_gmt.
In this example DAY_IN_SECONDS is a WordPress constant equal to 86400. Using it makes the code more readable, and you don't have to figure out what the number was supposed to mean later.


text:
Q: User control needs different resx file I have the following code in a User Control called View.ascx:
<label><asp:Label ID="lblProvince" runat="server" ResourceKey="lblProvince"></asp:Label>:</label>
<asp:DropDownList ID="PROVINCE" runat="server">
    <asp:ListItem ResourceKey="liselectprovince"></asp:ListItem>
    <asp:ListItem Value="ab" ResourceKey="liab"></asp:ListItem>
    <asp:ListItem Value="bc" ResourceKey="libc"></asp:ListItem>
    <asp:ListItem Value="mb" ResourceKey="limb"></asp:ListItem>
    <asp:ListItem Value="nb" ResourceKey="linb"></asp:ListItem>
    <asp:ListItem Value="nf" ResourceKey="linf"></asp:ListItem>
    <asp:ListItem Value="ns" ResourceKey="lins"></asp:ListItem>
    <asp:ListItem Value="nt" ResourceKey="lint"></asp:ListItem>
    <asp:ListItem Value="nu" ResourceKey="linu"></asp:ListItem>
    <asp:ListItem Value="on" ResourceKey="lion"></asp:ListItem>
    <asp:ListItem Value="pi" ResourceKey="lipi"></asp:ListItem>
    <asp:ListItem Value="qb" ResourceKey="liqb"></asp:ListItem>
    <asp:ListItem Value="sk" ResourceKey="lisk"></asp:ListItem>
    <asp:ListItem Value="yk" ResourceKey="liyk"></asp:ListItem>
</asp:DropDownList>

The ResourceKey maps to values found in files View.ascx.fr-CA.resx and View.ascx.resx.
I do not have access to the any other code on the server.  I can only do my work within a plugin of this greater software, which will embed any user control that I create.
The rest of hte site is being rendered as en-CA.
I tried to programmatically set culture from my user control like so:
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");

But that doesn't force my view.ascx to use values from view.ascx.fr-CA.resx.  Instead it still uses View.ascx.resx.
How can I write code that will select the appropriate resx file?  I want to use view.ascx.resx on all pages with url that start with /en and view.ascx.fr-CA.resx on all pages with url that start with /fr .

A: This is not exctly what you need:
ResourceManager manager = new ResourceManager("Resources.Messages", Assembly.Load("App_GlobalResources"));
string test = manager.GetString("EmailBodyMagazine",new System.Globalization.CultureInfo("fr-CA"););

But maybe you can also use the resource manager to access your files directly

A: I figured it out.  I can do this:
Localization.SetThreadCultures(new System.Globalization.CultureInfo("fr-CA"), DotNetNuke.Entities.Portals.PortalSettings.Current);

I can replace fr-CA with any other language.


text:
Q: Sending thousands notifications on PHP (Symfony2) using SQS I have a Symfony2 app that under some circumstances has to send more than 10.000 push and email notifications.
I developed a SQS flow with some workers polling the queues to send emails and mobile push notifications.
But now, I have the problem that, when in the request/response cycle I need to send to SQS this task/jobs (maybe not that amount) this task itself is consuming a lot of time (response timeout is normally reached).
Should I process this task at background (I need to send back a quick response)? And how to handle possible errors with this scenario?
NOTE: Amazon SQS can receive 10 messages at one request and I already using this method. Maybe should I build a simple SQS Message with a lot of notifications jobs (max. 256K) to send less HTTP requests to SQS?

A: The moment you have a single action that triggers 10k actions, you need to try to find a way to tell the user that "OK, I got it. I'll start working on it and will let you know when it's done".
So to bring that work into the background, a domain event should be raised from your user's action which would be queued into SQS. The user gets notified, and then a worker can pick up that message from the queue and start sending emails and push notifications to another queue.
At the end of the day, 10k messages in batches of 10 are just 1k requests to SQS, which should be pretty quick anyway.
Try to keep your messages small. Don't send the whole content of an email into a queue message, because then you'll get unnecessary long latencies. Keep the content in a reachable place or just query for it again when consuming the message instead of passing big content up and down the network.

A:
And how to handle possible errors with this scenario?

Amazon provides dead letter queues for this.  In asynchronous systems I've built, I usually create a queue and then attach a redrive policy to it that says "if I see the same message on this queue 10 times, send it to a dead letter queue so that it doesn't bounce back and forth between the queue and a consumer for all eternity".  The dead letter queue is simply another queue.
From a dead letter queue you can decide what to do with data that did not process.  Since it's notifications (emails or push notifications) in your case, you might have another component in your system that will periodically reprocess a dead letter queue.  Scheduled Lambdas are good for this.


text:
Q: Polynomials of Continuous Bijective Functions Dense in C([a,b]) This is a question that I cam across while practicing some old comprehensive exams at my school and I was wondering if you could offer some advice towards working through it. The question is as follows
Let $f(x):[a,b]\to[a,b]$ be a continuous, one-to-one, onto function. Show that $\{p(f(x)):p(x)\text{ is a polynomial}\}$ is dense in $C([a,b])$.
While thinking about it, I noticed a few things but I don't know how helpful they will be.

*

*$f^{-1}$ is one-to-one, onto, and uniformly continuous.

*$f([a,b])=[a,b]$ or $[b,a]$.

What I did was choose an arbitrary function $g(x)\in C([a,b])$. Then considered the function $h(x)=g(f^{-1}(x))$, which is clearly in $C([a,b])$. Then I know that I can approximate $h(x)$, by the Weierstrass Approximation Theorem, using some some polynomial $\mathcal{P}_h(x)$, depending on $\epsilon$. So that I get
\begin{align*}
||h(x)-\mathcal{P}_h(x)||_\infty<\epsilon
\end{align*}
Implying
\begin{align*}
||h(f(x))-\mathcal{P}_h(f(x))||_\infty&=||g(x)-\mathcal{P}_h(f(x))||_\infty<\epsilon
\end{align*}
Is this all that this problem boils down to? Or is there more to it than this?