text:
Q: filter child value and copy parent in xsl im trying to filter some book records from a larger metadata file. I only need records with a specific term in the field "rights". If the field contains "インターネット公開" it should go to the result every other record is unessary.
Sample xml:
<ListRecords>
  <record>
    <header>
    </header>
    <metadata>
      <title>農林時報</title>
      <creator>農林省</creator>
      <rights>国立国会図書館</rights>
    </metadata>
  </record>
  <record>
    <header>
    </header>
    <metadata>
      <title>大和本草</title>
      <creator>貝原篤信</creator>
      <rights>インターネット公開(保護期間満了)</rights>
    </metadata>
  </record>
</ListRecords>

My xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/TR/REC-html40">

<xsl:output method="xml" encoding="utf-16" indent="no" />

<xsl:template match="@*|node()">
    <xsl:if test="contains(current(), 'インターネット公開')">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
        </xsl:if>
</xsl:template>
</xsl:stylesheet>

The Result should show the hole xml structure but only records with the specified term.
I would be grateful for any help.

A: Your attempt will copy only elements that contain the prescribed string in their own text value. If you want to copy entire records, why don't you do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/ListRecords">
    <xsl:copy>
        <xsl:copy-of select="record[contains(metadata/rights, 'インターネット公開')]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


text:
Q: HTML 5 Drag & Drop upload with jQuery and PHP I'm currently following this example for HTML 5 drag and drop. I am hoping to use this to upload the dropped files to a remote FTP server with a php script. However, how do my php script access these dropped files ?
With a regular web form, I can use $_FILES.. But I don't suppose I can use $_FILES for the dropped files..
On the example, the script calls handleFiles function after a drop event
function handleFiles(files) {
var file = files[0];
document.getElementById("droplabel").innerHTML = "Processing " + file.name;
var reader = new FileReader();
// init the reader event handlers
reader.onprogress = handleReaderProgress;
reader.onloadend = handleReaderLoadEnd;
// begin the read operation
reader.readAsDataURL(file);
}

I guessing that I can iterate each element of the array list, and send each element to my php script. As I've mentioned above, how can I send this element from the array list to the php script? JSON ? jQuery POST ?
I am aware that there are various jquery plugins available to achieve this, and I have downloaded a few of them... However I'm just curious to know if I can implement the same thing with this example.

A: I presume by upload you mean upload it in a ajax operation.
file refer to a File object, which is available for you after the user had drop the file. After that you have two options:

*

*Read the file using FileReader, send the text in xhr as post data (not recommend as it only work with text)

*Pass the object to FormData then pass the FormData object to xhr to send the file (Doesn't work with Firefox <= 3.6 though)

Check Mozilla Developer Center document for the usage of these interfaces. I have working projects that use these objects, however there are too much bridging code to be a good walk-through demo. https://github.com/timdream/html5-file-upload

A: Why not use an open source solution for your problem rather than re-inventing the wheel.
http://plupload.com/
Is pretty much all you will ever need. I use it and it works wonders. Also, it falls back onto html 4 form uploading when a browser cannot handle html5.

redpajama_set_name: RedPajamaStackExchange


text:
Q: refresh (F5) eventHandler in BHO for IE9 which event is rised up in Internet Explorer (IE9) when the F5 key (refresh) is clicked? And how can I catch it with an Handler in my BHO?
Note:
I have created a BHO in C# for IE9. My class extend IObjectWithSite that allow me to add handlers through SetSite function.
public int SetSite(object site)
 {
   webBrowser = (SHDocVw.WebBrowser)site;
   //events here...
 }

A: If you are developing a browser plugin that injects Javascript, I found it useful to hook both ondocumentcomplete and ondownloadcomplete.

*

*Ondocumentcomplete fires as soon as the DOM has been loaded and can be manipulated, but it misses refreshes.

*Ondownloadcomplete waits until all resources (e.g., images) have downloaded, but catches refreshes. This delay can be quite long.
By hooking both, you get a responsive plugin most of the time, and you don't miss refreshes. Your javascript can then include a check to avoid running twice. Something like:
// Inject the code, but only once
if (typeof myplugin == 'undefined') {
    myplugin = new function () {
        // Your code runs here.
    };
}

I found the following page to be informative:

*

*Alternative way to detect refresh in a BHO

A: There is no direct method and it is hard to implement across different versions of IE. Although you can use combination of some events to achieve that. Be warned the following approaches are not fool proof.
Links:

*

*MSDN Forum

*Detecting the IE Refresh button

*Refresh and DISPID_DOCUMENTCOMPLETE


text:
Q: Relativistic momentum finding Kinetic energy of an object $mc^2$. I want to evaluate the momentum.
We know  Kinetic energy,
$$E_k = \frac{p^2}{2m}$$
$$mc^2 = \frac{p^2}{2m}$$
$$ p = \sqrt{2}mc$$
Note that the momentum is the relativistic mometum. Is there anything I did worng?

A: The formula goes like this
$$ E^2 = (p^2c^2 + m_0^2c^4) $$  where $m_0$ is the rest mass of the particle. If it is given, that the KE is $$E_k = m_0c^2$$, then you can write,
$$ (2m_0c^2)^2 = (p^2c^2 + m_0^2c^4)  $$ (one $ m_0c^2 $ for rest energy and the other for KE). and then calculate $p$.

A: mc2 is not the kinetic energy of an object but the rest energy. You cannot combine a rest energy equation with a kinetic energy equation.


text:
Q: Variable assignment in recursion Given this:
useAdd(List, What) :-
    addToList(List, What, New),
    reverseList(New, T),
    write("done "),
    write(T), nl, !.

addToList(List, What, [ What | List]).

reverseList([], List) :- write(List), nl.
reverseList([H | Old], []) :- reverseList(Old, [ H ]).
reverseList([ H | Old], New) :- reverseList(Old, [ H | New]).

Why does this happen (in swipl)?
?- useAdd([42, 100, ok], hello).
[ok,100,42,hello]
done []
true.

Obviously assigning to New in useAdd amounted to something, because the correct list is passed to reverseList.  But then, unlike New, T in useAdd is empty.

*

*How are those two assignments different?  Why does one work and the other not?

*How can I get the reversed list into T in useAdd?

A: Your definition of reverseList/2 uses T as the reversed list's tail.  The reversed list is built and printed at the deepest level of recursion, and then nothing is done with that created value:
2 ?- reverseList( [1,2,3,4], [0]).
[4,3,2,1,0]
true.
Instead, pass it in as a fresh logical variable, as a third parameter, pass it along unchanged between the invocations, and finally set it at the deepest level:
reverseList([], List, T) :- List = T, write(List), nl.
reverseList([H | Old], [], T) :- reverseList(Old, [ H ], T).
reverseList([ H | Old], New, T) :- reverseList(Old, [ H | New], T).
Then call it as reverseList( [1,2,3,4], Newtail, T) to get your T set at the deepest level of recursion:
6 ?- reverseList( [1,2,3,4], [0], T).
[4,3,2,1,0]
T = [4, 3, 2, 1, 0].

The definition is all over the place, the naming is terrible, and it used T probably for "tail", so you should name the new argument something like R instead, to at least hint at the fact that it will hold the reversed list as the result of an invocation.


text:
Q: Windows image acquisition - setting device properties in C# I have a C# (WinForm) program that supports scanning using WIA. I am trying to set device properties before scanning one or more documents. Primarily I want to set the paper size for the scanner. Following is a snippet of the code:
foreach (Property property in selectedDevice.Properties)
{
   //WiaProperties.WiaDpsHorizontalBedSize is my constant
   if (property.PropertyID == WiaProperties.WiaDpsHorizontalBedSize)
   {
       //Set property value here...
   }
}

I am finding the Horizontal Bed Size property, but the question is how do I set it to a value? There is a set_Value property off of property but that seems to take a ref to a result object. So I am at a loss as to how can I set properties on a device?

A: I am working on a scanning project as well, and there are very few WIA examples.  This code is what you are looking for to set the bed size, DPI, etc.  Check out the SetProperty method with an example on how to deal with set_Value.
class Scan
{
    // Scanner only device properties (DPS)
    public const int WIA_RESERVED_FOR_NEW_PROPS = 1024;
    public const int WIA_DIP_FIRST = 2;
    public const int WIA_DPA_FIRST = WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
    public const int WIA_DPC_FIRST = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
    public const int WIA_DPS_FIRST = WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
    public const int WIA_DPS_DOCUMENT_HANDLING_STATUS = WIA_DPS_FIRST + 13;
    public const int WIA_DPS_DOCUMENT_HANDLING_SELECT = WIA_DPS_FIRST + 14;
    public const int FEEDER = 1;
    public const int FLATBED = 2;
    public const int DUPLEX = 4;
    public const int FEED_READY = 1;

    WIA.CommonDialog _dialog = new WIA.CommonDialog();
    WIA.Device _scanner;

    public void ADFScan()
    {

        _dialog = new CommonDialogClass();
        _scanner = _dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false);

        foreach (Property item in _scanner.Items[1].Properties)
        {
            switch (item.PropertyID)
            {
                case 6146: //4 is Black-white,gray is 2, color 1
                    SetProperty(item, 2);
                    break;
                case 6147: //dots per inch/horizontal
                    SetProperty(item, 100);
                    break;
                case 6148: //dots per inch/vertical
                    SetProperty(item, 100);
                    break;
                case 6149: //x point where to start scan
                    SetProperty(item, 0);
                    break;
                case 6150: //y-point where to start scan
                    SetProperty(item, 0);
                    break;
                case 6151: //horizontal exent
                    SetProperty(item, (int)(8.5 * 100));
                    break;
                case 6152: //vertical extent
                    SetProperty(item, 11 * 100);
                    break;
            }
        }
        ImageFile image = (ImageFile)_scanner.Items[1].Transfer(FormatID.wiaFormatPNG);
        System.IO.File.Delete("tmp.png");
        image.SaveFile("tmp.png");
    }

    private void SetProperty(Property property, int value)
    {
        IProperty x = (IProperty)property;
        Object val = value;
        x.set_Value(ref val);
    }

    public void test()
    {
        bool WantsToScan = true;
        while (WantsToScan) ScanAndSaveOnePage();

    }

    static void Main(string[] args)
    {
        new Scan().test();
    }
}


text:
Q: Excel formula match value in column A and return not blank cell column B Need some help with creating a formula.
In column A I have text like "EAJ, ECJ, EDJ...", in column B there is text which I need to return, in this case "C1". However when I using vlookup of index/match getting blank cell by obvious reasons.
Is there any way to build a formula which will match text in column A and will return first not empty cell above in column B? For example if match text is in A322 then return value will be B318, because cells in range B322 up to B319 are blank.
Index/Match

A: You need to locate the last text in column B down to the row you locate ECJ in.
=INDEX(B:B, MATCH("zzz", B$1:INDEX(B:B, MATCH("ECJ", A:A, 0))))

Substitute "ECJ" for a cell on the worksheet cotaining ECJ or any other value to be matched in column A.


text:
Q: Xamarin é completamente grátis? Alguém sabe dizer se em algum momento é preciso pagar por usar o xamarin? Se mesmo desenvolvendo apps gratuitos é preciso pagar?
Caso seja um app que faça parte de um serviço, porém o app é grátis, é preciso de alguma licença ou algo do gênero?
O Unreal Engine por exemplo é grátis, porém uma parte do lucro obtido com o software desenvolvido com ele deve ser repassado a Epic Games, com o xamarin existe algo assim?

A: Não completamente. Ele é parte do Visual Studio agora, então, se você tem uma licença do Visual Studio poderá usar o Xamarin.
O Visual Studio Community é grátis e pode ser usado por desenvolvedores individuais, desenvolvedores de projetos open-source (para o desenvolvimento destes projetos), projetos/pesquisas acadêmicas, para fins educacionais e empresas com um time de desenvolvimento pequeno.
Se você se encaixa em um destes itens, então sim, o Xamarin é grátis pra você.
Você pode ver mais sobre o uso do Visual Studio/Xamarin Community em

*

*Visual Studio Community pode ser usado em projetos comerciais?

*Termos de licença para software Microsoft

*Termos de licença para software Xamarin

A: https://blog.xamarin.com/xamarin-for-all/
Uma parte que é interessante:
Visual Studio agora inclui o Xamarin.
Xamarin vai estar em todas as versões do Visual Studio (a partir da data do post), incluindo na versão Community (provavelmente a mais usada), que é grátis para desenvolvedores individuais, projetos open-source, pesquisas acadêmicas, propósitos educacionais e times profissionais pequenos.
Você pode desenvolver e publicar aplicativos iOS e Android feitos com C# ou F# diretamente com o Visual Studio,  sem limites de tamanho de app.
No link tem muito mais informações, vale a pena dar uma olhada.


text:
Q: Creating a selection set from selected features using select by location I am trying to convert my VBA code to vb.net. I use "Select by location" to select all the points that intersect lines. Then I want to click a button to put the points into a selection set. Then I can use two other buttons to cycle through the selection set.
When I try to convert my code I keep on getting the following error in vb.net.:
In vb I keep on getting error for 'pFeatureCursor' saying "Variable 'pFeatureCursor' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.
Here is the VBA code:
Public Sub GetSelSet()
  Dim pMxDoc As IMxDocument
  Dim pMap As IMap
  Dim pActiveView As IActiveView
  Dim pFeatureLayer As IFeatureLayer
  Dim pFeatureSelection As IFeatureSelection
  Dim pSelectionSet As ISelectionSet
  Dim pFeatureCursor As IFeatureCursor
  Dim pCurFeat As IFeature
  Dim intLayer As Integer

  Set pMxDoc = Application.Document
  Set pMap = pMxDoc.FocusMap
  Set pActiveView = pMap
  Set pSelSet = New esriSystem.Set
  CurrentIndex = 0

  For intLayer = 0 To pMap.LayerCount - 1
    If TypeOf pMap.Layer(intLayer) Is IFeatureLayer Then
      Set pFeatureLayer = pMap.Layer(intLayer)
      If Not pFeatureLayer.FeatureClass Is Nothing Then
        If pFeatureLayer.FeatureClass.featureCount(Nothing) > 0 Then
          Set pFeatureSelection = pFeatureLayer
          Set pSelectionSet = pFeatureSelection.SelectionSet
          pSelectionSet.Search Nothing, False, pFeatureCursor
          Set pCurFeat = pFeatureCursor.NextFeature

          Do While Not pCurFeat Is Nothing
            pSelSet.Add pCurFeat
            Set pCurFeat = pFeatureCursor.NextFeature
          Loop

        End If
      End If
    End If

  Next intLayer

End Sub

A: This is only a warning and not an error, the compiler is making you aware that there's a trap you might hit.. however you've got quite a few lines of code to enumerate the feature selection from IMap.Layers which will not traverse group layers - that's a more serious concern, if a layer isn't valid (red exclamation mark indicating the data isn't found) your code will crash and burn!
Rather than walking down that stony path IMap implements FeatureSelection which does ignore invalid layers and find selection in group layers (this is VB.net code, you'll need to add SET keyword when assigning objects):
Dim pCnt As Long
Dim pSelection As IEnumFeature
Dim pSelSet As ISelectionSet
pSelSet = New esriSystem.Set

pMap = pDoc.FocusMap 'pMap is of type IMap and pDoc is IMxDocument
If pMap.SelectionCount = 0 Then Exit Sub

' pMap.FeatureSelection is of type ISelection wich is implemented by EnumFeature
pSelection = CType(pMap.FeatureSelection, IEnumFeature)
pMaxFeat = pMap.SelectionCount

For pCnt = 0 To pMaxFeat - 1
    pSelSet.Add pSelection.Next
Next

Will get you to the same goal in less lines with an added layer of safety; note that in the selection set features will derive from different feature classes, use IFeature.Class as IFeatureClass to locate the source for each feature. This code can easily be converted to use IEditor.EditSelection to find all the features that are selected and editable implemented as IEnumFeature.
I hope that helps.


text:
Q: PHP5 unmet dependencies when upgrading Trying to upgrade PHP from 5.3 to 5.6 using the following:
sudo add-apt-repository ppa:ondrej/php5-5.6
sudo apt-get update
sudo apt-get install php5-common

When I try this, I run into this error and not sure how to resolve:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libapache2-mod-php5 : Depends: apache2-api-20120211
                       Depends: apache2 (>= 2.4)
                       Depends: php5-json
 php5-cli : Depends: php5-common (= 5.3.10-1ubuntu3.21) but 5.6.18+dfsg-1+deb.sury.org~precise+1 is to be installed
 php5-common : Breaks: php5-xdebug (< 2.2.2) but 2.1.0-1 is to be installed
 php5-curl : Depends: php5-common (= 5.3.10-1ubuntu3.21) but 5.6.18+dfsg-1+deb.sury.org~precise+1 is to be installed
 php5-gd : Depends: php5-common (= 5.3.10-1ubuntu3.21) but 5.6.18+dfsg-1+deb.sury.org~precise+1 is to be installed
 php5-intl : Depends: php5-common (= 5.3.10-1ubuntu3.21) but 5.6.18+dfsg-1+deb.sury.org~precise+1 is to be installed
 php5-mysqlnd : Depends: php5-common (= 5.3.10-1ubuntu3.21) but 5.6.18+dfsg-1+deb.sury.org~precise+1 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

If I try to precede the upgrade by doing sudo apt-get install python-software-properties then I get this error:
The following packages have unmet dependencies:
 libapache2-mod-php5 : Depends: apache2-api-20120211
                       Depends: apache2 (>= 2.4)
                       Depends: php5-common (= 5.6.18+dfsg-1+deb.sury.org~precise+1) but 5.3.10-1ubuntu3.21 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

If I try sudo apt-get apache2, I get this error:
The following packages have unmet dependencies:
 apache2 : Depends: apache2-bin (= 2.4.16-4+deb.sury.org~precise+4) but it is not going to be installed
           Depends: apache2-utils (>= 2.4)
           Depends: apache2-data (= 2.4.16-4+deb.sury.org~precise+4) but it is not going to be installed
           Conflicts: apache2.2-bin but 2.2.22-1ubuntu1.10 is to be installed
           Conflicts: apache2.2-common but 2.2.22-1ubuntu1.10 is to be installed
 libapache2-mod-php5 : Depends: apache2-api-20120211
                       Depends: php5-common (= 5.6.18+dfsg-1+deb.sury.org~precise+1) but 5.3.10-1ubuntu3.21 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I tried doing sudo apt-get -f install as suggested, but does not resolve problem. Instead, I get this:
The following extra packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils dh-php5 libedit2 libgd3 libmemcached11 libvpx1 php5-cli php5-common php5-curl php5-dev php5-gd php5-intl php5-json php5-mcrypt php5-memcached php5-mysqlnd php5-xdebug pkg-php-tools
Suggested packages:
  www-browser apache2-doc apache2-suexec-pristine apache2-suexec-custom libgd-tools php5-user-cache dh-make
Recommended packages:
  php5-readline
The following packages will be REMOVED:
  apache2-mpm-prefork apache2.2-bin apache2.2-common
The following NEW packages will be installed:
  apache2-bin apache2-data dh-php5 libgd3 libmemcached11 libvpx1 php5-json pkg-php-tools
The following packages will be upgraded:
  apache2 apache2-utils libedit2 php5-cli php5-common php5-curl php5-dev php5-gd php5-intl php5-mcrypt php5-memcached php5-mysqlnd php5-xdebug
13 upgraded, 8 newly installed, 3 to remove and 10 not upgraded.
8 not fully installed or removed.
Need to get 0 B/7,060 kB of archives.
After this operation, 3,685 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
(Reading database ... 149017 files and directories currently installed.)
Unpacking apache2-bin (from .../apache2-bin_2.4.16-4+deb.sury.org~precise+4_amd64.deb) ...
dpkg: error processing /var/cache/apt/archives/apache2-bin_2.4.16-4+deb.sury.org~precise+4_amd64.deb (--unpack):
 trying to overwrite '/usr/share/man/man8/apache2.8.gz', which is also in package apache2.2-common 2.2.22-1ubuntu1.10
dpkg-deb (subprocess): subprocess data was killed by signal (Broken pipe)
dpkg-deb: error: subprocess <decompress> returned error exit status 2
Processing triggers for man-db ...
Errors were encountered while processing:
 /var/cache/apt/archives/apache2-bin_2.4.16-4+deb.sury.org~precise+4_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Also tried doing just sudo apt-get install php5 but get essentially the same error.
What is the correct way to resolve these dependencies issues?

A: You can Give try with:
 sudo apt-get update && sudo apt-get install python-software-properties

Then Add by typing:
 sudo add-apt-repository ppa:ondrej/php5-5.6

Then update by typing:
 sudo apt-get update && sudo apt-get dist-upgrade

Then install by typing:
 sudo apt-get install php5

Check PHP Verision:
 php --version

Still getting please error please try :
Download libapache2-mod-php5 http://packages.ubuntu.com/trusty/libapache2-mod-php5
Architecture    Package Size    Installed Size  Files

amd64   2,158.6 kB  9,669.0 kB  [list of files]

i386    2,093.8 kB  9,027.0 kB  [list of files]

Install by Typing:
sudo dpkg -i /path/to/deb/file.deb

sudo apt-get install -f

Enjoy!

A: You must install too the Apache server in 2.4 version minimum. I don't think the PPA will provide you this package. So it break the dependancy. Then you will be able to install the php-common package.


text:
Q: Find the orthogonal projection $p$ of the vector $v$ on the line $\{ta+b, -\infty < t < \infty\}$ This is a practice problem in a 400-level linear algebra course. This is supposed to be review of 200-level material. For some reason, I'm having a mental block trying to understand the solution given.

Problem: Let $\bar{a}=\big[\begin{smallmatrix} 1 \\ 1 \end{smallmatrix}\big]$, $\bar{b}=\big[\begin{smallmatrix} 1 \\ 0 \end{smallmatrix}\big]$, and $\bar{v}=\big[\begin{smallmatrix}0 \\ 0 \end{smallmatrix}\big]$. Find the orthogonal projection $\bar{p}$ of the vector $\bar{v}$ on the line $\{t \bar{a}+\bar{b}, -\infty < t < \infty \}$.
Solution: Let $\bar{p} = t\bar{a}+\bar{b}$, then $0=\bar{a}^T(\bar{v}-\bar{p})$, and $t=-\frac{1}{2}$. Finally $\bar{p}=\big[\begin{smallmatrix} 1/2 \\ -1/2 \end{smallmatrix}\big]$.

The part I don't understand is that $\bar{v}=\big[\begin{smallmatrix}0 \\ 0 \end{smallmatrix}\big]$. I keep wanting to apply the formula:
$$ \text{proj}_\bar{p}\bar{v}=\frac{\bar{v}\cdot\bar{p}}{\bar{p}\cdot\bar{p}}\bar{p}$$ But $\bar{v}$ just ends up cancelling everything out. Is there another formula I'm missing?
If someone can explain the reasoning behind this, I would greatly appreciate it.

A: $v$ is the vector (the origin in this case) you are projecting on to the line $t \mapsto ta+b$. The line does not pass through the origin.
Solve $\min_t {1 \over 2} \|ta+b-v\|^2 $. Differentiating and finding where the derivative
is zero gives
$a^T (ta+b-v) = 0$ or $t = {a^T(v-b) \over \|a\|^2}$, computing gives $t=-{1 \over 2}$ and so the closest point is $ta+b = \binom{{1 \over 2}}{-{1 \over 2}}$.


text:
Q: Using Haystack search with Django Tables 2 views I am trying to use Haystack/Whoosh search with Django Tables 2. The search results should be rendered as table. This is my current view for rendering the tables:
def people(request):
    table = PersonTable(Person.objects.filter(pk=1))
    RequestConfig(request).configure(table)
    return render(request, 'people.html', {'table': table})

Haystack should pass the primary keys of search results to the above view function like so Person.objects.filter(pk=va1,pk=var2) so this view function can display the results.

I was able to write a working view:
def report(request, template='report.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, context_class=RequestContext, extra_context=None, results_per_page=None):
    table = ''
    query = ''
    results = EmptySearchQuerySet()

    if request.GET.get('q'):
        form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
            pklist = [ r.pk for r in results ]
            table = PersonTable(Person.objects.filter(pk__in=pklist))
            RequestConfig(request).configure(table)
    else:
        form = form_class(searchqueryset=searchqueryset, load_all=load_all)

    context = {
        'form': form,
        'table': table,
    }

    return render_to_response(template, context, context_instance=context_class(request))

It works somehow. However, as I'm just a Django beginner, I feel that there is scope for improvement. I posted it here so as to get some useful suggestions.

A: Presuming that creating your PersonTable instance with a SearchQuerySet is not an option, you could try passing a list of the Person objects from your search.
def search(request):
    # Let's say there's some logic here for querying your search engine
    # using Haystack, and `results` is a SearchQuerySet of Person results
    table = PersonTable([result.object for result in results])
    RequestConfig(request).configure(table)
    return render(request, 'people.html', {'table': table})

Otherwise your problem statement that you need to pass the primary keys of the results to the view function is a little unclear.


text:
Q: System.out is static, final. But it has a default value If out is a static, final instance object, it must be initialized and cannot be modified.
But it having a default value (of say console) seems to imply the default can be modified. I am therefore confused by the final modifier here. Thanks


text:
Q: change default format dataExporter in Primefaces 3.5 17  ibm07   ASP TEST    131 ABNY    2014-06-19
18  ibm07   ASP TEST    131 BGI 2014-06-19
19  ibm08   ASP PROD    131 VGI 2014-06-19
20  ibm08   ASP PROD    131 BMO 2014-06-19
21  ibm09   SSGA    PROD    131 STST    2014-06-19
22  ibm10   ASP PROD    131 MHTN    2014-06-19
23  ibm10   ASP PROD    131 GTC 2014-06-19
24  ibm10   ASP PROD    131 FTB 2014-06-19
25  ibm10   ASP PROD    131 SUMI    2014-06-19
26  ibm14   ASP TEST    121 LSL 2014-06-19
27  ibm14   ASP TEST    131 LSL 2014-06-19
28  ibm15   ASP PROD    111     2014-06-19
29  ibm15   ASP PROD    111 --- 2014-06-19
30  ibm15   ASP PROD    121     2014-06-19
i would like to change the format of the default primefaces datatable  above
to the below format.
sorry a don't have enough reputation to post the image!
any one can help please
ibm07    ASP      TEST  111   BBH,BGI,UBSAG,DBCT
   ibm07    ASP      TEST  131   FTB,TRBC,DBCT,LSL,CWT,ABNY,BGI
   ibm08    ASP      PROD  131   VGI,BMO
   ibm09    SSGA     PROD  131   STST
   ibm10    ASP      PROD  131   MHTN,GTC,FTB,SUMI
   ibm14    ASP      TEST  121   LSL
   ibm14    ASP      TEST  131   LSL
   ibm15    ASP      PROD  111   ---
that mean to do a grouping by client to minimaze rows
can any one help me please !!

A: I don't know how to archieve this using the build-in exporter, I think it's not possible. But you could use a fileDownload Button and create a csv/xls-File in the Controller.


text:
Q: Kubernetes build django + uwsgi + nginx show failed (111: Connection refused) while connecting to upstream when I create my.yaml, then nginx will show failed (111: Connection refused) while connecting to upstream
have any sugesstion about this? Is there pod network do not connnect?
uwsgi:
[uwsgi]
module          = myapp.wsgi
master          = true
processes       = 10
socket          = 127.0.0.1:8001
chmod-socket = 777
vacuum          = true
enable-threads = True

nginx:
upstream django_api {
server 127.0.0.1:8001 max_fails=20 fail_timeout=10s;
}
server {
    listen 80;

    #location /media  {
    #    alias /media;  # your Django project's media files - amend as required
    #}
    location /static {
    alias /usr/share/apps/static; # your Django project's static files - amend as required
    }
    location / {
    uwsgi_read_timeout 60;
    uwsgi_pass  django_api;
    include     ./uwsgi_params; # the uwsgi_params file you installed
    uwsgi_param Host $host;
    uwsgi_param X-Real-IP $remote_addr;
    uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for;
    uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto;
    }

}

A: So just a thought, maybe set your uwsgi to 0.0.0.0:8001 then on your podSpec set container port values with just 8001:
apiVersion: v1
kind: Pod
metadata:
  name: mypod
  labels:
    component: web
spec:
  containers:
    - name: django
      image: myimage
      ports:
        - containerPort: 8001
    - name: nginx
      image: nginx:alpine
      ....

this should make it available in localhost:8001/127.0.0.1:8001

A: I had a similar setup, and changing socket=server_name:8081 to socket=:8081 from uwsgi settings (uwsgi.ini) resolved my problem, see uWSGI nginx error : connect() failed (111: Connection refused) while connecting to upstream


text:
Q: jupyter kernelspec no such file or directory /lib/libstdc++.so.6.0.21 I'm trying to flesh out the workflow for a JupyterHub server in the case where a user creates an environment and wants to share it with another user. I want to test out one of the two methods.
I am trying to create an environment in a public path, and then have another user add the conda environment as a kernel. So far it looks like this.
# How the environment is created
jupyter@ip:~$ conda create -p /home/envs/test --clone root

# Current setup
nick {~}$ jupyter kernelspec list
Available kernels:
  python3    /opt/conda/share/jupyter/kernels/python3
nick {~}$ conda env list
# conda environments:
#
test                     /home/envs/test
nenv                     /home/nick/.conda/envs/nenv
base                  *  /opt/conda

nick {~}$ cat .condarc
envs_dirs:
  - /home/envs

My problem is I get an error when I try and install the kernel libstdc++.so.6.0.21 does not exist. What is libstdc++.so.6.0.21?
# error when trying to install kernel
nick {~}$ jupyter kernelspec install --user /home/envs/test
[InstallKernelSpec] Removing existing kernelspec in /home/nick/.local/share/jupyter/kernels/test
Traceback (most recent call last):
  File "/opt/conda/bin/jupyter-kernelspec", line 11, in <module>
    sys.exit(KernelSpecApp.launch_instance())
  File "/opt/conda/lib/python3.7/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/opt/conda/lib/python3.7/site-packages/jupyter_client/kernelspecapp.py", line 273, in start
    return self.subapp.start()
  File "/opt/conda/lib/python3.7/site-packages/jupyter_client/kernelspecapp.py", line 143, in start
    replace=self.replace,
  File "/opt/conda/lib/python3.7/site-packages/jupyter_client/kernelspec.py", line 346, in install_kernel_spec
    shutil.copytree(source_dir, destination)
  File "/opt/conda/lib/python3.7/shutil.py", line 365, in copytree
    raise Error(errors)
shutil.Error: [('/home/envs/test/lib/libstdc++.so.6.0.21', '/home/nick/.local/share/jupyter/kernels/test/lib/libstdc++.so.6.0.21', "[Errno 2] No such file or directory: '/home/envs/test/lib/libstdc++.so.6.0.21'")]

Note: I found this question which is similar; however, I found through this github thread why gcc had to be removed, and I already verified that it didn't exist in my environment with:
nick {~}$ conda list --name test | grep 'gcc'
_libgcc_mutex             0.1                        main
libgcc                    7.2.0                h69d50b8_2
libgcc-ng                 8.2.0                hdf63c60_1

I already have libgcc installed at a higher version as you can see above so I didn't think the other answer would do too much good either.

filename shows up as red with this, so I believe the link is broken.
(test) nick {~}$ ls -al /home/envs/test/lib/libstdc++.so.6.0.21
lrwxrwxrwx 1 jupyter jupyter 19 Aug  9 09:42 /home/envs/test/lib/libstdc++.so.6.0.21 -> libstdc++.so.6.0.24

A: I realized I was using jupyter kernelspec in a non-intended way here. It is not intended to actually create the kernel, but only to add a kernelspec if it exists (see here, at the bottom).

There are two options for writing a kernel:

*

*You can reuse the IPython kernel machinery to handle the communications, and just describe how to execute your code. This is much simpler if the target language can be driven from Python. See Making simple Python wrapper kernels for details.

*You can implement the kernel machinery in your target language. This is more work initially, but the people using your kernel might be more likely to contribute to it if it's in the language they know.

So, in my case what I really wanted to do was use IPythons utilities (option 1 above) which is documented well here. In which case to add the shared conda environment as a kernel in a way the users can access it I just need to run.
su - <user>
conda activate test
python -m ipykernel install --user --name test --display-name "Python (test)"


text:
Q: How to apply a function if an expression evaluates to true I'm trying to define a simple function that will accept a symbol and an expression, set the symbol equal to the expression, and then print out info about the equation. Like so:
ClearAll[showValue];
Attributes[showValue] = {HoldAll};
Options[showValue] = {"N" -> False, "S" -> False};
showValue[sym_, value_, OptionsPattern[]] :=
  Module[{},
   sym = value;
   Print[
    HoldForm[sym], " = ",
    If[OptionValue["S"], ScientificForm] If[OptionValue["N"],
      N] value
    ]
   ];

as you can see, I want to have some options that i can use to change the format of the output. What I would like is so that if the If evaluates to true, that it will return the function header in such a way as to apply the function to the arguments that are to the if statements' right. If effect, if the options given are:
showValue[k,
  UnitConvert[Quantity[1, "BoltzmannConstant"], ("Electronvolts")/(
   "Kelvins")], "N" -> True, "S" -> True];

then the result will be:
k = ScientificForm@N@k = 8.61733*10^(-5)eV/K

The purpose of this is so I can avoid an extremely large and burdensome branching tree, once I put in more options. My understanding of Mathematica leads me to believe that something like this is possible because we have operator behavior and functions that can return operators, I just don't know what the syntax for that is suppose to be.

A: So I don't know if this is the best or most efficient way to perform this task, but here is the code I came up with:
ClearAll[Pass];
Pass[x_] := x;
ClearAll[showValue];
Attributes[showValue] = {HoldAll};
Options[showValue] = {"N" -> False, "S" -> False};
showValue[sym_, value_, OptionsPattern[]] :=
  Module[{},
   sym = value;
   Print[
    HoldForm[sym], " = ",
    Composition[If[OptionValue["S"], ScientificForm, Pass],
      If[OptionValue["N"], N, Pass]][value]
    ]
   ];

I simply use a Pass function that just returns the argument, then use Composition to form the proper chain of functions. Again, I feel as though I am missing an easier path, so if anyone knows better, please let me know.


text:
Q: In my blog template I am getting Hugh empty space between blogger post and blogger footer in my external blogger template empty space between blogger post and footer. how can i reduce that space?
blog link below
http://chalaudyojakghadwuya.blogspot.in/

A: remove visibility : hidden; of #sidebar-wrapper, and replace it by display : none;


text:
Q: Spotlight search stopped working after upgrading to iOS 13 I have an iPhone 8 Plus phone and I installed iOS 13. Ever since I am always updating to the latest version of iOS 13. Regardless, the spotlight search does not work on my phone.
This is my main way of locating apps on the phone, so this issue is particularly painful. Here is what I do:

*

*Swipe down on the home screen.

*Start typing the name of the app, for example, "App Store"

*Nothing happens, the result list does not update while typing. The Siri Suggestions part of the screen just remains the same.

*Hit the Search button on the keyboard

*Again, nothing happens. The Siri Suggestions list is not updated.

I tried restarting the phone on several occasions but did not help. I am also installing the latest update. As of now, the version I have is 13.1.13.
I tried this with other phones with iOS 13, but they did not have this problem.
Any ideas, what I can try to fix this?

A: If your search is showing empty search results, try these as best and first solution:

*

*Tap Settings > General > Language & Region > iPad Language or iPhone Language

*Select a language (e.g.; Canada English) and tap Done. Then confirm your change by tapping Continue.

*Now change back to your original language.

If you think that Search is still not finding items, meaning it is not working correctly, try these steps:

*

*Go to Settings > Siri & Search

*Turn off (deactivate) everything (search results) by being on each App

*Now turn off your device by pressing and holding the on/off button until you see the slider. Then slide the red slider.

*Turn your device on.

*Now go to Settings > Siri & Search and now turn everything on.**


text:
Q: Reduce execution time of query I want to reduce the time taken by the query in mysql.
There are three tables say

*

*A ~600k rows,

*B ~2K rows,

*C ~100K rows

having 2 columns each.

*

*A has one column which is used in aggregation and other to join with table B.

*B has one column to join with A and other with C

*C has one column to join with B and other column to group by.

What should be the indexing plan to reduce the run time.  As of now it is using temporary tables and then file sort. Is there any way we could avoid temporary tables.
Sample query :
 SELECT
      sum(`revenue_facts`.`total_price`) AS `m0`
FROM
    `category_groups` AS `category_groups`,
    `revenue_facts` AS `revenue_facts`,
    `dim_products` AS `dim_products`
WHERE
    `dim_products`.`product_category_group_sk` =       `category_groups`.`product_category_group_sk` AND
    `revenue_facts`.`product_sk` = `dim_products`.`product_sk`
GROUP BY `category_groups`.`category_name`;

I already have indexes on group by column and the columns in join.
my query is currently taking *6 minute*s. I want to reduce the time taken. table structure is as
table A :
CREATE TABLE `revenue_facts` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `product_sk` bigint(20) unsigned NOT NULL,
  `total_price` decimal(12,2) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `product_sk` (`product_sk`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Table B :
CREATE TABLE `dim_products` (
  `product_sk` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `product_category_group_sk` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`product_sk`),
  KEY `product_id` (`product_id`),
 KEY (`product_sk`) (`product_sk`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

table C :
CREATE TABLE `category_groups` (
  `product_category_group_sk` bigint(20) unsigned NOT NULL,
  `category_sk` bigint(20) unsigned NOT NULL,
  `category_name` varchar(255) NOT NULL,
  PRIMARY KEY (`product_category_group_sk`,`category_sk`),
  KEY `category_sk` (`category_sk`),
  KEY `product_category_group_sk` (`product_category_group_sk`
  KEY `category_sk` (`category_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Execution plan used is:
1   SIMPLE  dim_products    index   PRIMARY,product_category_group_index    product_category_group_index    8   NULL    651264  Using index; Using temporary; Using filesort
1   SIMPLE  category_groups ref PRIMARY,category_sk,product_category_group_sk,category_name product_category_group_sk   8 etl_testing.dim_products.product_category_group_sk    4   Using index
1   SIMPLE  revenue_facts   ref product_sk  product_sk  8 etl_testing..dim_products.product_sk  5   NULL

A: Try this:
SELECT
    sum(`revenue_facts`.`total_price`) AS `m0`
FROM
    (`dim_products` LEFT JOIN `category_groups` ON `dim_products`.`product_category_group_sk` =  `category_groups`.`product_category_group_sk`)
    LEFT JOIN `revenue_facts` ON `dim_products`.`product_sk` = `revenue_facts`.`product_sk`
GROUP BY `category_groups`.`category_name`;

Also, as Abdul said:
"Post your table structures and explain plan"


text:
Q: Python sudo in new terminal window without passing password I have a problem. I'm trying to run sudo command in new terminal window from python script but every time I have to put password in new window.
Here is my code:
import subprocess
import sys
import os
def run_lirc():
    subprocess.call(['x-terminal-emulator','-e','sudo lircd'])
run_lirc()

Is any solution which allow me not to pass my root password?
I have to open it lirc in new terminal window.

A: Apart from calling some subcommand in another "terminal window" being a bad idea, that is an issue with the sudo configuration.
Sudo assigns tty cookies to sessions, effectively limiting the session timeout to the tty that got the authentication.
You can prevent this from happening by disabling the tty_tickets option in /etc/sudoers:
Defaults !tty_tickets


text:
Q: Obtener el mes a partir de una columna de la forma YYYY/MM/DD en pandas? Tengo un DataFrame con 2 columnas, "released" y "value".
De la columna "released", que esta en forma de fecha YYYY-MM-DD, quiero obtener simplemente el mes (en números) para después poder usarlo junto a los datos de la columna "value" y hacer un gráfico.
Que debo escribir? ya sea manipulando los strings o usando datetime.
Gracias.

A: Es posible hacerlo de esta forma:
raw_data = {'value': [20, 19, 22, 21],
            'released': ['01-02-1996', '08-05-1997', '04-28-1996', '12-16-1995']}
df = pd.DataFrame(raw_data)
df['mes'] = pd.DatetimeIndex(df['released']).month

   value    released  mes
0     20  01-02-1996    1
1     19  08-05-1997    8
2     22  04-28-1996    4
3     21  12-16-1995   12


text:
Q: How to conquer India in EU4? I am playing as Portugal and my goal from the beginning of the game has been to conquer the entire Indian subcontinent (or at least a very sizable portion) by the game's end. I thought this wasn't too ambitious, and indeed by the beginning of 1600s I held south India. I thought the nice casus belli I acquired earlier in the game to be able to freely conquer Asian and African primitive nations would work nicely. However, something set me back significantly. Since I held Goa from very early in the game, three Indian nations holding about 1/2 of India westernized (picture below, see the icon to the right of Bahmanis signifying technology group). This was apparently because they bordered a nation that was Western and significantly more advanced than they were for a very long time (I acquired Goa early 1500s).
Now my casus belli is gone and I need to fabricate claims for every single province. Not only that, but being westernized, their troops will be much more advanced (and since this is India also very numerous - their numbers were already challenging before westernization and I had to acquire alliances in India to this end).
So, two questions:

*

*What methods can I use to continue the conquest? Should I just give it up?

*How do I prevent the AI from westernizing in the first place?

PS: Westernized nations are Bahmanis, Gujarat and Delhi. Malwa and Bengal remain Indian.

A: I think a very important thing to keep in mind in this situation is that even though these Indian nations may have westernised, their troops will still be vastly inferior to yours as westernising does not give them western units. I have westernised as Ottomans and Russia and have always been stuck with the same troop types I would normally have had. Seems safe to assume the same restriction is valid for AI nations.
If you've been playing this game with a specific goal in mind, I see no reason at all to give up on it. Just create the claims you need and take them out. If the number of provinces and the attached cost in peace settlements threatens you, just develop the "Flexible Negotiations" Idea combined with "State Propaganda" to allow taking massive amounts of territories per war without having the whole world gang up on you.
As for the AI question: there is no way to prevent a non-western nation bordering on a western one that is far more advanced from westernising. You can give them a truly hard time DURING the process though. Having gone through westernisation a couple times myself I can only assume that an AI nation going through that process is also hugely vulnerable.

A: The game tries to mirrow the reality regarding strenght in this time. And there is a reason, why Portugal did not conquer India, but Great Britain. Portugal is too small and has too few armies. You saw this by yourself. If you give a Nation too much time, after you conquered the first area, they westernize and get too difficult to invade. You must be fast at the beginning. If this is not possible, try to concentrate on other areas, like Indonesia, as it was historically. If you really want to conquer India, then either take another nation, like England/GreatBritain, or Spain. Or you do it a bit later, when you have the better cards. Don´t take an area close to them, so they have no chance to westernize. When you feel strong enough, make the invasion in one rush.


text:
Q: Visual code inspector for QT classes and objects To be honest, I think that the QT quick when using widgets is a pretty bad visual tool for front-end developers, It's really hard to find the object you want to edit. I'm working with a big application and there some widgets there were not deleted, I had to create a huge map of all widgets we had, the UI files, and I still need to go to open each file in order to find a button class/object if I want to add some properties on my CSS file. Is there anything that looks like the chrome or firefox inspector, so when you click on the compile file or even on debugging mode on visual studio you can find what objects and classes you are seeing rendered?

A: Yest, there's an GPL tool named GammaRay.


text:
Q: How to select a string between two strings in a column in SQL Server? I want to get the string between two strings in a column of a table. How can I select the column? I have written the strings which are on either side. Can anyone help me how to include the column name with the string here?
DECLARE @Text NVARCHAR(MAX)

SELECT
    SUBSTRING(@Text, CHARINDEX('Manufacturer Name : ', @Text),
                     CHARINDEX('Manufacturer Part',@text) - CHARINDEX('Manufacturer Name : ', @Text) + LEN('Manufacturer Part'))
FROM
    tbIMPACArchiveNew
WHERE
    (Description LIKE '%Manufacturer Name: %'
     OR Description LIKE '%Manufacturer Name : %')
    AND Description LIKE '%Manufacturer Part%'

Expected result:
Column A                                                       Expected result
Manufacturer Name : ABC Manufacturer Part Number : XVB-C2B4         ABC
Manufacturer Name : DEF Manufacturer Part Number : 3RH1924-1GP11    DEF
Manufacturer Name : ABJ Manufacturer Part Number : FLDP-IOM248-0001 ABJ
Manufacturer Name : HIJ Manufacturer Part Number : L12/5MLLD0035    HIJ
Manufacturer Name : abhkdk Manufacturer Part Number : PEH1083510    abhkdk
Manufacturer Name : 1245 PUMP Manufacturer Part Number : 02-1010-55 1245

A: For a sample data of below
declare @table table (id int identity(1,1), data varchar(1000), descr varchar(1000))

insert into @table values ('Manufacturer Name : Manufacturer 1 Manufacturer Part : asjdfj','First Manufacturer')
insert into @table values ('Manufacturer Name : Manufacturer 2 Manufacturer Part : asjsadfasdfdfj','Second Manufacturer')
insert into @table values ('Manufacturer Name : Manufacturer 3 Manufacturer Part : er6ty','Third Manufacturer')

you can use
select substring(data,
                 charindex('Manufacturer Name : ', data) + len('Manufacturer Name : '),
                 charindex('Manufacturer Part : ',data) - len('Manufacturer Part :') - 2) as Manufacturer_Name
       , descr
from @table

If you notice I am removing 2 characters at the end of substring to eliminate 'M' from Manufacturer Part and the Space before the actual text. You can use RTRIM but i chose this way.

A: Here is a way to extract the text between two fixed strings.  Not exactly sure what you were doing with the @Text variable so I used it as an example below.
DECLARE @Text NVARCHAR(MAX) = 'blah blah Manufacturer Name : MY NAME Manufacturer Part blah blah'
SELECT SUBSTRING(@Text, CHARINDEX('Manufacturer Name : ', @Text) + LEN('Manufacturer Name : ') + 1, CHARINDEX('Manufacturer Part',@Text) - (CHARINDEX('Manufacturer Name : ', @Text) + 2 + LEN('Manufacturer Name : ')) )

SELECT SUBSTRING(Description, CHARINDEX('Manufacturer Name : ', Description) + LEN('Manufacturer Name : ') + 1, CHARINDEX('Manufacturer Part',Description) - (CHARINDEX('Manufacturer Name : ', Description) + 2 + LEN('Manufacturer Name : ')) )
FROM tbIMPACArchiveNew
WHERE Description LIKE '%Manufacturer Name : %Manufacturer Part'

A: I think this what you want
SELECT SUBSTRING ( Description , 20 , CHARINDEX("Manufacturer Part") - 20)
FROM  tbIMPACArchiveNew;

where 20 is the length of "Manufacturer Name : "

A: You can get the index of 4th space and remove the first 20.
SELECT SUBSTRING ( Description , 20 , instr(Description,' ',1,4 ) - 20)
FROM  tbIMPACArchiveNew;


text:
Q: Griffon JavaFX sample app can't compile I can't run the sample app from aalmiray's blog "The Griffon Trove: dialogs and JavaFX".

[griffonc] Compiling 1 source file to
  C:\Users\foo.griffon\1.0.1\projects\sample\classes\main Compilation
  error: BUG! exception in phase 'semantic analysis' in source unit
  'C:\Users\foo\sample\griffon-app\views\sample\DialogView.groovy'
  Invalid index

Commenting the import javafx.geometry.Insets helps by compiling.
Groovy Version: 1.8.5 JVM: 1.6.0_24 Vendor: Sun Microsystems Inc.
OS: Windows 7 x64
Griffon Version: 1.0.1
JavaFX Version: 2.1 Runtime
Link is here.

A: It looks to me you're being affected by http://jira.codehaus.org/browse/GRIFFON-517. If this is the case then please make sure you're running latest versions of the JavaFX and GroovyFX plugins. You can quickly check if a plugin requires updates by invoking griffon list-plugin-updates.
You can also check http://artifacts.griffon-framework.org for updates.


text:
Q: How to make an alias link to a Windows server folder On our server (windows 2012) we have a folder for Scan files called server/scans/(username). I know how to setup link from windows PC so that user can access the scans. How do I setup the same thing on a Mac Pro notebook?
I understand Apple calls shortcuts as alias. Before I'd just start a shortcut and type in IP address to setup path. How do I do this on the Mac?

A: Drag to the Dock or Sidebar

*

*You can drag the Folder to your dock (between the trash and the separator to the applications), or to the sidebar in Finder.

Create an Alias
You can also create an Alias:

*

*Click the icon to select (highlight) it, and in the File Menu, choose "Make Alias".

*Drag the folder holding down both the 'Option' ⌥ and 'Command' ⌘ keys together while you release the mouse button (a small arrow will appear in the lower left of the icon).

An Alias, like a Windows shortcut, is an icon that can be placed in any folder or on the desktop.

A: You can go to the Finder Preferences then tick 'Connected Servers' under "Show these items on the desktop."
This worked for me.


text:
Q: animate {ScrollTop} not working correctly for header() tags I have an application in which I have to scroll questions on the basis of label clicked,
The issue is it's not picking up the right height from the offset().top.
According to the clicked label, I have to scroll up and down.
I have Question structure like this

// I am doing something like this, this is the part of the function which is triggered when a particular label is clicked.

     BRAND

      STYLING

      Style cat

$(document).on("click", ".set-label", function(e) {
      var clickedLabel = $(this).text().trim();
      var dim = $(this).parent().parent().next().find('h4');
      var findTag = $(dim).filter(function() {
        if ($(this).text().toString() == clickedLabel.toString()) {
          $('div[class="parentquestion"]').animate({
            scrollTop: $(this).offset().top
          }, 'slow');
        }
      });
    })

BRAND

 Why so serious

    <textarea name="commit[9]"></textarea>

STYLING

 testing this demo

    <textarea name="commit[10]"></textarea>

Style cat

 propaganda invasion

    <textarea name="commit[11]"></textarea>

this is my css for parentquestion
    .parentquestion {
    overflow-y: scroll;
    float: left;
    width: 80%;
    height: 490px;
    margin-top: 70px;
}

may be thats creating issue.
when I click any label its scrolls up and down but not to the required  tag. Am I doing something wrong? Is offset() correctly calculating the height in reference to its parent which is $('div[class="parentquestion"]').

A: This may help you. I use $('html, body') instead of $('div[class="parentquestion"]') and place all the set-label element to single div.

// I am doing something like this, this is the part of the function which is triggered when a particular label is clicked.

$(document).on("click", ".set-label", function(e) {

      var clickedLabel = $(this).text().trim();
      var dim = $(this).parent().next().find('h4');

      var findTag = $(dim).filter(function() {

        if ($(this).text().toString() == clickedLabel.toString()) {

          $('html, body').animate({
            scrollTop: $(this).offset().top
          },'slow');
        }
      });
    })

BRAND

STYLING
Style cat

BRAND

 Why so serious

    <textarea name="commit[9]"></textarea>

STYLING

 testing this demo

    <textarea name="commit[10]"></textarea>

Style cat

 propaganda invasion

    <textarea name="commit[11]"></textarea>

head 4

 sub head 4

    <textarea name="commit[11]"></textarea>

head 5

 subhead 5

    <textarea name="commit[11]"></textarea>

A: You need to define an Id for the h2 tags.
    ...

A: well i finally solved it myself,
$(document).on("click", ".set-label", function(e) {
  var clickedLabel = $(this).text().trim();
  var dim = $(this).parent().parent().next().find('h4');
  var findTag = $(dim).filter(function() {
  if ($(this).text().toString() == clickedLabel.toString()) {
  var childOffset = $(this).position().top + $('.parentquestion').scrollTop() - $(this).height();
      $('div[class="parentquestion"]').animate({
        scrollTop: childOffset}, 'slow');
    }
  });
})

The trick was to calculate its current position $(this).position().top and add it to its parent height which is $('.parentquestion').scrollTop() and i was getting extra height of that  tag so I subtracted it from it using $(this).height()
And I have to use $('div[class="parentquestion"]').animate as I want only this particular div to be scrollable, not the whole document as I have many div's on my page,
Hope this will help all.


text:
Q: Index array based on value limits of another Let's say I have an array (or even a list) that looks like:
tmp_data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And then I have another ray that are distance values:
dist_data = [ 15.625  46.875  78.125 109.375 140.625 171.875 203.125 234.375 265.625 296.875]

Now, say I want to create a threshold of distance that I would like to perform an operation on from tmp_data. For this example, let's just take the max value. And let's set the threshold distance to 100. What I would like to do is take the n number of elements every 100 distance units and replace all elements in that with the maximum value in that small array. For example: I would want the final output to be
max_tmp_data_100 = [2,2,2,5,5,5,8,8,8,9]

This is because the first 3 elements in dist_data are below 100, so we take the first three elements of tmp_data (0,1,2), and get the maximum of this and replace all elements in there with that value, 2
Then, the next set of data that would be below the next 100 value would be
tmp_dist_array_100 = [109.375 140.625 171.875]
tmp_data_100 = [3,4,5]
max_tmp_data_100 = [5,5,5]
(append to [2,2,2])

I have come up with the following:
# Initialize
final_array = []
d_array = []
idx = 1

for i in range(0,10):
    if dist_data[i] < idx * final_res:
        d_array.append(tmp_data[i])
    elif dist_data[i] > idx * final_res:
        # Now get the values
        max_val = np.amax(d_array)
        new_array = np.ones(len(d_array)) * max_val
        final_array.extend(new_array)
        idx = idx + 1

But the outcome is
[2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 5.0, 5.0]

When it should be [2,2,2,5,5,5,8,8,8,9]

A: You can do with groupby
from itertools import groupby

dist_data = [ 15.625, 46.875 ,78.125 ,109.375 ,140.625 ,171.875 ,203.125 ,234.375, 265.625 ,296.875]
tmp_data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []

index_list = [[dist_data.index(i) for i in l]
               for k, l in groupby(dist_data, key=lambda x:x//100)]
for i in tmp_data:
    for lst in index_list:
        if i in lst:
            result.append(max(lst))

print(result)
# [2, 2, 2, 5, 5, 5, 9, 9, 9, 9]

A per your requirements last 4 elements will comes under next threshold value, the max of last 4 element is 9.

A: With numpy:
import numpy as np

cdist_data = [15.625, 46.875, 78.125, 109.375, 140.625, 171.875, 203.125, 234.375,265.625, 296.875]
cut = 100

a = np.array(dist_data)
vals = np.searchsorted(a, np.r_[cut:a.max() + cut:cut]) - 1
print(vals[(a/cut).astype(int)])

It gives:
[2 2 2 5 5 5 9 9 9 9]


text:
Q: MFC tooltip for list control of dialog box I have developed on application, which shows a dialog box with two list controls.
In this list control, I am showing images. Now I want is, when we move the mouse on images from the list control of dialog box, It will show tool tip for that.
How can I show tool tips for images in a list control in a dialog box?

A: The CToolTipCtrl control is the MFC wrapper class around the Win32 "tool tip". You can use this to display a small pop-up window to describe another control or provide additional information in your app.
If you're using a ListBox control, explore one of these sample projects to see how to display tooltips for individual items displayed within that ListBox control:

*

*ListBox With ToolTip Support

*List Box With ToolTips
And if you're using a ListView control (CListCtrl in MFC), then you should start by reading the documentation for the GetToolTips function and the corresponding SetToolTips function. You can also check out how this sample ListView control implements tooltips:

*

*CListCtrl and Displaying a Tooltip


text:
Q: Wordpress Plugin Update Failed Could not copy file error occurs I'm using amazon web server and while updating any plugin an "Update Failed: Could not copy file" error occurs.
I have set /opt/bitnami/apps/wordpress/htdocs and  /opt/bitnami/apps/wordpress/htdocs/wp-content to 777, but still my plugins are not updating.

A: I found the solution
sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs
sudo find /opt/bitnami/apps/wordpress/htdocs -type f -exec chmod 664 {} \;
sudo chmod 640 /opt/bitnami/apps/wordpress/htdocs/wp-config.php
sudo find /opt/bitnami/apps/wordpress/htdocs -type d -exec chmod 775 {} \;

After that, please restart services and try to update plugins again
sudo /opt/bitnami/ctlscript.sh restart


text:
Q: What does a scoped lifetime in rust actually mean? So, in:
fn v1<'a> (a:~[&'a str]) -> ~[&'a str] {
  return a;
}

#[test]
fn test_can_create_struct() {
  let x = v1("Hello World".split(' ').collect());
}

I know, I've read http://static.rust-lang.org/doc/master/guide-lifetimes.html#named-lifetimes, but I don't understand what this code actually does.
The function is basically parametrized like a generic fn but with a lifetime, is what I've seen said on the IRC channel, but lets imagine that is the case, and we have a L, which is some specific lifetime structure.
Apparently I'm implicitly calling:
v1::<L>("Hello World".split(' ').collect());

..but I'm not. The lifetime being passed to this function is an instance of a lifetime, its not a TYPE of lifetime, so that comment doesn't make any sense to me.
I mean, I basically understand whats going on (I think): The returned ~[&str] has the same lifetime as the scope of the caller, presumably the test_can_create_struct() function. That's because (as I understand it) the function v1 is invoked with the lifetime instance from the calling function.
Very confusing.
Then we have some other examples like:
https://gist.github.com/bvssvni/8970459
Here's a fragment:
impl<'a> Data<'a> {
  pub fn new() -> Data<'a> {
    Data { a: None, b: None }
  }

  pub fn a(&'a mut self, a: int) -> State<'a, Step1> {
    self.a = Some(a);
    State { data: self }
  }
}

Now here I naively assumed that the Data<'a> means that the lifetime instance for the function a() is the same.
i.e. If you create a Data (let blah = Data::new()) and call blah.a(), the lifetime is inherited from the create call; i.e. the State object returned will exist for as long as the parent Data object does.
...but apparently that's wrong too. So I have just no idea what the lifetime variables mean at all now.
Help!

A: So the easiest way to answer this will be to take a step back and walk you through what a lifetime actually is.
Lets take a simple function:
fn simple_function() {
  let a = MyFoo::new();
  println("{}", a);
}

In this function, we have a variable, a. This variable, like all variables, lives for a certain amount of time. In this case, it lives to the end of the function. When the function ends, a dies. The lifetime of a, can then be described as starting at the beginning of the function, end ending at the end of the function.
This next function won't compile:
fn broken_function() -> &MyFoo {
  let a = MyFoo::new();
  return &a;
}

When you do &a, you are borrowing a reference to a. The thing about borrowing, though, is that you are expected to give the thing you borrowed back. Rust is very strict about this, and won't let you have references you can't return. If the thing you borrowed your reference from isn't around any more, you can't return the reference and that's just not on.
What it means for our broken_function is that, because a dies at the end of the function, the reference can't escape the function, because that would make it outlast a.
The next step is this:
fn call_fn() {
  let a = MyFoo:new();
  {
    let a_ref = &a;
    let b = lifetimed(a_ref);

    println!("{}", *b);
  }
}

fn lifetimed<'a>(foo: &'a MyFoo) -> &'a MyBar {
   return foo.as_bar();
}

Here are two functions, call_fn and lifetimed, there's some subtle stuff going on here, so I'll break it down.
In call_fn I first create a new instance of MyFoo and assign it to a, then, I borrow a reference to a and assign it to a_ref. The thing with borrowing is that when you do a borrow, the lifetime information is transfered from the variable you are borrowing, into the reference itself. So now a_ref, as a variable, has its own lifetime, which starts and ends at the beginning and end of that inner scope, but the type of a_ref also has a lifetime, the one transferred over from a.
Concrete lifetimes can't be named, but lets pretend we can do it anyway by using numbers. If the lifetime of a is #1, then the type of a_ref is &'#1 MyFoo. When we pass a_ref to lifetimed, the compiler fills in the lifetime parameter 'a like it does for other type parameters. lifetimed's return type is a reference with the same lifetime, so the compiler fills in the space there. Effectively making a unique call to lifetimed(foo: &'#1 MyFoo) -> &'#1 MyBar.
This is why lifetimes appear in the type parameter list, they are part of the type system, and if the types don't match up, that's an error. The compiler works out the lifetimes needed in order for the function to compile, so you never have to worry about it, but won't look outside the current function to get more information. You need to use the parameters to tell the compiler about the function you're calling so it knows that everything is ok.

NB: There is one lifetime you can explicitly name. 'static which is the lifetime of things that last for the entire length of the program.


text:
Q: Debugging AngularJS Code in JHipster (Intellij) I am running Application.java from within IntelliJ and Grunt Serve from the Command Window. Thus, I can debug Java code and Live Reload changes to Html. But I cannot set breakpoints or trace Javascript files.
I know I could debug in Chrome, but I rather debug in IntelliJ if at all possible.
I would appreciate any suggestions.

*

*Thanks

A: You should be able to do this with the NodeJS plugin for IntelliJ. I have it installed on my machine and I'm able to right-click on my project's Gruntfile.js and select Run or Debug.


text:
Q: Retrofit display request details - body, headers, etc I can't seem to find anything in Retrofit docs regarding how to display any Request details.
Specifically, I want to see JSON from POST Request Body.
The problem is that my request to the server fails with no details message, and I suspect that something is wrong on my side.

A: here is an updated answer for retrofit 2.0
 HttpLoggingInterceptor body = new HttpLoggingInterceptor();
        body.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(body);

        OkHttpClient client = builder.build();

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)

A: Maybe there is a better way to achieve this, but you can configure your log level using the RestAdapter.Builder like:
   RestAdapter.Builder builder=...
   builder.setLogLevel(LogLevel.FULL).setLog(new RestAdapter.Log() {
            public void log(String msg) {
               Log.i("retrofit", msg);
            }
        });


text:
Q: Are there any common phrases in the English language that use metric units of measurement? We've got things like 'inch closer' or 'miss by miles' but nothing common that uses the metric system as far as I know.

A: There are a lot of expressions using second, which is metric. Of course, here the fact that the unit predates the SI system is a strong influence.
Gram is beginning to replace ounce, grain and other small units in expressions where it would once have been used, so we can find people using "gram of sense", "gram of truth" etc.
Calorie appears in a few expressions related to health, diet and exercise and as such generally referring to a "large calorie" (kcal) rather than a "small calorie" (cal) since large calories are what are conventionally used by food. This unit used to be part of the metric system, and can be considered as part of it in conventional use, though it is no longer used in the SI and so you might decide not to include it as "metric" or not.
Megahertz is sometimes used to as a metonym for internet connection speeds and computing power. "Is someone taking all the megahertz?" might be a joking complaint by someone on a shared network, and there are variations of this:

We will no doubt begin to see more such expressions as young people increasingly don't learn the obsolete units, though the history of the language, and the fondness of the US for being quaint, will likely keep them in the language for some time. After all, we still have farthing and (rarely) even sou used to mean "very small amount of money" though increasingly the people using them may have never seen a farthing, or even know what a sou is.

A: In Australian English we would say "It's only five kay's to the pub" or "Sydney to Brissie, about a thousand klicks"


text:
Q: Why is UserDataSet being created twice by UserState? I implemented a Chatbot with MS Botframework v4. I use UserState and ConversationState and my MemoryStorage is a BlobDB from Azure.
When I run my bot, I get two datasets for the UserState and only one for ConversationState.
At some point in my dialogs, the Bot seems to "switch" to another UserState dataset and everything previously saved in the old set is not accessible anymore.
This happens pretty early in in the conversation.
This is my onTurn. Here I access UserState and ConversationState for the first time:
async onTurn(turnContext) {

        const dc = await this.dialogSet.createContext(turnContext);

        //await logMessageText(this.memoryStorage, turnContext, this.userState);

        // See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types.
        if (turnContext.activity.type === ActivityTypes.value){
            console.log(turnContext.activity.type.value);
        }

        if (turnContext.activity.type === ActivityTypes.Message) {
            // Continue ongoing dialog
            await dc.continueDialog();
        } else if (turnContext.activity.type === ActivityTypes.ConversationUpdate) {
            // Do we have any new members added to the conversation?
            if (turnContext.activity.membersAdded.length !== 0) {
                // Iterate over all new members added to the conversation
                for (var idx in turnContext.activity.membersAdded) {
                    // Greet anyone that was not the target (recipient) of this message.
                    // Since the bot is the recipient for events from the channel,
                    // context.activity.membersAdded === context.activity.recipient.Id indicates the
                    // bot was added to the conversation, and the opposite indicates this is a user.
                    if (turnContext.activity.membersAdded[idx].id !== turnContext.activity.recipient.id) {

                        // Funktionierender Code, wenn WebChat gefixt
                        console.log("User added");

                        // Read ConversationData from State
                        const conversationData = await this.conversationDataAccessor.get(turnContext, {});
                        const user = await this.userDataAccessor.get(turnContext, {});

                        // Get userID which is either IDA for advisory or IDR for result
                        conversationData.URLparam = turnContext.activity.membersAdded[idx].id;

                        // Manually set userId for Emulator use
                        conversationData.URLparam = "1234A";

                        // Set userID
                        if (!conversationData.userID) {
                            console.log("UserID wird eingetragen");
                            conversationData.userID = conversationData.URLparam.substring(0, conversationData.URLparam.length-1);
                            console.log("Eingetragene user ID:" + conversationData.userID);
                        }

                        // Get last character which determines mode
                        conversationData.mode = conversationData.URLparam.substring(conversationData.URLparam.length-1, conversationData.URLparam.length);

                        // Write user and conversationdata to State
                        await this.conversationDataAccessor.set(turnContext, conversationData);
                        await this.userDataAccessor.set(turnContext, user);

                        // Route to correct dialog depending on treatment and bot type
                        if (treatment.initiation == true && conversationData.mode.localeCompare("A") == 0) {
                            console.log("Advisory Modus");
                            await dc.beginDialog('welcome', conversationData.userID);
                        } else if (treatment.initiation == false) {
                            await dc.beginDialog('startBot', conversationData.userID);
                        } else if (treatment.initiation == true && conversationData.mode.localeCompare("R") == 0) {
                            console.log("Result Modus");
                            await dc.beginDialog('investmentResult', conversationData.userID)
                        }
                    }
                    if (turnContext.activity.membersAdded[idx].id === turnContext.activity.recipient.id) {
                        // Start the dialog.
                        console.log("Bot joined");

                    }
                }
            }
        }

My first dialog 'welcome' and then 'promptForName' is called. Everything works fine in the next code snippet:
// Function for welcoming user
    async welcomeUser (step) {
        console.log("Welcome User Dialog");

        // Get userId from onTurn()
        const userID = step.options;

        // Get conversation- and userData from bot state
        const conversationData = await this.conversationDataAccessor.get(step.context, {});
        const user = await this.userDataAccessor.get(step.context, {});

        console.log("User in welcome dialog");
        console.log(util.inspect(user, false, null, false ));

        console.log("conversationData from Middleware");
        console.log(util.inspect(conversationData, false, null, false ));

        // Write user and conversationdata to state
        await this.userDataAccessor.set(step.context, user);
        await this.conversationDataAccessor.set(step.context, conversationData);

        // Welcome the user
        if (treatment.introduction == true && treatment.rememberName == true && treatment.gender == true) {
            await sendWithDelay("Hallo und herzlich willkommen, ich bin **Charles**, dein persönlicher **Investmentberater**. Ich begleite dich durch den Beratungsprozess.", step);
        } else if (treatment.introduction == true && treatment.gender == false) {
            var msg = "Hallo und herzlich willkommen, ich bin ein **Robo-Advisor**. Ich begleite dich durch den Beratungsprozess.";
            await sendWithDelay(msg, step);
        } else if (treatment.introduction == false && treatment.selfReference == false && treatment.rememberName == false) {
            var msg = "Du wirst nun durch den Beratungsprozess begleitet.";
            await sendWithDelay(msg, step);
        }

        // Check if bot in testmode and route to dialogs
        if (testing == true) {
            // Start main dialog
            return await step.beginDialog('mainMenu', userID);
        } else {
            // Start Profilecreation
            return await step.beginDialog('createProfile', userID);
        }
    }

    // Functions for creating UserProfile
        async promptForName (step) {
            console.log("Name Prompt");

            // Get userID from prior step and clear changes
            const userID = step.options;

            // Read UserData from State
            const user = await this.userDataAccessor.get(step.context, {});
            const conversationData = await this.conversationDataAccessor.get(step.context, {});

            // Save User- and Conversationdata to State
            await this.userDataAccessor.set(step.context, user);
            await this.conversationDataAccessor.set(step.context, conversationData);

            // Before prompting, check if value already exists
            if(!user.name){
                if (user.deleted == true) {

                        if (treatment.selfReference == true) {
                            var msg = "Ich stelle dir nun die gleichen Fragen erneut.";
                            await sendWithDelay(msg, step);
                        } else {
                            var msg = "Im folgenden nochmal die gleichen Fragen.";
                            await sendWithDelay(msg, step);
                        }
                } else {
                        if (treatment.selfReference == true) {
                            var msg = "Ich stelle dir nun ein paar Fragen, um deine wichtigsten Daten zu erfassen.";
                            await sendWithDelay(msg, step);
                        } else {
                            var msg = "Im folgenden ein paar Fragen, um deine wichtigsten Daten zu erfassen.";
                            await sendWithDelay(msg, step);
                        }

                }
                // Username doesn't exist --> Prompt
                await delay(userData.name.prompt, step).then(async function() {
                    return await step.prompt(NAME_PROMPT, userData.name.prompt);
                });
            } else {
                return await step.next();
            }
        }

In the next snippet, where the user's reply is written to userData, suddenly a new dataSet is created.
async promptForAge (step) {
            console.log("Age Prompt");

            // Get userID from prior step and clear changes
            var userID = step.options;

            // Get UserData from State
            const user = await this.userDataAccessor.get(step.context, {});

            console.log("User in age dialog");
            console.log(util.inspect(user, false, null, false ));

            // Before saving entry, check if it already exists
            if(!user.name) {

                user.name = step.result;

                // Write userData to State
                await this.userDataAccessor.set(step.context, user);

                // Notify user about his name being remembered
                if (treatment.rememberName == true) {
                    var msg = `Hallo **${user.name}**! Danke, dass du mir deinen Namen verraten hast. Ich werde ihn mir ab jetzt merken.`;
                    await sendWithDelay(msg, step);
                }
            }
            // Before prompting, check if value already exists
            if(!user.age) {
                await delay(userData.age.prompt, step).then(async function() {
                    return await step.prompt(AGE_PROMPT, userData.age.prompt);
                });

            } else {
                return await step.next();
            }
        }

This is how the datasets look in my DB:

This is the content of the two user datasets:
The first one that is being created
{"id":"emulator%2Fusers%2Fdeb871a4-cbb9-4e3c-9fff-e9ed88f597f5","realId":"emulator/users/deb871a4-cbb9-4e3c-9fff-e9ed88f597f5/","document":{"userData":{},"eTag":"*"}}

The one that's being created once step.result is written to user.name:
{"id":"emulator%2Fusers%2Fr_72zsnsmmnp","realId":"emulator/users/r_72zsnsmmnp/","document":{"userData":{"name":"John Doe"},"eTag":"*"}}


text:
Q: How early can scientists detect that a deadly asteroid will hit planet earth? With the advancements in science and technology, how early can scientists of the world detect that a certain asteroid will hit planet earth and cause damage? Are there any impact avoidance strategies or a disaster recovery plan agreed upon by world nations?
Edit: This wikipedia article shows some links to few past projects

A: The world's leader in the detection is NASA's Near-Earth Object Program

http://neo.jpl.nasa.gov/

which observes the objects and calculates their future locations. The Palermo scale and the Torino scale are being used to quantify the degree of the threat. Currently, there are just two objects that have a nonzero Palermo scale (namely the level 1, the minimal one after zero) and could hit in the 2040s and 2050s, see the table

http://neo.jpl.nasa.gov/risk/

but chances are that they will go away. These particular examples – with diameters 130-140 meters - would only cause havoc at the regional or continental scale; objects with diameter below 20 meters or so may be ignored because they pretty much burn in the atmosphere. The chances of collision are 1 in 500 and 1 in 1800 or so, respectively.
It's actually rather unlikely that a major enough collision in the next 2-3 decades is being overlooked by this program; it is reliable enough. For this reason, we would have enough time to prepare. Various methods to deflect the asteroids by nuclear detonations that "peel" a piece from the asteroid etc. have been discussed – they even made it to movies – but of course that there is no particular agreed policy because there is no particular threat.
More generally, I want to say that it is kind of irrational to be preparing for a truly dangerous event if the event only occurs less than once per million years. There are many threats around us that are arguably much more likely to kill us – e.g. various biological scenarios (pandemics). If you imagine that at some point, the threat becomes really high but it is more than 20 or 30 or more years in the future, it would still be reasonable not to panic and leave at least a decade for a careful thinking, planning, and competition between projects, which could be realized in the rest of the time. The technological progress and improvement of ideas could be substantial and probably more beneficial than the efforts to "solve it right away".
Also, I don't think it's right to suggest that the solution would be led by some international bureaucracy under the United Nations etc. It's pretty clear that one agency, most likely NASA, would lead all the activities so it would be de facto done by one nation (or at most, one confederation such as the EU and ESA), depending on the likely location of the collision point and other things. The U.N.-based institutions have been found largely dysfunctional in their treatment of sufficiently hi-tech challenges due to corruption and the unprofessional, low-tech "activist" approach by most participants.


text:
Q: Replacing javascript nashorn:mozilla_compat.js use in ant script Oracle has depreciated nashorn and I use it in my apache ant build scripts.
Here is a short example;
try{load("nashorn:mozilla_compat.js");}catch(e){;}
    importClass(java.io.File);
    var sourceName = project.getProperty("build.source.dir") + "/" +project.getProperty("teiFile") + ".xml";
    var targetName = project.getProperty("build.search.dir") + "/" + project.getProperty("teiFile") + ".xml";
    var sourceFile = new File("", sourceName);
    var targetFile = new File("", targetName);
    var uptodate = targetFile.exists() && sourceFile.lastModified() < targetFile.lastModified();
      var sourcePrefix = project.getProperty("teiFile");
      if(!uptodate & !sourcePrefix.startsWith("G")) {
         ......
       }
}

I've heard mentions of Rhino or graalVM as a replacement, but each seems to have a fairly long list of deficiencies.Suggestions for a library that is currently active and stable.
thanks, scott

A: GraalVM is currently active, stable, has a Nashorn compatibility mode.
You can run your ant scripts with GraalVM, and the JS engine is included by default. Or you can include GraalVM's JavaScript as a few dependencies and run on OpenJDK, which will be slower, and might be an untested combination of OpenJDK and GraalVM's JavaScript, but can also work.


text:
Q: Chef server upgrade issue - encoding on non-encoding capable object I'm trying to upgrade my existing chef server from 12.19.31 to 13.3.1.
I built this version using the instructions on https://github.com/chef/chef-server
Then I installed the package.
sudo dpkg -i chef-server-core_13.3.1+20201008233604-1_amd64.deb (Reading database ... 153055 files and directories currently installed.) Preparing to unpack chef-server-core_13.3.1+20201008233604-1_amd64.deb ... Unpacking chef-server-core (13.3.1+20201008233604-1) over (12.19.31-1) ... Setting up chef-server-core (13.3.1+20201008233604-1) ... You have upgraded Chef Server!

The next step in the upgrade process is to run:

chef-server-ctl upgrade

After the upgrade command completes, your Chef services will remain in a down state. To bring them back up run:

chef-server-ctl start

Then, to remove configuration files, logs, directories, users, etc. that were used by internal services that have been removed from this version of Chef Server, please run:

chef-server-ctl cleanup

(Add the '--no-op' option to see what would be removed by this command)

For detailed upgrade instructions please see: https://docs.chef.io/upgrade_server.html

Then I ran the command chef-server-ctl upgrade
------------------------------------------------------------------- The service postgresql is running externally and cannot be managed vi
chef-server-ctl.  Please log into chef-dev-db-tawny.tinyspeck.com to
manage it directly.
------------------------------------------------------------------- /opt/opscode/embedded/service/gem/ruby/2.6.0/gems/sequel-3.34.1/lib/sequel/database/schema_generator.rb:19:
warning: constant ::Fixnum is deprecated
/opt/opscode/embedded/service/gem/ruby/2.6.0/gems/sequel-3.34.1/lib/sequel/database/schema_generator.rb:19:
warning: constant ::Bignum is deprecated [private-chef-upgrade] -
ERROR: migration-level not initialized. [private-chef-upgrade] -
ERROR: If this is an existing Chef Server install try running
`chef-server-ctl rebuild-migration-state` and then retry the upgrade

Finally I ran sudo chef-server-ctl rebuild-migration-state and I'm getting the following error,
/opt/opscode/embedded/service/gem/ruby/2.6.0/gems/sequel-3.34.1/lib/sequel/database/schema_generator.rb:19:
warning: constant ::Fixnum is deprecated
/opt/opscode/embedded/service/gem/ruby/2.6.0/gems/sequel-3.34.1/lib/sequel/database/schema_generator.rb:19:
warning: constant ::Bignum is deprecated [private-chef-upgrade] -
Infering migration-level from system state bundler: failed to load
command: ./bin/partybus (./bin/partybus) ArgumentError: cannot set
encoding on non-encoding capable object
/opt/opscode/embedded/service/partybus/lib/partybus/migration_api/v1.rb:123:in
`exec'
/opt/opscode/embedded/service/partybus/lib/partybus/migration_api/v1.rb:123:in
`check_sqitch'   (eval):13:in `block in load_migration'
/opt/opscode/embedded/service/partybus/lib/partybus/migration_api/v1.rb:16:in
`instance_eval'
/opt/opscode/embedded/service/partybus/lib/partybus/migration_api/v1.rb:16:in
`initialize'
/opt/opscode/embedded/service/partybus/lib/partybus/dsl_runner.rb:42:in
`new'
/opt/opscode/embedded/service/partybus/lib/partybus/dsl_runner.rb:42:in
`run_check'
/opt/opscode/embedded/service/partybus/lib/partybus/dsl_runner.rb:25:in
`check'
/opt/opscode/embedded/service/partybus/lib/partybus/migrations.rb:46:in
`run_check'
/opt/opscode/embedded/service/partybus/bin/partybus:90:in `block in
infer_migration_state'
/opt/opscode/embedded/service/partybus/bin/partybus:89:in `each'
/opt/opscode/embedded/service/partybus/bin/partybus:89:in
`infer_migration_state'
/opt/opscode/embedded/service/partybus/bin/partybus:168:in `block in
<top (required)>'
/opt/opscode/embedded/service/partybus/bin/partybus:159:in `open'
/opt/opscode/embedded/service/partybus/bin/partybus:159:in `<top
(required)>'

I'm stuck and can't figure out what's going on. Any help would be highly appreciated.

A: I ran into the same exact issue (except for slightly different versions) and was able to solve the issue with the following steps:

*

*Deploy a new chef infra server using the version you're migrating from (i.e. v12.19.31)

*Copy /var/opt/opscode/upgrades/migration-level from the new server (created in step 1) to the original server you're trying to upgrade.

*Re-run chef-server-ctl upgrade on the server you're trying to upgrade.


text:
Q: InfluxDB checks with dynamic thresholds Looking at the examples for creating checks in InfluxDB I can only find examples for checks that have fixed thresholds. This example check query is made using the UI-interface:
import "influxdata/influxdb/monitor"
import "influxdata/influxdb/v1"

data = from(bucket: "FirstBucket")
    |> range(start: -5s)
    |> filter(fn: (r) => r["_measurement"] == "PLC1/Reg400003" or r["_measurement"] == "PLC1/Reg400001" or r["_measurement"] == "PLC1/Reg400002")
    |> filter(fn: (r) => r["_field"] == "value")
    |> aggregateWindow(every: 5s, fn: mean, createEmpty: false)

option task = {name: "MyFirstCheck", every: 5s, offset: 0s}

check = {_check_id: "09b2b2f731634000", _check_name: "MyFirstCheck", _type: "threshold", tags: {myFirstCheckTag: "myFirstCheckTagValue"}}
info = (r) => r["value"] > 0.5    //Fixed threshold
crit = (r) => r["value"] > 35.0   //Fixed threshold
warn = (r) => r["value"] > 3.0    //Fixed threshold
messageFn = (r) => "Check: ${ r._check_name } is: ${ r._level }"

data |> v1["fieldsAsCols"]() |> monitor["check"](
    data: check,
    messageFn: messageFn,
    info: info,
    crit: crit,
    warn: warn,
)

What would be the best way to change that to thresholds that are, for instance, read from  an external source? Maybe I can replace the fixed thresholds with tag-values?

A: So I did some digging and came up with this solution:
import "csv"
csvData =
    "
_measurement,Max,Min
PLC1/Reg400001,15.43,1
PLC1/Reg400002,16.43,2
PLC1/Reg400003,17.43,3
PLC1/Reg400004,18.43,4
"

thresholds=csv.from(csv: csvData, mode: "raw")

tData=from(bucket: "FirstBucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "PLC1/Reg400001" or r["_measurement"] == "PLC1/Reg400002" or r["_measurement"] == "PLC1/Reg400003")
  |> filter(fn: (r) => r["_field"] == "value")

join(tables: {t1: thresholds, t2: tData}, on: ["_measurement"], method: "inner")

The join function adds the Max and min columns to the query result. These columns can be used as externally provided thresholds for generating checks (the CSV can be read from a URL later). This solution has no need for an SQL server.


text:
Q: Need all records of left table but IF there's a match on right table I have further restrictions I've found very similar questions all involving the problem of restrictions in the WHERE clause defeating the desired effect of the LEFT JOIN. But I'm not able to extend those problems and answers to my situation.
I need all the records of left table regardless of match in the right. IF there's a match on the right table, there will likely be multiple matches, and I run a subquery to get the correct one.
Left table has a key and a billing period name for each row, right table has the same key and dated transactions. If there's a match on the key, then I need to return just the record from the right table having a transaction date that is most recent one for the corresponding billing period in the matching left table record.
So, because the WHERE statement for choosing the correct matching record from the right table is a subquery, I can't stick it in the ON portion of my LEFT JOIN.
My next approach will be to go ahead and let the thing run as an inner query, then UNION those results with a second query to pick up the non-matching left-table records. That sounds awful, but I'm no stranger to brute force approaches.
key1 billing_period                   key2      date     value
 1    period_1                         1        date_1     a1
 2    period_1                         1        date_2     a2
 3    period_1                         1        date_3     a3
 4    period_1                         3        date_1     a4
                                       3        date_4     a6

desired output is
 1   period_1  date_2  a2
 2   period_1
 3   period_1  date_4  a6
 4   period_1

because a) I want all records from the left table, and b) date_2 was the correct date to choose for among those having a key value of 1, and date_4 met the criteria among all dates available having a match on a key value of 3. Those dates were the latest dates still falling within the respective period_x.
The pseudocode is 'if there's a match key1 = key2, then for all such matches return the one having the latest date that's within the billing_period. if there is NOT a match at all, just return the left table record'.

A: Basically you need a left join with a condition:
A LEFT JOIN B
WHERE B.SomeColumn IS NULL OR (some condition)

A: I could find no way to put a condition on the join itself, and in fact the key to the solution for me was to ensure there was no condition at all--in order to allow LEFT JOIN to do the work. So, they key here was to ensure the right table was the correct table before attempting the join.
For this problem, I first did the (pseudo) query
SELECT key, value, bp.period as period
FROM rtable, bp
WHERE rtable.date = (SELECT max(rtable2.date) from rtable2, bp2
    WHERE rtable2.date BETWEEN bp2.start AND bp2.end
    AND bp2.period = bp.period)

then did my LEFT JOIN on this AS [alias] ON key AND period. Seems to have worked perfectly.
In my problem statement I included the date values from the right table as output, when in fact I don't actually need to see those dates. Poor problem definition on my part. I'll take more time with the example next time.


text:
Q: How do you cycle through items in a Relationship? This is the current code:
Class %Utcov.Test Extends %RegisteredObject
{

ClassMethod listClasses(ns As %String, projectName As %String)
{
    // Switch namespaces to the new one
    new $namespace
    set $namespace = ns

    // Grab our project, by name; fail otherwise
    // TODO: failing is CRUDE at this point...
    #dim project as %Studio.Project
    #dim status as %Status

    // TODO: note sure what the "concurrency" parameter is; leave the default
    // which is -1
    set project = ##class(%Studio.Project).%OpenId(projectName, /* default */, .status)

    if ('status) {
        write "Argh; failed to load", !
        halt // meh... Ugly, f*ing ugly
    }

    w project.Items
}

ClassMethod main()
{
    do ..listClasses("USER", "cache-tort-git")
}

}

First things first: I know that the code sucks... But that's the learning curve, I will eventually do better... The problem I want to solve here is this line:
w project.Items

At the console, it currently prints:
2@%Library.RelationshiptObject

but what I'd like to do is of course to cycle through these objects, which, according to the documentation, are "instances" of %Studio.ProjectItem.
How do I cycle through these? WRITE doesn't cut it, and in fact I surmised from the start that it would not... I just cannot figure out how this is done in ObjectScript :/

A: When your writed object with w project.Items, you got such string 2@%Library.RelationshiptObject, this string may help in understanding what the object we got, and in this case it is an object of class %Library.RelationshiptObject, when you open this class in documentation, you may find some methods which could help you.
Here you can find some examples, how to work with relationships, in objects way and with sql.

A: Set tKey = ""
For {
    ;tItem will be the first item in your list which will be ordered by OREF
    Set tItem = project.Items.GetNext(.tKey)
    Quit:(tKey = "")
    ;Do whatever you want with tItem
}


text:
Q: Map Reduce on timestamps Mongodb Database:
{"thread": "abc", "message": "hjhjh", "Date": (2010,4,5,0,0,0)}
{"thread": "abc", "message": "hjhjh",  "Date": (2009,3,5,0,0,0)}
{"thread": "efg", "message": "hjhjh",  "Date": (2010,3,7,0,0,0)}
{"thread": "efg", "message": "hjhjh",  "Date": (2011,4,5,0,0,0)}

How can I Map-Reduce or aggregate on the above data to generate an output as:
{"thread": "abc", "messages_per_month": 5}
{"thread": "efg", "messages_per_month": 4}

I am trying to write some code but its difficult to average on unsorted dates. Are there any built in functions averaging on time to do this?

A: You could do min/max on the dates like described here for numbers and just add a counter for the messages. The result would be a list of threads with the number of messages and min/max date. From the dates you can calculate the number of months which you can then use to average on the number of messages.
Edit: updated link with link to archived version


text:
Q: How to handle JS serialized item in PHP? Hey guys!
I am having a bit of trouble handling the data from a submitted form that is serialized with JS.
In the form there a textarea fields which users can input any text they want but when they enter & like "apples & oranges", I have trouble handling that.  As we know that JS serializes & to %26 and spaces with a "+" sign.
So now back in PHP, I am trying to put this data into the database and call it back out elsewhere but for the life of me don't know how to handle the special characters properly.
Note that I am also php exploding the data at the "&" sign to make it into an array, then is put into the database as an array.  I tried several methods like urldecode, htmlentities but those don't help because remember I need to explode at "&".
I am serializing in JS because its an AJAX submitting form.

A: What about url*decode*?

A: parse_str()

A: If something is serialized in JS and then sent to a PHP script - it can only be via GET or POST method, which in return means that the serialized data will be stored in one of the following arrays: $_GET if method was GET, $_POST if method was POST and $_REQUEST regardless of the method (so you can capture both POST and GET variables with a single array).
That means that you shouldn't have your custom function that creates from and to php array since it's already done for you.
If you want to store the array in string format, you should serialize that array before storing it into the db and then unserialize it when you want to use it in array format after pulling it out from db.

A: I would use a double replace to prevent using a loop.
First I would replace all & to '####-####' or any other code that is highly unlikely to appear (or use chr(0)).
Then use urldecode() to replace all %26 to & and all + to ' '
Last explode on '####-####' instead of the &

A: You can use urldecode to get the text representation of those encoded characters. I doubt that JS is doing this by itself though.