text:
Q: Tooltips in Joomla containing HTML I created a component using Component Creator for Joomla 3.X
The problem is that on the site the tooltips show html code. For example:
Title
Description

Instead, on the administrator they are displayed properly:

Title
Description

I was reviewing the documentation here and here, and it seems that it is possible to define the output format when calling the tooltip function but there are no calls inside the component to that function. The only call I see is JHtml::_('behavior.tooltip'); at the begining of the view file and don't know how to specify the output format.
The site is in this URL:
http://50.87.185.99/colombianadederecho_blank/index.php/administradores-ph/registrarse

Added:
It seems like the code is called when building the label for each field:

<?php echo $this->form->getLabel('document'); ?>

<?php echo $this->form->getInput('document'); ?>

And it is stored in the title attribute:
title="<strong>Title</strong><br />Description"

So, I think the problem is in the Javascript function, maybe using a .text() jQuery function instead of a .html().
Inspecting the source code I found this, but don't understand why it is not working properly:
window.addEvent('domready', function() {
            $$('.hasTip').each(function(el) {
                var title = el.get('title');
                if (title) {
                    var parts = title.split('::', 2);
                    el.store('tip:title', parts[0]);
                    el.store('tip:text', parts[1]);
                }
            });
            var JTooltips = new Tips($$('.hasTip'), {"maxTitleChars": 50,"fixed": false});
        });

jQuery(document).ready(function() {
    jQuery('.hasTooltip').tooltip({"html": true,"container": "body"});
});

Solution:
As @ilias found it was a problem between libraries. I had to disable the bootstrap call in the header using this plugin and call it from the end of the body:

A: I don't know the code that Component Creator produces, however I assume that the tooltips are like in the administrator views. If this is the case you should check for something like this:
<button type="submit" class="btn hasTooltip" title="<?php echo JHtml::tooltipText('JSEARCH_FILTER_SUBMIT'); ?>"></button>

and enclose the contents of JHtml::tootlipText() in strip_tags().
Otherwise try to find the line Title
Description where the tags are shown and enclose it in strip_tags(). For example you might have something that looks like:
echo $this->escape($item->description);

that should be turned into:
echo $this->escape(strip_tags($item->description));


text:
Q: Alarm Notification is displayed as soon as alarm is set, even though time is future time I am facing a problem in setting a alarm, I am giving future time to the alarmManager.Set method but as soon as alarm  gets triggered I am getting the notification instead of receiving the notification at the specified time. Please let me know what mistake am I doing. This is the first time I am working on alarm so please let me know my mistakes. All suggestions are welcome. Thanks in advance.
My Alarm Setting method:
I am taking the entered time by the user and formatting the time and giving it to the alarmManager.Set method:
String givenDateString = dateTime;
    Log.d("Pana", "The value of Date Time is " +dateTime);
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
    try {
        Date mDate = sdf.parse(givenDateString);
        timeInMilliseconds = mDate.getTime();
        Log.d("Pana ", "Date in milli :: " + timeInMilliseconds);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // create an Intent and set the class which will execute when Alarm triggers, here we have
    // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
    // alarm triggers and
    //we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
    Intent intentAlarm = new Intent(this, AlarmReceiverNotification.class);

    // create the object
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //set the alarm for particular time
    alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMilliseconds , PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(this, "Alarm Scheduled for Tomorrow", Toast.LENGTH_LONG).show();

    Intent intent = new Intent(this, MyAlarmService.class);
    intent.putExtra("Time", timeInMilliseconds);
    startService(intent);

    boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent("com.ms.t.tms.MY_UNIQUE_ACTION"),
            PendingIntent.FLAG_NO_CREATE) != null);

    if (alarmUp)
    {
        Log.d("myTag", "Alarm is already active");
    }

My receiver class:
 public class MyAlarmService extends IntentService {

        private NotificationManager mManager;
        Notification notification;
        Intent intent;

        public MyAlarmService() {
            super("MyAlarmService");
        }

        /**
         * Creates an IntentService.  Invoked by your subclass's constructor.
         *
         * @param name Used to name the worker thread, important only for debugging.
         */
        public MyAlarmService(String name) {
            super(name);
        }

        @Override
        protected void onHandleIntent(Intent intent) {

        }

        @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);

                Log.d("Pana", "Alarm is triggered");

                Long time = intent.getLongExtra("Time", 0);

                mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
                Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

                notification = new Notification(R.mipmap.ic_launcher,"This is a test message!", time);
                intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
                notification.flags |= Notification.FLAG_AUTO_CANCEL;
                notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

                mManager.notify(0, notification);
            }
        }

A: Faced same problem but finally able to solve it.
In my case i was supplying wrong month while parsing with SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy HH:mm", Locale.ENGLISH);

You can check weather your timeInMilliseconds is correct or not using
Log.i(TAG, "Date in milli :: " + timeInMilliseconds);

Log.i(TAG,"System.currentTimeMillis() = "+System.currentTimeMillis());

if timeInMilliseconds is less than System.currentTimeMillis() then timeInMilliseconds is wrong else correct.
In this M is month in year starting from 1 to 12
In my case i was supplying month starting from 0 to 11
To solve this issue i incremented month by 1 and then parsed with SimpleDateFormat and problem solved.

A: Your notification is displayed as soon as you are binding your service MyAlarmService because you are showing notification in onStartCommand() method
You should pass Calender object to MyAlarmService so that you can show notification at that specific time. You can refer to here

A: Here is the code to set Alarm using Alarm Manager class. Just keep in mind that your unique id should different and time should in millisecond.
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

AlarmManager mAlarm = (AlarmManager) MainActivity.this
                                .getSystemService(MainActivity.this.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();

// Unique id should be different all the time. So I used it with System current Millis seconds.

PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
                                    uniqueId, intentR, 0);

// Give you time in milliseconds for the Alarm. I given Alarm time after 1 minute (1 * 60 * 10000

mAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, systemTime + 1 * 60 * 60 * 1000,
                                    pendingIntent);

intentArray.add(pendingIntent);

redpajama_set_name: RedPajamaStackExchange


text:
Q: python tarfile writes tar to pipe I want to create a tar file and pipe it to a http upload.
However, seems python tarfile module performs seek which make it impossible to pipe to the next process.
Here is the code
tar = tarfile.open('named_pipe', mode='w')
tar.add('file1')
p.close()

'named_pipe' is a named pipe file created by mkfifo command
when I run it and cat the named_pipe in another terminal, I got the error
tar = tarfile.open('named_pipe', mode='w')
  File "/usr/lib/python2.7/tarfile.py", line 1695, in open
    return cls.taropen(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1566, in __init__
    self.offset = self.fileobj.tell()
IOError: [Errno 29] Illegal seek

Any ideas?

A: We do something similar, but from the other side. We have a web app that feeds a tarfile to the visitors browser, which means we stream it over the http session.  The trick is to pass the opened and writeable file handle to the tarfile.open() call, along with the mode set to "w|".  Something like this:
# assume stream is set to your pipe

with tarfile.open(name="upload.tar",
    mode = "w|",
    fileobj = stream,
    encoding = 'utf-8') as out:

    out.add(file_to_add_to_tar)


text:
Q: If an activity is killed, does the AsyncTask live on? I think I know the answer to this, but does an AsyncTask continue to live on once its calling Activity has been finish()ed?
    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(), "Your data is processing.", Toast.LENGTH_LONG);
        finish();
    }

Edit: so far two different answers :)

A: The AsyncTask is tied to a UI thread and if the Activity is finished the async task is canceled.
[update] - Hackbod's comment below is correct. It should be noted that AsyncTasks are meant to be short lived and as such not worry so much about this issue. An AsycTask is only truly gone when it is completed OR the process is killed which may or may not happen after finish is called.

A: It keeps running until the onPostExecute finishes.

A: I've experienced some weirdness with Async Tasks where if an activity is killed by the OS and when the app resumes, the AsyncTasks sometimes do not run at all. I am unsure why they get into this state. If you execute your AsyncTasks in your own executor thread, this does not happen. I might be running into some odd circumstance. Thought it might be useful to post here anyway :).

A: Async task keeps running untill he onPostExecute() is finished.
try it by putting a toast on finish()  and  onPostExecute() to see which toast is shown first.

A: Asynctask are not bounded to any life cycle method of Activity or Service.
It keeps running in a separate thread until the onPostExecute() gets executed in the main thread.

A: Async Tasks have no effect of the Activity lifecycle or any configuration changes. They keep on running till onPostExecute() method has been called.
One should use Services for long running operations instead.


text:
Q: Spring Batch FlatFileItemReader continue on incorrect number of tokens I'm using Spring Batch FlatFileItemReader to parse csv files. Every now and then I get an ill-formated line and the application completely crashes with:
Caused by: org.springframework.batch.item.file.transform.IncorrectTokenCountException: Incorrect number of tokens found in record: expected 11 actual 18

Is there any way to tell the FlatFileItemReader to continue (throw exception and continue or ignore and continue) without it completely exiting the application.
I'm guessing I may need to extend the FlatFileItemReader to make this happen as there does not appear to be any setting for this. Any suggestions on how best to proceed and make this happen?

A: You can configure SkipLogic for your batch jobs
Here's a link to doc
Basically, if you are using Java Config to manage your Batch Job
you can do something like this
stepBuilderFactory.get("step1")
                .<Person, Person>chunk(10)
                .reader(reader)
                .writer(writer)
                .processor(processor)
                .faultTolerant()
                .skipLimit(10)
                .skip(RuntimeException.class)
                .listener(skipListener) // if you want to add
                .build();

A: I was able to solve this by creating a class that extended the DefaultLineMapper that gets injected into the FlatFileItemReader.
I then overrode mapLine method like this:
@Override
public T mapLine(String line, int lineNumber) throws Exception {
    T t = null;

    try {
        t = super.mapLine(line, lineNumber);
    } catch (Exception e) {
        log.error("Unable to parse line number <<{}>> with line <<{}>>.", lineNumber, line);
    }

    return t;
}

A: I'm not sure if this is the same as your issue, but I was getting the same error when parsing a caret "^" delimited file that contained quote " characters.
The " character is intended to be used to to extend a field across line endings or to enclose a String which contains the delimiter. So my line that looks like this:
^3500 LCF Gas:  109" Wheelbase, Reg Cab^Chevrolet^3500 LCF Gas^109" Wheelbase, Reg Cab^L

would be parsed like it has only 2 fields:

*

*3500 LCF Gas:  109" Wheelbase, Reg Cab^Chevrolet^3500 LCF Gas^109" Wheelbase, Reg Cab

*L

What I really wanted is 5 fields:

*

*3500 LCF Gas:  109" Wheelbase, Reg Cab

*Chevrolet

*3500 LCF Gas

*109" Wheelbase, Reg Cab

*L

My file didn't contain any ampersands so I changed the DelimitedLinetokenizer default quoteCharacter from " to &.
lineTokenizer.setQuoteCharacter('&');

Which fixed my issue that resulted in the same error when using Spring Batch.

A: I managed to solve this by setting the property "strict" to false for the property "lineTokenizer" from DefaultLineMapper .


text:
Q: Simple list of branch for a Node Python AnyTree Given a simple tree in AnyTree, when I look at a node it tells me its path to the root, but I cannot find anything that will simply give me that path as a list of the node names, or as a string which I can simply turn into a list of the names.
Typical example
from anytree import Node, RenderTree, AsciiStyle

f = Node("f")
b = Node("b", parent=f)
a = Node("a", parent=b)
d = Node("d", parent=b)
c = Node("c", parent=d)
e = Node("e", parent=d)
g = Node("g", parent=f)
i = Node("i", parent=g)
h = Node("h", parent=i)
print(RenderTree(f, style=AsciiStyle()).by_attr())

Which renders up as the tree:
f
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h

I just want the path from a leaf to the top or root. So some command that will do this:
>>> ShowMePath(e,f)         # a command like this
["e", "d", "b", "f"]

I'd even be happy if I could just get a string version of the node name which I could .split() to get that string.
>>> e
Node('/f/b/d/e')       < can I get this as a string to split it?

All the iterator methods examples (eg PostOrderIter) seem to return parallel branches rather than just a simple path to the top. I've looked through the docs but don't see this simple give-me-the-path option. What am I missing? Isn't this something everyone needs?

A: Okay - a solution.  Turns out there is a .path attribute which returns a tuple of the path of nodes to the top. Didn't see that digging through the docs initially.
So I can get to my desired list in the example above with:
pathList = list(e.path)
namesList = [n.name for n in pathList]

and I'm there.


text:
Q: Python changing part of each line in a file I am learning python and I am trying to write a code that allows me to read in a file, then change a portion of each line in a text file, and the output is written to the file.
Each line in the file has different years and information in it.
What I have so far is:
filein = input('file.txt', 'r')

for line in filein:
    str = "1984 - 2000"
        print str.replace("1984 - 2000", "1970 - 2010")

file.close()

When I try this I get this error "SyntaxError: multiple statements found while compiling a single statement"
How can I fix/ improve this code?

A: I believe what you are looking for is
filein = open('file.txt', 'r')
lines = filein.read()

for line in lines:
    str = "1984 - 2000"
    print (line.replace(str, "1970 - 2010"))

filein.close()

A: First of all you have to put parenthesis around what your printing. Also change str to line and 1984-2000 to str. Like this:
print (line.replace(str, "1970 - 2010"))


text:
Q: What are the invariant Pseudo-differential operators on a Lie group? It is well-known that (left) $G$-invariant differential operators on a Lie group $G$, has an algebraic description, i.e. universal enveloping algebra of the Lie algebra of the group.
On the other hand $\Psi$Do are generalization of the differential operators on general smooth manifold.
My question is that:
Does any algebraic description for the $G$-invariant $\Psi$DOs on the Lie groups (or more general on homogeneous spaces $G/H$) exist ?
Thanks

A: It seems to me that an interesting "first step" or sub-problem---and one that should be fairly straightforward, is to characterize the space of invariant symbols of pseudo differential operators on a Lie group (or more generally on a homogeneous space of a Lie group).

A: I have never seen such a characterization (and I'm inclined to agree with André that there may not be one at the same level of simplicity as in the case of invariant differential operators), but my best bet towards such one would be to employ a Beals-Cordes-type characterization of pseudodifferential operators: a bounded operator $T$ in the Hilbert space $L^2(\mathbb{R}^n)$ is a pseudodifferential operator of order zero if and only if its commutators with any element of the Lie algebra generated by the coordinate vector fields and (multiplication by) the linear monomials in $\mathbb{R}^n$ (seen as the Abelian Lie group of $n$-dimensional translations) are bounded operators in $L^2(\mathbb{R}^n)$ as well. Obviously, the invariant operators are those that, in addition, have zero commutator with all elements of the Lie algebra of $\mathbb{R}^n$. See for instance H. O. Cordes, "The Technique of Pseudodifferential Operators" (Cambridge, 1995), Chapter 8.
An appropriate replacement of the above Lie algebra in the case of a (reductive) Lie group would involve its Lie algebra and the analog of multiplication by linear monomials, which probably involves the Fourier-Helgason transform (see, for instance, S. Helgason, "Geometric Analysis on Symmetric Spaces" (AMS, 1994), Chapter III).

A: There is the following description of $G$ invariant pseudodifferential operators on a Riemannian homogeneous space $G/H$: The Schwartz kernels are smooth outside the diagonal and conormal with respect to the diagonal; this is equivalent to Beals' commutator characterization mentioned in Pedro Lauridsen Ribeiro's answer. Moreover, the full geometric symbols are, modulo symbols of order $-\infty$, invariant under the symplectic action of $G$ on $T^*(G/H)$.
Geometric symbols are defined by pulling back Schwartz kernels under the exponential map of the Levi-Civita connection to a neighbourhood of the zero section of the tangent bundle $T(G/H)$, and then taking Fourier transforms in the fiber variable. See here for more details of and references to the geometric pseudodifferential calculus. That principal symbols must be invariant is clear from the transformation behaviour under diffeomorphisms (special case of Egorov's theorem, or FIO calculus). Lemma 6.2 in the  paper in Math. Z., of which I am a coauthor, gives the invariance of the full geometric symbol if the diffeomorphism is an isometry, e.g. an action on $G/H$ by a group element.
The description discards smoothing operators. This is reasonable if one adopts, from Sato's microlocal analysis, the view that pseudodifferential operators operate on microfunctions.
The above characterization of invariant pseudodifferential operators is not algebraic. However, I think that it is simple and straightforward. I don't know if there is a characterization of $G$ invariant microdifferential (pseudodifferential) operators in the setting of algebraic analysis which is more algebraic.

A: I am tempted to answer your question by the negative:
I believe that there does not exist any other, simpler, way of saying
"left-invariant pseudo-differential operator on $G$".
The reason is that if you look at the subset of smoothing operators (operators with smooth integral kernel), I already don't know how to say
"left-invariant smoothing operator on $G$" in any simpler (algebraic) way.

A: Rather then only considering invariant PSD operators, you might want to consider all $G$ invariant operators, i.e., $G$-intertwiner. I describe their functional calculus below. Their functional calculus can be realized/studied via convolution products and representation theory. What I describe is in the realm of the first answer by Pedro Lauridsen Ribeiro. I let you decide whether this classifies as "algebraic", but it is certainly of operator-algebraic/ representation-theoretic flavour. I claim everything else which is $G$-invariant operator will have a equivalent functional calculus.
Here is an example. Assume $H$ is compact. We identify $L^2(G/H)$ with the induced representation $\pi = Ind_{H}^{G} 1$ or the $H$-invariant vectors in $L^2(G)$ and then uses the convolution operators for $\phi \in C_c^\infty(G//H)$:
$$T_\phi f(g) = \int\limits_{G} \phi(x) f(xg) d x.$$
E.g. for $G =SL_2(\mathbb{R})$ and $H=SO(2)$, the algebra $C_c^\infty(G//H)$ is commutative by the Gelfand trick (this is not so essential) and the trace $T_\phi$ is an integral of the Harish-Chandra/Selberg transform of $\phi$ over the spectrum of the hyperbolic Laplacian or, alternatively, an integral
$$ \int\limits tr\; \pi(\phi) d_{Pl} \pi$$ over the irreducible unitary (tempered) reps $\pi$ of $G$ with $H$-invariant vectors (only principal series representations here). The measure $d_{Pl}$ is the Plancherel measure.
If $H$ is not compact, you can still do something similar working with $C_c^\infty(G)$ and obtain a similar analysis. E.g. take the two important situations when $H$ is a lattice or a parabolic subgroup in a reductive Lie group. The advantage: this generalizes to locally compact groups. E.g. on reductive groups over non-archimedean fields, there are no differential operators in any obvious way, but this gives you the Hecke operators. These ideas are crucial also in the context of the Selberg trace formula.


text:
Q: Firefox page-mod and iframe not loading So, I'm developping a firefox plugin based on page mod and iframe. The chrome version using iframe within content script is working perfectly.
So basically, I inject a button, when the button is pressed he change the display type of a div containing some windowing stuff (to make a movable window within the browser and a close button) and this window contain an iframe. The iframe contain the application which is entirely contained within the plugin package, just make few ajax calls to a server to refresh the local storage datas.
I can inject the open button, the windowing stuffs and the iframe but whenever what I put in the iframe, the content is not loading. (excepted in one case, but not what I want).
To set the content of the iframe I basically :

*

*retrieve the url within the resources : require("sdk/self").url("index.html")

*Send it to my injector with a message

*Set it in the iframe with : iframe.setAttribute("src", iframeSource);

Here's what's injected in the page :

    #document

If I browse resource://jid1-83zazep6ncytaa-at-jetpack/myaddon/data/index.html I get the page rendered correctly (css and js functionnal).
Also the two buttons and the header are displayed correctly (images, style and associated js). So it's really on the iframe that is not loading and rendering.
In the Console I don't get any js error or security error.
If I replace the iframe content with google (and inject it on google), the iframe don't render too.
So do you have any ideas ?
PS : There's one method that is working but not as I want. The problem with the method I've found is that the javascript is not running and I still have some styling issue. So not the way to go I think.
// Load the document
var source = data.load("index.html");

// Replace the relative path with the packed paths
source = source.replace("css/style.css", data.url("css/style.css"));
source = source.replace("css/ico.css", data.url("css/ico.css"));
source = source.replace("css/jquery-ui.css", data.url("css/jquery-ui.css"));
source = source.replace("js/external/jquery-1.9.1.js", data.url("js/external/jquery-1.9.1.js"));
source = source.replace("js/external/jquery-numeric.js", data.url("js/external/jquery-numeric.js"));
source = source.replace("js/external/jquery-ui.js", data.url("js/external/jquery-ui.js"));
source = source.replace("js/trade/data.js", data.url("js/trade/data.js"));
source = source.replace("js/trade/main.js", data.url("js/trade/main.js"));
console.log(source);

// Encode the content
let content = encodeURIComponent(source);
let binarySource = "data:text/html;charset=utf-8," + content;

// When in the injector, set the "binary source" as content
iframe.contentWindow.location.href=iframeSource;


text:
Q: Trigger observable manually? I have a service with a collection of CRUD actions. One of them is a "get all" kind of deal. All return HTTP observables like:
  getUsers(): Observable<User[]> {
    return this.http.get(this.baseURL + '/api/users').map((response: Response) => response.json()).share();
  }

Now, I have one component subscribed to the service with an async pipe:
this.users = this.userService.getUsers();
<md-list-item *ngFor="let user of users | async;>
And in another component, I'd like to call the getUsers method (since it performed some actions on the data), and have the other component automatically update.
this.service.getUsers() doesn't work of course because it needs to be subscribed to.
Is there someway to make a subscription/observable permanent? Am I missing something?
I've usually done something where components subscribe to a subject in a service directly and I manually update it. But was wondering if there's some fancy shamncy way.

A: In the case of an observable created from an HTTP call, the corresponding request will be called twice if subscribed twice) By default such observables are cold (they can't be shared).
You can make your observable hot using the share method:
import 'rxjs/add/operator/share';

this.users$ = this.userService.getUsers().share();


text:
Q: Adding Imports To addon.xml for Kodi What is the syntax for adding imports to Kodi addon.xml file? I am trying to use pythons requests, and I get this error:
07:54:13.435 T:123145511706624   ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
                                             - NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
                                            Error Type: <type 'exceptions.ImportError'>
                                            Error Contents: No module named requests
                                            Traceback (most recent call last):
                                              File "//Kodi/addons/bingewave.venues/addon.py", line 8, in <module>
                                                import requests
                                            ImportError: No module named requests
                                            -->End of Python script error report<--

Now I noticed Kodi has a lot of libraries built into the platform that include these: http://kodi.wiki/view/Category:Add-on_libraries/modules
Currently in my add-on xml, I have this:
<addon id="example" name="Example" version="1.0.4" provider-name="zag">
    <requires>
        <import addon="xbmc.python" version="2.14.0"/>
    </requires>
    <extension point="xbmc.python.script" library="addon.py">
        <provides>executable</provides>
    </extension>
</addon>

What is the syntax for importing more modules like requests?

A: Add this to the <requires> defintion <import addon="script.module.requests" version="2.12.4"/>
It won't resolve this for your local dev enviroment, it will only be resolved if you install the addon via an zip or from an addon repo. So just setting it and starting kodi will likly crash your addon anyway.
If your looking for the module to install to for your dev enviroment look here http://mirror.de.leaseweb.net/xbmc/addons/krypton/script.module.requests/


text:
Q: java.util.ConcurrentModificationException while adding elements? I have a servlet which uses a service to parse a YAML file. but when I put some user traffic on my servlet I get:
SEVERE: Servlet.service() for servlet [SitesController] in context with path [] threw exception [java.util.ConcurrentModificationException] with root cause
java.util.ConcurrentModificationException
    at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1129)
    at java.util.ArrayList$SubList.listIterator(ArrayList.java:1009)
    ...
    at com.example.UrlRedirectEngin.redirectoToRespectiveSubDomain(UrlRedirectEngin.java:250)

I am not sure if the exception is from parsing the YAML file or not. However the exception is pointing to the line below which I render the page line 250:
request.getRequestDispatcher(JSP_PAGE).forward(request, response);

I just want to know if ConcurrentModificationException can also happens while adding elements to a Map?
If yes how can I handle this issue. Thanks.

A: The line
request.getRequestDispatcher(JSP_PAGE).forward(request, response);

forwards to an JSP page. The error may be inside  of that JSP as well (the part of the stacktrace may hide the original error)

A: ConcurrentModificationException means that you are editing your map/collection when you try to read it.
Simple example :
final List<String> list = new ArrayList<String>()
    private static final long serialVersionUID = 1L; {
        {
            add("Hi");
            add("This is a test");
        }
    };
for(final String string : list) {
    if(string.equals("Hi")) {
        list.remove("Hi");
    }
}

I think getRequestDispatcher is modifying your map while your using it.


text:
Q: Why can a constructor be called only once per instance? Why are constructor calls in Java allowed only once per instance? If would be useful to set multiple instance variables in one call rather than calling several setters.

A: Your mistake is assuming that you should be writing default constructors and setting all the values using setters.  An object should be 100% ready to go when it's created, so you should be writing one constructor that initializes its entire state.
It's not the Java "gods" that are mistaken, it's you.

A: There a deeper point here: Each method can run any number of times, zero to many, per object. The fact that a  constructor can run only once is an advantage as it allows you to write code that will be executed exactly once per object. For instance: registration, acquisition of external resources (files, sockets, DB connections), data manipulation (if you want your input to be sorted you make the sorting inside the constructor and the language ensures that sorting will take place).

A: Another alternative to the constructor and other constructor patterns described here is the Builder pattern. There are plenty of pages describing how it works, but can be summeraised with the following concise example:
import java.awt.Color;
import java.util.LinkedList;
import java.util.List;
public class Badger {
private int legs;
private boolean nose;
private List<Color> colors;

private Badger() {
    colors = new LinkedList<Color>();
}

public static class BadgerBuilder {
    private Badger badger;

    private BadgerBuilder(){}

    public static BadgerBuilder buildBadger() {
        BadgerBuilder b = new BadgerBuilder();
        b.badger = new Badger();
        return b;
    }

    public BadgerBuilder legs(int legs) {
        badger.legs = legs;
        return this;
    }

    public BadgerBuilder hasNose(boolean nose) {
        badger.nose = nose;
        return this;
    }

    public BadgerBuilder addColor(Color c) {
        badger.colors.add(c);
        return this;
    }

    public Badger build() {
        return badger;
    }
}

public static void main(String [] args) {
    Badger b = BadgerBuilder.buildBadger()
                                .legs(4)
                                .hasNose(true)
                                .addColor(Color.black)
                                .addColor(Color.white)
                                .build();
}

A: If you want to set several variables at once just define a function:
public class Person {
  public Person(String firstName, String lastName, Date dateOfBirth) {
    set(firstName, lastName, dateOfBirth);
  }

  public void set(String firstName, String lastName, String dateOfBirth) {
    ...
  }
}

By definition an object is only constructed once, hence the constructor is only called once.
One thing worth noting: it's more common to favour immutability, so:
public class Person {
  private final String firstName;
  private final String lastName;
  private final Date dateOfBirth;

  public Person(String firstName, String lastName, Date dateOfBirth) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.dateOfBirth = dateOfBirth == null ? null new Date(dateOfBirth.getTime());
  }

  public String getFirstName() { return firstName; }
  public String getLastName() { return lastName; }
  public Date getDateOfBirth() { return dateOfBirth == null ? null : new Date(dateOfBirth.getTime()); }

  public Person withFirstName(String firstName) {
    return new Person(firstName, lastName, dateOfBirth);
  }

  public Person withLastName(String lastName) {
    return new Person(firstName, lastName, dateOfBirth);
  }

  public Person withDateOfBirth(Date dateOfBirth) {
    return new Person(firstName, lastName, dateOfBirth);
  }
}

because a lot of concurrency issues simply go away when you do this. Not just concurrency issues too. String, BigDecimal, BigInteger and some other standard classes are immutable (immutable means once instantiated its state can never change). Date isn't. You see in the above code I have to constantly defensively copy the date of birth? That's because Date is not immutable. If you didn't a caller could do this:
public class Person {
  private final Date dateOfBirth;

  ...

  public Date getDateOfBirth() { return dateOfBirth; }
}

Person person = new Person(...);
Date date1 = person.getDateOfBirth();
date1.setTime(1000000000L);
System.out.println(person.getDateOfBirth());

The date of birth will have changed. That problem is caused solely by Date being mutable. That's another reason to favour immutability.

A: Nothing prevents you from writing another method that sets all the desired fields at once. It can even be called from the constructor in order to prevent code duplication.

A: You can call one constructor from another.
For example:
class MyClass {

  public MyClass() {
     // initialize what you want
  }

  public MyClass(String custom) {
    this();
    // custom initialization
  }
}

A: As many have mentioned, the constructor doesn't actually construct but sets the initial values on the object.  This is important in that it is the only place to set final fields that are otherwise uninitialized. This should be a clue that the constructor isn't the same as any other function. Also, having a good and complete constructor can help define the invariants.
However, there are some tradeoffs and potential pitfalls here.  It is not always correct that objects are "completely finished" when the constructor is complete.  The constructors are invoked bottom up inheritance-wise but completed top down.  Thus even when your constructor is finished, subclasses may still have work to do.  So if you pass out a reference to yourself (an escape) during construction and that other class expect the caller to be in a complete/stable state, then problems could occur because the subclasses have not had their opportunity complete.  This is particularly risky in highly concurrent code.  In this case it becomes safer or even mandatory to use a construct/init pattern.  Thus it may not be possible to get the object into a safe enough state to pass to other objects in the constructor.  The are many cases where objects have circular dependencies and it becomes necessary to do basic construction on all then init them all.
IRC Josh Bloch (Effective Java) and Brian Goetz (Java Concurrency in Practice) both have some good discussions of these topics.  Factory construction with private constructors if often a good alternative and has many benefits and is covered by Bloch.


text:
Q: Server permissionsto allow php script to run but other users cant open I have an apache server set up, there is a php script for a login page (contains passwords).
I want to be able to give the server permissions to run the script but not for users who login  through the script to access the login.php through webmin(which is installed on the server). The permissions for users who connect through webmin is set to the same as a user named 'front' which is not the owner. The login.php file is is set so the owner is root.
After running the command 'sudo chmod 777 ~directory of file~'  the server could open the login page but obviously users who open file manager through webmin can also reead the usernames in the login file.
So I set the permissions to 'sudo chmod 200 ~directory of file~' this worked as I wanted.
However upon restart the server would no longer display the login page (I assume somehow the permissions did not allow this).
I then set the permission to '777' (everything worked but not secure) then back to '200' which made the login-page load and the users weren't able to access the login.php file. Now I have to run both these commands (in that order) whenever I restart the server,
what could be causing this?
note: the users need to access the web-directory to edit pages but should not be able to read that specific page.


text:
Q: Position of the column in the index How to get the position of a column in the index in PostgreSQL database? indkey in pg_index catalog table gives the position of that column in it's table, but i want the position of the column in it's containing index.

A: Here's one way. It might not be the best way.
SELECT c.relname, a.attname, a.attnum
FROM pg_attribute a
INNER JOIN pg_class c on c.oid = a.attrelid
WHERE c.relkind = 'i'
  AND c.relname = 'beds_pkey'
  AND a.attnum > 0

where beds_pkey is the name of the index.

A: Here is a query that retrieves the position on the index when you search by table:
select
  c.relname as tabela,
  a.relname as indexname,
  d.attname as coluna,
  (
    select
      temp.i + 1
    from
      (
        SELECT generate_series(array_lower(b.indkey,1),array_upper(b.indkey,1)) as i
      ) temp
    where
      b.indkey[i] = d.attnum
  ) as posicao
from
  pg_class a
    inner join
  pg_index b
    on
  a.oid = b.indexrelid
    inner join
  pg_class c
    on
  b.indrelid = c.oid
    inner join
  pg_attribute d
    on
  c.oid = d.attrelid and
  d.attnum = any(b.indkey)
where
  b.indisprimary != true and
  a.relname not like 'pg_%'
order by
  tabela, indexname, posicao

A: indkey is an array and the order of the entries in that array determine the order of the index columns.
So if indkey contains {2,4} then the second column of the table comes first in the index, and the table's fourth column is the second column in the index.
If indkey contains {4,3} then the table's fourth column is the first column in the index and the table's third column is the index' second column.

A: Just use array_position() function to get desired column index within indkey array:
select c.relname, a.attname,
       array_position(i.indkey, a.attnum)
  from pg_index i
  join pg_class c
    on c.oid = i.indexrelid
   and c.relkind = 'i'
  join pg_attribute a
    on a.attrelid = 'your_table'::regclass::oid
   and a.attnum = any(i.indkey)
 where indrelid = 'your_table'::regclass::oid
 order by 1, 2;


text:
Q: Youtube Analytics API, return 500 videos, only metrics are returned? With YouTube Analytics I can return a single YouTube video daily history from start date to end date with the below query:
https://youtubeanalytics.googleapis.com/v2/reports?ids=channel==$channel_id&metrics=views,likes,dislikes,comments,subscribersGained,averageViewDuration&dimensions=day&startDate=2019-09-20&endDate=2020-10-28&filters=video==$videoid

However the channel has 2500 videos. I can do this with the above query for a one video at a time but i'm trying to do 500 videos at a time.  I've read documentation and they allow multiple video id's.
$videoids = "$videoid1,$videoid2,$videoid3,$videoid4,$videoid5";

https://youtubeanalytics.googleapis.com/v2/reports?ids=channel==$channel_id&metrics=views,likes,dislikes,comments,subscribersGained,averageViewDuration&dimensions=day&startDate=2019-09-20&endDate=2020-10-28&filters=video==$videoids

The problem is no video id is returned only the metrics.  I need the videoid to be returned so I can put the metric values into database, with relative video id.
How do i solve?


text:
Q: Native C extension not finding code used by Ruby core Based on browsing the Ruby API sources for Array#length and Range#begin I know that macros RARRAY_LEN and RANGE_BEG exist and are used to implement the corresponding methods:
Array#length
static VALUE
rb_ary_length(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    return LONG2NUM(len);
}

Range#begin
static VALUE
range_begin(VALUE range)
{
    return RANGE_BEG(range);
}

However, while the code below has no problems with RARRAY_LEN I have been unable to get RANGE_BEG to work:
test.c
#include "test.h"

VALUE rb_mTest = Qnil;
VALUE rb_cTest = Qnil;

VALUE super_initialize(VALUE self) {
  return self;
}

VALUE array_len(VALUE self, VALUE ary) {
  Check_Type(ary, T_ARRAY);
  return LONG2NUM(RARRAY_LEN(ary));       // this works
}

VALUE range_begin(VALUE self, VALUE rng) {
  if (rb_obj_is_kind_of(rng, rb_cRange)) {
    // return RANGE_BEG(rng);                          // doesn't work
    return rb_funcall(rng, rb_intern("begin"), 0);     // this works
  }
  return Qnil;
}

void Init_test(void) {
  rb_mTest = rb_define_module("RangeTest");
  rb_cTest = rb_define_class_under(rb_mTest, "Tester", rb_cObject);

  rb_define_method(rb_cTest, "initialize", super_initialize, 0);
  rb_define_method(rb_cTest, "array_len", array_len, 1);
  rb_define_method(rb_cTest, "begin_value", range_begin, 1);
}

test.h
#ifndef TEST_H
#define TEST_H 1

#include "ruby.h"

VALUE super_initialize(VALUE self);
void Init_test(void);
VALUE range_begin(VALUE self, VALUE rng);
VALUE array_len(VALUE self, VALUE ary);

#endif /* TEST_H */

When the commented line is made active, the compiler generates this error message:
error: implicit declaration of function 'RANGE_BEG' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
    return RANGE_BEG(rng);
           ^
1 error generated.

This sounds to me like I'm missing an include, but 1) no additional include is required for RARRAY_LEN; 2) including range.h didn't change anything; and 3) I've failed to find where RANGE_BEG is defined when I tried searching with grep.
As you can see, I have a work-around using rb_funcall but would like to know why one macro found in the Ruby source works while another doesn't. The extension docs I've looked at have also implied that the macro versions are more efficient than function call versions for data access, so using the macro would be preferable.
To sum up, I'm hoping anybody can tell me a suitable incantation to get the compiler to access RANGE_BEG. This is happening on MacOS 12.4 (Monterey) using ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [arm64-darwin21] installed by HomeBrew, with CPPFLAGS=-I/opt/homebrew/opt/ruby/include and LDFLAGS=-L/opt/homebrew/opt/ruby/lib.

A: For whatever reason the RANGE_XXX macros are not included in the API headers. They are only defined and used in the internal Ruby implementation itself. It seems they wanted to keep these methods private, probably to ensure backwards and forward compatibility in case the internal implementation changes over time.
However, you get almost identical access through the API by using the provided method rb_range_values:
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp);

You can peek at its implementation here, where you can see it actually makes use of those internal macros.
To use it you simply have to define the returned variables and then call:
 VALUE beg;
 VALUE end;
 int excl;
 rb_range_values(range, &beg, &end, &excl);

Although this method does a little bit more than you need, it seeems likely it is still faster than a version using funcall, but you would need to benchmark to make sure.


text: Q: How to keep only numbers in text from bibliography? I want all my cite references to have numbers in them from 1 to N but make references section empty (no source information, pages names volumes...). How to do such thing in latex?


text:
Q: Parsing throw JSON with Python - String indices must be integers I am trying to parse through json data with Python 3.
My objective is to get all the cities from the JSON and add them to a list:
cities = []
for component in userdata['tagged_places']['data'][0]['place']['location']:
    cities.append(component['city'])

Python returns me this error:
TypeError: string indices must be integers

This is what my JSON in variable userdata looks like:
    {
   'id':'1234',
   'tagged_places':{
      'data':{
         'created_time':'2017-12-31T02:33:31+0000',
         'id':'1234',
         'place':{
            'id':'455149097983173',
            'location':{
               'city':'Buenos Aires',
               'country':'Argentina',
               'latitude':-34.59537,
               'longitude':-58.39196,
               'street':'Rodriguez Peña '               '1165, Recoleta, '               'Buenos Aires',
               'zip':'C1020ADW'
            },
            'name':'La Cholita'
         }
      },
      {
         'created_time':'2017-11-04T13:43:00+0000',
         'id':'1234',
         'place':{
            'id':'58666790576',
            'location':{
               'city':'Concepción',
               'country':'Chile',
               'latitude':-36.829561426349,
               'longitude':-73.036282767458,
               'street':'Víctor Lamas '               '#1290',
               'zip':'4070386'
            },
            'name':'Universidad de Concepción'
         }
      },

My objective is to return Concepcion & Buenos Aires to my cities list.
If I do
city = userdata['tagged_places']['data'][0]['place']['location']['city']

city gets returned correctly.

A: userdata['tagged_places']['data'][0]['place']['location'] is a dict. Hence, you can just access a key as you do via
userdata['tagged_places']['data'][0]['place']['location']['city']

Iterating a dict, however, produces its keys, which in your case are strings:
for component in userdata['tagged_places']['data'][0]['place']['location']:
    print(component)
    # 'city', 'country', etc.
    component['city']  # cannot work:  'city'['city']

If you want to collect all the cities, you should do sth like:
# assuming data is a list, which it appears to be given your working code
for component in userdata['tagged_places']['data']:
    cities.append(component['place']['location']['city'])

A: You need to loop through your items...
mydict = userdata['tagged_places']['data'][0]['place']['location']
for key, value in mydict.iteritems():
    print key
    print value

Try this and see if you can see your data....


text:
Q: Split A Sentence by Space and Hyphen usinh Regex PHP I want to split this string to 3 array element.

MW 01:00 PM - 02:30 PM

Output:
array[0] = MW
array[1] = 01:00 PM
array[2] = 02:30 PM

Help me with the regex expression that will extract that string to an array.
^[a-zA-Z\d-_]+$

A: You can split at spaces and optional hyphen if there is a digit ahead by use of a lookahead.
$arr = preg_split('/ +-? *(?=\d)/', $str);

See demo at eval.in

A: <?php

$str = "MW 01:00 PM - 02:30 PM";

$matches = [];

preg_match("/^([a-zA-Z]+)\s+(\d{1,2}:\d{1,2}\s+PM)\s+\-\s+(\d{1,2}:\d{1,2}\s+PM)$/",$str,$matches);

print_r($matches);

OUTPUT
Array
(
    [0] => MW 01:00 PM - 02:30 PM
    [1] => MW
    [2] => 01:00 PM
    [3] => 02:30 PM
)

A: This works too (but is longer):
$str = "MW 01:00 PM - 02:30 PM";
preg_match('/([A-Z]{2}) ([0-9]{2}:[0-9]{2} [A-Z]{2}) - ([0-9]{2}:[0-9]{2} [A-Z]{2})/', $str, $match);

echo '<pre>' . print_r($match, true) . '</pre>';

Output:
Array
(
    [0] => MW 01:00 PM - 02:30 PM
    [1] => MW
    [2] => 01:00 PM
    [3] => 02:30 PM
)


text:
Q: why I can't install socket.io there always an error on the console , what's going on?
npm ERR! code 1
npm ERR! path E:\full-stack\proshop-2\socket\node_modules\utf-8-validate
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@7.1.2
npm ERR! gyp info using node@14.15.4 | win32 | x64
npm ERR! gyp info find Python using Python version 3.8.2 found at "C:\Users\87302\AppData\Local\Programs\Python\Python38\python.exe"
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or
newer, try re-running with '--loglevel silly' for more details
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studionpm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack     at VisualStudioFinder.fail (C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:121:47)npm ERR! gyp ERR! stack     at C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:74:16
npm ERR! gyp ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
npm ERR! gyp ERR! stack     at C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:70:14
npm ERR! gyp ERR! stack     at C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:372:16
npm ERR! gyp ERR! stack     at C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack     at C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack     at ChildProcess.exithandler (child_process.js:315:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
npm ERR! gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
npm ERR! gyp ERR! System Windows_NT 10.0.19042
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\87302\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd E:\full-stack\proshop-2\socket\node_modules\utf-8-validate
npm ERR! gyp ERR! node -v v14.15.4
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! not ok
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\87302\AppData\Local\npm-cache_logs\2021-06-24T14_21_49_906Z-debug.log

A: It looks like you're missing the Visual Studio and Python on your system, or at least Node isn't aware of them.  You might want to try installing:

*

*https://github.com/felixrieseberg/windows-build-tools

*https://github.com/nodejs/node-gyp#installation
With the Windows Build Tools, you need to run from an elevated (admin) terminal
npm install --global windows-build-tools
npm install -g node-gyp

A: You can use 'yarn';
first, yarn install
second, yarn
third, yarn run dev


text:
Q: p-table keep first column fixed/freeze I am using primeng p-table and I want to freeze the first column from horizontal scrolling. The header, body and footer first columns does not scroll when the table is scrolled horizontally. How can I do that?
I am using  for *ngIf in header, body and footer. Follow code below. Ignore any syntax error, there are no syntax error in original code.

  <ng-container *ngFor="let col of columns">
    <ng-container *ngIf="condition; else nextTh2">
      {{col.label}}
    </ng-container>
    <ng-template #nextTh>
      <ng-container *ngIf="condition2; else nextTh3">
        {{col.label}}
      </ng-container>
    </ng-template>
    .
    .
    .
  </ng-container>

A: You can use the pFrozenColumn directive, placed on th and td elements in the header and body templates for the table.
If you want to freeze and unfreeze the column dynamically, use the directive together with the input [frozen].
Here's an example from the PrimeNG documentation, found here (Look for "Frozen Columns" on the page):

    <ng-template pTemplate="header">

            Name
            Id
            Country
            Date
            Company
            Status
            Activity
            Representative
            Balance

    </ng-template>
    <ng-template pTemplate="body" let-customer>

            {{customer.name}}
            {{customer.id}}
            {{customer.country.name}}
            {{customer.date}}
            {{customer.company}}
            {{customer.status}}
            {{customer.activity}}
            {{customer.representative.name}}
            {{formatCurrency(customer.balance)}}

    </ng-template>


text:
Q: Visual Studio Preview for Mac and Xamarin Mono 4 Issue I have been using Xamarin Studio on a Mac to write an app, and am sharing a lot of the code and projects with a Linux Mono project. For this reason I have to target the Mono / .NET 4.5 framework.
In the Mac project settings for target framework, Mono / .NET 4.5 is under "Unsupported Framework" and has a yellow caution symbol. I understand and accept this, since I need to also support Linux and the older Mono 4 framework.
However, I think Visual Studio preview for Mac changed my installed Mono runtime. When I opened the same project in VS4M, it gave an error:

could not find System.Runtime 4.0.0.0

I tried to run my project in Xamarin Studio and got the same error, but within a couple minutes received a notification to Xamarin. After updating, my app ran again.
I then opened VS4M to see if that worked, and now I get:

Could not launch Visual Studio
  This application requires a newer version (4.8+) of the mono framework.

Is there a better way to deal with this? I need to be able to build and debug this project in Linux using the open source Linux tools that are a bit out of date from Xamarin and apparently are not compatible.
Will downloading 4.8 Mono mess up Xamarin again?


text:
Q: How to implent week view calender in android? I want to implement a Week View Calender like the ones below. Another example may be the ICS Google Calender. The events will come from a database. So far i don't know where to start. Any ideas how i do this? Code and layout will be appreciated.

A: The calendar application that comes with stock android is open source. You can see the source code here. Getting a feel for this applications layout might be a good place to start.
Maybe you'll want to reuse some of this code.

A: Android Week View. can you use this Source code here


text:
Q: TFS database growing with builds We have a TFS 2013 server providing source control and build services. We recently turned on automated builds for our projects and we are finding that the database is growing very quickly with each build.
I understand that this version of TFS has added the option to output builds to the TFS server, in an un-version controlled location (http://nakedalm.com/new-un-versioned-repository-in-tfs-2012/)
We are only keeping the last two succesful builds, but it seems when we delete old builds we don't actually recover any space. I've been looking into it and it seems there is a destroy command I can use to delete old builds from the database, but I cannot find anything that mentions this injunction with the new TFS drop location.
Our builds were also applying labels, but I'm not sure if labels actually require any space, and whether that space is reclaimed after you delete an old label?
Is anyone able to point me in the right direction for this?
Thanks

A: Labels do not consume any significant space.

I understand that this version of TFS has added the option to output
  builds to the TFS server, in an un-version controlled location
  (http://nakedalm.com/new-un-versioned-repository-in-tfs-2012/)

This came from VSOnline, where your output could be stored back into source control, this is an available option in TFS2013 but only if you choose the Copy Build Ouput to Server option in the build defaults. Use a network share instead to store your build outputs, if you believe this is consuming too much space.
When you delete a build through the retention policy, most artefacts of the build will be deleted for example the drop folder, and you will no longer be able to see the build in the build screen, however this is only a logical delete and the records remain in the database but are flagged with a delete flag.
The Destroy command will physically delete the build from the system, it will be completely gone and all records will be removed from the DB, please bear in mind that TFS may not recover the space straight away, the TFSJob Agent will recover the space during its normal running process so you may not see the space recovered for 24 hrs +.
You can check the size of the test attachments table as you may find that your space is being consumed by test libraries etc that are being stored.
installing TFS Power tools will install the test attachement cleaner tool and running this will show you whether it is the test attachments that are consuming space. it has instructions for how to clean up the table and how to run a scheduled job to keep on top of the housekeeping

TFSBUILD Destroy example
  this will destroy all builds between 5/5/14 and 20/5/14 that have been deleted

tfsbuild destroy /collection:http://TFSServer:8080/tfs/TPC /dateRange:05/05/2014~20/05/2014 /buildDefinition:POC\zzz_DBSample
Microsoft (R) TfsBuild Version 12.0.0.0
for Microsoft Visual Studio v12.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Destroy build record for DEV_DBSample_1.0.14128.1 permanently? (Yes/No/All) y
Destroying DEV_DBSample_1.0.14128.1... Done
Destroy build record for DEV_DBSample_1.0.14128.2 permanently? (Yes/No/All) a
Destroying DEV_DBSample_1.0.14128.2... Done
Destroying DEV_DBSample_1.0.14128.3... Done
Destroying DEV_DBSample_1.0.14128.4... Done
Destroying DEV_DBSample_1.0.14128.5... Done
Destroying DEV_DBSample_1.0.14129.1... Done
Destroying DEV_DBSample_1.0.14129.2... Done
Destroying DEV_DBSample_1.0.14129.3... Done
Destroying DEV_DBSample_1.0.14134.1... Done
Destroying DEV_DBSample_1.0.14134.2... Done
Destroying DEV_DBSample_1.0.14135.1... Done
Destroying DEV_DBSample_1.0.14135.2... Done

note how the build definition name has changed since the builds were created and TFS still finds the correct records


text:
Q: How to read this symbol "$\varpropto$" in the following equation and what is its meaning? I stumbled upon the following equation in a research paper and I don't know how to read the symbol "$\varpropto$" in the context of the equation. Is it read "proportional to"? If so, what does it mean in the following equation?
$$p(e\mid a,f) = \frac{p(e,a,f)}{p(a,f)}\varpropto p(e\mid a)\cdot p(f\mid e,a)$$
I don't have any idea what "proportional to" would mean in the context of this equation if that is what the symbol "$\varpropto$" means here. Please clarify.

A: Yes, its means proportional to. Observe that:
\begin{align*}
\dfrac{p(e, a, f)}{p(a,f)} &= \dfrac{p(e,a)p(f \mid e,a)}{p(a,f)} \\
&= \dfrac{p(a)p(e \mid a)p(f \mid e,a)}{p(a,f)} \\
&= K \cdot p(e \mid a)p(f \mid e,a) \\
\end{align*}
where $K = \dfrac{p(a)}{p(a,f)}$ is a constant.

A: Hint:
Check out Bayes' theorem:
$$P(A\mid B) \propto  P(A) \cdot P(B\mid A) $$


text:
Q: Output only the first pattern-line and its following line I need to filter the output of a command.
I tried this.
bpeek | grep nPDE

My problem is that I need all matches of nPDE and the line after the found file.  So the output would be like:
iteration nPDE
1         1
iteration nPDE
2         4

The best case would be if it would show me the found line only once and then only the line after it.
I found solutions with awk, But as far as I know awk can only read files.

A: There is an option for that.
grep --help
...
  -A, --after-context=NUM   print NUM lines of trailing context

Therefore:
bpeek | grep -A 1 'nPDE'

A: With awk (for completeness since you have grep and sed solutions):
awk '/nPDE/{c=2} c&&c--'

A: grep -A works if your grep supports it (it's not in POSIX grep). If it doesn't, you can use sed:
bpeek | sed '/nPDE/!d;N'

which does the following:
/nPDE/!d # If the line doesn't match "nPDE", delete it (starts new cycle)
N        # Else, append next line and print them both

Notice that this would fail to print the right output for this file
nPDE
nPDE
context line

If you have GNU sed, you can use an address range as follows:
sed '/nPDE/,+1!d'

Addresses of the format addr1,+N define the range between addr1 (in our case /nPDE/) and the following N lines. This solution is easier to adapt to a different number of context lines, but still fails with the example above.
A solution that manages cases like
blah
nPDE
context
blah
blah
nPDE
nPDE
context
nPDE

would like like
sed -n '/nPDE/{$p;:a;N;/\n[^\n]*nPDE[^\n]*$/!{p;b};ba}'

doing the following:
/nPDE/ {                       # If the line matches "nPDE"
    $p                         # If we're on the last line, just print it
    :a                         # Label to jump to
    N                          # Append next line to pattern space
    /\n[^\n]*nPDE[^\n]*$/! {   # If appended line does not contain "nPDE"
        p                      # Print pattern space
        b                      # Branch to end (start new loop)
    }
    ba                         # Branch to label (appended line contained "nPDE")
}

All other lines are not printed because of the -n option.
As pointed out in Ed's comment, this is neither readable nor easily extended to a larger amount of context lines, but works correctly for one context line.


text:
Q: Index omits the associated page number for most index entries; this affects just one document For one document the page number is almost always missing from the index. This seems to be document-relevant, because correct indexing is possible for other documents. The TOC page numbering is correct and page numbers are present on each page.
I have repaired (Open and Repair) the associated document and repaired MS Office 2016 - there was no improvement.
I have deleted (and recreated) the index - there was no improvement.
I saved the document in Word 2003 format and recreated the index - there was no improvement.
Is there anything else I can try?
Partial index:

Here is a link to a sample document with the problem.

A: Compare the Index Field in a working document with the field that is not working.
Alt+F9 to toggle view of Field codes.
You can simply copy a working Index field from one document to another.
Here is my article on the Microsoft site on working with fields.


text:
Q: Why are database links bad for security? I heard database links are bad for organizations to use. Why is it bad for security?

A: Where did you hear this?
Database links, like any tool, have their uses and misuses.  There is nothing inherently insecure about using a database link.  But there are certainly plenty of ways to architect a system using database links that is insecure.
A database link lets you connect one database to another.  Broadly speaking, you can define the database link so that it connects to the remote database as a specific fixed user on the remote database or you can define the database link so that it connects to the remote database as the current user.  Those configurations have different issues.
If you use a fixed user, you have to be careful that the users that can access the local database link ought to have access to whatever privileges the remote database user has.  If you use a relatively powerful account to create the database link but then give access to that link to relatively low-privilege users, that can certainly be a security issue.  It can also be challenging to identify situations of concern where this has taken place because no single database has the whole picture.  If user Bob on database A has read-only access to a couple of tables but there is a public database link on A that connects to database B as a highly privileged user, someone that compromises Bob's account the ability to execute commands on B as that highly privileged user.  Of course, you can mitigate these issues by not creating database links as highly privileged users, taking care when creating public database links, creating private database links when the fixed user is going to have privileges that you don't want to grant to everyone, etc.
If you use current user database links, then the user Bob on database A connects to database B as Bob and has whatever privileges Bob does on database B.  In general, that is likely to be easier to secure.  It's at least much harder to unintentionally do something stupid.  The downside to this approach, however, is that Bob would need to keep his password synchronized on both databases or the database link won't work.  That generally involves developing a bit of infrastructure to allow Bob to reset his password on all databases (or use some sort of external authentication) which is a bit of work to set up and maintain.  Occasionally, it will also limit what security measures the DBA can configure when you have a mixed environment.  When you upgraded database A to 11.2, for example, you probably wouldn't want to enable case-sensitive passwords until database B was similarly upgraded.  If you have lots of database links between lots of systems on very different upgrade schedules, this sort of thing might be concerning.

A: Some years back there was a significant bug where the "System Change Number" could be pushed ahead on a database and this would follow through to any database connected via a database link, resulting in a cascade of failures. Depending on how risk averse the organisation is, it can be a sensible precaution to keep databases isolated from each othe and reduce the effect of any 'outbreak'.
"Where this vulnerability gets interesting is that the SCN is synchronized to the highest SCN when two databases are connected via a database link.  Therefore, it is possible to increase a database to the near maximum SCN through a database link, which will cascade through to all other interconnected databases.  The result can be ORA-600 errors and potentially database crashes on the database with the lower SCN."
https://www.integrigy.com/oracle-security-blog/critical-oracle-database-bug-system-change-number-scn-cve-2012-0082


text:
Q: O que tem de errado no CSS que faz esse comportamento estranho entre os dois SOs? Estou tentando resolver um problema de desalinhamento no layout, que no Windows 10, com o Chrome mais recente ele muda o padding da altura de um botão. Este botão fica certinho no Mac OS Mojave, utilizando a mesma versão do Chrome, observe entre as imagens, a diferença:
Mac:

Windows:

.item-descritores {
    display: -webkit-flex;
    flex-wrap: wrap;
    -webkit-flex-wrap: wrap;
    justify-content: center;
    -webkit-justify-content: center;
    text-align: center;
    margin: auto -6% auto -6%;
    position: relative;
    z-index: 200;
}
.selo-descritores {
    padding: 7px 10px 3px;
    background: #d8d8d8;
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
    text-align: center;
    font-size: 15px;
    font-weight: bold;
    margin: 4px;
    color: #777;
    border: none;
}

button {
   -webkit-writing-mode: horizontal-tb !important;
   text-rendering: auto;
   color: buttontext;
   letter-spacing: normal;
   word-spacing: normal;
   text-transform: none;
   text-indent: 0px;
   text-shadow: none;
   display: inline-block;
   text-align: center;
   align-items: flex-start;
}
* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
<div class="item-descritores"  style="">
   <button data-toggle="tooltip"  title="" class="selo-descritores" style="">EF15LP03</button>
</div>


text:
Q: Why does the jquery selector ("id,id") selects all elements with duplicate IDs I came across some year old code written by a good developer (yes, I knew him personally) to access all elements having the same id.
$("#choice,#choice")

It returns all elements having the id. But if we use the below
$("#choice")

It returns only the first match, as expected.
After searching for some time, I'm unable to figure out any official links pointing to his technique, as to how it selected all elements with duplicate id.
Can anyone please explain how is this working ?
UPDATE
Please see the question is not about what alternative to use. I'm aware of classSelectors and attributeSelectors and know having duplicate IDs is not recommended, but sometimes you just have to live with years old code the way it is (if you know what I mean).
http://jsbin.com/zodeyexigo/1/edit?html,js,output

A: Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a tag selector, like this:
$('span[id="a"]');

A: If you look at the code of sizzle.js that jQuery uses for selecting elements based on selector you will understand why this happens. It uses following regex to match simple ID, TAG or class selector:
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

but as the selector in question is $("#ID,#ID") it does not match with the selector and uses querySelectorAll (line no 270 in ref link), which replaces selector to "[id='" + nid + "'] " (line no 297 in ref link) which selects all the elements with matching ID.
However, I agree with the other people in this thread, that it is not good idea to have same ID for multiple elements.

A: So in JS Fiddle i have shown an example of what jQuery is doing.
https://jsfiddle.net/akp3a7La/
When you have a
$('#choice,#choice');

It is actually getting all the instances of the objects #choice twice, and then filtering out any duplicates.
in my example i show you how it does that also when you have something like this
$("#choice,li");

Where
* items are actually your #choice items.
In the Jquery Documentation
https://api.jquery.com/multiple-selector/
it talks about multiple Selectors, which is what i think is happening here, your developer friend is selecting the same ID twice, and it would be returning it twice. as you can only have one input with the same ID once on a page (good html syntax)

A: Having duplicated id on the page making your html not valid . ID is unique identifier for one element on the page (spec). Using classes, that are classify similar elements that's your case and $('.choice') will return set of elements


text:
Q: Nothing happens after submitting an POST via requests I am at the stage of a beginner in requests. I can login to the website but I can't add a new post through this query. After sending the query, it redirects me to the page with adding a post as if my query was incorrect.
Inspect via Chrome Inspector
**General:**
Request URL: https://www.example.com/add-post.php?&at=1&c1=15&c2=101
Request Method: POST
Status Code: 302 Moved Temporarily
Remote Address: some adress
Referrer Policy: strict-origin-when-cross-origin

**Response Headers:**
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: keep-alive
Content-Type: text/html; charset=iso-8859-2
Date: Thu, 03 Nov 2022 09:57:02 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Location: thanks-page.php?post_id=2004616354
Pragma: no-cache
Server: nginx
Set-Cookie: adata=a4%2FZVWigSkJytx%2BRt9aXm%2BKCnwc3SzBQcgLu4PyP9DFJBIq7%2B%2F0ehdH9ow0fBLHi; expires=Tue, 02-Nov-2027 09:57:02 GMT; Max-Age=157680000; path=/; domain=.site.com; SameSite=Lax
Transfer-Encoding: chunked
X-Powered-By: PHP/5.6.40-0+deb8u12

**Request Headers:**
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 2100
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarySzQAwauzwPfQBOaX
Cookie: PHPSESSID=c0c0ea5f8e8a82582e1b3e5eb964cddf; uubcide=g9QOB6mvx%2B0dHbJgw3SaYAKWTmt1cvywGccppGWvXGWdtY2GkUmXJEHJtHZGHuwR; cookies_refresh={"http":1667469177376,"https":1667469177376}; exo_zones=%7B%7D; auc_st=1; auc=rqeIZr2vtE5hBH6lJ41wpBGN%2BEirS6dZeDsUk11ypfkoFrTSeLZJbA8e1esRaHVNlkeiOrk%2BVmvEgAs4sISGww%3D%3D; push_ref_id=KhSfLz6diDUQM0bLUCOlKQF%2BRtn0MCbN5O%2BvQY8DmGi2IQaYClTRdU%2FXMbk%3D; usrsdata=nBXAJp5iGAv%2BkjmLNtN4cNjh3iZ2FAGadDLuMMH%2FFxM%3D; last_user_id=113579; cookiesinfo=2; disablecontentwarning=1; ucons=1%3B1%3B1%3B1%3B1; push_prompt_n=1; push_prompt_skip=1; adbinf=3; nth_pageview=12; mp_7ccb86f5c2939026a4b5de83b5971ed9_mixpanel=%7B%22distinct_id%22%3A%20%221843ce860a563c-019f36c53cee3e-162d1e0a-1aeaa0-1843ce860a669f%22%2C%22%24device_id%22%3A%20%221843ce860a563c-019f36c53cee3e-162d1e0a-1aeaa0-1843ce860a669f%22%2C%22site_type%22%3A%20%22similarweb%20extension%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D
Host: www.example.com
Origin: https://www.example.com
Referer: https://www.example.com/add-post.php?&at=1&c1=15&c2=101
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Sec-GPC: 1

**Multipart**
------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="post_category"
11

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="ad_post"
1

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="post_title"
This is a title, minimum 5 chars

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="desc"
This is the content of the post that will be added, it should contain a minimum of 80 characters

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="contact_name"
TechManiac

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="phone"

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="email"
email@gmail.com

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="post_photos"
0

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="filename"; filename=""
Content-Type: application/octet-stream

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="submit_adv"
1

------WebKitFormBoundarySzQAwauzwPfQBOaX
Content-Disposition: form-data; name="submitbutton"
Add Post

Based on the things found in the documentation and on our forum, I tried to create a code that would be as similar as possible to the data that is sent in the query post
import requests
from requests_html import HTMLSession

the_data = {"email": "email", "pass": "password"}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
headers_post = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryOT1glP4vf8Tw3w7o',
'Host': 'www.example.com',
'Origin': 'https://www.example.com',
'Referer': 'https://www.example.com/add-post.php?&at=1&c1=15&c2=101',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-User': '?1',
'Sec-GPC': '1',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
}

url = 'https://www.example.com/index.php?s=login'
session = HTMLSession()
s = session.post(url, data=the_data, headers=headers)
#logged in correctly

files = {
    'post_category':(None, '11'),
    'ad_post':(None, '1'),
    'post_title':(None, 'This is a title, minimum 5 chars'),
    'desc':(None, 'This is the content of the post that will be added, it should contain a minimum of 80 characters'),
    'contact_name':(None, 'TechManiac'),
    'phone':(None, ''),
    'email':(None, 'email@gmail.com'),
    'post_photos':(None, '0'),
    'filename':(None, ''),
    'submit_adv':(None, '1'),
    'submitbutton':(None, 'Add Post')
}
req = session.post('https://www.example.com/add-post.php?&at=1&c1=15&c2=101', files=files, headers=headers_post)

After executing this code, looking at the source of the page that is displayed to me (print(req.text)) in the console, it redirects me to https://www.example.com/add-post.php?&at=1&c1=15&c2=101 and not to the thank you page, as if no post was sent or added.
Where i should search the problem? Maybe problem is in:
Content-Disposition: form-data; name="filename"; filename=""
Content-Type: application/octet-stream

In my code is only:
'filename':(None, '')

But i dont know how to do that correctly.
Maybe problem is in cookies or redirect?
Also try:
req = session.post('https://www.example.com/add-post.php?&at=1&c1=15&c2=101', files=files, headers=headers_post, allow_redirects=False)

if req.status_code == 302: # expected here
    jar = req.cookies
    redirect_URL2 = req.headers['location']
    req2 = session.get(redirect_URL2, cookies=jar)

But nothing happened as it print code 200 and skips waiting for that 302.
Has anyone dealt with a similar situation and can help, based on the code, what to do and what to pay attention to, that through google inspector everything works and is very similar and not in the python code?
Thanks :)
Edit*
Probably the bug is in the query because it redirects me to the posting page - like something is missing?


text:
Q: Get the web page content using Angular 2 and Http object Im new in Angular 2 framework and I try tu understand Http object.
Im following the tutorial here:
http://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/
Its perfect to retrieve JSON file from a server that provide this kind of data but I want to retrieve the HTML content into a variable. I would like to have all the html file and parse it to get some informations.
When I modify the URL in the example by a website like this:
this.http.request('https://www.google.ca/' ).map(res => res.text()).subscribe(data => {
    this.webPage = data.toString();
    console.log("data:" + data );
});

I got this error:

EXCEPTION: Response with status: 0  for URL: null

Do I use the good API?
What im doing wrong?
Thanks,
Pat

A: This is a CORS problem.
The full error is:
XMLHttpRequest cannot load https://www.google.ca/.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://run.plnkr.co' is therefore not allowed access.
EXCEPTION: Response with status: 0  for URL: null

You cannot request 'https://www.google.ca/' because: 1) when you make a http request in your app, the origin is already defined as your host, could be 'localhost' or your site's host. 2) 'www.google.ca' is another origin, and it has no 'Access-Control-Allow-Origin' set, or you site's host is not in their 'Access-Control-Allow-Origin' list.
If you want the html of 'www.google.ca', you need a proxy server, and the steps are: 1) in your ng2 app, you send a request to proxy server and ask it to do ... 2) you proxy server request 'www.google.ca' and send the html to your ng2 app.
When the proxy server request 'www.google.ca', the origin is defined as 'www.google.ca'. So the proxy server can get the html.


text:
Q: Using Scanner in Java how can I hasNext(aString) where the string is not regex pattern? I am trying to do as my question states, sooo I have the following code which would find the match.

String test = scan.next();
if (test.equals("$let"))
 return 1;

However, I would prefer to use hasNext as to not consume a token; however, when i do the following it fails.

if (scan.hasNext("$let"))
 return 1;

I realize the when giving has next a variable it expects a pattern, but I thought if i don't have any regex symbols it should work. I also thought $ was possibly some regex symbol so I tried /$ however, that did not work!
Thanks for the help!

A: You should use \\$ to escape the regex, but it's easier to just get the next() and save the result.

A: In general, if you have some arbitrary string that you want to match literally with no meanings to any regex metacharacters, you can use java.util.Pattern.quote.
Scanner sc = new Scanner("$)}**");
System.out.println(sc.hasNext(Pattern.quote("$)}**"))); // prints "true"
System.out.println(sc.hasNext("\\Q$)}**\\E")); // prints "true"
System.out.println(sc.hasNext("$)}**")); // throws PatternSyntaxException

You can also use the \Q and \E quotation markers, but of course you need to ensure that the quoted string must not itself contain \E.


text:
Q: Django pagination - 5k objects As a continuation of this question Django pagination with bootstrap any my works under my Contacts app I have to ask for your help once more. I have a problem I cannot resolve. I used few suggestions about pagination but all that is changing is the bottom pagination menu. My app is still loading all 5k objects every time, over and over. I am new at this, this app is my first project and this is the final 'big' missing part. I promiss to post final cone when I'm done :)
Best regards.
views.py
def index(request):

    contacts_list = contacts.objects.all()
    contacts_filter = LFilter(request.GET, queryset=contacts_list)

    paginator = Paginator(contacts_list, 50)
    try:
        page = int(request.GET.get('page','1'))
    except:
        page = 1
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)

    index = contacts.number - 1
    max_index = len(paginator.page_range)
    start_index = index - 3 if index >= 3 else 0
    end_index = index + 3 if index <= max_index - 3 else max_index
    page_range = paginator.page_range[start_index:end_index]

    return render(
        request, 'index.html',
        context={'filter': contacts_filter,
                'contacts': contacts,
                'page_range': page_range, }
                )`

index.py
{% for obj in filter.qs %}
    Code for contact information to display
{% endfor %}

    {% if contacts.has_previous %}
        Prev
    {% endif %}
    {% if contacts.has_next %}
        Next
    {% endif %}

        {% for pg in page_range %}
            {% if contacts.number == pg %}

{{pg}}

            {% else %}

{{pg}}

            {% endif %}
        {% endfor %}


text:
Q: How does the website know my timezone though I am using vpn I am using a vpn. My web browser is chrome.
When registering to a particular site, I gave a different location. The site gives me a notification every 10PM. The problem is it is giving notification in my local time not in the time-zone from which I have registered to the site.
The permission that are allowed to the site are
Motion sensors
JavaScript
Images
Background sync
Payment Handlers

No, Permission for Location is not allowed.
How does the site know my local time-zone though I am using a vpn.
Can a web browser take time from the machine and send it to the server via HTTP header or something?
What is going on here?
P.S. Just to be clear, it is not a browser notification which is allowed by Notifications in chrome browser. It is like stackoverflow notification (top right of the browser windows). One more thing, I access that site from a linux desktop and not a mobile device. Not sure, what that Motion sensors permission is doing there in my desktop.

A: I may be missing something, but if you press F12 in your browser, and type this:console.log(`Time offset is ${-new Date().getTimezoneOffset()/60} hours`);, you can see your time offset, and if you type console.log(new Date());, you can see your current time.
That information can be sent when you're logging in.

document.getElementById('current-time').innerText = `Current date: ${new Date}\nTime Offset: ${-new Date().getTimezoneOffset()/60} hours`;
<div id="current-time">
</div>

EDIT:
Time zone offset code is adapted from this answer.


text:
Q: directory listing in python I am getting trouble with directory listing.Suppose, I have a directory with some subdirectory(named as a-z, 0-9, %, -).In each subdirectory, I have some related xml files.
So, I have to read each lines of this files.I have tried with the following code.
def listFilesMain(dirpath):
    for dirname, dirnames, filenames in os.walk(dirpath):
        for subdirname in dirnames:
            os.path.join(dirname, subdirname)
        for filename in filenames:
            fPath = os.path.join(dirname, filename)
            fileListMain.append(fPath)

It works only if I tried to run my program from subdirectory, but no results if I tried to run from main directory. What's going wrong here?
Any kind of help will be greatly appreciated. Thanks!

A: How about this:
def list_files(dirpath):
    files = []
    for dirname, dirnames, filenames in os.walk(dirpath):
        files += [os.path.join(dirname, filename) for filename in filenames]
    return files

You could also do this as a generator, so the list isn't stored in its entirety:
def list_files(dirpath):
    for dirname, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            yield os.path.join(dirname, filename)

Finally, you might want to enforce absolute paths:
def list_files(dirpath):
    dirpath = os.path.abspath(dirpath)
    for dirname, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            yield os.path.join(dirname, filename)

All of these can be called with a line like:
for filePath in list_files(dirpath):
    # Check that the file is an XML file.
    # Then handle the file.

A: if your subdirectories are softlinks, make sure you specify followlinks=True as an argument to os.walk(..). From the documentation:
    By default, os.walk does not follow symbolic links to subdirectories on
    systems that support them.  In order to get this functionality, set the
    optional argument 'followlinks' to true.


text:
Q: Data Annotation model validation for Required attribute In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through.
    public async Task<ActionResult> IsAccountClosed([Required] string nric)
    {
      // code removed for brevity
    }

A:
In my web api project, I have this code which uses Data Annotation Required attribute to validate. But when I test it using Postman, it can still go through?

The [Required] attribute allows you to use ModelState.IsValid construct. As model binding and model validation occur before the execution of a controller action or a Razor Pages handler method.it's the app's responsibility to inspect ModelState.IsValid and react appropriately. So you should use ModelState.IsValid inside then it would act what you are expecting.
Controller
public async Task<ActionResult> IsAccountClosed([Required] string nric)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            return Ok();

        }

Note: It should also work even you don't use ModelState.IsValid attribute because model validation executes before the controller being executed.
Output:


text:
Q: How to eliminate duplicate code multiple service calls I have a DataService which returns an observable with different api call, I need to reuse the below block and call in each http request.
export class DataService {
  constructor(
    private http: HttpClient,      ) {}

  fetchWind(): Observable<ModelClass> {
    return this.http
      .get<StaticDataElements>(Wind_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
      }

  fetchEmission(): Observable<ModelClass> {
    return this.http
      .get<ModelClass>(Emission_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
  }

  fetchSolar(): Observable<ModelClass> {
    return this.http
      .get<ModelClass>(Solar_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
  }

Here is the duplicate code for each service call need to write one function to pass the request url and get the response and error. Here solar, wind, emissiom have same code repeated in three http calls other than url, response, error
 return this.http
          .get<ModelClass>(Solar_REQUEST_URL)
          .pipe(
            tap(
              response => response,
              error => this.handleError(error, 'Service_Failure')
            )
          );

A: if you mean avoid repeating this lines:
.pipe(
    tap(
      response => response,
      error => this.handleError(error, 'Service_Failure')
    )
  );

then, write a method like this:
getRespons<T>(url:string){
     return this.http
          .get<T>(url)
          .pipe(
            tap(
              response => response,
              error => this.handleError(error, 'Service_Failure')
            )
          );
}

and use it in this way:
fetchSolar(): Observable<ModelClass> {
    return this.getRespons<ModelClass>(Solar_REQUEST_URL);
}

A: One strategy to reducing duplicate code is to simply expose an observable that can be subscribed to.
In your data service you can add the following changes:
export class DataService {
  solarData$: Observable<ModelClass>;

  constructor(
    private http: HttpClient,      ) {
    this.solarData$ = this.fetchSolar();
  }

  fetchWind(): Observable<ModelClass> {
    return this.http
      .get<StaticDataElements>(Wind_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
      }

  fetchEmission(): Observable<ModelClass> {
    return this.http
      .get<ModelClass>(Emission_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
  }

  fetchSolar(): Observable<ModelClass> {
    return this.http
      .get<ModelClass>(Solar_REQUEST_URL)
      .pipe(
        tap(
          response => response,
          error => this.handleError(error, 'Service_Failure')
        )
      );
  }

Then in each of your components.
export class MyComponent implements <whatever> {

  constructor(private dataService: DataService) {}

  //in some method
  foo() {
    componentData$ = this.dataService.solarData$; // or subscribe and stuff
  }
}


text:
Q: ¿como puedo meter los nombres de los ficheros en un arreglo en la funcion recursiva? Con esta función puedo recolectar los nombres de los ficheros, ¿como puedo meterlos a un arreglo?
Codigo para leer archivos:
(on create)
 final File carpeta = new
File("/storage/emulated/0/Android/data/cc.openframeworks.androidMultiOFActivitiesExample/files/pics");

 listarFicherosPorCarpeta(carpeta);

public void listarFicherosPorCarpeta(final File carpeta) {
    for (final File ficheroEntrada : carpeta.listFiles()) {
        if (ficheroEntrada.isDirectory()) {
            listarFicherosPorCarpeta(ficheroEntrada);
        } else {
            System.out.println(ficheroEntrada.getName());

        }

    }

}

Esto es lo que estoy intentando pero me marca error:
  List<String> list = new ArrayList<String>();

public void listarFicherosPorCarpeta(final File carpeta) {
    for (final File ficheroEntrada : carpeta.listFiles()) {

        if (ficheroEntrada.isDirectory()) {
            listarFicherosPorCarpeta(ficheroEntrada);
        } else {
            System.out.println(ficheroEntrada.getName());

           for(int i=0; i< ficheroEntrada.length(); i++)
               list.add(ficheroEntrada[i].getName());

        }
    }
}

Esta parte me marca error:
   list.add(ficheroEntrada[i].getName());

A: Tu método recursivo para leer los archivos en un directorio es correcto, solo necesitas almacenar los nombres en el ArrayList,
List<String> list = new ArrayList<String>();

public void listarFicherosPorCarpeta(final File carpeta) {
    for (final File ficheroEntrada : carpeta.listFiles()) {
        if (ficheroEntrada.isDirectory()) {
            listarFicherosPorCarpeta(ficheroEntrada);
        } else {
            System.out.println(ficheroEntrada.getName());

            //Almacena nombres de archivos a lista.
            list.add(ficheroEntrada.getName());
        }

    }
}

Ahora para obtener el array simplemente convierte el list en el cual se almacenaron los nombres de archivo a un array:
final File carpeta = new
File("/storage/emulated/0/Android/data/cc.openframeworks.androidMultiOFActivitiesExample/files/pics");
 listarFicherosPorCarpeta(carpeta);

 //Convierte la lista en un array de Strings.
 String[] ficheros = list.toArray(new String[list.size()]);

 //Imprime nombres almacenados.
 System.out.println("archivos almacenados: " + Arrays.toString(ficheros));


text:
Q: Derivatives of parametric curve Given the curve $x = t^3 + 3t + 1 ,  y = t^2 + 4t - 4$
A. Find $\frac{dy}{dx}$ in terms of $t$.
B. Find $\frac{d^2y}{dx^2}$ in terms of t
I need help answering those please.
For A). the answer I got is $\frac{4}{3t}$ I'm not sure if it is correct.

A: Need to use chain rule and quotient rule to get these derivatives.
$x = t^3 + 3t + 1 , y = t^2 + 4t$
$\frac{dx}{dt}$ = $3t^2$+3
$\frac{dy}{dt}$ = 2t+4
$\frac{dt}{dx}$ =$\frac{1}{3t^2+3}$
$\frac{dy}{dx}$ =$\frac{dy}{dt}$$\frac{dt}{dx}$=$\frac{2t+4}{3t^2+3}$
$\frac{d^2y}{d^2x}$ =$\frac{d\frac{2t+4}{3t^2+3}}{dt}$ $\frac{dt}{dx}$
=$\frac{2(3t^2+3)-(2t+4)(6t)}{(3t^2+3)^3}$ =  $\frac{-2t^2-8t+2}{9(t^2+1)^3}$


text:
Q: Mongoose Model.create and bluebird promises I'm unable to use bluebird promise functions (catch, spread, each) with chains that start with a Model.create() promise. I'm currently on mongoose 4.1.0 with bluebird 2.9.34. Everything works fine if I use .save()
Is there a workaround for this right now?
Thanks