text:
Q: How to use Cloudflare's free SSL to force https on my Django application on Apache+mod_wsgi stack? I wanted to use the free SSL (DNS) service provided by Cloudflare in my Django Application running on Apache + mod_wsgi stack. I can find setup examples for Nginx + uWSGI stack, but not for Apache + mod_wsgi stack so far. I was following this answer here https://stackoverflow.com/a/27650503/2051292 . But I couldn't convert the workaround from Nginx configuration to Apache/mod_wsgi. I'm facing few problems,

*

*Even I use https to visit the web pages clicking on any of the internal links or submitting login/registration forms goes only to http pages.
(I actually want all the links to goto the https pages)

*On the web page forms (login, registration) I'm getting CSRF Failed 403 Access Forbidden error. And I login at https page, but after verification the redirects to a http page with CSRF error.

*Sometimes tweaking the configuration leads to redirect loop.
Would like to know the working configuration for using cloudflare free SSL with Apache + mod_wsgi stack and the Django settings also for the setup
EDIT: In case if you don't know, this is how Cloudflare's free SSL works.

I don't have an SSL certificate with me, I'm trying to use the free SSL by using the Flexible SSL. i.e. The connection from user to Cloudflare DNS will be https and the connection between Cloudflare and my server will be http.
Note: Currently I'm NOT using any middleware like django-sslify . But using it will help any other way. I'm okay with that also.

A: While I don't know the specifics of using Cloudflare, it should be the same Apache configuration once you have the appropriate certificates nave figured out the proxy settings mentioned in the other answer. Here's an example Apache configuration I have used for hosting Django with mod_wsgi and mod_ssl under CentOS. Under this configuration, we don't even listen to port 80. This assumes your web site is hosted at https://example.com/mysite, and that it is deployed to /var/www/html/mysite under the user mysiteuser with a virtualenv called mysitevenv:
LoadModule wsgi_module modules/mod_wsgi.so
LoadModule ssl_module modules/mod_ssl.so

WSGISocketPrefix /var/run/wsgi

NameVirtualHost *:443
Listen 443
<VirtualHost *:443>

  ServerName example.com
  ErrorLog /home/mysiteuser/apache_errors.log

  WSGIDaemonProcess mysite-https python-home=/home/mysiteuser/.virtualenvs/mysitevenv
  WSGIScriptAlias /mysite /var/www/html/mysite/mysite/wsgi.py process-group=mysite-https application-group=mysite-https
  WSGIProcessGroup so-https
  Alias /mysite/static/ /var/www/html/mysite/static/

  SSLENGINE on

  SSLCertificateFile /etc/pki/tls/certs/localhost.crt
  SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
  SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
  SSLProtocol all -SSLv2
</VirtualHost>


text:
Q: Difference between "opacity" and "opaqueness" What is the difference in the meaning und usage of the words opacity and opaqueness?

A: Not entirely a new answer; I'd like to modify the idea provided by @tchrist:

opaqueness — the state or fact of being opaque.
  opacity — The degree of being opaque.

This material is not suitable due to its opaqueness.
This material is not suitable because of its high opacity.

A: "Opacity" is usually used in technical contexts, and invokes a nuance of it being a measurable quantity. "Opaqueness" is normally used when speaking colloquially, and can also be used metaphorically to mean "incomprehensibility resulting from obscurity of meaning" (Mirriam-Webster). To that end, it would sound strange to give an actual measurement of "opaqueness". For example:

This fluid has an ?opaqueness of 40 square meters per kg.

This sentence sounds strange.

This fluid has an opacity of 40 square meters per kg.

This is correct.

A: Opacity is a measure of light blocking (non-penetration) by a material.
It can go from 0% (transparent; no blockage) to 50% (translucent; partial blockage) to 100% (opaque - complete blockage).
By definition, opaque means light cannot penetrate (100% opacity).  If light could even partially penetrate, it would be translucent, not opaque.
So opaqueness is the state or condition of being opaque (no light can pass through).  Opacity is a measure of how much light cannot pass through.

A: The difference between the two is more one of actual use than one of nuance.  For simple meaning, the OED provides:

*

*opaqueness — the quality of being opaque; opacity.

*opacity — The quality or fact of being opaque; opaqueness.

The earliest citation given for opaqueness  in English is 1647, and that of opacity is 1611.  Opacity is a French loanword, or was.  It comes from

French opacité (15-16th c. in Hatz.-Darm.), ad. Latin opācitās, f. opācus opaque.

Whereas opaqueness was formed simply by adding the normal English derivational suffix -ness to the existing word opaque.  Opacity has several senses and subsenses listed in the OED, while opaqueness has only the one I have provided above.
But as I said, the real difference is how often each is used relative to the other. This Google N-Gram shows that in actual printed use, opacity is favored over opaqueness by a favor of around 15 to 1:

Although these words aren't normally made into plurals, they can be, and sometimes must be.  Here the comparative euphony of opacities over the Gollum-like opaquenesses wins hands down in this other Google N-Gram:

In actual examples, here are the first three recent usage citations obtained by those N-Grams, first for opaquenesses:

*

*It involves the acceptance of others by means of an indifference to, or neglect of, their differences, of all the opaquenesses and knobby protrusions that make it diflicult to swallow their souls into one's own.  [citation]

*He and Kistin had visited the hospitals once and seen briefly the doctorless, nurse- less place where those returning from enclayment were given a chance to cure themselves of the dreadful opaquenesses caused by lying, stealing, false pride, and the like. [citation]

*Blackmur acquired great influence as a critic because he tackled the difficulties and opaquenesses of such modern poets as Yeats, Eliot, Stevens and Hart Crane head-on in a commentary that was subtle, discriminating, illuminating and ... [citation]
And then for opacities:

*

*The opacities are classified according to the diameter of the predominant opacities: [citation]

*In this system, the size, shape, and profusion of opacities on the radiographs of patients with penumoconiosis are classified in a detailed fashion by trained observers, using a set of standard radiographs. [citation]

*Large capacities (greater than 1 cm in diameter) correspond to lesions of complicated pneumoconiosis (progressive massive fibrosis) and are classified into categories—A, B, and C—depending on their size. [citation]
In summary, I would strongly recommend using opacity over opaqueness.

A: I'd like to add this thought. While I heartily agree that opacity is highly preferable to opaqueness, I ended up on this page because I was concerned that the particular audience for which I'm writing at the moment might stumble over opacity or not catch the meaning at all, where the point of the sentence is to harshly criticize the addressee for deliberately making a process opaque for the purpose of concealing cheating.  The concept has to leap off the page and smack the reader up side the head to achieve its greatest effect.
I've never thought about when "-icity" should be used and when "-ness" would be proper.  Considering it now based on my own use and experience without any investigation, it seems to me that it may be as simple as whether 1) one of them grates on the ear, or b) adding "-icity" makes the noun too dissimilar from the adjective for the relation to be clear, or even to be recognizable at all.  Consider opaque and unique.  I may be mistaking familiarity for connection as to opaque and opacity, but unicity for unique definitely doesn't work.

A: I use opacity as a parameter between 0 and 100%, when describing the degree of transparency of something, most often web markup. For example, opacity = 0.2 would be very close to transparent, or "see through". A more typical value for my purposes is opacity = 0.8 which is only slightly transparent. Of course, a value of 1.0 or 100% means totally opaque, solid, not gauzy or translucent at all.
Opaqueness is more familiar to me as word used for prose communication, rather than webpage design. Although the word is legitimate, I don't find it easy to use in context. It seems more idiomatic to describe something as "more opaque" or "less opaque", although an example of usage of would be to say something had "an aspect of opaqueness to it".

A: The difference in use is that you would use opacity to refer to understanding, when something is difficult to understand or obscure.
opacity, n.
a. Obscurity of meaning; resistance to interpretation; impenetrability; an instance of this. rare before 20th cent.
or
opacity
noun
the quality of lacking transparency or translucence:
thinner paints need black added to increase opacity
the quality of being obscure in meaning:
the difficulty and opacity in Barthes' texts
Opaqueness is the noun to the adjective opaque, and would be used to describe the extent to which something is opaque, or able to transmit light.
opaque
A. adj.
2.
a. Not transmitting light, not transparent or translucent; impenetrable to sight. Also fig.
or
Definition of opaque
not able to be seen through; not transparent:
bottles filled with a pale opaque liquid
(especially of language) hard or impossible to understand:
technical jargon that was opaque to her
Used figuratively, in an understanding = seeing the light sort of way, the two words can become very similar, as shown particularly by the Oxford Dictionaries entries.
Opacity also has several technical uses. As pointed out by several posters, it is used in programming. It is wrong to imagine that language exists only for programmers though - opacity also has a technical use in physics, and in linguistics, and in photography, and in the paint industry, and probably others that I am unaware of. For these localised uses it is probably better to ask in the appropriate forums.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Higher homotopy groups in terms of the fundamental groupoid Let $X$ be a topological space. Then we can construct the following structure. Let an $n$-morphism be a map $I^n\to X$. We can view $n+1$ morphisms exactly as homotopies between $n$-morphisms.
Let $f,g$ and $h$ be $n$-morphisms and $H$ and $G$ be homotopies from $f$ to $g$ and from $g$ to $h$ respectively. Then we define $G\circ_{n+1}H$ to be the homotopy from $f$ to $h$ defined by
$$G\circ_{n+1}H(x_1,\dots,x_n,x)=
\begin{cases}
H(x_1\dots,x_n,2x)\;\;\;\;\;\,\text{ if $x\in\left[0,\frac{1}{2}\right]$}\\
G(x_1\dots,x_n,2x-1)\text{ if $x\in\left[\frac{1}{2},1\right]$}
\end{cases}$$
It is easy to see that $\circ_n$ is associative and for every $n$-morphism f, there is the trivial homotopy with itself $\text{id}_f$. So we see that for every $n\geq0$, we have a category with objects as $n$-morphisms and arrows as $n+1$-morphisms.
Then we can define the map $\bar{H}\colon I^{n+1}\to X$ as $\bar{H}(x_1\dots,x_n,x)=H(x_1\dots,x_n,1-x)$. Then $\bar{H}$ is a homotopy from $g$ to $f$. Then composite $\bar H\circ_{n+1}H$ homotopy fromm $f$ to itself is defined by
$$\bar H\circ_{n+1}H(x_1,\dots,x_n,x)=
\begin{cases}
H(x_1\dots,x_n,2x)\;\;\;\;\;\,\text{ if $x\in\left[0,\frac{1}{2}\right]$}\\
H(x_1\dots,x_n,2-2x)\text{ if $x\in\left[\frac{1}{2},1\right]$}
\end{cases}$$
Define $\alpha$ to be the homotopy ($n+2$-morphism) from $\text{id}_f$ to $\bar H\circ_{n+1}H$ defined by
$$
\alpha(x_1,\dots,x_n,x,t)=
\begin{cases}
H(x_1,\dots,x_n,2tx)\;\;\;\;\;\;\;\;\;\,\text{if $x\in\left[0,\frac{1}{2}\right]$}\\
H(x_1,\dots,x_n,2t(1-x))\;\text{if $x\in\left[\frac{1}{2},1\right]$}
\end{cases}
$$
So we see that for every $n+1$-morphism, there is 'weak' inverse. So This is in some sense, a weak $\infty$-groupoid.
Now, we choose a point $x_0$. This is a $0$-morphism. So, we can look at $\text{Hom}(x_0,x_0)$ (set of $1$-morphisms from $x_0$ to $x_0$). Now, we can formally turn all the higher weak equivalences into equalities (by quotienting by this hom-set by the appropriate relation). Then, the group left over is nothing but $\pi_1(X,x_0)$.
My questions then are

*

*We can perform an equivalent process at higher levels. That is, choose an $n$-morphism and turn all the $n+2$-morphisms into strong equivalences. Then we have the group $\text{Hom}_{n+1}(f,f)$ ($n+1$ automorphisms of $f$ identified upto equivalence). Are these groups classically interesting? Do they have good properties (under homotopy equivalnce, for example)?

*Can we describe higher homotopy groups in terms of this weak $\infty$-groupoid?

A: From your definition, it's really not clear what groups you're referring to. That's because your weak groupoid is cubical, in that an $n$-morphism is shaped like an $n$-dimensional hypercube. In particular, it has $n$ $(n-1)$-dimensional domains and $n$ codomains, corresponding to the $2n$ top-dimensional faces of the hypercube.
So, when you claim to reconstruct $\pi_1(X,x)$, what exactly is the relation you're putting on $Hom(x,x)$? You say you're making all higher morphisms into equalities, which suggests to me the relation $f\sim g$ if there exists a 2-morphism with $f$ and $g$ as two opposing faces. This is the relation that $f$ and $g$ are homotopic without endpoints fixed. The resulting quotient admits no natural group structure-it's the conjugacy classes in $\pi_1(X,x)$.
The relation that will produce groups is: $f\sim g$ if there exists a 2-morphism with $f$ and $g$ as two opposing faces and in which the other two faces are degenerate. That is, the relation is precisely that there exists a homotopy between $f$ and $g$ with endpoints fixed, which is precisely the defining relation for $\pi_1(X,x)$.
In higher dimensions, the appropriate relation is analogous: two $n$-morphisms $f,g$ with boundaries degenerate at $x$ are equivalent if they form opposite faces of an $n+1$-morphism in which all other faces are degenerate. Again, this is precisely the definition of $\pi_n(X,x)$.
What about automorphism groups of morphisms? For instance, given a 1-morphism $f:x\to y$, we have a group of all 2-morphisms $H$ whose boundary paths are $f,x,f,$ and $y$, where $x$ and $y$ stand for their constant paths, taken up to 3-morphisms with $H$ and $K$ as two faces and $x,f,y,$ and $f$ as the other four. This is nothing more or less than $\pi_1(P(x,y),f)$, where $P(x,y)$ denotes the space of paths in $X$ between $x$ and $y$. This may look like an unfamiliar space, but composing with $f^{-1}$ gives a homotopy equivalence with $\Omega(X,x)$, the space of loops based at $x$, which is well known to have $\pi_2 X$ for its fundamental groups.
There are still more groups to be found in your groupoid! For instance, given a loop $\gamma$ in $X$, an appropriate relation on certain 2-morphisms will reproduce $\pi_1(LX,\gamma)$, which is hard to express precisely in terms of $X$ if $\gamma$ isn't contractible. In fact, you can do quite a lot more: your groupoid contains enough information to reconstruct $X$ up to homotopy equivalence (assuming it's of the homotopy type of a CW complex) so that in principle it contains every homotopy meaningful group that can be constructed out of $X$.
However, there are some strict limits on discovering new such groups as you wanted to. By Heller's representability theorem, any functor on based spaces into groups which respects homotopies, products, and relative path spaces must be induced by homotopy classes of maps out of some space. That's why we shouldn't be surprised to find a homotopy group of a space related to $X$ above-it's almost impossible to do anything else.

A: The groups you define are merely isomorphic to the usual higher homotopy groups.
Let me do the case $n = 1$ otherwise it becomes notationally tedious. Fix some $f : [0,1] \to X$. You're looking at the set
$$\{ H :  [0,1]^2 \to X \mid H(0,t) = H(1,t) = f(t) \} / \sim$$
where $\sim$ is the relation "homotopic", and a group structure given by concatenation. I claim that this is simply $\pi_2(X, f(0))$. I'll write maps in one directions, and it's easy that it's compatible with the group structure and bijective (by building a similar map in the reverse direction).
Start with a representative of $\pi_2(X,f(0))$, say $A : [0,1]^2 \to X$ such that $A(\partial[0,1]^2) = \{f(0)\}$. You can build a $H : [0,1]^2 \to X$ as above by:
$$H(s,t) = \begin{cases}
f(t(1-3s)), & \text{if } 0 \le s \le 1/3; \\
A(3s-1,t), & \text{if } 1/3 \le s \le 2/3; \\
f(t(3s-2)), & \text{if } 2/3 \le s \le 1.
\end{cases}$$
Basically for $0 \le s \le 1/3$ we build a homotopy from $f$ to the constant map equal to $f(0)$; for $1/3 \le s \le 2/3$ we use $A$; and for $2/3 \le s \le 1$, we again build a homotopy from $t \mapsto f(0)$ to $f$.

A: The groups $Hom_{n+1}(f), Hom_{n+1}(g)$ are isomorphic if $f, g$ are homotopic. Therefore it suffices to consider the group $Hom_{n+1}(c)$ where $c : I^n \to X$ is a constant map with value $x_0$. Define
$\varphi : \pi_1(X,x_0) \to Hom_{n+1}(c), \varphi([\omega]) = [\overline{\omega}]$ with $\overline{\omega}(x,t) = \omega(t)$.
This is clearly a group homomorphism. We show that it is an isomorphism.
$\varphi$ is surjective: Let $[A] \in Hom_{n+1}(c)$. Define
$\omega_A : I \to X, \omega_A(t) = A(0,t)$ with $0 = (0,...,0) \in I^n$,
$\Sigma : I^{n+1} \times I \to X, \Sigma(x,s,t) = A(t \cdot x, s)$.
Then $\Sigma_0 = \overline{\omega_A}$, $\Sigma_1 = A$. This shows $\varphi([\omega_A]) = [A]$.
That $\varphi$ is injectice can be shown similarly.


text:
Q: remove prefix and suffix and leave middle string 2018-09-12_@zulire_6600287891371330821
2019-07-14_@alex_marv_660067913713308218755

https://regexr.com/5huq8
i am trying to remove everything before and after the central word [zuliere , alex etc] but my regex is not working.
i tried this
.*_@(.zulire)_6.
result i am trying to get
zulire
alex_marv

i am trying to use it in this powershell
Get-ChildItem -File |  # Get files
  Group-Object { $_.Name -match '@([^_]+)' } |  # Group by part before first underscore
  ForEach-Object {
    # Create directory
    $dir = New-Item -Type Directory -Name $_.Name
    # Move files there
    $_.Group | Move-Item -Destination $dir
  }
Start-Sleep -Seconds 600

A: You may match any chars in between @ and the last _ followed with one or more digits:
$string = '2018-09-12_@zulire_6600287891371330821'
$string -match '(?<=@).*(?=_\d+$)' | Out-Null
$matches[0]
# => zulire

See the regex demo. Details:

*

*(?<=@) - a location immediately preceded with @

*.* - any 0 or more chars other than a newline, as many as possible

*(?=_\d+$) - immediately followed with _ and one or more digits till end of string.

If you insist on  a -replace solution use
$string -replace '.*@(.*)_\d+$', '$1'

See this regex demo. Here,

*

*.* - any 0 or more chars other than a newline, as many as possible

*@ - a @ char

*(.*) - Group 1 ($1): any 0 or more chars other than a newline, as many as possible

*_ - a _ char

*\d+ -  one or more digits

*$ - end of string.

NOTE: If there may be anything at the end but _, just replace \d+$ with .*:
$string -replace '.*@(.*)_.*', '$1'


text:
Q: Devstack/Openstack Home lab on Ubuntu - [ VM's created on Ubuntu machine using Openstack are not accessible outside LAN] I am setting up Devstack (Openstack) Home Lab set on ubuntu box and we creating VM's on same ubuntu machine where Openstack is installed. But the Internal IP's (10.0.02,.. ) 0r corresponding floating IP's (172.24.4.2,... ) are not accessible from other LAN machine's. How we can publish internal IP's to external LAN machines.
Regards
Rishi

A: This is not enable for default. What I know is that vms can access all the machines, but outer would machines can't access internal vms.
However, the head node of openstack can access any of you vms.

A: What you need to do on dashboard is following

*

*Launch Instance

*Associate Floating IP to the Instance

*Check security profile and confirm the protocol you use is on the list (by default implicit deny all)

Please make sure "q-l3" and other neutron service is enabled in your devstack/local.conf.
if you can give us Open vSwitch information it will help.
$ sudo ovs-vsctl show

    Bridge br-int
        Port ...
    Bridge br-ex
        Port "eth2"
            Interface "eth2"
        Port "qg-5d0d5dbd-99"
            Interface "qg-5d0d5dbd-99"
                type: internal
        Port br-ex
            Interface br-ex
                type: internal


text:
Q: UIButton's text is not centered Hi I have an simple application where I am supposed to change the frame of a UIButton based on its super view and based on its frame the title size should get change.
I am using Autolayout to change the frame of that UIButton. But not getting any idea how to change the font size of that UIButton.

Here is the code I have tried so far.
1. [self.cButton sizeToFit] ;

2. [self.cButton.titleLabel sizeToFit] ;

3. self.cButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter ;

4. self.cButton.titleLabel.adjustsFontSizeToFitWidth = YES;

5. self.cButton.titleLabel.textAlignment = NSTextAlignmentCenter ;

6. self.cButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);

Like I have tried many things.
Can anyone tell me if I am missing something here and I am doing something wrong.

A: I was having this issue and it turned out that I was overriding layoutSubviews and had forgotten to call [super layoutSubviews].


text:
Q: PHP post method only showing the first word? Can someone see where I have gone wrong? I have
                echo'<option value='.$row['car'].'>'.$row['car'].'</option>';
            }
?>
            </select>

I want to display the whole word in $row['car'].

A: You MUST have quotes around your attributes if they contain more than one word.
echo '<option value="'.$row['car'].'">' . $row['car'] . '</option>';


text:
Q: Datatables Cannot read property 'fnGetData' of undefined I am using jQuery Datatables in my project and everything works great now. But i am getting below warning error in my browser console and i dont get any clue about this error why this is coming. But it is not stopping any functionalities.
 Uncaught TypeError: Cannot read property 'fnGetData' of undefined

This is error is just coming after the table draw.
Below are parameter that i am using for my datatable. So you can get some idea on this warning error.
var initParams = {
        "bDestroy": true,
        "autoWidth": false,
        "bSortClasses": true,
        "iDisplayLength": 15,
        "aLengthMenu": [[10, 15, 30, 50, 100, -1], [10, 15, 30, 50, 100, "All"]],
        "sAjaxSource": defaultReq,
        "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
            oSettings.jqXHR = $.ajax( {
               "dataType": 'json',
               "type": "GET",
               "url": sSource,
               "data": aoData,
               "success": fnCallback,
               "error": function (e) {
                   console.log(e.message);
               }
           });
        },
        "aoColumns": cols,
        "aoColumnDefs": colDef
    };

I am triggering an ajax (sAjaxSource) request to get table data.
Any help would be appreciated :)

A: Your initialization code is correct. I suspect you're using newer DataTables 1.10.x library (by presence of autoWidth option).
Error Cannot read property 'fnGetData' of undefined can occur when you're trying to call older version (1.9.x) method fnGetData() on API instance of newer 1.10.x version of DataTables, for example:
var data = $('#example').DataTables().fnGetData();

Correct way to call fnGetData() in both 1.9.x and 1.10.x versions is
var data = $('#example').dataTable().fnGetData();

See DataTables 1.9 to 1.10 migration reference for more information.

A: Use rows().nodes() instead of fnGetData().
Like this,
var data = $('#example').DataTables().rows().nodes();


text:
Q: How to show text with icon for item from ActionBar? There is the following menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/item1"
        android:icon="@drawable/icon"
        android:title="Text111" android:showAsAction="ifRoom|withText"/>
</menu>

As you can see I set icon, title and "showAsAction" attribute for my menu item, but there is only icon on Actionbar when I execute it. How can I fix it?

A: <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/item1"
        android:icon="@drawable/ic_launcher"
        android:title="Text111" android:showAsAction="withText"/>
</menu>

check back your code , test with ic_launcher first .and move ifRoom to check if its the cause or no!.


text:
Q: Excel Crashes on wb.Close in VBA Everything in this code works fine, except at the very end when I go to close the workbook that I am performing some operations on. I'm inserting some code into ThisWorkbook of the workbook that I'm opening from a text file and also copying a few tabs in my master spreadsheet to each workbook that I open in this loop.  At the end of the loop it crashes when I try to close and move on to the next workbook.
Sub AddSht_AddCode()
Dim wb As Workbook
Dim xPro As VBIDE.VBProject
Dim xCom As Variant
Dim xMod As VBIDE.CodeModule
Dim xLine As Long
Dim strFolderPath As String
Dim strFolderPathTo As String
Dim strCodePath As String
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim mergearea As Range
Dim c As Range

Application.ScreenUpdating = False
Application.DisplayAlerts = False
strFolderPath = Sheets("Master - DO NOT MOVE").Range("B2").Value

strCodePath = Sheets("Master - DO NOT MOVE").Range("b18").Value
If IsNull(strFolderPath) Or strFolderPath = "" Then
    MsgBox "Please make sure you have a valid DFF path entered in Cell B2 on the Master worksheet.", vbOKOnly
    Exit Sub
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")

If Dir(strFolderPath, vbDirectory) = "" Then
    MsgBox "The DFF folder path entered is not a valid path.  Please edit and try again.", vbOKOnly
    Exit Sub
Else
    Set objFolder = objFSO.GetFolder(strFolderPath)
End If

'create_projid_array
'create_projid_new

For Each objFile In objFolder.Files

'If (InStr(objFile.Name, ".xlsm") > 0 Or InStr(objFile.Name, ".xlsx") > 0) And check_var_array(Left(objFile.Name, InStr(1, objFile.Name, ".") - 1), projarray) = 1 Then
'If (InStr(objFile.Name, ".xlsx") > 0 Or InStr(objFile.Name, ".xlsb") > 0) And check_var_array(Left(objFile.Name, InStr(1, objFile.Name, ".") - 1), projarray) = 1 Then
If (InStr(objFile.Name, ".xlsm") > 0) Then
'If check_var_array(objFile.Name, projarray) = 1 Then

    Application.AutomationSecurity = msoAutomationSecurityLow
    Set wb = Workbooks.Open(objFile, False)
    'Application.AutomationSecurity = msoAutomationSecurityByUI

    Workbooks("DFFPHI_w_QAQC.xlsm").Activate
    If Right(objFile.Name, 5) = ".xlsx" Then
        Sheets(Array("Template", "Log")).Copy After:=wb.Sheets(1)
        If Sheets("Master - DO NOT MOVE").Range("B4") = True Then
        wb.Activate
        wb.Sheets("Data").UsedRange.Clear
        wb.Sheets("Data").Range("A1").Value = 0
        Workbooks("DFFPHI_w_QAQC.xlsm").Sheets("Data").Range("B1:BO2400").Copy Destination:=wb.Sheets("Data").Range("B1")
        End If
    End If

    wb.Activate
    wb.Sheets(1).Visible = xlSheetVisible
    wb.Sheets(1).Unprotect Password:="xxxxxxxxx"
    Set mergearea = wb.Sheets(1).Range("i5:l6")
    For Each c In mergearea
    If c.MergeCells Then
    c.UnMerge
    End If
    Next
    wb.Sheets(1).Range("J5").ClearContents
    wb.Sheets(1).Range("j6").ClearContents
    'Selection.UnMerge
    'Selection.ClearContents

    If Right(objFile.Name, 5) = ".xlsm" Then
        wb.Sheets("Template").Visible = xlSheetVisible
        wb.Sheets("Data").Visible = xlSheetVisible

        Workbooks("DFFPHI_w_QAQC.xlsm").Activate
            If Sheets("Master - DO NOT MOVE").Range("B4") = True Then
            wb.Activate
            wb.Sheets("Data").UsedRange.Clear
            wb.Sheets("Data").Range("A1").Value = 0
            Workbooks("DFFPHI_w_QAQC.xlsm").Sheets("Data").Range("B1:BO2400").Copy Destination:=wb.Sheets("Data").Range("B1")
            End If

        Workbooks("DFFPHI_w_QAQC.xlsm").Activate

        If Sheets("Master - DO NOT MOVE").Range("B6") = True Then
        wb.Activate
        wb.Sheets("Template").UsedRange.Clear
        Workbooks("DFFPHI_w_QAQC.xlsm").Sheets("Template").Range("A1:G524").Copy Destination:=wb.Sheets("Template").Range("A1")
            If Left(wb.Sheets(1).Range("I7"), 3) = "PO " Or Left(wb.Sheets(1).Range("I7"), 3) = "PO#" Then
            wb.Sheets(1).Range("I7").Copy Destination:=wb.Sheets("Template").Range("F3")
            End If
        End If
    End If

    wb.Activate
    Call update_dropdowns
    Call update_ga_formula(wb.Name)

    wb.Sheets(Array("Template", "Data")).Select
    ActiveWindow.SelectedSheets.Visible = False
    wb.Activate
With wb
    Set xPro = .VBProject
    Set xCom = xPro.VBComponents("ThisWorkbook")
    Set xMod = xCom.CodeModule
    xMod.DeleteLines 1, _
    xMod.CountOfLines
    xMod.AddFromFile strCodePath
End With

    wb.Activate
With wb.Sheets(1)
.Protect Password:="xxxxxxx", UserInterfaceOnly:=True, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, DrawingObjects:=False, Contents:=True, Scenarios:=True, AllowFiltering:=True
.EnableOutlining = True
End With

    wb.Save
    wb.Close  <<<<<EXCEL CRASHES HERE>>>>>>>

End If

Next

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

A: Check the code in the wb close / save events for any invalid actions:

*

*BeforeClose()

*BeforeSave()

*SheetDeactivate()

*WindowDeactivate(), etc

Not related, but remove the .Activate statements and qualify the objects if needed
For example:
Workbooks("DFFPHI_w_QAQC.xlsm").Activate
    If Sheets("Master - DO NOT MOVE").Range("B4") = True Then

should be replaced with
If Workbooks("DFFPHI_w_QAQC.xlsm").Sheets("Master - DO NOT MOVE").Range("B4") = True Then

Statements .Select and .Activate are not needed and have poor performance

A: Just to finalize:
In my specific situation I was adding a BeforeClose Event to the target workbook ThisWorkbook object.  In the code that is performing this operation, it was crashing after the BeforeClose code was inserted in the target workbook and upon having the source code try to close the workbook with wb.Close.
I changed:
wb.Close

to
Application.EnableEvents = False
wb.Close
Application.EnableEvents = True

So, bypassed the target workbook events altogether and it's fixed.


text:
Q: Trying to understand this line of java code mCallback = (OnHeadlineSelectedListener) activity;

This is some java code for an android app tutorial. I don't understand the what this is doing exactly. I know it's assigning a value to mCallback but what? why is OnHeadlineSelectedListener in parenthesis and then the activity object is right behind it, what the heck?
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.vizoplex.my.first.app;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}

A: It is trying to cast that activity to an OnHeadlineSelectedListener, probably because this actual activity extends that Listener. This way, mCallback acts as a listener with the callback correctly defined.
Edit:
There you have:
try {
    mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
    throw new ClassCastException(activity.toString()
            + " must implement OnHeadlineSelectedListener");
}

It's trying to cast activity to OnHeadlineSelectedListener. If activity doesn't implement this Listener, then an exception is thrown. The message is pretty straightforward:
activity.toString()+ " must implement OnHeadlineSelectedListener"

A: That is type casting.
For example:
You have Animal interface with two methods, run and eat.
public interface Animal {
    public String run();
    public String eat(String food);
}

And you have class, which implements it, say, Cat class. Cat class has some extra methods, scratch and mew.
public class Cat implements Animal{
   public String run(){
     return "Run as a cat";
   }
   public String eat(){
     return "Eat fish";
   }
   public String mew(){
     return "MEW!!!!";
   }
   public String scratch(){
     return "scratch-scratch-scratch";
   }
}

Also, you have Dog class, which has bark method.
public class Dog implements Animal{
   public String run(){
     return "Run as a dog";
   }
   public String eat(){
     return "Eat meat";
   }
   public String bark(){
     return "BARK!!!!";
   }
}

So, very often you need to work with you animal like with some exact animal (dog or cat). But compiler cat not make this casting without your help. So, you have to tell it what exactly you want:
public void Show{
  Cat cat = new Cat(); //you have a cat
  Dog dog = new Dog(); //and a dog
  Animal animal = null; //and animal
  dog = (Dog)animal; //and here is where compiler can't convert animal to dog without your help.
  Animal animal2 = cat; //But this casting it can make without your help, as it exactly knows what to do.
}

This one book is very usefull to learn Java.  If you are really interested in understanding such things, you should read it. The full explanation of how casting works can be found in this book too.

A: activity is being casted to an OnHeadlineSelectedListener object, which mCallback is being assigned to.

A: I think mCallback object is the subclass of activity object's class.
So this statement casts the activity object to a more specific mCallback object.
For more information on casting Click here

A: It's casting an activity to be a OnHeadlineSelectedListener. It's assuming that the activity implements OnHeadlineSelectedListener. This is being done so you can directly call methods in the interface OnHeadlineSelectedListener.

A: I've transitioned out of Java recently, but it looks to me as if that line is casting activity to the type OnHeadlineSelectedListener. Casting makes one type into another, and throws an Exception (of one form or another,) if the types are incompatible.
The syntax is this:
variable = (Type) variableOfType2;


text:
Q: bash: /etc/bash.bashrc: Permission denied whenever I open a terminal On Ubuntu 13.10, when I open a new terminal, I sometimes get the following output on the terminal:
bash: /etc/bash.bashrc: Permission denied

However, the permissions should be fine:
>ls -l /etc/bash.bashrc
-rwxr-xr-x 1 root root 2177 Mär 30  2013 /etc/bash.bashrc*

What is the problem? How can I fix it? What is the purpose of the file /etc/bash.bashrc and where exactly does it gets called?
Content of this file:
# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#    ;;
#*)
#    ;;
#esac

# enable bash completion in interactive shells
#if ! shopt -oq posix; then
#  if [ -f /usr/share/bash-completion/bash_completion ]; then
#    . /usr/share/bash-completion/bash_completion
#  elif [ -f /etc/bash_completion ]; then
#    . /etc/bash_completion
#  fi
#fi

# sudo hint
if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then
    case " $(groups) " in *\ admin\ *)
    if [ -x /usr/bin/sudo ]; then
    cat <<-EOF
    To run a command as administrator (user "root"), use "sudo <command>".
    See "man sudo_root" for details.

    EOF
    fi
    esac
fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
    function command_not_found_handle {
            # check because c-n-f could've been removed in the meantime
                if [ -x /usr/lib/command-not-found ]; then
           /usr/lib/command-not-found -- "$1"
                   return $?
                elif [ -x /usr/share/command-not-found/command-not-found ]; then
           /usr/share/command-not-found/command-not-found -- "$1"
                   return $?
        else
           printf "%s: command not found\n" "$1" >&2
           return 127
        fi
    }
fi

A: Try: chmod 0755 /etc as root. You could have run into an issue with the /etc directory's permissions being wrong. Also revert the permissions of the bash.bashrc file to their original permissions chmod 644 /etc/bash.bashrc.

A: This happened with the Samba AD user so I have deleted and recreated with the same user info. on the AD console. I have renamed only the home directory, mv /home/domain/user /home/domain/user.exassumed that home directory alone might've affected and made the user logged in fresh then moved whole contents back to the new home directory from the renamed home directory. mv /home/domain/user.ex/* home/domain/userTherfore home directory restored to stock and abrt-cli status' timed outerror disappeared as well.


text:
Q: How to change the "text"on the kendo grid button? On my kendo grid there is a button, by default it's add new record. I want to change it. I used the following tag but does not work :
#turbinegrid .k-icon.k-add::after {
    content: "ADD";
}

A: You can set template for the button like below,
$("#myGrid").kendoGrid({
toolbar: [{
      template: '

Tech Documents

**Create One**

'
     }]
});

Use Your Text for the button in place of Create One.

A: When using MVC you can set the text like this:
@(Html.Kendo().Grid<GridViewModel>()
    .ToolBar(tools =>
    {
        tools.Create().Text("ADD");
    })
)

When using jQuery use this:
$("#grid").kendoGrid({
    toolbar: [{ name: "create", text: "ADD" }]
});

A: #turbinegrid .k-icon.k-add {
    font-size: 0px !important;
}
#turbinegrid .k-icon.k-add::after {
    content: "New Text" !important;
    font-size: 18px !important;
}


text:
Q: Is there a standard name for testing the number of tests, or other calculated parameters? This is a general question about testing, independent of language.
One method I often use when writing tests, which I've never heard of before although I surely didn't invent it, is the following:
Suppose that I'm testing something multiple times, e.g. in a loop; e.g., it could be artificially generated test data. E.g., it might be calling a func(...) which returns some data containing a list/vector/array etc. etc. of results.
I have at the start of the test something like
int total_size = 0
...and with each calculated result:
data = func(...)
do_some_test(data)
total_size = total_size + data.size()
Then, finally at the end of the test, I'll do
TEST_THAT(total_size == 10000)
...or whatever the value is. Of course, it might not be size that I test; it could use any discrete or integer-valued property of the data objects.
So, this could be regarded as a very weak kind of integer-valued hash of test data, input and/or output, although human-readable.
There are at least four reasons to do this:
(a) Check that we are actually testing something; it's all too easy to have bugs in test code which mean that we're not testing anything, or as much as we thought.
(b) If something changes unexpectedly, due to the algorithms or tests, even if the tests still pass, then we have a chance of spotting that it changed.
(c) Although it could give a false sense of security, it's always nice to see that a test has run through 1000 times, or tested 5000 things, etc. etc. rather than just 5, say. If people ask you how well tested something is, you can immediately say "it has been tested on 2000 objects, of total size 10000", or similar.
(d) If running the same code on multiple platforms or compilers, it helps to find differences between them.
So, my questions (sorry, two rather than one!):
(1) Is this a standard method with a well-known name?
(2) Assuming it is well known, is this regarded as good practice (if done sensibly, of course?)


text:
Q: Create a sparse matrix from a list of rows (sparse vectors) I would like to efficiently create the following sparse matrix of dimension (s, n1+n2):
v0 v1
v0 v2
v0 v3
 ...
v0 vs

given sparse vector v0 (1, n1) and a list of sparse vectors (1, n2) l = [v1, ... , vs].
I have tried to use coo_matrix() but it was unsuccessful as it seems to only work if you have dense vectors:
left = coo_matrix(np.repeat(v0, s))
right = coo_matrix(l)
m = hstack((left, right))

Edit 1:
I have found a workaround that does not seem very efficient:
right = vstack([x for x in l])
left = vstack([v0 for i in range(len(l))])
m = hstack((left, right))

Edit 2:
This is an example (not working) to help you understand the situation.
from scipy.sparse import random, coo_matrix
from numpy import repeat

s = 10
n1 = 3
n2 = 5

v0 = random(1, n1)
l = [random(1, n2) for i in range(s)]

left = coo_matrix(repeat(v0, s))
right = coo_matrix(l)
m = hstack((left, right))

A: In [1]: from scipy import sparse

In [2]: s, n1, n2 = 10,3,5
In [3]: v0 = sparse.random(1, n1)
In [4]: v0
Out[4]:
<1x3 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>
In [5]: l = [sparse.random(1, n2) for i in range(s)]
In [6]: l
Out[6]:
[<1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>,
  ...
 <1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>]

Instead of np.repeat use sparse.vstack to create a stack of V0 copies
In [7]: V0 = sparse.vstack([v0]*s)
In [8]: V0
Out[8]:
<10x3 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

Similarly convert the list of n2 matrices into one matrix:
In [10]: V1 = sparse.vstack(l)
In [11]: V1
Out[11]:
<10x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

Now join them:
In [12]: m = sparse.hstack((V0,V1))
In [13]: m
Out[13]:
<10x8 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

I won't make any claims about this being efficient. hstack and vstack use bmat (check their code).  bmat collects the coo attributes of all the blocks, and joins them (with offsets) into the inputs to a new coo_matrix call (again, the code is readable).  So you could avoid some intermediate conversions by using bmat directly, or even playing with the coo attributes directly.  But hstack and vstack are relatively intuitive.


text:
Q: Geometrical meaning of admissible hermitian metric on a line bundle Let $(X,\Omega)$ be a complex compact Kahler manifold, where $\Omega$ is the fundamental $(1,1)$-form. Moreover let $L$ be a holomorphic line bundle on $X$.

A (smooth) hermitian metric $h$ on $X$ is said admissible with
  respect to $\Omega$ if
  $$c_1(L,h)=a\Omega$$
   for $a\in\mathbb R$. Here $c_1(L,h)$ is the curvature form or first Chern form of the hermitian line bundle $(L,h)$.

I'd like to visualize geometrically (in some informal way) what is the meaning of the condition  $c_1(L,h)=a\Omega$. Admissible hermitian metrics are unique up to a multiplication by a smooth function, so they seem to be very particular hermtian metrics. What is their peculiarity?

A: I don't know if this answers to your question, and very likely you already know it, but one easy fact is the following.
First of all an obvious necessary condition is that at the level of cohomology classes we have
$$
c_1(L)=a[\Omega].
$$
Once you have this, you put any smooth hermitian metric on $L$, say $h_0$, and look at its Chern curvature $c_1(L,h_0)=i/2\pi\,\Theta(L,h_0)$. Since it defines the same cohomology class as $a\Omega$, and since $X$ is Kähler, the $\partial\bar\partial$-lemma tells you that you can find a smooth function $f\colon X\to\mathbb R$ such that
$$
c_1(L,h_0)-a\Omega=\frac i{2\pi}\partial\bar\partial f.
$$
Now, set $h=e^{f}h_0$. Then,
$$
c_1(L,e^fh_0)=-\frac i{2\pi}\partial\bar\partial\log(e^fh_0)=c_1(L,h_0)-\frac i{2\pi}\partial\bar\partial f=a\Omega.
$$

A: Such hermitian metrics $h$ on the Line bundle are called Kaehler Hermite Einstein metrics. Such metrics are minimal energy, in the sense that their curvature is harmonic (since
$2\Delta\omega = \Lambda \partial\bar\partial \omega = 0$ by the Kaehler identities). In addition, however, the orthogonal complement of the Kaehler form (which is negative definite in the "intersection form" $\int \omega^{n-2} c_1(L) c_1(L')$)  is zero.
Note that the condition implies that the manifold is projective. In fact the line bundle is ample because the curvature $\Omega$ is a positive form which implies Kodaira vanishing, so the section in $L^N$ for $N \gg 0$ gives an embedding.
IIRC (but I am not actually sure) in the limit $N\to \infty$ the hermitian metric $h$ on $L$ is $1/N$ of the pullback metric of the Fubini-Study metric on $L^N$ under this embedding.


text:
Q: Is there a way to export to a variable common command line operations? If I have an operation such as
ps -u $USER -o pid,rss,command

is there a way I can assign this to a variable so that I do not have to type it out every time?

A: If you want to save the command and replay it often, you can make an alias:
alias myps='ps -u $USER -o pid,rss,command'

Now, you can re-run the command by typing:
$ myps

You can also store this in your .bashrc file or .bash_profile.
On the other hand, if you have GNU readline available, you might get by with something like this: Ctrl+R ps -u
Ctrl+r does a history lookup; all you have to do is type a unique portion of a command, and then press Enter to execute it; or press Ctrl+C to abort.


text:
Q: Testing whether my database connection is working with Heroku The app on Heroku was displaying the error "We're sorry, but something went wrong" up until I ran heroku run rake db:migrate, at which point the app didn't display any errors and worked fine besides not displaying any records from the database like it's supposed to.
I'm not sure whether the connection to the database on Heroku isn't working or whether the database on Heroku just has nothing in it, in which case I don't know why I can't push the contents on my local database to Heroku. heroku db:push didn't return any errors.
No errors from Rails or Heroku Toolbelt in the terminal, no errors on my local version, no errors on the version on Heroku, no indication of what isn't working.
Not sure what else to say.
This is what database.yml looks like:
default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: app_development

test:
  <<: *default
  database: app_test

production:
  <<: *default
  database: # heroku database
  username: # heroku username
  password: # heroku password

Update: I inserted a record into the database on Heroku manually and it threw up the "We're sorry, but something went wrong error". So I guess the connection isn't working.

A: Push your local database to heroku using heroku pg:push.  For example:
heroku pg:push mylocaldb HEROKU_POSTGRESQL_MAGENTA --app sushi

Check issues with your Heroku postgres database with heroku pg:diagnose
See the Heroku Postgres guide for more information


text:
Q: How to interpret stacktrace error reports I released a new version of my app on the android store recently, and got an error report 2 days later in the android dashboard.  My new feature was to add more sound, which the stack trace seems to indicate as the cause.  Any idea what the below stacktrace means or how I can fix it?
DALVIK THREADS:
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x2aacdf48 self=0xcdd0
  | sysTid=2611 nice=0 sched=0/0 cgrp=unknown handle=1876199472
  at android.media.SoundPool._load(Native Method)
  at android.media.SoundPool.load(SoundPool.java:207)
  at maddy.toddlershapes.d.a((null):-1)
  at maddy.toddlershapes.ToddlerShapes.onCreate((null):-1)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:123)
  at android.app.ActivityThread.main(ActivityThread.java:4627)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:521)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
  at dalvik.system.NativeStart.main(Native Method)

"SoundPoolThread" prio=5 tid=8 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x32d6fef8 self=0x225468
  | sysTid=2618 nice=0 sched=0/0 cgrp=unknown handle=2246400
  at dalvik.system.NativeStart.run(Native Method)

"SoundPool" prio=5 tid=7 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x32d6fe48 self=0x224a70
  | sysTid=2617 nice=0 sched=0/0 cgrp=unknown handle=2246232
  at dalvik.system.NativeStart.run(Native Method)

"Binder Thread #2" prio=5 tid=6 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x32d580c0 self=0x130f18
  | sysTid=2616 nice=0 sched=0/0 cgrp=unknown handle=1230568
  at dalvik.system.NativeStart.run(Native Method)

"Binder Thread #1" prio=5 tid=5 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x32d58000 self=0x131f48
  | sysTid=2615 nice=0 sched=0/0 cgrp=unknown handle=1253128
  at dalvik.system.NativeStart.run(Native Method)

"Compiler" daemon prio=5 tid=4 VMWAIT
  | group="system" sCount=1 dsCount=0 s=N obj=0x32d542a0 self=0x131cc8
  | sysTid=2614 nice=0 sched=0/0 cgrp=unknown handle=1249976
  at dalvik.system.NativeStart.run(Native Method)

"Signal Catcher" daemon prio=5 tid=3 RUNNABLE
  | group="system" sCount=0 dsCount=0 s=N obj=0x32d541e8 self=0x131158
  | sysTid=2613 nice=0 sched=0/0 cgrp=unknown handle=1263960
  at dalvik.system.NativeStart.run(Native Method)

"HeapWorker" daemon prio=5 tid=2 VMWAIT
  | group="system" sCount=1 dsCount=0 s=N obj=0x2ff58230 self=0x134818
  | sysTid=2612 nice=0 sched=0/0 cgrp=unknown handle=1276096
  at dalvik.system.NativeStart.run(Native Method)


text:
Q: 301 Redirect Working when Typed, but Not From Google Results I am having a heck of a time trying to set up a 301 redirect. I have a bigcartel site with a custom domain, redirecting to my new Square Online site. It works when you type the URL in, but it doesn't work when you find the website using google. When you click the site from Google, it goes to the old website.
I went into cPanel and added a 301 Redirect for the entire domain, with or without the "www" to redirect to the new site permanently. I even went into the .htaccess file and checked my settings in there, and it shows:
RewriteOptions inherit
RewriteCond %{HTTP_HOST} ^.*$
RewriteRule ^/?$ "https\:\/\/mywebsite\.square\.site\/" [R=301,L]

I know it isn't a time thing, because I set up this redirect months ago. Any help is appreciated!


text:
Q: Swift array behaviour In Swift arrays have a special behaviour, but why here does arr1 contain two times "item 1" whereas arr2 contains it only once ?
What does defining arr1 as an instance variable change here (versus defining arr2 as a local variable) ?
Update: I'm using Xcode 6.0.1

A: I can reproduce this result reliably in Xcode 6.0.1:

But not in Xcode 6.1 GM:

Looks like it's a bug that got fixed.
As a temporary workaround, this works in Xcode 6.0.1:


text:
Q: Mass Transit: Using AWS SQS and Job Consumers Currently we're using Hangfire for scheduling and running long lived tasks. We need these tasks to be able to be retried in the event of an ungraceful shutdown, which Hangfire handles for us.
We're looking to try and move to a producer/consumer model and I've built a basic prototype with Masstransit and AWS SQS, but I have some concerns about how to handle the event of a task being processed during an ungraceful shutdown.
I understand that eventually the SQS visibility timeout will expire and the queued item will be picked up for processing again, but setting that timeout isn't trivial as the length of tasks can be quite varied and I'd prefer if the task could immediately resume/retry processing when the application starts up again.
I got reading about Job Consumers and they seemed to be better fitted to this type of scenario, but all the examples I've seen are using RabbitMQ. Wondering if it's possible/appropriate to do this using SQS, or if there's a better approach?
Thank you for taking the time to read this question :)

A: MassTransit will extend the visibility timeout as long as the consumer is still running.
I believe SQS has an upper-limit of something like 12 hours, but you should look it up and find out.
Job Consumers have significantly greater requirements (sagas, temporary queues, etc.) and SQS is really annoying about not having auto-delete/expiring queues, so I'd stick to a regular consumer if you can swing it.


text:
Q: CS0103: The name 'xxxx' does not exist. This randomly occurs I have researched this quite a bit and while I can find a number of articles on the general issue and the code, unfortunately none quite like what we have.
Environment: We have 2 web servers running Windows 2012 and IIS 8. All running .net 2-4.5
Web Server 1: This is our main server that runs our main websites and web applications
Web Server 2: This runs our client websites
Code: Both sets of code are uncompiled. Both the shared code and the client websites are .NET 4 sites.
Scenario
On Web1 we have a set of website code that is shared amongst a number of client websites. On Web2 the client site is set up in IIS and a sub directory of the App_code is a virtual directory pointing to a folder in the shared code on web1. We also have another virtual folder that points to the Web1 code as well. We have over 100 websites running in this fashion for over a couple of months.
Recently a couple of our clients have contacted us to say that they are receiving an error when browsing to parts of their website that are served by these virtual directories. The file that it references in the error message is in a modules folder in the virtual directory. it is a .cs file.
It only seems to be one website at a time and if we make a change that forces IIS to 'recompile'  the site (meaning that we make a slight change to the web.config, save it and then change it back and save again), the error disappears and the web site starts working correctly. When we check other sites that are in the exact same setup as the one failing, we do not get any errors and they work correctly.
We are whits end as the issue seems to be completely random. This issue has only started occurring in the last week or at least this is the first we have seen of it.
We are at the point where we believe that it might be an IIS 8 issue and something that might be occurring when it is trying to recompile a client web site but due to the randomness and the 'easy fix' it is difficult to troubleshoot or even know where to go looking for the issue.
Any help would be much appreciated.
Thanks
Don

A: What is the error you're having? Based on what you said, the behavior is random and points on a C# file, not much can be said and only guesses could be make...


text:
Q: PDO get sql error code - must be of the type integer How to get the error code from MYSQL via PDO as integer?
try{
    ...
}
catch(PDOException $e){
    throw new Fatal($e->getMessage(), $e->getCode());
}

$e->getCode() will return something like HY000

Argument 2 passed to Fatal::__construct() must be of the type integer,
  string given ...
... Fatal->__construct('SQLSTATE[HY000]...', 'HY000')

A: Take a look at $e->errorInfo.
http://php.net/manual/en/class.pdoexception.php says:

errorInfo

*

*Corresponds to PDO::errorInfo() or PDOStatement::errorInfo()

http://php.net/manual/en/pdostatement.errorinfo.php documents the fields returned by errorInfo().
Example:
try {
        $stmt = $pdo->query("Bogus Query");
} catch (PDOException $e) {
        echo "Caught exception!\n";
        var_dump($e->errorInfo);
}

Output:
Caught exception!
array(3) {
  [0]=>
  string(5) "42000"
  [1]=>
  int(1064)
  [2]=>
  string(157) "You have an error in your SQL syntax; check the manual that corresponds to
      your MySQL server version for the right syntax to use near 'Bogus Query' at line 1"
}

You can see that the [1] element is an integer.


text:
Q: How to add a new line with the same indentation Then I press Enter in Insert mode, a new line is created, but the cursor is placed at the  beginning of the line.
How do I create a new line with the same indentation as the current one?

A: I'd also suggest adding this to your .vimrc:
set smartindent

It will increase the indent in a new block.

A: Both will annoy you when pasting, as Vim will try and indent everything on the fly.
Prior to pasting enter:
:set paste

A: Adding set autoindent  to your ~/.vimrc can do that for you automagically.

A: At bottom of the file, I'm using:
# vim: ts=2 sw=2 sts=2 sr noet st ai si

For example Dockerfile:
FROM centos-7
RUN ...
CMD ...

# vim: ts=2 sw=2 sts=2 sr noet st ai si

If you want keep the indentation only, use # vim: st ai si


text:
Q: how can i compare a start time with the system clock using ctime/chrono libaray I'm running into a error trying to compile the program with conversion from double to int. What I want is to be able to display out the difference not just in seconds but in hours/minutes/seconds but I can't think of how to make the difftime work. If there is a better option like using chrono, I would appreciate the help.
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>

int main() {
    std::tm now{},;
    std::chrono::system_clock::time_point cc;

    std::cout << "enter\nyear month day\n";

    std::cin >> now.tm_year >> now.tm_mon >> now.tm_mday;

    now.tm_year -= 1900;
    now.tm_mon -= 1;

    std::time_t n = std::mktime(&now);
    cc = std::chrono::system_clock::from_time_t(n);
    n = std::chrono::system_clock::to_time_t(cc);

    std::cout << std::put_time(std::localtime(&n), "%FT%T") << "\n";
    std::time_t system_time = time(nullptr);
    std::cout << asctime(localtime(&system_time));

    double fc = difftime(system_time, mktime(&now));
    std::cout << "time diff "<< fc << endl;

}

A: You should checkout the date lib from howard hinnant.
https://github.com/HowardHinnant/date
The tz lib in it Can do your local time diff calculation in without converting it to utc. (normally you should always convert to utc before calculation, because of the daylight saving time) It also contains format functions to stream it in hour min sec format.

A: The better way of doing it is using a steady_clock instead of system_clock.
I don't know what your task is but you may use another class such as Stopwatch to generate elapsed time.
#include <chrono>
#include <ctime>
class StopWatch {
private:
chrono::time_point<chrono::steady_clock> start;
public:
void reset() { start = chrono::steady_clock::now(); }
StopWatch() { reset(); }
double elapsedSeconds() {
chrono::duration<double> d = chrono::steady_clock::now() - start;
return chrono::duration_cast<chrono::microseconds>(d).count() / 1000000.;
}};

After that, you can simply use Stopwatch:
int main(void){
Stopwatch s;
cout<<s.elapsedSeconds();
}


text:
Q: How to implement logging in rails using rails? I am working on a project and I have to use logging in the project, I have chosen log4r for logging.
Well I want to know what is the best way for implementing it:

*

*Should I create a single instance and use that instance for whole application

*Should I create a new static instance for every class

*Should I create a factory of all the loggers and use it.

I want to implement the 3rd option, but I don't know how I should do it, can any one tell me how to implement option 3.

A: I think it really depends on your project and the amount of granularity you require.
At the end of the day the reason you are logging events is so that at some future date you can look through the logs and examine what happened when. Given that, you should try to make it as easy for yourself as possible to find the information you are likely to require.
If your just doing general logging that you don't expect to have to troll through very often, then an app wide logger makes sense because it's probably not going to be a huge issue to eat the overhead of looking through on massive log file if your doing it very infrequently.
If there are specific actions your are more likely to want to review then a separate logger for those actions would probably be beneficial as it reduces to difficulty of finding information you're wanting to look up more regularly.
A good example is a rails app with some sort of payment system attached. In that case, in my opinion, the best option is to have a separate logger for any payment actions you want to record (successful, failed, unprocessed, etc) and then use the rails log for everything else. That way the payment information I'm more likely to want to find is in it's own log file and quicker to search but I can still wade through the rails log file for anything else  I need.
Hope that answers your question.


text:
Q: Не работает значение времени в hide(), show() При использовании метода hide() или show(), страница не обращает внимание на скорость выставленную в круглых скобках, и в результате сразу скрывает или сразу показывает объект. В чем может быть проблема?
$('#forheader').hide(8000);

A: Была подключена slim версия библиотеки jQuery, как оказалось она не поддерживает временные значения в методе hide(), поэтому элемент страницы сразу пропадал.
Решение: подключить обычную (полную) версию библиотеки jQuery.
п.с. Я методом большого количества проб, нашел ответ. Решил не удалять вопрос, так как поиск ничего на этот счет не выдает, может кому то тоже пригодится и кто-то сэкономит время.


text:
Q: Row level transactions + locks and RDBMS scalability I use transactions to lock on rows in my database. Generally, the number of 'things' accessing the same rows at a single time is small, however, for correctness I would still like to use transactions to have 'all or nothing' changes across multiple tables to ensure correctness.
I am wondering, if I don't ever expect the number of 'things' accessing a row to be more than a single digit, and these operations are quite small, then does locking, in this case, really affect my ability to scale the database. My understanding is that RDBMS don't scale as well as, say, NoSQL technologies because of the ACID properties. While ACID properties still apply (e.g. updating data may still require an index change, which I'm guessing is synchronous in RDBMS world?... maybe that is configurable?), given I am not having a lot of contention on a single record
While I may not have a lot of contention on a single record, I will have many many locks on records throughout the database at the same time. If these locks are isolated, am I limited in anyway by the overhead/number of simultaneous locks? Is my database scalability good?
EDIT: More context:
I use postgres and part of our product includes a large inventory stock system which maintains quantities of various inventory. There are many scenarios that can modify inventory quantity from many different ways (e.g. users can manually adjust quantity using UI or automatically when a stock request or refill event comes into our system through our exposed APIs). Between reading the stock quantity and adjusting it (assuming I am not using increment/decrement in this scenario) I hold a row level lock as part of the transaction.
Interested to hear people's thoughts
Thanks


text:
Q: Categorize rows as first, last or in between
I have a table called road_events.
  create table road_events
   (
    event_id number(5,0),
    road_id number(5,0),
    event_type nvarchar2(50),
    lifecycle_number number(5,0)
   );

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (1,100,'RECONSTRUCTION',1);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (2,100,'RECONSTRUCTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (3,100,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (4,100,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (5,100,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (6,100,'INSPECTION',2);

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (7,200,'INSPECTION',0);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (8,200,'RECONSTRUCTION',1);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (9,200,'INSPECTION',1);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (10,200,'INSPECTION',1);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (11,200,'RECONSTRUCTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (12,200,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (13,200,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (14,200,'INSPECTION',2);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (15,200,'RECONSTRUCTION',3);

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (16,300,'RECONSTRUCTION',1);

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (17,400,'INSPECTION',0);

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (18,500,'RECONSTRUCTION',1);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (19,500,'RECONSTRUCTION',2);

insert into road_events (event_id,road_id,event_type,lifecycle_number) values (20,600,'INSPECTION',0);
insert into road_events (event_id,road_id,event_type,lifecycle_number) values (21,600,'INSPECTION',0);

select
    event_id,
    road_id,
    substr(event_type,0,15) as event_type,
    lifecycle_number
from
    road_events
order by
    event_id

  EVENT_ID    ROAD_ID EVENT_TYPE      LIFECYCLE_NUMBER
---------- ---------- --------------- ----------------
         1        100 RECONSTRUCTION                 1
         2        100 RECONSTRUCTION                 2
         3        100 INSPECTION                     2
         4        100 INSPECTION                     2
         5        100 INSPECTION                     2
         6        100 INSPECTION                     2

         7        200 INSPECTION                     0
         8        200 RECONSTRUCTION                 1
         9        200 INSPECTION                     1
        10        200 INSPECTION                     1
        11        200 RECONSTRUCTION                 2
        12        200 INSPECTION                     2
        13        200 INSPECTION                     2
        14        200 INSPECTION                     2
        15        200 RECONSTRUCTION                 3

        16        300 RECONSTRUCTION                 1

        17        400 INSPECTION                     0

        18        500 RECONSTRUCTION                 1
        19        500 RECONSTRUCTION                 2

        20        600 INSPECTION                     0
        21        600 INSPECTION                     0

For each road, I would like to categorize the rows in each lifecycle with a lifecycle_name (in this order):

*

*The rows in the last(max) lifecycle would be called current lifecycle

*The rows in the first(min) lifecycle would be called original lifecycle (if applicable)

*Any others would be called past lifecycle (if applicable)

It would look like this:
+----------+---------+----------------+------------------+--------------------+
| EVENT_ID | ROAD_ID |   EVENT_TYPE   | LIFECYCLE_NUMBER |   LIFECYCLE_NAME   |
+----------+---------+----------------+------------------+--------------------+
|        1 |     100 | RECONSTRUCTION |                1 | ORIGINAL LIFECYCLE |
|        2 |     100 | RECONSTRUCTION |                2 | CURRENT LIFECYCLE  |
|        3 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE  |
|        4 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE  |
|        5 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE  |
|        6 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+
|        7 |     200 | INSPECTION     |                0 | ORIGINAL LIFECYCLE |
|        8 |     200 | RECONSTRUCTION |                1 | PAST LIFECYCLE     |
|        9 |     200 | INSPECTION     |                1 | PAST LIFECYCLE     |
|       10 |     200 | INSPECTION     |                1 | PAST LIFECYCLE     |
|       11 |     200 | RECONSTRUCTION |                2 | PAST LIFECYCLE     |
|       12 |     200 | INSPECTION     |                2 | PAST LIFECYCLE     |
|       13 |     200 | INSPECTION     |                2 | PAST LIFECYCLE     |
|       14 |     200 | INSPECTION     |                2 | PAST LIFECYCLE     |
|       15 |     200 | RECONSTRUCTION |                3 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+
|       16 |     300 | RECONSTRUCTION |                1 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+
|       17 |     400 | INSPECTION     |                0 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+
|       18 |     500 | RECONSTRUCTION |                1 | ORIGINAL LIFECYCLE |
|       19 |     500 | RECONSTRUCTION |                2 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+
|       20 |     600 | INSPECTION     |                0 | CURRENT LIFECYCLE  |
|       21 |     600 | INSPECTION     |                0 | CURRENT LIFECYCLE  |
+----------+---------+----------------+------------------+--------------------+

Is there a way to succinctly categorize the rows into current lifecycle, original lifecycle, and past lifecycle, where applicable?
I can think of some lengthy/cumbersome ways to do it with case statements and subqueries, but I'm looking for something a bit more elegant than that.
Update:

*

*I've updated the question with a few more scenarios (roads 300-600). Credit goes to @markp for thinking of this.

*@markp also highlighted that current lifecycle trumps original lifecycle.

A: I'd start with finding the min/max lifecycle numbers for each road id, eg:
select road_id,
       min(lifecycle_number) as min_lcnum,
       max(lifecycle_number) as max_lcnum
from   road_events
group by road_id
order by 1;

 ROAD_ID | MIN_LCNUM | MAX_LCNUM
 ------- | --------- | ---------
     100 |         1 |         2
     200 |         0 |         3
     300 |         1 |         1
     400 |         0 |         0
     500 |         1 |         2
     600 |         0 |         0

Push this min/max code into a cte, add a relatively simple case statement and we get:
with
cte as
(select road_id,
        min(lifecycle_number) as min_lcnum,
        max(lifecycle_number) as max_lcnum
 from   road_events
 group by road_id)

select  re.event_id,
        re.road_id,
        re.event_type,
        re.lifecycle_number,

        case when re.lifecycle_number = c.max_lcnum
             then 'CURRENT LIFECYCLE'
             when re.lifecycle_number = c.min_lcnum
             then 'ORIGINAL LIFECYCLE'
             else 'PAST LIFECYCLE'
        end as LIFECYCLE_NAME

from    road_events re

join    cte c
on      c.road_id = re.road_id

order by re.event_id;

 EVENT_ID | ROAD_ID | EVENT_TYPE     | LIFECYCLE_NUMBER | LIFECYCLE_NAME
 -------- | ------- | -------------- | ---------------- | ------------------
        1 |     100 | RECONSTRUCTION |                1 | ORIGINAL LIFECYCLE
        2 |     100 | RECONSTRUCTION |                2 | CURRENT LIFECYCLE
        3 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE
        4 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE
        5 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE
        6 |     100 | INSPECTION     |                2 | CURRENT LIFECYCLE

        7 |     200 | INSPECTION     |                0 | ORIGINAL LIFECYCLE
        8 |     200 | RECONSTRUCTION |                1 | PAST LIFECYCLE
        9 |     200 | INSPECTION     |                1 | PAST LIFECYCLE
       10 |     200 | INSPECTION     |                1 | PAST LIFECYCLE
       11 |     200 | RECONSTRUCTION |                2 | PAST LIFECYCLE
       12 |     200 | INSPECTION     |                2 | PAST LIFECYCLE
       13 |     200 | INSPECTION     |                2 | PAST LIFECYCLE
       14 |     200 | INSPECTION     |                2 | PAST LIFECYCLE
       15 |     200 | RECONSTRUCTION |                3 | CURRENT LIFECYCLE

       16 |     300 | RECONSTRUCTION |                1 | CURRENT LIFECYCLE

       17 |     400 | INSPECTION     |                0 | CURRENT LIFECYCLE

       18 |     500 | RECONSTRUCTION |                1 | ORIGINAL LIFECYCLE
       19 |     500 | RECONSTRUCTION |                2 | CURRENT LIFECYCLE

       20 |     600 | INSPECTION     |                0 | CURRENT LIFECYCLE
       21 |     600 | INSPECTION     |                0 | CURRENT LIFECYCLE

Here's a dbfiddle

A: You can use two window functions, min() and max() with the same window, over the partition by road_id:
select  event_id,
        road_id,
        event_type,
        lifecycle_number,
        case lifecycle_number
            when max(lifecycle_number) over (partition by road_id)
                then 'CURRENT LIFECYCLE'
            when min(lifecycle_number) over (partition by road_id)
                then 'ORIGINAL LIFECYCLE'
                else 'PAST LIFECYCLE'
        end as LIFECYCLE_NAME
from    road_events re
order by event_id;

You could also use first_value() and last_value() window functions.
Test at dbfiddle.uk


text:
Q: Unconditionally open a URL or launch an application post installation in Inno Setup Let's say my Inno Setup script contain following under [Run]:
Filename: "{app}\{#MyAppExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; \
    Flags: shellexec postinstall skipifsilent runascurrentuser

I want this action to be forcefully performed, like mandatory with checks on disable. Or there is URL which I want to open on Post Install but again with forced, so checks on it be disable.
What is required to achieve that?

A: If you want to disable whole checklist, it's as simple as disabling whole RunList control:
[Code]

procedure InitializeWizard();
begin
  WizardForm.RunList.Enabled := False;
end;

If you want to disable the individual checkboxes, you need to know their indexes. What might not be trivial, if their number changes conditionally. But usually it would be easy.
[Code]

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpFinished then
  begin
    if WizardForm.RunList.Items.Count >= 1 then
      WizardForm.RunList.ItemEnabled[0] := False;
  end;
end;


text:
Q: How to find mx host for multiple email addresses I have a list of about 100 email addresses that I sent mail to (not spam, invitations to a private memorial service for my best friend). I know that my own email, which is hosted by Network Solutions never receives emails sent from the godaddy domain used to send to the list. Netsol technical support has had an open ticket for several days, no help, not surprising. Godaddy technical support was more helpful in the sense that they actually checked their server logs while I was on the line, and said they could see that the email was put on the wire without a problem. So I would like to find all of the addresses on the list that are hosted by Network Solutions, and contact them by phone, text or email to see if they got the invitation, and if not send it some other way.
The only way I know how to do this is to go to https://mxtoolbox.com/supertool, type in the domain part of the address, and select MX Lookup. Something I can do, but I was hoping for something less labor-intensive just to identify likely problem addresses.

A: simply by querying the dns resolver:
~$ nslookup -type=MX google.de
Server:     127.0.0.53
Address:    127.0.0.53#53

Non-authoritative answer:
google.de   mail exchanger = 0 smtp.google.com


text:
Q: How to use Audio Groups in Photon Voice Unity3D? Hi I am new to multiplayer development and I am using photon voice and wanted to make private voice chat between two player in a room created which has many players. I was directed to
https://doc.photonengine.com/en-us/voice/current/getting-started/voice-for-pun?utm_campaign=sendgrid&utm_source=sendgrid.com&utm_medium=email
by support of photon but I am not able to get it working. How should I make private voice chat in this multiplayer. please give example for explanation. Thanks

A: There is a demo scene for Push To Talk which showcases how to do this.
Let me try to explain how to implement player to player voice chat using current Photon Voice:
Photon Voice uses voice groups (which is nothing but Photon LoadBalancing's "Interest Groups") to separate voice channels/targets.
Filter incoming sounds (select "what to hear" or "who do you want to listen to"):
Each actor needs to subscribe to voice groups it's interested in. By default all actors listen to audio group 0 which could be seen as a global audio group for voice broadcast. If you want to listen to voice sent to other groups you need to subscribe to them. You can also unsubscribe from previously subscribed ones. The operation to do all this is: PhotonVoiceNetwork.Client.ChangeAudioGroups(byte[] groupsToRemove, byte[] groupsToAdd);
Select a single transmission target audio group (select "who do you want to talk to"):
Each actor needs to decide to which voice group it wants to transmit audio. The target audio group can be set using PhotonVoiceRecorder.AudioGroup.

So depending on the use case what you can do is:

*

*Speak to a single group and listen to multiple groups. You can speak to a group other than those you listen to. You can listen to all available groups.

*Speak to a single group and listen only to default group.

*Speak and listen to a single same audio group. For this particular use case, there is a shortcut to switch between this single in/out group by setting: PhotonVoiceNetwork.Client.GlobalAudioGroup. If you choose to set GlobalAudioGroup no need to call ChangeAudioGroups or set PhotonVoiceRecorder.AudioGroup as it's done internally for you.

In the three cases, you always listen to default audio group 0.
The Photon Voice demo offers two options for private (1 to 1) voice chat:

*

*"MuteOthersWhileTalking" enabled: corresponds to case n°3.

*"MuteOthersWhileTalking" disabled: corresponds to case n°1.

The audio groups in the demo are constructed this way:
We have rooms of 4 actors.
We need 6 audio groups.
For each pair of actors we calculate a unique group code.

*

*actor A with actor number (player ID) equal to x

*actor B with actor number equal to y

Here is how we get the audio group of private voice chat between A and B (if an actor number reaches 24 we have a problem):
if (x < y)
{
     AudioGroup = y + x * 10;
}
else if (x > y)
{
     AudioGroup = x + y * 10;
}
else
{
     // error
}

Example: The audio group for actors 1 and 2 is 12.
Another approach of "calculating" private voice groups is to use the actor number as audio group: each actor subscribes to a single audio group with a code equal to its actor number. whenever you want to talk to a remote actor you set the target audio group (using PhotonVoiceRecorder.AudioGroup only) to the target actor number.
The advantage of this approach:

*

*Less audio groups: We need as many audio groups as actors.

*Less audio groups switching: single audio group to subscribe to and no unsubscribing.

The drawback of this approach:

*

*You can't mute any other actor. You will listen to anyone who wants to talk to you privately.


text:
Q: Limit number of results with :gt() selector I know I can use the gt selector to target all elements after a certain index, but what if I want to affect only a certain number of elements, for example the first 3?
So the following will give yellow background to all tds after index 4:

TD #0	TD #1	TD #2

TD #3	TD #4	TD #5

TD #6	TD #7	TD #8

$( "td:gt(4)" ).css( "backgroundColor", "yellow" );

But what if I wanted to target only the first 2 tds after index 4, not all of them?

A: You can try with:
$("td:gt(4):lt(2)").css("backgroundColor", "yellow");

http://jsfiddle.net/RdaGd/1/

A: i thought it would work with
$( "td:gt(4):lt(2)" ).css( "backgroundColor", "yellow" );

i have another solution
$( "td" ).slice(5, 7).css( "backgroundColor", "yellow" );

http://jsfiddle.net/EL9VW/


text:
Q: Code for Greatest Common Divisor in Python The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is Euclid's algorithm, which is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a.
Write a function called gcd that takes parameters a and b and returns their greatest common divisor.

A: using recursion,
def gcd(a,b):
    return a if not b else gcd(b, a%b)

using while,
def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

using lambda,
gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10

A: The algorithms with m-n can runs awfully long.
This one performs much better:
def gcd(x, y):
    while y != 0:
        (x, y) = (y, x % y)
    return x

A: It's in the standard library.
>>> from fractions import gcd
>>> gcd(20,8)
4

Source code from the inspect module in Python 2.7:
>>> print inspect.getsource(gcd)
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

As of Python 3.5, gcd is in the math module; the one in fractions is deprecated. Moreover, inspect.getsource no longer returns explanatory source code for either method.

A: This version of code utilizes Euclid's Algorithm for finding GCD.
def gcd_recursive(a, b):
    if b == 0:
        return a
    else:
        return gcd_recursive(b, a % b)

A: def gcd(m,n):
    return gcd(abs(m-n), min(m, n)) if (m-n) else n

A: Very concise solution using recursion:
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a%b)

A: gcd = lambda m,n: m if not n else gcd(n,m%n)

A: a=int(raw_input('1st no \n'))
b=int(raw_input('2nd no \n'))

def gcd(m,n):
    z=abs(m-n)
    if (m-n)==0:
        return n
    else:
        return gcd(z,min(m,n))

print gcd(a,b)

A different approach based on euclid's algorithm.

A: def gcdRecur(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    # Base case is when b = 0
    if b == 0:
        return a

    # Recursive case
    return gcdRecur(b, a % b)

A: I think another way is to use recursion. Here is my code:
def gcd(a, b):
    if a > b:
        c = a - b
        gcd(b, c)
    elif a < b:
        c = b - a
        gcd(a, c)
    else:
        return a

A: in python with recursion:
def gcd(a, b):
    if a%b == 0:
        return b
    return gcd(b, a%b)

A: def gcd(a,b):
    if b > a:
        return gcd(b,a)
    r = a%b
    if r == 0:
        return b
    return gcd(r,b)

A: For a>b:
def gcd(a, b):

    if(a<b):
        a,b=b,a

    while(b!=0):
        r,b=b,a%r
        a=r
    return a

For either a>b or a<b:
def gcd(a, b):

    t = min(a, b)

    # Keep looping until t divides both a & b evenly
    while a % t != 0 or b % t != 0:
        t -= 1

    return t

A: I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:
num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])

A: def _grateest_common_devisor_euclid(p, q):
    if q==0 :
        return p
    else:
        reminder = p%q
        return _grateest_common_devisor_euclid(q, reminder)

print(_grateest_common_devisor_euclid(8,3))

A: #This program will find the hcf of a given list of numbers.

A = [65, 20, 100, 85, 125]     #creates and initializes the list of numbers

def greatest_common_divisor(_A):
  iterator = 1
  factor = 1
  a_length = len(_A)
  smallest = 99999

#get the smallest number
for number in _A: #iterate through array
  if number < smallest: #if current not the smallest number
    smallest = number #set to highest

while iterator <= smallest: #iterate from 1 ... smallest number
for index in range(0, a_length): #loop through array
  if _A[index] % iterator != 0: #if the element is not equally divisible by 0
    break #stop and go to next element
  if index == (a_length - 1): #if we reach the last element of array
    factor = iterator #it means that all of them are divisibe by 0
iterator += 1 #let's increment to check if array divisible by next iterator
#print the factor
print factor

print "The highest common factor of: ",
for element in A:
  print element,
print " is: ",

greatest_common_devisor(A)

A: def gcdIter(a, b):
gcd= min (a,b)
for i in range(0,min(a,b)):
    if (a%gcd==0 and b%gcd==0):
        return gcd
        break
    gcd-=1

A: Here's the solution implementing the concept of Iteration:
def gcdIter(a, b):
    '''
    a, b: positive integers

    returns: a positive integer, the greatest common divisor of a & b.
    '''
    if a > b:
        result = b
    result = a

    if result == 1:
        return 1

    while result > 0:
        if a % result == 0 and b % result == 0:
            return result
        result -= 1

A: This code calculates the gcd of more than two numbers depending on the choice given by  # the user, here user gives the number
numbers = [];
count = input ("HOW MANY NUMBERS YOU WANT TO CALCULATE GCD?\n")
for i in range(0, count):
  number = input("ENTER THE NUMBER : \n")
  numbers.append(number)
numbers_sorted = sorted(numbers)
print  'NUMBERS SORTED IN INCREASING ORDER\n',numbers_sorted
gcd = numbers_sorted[0]

for i in range(1, count):
  divisor = gcd
  dividend = numbers_sorted[i]
  remainder = dividend % divisor
  if remainder == 0 :
  gcd = divisor
  else :
    while not remainder == 0 :
      dividend_one = divisor
      divisor_one = remainder
      remainder = dividend_one % divisor_one
      gcd = divisor_one

print 'GCD OF ' ,count,'NUMBERS IS \n', gcd

A: The value swapping didn't work well for me. So I just set up a mirror-like situation for numbers that are entered in either a < b OR a > b:
def gcd(a, b):
    if a > b:
        r = a % b
        if r == 0:
            return b
        else:
            return gcd(b, r)
    if a < b:
        r = b % a
        if r == 0:
            return a
        else:
            return gcd(a, r)

print gcd(18, 2)


text:
Q: How to view btmon (bluez) logs in ComProbe Viewer or Wireshark? I am using btmon to get the bluetooth HCI snoop logs in Linux. I want them to view using Comprobe viewer tool.
Is there any option to use in btmon for the same? Or is it possible to convert this file to cfa format?


text:
Q: Convert NSCFString to NSString I am getting a dictionary from server
myDictionary =
{
"rank":"1",
"color":"red",
"position":"middle"
}

Now I want to check the value of key "position" in if condition
I am doing it like this
if ([[myDictionary valueForKey:@"position"] isEqualToString:@"middle"]) {
        //do Some stuff
} else{
        //do some other stuff
}

but data type of [myDictionary valueForKey:@"position"] is _NSCFString, so it does not compare value properly and never goes in if loop even the value is correct.
how do I convert it into NSString so that I could compare it in if condition ?
I have seen these questions..
NSString instance reports its class as NSCFString
Getting an NSString from an NSCFString
NSString or NSCFString in xcode?
from these question I just came to know that
NSString is really a container class for different types of string objects. Generally an NSString constructor does return an object that is actually of type NSCFString, which is a thin wrapper around the Core Foundation CFString struct.
but they didn't help me..and no one actually telling how to convert in into NSString, so please don't mark it as duplicate.

A: You don't need to convert _NSCFString to NSString. As a subclass of NSString it's guaranteed to respond to -isEqualToString: (and every other method in NSString). Your issue is not coming from the string, likely it is coming from myDictionary. Try logging all the keys in the dictionary and make sure it is behaving as expected.

A: CFStrings can be cast to NSStrings as per the docs

NSString is "toll-free bridged" with its Core Foundation counterpart, CFStringRef. See "Toll-Free Bridging" for more information on toll-free bridging.

NSString *nsString = @"Hello";
CFStringRef cfString = (CFStringRef) nsString;

You really want to work out why the values aren't being equal. Separate out your method calls:
NSString *positionValue = myDictionary[@"position"];
NSLog(@"Position value: %@", positionValue);
if ([positionValue isEqualToString:@"middle"]) {
    // do Some stuff
} else{
    // do some other stuff
}


text:
Q: Firebase is returning 3 times the same value I'm having some problems after the Firebase made its last update. My biggest problem at the moment is that I am unable to fix a class of application that I had done before this update.
The class below is returning 3 times the same name in my listview, and I have 3 registered users and all 3 have different names.
Note: It returns 3 times the name of the User that the application are logged.
package com.example.stark.chattest;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.example.stark.chattest.model.Message;
import com.example.stark.chattest.model.User;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class ChatActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference myRef = database.getReference("users");
    private String TAG = "Resultado: ";
    private ArrayList<String> userName = new ArrayList<String>();
    private ListView usersListView = (ListView) findViewById(R.id.chatListView);
    private ListAdapter usersListViewAdapter = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, userName);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        mAuth = FirebaseAuth.getInstance();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                } else {
                    Intent intent = new Intent(ChatActivity.this, SignActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };

        ImageButton sendImageButton = (ImageButton) findViewById(R.id.sendImageButton);

        sendImageButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText messageEditText = (EditText)findViewById(R.id.messageEditText);
                FirebaseUser firebaseUser = mAuth.getCurrentUser();
                Message message = new Message();
                message.setMessage(String.valueOf(messageEditText.getText()));
                message.setRead(true);
                message.setTime(22221);
                message.setSendersID(firebaseUser.getUid());
                message.setReceiversID("WTImZyGv5fcOJlGWI9fi0gdrfbd2");

                myRef.child(message.getSendersID()).child("message").child(message.getReceiversID()).child("4").setValue(message);

                //Set the Reciever Message
                message.setRead(false);
                myRef.child(message.getReceiversID()).child("message").child(message.getSendersID()).child("4").setValue(message);
            }
        });

        ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                User user = dataSnapshot.getValue(User.class);
                userName.add(user.getName());
                usersListView.setAdapter(usersListViewAdapter);

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        myRef.addChildEventListener(childEventListener);
    }
}

Here is my DB table.
Note: English is not my mother language :p
@Edit
I removed everything within the onChildChanged and put all the code in onChildAdded.

A: You should change a couple of things in your code, for e.g this line
ListView usersListView = (ListView) findViewById(R.id.chatListView);
ListAdapter usersListViewAdapter = new ArrayAdapter<String>(ChatActivity.this, android.R.layout.simple_list_item_1, userName);

write this line in your onCreate() method, you need to initialize only once,
and regarding querying users,you should do this in your onChildAdded() method instead of onChildChanged(), and you will not have to parse through the results with a for loop it will be automatically added
A little code to explain what i said,
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
    User user = dataSnapshot.getValue(User.class);
    userName.add(user.getName());
    usersListViewAdapter.notifyDataSetChanged();
}

you can remove code from onChildChanged(), See if this helps