text:
Q: How can i prevent memory leaks in my C++ program? I'm working on a program that uses a double linked list implementation of a sorted queue. This file is the only file that a memory leak occurs.
Also, I am not allowed to edit the header.
I understand that to prevent memory leaks you must delete all objects created using new .
My problem is that if i place a delete at the end of my Enqueue(Message msg) function like so:
void PriorityQ::Enqueue(Message msg)
{
Priorities P = msg.GetPriority();
Node* Location = frontPtr;
Node* PrevLocation = frontPtr;
Node* NewNode = new Node;
NewNode->data = msg;

  if (IsFull())
    throw FullPQ();
  else if (count == 0)
    {
        NewNode->previousPtr = NULL;
        NewNode->nextPtr = NULL;
        count++;
        frontPtr = NewNode;
        rearPtr = NewNode;
    }
    else
    {
        Priorities  LP = Location->data.GetPriority();
        while(LP >= P)
        {
            if(Location == NULL)
                break;

            PrevLocation = Location;
            Location = Location->nextPtr;

            if(Location != NULL)
                LP = Location->data.GetPriority();

        }//end line 50 while

             if(Location == NULL)
                {
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;
                    PrevLocation->nextPtr = NewNode;
                    rearPtr = NewNode;
                    count++;

                }
            else
                {
                    PrevLocation = Location->previousPtr;
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;

                    if(PrevLocation == NULL)
                    {
                        Location->previousPtr = NewNode;
                        count++;
                        frontPtr = NewNode;
                    }
                    else
                    {
                        PrevLocation->nextPtr = NewNode;
                        Location->previousPtr = NewNode;
                        count++;
                    }
                }// end line 73 else

    } //end Line 48 else
delete NewNode;
}//end  Enqueue() Function

I get a segmentation error the next time the Enqueue(Message msg) function is called, and if i place the delete in my destructor:
PriorityQ::~PriorityQ()
{
 MakeEmpty();

 delete NewNode;

}

it gives me this error priorityq.cpp  [Error] 'NewNode' was not declared in this scope
So my question is how can I prevent memory leaks in my code without deallocating my objects in queue immediately after creating them.
Here is the full  file.
#include "priorityq.h"

PriorityQ::PriorityQ()
{
    frontPtr = NULL;
    rearPtr = NULL;
    count = 0;

}

PriorityQ::~PriorityQ()
{
    MakeEmpty();

  delete NewNode;

}

void PriorityQ::MakeEmpty()
{
    frontPtr = NULL;
    rearPtr = NULL;
    count = 0;
}

void PriorityQ::Enqueue(Message msg)
{
    Priorities P = msg.GetPriority();
    Node* Location = frontPtr;
    Node* PrevLocation = frontPtr;
    Node* NewNode = new Node;
    NewNode->data = msg;

      if (IsFull())
        throw FullPQ();
  else if (count == 0)
    {
        NewNode->previousPtr = NULL;
        NewNode->nextPtr = NULL;
        count++;
        frontPtr = NewNode;
        rearPtr = NewNode;
    }
    else
    {
        Priorities  LP = Location->data.GetPriority();
        while(LP >= P)
        {
            if(Location == NULL)
                break;

            PrevLocation = Location;
            Location = Location->nextPtr;

            if(Location != NULL)
                LP = Location->data.GetPriority();

        }//end line 50 while

             if(Location == NULL)
                {
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;
                    PrevLocation->nextPtr = NewNode;
                    rearPtr = NewNode;
                    count++;

                }
            else
                {
                    PrevLocation = Location->previousPtr;
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;

                    if(PrevLocation == NULL)
                    {
                        Location->previousPtr = NewNode;
                        count++;
                        frontPtr = NewNode;
                    }
                    else
                    {
                        PrevLocation->nextPtr = NewNode;
                        Location->previousPtr = NewNode;
                        count++;
                    }
                }// end line 73 else

    } //end Line 48 else
delete NewNode;
}//end line 27 Enqueue() Function

void PriorityQ::Dequeue()
{
    if(IsEmpty())
    {
        EmptyPQ Empty;
        throw Empty;
    }

Node* Location = frontPtr;
frontPtr = frontPtr->nextPtr;
Location->nextPtr = NULL;

if(frontPtr != NULL)
{
    frontPtr->previousPtr = NULL;
}
else
{
    MakeEmpty();
}
if(count != 0)
    count--;

}

void PriorityQ::Purge(Priorities p)
{
if(IsEmpty())
{
    EmptyPQ Empty;
    throw Empty;
}

Node* PurgePtr = frontPtr;
Priorities c = PurgePtr->data.GetPriority();
for(int j = 1; j < count; j++)
{
    if(c == p)
    {
        if(PurgePtr->previousPtr == NULL)
            Dequeue();
        else if( PurgePtr->nextPtr == NULL)
            PurgePtr->previousPtr->nextPtr = NULL;
        else
        {
            PurgePtr->previousPtr->nextPtr = PurgePtr->nextPtr;
            PurgePtr->nextPtr->previousPtr = PurgePtr->previousPtr;
        }
    }// end line 130 if
    else
    {
        PurgePtr = PurgePtr->nextPtr;
        c = PurgePtr->data.GetPriority();

    }
}// end line 127 for

}

Message PriorityQ::Front() const
{
    if(IsEmpty())
        throw EmptyPQ();
    return frontPtr->data;
}

Message PriorityQ::Rear() const
{
    if(IsEmpty())
        throw EmptyPQ();
    return rearPtr->data;
}

Message PriorityQ::Peek(int n) const
{
    if(n <= (count - 1) )
    {
        Node* PeekPtr = frontPtr;

        for(int j = 0; j < n; j++)
        {
            PeekPtr = PeekPtr->nextPtr;
        }

        return PeekPtr->data;

    }
    else
        throw InvalidPeekPQ();

}

bool PriorityQ::IsFull() const
{
    if(count < 501)
        return false;
    else
        return true;
}

bool PriorityQ::IsEmpty() const
{
    if(count == 0 && frontPtr == NULL)
        return true;
    else
        return false;
}

int PriorityQ::Size() const
{

    return count;
}

A: The problem is NewNode is a pointer local of the method void Priority::Enqueue. So it can't be accessed from other method.
When the method finish NewNode is eliminate and you can't access it.


text:
Q: How to generate group in jsplumb angular and add nodes to it dynamically after the group is created in angular 7 I would like to create a jsplumb group and then add nodes to it dynamically. But I can find in the document that one node needs to created and then after that only it can be added to the group. But in my case I have to add the group first and then I will drag drop the node. Both should have same jsplumb instance so that I can save the node values as well as group values.
I got this code from the main documentation.
HTML
  <!doctype html>

    <title>jsPlumb - groups demonstration</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">

    <link rel="stylesheet" href="../../css/jsplumbtoolkit-defaults.css">
    <link rel="stylesheet" href="../../css/main.css">
    <link rel="stylesheet" href="../../css/jsplumbtoolkit-demo.css">
    <link rel="stylesheet" href="demo.css">

Elements constrained to group (constrain:true)

Elements are draggable to other groups

Deletes group and children

Not droppable (droppable:false)

1.1

1.2

Elements are reverted on drop outside (revert:true)

Elements not draggable to other groups (dropOverride:true)

Deletes group only

2.1

2.2

Elements may be dragged outside bounds (revert:false)

Elements are draggable to other groups

Deletes group only

3.1

3.2

Elements pruned on drop outside (prune:true)

Elements are draggable to other groups

Deletes group and children

4.1

4.2

Elements orphaned on drop outside (orphan:true)

Elements are draggable to other groups

Deletes group only

Not droppable (droppable:false)

5.1

5.2

No connections shown when group collapsed (proxied:false)

Elements are draggable to other groups

Deletes group and children

6.1

6.2

Elements are draggable to other groups, using ghost proxy (ghost:true)

Deletes group and children

7.1

7.2

Elements are draggable to other groups, using ghost proxy (ghost:true)

Deletes group and children

Janani node 1

Janani node 2

?

Events

GROUPS

Demonstrates all of the ways you can use Groups.

js
jsPlumb.ready(function () {
var j = window.j = jsPlumb.getInstance({Container:canvas, Connector:"StateMachine", Endpoint:["Dot", {radius:3}], Anchor:"Center"});

j.bind("connection", function(p) {
    p.connection.bind("click", function() {
        j.detach(this);
    });
});

var evts = document.querySelector("#events");
var _appendEvent = function(name, detail) {
    evts.innerHTML = "
" + name + "
 " + detail + "
" + evts.innerHTML;
};
j.bind("group:addMember", function(p) {
    _appendEvent("group:addMember", p.group.id + " - " + p.el.id);
});
j.bind("group:removeMember", function(p) {
    _appendEvent("group:removeMember", p.group.id + " - " + p.el.id);
});
j.bind("group:expand", function(p) {
    _appendEvent("group:expand", p.group.id);
});
j.bind("group:collapse", function(p) {
    _appendEvent("group:collapse", p.group.id);
});
j.bind("group:add", function(p) {
    _appendEvent("group:add", p.group.id);
});
j.bind("group:remove", function(p) {
    _appendEvent("group:remove", p.group.id);
});

// connect some before configuring group
j.connect({source:c1_1, target:c2_1});
j.connect({source:c2_1, target:c3_1});
j.connect({source:c2_2, target:c6_2});
j.connect({source:c3_1, target:c4_1});
j.connect({source:c4_1, target:c5_1});
j.connect({source:c1_1,target:c1_2});
j.connect({source:c2_1,target:c2_2});

// NOTE ordering here. we make one draggable before adding it to the group, and we add the other to the group
//before making it draggable. they should both be constrained to the group extents.
j.draggable(c1_1);
j.addGroup({
    el:container1,
    id:"one",
    constrain:true,
    anchor:"Continuous",
    endpoint:"Blank",
    droppable:false
});
j.addToGroup("one", c1_1);
j.addToGroup("one", c1_2);
j.draggable(c1_2);

j.draggable(c2_1);
j.addGroup({
    el:container2,
    id:"two",
    dropOverride:true,
    endpoint:["Dot", { radius:3 }]
});  //(the default is to revert)
j.addToGroup("two", c2_1);
j.addToGroup("two", c2_2);
j.draggable(c2_2);

j.draggable(c3_1);
j.addGroup({
    el:container3,
    id:"three",
    revert:false,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("three", c3_1);
j.addToGroup("three", c3_2);
j.draggable(c3_2);

j.draggable(c4_1);
j.addGroup({
    el:container4,
    id:"four",
    prune:true,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("four", c4_1);
j.addToGroup("four", c4_2);
j.draggable(c4_2);

j.draggable(c5_1);
j.addGroup({
    el:container5,
    id:"five",
    orphan:true,
    droppable:false,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("five", [c5_1, c5_2]);
j.draggable(c5_2);

j.draggable(c6_1);
j.addGroup({
    el:container6,
    id:"six",
    proxied:false,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("six", [c6_1, c6_2]);
j.draggable(c6_2);

j.draggable(c7_1);
j.addGroup({
    el:container7,
    id:"seven",
    ghost:true,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("seven", [c7_1, c7_2]);
j.draggable(c7_2);

// the independent element that demonstrates the fact that it can be dropped onto a group
j.draggable("standalone");
//janani test start
j.draggable(jananinode1);
  j.addGroup({
    el:jananicontainer,
    id:"janani",
    ghost:true,
    endpoint:["Dot", { radius:3 }]
});
j.addToGroup("janani", [jananinode1,jananinode2]);
j.draggable(jananinode2);
j.connect({source:"jananinode1",target:"jananinode2"});

//janani test end
//... and connect others afterwards.
j.connect({source:c3_1,target:c3_2});
j.connect({source:c4_1,target:c4_2});
j.connect({source:c5_1,target:c5_2});
j.connect({source:c5_1,target:c3_2});
j.connect({source:c5_1,target:container5, anchors:["Center", "Continuous"]});
j.connect({source:c5_2,target:c6_1});
j.connect({source:c6_2,target:c7_1});

// delete group button
j.on(canvas, "click", ".del", function() {
    var g = this.parentNode.getAttribute("group");
    j.removeGroup(g, this.getAttribute("delete-all") != null);
});

// collapse/expand group button
j.on(canvas, "click", ".node-collapse", function() {
    var g = this.parentNode.getAttribute("group"), collapsed = j.hasClass(this.parentNode, "collapsed");

    j[collapsed ? "removeClass" : "addClass"](this.parentNode, "collapsed");
    j[collapsed ? "expandGroup" : "collapseGroup"](g);
});

jsPlumb.fire("jsPlumbDemoLoaded", j);

});
css
.w {
    position:absolute;
    width:30px;
    height:30px;
    border:1px solid black;
    font-size:12px;
    border-radius:3px;
    text-align:center;
    background-color:WhiteSmoke;
    opacity:0.7;
    z-index:10;
    color:black;
    cursor:move;
}

.w:hover {
    background-color:#629f8d;
}

.group-container {
    position: absolute;
    width: 200px;
    height: 200px;
    border-radius: 12px;
    background-color: WhiteSmoke;
    font-size: 12px;
    cursor:move;
}

.group-container ul {
    margin-left:25px;
    padding: 0;
}

.group-container ul li {
    list-style-type:circle;
    margin-bottom: 7px;
}

.large {
    width:600px;
    height:600px;
}

.group-container.collapsed {
    height:40px;
}

.title {
    background-color:#ABC1BB;
    padding-right:16px;
    font-size:13px;
    height:30px;
}

#container1 { left:20px;top:50px; }
#container2 { left:250px;top:50px; }
#container3 { left:480px;top:50px; }
#container4 { left:710px;top:50px; }
#container5 { left:600px;top:340px; }
#container6 { left:370px;top:340px; }
#container7 { left:140px;top:340px; }

.del, .node-collapse {
    position:absolute;
    top:5px;
    right:5px;
    background-color:white;
    padding:1px;
    cursor:pointer;
    font-size:13px;
    width:20px;
    height:20px;
    border-radius: 50%;
    text-align:center;
    display:block;
}

.del:after {
    content:"X";
}

.node-collapse {
    right:29px;
    text-align: center;
}

.node-collapse:after {
    content:"-";
}

.group-container.collapsed .node-collapse:after {
    content:"+";
}

.del[delete-all] {
    background-color: pink;
}

.jtk-connector path {
    stroke-width:1;
}

.jtk-group-collapsed .w, .jtk-group-collapsed ul, .jtk-group-collapsed .container, .jtk-group-collapsed .name {
    display:none;
}

.jtk-drag-hover {
    outline:4px solid cornflowerblue;
}

.katavorio-ghost-proxy {
    outline:2px solid red;
}

.events {
    position:absolute;
    right:0;
    top:0;
    border-left:4px solid #58775d;
    bottom:0;
    width:156px;
    font-size: 11px;
    padding-left:11px;
    background-color: white;
}

#events {
    position: absolute;
    right: 0;
    top: 0;
    border-left: 1px solid #58775d;
    bottom: 0;
    width: 256px;
    font-size: 11px;
    padding-left: 11px;
    background-color: white;
}

.events h3 {
    font-size: 20px;
    margin-top: 10px;
}

The drag drop nodes will get populated in the sides and it will be cloned that logic is done.

A: I followed the JSplumb documentation on master.. and added the similar code by creating a separate component and css file. Automatically When I dropped the created nodes inside the group it got added to the group. Delete is also working fine but for minimize we need to make the changes based on the class collapsed which gets added to the group div.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compiling Oniguruma regex library to javascript using Emscripten I'm trying to get a more powerful regex library into javascript. The only solution I found is to compile Oniguruma regex library to javascript using Emscripten
I've installed Emscripten and tested it with their small test scripts, also downloaded oniguruma source code, but still don't know what should be done next.
Anyone familiar with emscripten?

A: When you utilize Emscripten, the general way of building/compiling from C/C++ stays similar. The steps which change, are that you don't use e.g. the gcc compiler but Emscripten compiler.
That said there is the general question of whether you are familiar with C/C++ and more specific with autotools (which seems like the build tool Oniguruma uses). If you are not, you will probably have a very hard time understanding what needs to be done and how.
Last I checked Emscripten did not have support for Libtool, so building, utilizing autotools, will probably fail. Feel free to ask at Emscripten IRC channel though, whether this is indeed not possible.
Another way I can think of is using autotools to generate Makefiles and then writing custom targets for Emscripten programs. Beware that this is for advanced users, familiar with the make cruft.
If these steps are to taxing for you perhaps you should see whether a Javascript library can be sufficient for you.

A: A more realistic approach to do this is going to be to use http://xregexp.com. It adds many more features to RegExps and compiles them down to JavaScripts more limited RegExp dialect so it can get the best of both features and performance. Compiling a regexp library using emscripten is very unlikely to be performant enough to use in production. For some uses, emscripten is excellent, but in this case it seems like the overhead is going to be not worth the cost.
The author of XRegExp even has an article on lookbehinds http://blog.stevenlevithan.com/archives/javascript-regex-lookbehind


text:
Q: Uncaught TypeError after data is changed in react I have a bit of a weird error with react and my google charts, when i first login to my page that shows my chart everything shows fine, but theres a place where i import data for new values to show on my chart and the chart disappears when i import new values and i get the following errors:
Uncaught TypeError: processedData[(index + 1)] is undefined
Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development

I have added null checks and everything but the error still persists.
Here is my code where the error is happening:
    import React from 'react';
import { Chart } from "react-google-charts";

export const DoubleColumnChart = (props) => {

  const processData = (data) => {
    if (data == null) return [[]];
    if (data.labels == null) return [[]];
    var processedData = [[]];
    if(processData == null) return [[]];
    processedData[0].push('Category');
    data.labels.forEach(function (label) {
      var finalLabel = null;
      finalLabel = label[0];
      if (label.length > 1) {
        for (var i = 1; i  parseInt(160 / data.labels.length, 10)) {
            finalLabel = finalLabel + '...';
            break;
          }
          finalLabel = finalLabel + '\n' + label[i];
        }
      }
      processedData.push([finalLabel]);
    });

    data.datasets.forEach(function (dataset) {
      processedData[0].push(dataset.label);
      dataset.data.forEach(function (data, index) {
        if(processData == null) return [[]];
        processedData[index + 1].push(data);
      });
    });

    return processedData;
  }

  const processColors = (data) => {
    if (data == null) return [];
    if (data.datasets == null) return [[]];
    var processedColors = [];
    data.datasets.forEach(function (dataset) {
      processedColors.push(dataset.backgroundColor);
    });
    return processedColors
  }

  if (props.isVisible == false) {
    return

;
  }

  return (
    <Chart
      width={'99%'}
      height={'375px'}
      chartType="ColumnChart"
      loader={
Loading Chart
}
      data={processData(props.data)}
      options={{
        animation: {
          duration: 1500,
          easing: 'out',
          startup: true,
        },
        legend: { position: 'bottom', textStyle: { color: 'gray' } },
        vAxis: { textStyle: { color: 'gray' } },
        hAxis: { textStyle: { fontSize: 10, color: 'gray' } },
        tooltip: { trigger: 'hover', showColorCode: true },
        chartArea: {
          top: '2%',
          left: '5%',
          height: "77%",
          width: "100%",
        },
        colors: processColors(props.data),
        dataOpacity: '0.9',
      }}
      chartEvents={[
        {
          eventName: 'select',
          callback: ({ chartWrapper }) => {
            const chart = chartWrapper.getChart()
            const selection = chart.getSelection()
            if (selection.length === 1) {
              const [selectedItem] = selection;
              const { row } = selectedItem;
              var labelData = props.data.labels[row];
              var finalLabel = '';
              for (var i = 0; i < labelData.length; i++) {
                finalLabel = finalLabel + labelData[i];
              }
              finalLabel = finalLabel.replace(/ /g, '');
              if (props.onSegmentClick) props.onSegmentClick(finalLabel);
            }
          },
        },
      ]}
      rootProps={{ 'data-testid': '1' }}
    />
  );
}

But if i hard refresh, the new data does show and the console error goes away


text:
Q: yii2 kartik-v/yii2-widget-fileinput installation I installed yii2 fileupload extension with:

*

*php version 7 and linux (putty)

*php version 7 and 5 and window (cmd)
but failed!
message that shown to me on composer is :
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
– Installing kartik-v/bootstrap-fileinput (v4.4.8): Loading from cache
– Installing kartik-v/yii2-widget-fileinput (dev-master c549564): Cloning c549564
Failed to download kartik-v/yii2-widget-fileinput from source: Failed to clone https://github.com/kartik-v/yii2-widget-fileinput.git, git was not found, check that it is installed and in your PATH env.
sh: git: command not found
Now trying to download from dist
– Installing kartik-v/yii2-widget-fileinput (dev-master c549564): Loading from cache
Package mongosoft/yii2-upload-behavior is abandoned, you should avoid using it.
 Use mohorev/yii2-upload-behavior instead.
Writing lock file
Generating autoload files.
and when i used this command :
echo '<label class="control-label">Add Attachments</label>';

echo FileInput::widget([
    'model' => $model,
    'attribute' => 'attachment_1',
    'options' => ['multiple' => true]
]);

this error happend :
Class 'kartik\widgets\FileInput' not found
and message that shown to me on cmd was too long!!
Have resources been changed?
What can I do?
Is there a way to do it manually?
you can see this extension at :
yii2 fileupload extension

A: Well, the first error shows that you must install git (for example in ubuntu you can do it with $ sudo apt install git).
The second error is because of a blur on the namespace of FileInput documentation. Based on This line of code, you should use kartik\file\FileInput as the used namespace.


text:
Q: ehCache and Spring MVC Error with HIbernate I keep getting this error while setting up ehcache in Spring MVC.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.googlecode.ehcache.annotations.config.internalEhCacheEvictionTask': Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: net.sf.ehcache.CacheManager.getName()Ljava/lang/String;

Below is my setup, and I am using hibernate 3.2.7.GA

<ehcache:config cache-manager="ehCacheManager">
    <ehcache:evict-expired-elements interval="60" />
</ehcache:config>

<beans:bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <beans:property name="configLocation"  value="/WEB-INF/spring/ehcache.xml"/>
</beans:bean>

Pom.xml
<dependency>
          <groupId>com.googlecode.ehcache-spring-annotations</groupId>
          <artifactId>ehcache-spring-annotations</artifactId>
          <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache</artifactId>
           <version>2.3.2</version>
           <type>pom</type>
       </dependency>
    </dependencies>
    <repositories>
          <repository>
            <id>terracotta-releases</id>
            <url>http://www.terracotta.org/download/reflector/releases</url>
            <releases><enabled>true</enabled></releases>
            <snapshots><enabled>false</enabled></snapshots>
        </repository>

A: The zip file of ehcache-spring-annotations containing the dependencies, downloaded on the project web site, contains ehcache-core version 2.2.0. You're using 2.3.2. There might be an incompatibility between those versions.

A: Got it working by using an exclude, so yes there was a clash issue.
   <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-commons-annotations</artifactId>
                <version>${org.hibernate.commons.annotations-version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>net.sf.ehcache</groupId>
                        <artifactId>ehcache</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>


text:
Q: Bii not finding dependencies in project when not initialized with "-L" I'm taking my first steps with bii. I can complete the get started tutorial with no problems. However, when I manually create a new project on github, pull it, add a main file with gtest and gmock includes, run the commend bii init within the project folder, then type bii find, I just get the following . .

INFO: Processing changes...
INFO: No deps to find on server

I worked out that if I initialize the repository with bii init -L then everything works. However, bii init --help says . .

usage: bii init [-h] [-L [LAYOUT]] [name]
creates a new biicode project
positional arguments:   name                  Optional name of the
  folder. If specified, bii will
                          create a new folder and initialize a project inside,
                          otherwise, it will try to initialize in the current
                          folder
optional arguments:   -h, --help            show this help message and
  exit   -L [LAYOUT], -l [LAYOUT], --layout [LAYOUT]
                          Optional layout. If no param is specified, it will use
                          the "minimal" one. Other available: CLion

Which suggests the L parameter is ignored if I do not specify a layout.
My question is what does the L parameter do with no layout specified, compared to just typing bii init with no extra params?
NOTES:

*

*OSX 10.10.2

*bii 2.7

A: bii init command without parameters enables working with multiple blocks at the same time within the same project.
It inits by default a classic layout. Its behaviour is explained in biicode's docs here.
To use it:
bii init to init your project and then bii new username/blockname to create the folder structure needed to use multiple blocks at the same time.
Then your code should be placed under project/blocks/username/blockname directory.
Using bii init enables working with multiple blocks like this:
cd your_project_name
bii open examples/tinythread
bii open examples/box2d
bii build
cd bin
./run_any_exectuable_here

You can also check the docs section about layouts.

A: Basically
$ bii init -L

is the same as
$ bii init -L=simple

Where simple is the minimal layout, that allows to edit a block directly in the project root.
Surely the command help can be improved. The resulting layout will be:
project
 |-bii
 |  |-deps
 |  |-cmake
 |  |-build
 |-bin
 |  |-myexe
 |-main.cpp

If not using the -L option, you are creating a regular biicode project layout, which is much different, that require user blocks to be inside the "blocks" folder and all the aux folders (deps, build, cmake) will be in the project root. The typical workflow there would be
$ bii init myproject
$ cd myproject
$ git clone repo-url blocks/mybiicodeuser/myblockname

It is typical that the blockname is equal to the github repository name, and many people have a username equal for github and biicode.


text:
Q: Change onClick function for component react js? I have component with button and 2 functions.Button component used in various components. And for some need one function for onclick event, for other - second. How can I change functions for onclick event? I'm using this answer, but always getting undefined in my components.
export default class MyButtonComponent extends Component {

constructor(props) {
    super(props);
    propTypes: {
        onClick: PropTypes.func
    };
    this.state = { loading: false, api_url: "http://localhost:8000" };
}

 static get DefaultProps() {
  return {
    onClick: this.firstFunction(event)
  }
}

firstFunction(){
/*some code*/
}

secondFunction(){
/*some code*/
}

render() {
    return (
        <LaddaButton
            loading={this.state.loading}
            onClick={this.props.onClick}
            className='submit'
            data-color="#eee"
            data-style={SLIDE_UP}
            data-spinner-size={30}
            data-spinner-color="#ddd"
            data-spinner-lines={12}
            data-url={this.props.url}
        >
            Отправить
        </LaddaButton>

    );
}

And in another component:
<FormGroup>
     <Col mdOffset={5} md={7}>
         <MyButtonComponent onClick={this.secondFunction} data-url="someurl.com"></MyButtonComponent>
     </Col>
</FormGroup>

Also tried add
onClick={e => this.secondFunction(e)}

to button componentm but always getting error
_this2.secondFunction is not a function

A: The problem looks to be with how you're using this - when you call this.secondFunction in the <FormGroup> element of your other component, it's looking for secondFunction in that component. You've defined secondFunction in MyButtonComponent, so it's coming back as undefined.
You could get around this by defining a single click handler in MyButtonComponent that chooses which function to call based on a prop that you can update externally. E.g.
function myClickHandler(e) {
    if(useFirst) {
        this.firstFunction(e);
    } else {
        this.secondFunction(e);
    }
}

Then you could change that property in the render method of your other component, e.g.
<FormGroup>
    <Col mdOffset={5} md={7}>
        <MyButtonComponent useFirst=false data-url="someurl.com"></MyButtonComponent>
    </Col>
</FormGroup>

A: Since you are passing secondFunction() as a prop to the MyButtonComponent component and hence it must not be defined in the MyButtonComponent component but in the component in which you have the below code
<FormGroup>
     <Col mdOffset={5} md={7}>
         <MyButtonComponent onClick={this.secondFunction} data-url="someurl.com"></MyButtonComponent>
     </Col>
</FormGroup>

In the MyButtonComponent you can reference it as this.props.onClick() but it must be defined in the calling component
Also you need to bind the function while passing it as a prop to the MyButtonComponent like
<FormGroup>
     <Col mdOffset={5} md={7}>
         <MyButtonComponent onClick={this.secondFunction.bind(this)} data-url="someurl.com"></MyButtonComponent>
     </Col>
</FormGroup>

Check the answer here to understand the flow better


text:
Q: Force BigInt to be INTEGER in a view I have an Alarm table that has column for device, severity and an obsolete flag among others and view that is generating one of it's columns in a CASE statement.  The idea is that many alarms for the same device will be grouped together and their overallSeverity will either be the maximum severity of not obsolete alarms or will be the lowest possible severity (1) if they are all flagged obsolete.
Here is what I'm trying:
(CASE
    WHEN (SUM(`al`.`OBSOLETE`) = COUNT(`al`.`ALARM_ID`)) THEN 1
    ELSE (SELECT
            MAX(`al`.`SEVERITY`)
        FROM
            `alarm` `al`
        WHERE
            (`al`.`OBSOLETE` <> 1))
END) AS `overallSeverity`,

Which works fine as sql and gives the desired result in MySQL Workbench
The issue is that I'm using hibernate to select from this view and show these groups on a webpage and the Java code is expecting overallSeverity to be an int and SQL seems to default it to be a BigInt.
The following worked but doesnt always return the desired value for overallSeverity if none of them were actually the lowest possible value:
WHEN SUM(al.OBSOLETE) = COUNT(al.ALARM_ID) THEN min(al.severity)

In this case if the lowest severity in the group was 2 then that's of course what is returned as overallSeverity but if all are obsolete we want to always display 1.
Is there a way to force the view to return an INTEGER for that column?  The severity column in Alarm is type int(1) so I'm essentially trying to keep that.


text:
Q: javax.servlet.HttpServletRequest.getContentLength() returns int only In order to deal with a large request body in a HTTP POST or PUT, relying on HttpServletRequest.getContentLength() is not a good idea, since it returns only integer values, or -1 for request bodies > 2GB.
However, I see no reason, why larger request bodies should not be allowed. RFC 2616 says

Any Content-Length greater than or equal to zero is a valid value.

Is it valid to use HttpServletRequest.getHeader('content-length') and parse it to Long instead?

A: Since Servlet 3.1 (Java EE 7), a new method is available, getContentLengthLong():
long contentLength = request.getContentLengthLong();

The same applies to its counterpart on the response, setContentLengthLong():
response.setContentLengthLong(file.length());

A: Yes, this is a fine approach - use getHeader("Content-Length") (capitalized) and Long.parseLong(..). I believe it's what the container is doing, but it is limited to int by the serlvet spec.


text:
Q: CSS margin and padding not being applied So I've got essentially a list of items, that are separated by a border. I'd like to have equal padding and margin applied to the top and bottom of each item.
Here's a fiddle that contains a simplified version of what I'm working with.
Now, you see, I have 10px of margin and padding applied to the top and bottom of each item, but the items aren't evenly spaced. There's more space above each item than below it.
I realize that this is probably a result of CSS's collapsing margins behaviour, and that I could fix it by adding more padding than margin to get the spacing I want.
The issue is, however, that to some items, I want to highlight by adding a background colour, like this fiddle. And when I do, the padding on the top and the bottom must be the same.
So how can I fix this issue? I want it to be super flexible, so I can customize the amount of padding and margin if I like, and also be able to remove the border but still have it display properly.
HTML:

CSS:
.item {
  display: block;
  width: 150px;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-bottom: 10px;
  padding-top: 10px;
  border-bottom: 1px solid red;
}

.fill {
  background-color: #aaa;
  display: block;
  height: 150px;
}

.bg {
  background-color: #ccc;
}

A: Here is a fork of your fiddle

To achieve correct symetrical, vertical spacing, I actually created a 1px div to replace your border:

with myborder class like so:
.myborder {
    heigth: 1px;
    background: red;
    font-size: 1px;
    margin-top: 10px;
    width: 150px;
}

The border div is placed in between item divs, like so:

In item class, I removed the border and margin-bottom attributes:
.item {
    display: block;
    width: 150px;
    margin-top: 10px;
    /*margin-bottom: 10px;*/
    padding-bottom: 20px;
    padding-top: 20px;
    /*border-bottom: 1px solid red;*/
    background-color:yellow;
}

You will get symetrical, vertical spacing between items as long as myborder's margin-top and item's margin-top attributes are equal.

UPDATE: in the provided, forked fiddle, I also created an invisible border class, as you mentioned being able to remove the border and keep proper spacing:
.myinvisibleborder {
    height: 1px;
    background: transparent;
    font-size: 1px;
    margin-top: 10px;
    width: 150px;
}

By setting background to transparent, it becomes invisible; another way would be to set height and font-size to 0px;

A:
The reson for problem lies in margin itself. If you are providing a
  margin then it will take a blank space from provious element. Now if
  you are applying padding means indirectly u are increasing div size.
  Here in your problem u can solve this by making top and bottom margin
  0 and instead doubling padding in ".item" class as follows:

.item {
    display: block;
    width: 150px;
    **margin-top: 0px;
    margin-bottom: 0px;
    padding-bottom: 20px;
    padding-top: 20px;**
    border-bottom: 1px solid red;
}

this will look perfect without touching to other code segments!

A: The problem is the way you are seeing things. The padding and margins are all equal, but you can't see them that way as you only have a bottom border. If you add a top border (red like the bottom one), you can see that the spacing is exactly the same between the items.
Now if you want to fix your problem, you have to take into account that you only have one border, so you can remove one of the paddings or margins.
Edit: Replace your css code with the following and you should achieve what you want:
.item {
display: block;
width: 150px;
margin-bottom: 10px;
padding-bottom: 10px;
border-bottom: 1px solid red;
}

Edit 2: I just realised that because of your highlighting in your second example, you'll run into another problem. So you'll probably have to take out the red line from the divs and put them into a separate entity.
Edit 3: Here's a jsfiddle with updated, hope it does what you want.


text:
Q: Does USB 2.0 high speed host require a chassis ground? I'm trying to design a microcontroller-based board in which the MCU will function as a USB 2.0 High Speed (480 Mbit/s) host for connected USB HS devices.  I have been researching circuit design for USB HS, including issues like matching trace lengths, spec-compliant differential impedance, ESD protection, etc.  One issue that comes up in some references (such as this answer:  Ground and earth layers on PCB) is the need for separate digital and chassis grounds.
I am just designing a bare prototype PCB with no enclosure to ground to.  After a few revisions of the PCB, I may want to 3D print a plastic enclosure to make it look nice, but even then there would be no true earth ground available to me.  Does this lack of a chassis/earth ground mean that USB 2.0 HS speeds are not attainable in this circuit?  How bad might the performance degradation be if I get everything else right?
For clarity:

*

*My board is powered by a 9V (unregulated) wall wart connected through a DC barrel jack on the PCB, with, possibly, a 9V battery backup in case the cord comes unplugged. From this I plan to create regulated 5V and 3.3V rails. The wall wort is two pronged, so there is no earth ground available even from it.  I am just a hobbyist and do not want to touch mains voltages, so building an entire PSU (i.e., A/C transformer + rectifier) is something I'd prefer not to do.

*The closest I could come to a chassis ground that I can think of is to call the USB shield the chassis ground and treat it as such, i.e., connect it through a 1nF/3kV capacitor to the signal ground plane in the PCB.  But is this a good enough "chassis" to be worth doing or do I need an entire separate chassis ground layer in the PCB stack to accomplish anything?

A: Chassis and signal return serve different purposes. Using one as the other requires some considerations and definitely layout provisions.
But do you even need a chassis node? It's mainly an ESD fast-track and EMI shield in your application. Both of these functions are nice to have, but can be lived without as commenters have noted. As you lack mains voltage, you don't need the protective Earth function for Class I equipment.

*

*Prevent EMI with good layout. Your biggest concern will be the long cables anyway, and it doesn't matter for EMI if there is Earth Ground or any other potential and the other end of thise cables. You must make sure, not to develop large common-mode currents over those cables. Certainly possible without a chassis, e.g. with common-mode chokes.

*ESD can be nasty, so you have to design stuff in a way that the ESD strikes rugged structures, e.g. your GND plane, instead of susceptible parts like MCU.
Also note that none of the classical tasks of a chassis are achieved by an on-board chassis plane in the stackup. That is just a wasted layer.
As you are designing the host, this still leaves the question about how to connect the shield. This should be connected to the host chassis, so you have to assign something as your chassis node. In your case, I would derive the Chassis just plainly from your ground plane with a short (or 0 Ω resistor).

A: The below is take from TI application note(USB 2.0 Board Design and Layout Guidelines).
This is also a very good reference.(How to correctly connect a USB shield on a PCB)

Place a ferrite in series with the cable shield pins near the USB connector socket to keep EMI from getting
onto the cable shield. The ferrite bead between the cable shield and ground may be valued between 10 Ω
and 50 Ω at 100 MHz; it should be resistive to approximately 1 GHz. To keep EMI from getting onto the
cable bus power wire (a very large antenna) a ferrite may be placed in series with cable bus power,
VBUS, near the USB connector pin 1. The ferrite bead between connector pin 1 and bus power may be
valued between 47 Ω and approximately 1000 Ω at 100 MHz. It should continue being resistive out to
approximately 1 GHz, as shown in Figure above.


text:
Q: Huge Server: Backing Up Many TB of Data with Instant Failover? We have a very challenging system to back up:
1. We have 20 TB of data right now.
2. Each month we get another 3 TB of data, and about 5 TB of data changes each month.
3. We are currently a Windows-based shop and use DELL MD1000 systems.
We want to:
- Fail over in real time to the most recent backup copy of the data.
- Be able to restore previous versions of the data for the past 60 days.
NOTES:
- Because of all the writing and re-writing to disk, file corruption is fairly common, so snapshots that don't duplicate data and not very useful.
- Keep in mind that decompressing 2 TB of data in order to restore would result in days of downtime. Even just copying the data could take forever.
** What possible solutions do we have? **

A: For dull technical reasons I don't normally recommend NetApp boxes but I think for this situation they'd be ideal. You could basically just snapshot the volumes every N minutes, it's what they do best - you can then just mirror the whole drive to another location or whatever for DR and run a tape/disk backup from either side.
That's not huge by the way, not small though :)


text:
Q: How to display (echo) a large json file in bash? I have a json file and I know the location of it. let us say C:\desktop\file. I am adding a bash script in an existing application that would read this bash script take the output and use the json that it extracts for something else. How would I go about doing that.
output should be something like
echo Start
echo C:\desktop\file
echo End

The file is also large


text:
Q: How to group sorted lat/long with distance condition I have data like this  (it's already has been sorted).
lat_long
9.999,98.655
9.998,98.647
9.998,98.646
9.998,98.614
9.997,98.655
9.997,98.648
9.997,98.647
9.997,98.646
9.996,98.725

I want to group place with condition that the first place(first row) have to be within 500 meters (or 55/1100 in lat/long scale) compared with the next row.For the first row that is further than 500 meters it will be in the second and third group and so on.
I can do this in oraclesql or python .
My expected out put will be like this (but in this example does not match my condition. just for understanding.)
lat_long             group      first_lat_long
9.999,98.655          1          9.999,98.655
9.998,98.647          1          9.999,98.655
9.998,98.646          1          9.999,98.655
9.998,98.614          2          9.998,98.614
9.997,98.655          2          9.998,98.614
9.997,98.648          2          9.998,98.614
9.997,98.647          3          9.997,98.647
9.997,98.646          3          9.997,98.647
9.996,98.725          4          9.996,98.725


text:
Q: Отсортировать pandas.DataFrame по частоте элементов в колонке Господа , подскажите метод pandas , который сортирует элементы в колонке , в зависимости от того как часто они встречаются

A: Насколько мне известно такого метода "из коробки" нет, но это несложно сделать самому:
Создаем DF из случайных данных, так чтобы значения в столбце grp были распределены неравномерно:
np.random.seed(123)

N= 10
df = pd.DataFrame({
  'grp':np.random.choice(['aaa','bbb','ccc'], N, p=[0.3, .6, .1]),
  'val':np.random.randint(100, size=N)
})

получилось:
In [119]: df
Out[119]:
   grp  val
0  bbb   46
1  aaa   96
2  aaa   25
3  bbb   83
4  bbb   78
5  bbb   36
6  ccc   96
7  bbb   80
8  bbb   68
9  bbb   49

In [120]: df['grp'].value_counts()
Out[120]:
bbb    7
aaa    2
ccc    1
Name: grp, dtype: int64

Решение:
idx = (df.groupby('grp')['val'].transform('count')).sort_values(ascending=False).index

df.reindex(idx)

Результат:
In [126]: df.reindex(idx)
Out[126]:
   grp  val
9  bbb   49
8  bbb   68
7  bbb   80
5  bbb   36
4  bbb   78
3  bbb   83
0  bbb   46
2  aaa   25
1  aaa   96
6  ccc   96


text:
Q: admob test ads appearing I released my Android app two days ago, using admob advertising. I used my personal phone as the test phone,  but took out the test mode code before releasing it. My admob status is active and I get requests and impressions on the report, but whenever I try to use the app on my personal phone i only get "test ads". I don't know why. I looked through the code of my app and can't find anything amiss. And i did delete the test version of the app and then download the released version from the market.

A: I'm not sure why the test ads are appearing in your app, but one way to shut them off is to go to your Admob App Settings, and choose the option "Disable test mode for all requests" as your Test Mode setting.

A: You customers would not have been seeing the debug ads.   You probably have a line like:
AdManager.setTestDevices( new String[] {
  AdManager.TEST_EMULATOR, // Android emulator
  "E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
}

Assuming E83D20734F72FB3108F104ABC0FFC738 is you're personal phone, any time that phone makes a request it will get a test ad.  All other phones will not be eligible for test ads, unless they are also individually added to that method.

A: Nick's answer works.  (But is missing the final parenthesis.)
But what if I want to give my (not yet released) Android app out to 10 friends?
Is there any java code that says "treat ALL phones as test devices"?

A: Here is code for treat all devices as test devices:
        String aid = Settings.Secure.getString(context.getContentResolver(), "android_id");
        try {
            Object obj;
            ((MessageDigest) (obj = MessageDigest.getInstance("MD5"))).update(aid.getBytes(), 0, aid.length());

            aid = String.format("%032X", new Object[] { new BigInteger(1, ((MessageDigest) obj).digest()) });
        } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
            aid = aid.substring(0, 32);
        }

        adRequest.addTestDevice(aid);


text:
Q: Using a custom PHP.INI for a single site. Windows 2003, 64bit, IIS7.5, PHP 5.3.6 I have a single PHP script on a single site that requires me to set the upload size maximum fairly high. I would prefer not to do this globally.
According to the PHP docs, I can not set the values for some variable such as post_max_size , max_file_uploads or upload_max_filesize using ini_set. I've seen a number of solutions here running PHP on a UNIX box or on Windows running Apache, but none that are clear to me using IIS.
My understanding is that there is a way for me to have a custom php.ini file to override specific php.ini value.
Ideally, I would love to have a php.ini file in the folder with that one script that looks something like this:
[PHP]
post_max_size = 200M
max_file_uploads = 5
upload_max_filesize = 200M

How can I accomplish this without setting the values globally on my server?
Thanks.

A: It's certainly possible to use different PHP settings for a specific website or to even use a different version of PHP per website. An article titled Using FastCGI to Host PHP Applications on IIS 7 by Ruslan Yakushev on IIS.net explains how to set it up. It also contains other useful tips on how to set it up securely.


text:
Q: How to show the menu of your game again in actionscript 3? What I am trying to do is to make a game in as3. What i did so far is that I made a game and from that .swf file loaded a menu in with the name "startScreen.swf". From that external swf file can i navigate to my storyscreen, instructionsscreen and play my game. the storyscreen and instructionsscreen are all external swf files.
What i want to do is when i press ESC, I want to unload my swf file and show my menu again. But the problem is when I press ESC my startscreen shows but when i press play game, It don't unload my startscreen again and just plays over it.
Is there a way to load all my swf files before the game starts and when I want to return to the startscreen, They just unload and load my startscreen again. Or another option is to just restart the game which is my favorite choice.
public var Player:MovieClip

private var leftKeyIsDown:Boolean;
private var RightKeyIsDown:Boolean;

private var aMissileArray:Array;
private var aEnemyArray:Array;

public var scoreTxt:TextField;
public var ammoTxt:TextField;
public var MenuEnd:EndGameScreen;
public var menuAgain:EndGameScreen;

private var MenuStart:mcStartGameScreen;
private var MenuStory:mcStartGameScreen;
private var MenuInstructions:mcStartGameScreen;

private var nScore:Number;
private var nAmmo:Number;
private var tEnemyTimer:Timer;

private var screens:Object = {
    "SHOW_INSTRUCTIONS":{
        "loader":new Loader(),
        "url":new URLRequest("instructionsScreen.swf")
    },
    "SHOW_STORY":{
        "loader":new Loader(),
        "url":new URLRequest("storyScreen.swf")
    },
    "START_GAME":{
        "loader":new Loader(),
        "url":new URLRequest("startScreen.swf")
    }
}
public function FirstGame()
{
    //Create a loader object
    var startLoader:Loader = new Loader();
    //add event listener to listen for the complete event
    startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
    //load our loader object
    startLoader.load(new URLRequest("startScreen.swf"));
}

public function startLoaded(e:Event):void
{
    MenuEnd.hideScreen();
    Player.visible = false;
    scoreTxt.visible = false;
    ammoTxt.visible = false;

    //get a reference to the loaded movieclip
    MenuStart = e.target.content as mcStartGameScreen;
    //listen for start game event
    MenuStart.addEventListener("START_GAME", playGameAgain);
    //add it to the stage
    addChild(MenuStart);

    //get a reference to the loaded movieclip
    MenuStory = e.target.content as mcStartGameScreen;
    //listen for start game event
    MenuStory.addEventListener("SHOW_STORY", storyGameScreen);
    //add it to the stage
    addChild(MenuStory);

    //get a reference to the loaded movieclip
    MenuInstructions = e.target.content as mcStartGameScreen;
    //listen for start game event
    MenuInstructions.addEventListener("SHOW_INSTRUCTIONS", instructionsGameScreen);
    //add it to the stage
    addChild(MenuInstructions);
}

private function instructionsGameScreen(e:Event):void
{
    var instructionsLoader:Loader = new Loader();
    var url:URLRequest = new URLRequest("instructionsScreen.swf");
    instructionsLoader.load(url);
    addChild(instructionsLoader);

    stage.addEventListener(KeyboardEvent.KEY_UP, esc);
}

private function storyGameScreen(e:Event):void
{
    var storyLoader:Loader = new Loader();
    var url:URLRequest = new URLRequest("storyScreen.swf");
    storyLoader.load(url);
    addChild(storyLoader);

    stage.addEventListener(KeyboardEvent.KEY_UP, esc);
}

private function esc(e:KeyboardEvent):void
{
    if (e.keyCode == 27)
    {
        //fscommand("quit");

        //(new URLRequest(stage.loaderInfo.url), "FirstGame.swf");

    }
}

private function playGameAgain(e:Event):void
{

    //initialize variables
    aMissileArray = new Array();
    aEnemyArray = new Array();
    nScore = 0;
    nAmmo = 20;
    Player.x = 262,95
    Player.y = 323,30

    Player.visible = true;
    scoreTxt.visible = true;
    ammoTxt.visible = true;

    MenuStart.hideScreen();

    MenuEnd.addEventListener("PLAY_AGAIN", playGameAgain);
    MenuEnd.hideScreen();

    updateScoreText();
    updateAmmoText();

    //trace("First Game Loaded");
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);

    stage.addEventListener(Event.ENTER_FRAME, gameLoop)

    //creat an timer object
    tEnemyTimer = new Timer(1000)
    //listen for the timer ticks/intervals
    tEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy)
    //start our timer
    tEnemyTimer.start();

}

You can see by the storyscreen when you press ESC. There is nothing. There I want to restart or load my startscreen and unload the other swf files.


text:
Q: Best practice for using caching the results of an iterator block Iterator blocks' lazy loading behavior is causing difficulties in caching data. Consider this small test program:
class Program
{
    static IEnumerable<int> LoadDataFromDatabase()
    {
        Console.WriteLine("Hitting database....");
        yield return 13;
    }

    static IEnumerable<int> _cachedData = null;
    static IEnumerable<int> CachedData
    {
        get
        {
            if (_cachedData == null)
            {
                _cachedData = LoadDataFromDatabase();
            }
            return _cachedData;
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("Collection contains {0} items.", CachedData.Count()));
        Console.WriteLine(string.Format("Collection contains {0} items.", CachedData.Count()));
    }
}

The output to this is

Hitting database....
Collection contains 1 items.
Hitting database....
Collection contains 1 items.

I want to only hit the database once (hence the caching), but because LoadDataFromDatabase() is an iterator block, the actual database call is what's cached -- not the data.
What is the best practice in this scenario? Should I just do _cachedData = LoadDataFromDatabase().ToList() to store the evaluated data?

A: You could add .ToList():
static IEnumerable<int> CachedData
{
    get
    {
        if (_cachedData == null)
        {
            _cachedData = LoadDataFromDatabase().ToList();
        }
        return _cachedData;
    }
}

The disadvantage is that if there a 100.000 items in the list and you do this:
var list1 = CachedData.Take(2).Sum();
var list2 = CachedData.Take(3).Sum();
var list3 = CachedData.Take(1).Sum();

... it will load 100.000 items of the list.
The solution is to make implement a LazyList that caches the Enumerable while you are iterating and not in advance. Just replace .ToList() with .ToLazyList().
This results in the best option:

*

*The first 3 items are only loaded 1 time in total.

*Item 4 has never been loaded

An example of an implementation of a lazy list is here.


text:
Q: How do I make my view that is being manipulated by UIPushBehavior not rotate as much? It's an absurd amount Right now, I have a UIPushBehavior that I use on a view to push it off screen depending on where the user touched with a UIPanGestureRecognizer. It works, but my problem is the view rotates an absurd amount... like it's attached to the tire of a sports car.
This is how I attach the UIPushBehavior:
else if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
    [self.animator removeBehavior:self.panAttachmentBehavior];

    self.pushBehavior = [[UIPushBehavior alloc] initWithItems:@[self.imageView] mode:UIPushBehaviorModeInstantaneous];
    [self.pushBehavior setTargetOffsetFromCenter:centerOffset forItem:self.imageView];
    self.pushBehavior.active = YES;

    CGPoint velocity = [panGestureRecognizer velocityInView:self.view];
    CGFloat area = CGRectGetWidth(self.imageView.bounds) * CGRectGetHeight(self.imageView.bounds);
    CGFloat UIKitNewtonScaling = 1000000.0;
    CGFloat scaling = area / UIKitNewtonScaling;
    CGVector pushDirection = CGVectorMake(velocity.x * scaling, velocity.y * scaling);

    self.pushBehavior.pushDirection = pushDirection;

    [self.animator addBehavior:self.pushBehavior];
}

I don't know exactly what I should be changing to manipulate it more. Velocity and everything are perfect, I just don't want it to rotate as absurdly.

A: Maybe it's too late, but if you want to eliminate rotation altogether, do this:
UIDynamicItemBehavior* dynamic = [[UIDynamicItemBehavior alloc] initWithItems:@[self.imageView]];
dynamic.allowsRotation = NO;
[self.animator addBehavior:dynamic];

and the [self.animator addBehavior:self.pushBehavior];


text:
Q: Scala function which computes a stream that contains an Arithmetic sequence Test
test("arithmetic") {
  assert(Calculation.arithmetic(5, 10) === 30)
}

Main
def arithmetic(a: Int, b: Int) : Int = {
  val c = b - a
  val third = b + c
  val fourth = third + c
  val fifth = fourth + c
  fifth + c
}

In Scala one could create a stream that contains a Fibonacci sequence using val fibs = fibFrom(1, 1).take(7). Is it possible to use a stream that creates Arithmetic sequences in Scala as well? If positive, how to implement it?

A: A fibonacci sequence is an arithmetic sequence and you can create whatever sequence you want:
scala> val s: Stream[Int] = 0 #:: s.map(_+5)
s: Stream[Int] = Stream(0, ?)

scala> s(10)
res0: Int = 50

scala> (s take 10).toList
res1: List[Int] = List(0, 5, 10, 15, 20, 25, 30, 35, 40, 45)


text:
Q: Why is there a pip and pip3 on my windows 10 when both point to the same Python 3.8.1 installation? I only installed Python 3.8.1 on my Windows 10, from some instructions I started to use pip3 and installed all the requirements with pip3 but I was hit with numerous problems, especially the packages I just installed can't get imported by python error. Then I did this pip3 --version and pip --version, the results are different. Then I did pip --list and pip3 --list, the results are different too, of course, so I did all the requirements in pip, and that seems to fix my problem.
So now I have this question, why is there a pip and then a pip3 on the same Python 3.8.1?
where pip and where pip3 both return the same folder, C:\Python38\Scripts\pip3.exe

A: Binaries like python and pip point to the default version of Python which was often 2.x, and pip3 and python3 point to the latest installed version of Python 3.x. This was necessary because a lot of software was written for Python 2 and not updated to work with py3. Now that python 2 has reached its end of life, this should hopefully go away in the future.


text:
Q: Convergence of directed family in topological space Let $X$ and $J\neq\emptyset$ be sets s.t for every $j\in J$ $(Z_j,\tau _j)$ is a topological space. Let $\tau $ be weakest topology on $X$ s.t for every $j\in J$, $f_j : X\to Z_j$ is continous. Let $x\in X$ and $(x_\alpha)_{\alpha\in\mathcal
A}$

Show that if for every $j\in J$, $f_j(x_\alpha)\to f_j(x)$, then $x_\alpha\to x$

By convergence, we mean $x_\alpha\to x\iff \forall U_x, \exists\alpha _0 : \forall\alpha (\alpha _0\preceq\alpha\Longrightarrow x_\alpha\in U_x)$, where $U_x$ is a neighborhood of $x$.
Initial thought: Assume for a contradiction, for some $U_x\in\tau $, for every $\alpha$, exists $\alpha _0$ s.t $\alpha\preceq\alpha _0$ and $x_{\alpha _0}\notin U_x$.
Due to continuity of $f_j,j\in J$ we have for every $V_{f_j(x)}\in\tau _j$ exists $\alpha _0$:
$$\forall\alpha (\alpha _0\preceq\alpha \Longrightarrow f_j(x_\alpha)\in V_{f_j(x)}) $$
Therefore $x_\alpha\in f_j^{-1}(V_{f_j(x)})\in\tau $, trouble is that potentially any preimage of $V_{f_j(x)}$ for any $j\in J$ might "miss" the fixed $U_x$ (aside from $x$ itself, of course, but isn't contained in $U_x$).  An idea
$$\bigcup_{j\in J}\bigcup_{V\in\mathcal{V}_{f_j(x)}}f_j^{-1}(V)\overset{?}=\bigcup_{U\in\mathcal{U}_x}U $$
Where $\mathcal{U}_x$ is the collection of all $\tau$ open neighborhoods $x$ and analogous description for $\mathcal{V}_{f_j(x)}$.
It's obvious that $\subset$, but it's not so obvious that $\supset$ and it might not even be true.
What to do? I'm probably over-thinking this problem waaay out of proportion.

A: A basis of $\tau$ is given by the family of sets of the form
$$U = \bigcap_{j \in J_0} f_j^{-1}(W_j),$$
where $J_0$ is a finite subset of $J$, and for every $j \in J_0$, $W_j\in \tau_j$.
Thus, for $x\in X$, a neighbourhood basis of $x$ is given by the family of sets of the form
$$U = \bigcap_{j \in J_0} f_j^{-1}(V_j),\tag{$\ast$}$$
where $J_0$ is a finite subset of $J$ and $V_j$ is a neighbourhood of $f_j(x)$ for each $j \in J_0$.

Let's suppose we have a net $(x_{\alpha})_{\alpha \in \mathcal{A}}$ in $X$ such that $f_j(x_{\alpha}) \to f_j(x)$ for every $j$. We want to show that $x_{\alpha} \to x$.
So let $U$ be an arbitrary neighbourhood of $x$. Choose a neighbourhood $U'$ of $x$ of the form $(\ast)$ such that $U' \subset U$. By assumption, $f_j(x_{\alpha}) \to f_j(x)$ for every $j\in J_0$, so there is an $\alpha_j \in \mathcal{A}$ such that $\alpha_j \preceq \alpha$ implies $f_j(x_{\alpha}) \in V_j$. Since $\mathcal{A}$ is a directed set, there is an $\alpha_{J_0} \in \mathcal{A}$ such that $\alpha_j \preceq \alpha_{J_0}$ for every $j \in J_0$. But then
$$x_{\alpha} \in \bigcap_{j \in J_0} f_j^{-1}(V_j),$$
i.e. $x_{\alpha} \in U' \subset U$, for every $\alpha\in \mathcal{A}$ such that $\alpha_{J_0} \preceq \alpha$. Since $U$ was arbitrary, we have $x_{\alpha} \to x$.


text:
Q: Difference between list and library I have gone through lots of articles on internet and finally decided to ask a question here to all experts.
-- Edits --
I noticed,

*

*I can manage event receivers in both almost same way

*I can create folders in both

*I can add custom fields, site columns to both in same way

*I can save it as list template and move it to some other site collection with data!

So, I want to ask what are what are differences when you think as an architech, developer, analyst or end user?

A: A list contains some fields and data associated with those fields.
Library is nothing but a list, but it contains some attachments. Those attachments are may be word documents, excel sheets pdfs etc..
Find this link

A: A SharePoint Library is a List which has been enhanced with a lot of features (like templates) target at storing documents/files as the main item.
You should use a library when what you want to store is documents/files to which you may have related information, workflows, ...
You should use a list when your main focus isn't a document/file, but something other to which you may relate workflows, attachments, ...
You can do (almost) anything you can do with a list to a document library


text:
Q: Accessing an attribute on a foreign table by joining two tables in Rails ActiveRecord I have a model, Message that belongs to the model User and the User model has an attribute name.
Message:

user_id
message_body

1
"hello world"

User:

user_id
name.

1
"johndoe"

The result I want is a complete list of all the messages and the respective user name that created each of those messages.
the api controller endpoint looks something like:
def index
  @messages = Message.all
  render json: { messages: @messages }
end

The issue is that when I return @messages it only contains the user_id that each message belongs to. What I really want is the user name
I could loop through every message and construct an entirely new object that looks something like:
@object = [
  {
    name: @messages[0].user.name,
    message_body: @messages[0].body
  },
  {
    name: @messages[1].user.name,
    message_body: @messages[1].body
  },

  etc.
]

and then call render json: { messages: @object }
This would probably work fine, but it seems inefficient. Is there a better method for joining these tables for this result?

name
message body

"johndoe"
"hello world"

I was hoping the above example would be enough to get the answer I'm looking for. This is a simplified version of my architecture. In reality it's a bit more complicated:
LeagueChatMessage belongs_to LeagueChat
LeagueChatMessage belongs_to User
LeagueChat belongs_to League
League has_one LeagueChat

so this is really what the controller looks like
def index
  @league = League.find_by(id: 1)
  render json: { messages: @league.league_chat.league_chat_messages }
end

it works fine. It returns all the league chat messages for the league with the id: 1 but it returns the user_id for each message instead of the user name

A: Use following logic
@data = Message.includes(:user)

Now you can use like below
@data.each do |msg|
     puts "Message #{msg.body}"
     puts "User #{msg.user.name}"
 end

I used puts for understanding but you can use this object in views as you want. And your approach leads to an n+1 query problem, so I used the includes, which helps remove the n+1 query. Try this and let me know if you have any queries.


text:
Q: unCaught type error: cannot read property 'null' value for document.getElementByID().value; I am trying to get value of input field but console says cannot read property null value.I have used document.getElementByID().value function. As I do view source the code displays values well but the javascript variable is not getting value. Following is my code:

I also tried using jquery get val() function, as follows...

Look my html code:

 <?php while($row = mysqli_fetch_array( $fetch_customer_menu_result))
      {
        $item_ID=$row['item_id'];
        $item_NAME=$row['item_name'];
        $item_PRICE=$row['item_price'];

        echo '

          <input class="form-control w3-left" type="number" placeholder="count" id="quantity_'.$row['item_id'].'" value="1">

              Rate (each):

              Rs. '.$row['item_price'].'

            <button type="button" class="w3-red btn form-control" onclick="addCart(\' '.$item_ID.' \',\' '.$item_NAME.' \',\' '.$item_PRICE.' \')" >Add To Cart</button>

';
      }
      ?>

A:
Uncaught type error: cannot read property 'null' value for document.getElementById().value;

This error means that document.getElementById() returns a null pointer (i.e. it can't find the element that it is looking for, so it returns null), and that you are then trying to find the value of a field that doesn't exist (document.getElementById("quantity_"+id).value becomes null.value, and null does not have a field named value).
Why?
The most likely reason (in this case) is that the value you pass in as id in your addCart function is incorrect. However, there could be a few causes. Follow these debugging steps:

*

*Make sure that the order of the parameters is the same as defined in your function and where you are calling it (i.e. you are not passing in name where you should be passing in id)

*Add this line just above the line where you get the error: console.log("quantity_"+id) and then use the browser console to check if the text box has exactly that ID - if it doesn't, then that is your problem.

*Make sure addCart is only being called when the text field is on the screen - ensure you don't delete the text field and then call addCart, and that addCart doesn't get called before the element has been created.

*Make sure that there are not two functions with the name addCart.


text:
Q: Undefined Keycloak Properties Authenticated and UserInfo I am trying to get the username and uid of the logged-in user.
In my application I used the ReactKeycloakProvider and useKeycloak()
import {ReactKeycloakProvider} from '@react-keycloak/web';
import keycloak from './keycloak';

const onKeycloakEvent = (event: any, error: any) => {
    console.log('onKeycloakEvent', event, error)
}

const onKeycloakTokens = (tokens: any) => {
    console.log('onKeycloakTokens', tokens)
}

const initOptions = {
    onLoad: 'login-required',
    checkLoginIframe: false
}

ReactDOM.render(
    <React.StrictMode>
        <ReactKeycloakProvider
            authClient={keycloak}
            initOptions={initOptions}
            onEvent={onKeycloakEvent}
            onTokens={onKeycloakTokens}
        >
            <Provider store={store}>
                <App/>
            </Provider>
        </ReactKeycloakProvider>

    </React.StrictMode>,
    document.getElementById('root')
);

As a test I wanted to see if I can fetch the userInfo into my Header.tsx
import { useKeycloak} from "@react-keycloak/web";

const Header = () => {

    const { keycloak, initialized } = useKeycloak();

    console.log(keycloak);
    console.log(keycloak.authenticated);
    console.log(keycloak.userInfo);
    ...

Problem: For some reason the following logs output undefined
console.log(keycloak.authenticated);
console.log(keycloak.userInfo);

The example in the official documentation looks like this:
https://github.com/react-keycloak/react-keycloak-examples/blob/master/examples/react-router/src/pages/Home.tsx
and is almost identical to mine.

A: I found the solution.
I had to change the settings within Keycloak. So what I did was: Chose my Realm, and then under Clients -> Acess Type and change it from confidential to public.

A: The difference in KeyCloak with public and confidential Clients is the Client-Secret. With 'public' you dont need the secret to initiate the login protocol which means in theory everybody can register/login to your KeyCloak. With the confidential type KeyCloak generates a unique Client-Secret for your Client that  you have to pass on in the options to start the logon process. With that you can make sure that only your Application (where you pass on the secret) gets to authenticate with your KeyCloak-Client.


text:
Q: Sort by 2 columns with hierarchical sorting [Pandas] I have a dataframe such as:
COL1 COL2
1 pupa male
2 pupa female
3 pupae female
4 larva female
5 larvae female & male
6 pupe female
10 adult female
12 NA female
7 pupa male
8 pupae male
9 adult male
11 pupae NA
13 NA male

so the idea is to first sort by COL2 where I should sort any value containing female in first:
str.contains("female") > !str.contains("female")

COL2 > COL1 so
Then sort by COL1 where I should first put value containing pup then larv then others
str.contains('pup') > str.contains("larv") > other

Here is the expected value:
COL1 COL2
2 pupa female
3 pupae female
6 pupe female
4 larva female
5 larvae female & male
10 adult female
12 NA female
1 pupa male
7 pupa male
8 pupae male
9 adult male
11 pupae NA
13 NA male

So far I only succeed to sort by COL1 using:
df['Sex'] = pd.Categorical(df['Sex'], ['female','pooled male and female', 'male and female','male'])

df=new_df.sort_values("Sex")

But as you can see here the solution needs a list instead of a .str.contains solution (which is more globally)

A: Best things i found for you is to convert these labels to numbers & then sort.
Ex. female & starts with female = 1,male = 0 & others = -1, Same way for col1.
Then it will be easy to sort. Below i have something for you -
data = [['pupa', 'male'],
['pupa', 'female'],
['pupae', 'female'],
['larva', 'female'],
['larvae', 'female & male'],
['pupe', 'female'],
['pupa', 'male'],
['pupae', 'male'],
['adult', 'male'],
['adult', 'female'],
['pupae', 'NA'],
['NA', 'female'],
['NA', 'male']]

import pandas as pd

data_df = pd.DataFrame(data, columns=['col1', 'col2'])
data_df
    col1    col2
0   pupa    male
1   pupa    female
2   pupae   female
3   larva   female
4   larvae  female & male
5   pupe    female
6   pupa    male
7   pupae   male
8   adult   male
9   adult   female
10  pupae   NA
11  NA      female
12  NA      male

data_df['col2_cond'] = data_df['col2'].apply(
    lambda x:1 if x.startswith('female') else (-1 if x == 'NA' else 0)
)
data_df['col1_cond'] = data_df['col1'].apply(
    lambda x:2 if x.find('pup') != -1 else (1 if x.find('larv') != -1 else (-1 if x == 'NA' else 0))
)

data_df.sort_values(['col2_cond', 'col1_cond'], ascending=[False, False])
    col1    col2      col2_cond col1_cond
1   pupa    female          1   2
2   pupae   female          1   2
5   pupe    female          1   2
3   larva   female          1   1
4   larvae  female & male   1   1
9   adult   female          1   0
11  NA      female          1   -1
0   pupa    male            0   2
6   pupa    male            0   2
7   pupae   male            0   2
8   adult   male            0   0
12  NA      male            0   -1
10  pupae   NA             -1   2

Note - I considered NA as string elements. But you can check for None types.


text:
Q: Add $title to url with .htaccess file I recently had the following answered: .htaccess rewrite url does not work
I would like to now add the title from the db for each id to the URL too. From what I've read on the internet it seems that it is possible. Mostly I have $title in each php file which refers to the title in the db.
Currently I'm using this in my current .htaccess file:
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# Redirect cars.php?cars_item=231 to cars/231/
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+cars/cars\.php\?cars_item=([^&\s]+) [NC]
RewriteRule ^ /cars/%1 [R=302,L]

# Internally forward cars/231/ to cars.php?cars_item=231
RewriteRule ^cars/([0-9]+)/?$ /cars/cars.php?cars_item=$1 [NC,L]

And the following as href: $title.
So what I wish to have as my URL is the following.  Basically I need to add the title to the current URL and replace the spaces between words in title with dashes.
http://www.domain.com/cars/543/new-porsche-is-out

*

*cars -> subfolder

*543 -> $id (From the database)

*new-porsche-is-out -> $title (From the database)

A: You can just change your last rule to allow title in the end:
# Internally forward cars/231/title to cars.php?cars_item=231
RewriteRule ^cars/([0-9]+) /cars/cars.php?cars_item=$1 [NC,L,QSA]


text:
Q: SAS total of 'by' category I have the following sample data:
data have;
   input username $ amount betdate : datetime.;
   dateOnly = datepart(betdate) ;
   format betdate DATETIME.;
   format dateOnly ddmmyy8.;
   datalines;
player1 90 12NOV2008:12:04:01
player1 -100 04NOV2008:09:03:44
player2 120 07NOV2008:14:03:33
player1 -50 05NOV2008:09:00:00
player1 -30 05NOV2008:09:05:00
player1 20 05NOV2008:09:00:05
player2 10 09NOV2008:10:05:10
player2 -35 15NOV2008:15:05:33
run;
 PROC PRINT data=have; RUN;

proc sort data=have;
   by username betdate;
run;

data want;
   set have;
   by username dateOnly betdate;
   retain calendarTime eventTime cumulativeDailyProfit profitableFlag totalDailyProfit;
   if first.username then calendarTime = 0;
   if first.dateOnly then calendarTime + 1;
   if first.username then eventTime = 0;
   if first.betdate then eventTime + 1;

   if first.username then cumulativeDailyProfit= 0;
   if first.dateOnly then cumulativeDailyProfit= 0;
   if first.betdate then cumulativeDailyProfit+ amount;

   if first.dateOnly then totalDailyProfit = 0;
   if first.betdate then totalDailyProfit + amount;
 PROC PRINT data=want; RUN;

The final column in the output 'cumulativeDailyProfit' is exactly what I want: an incrementing value which adds the value of the 'amount' field. However, I don't want the same to happen for the field 'totalDailyProfit' becuase I want this to show the profit at the end of the day i.e. the last value for cumulativeDailyProfit for each customer.
For example, the eight columns above would ideally show the following: -100, -60, -60 ,-60, 90, 120, 10, -35. I will then set the 'profitableFlag' boolean if this value is greater than 0 for the rows relating to that day and that customer.
Is this something that can actually be done in a data step? I want to be able to run the following query (with the right flag in the case when clause) to get the average, average on winning days and average on losing days.
proc sql;
    select calendarTime,
    mean(amount) as meanStake,
    mean(case when profitableFlag  = 1 then amount else . End) as meanLosingDayStake,
    mean(case when profitableFlag  = 1 then amount else . End) as meanWinningDayStake
    from want
    group by 1;
quit;

A: Try this query :
proc sql;
    select calendarTime,
    avg(amount) as meanStake,
    avg(case when profitableFlag  = 1
            then amount else 0 End) as meanLosingDayStake,
    avg(case when profitableFlag  = 1
            then amount else 0 End) as meanWinningDayStake
    from want
    group by calendarTime;
quit;


text:
Q: Motivations for Hyperbolic Geometry Why would one study hyperbolic geometry? I am only aware of the motivation where you give axioms for elementary euclidean geometry and then start to wonder wether the parallel axiom is necessary. You then see that if you negate the axiom you get the hyperbolic space instead of the euclidean space. But if this were the only motivation then one might very well learn the construction of the space and then stop. Instead it is taught in elementary and differential geometry and this can't be only because the theorems are exotic if compared to the euclidean case.
I am mostly looking for mathematical motivations here, so what are relations to other fields, what are the advanced topics and such. Why is hyperbolic geometry of interest for a mathematician?

A: First, we should note that a very similar question has already been asked here, and several interesting answers were given. But because the question keeps coming up, I'm going to go out on a limb and suggest that there still might be room for a more complete list of reasons why hyperbolic geometry is important in its own right.
It's hard to know where to start, because there are so many good reasons to study hyperbolic geometry beyond its obvious historical importance in the development of geometry. I'm going to start this list with a few things I can think of off the top of my head; I'll make this answer community wiki so others can elaborate or add to it as they think of other things.
Why is hyperbolic geometry important?

*

*History of math: First, just for completeness, I'll mention the historical reason. The discovery of hyperbolic geometry was, in my opinion, the second most important event in the history of mathematics (the first being Euclid's introduction of the axiomatic method). Up until the nineteenth century, everyone thought of axioms as self-evident truths about the real world, which could be built upon to derive less self-evident truths. Since the discovery of hyperbolic geometry, axioms have been thought of as more or less arbitrary assumptions that could be used to get an axiomatic system started, and then everything proved within that system is exactly as valid as the axioms themselves. It's the foundation of the way we currently understand mathematical truth. (I've written more about this in the preface and Chapter 1 of my undergraduate textbook Axiomatic Geometry.)

*Complex analysis: The hyperbolic geometry of the unit disk (or, equivalently, the upper half-plane) plays a central role in complex analysis. For example, the Schwarz-Pick Lemma says that any holomorphic map from the unit disk to itself is either an isometry of the hyperbolic metric or a strict contraction (which decreases all distances). This has important consequences for understanding the nature of holomorphic maps.

*Geometry of Surfaces: Most connected surfaces (all but the plane, cylinder, torus, Möbius strip, Klein bottle, sphere, and projective plane) carry a Riemannian metric of constant negative curvature, which is therefore locally isometric to the hyperbolic plane. Moreover, all such surfaces can be realized as quotients of the hyperbolic plane modulo discrete groups of hyperbolic isometries.

*Geometry of Three-Manifolds: The geometrization theorem says that every closed 3-manifold can be cut along spheres and tori into finitely many pieces, each of which can be given one of eight possible highly symmetric geometric structures. By far the richest of these structures is hyperbolic geometry, which accounts for "most" three manifolds.

*Cosmology: The leading candidates for modeling the shape of the universe as a whole are the FLRW models, in which the spatial geometry of the universe is either flat, spherical, or hyperbolic. Which one depends on the average density of matter and energy and the value of the "cosmological constant."

*Fermat's Last Theorem: Wiles's proof of Fermat's last theorem made essential (and unexpected) use of modular forms, which are functions on the hyperbolic plane that satisfy a specific transformation property under a certain discrete group of hyperbolic isometries.

*Art: This list wouldn't be complete without mentioning the groundbreaking uses of hyperbolic geometry in the art of M. C. Escher.

A: +1) Blue, one needs to look into some history here.
That parallel postulate (which was put indeed as an axiom by Euclid) was challenged by many not to be a postulate at all. In fact, many mathematicians and other scientists alike thought that it should have been a theorem rather than just being given as an assumption. When considering it as a theorem, in a nut shell it came down to several cases to be observed when the "proof" was generated.
And as it turns out, for many parallel lines through a given point it came a hyperbolic surface and when no parallel line would suit, the surface became a sphere. And so this resulted in many new properties, one of them being that the sum of angles relates to the area of a triangle. Challenging the parallel postulate is just another great example that new doors to unknown worlds open up. A good book (there are several) to read would be : "Introduction to non Euclidean Geometry" by Wolfe (Dover publ).

A: I share the same views of Imranfat.Imagine for close to 19 centuries Euclidean geometry ruled the roost, just a plus minus change at the proper place opened the door to a new world so similar and yet so different and captivatingly beautiful. In the new order there being a teasing familiar part, an unknown part that demands your intellectual attention holding out a hope for new research.
There is not one but a host of novelties out there.The validity and further scope even over and above the three models awaiting new approaches or  developments. The refreshingly new definitions of line intersection and parallels that remove a straight line and plug in curved lines in place with fully recognizable validity..All trigonometric functions can be transformed into hyperbolic functions. Triangles with angle excess getting into deficit.
Even its history is interesting.The big Gauss kept it to himself for a long time until its reality had to surface, its discovery and frustrations by Bolyai, Riemann's made distinction between the infinite and the indefinite, Gauss's spontaneous cry of joy after his Dissertation, Beltrami's solid work leading to its firm footing, his paper-mache  molded model with saddle points..even today Daina Tamania's crocheting on display at the Smithsonian etc. etc..
Difficult to answer what job opportunities and what extra $ comes out of it, but a concern for any avenue that science takes you through is good. Just wroting in extempore..
Gauss Egregium theorem. You squeeze a hemisphere to see all three type of shapes and even a fourth one a non-symmetrical shape like a huge grain of wheat without rotational symmetry. A curved line on a cone is still straight when opened out flat can be relevant to warped surfaces..  A beautiful mind that sees any surface isometrically embeddable into possible deeper dimension far beyond a geometry what meets the eye, the hyperbolic geometry's unmistable part.

A: I think that there is one use for hyperbolic geometry. I think some properties of the theory of special relativity can be figured out from properties of hyperbolic geometry. I think there are also some people who see no use for hyperbolic geometry but want to study it anyway.
Although that didn't use to be the case, I am now interested in mentally studying more general math all on my own. I think that some time in the future, it will come to me very naturally that when ever a property of something could is not such an insignificant property in a certain sense which is probably more broad than most people consider significant and includes properties that are not useful to know, and that property can actually be computed without too large a number of computations, I will see and notice that property. I'm probably going to love that that comes naturally. I'm not studying hyperbolic geometry very much myself at the moment. However, some people like me might study hyperbolic geometry for fun even if they see no use for it.


text:
Q: Why does /wp-admin login send me to this landing page? I'm trying to help a friend access his website after a different developer created it, but when I visit the site.com/wp-admin, it doesn't take me to the typical dashboard and backend I'm used to seeing. It looks like this.

When you click through all those links, it just shows all the wp-super-cache data and maybe one page of code, but it's all uneditable. What could be the case? How can I find a way to access the dashboard again? Did the old developers hide it so that we can't go in and fix it ourselves?
Thanks so much for all your help!

A: Do you have access via FTP or SFTP? If so you could test disabling all plugins. To do that go to /wp-content/plugins/ Inside the plugins directory create a new directory calle off and move all plugins inside the off directory. See if you can access the login page now. If not you can try the same thing in /wp-content/themes/ to see if it's a plugin or a theme causing that.
Other thing to try is to find the .htaccess file in your root folder and rename it to disable it to see if that is causing this behavior.

A: You can try /wp-login.php instead.  WordPress htaccess by default ignores direct hits to files and directories.  cache plugin will make modifications to htaccess as well. sorry not great answer but i can't comment yet apparently you gotta do this for a real long time to prove your worth.


text:
Q: Improving SharePoint Online Search We are trying to expose some advanced search capabilities for a SharePoint Online document library in the "new" format. We've uploaded a number of files to this library that may need to be produced in litigation. Our users are finding the limits of the built-in search though.
Filters are good, but there's no display of all of the different types of metadata columns I've added to the library. Only a subset.
Using keyword search:

*

*No overview of the different types of metadata, or ability to
specify the fields to search.

*Results are a little unpredictable.
Using standard qualifiers like "", AND, OR doesn't work the way you
expect.

*There's no indicator as to how many results you've
retrieved, and you can't perform an action on the result set that
was returned. The dynamic display of results makes this frustrating.

I've tried using the enterprise search, and at least out of the box, it has a different problem: clicking on a search result brings you to a view where it's not possible to update the metadata on the result. It's a scroll/view-only display. (this is for PDFs and .msg files).
How can I improve the search results and search filtering options? Is there a simple, out of the box way, or do I have to build a bunch of forms? I did find

*

*Making SharePoint Search Results Even Better For Your Users

*Customizing the Search Experience in SharePoint Online
which give some indications for SharePoint 2013, and I assume similar for 2016 and Online. Is there a solution we can buy that exposes searching on metadata columns out of the box? We have limited resources to build custom solutions.
Thanks for anything that will help get this started! The searching I've done on Google gives very limited relevant results, so if there's a great overview somewhere let me know.

A: All of the metadata that you have added to the library should be searchable (since its Online it might take a bit of time for the crawlers to pick up those).
Once its crawled you can create Metadata properties and attach it to crawled property.
Then you can also make the relevant properties Refineable.
You can also go to Search Settings -> Result Sources -> And use the query editor to try out what queries works best for you and tune it accordingly.
Also on the result web part properties you can configure a bunch of settings that allow you to display the number of results, paging, sorting etc.
https://technet.microsoft.com/en-us/library/gg549987.aspx


text:
Q: Minecraft: TAB name change I have a nickname plugin on this server and I have changed my name. Is there a way for me to change my name on TAB too? Thanks!

A: This sounds like a plugin request I do say, but I'll recommend one anyways.
ColoredTabList includes the  command coloredtablist nick <nickname> . This Changes your Name in the Tablist until you reconnect or the Server reloads.


text:
Q: Product count difference on categories and attributes filter in layered navigation on category Page in Magento 2 There is a problem with showing product count on category and attribute filter section on the category page. In the product listing page, we are enabled to show the out of stock products. And in listing toolbar section it showing correct product count. But in Layered navigation filter section for the category and attributes it showing product count without out of stock products.

A: if you added some custom conditions for product collection, your custom conditions work fine for your product collection in the listing page but when you check for layered navigation in the left sidebar, You may have the wrong result for product collection.
Reference Link


text:
Q: How do I echo a value into an option form from mysql I have two dropdown/select input on a form, Room Type and Number of Guests both of them are connected to mysql.
How do I make the value of my Number of guests change automatically to whatever data is connected to the Room Type.
For example, Room Type A can only have a maximum of 2 guests and on mysql there is a table for room types which have the number of rooms and number of guests limits.
How do I echo the guests limit into the number of guests input form?
Here's my ROOM TYPE code:

Room Type

    <select id="category" name="category" required="">

      <?php
      include 'connect.php';
      $room= "SELECT * FROM roomtype";
       $resroom = $conn->query($room);
        while($roomtype = $resroom->fetch_assoc()){
        ?>
      <option value="<?php echo $roomtype['roomtype'];?>" ><?php echo $roomtype['roomtype'];?></option>

        <?php
        $max = $roomtype['guests'];
        }?>
        </select>

Here's my Number of guests code:

Number of Guests *

<select id="category1" name="guests" required="">
 <?php
 include 'connect.php';
 $inc = 1;
 if(isset($_POST))
 {
 $category = $_POST['category'];
 }
 $guest = "SELECT * FROM roomtype WHERE roomtype = $category";
  $g = $conn->query($guest);
   while($guest1 = $g->fetch_assoc()){
 while ($guest1 ['guests'] < 0){
  ?>
  <option value="1"><?php echo $inc; $inc = $inc + 1; }}?></option>
   </select>

My connect/database code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "booking";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>

The roomtypetable has three columns id, roomtype, guests.

A: You need to achieve the same with the help of JQuery instead of php. because this operation will happen at the client side.
What you can do is add a comman attr in both select option named value with the id you will fetch from mysql.
Aside this you need to handle onselect event you need to change the value in numberofguest.
for more details : how to change a selections options based on another select option selected?

A: First you have to select room data with number of guests of every room..
Now code them like this

Room Type

<select id="category" name="category" required="">
    <option value="0">Room Number</option>
    <?php
        include 'connect.php';
        $room= "SELECT * FROM roomtype";
        $resroom = $conn->query($room);
        while($roomtype = $resroom->fetch_assoc())echo '
    <option value="'.$roomtype['roomtype'].'" data-limit="'.$roomtype['guests'].'" >'.$roomtype['roomtype'].'</option>';
    ?>
</select>

Number of Guests

<select id="guests" name="guest"><option value="">Number of Guests</option></select>

jQuery


text:
Q: How to check if record exists by searching into inner array I have this record in DB
{
   "_id": ObjectId("5759ccbcc2b503980c000143"),
   "phone": "516-425-5878",
   "orders": [
     "1338475681",
     "1891805481",
     "1891805481"
  ]
}

Here is my code.
$collection = $mongo_db_obj->selectCollection('scrapers', 'leads');
$data = array(
    'phone' => '516-425-5878',
    "orders" => array('$in'=>1891805481)
);

$doc = $collection->findOne($data);

dump($doc);

I want to check if particular phone and and order id inside orders array exists or not. But my code is giving error.
I have tried this one too.
$data = array(
'phone' => '516-425-5878',
"orders" => array(1891805481)
 );

But it returns empty results.
How do I check that?

A: $in operator selects documents where field values matches values in an array.
Please try executing following code snippet as a solution to above mentioned issue
$conn = new MongoClient('localhost:27017');
$db = $conn->selectDB("mydb");
$collection=$db->mycoll;
$data = array(
    'phone' => '516-425-5878',
    "orders" => array('$in'=>array('1891805481'))
);
$data=$collection->findOne($data);


text:
Q: How can a writer after a barrier be visible before a write preceding the barrier? In the memory barrier documentation of the linux kernel (Documentation/memory-barriers.txt), there are examples showing that a writer after a memory barrier is visible before a write preceding the memory barrier to other CPUs. How can this happen? Why is the write barrier not sufficient in ordering these writes?
In particular the following:
843         CPU 1                   CPU 2
844         ======================= =======================
845                 { B = 7; X = 9; Y = 8; C = &Y }
846         STORE A = 1
847         STORE B = 2
848         <write barrier>
849         STORE C = &B            LOAD X
850         STORE D = 4             LOAD C (gets &B)
851                                 LOAD *C (reads B)
852
853 Without intervention, CPU 2 may perceive the events on CPU 1 in some
854 effectively random order, despite the write barrier issued by CPU 1:
855
856         +-------+       :      :                :       :
857         |       |       +------+                +-------+  | Sequence of update
858         |       |------>| B=2  |-----       --->| Y->8  |  | of perception on
859         |       |  :    +------+     \          +-------+  | CPU 2
860         | CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
861         |       |       +------+       |        +-------+
862         |       |   wwwwwwwwwwwwwwww   |        :       :
863         |       |       +------+       |        :       :
864         |       |  :    | C=&B |---    |        :       :       +-------+
865         |       |  :    +------+   \   |        +-------+       |       |
866         |       |------>| D=4  |    ----------->| C->&B |------>|       |
867         |       |       +------+       |        +-------+       |       |
868         +-------+       :      :       |        :       :       |       |
869                                        |        :       :       |       |
870                                        |        :       :       | CPU 2 |
871                                        |        +-------+       |       |
872             Apparently incorrect --->  |        | B->7  |------>|       |
873             perception of B (!)        |        +-------+       |       |
874                                        |        :       :       |       |
875                                        |        +-------+       |       |
876             The load of X holds --->    \       | X->9  |------>|       |
877             up the maintenance           \      +-------+       |       |
878             of coherence of B             ----->| B->2  |       +-------+
879                                                 +-------+
880                                                 :       :
881
882
883 In the above example, CPU 2 perceives that B is 7, despite the load of *C
884 (which would be B) coming after the LOAD of C.

A: The write barrier does order the write correctly.
As the following text explains, the problem is that CPU 2 can read *C before C because it does not use any kind of read barrier.

A: A better article to read for memory barriers is http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.07.23a.pdf


text:
Q: Startup screen toggle button [Visual Basic] So, I'm working on a program in Visual Basic (2010) and I have a startup window with some quick buttons and stuff.
I want to have a checkbutton that can determine wether or not the startup screen will be displayed next time the application starts.
Anyone that can help?
Thanks!

A: You could look at using settings (Right click your project in the Solution Explorer and go to "Properties", there'll be a tab called "Settings") and create a bool for "showStartup" then use the following code:
if (Properties.Settings.Default.showStartup)
{
    startupForm.ShowDialog();
}

As for working with a checkbox, you can use the "CheckedChanged" event and use:
Properties.Settings.Default.showStartup = showOnStartup.Checked;