text:
Q: Definition of Equation of straight line My text book of Coordinate Geometry defines straight line as follows:-

Equation of a line:- Equation of a straight line is an equation in $x$ and $y$ which is satisfied by the coordinates of all points on the line and is not satisfied by the coordinates of any points which does not lie on the line. Thus, in order to find the equation of a line and establish a relation in $x$ and $y$ which contains only $x$ and $y$ and known quantities.

I don't see the significance of this definition of line, at least at my present level of mastery of the subject(which you can say is infinitesimal).
Is this just a formal way to define a line, or does this help in proving some very non-intuitive results in geometry. Some illustrations to show the significance of this definition would be appreciated.
Also, I think that defining the line in terms of points holds some algebraic relevance like relating the solution set or something like that. I am not very clear what I am trying to conclude by trying to come up with an algebraic connection but I think that the book implies to think of the solution set of the equation. Am I thinking correctly in this regard or am I just thinking aimlessly, if the direction is correct then if you could can you give a suitable example to illustrate it. I would be pleased if you can also answer this additional question.


text:
Q: Object tracking in video I'm trying to tracking people in the video. But I can not find a suitable algorithm that would behave similarly to https://www.youtube.com/watch?v=Qjr3RYecv3U.
I tried template matching in combination with optical flow, but always lose the tracked object if it overlaps another object. Could someone recommend a suitable method for tracking?
I am using Python and OpenCV.

A: The results of the ILSVRC 2017 competition were released yesterday (July 17, 2017).  The winner in the two tracking categories, Task 3c (Object detection/tracking from video with provided training data) and Task 3d (Object detection/tracking from video with additional training data), was this team:
Jiankang Deng(1), Yuxiang Zhou(1), Baosheng Yu(2), Zhe Chen(2), Stefanos Zafeiriou(1), Dacheng Tao(2), (1)Imperial College London, (2)University of Sydney
Here are their publications, source code, and a presentation:
[1] Deep Feature Flow for Video Recognition
Xizhou Zhu, Yuwen Xiong, Jifeng Dai, Lu Yuan, and Yichen Wei, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2017.
[2] Flow-Guided Feature Aggregation for Video Object Detection, Xizhou Zhu, Yujie Wang, Jifeng Dai, Lu Yuan, and Yichen Wei. Arxiv tech report, 2017.
Presentation
https://www.youtube.com/watch?v=J0rMHE6ehGw
Source Code
https://github.com/msracver/Deep-Feature-Flow
The code has the following prerequisites:

*

*Python 3.2.0+

*Microsoft's MXNet

*Cython

*OpenCV (Python bindings)

Their code requires a GPU with at least 6GB of memory.
Another option is ROLO.  The author is Guanghan Ning and he uses You Only Look Once (YOLO) for detection and uses TensorFlow to implement LSTMs for tracking.
His published a paper:
Spatially Supervised Recurrent Convolutional Neural Networks for Visual Object Tracking, IEEE International Symposium on Circuits and Systems, 2017
His code is here: https://github.com/Guanghan/ROLO
Project page: http://guanghan.info/projects/ROLO/
Prerequisites:

*

*Python 2.7 or 3.3+

*TensorFlow

*Scipy

*OpenCV (Python bindings)

Some videos of his work:

*

*ROLO example on unseen sequence: Surfer

*ROLO example on unseen sequence: Boy

*ROLO example on unseen sequence: Jumping

A: If you are looking for some quick code which runs in CPU, take a look at Drew-NF. This is a python implementation of the neural network discussed in the paper Tubelets with
Convolutional Neural Networks for Object Detection from Videos.
To Run the script you need:

*

*Tensorflow

*OpenCV
DrewNF Github Repo

redpajama_set_name: RedPajamaStackExchange


text:
Q: how do I pass data from native app to flutter? I have read this https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps.
My problem is to pass data from existing native android app to flutter module (such as: token, username...etc). So, I want to ask if there is any way to pass data between Native code in existing native app and code in flutter module?
For example, there are two pages, A and B, A is written in Java code, B embed flutter view, I didn't find any way to pass data from A to the flutter view in B.
public class TwoActivity extends AppCompatActivity {

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

        setContentView(R.layout.two_activity);

        //this params passed from HomeActivity
        String params = getIntent().getStringExtra("params");

        FrameLayout rootView = findViewById(R.id.container);

        View flutterView = Flutter.createView(this, getLifecycle(), "service");

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rootView.addView(flutterView, layoutParams);
    }
}

this is main.dart
void main() => runApp(chooseWidget(window.defaultRouteName));

Widget chooseWidget(String route) {
  switch(route) {
    case 'service':
      return MyFlutterView();
  }
}

class MyFlutterView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  static const platform = const MethodChannel('samples.flutter.dev/start');

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[

          Text(
            'this is a flutter page',
            style: TextStyle(
              fontSize: 14,
              color: Colors.blue
            ),
          ),

          FlatButton(
            onPressed: () {
              platform.invokeMethod('startActivity');
            },
            child: Text('go native page'),
            color: Colors.purple,
            highlightColor: Colors.deepPurple,
          )
        ],
      ),
    );
  }
}

-------------------------->edit in 2019.7.18<-----------------------------
Thank you for your help. I found the answer.
1、BasicMessageChannel:use this to pass string or other object.

2、MethodChannel:use this to method invocation

3、EventChannel: use this to event streams

A: You can use method channel for this
private static final String CHANNEL = "AndySample/test";

FlutterEngine flutterEngine=new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
    DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache
    .getInstance()
    .put("my_engine_id", flutterEngine);
flutterEngine.getNavigationChannel().setInitialRoute("/");

    MethodChannel mc=new
    MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),CHANNEL);
    mc.setMethodCallHandler((methodCall, result) ->
        {
            if(methodCall.method.equals("test"))
            {
                result.success("Hai from android and this is the data yopu sent me "+ methodCall.argument("data"));
//Accessing data sent from flutter
            }
            else
            {
                Log.i("new method came",methodCall.method);
            }

        }
    );

use this blog to know more
https://medium.com/@andymobitec/flutter-sending-data-between-android-and-flutter-1e0693fbae64

A: You can pass data with method channel, Yes I am late for answer but it might be useful for other devs.
In native you need to invoke method channel, below is example of android.
val testChannel = MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, "method_channel_name")
            testChannel.invokeMethod("method_name", referrerUrl);

In Flutter you can listen this invoked method.
static const platform = const MethodChannel('method_channel_name');
platform.setMethodCallHandler((call)async{
      // you can get hear method and passed arguments with method
      print("init state setMethodCallHandler ${call.arguments}");
    });


text:
Q: Combining Choice with Any fails to marshal without @XmlRootElement I'm using JAX-B to generate POJOs from a predefined XSD.
I encountered this element definition
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://order.example.com"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://order.example.com"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified">

    <xs:element name="Order">
        <xs:complexType>
            <xs:sequence>
                <xs:choice maxOccurs="unbounded">
                    <xs:choice minOccurs="0" maxOccurs="3">
                        <xs:element name="Credit" type="CreditType" form="qualified"/>
                        <xs:element name="GiftCard" type="GiftCardType" form="qualified"/>
                    </xs:choice>
                    <xs:any namespace="##other" processContents="lax"/>
                </xs:choice>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="CreditType">
        <xs:sequence>
            <xs:element name="Number" type="xs:string" />
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="GiftCardType">
        <xs:sequence>
            <xs:element name="Code" type="xs:long" />
        </xs:sequence>
    </xs:complexType>

</xs:schema>

As you notice there's an awful combination of a nested <choice/> with <any/>.
XJC generates this code:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "creditOrGiftCardOrAny"
})
@XmlRootElement(name = "Order")
public class Order {

    @XmlElementRefs({
        @XmlElementRef(name = "GiftCard", namespace = "http://order.example.com", type = JAXBElement.class, required = false),
        @XmlElementRef(name = "Credit", namespace = "http://order.example.com", type = JAXBElement.class, required = false)
    })
    @XmlAnyElement(lax = true)
    protected List<Object> creditOrGiftCardOrAny;
}

Where the property references JAXBElements instead of the generated classes of CreditType and GiftCardType.
If I try to marshal an Order object like this:
Order order = new Order();
CreditType credit = new CreditType();
credit.setNumber("4111111111111111");
order.getCreditOrGiftCardOrAny().add(credit);

JAXBContext jaxbContext = JAXBContext.newInstance(Order.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(order, System.out);

I get the following error:
[com.sun.istack.internal.SAXException2: unable to marshal type "com.example.order.CreditType" as an element because it is missing an @XmlRootElement annotation]

Which can be solved by adding a binding that forces XJC to annotate the class, the problem is that in my case I have many occurrences of this issue and so having to add a binding for each type doesn't scale very well.
Anyone has a better suggestion?
I uploaded a maven project reproducing the issue: https://github.com/jcfandino/jaxb-choice
Just run:
git clone https://github.com/jcfandino/jaxb-choice.git && cd jaxb-choice
mvn test


text:
Q: Getting "Can't set headers after they are sent error" in PassportJS authentication middleware I have several NodeJS APIs and they need Azure AD authentication. I used PassportJS along with passport-azure-ad node package for that. I am getting Can't set headers after they are sent error when I am doing load test using JMeter and reaching X number of users. The error is not occurring in normal usage.
I checked the code, I didn't come across any place where response object is modified after it's sent. Below given is stripped version of code and exception stacktrace. I have also put the comment within code for line of number which is part of stacktrace. Please guide me what I am doing wrong. I can add further details if needed.
Stacktrace
at AppInsightsAsyncCorrelatedErrorWrapper.ZoneAwareError (.....\node_modules\applicationinsights\node_modules\zone.js\dist\zone-node.js:811:33)
at new AppInsightsAsyncCorrelatedErrorWrapper (.....\node_modules\applicationinsights\out\AutoCollection\CorrelationContextManager.js:193:18)
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (.....\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (.....\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (.....\node_modules\express\lib\response.js:267:15)
at myPassport.authenticate (.....\.....\common\authentication-middleware.js:252:47)
at Strategy.strategy.error (.....\node_modules\passport\lib\middleware\authenticate.js:353:18)
at verified (.....\node_modules\passport-azure-ad\lib\bearerstrategy.js:550:23)
at .....\.....\common\authentication-middleware.js:165:29
at Request.request [as _callback] (.....\.....\currentUserUtil.js:23:7)
at self.callback (.....\node_modules\request\request.js:185:22)
at ZoneDelegate.invokeTask (.....\node_modules\applicationinsights\node_modules\zone.js\dist\zone-node.js:275:35)
at Zone.runTask (.....\node_modules\applicationinsights\node_modules\zone.js\dist\zone-node.js:151:47)

index.js
const express = require('express');
const app = express();
const entityRoute = require('./entity-api');

const authMiddleWare = require('../common/authentication-middleware');
authMiddleWare.initializeAuthentication();

app.get('/', (req, res) => {
    res.json({ item: 'My RESTful API - Version 1.0.0' });
})
.use('/entity', function(req, res, next) {
    authMiddleWare.ensureAuthentication(req, res, next);
}, entityRoute);

module.exports = app;

authentication-middleware.js
var Passport = require('passport').Passport;
var myPassport = new Passport();
let ODICBearerStrategy = require('passport-azure-ad').BearerStrategy;
const currentUserUtil = require('./currentUserUtil');

const _initializeAuthentication = function() {
    myPassport.use(validateTokenMiddleware());
}

const validateTokenMiddleware = function() {
    var options = {
        // several values here
    };
    var bearerStrategy = new ODICBearerStrategy(options,
        function(req, decodedToken, done) {
            try {
                if (decodedToken && decodedToken.oid) {
                    currentUserUtil.getCurrentUserByOid(decodedToken.oid, req.get('authorization'), function(result) {
                        if (result && result.oid == decodedToken.oid) {
                            done(null, {}, decodedToken);
                        } else if (result && !result.Status && decodedToken.name && decodedToken.name.toLowerCase() == "superadmin") {
                            done(null, {}, decodedToken);
                        } else {
                            // below line is part of stacktrace - authentication-middleware.js:165:29
                            done("Access Denied", "Access Denied", "Access Denied");
                        }
                    })
                } else {
                    done("Access Denied", "Access Denied", "Access Denied");
                }
            } catch (ex) {
                done("Access Denied", "Access Denied", "Access Denied");
            }
        }
    );
    return bearerStrategy;
};

const _ensureAuthentication = function(req, res, next) {
    myPassport.authenticate('oauth-bearer', {
        session: false
    }, (err, user, info) => {
        if (err || !user) {
            let errorMsg = "Token Missing : Access Denied";
            if (info) {
                if (info.indexOf('expired') !== -1) {
                    errorMsg = "Token Expired :  Access Denied";
                } else if (info.indexOf('did not receive a token') !== -1) {
                    errorMsg = "Token Invalid : Access Denied"
                } else if (info.indexOf('invalid') !== -1) {
                    errorMsg = "Token Invalid : Access Denied"
                }
            }
            // below line is part of stacktrace - authentication-middleware.js:252:47
            return res.status(401).json({
                "Result": "False",
                "userMessage": errorMsg
            });
        } else {
            return next();
        }
    })(req, res, next);
}

module.exports = {
    initializeAuthentication: _initializeAuthentication,
    ensureAuthentication: _ensureAuthentication
}

currentUserUtil.js
var request = require("request");

// Returns the user object based on Azure AD OID (object ID)
function _getCurrentUserByOid(oid, token, callback) {
    var config_par = {
        "method": "GET",
        "headers": {
            "authorization": token
        },
        "url": `https://example.com/api/user/oid/${oid}`,
    }
    request(config_par, (error, response, body) => {
        if (error) {
            callback({ "Status": false });
        }
        try {
            callback(JSON.parse(body));
        } catch (ex) {
            // below line is part of stacktrace - currentUserUtil.js:23:7
            callback({ "Status": false });
        }
    });
}

module.exports = {
    getCurrentUserByOid: _getCurrentUserByOid
}


text:
Q: EclipseLink JPA secondary server hoping someone may tell me if there is a way to provide automatic redundancy using JPA. We're currently using EclipseLink but can change should another provider have a suitable solution) and we need to ensure that we switch to our backup database should our primary database become unavailable (since its not located in the same building as our application). thanks for your input.

A: The easiest way is to change the jdbc connection url as explained in the mysql documentation. As an example
jdbc:mysql://master.server.com:3306,backup.server.com:3306/dbname

In this scenario, if maser.server.com fails, the driver will redirect the commands to backup.server.com. I strongly suggest you to read the whole documentation, as there are a lot of properties which change the failover behaviour, in particular the section High Availability and Clustering.


text:
Q: jQuery Mobile won't load OpenLayers Map I'm starting with jQueryMobile and wanted to display a map using OpenLayers. However I'm having a weird issue. Here is the almost working code. Sorry I couldn't make a fiddle, however you can test it easily with copy/paste on notepad or whatever.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

This code doesn't show the map.
Now if you take off the following line :

You can see that the map is showing.
Any idea on how can I solve this ? because I think it can be solved easily but can't see how.
Thank you.

A: I knew it was stupid, if it can interest someone , the css should be like :
#pageone, #pageone .ui-content, #basicMap {
   width: 100%;
   height: 100%;
   display : block;
}

And call JS :
$(document).ready(init());

Don't know however why this works.


text:
Q: Combining boost range algorithms, eg. boost::copy and boost::remove_if I am trying to write a complex list of algorithms that must be applied to a range sequence.  I would like to nest many algorithms using a syntax similar to the following code.  My only problem is that it won't compile.  Any suggestions?
bool pred(double x);

double d[]={1,2,3,4};
std::vector<double> x(d,d+4);
std::vector<double> y;
boost::copy( x, std::back_inserter(y) );   // OK
boost::copy( boost::remove_if(x,&pred), std::back_inserter(y) ); // ERROR

For this syntax to work, I don't want to have to specify the template parameters for the inner algorithm.  This could be simplified with the use of auto keyword, but I need to keep the code backwards compatible.
This is a fragment of the error messages:
1>c:\dev\thirdparty\boost\boost-1.48.0-windows-vc90-x32-p64925\installed\include\boost-1_48\boost/range/iterator.hpp(63) : error C2039: 'type' : is not a member of 'boost::mpl::eval_if_c<C,F1,F2>'
1>        with
1>        [
1>            C=true,
1>            F1=boost::range_const_iterator<std::_Vector_iterator<double,std::allocator<double>>>,
1>            F2=boost::range_mutable_iterator<const std::_Vector_iterator<double,std::allocator<double>>>
1>        ]

1>        c:\dev\thirdparty\boost\boost-1.48.0-windows-vc90-x32-p64925\installed\include\boost-1_48\boost/range/concepts.hpp(256) : see reference to class template instantiation 'boost::range_iterator<C>' being compiled
1>        with
1>        [
1>            C=const std::_Vector_iterator<double,std::allocator<double>>
1>        ]
1>        c:\dev\thirdparty\boost\boost-1.48.0-windows-vc90-x32-p64925\installed\include\boost-1_48\boost/concept/detail/has_constraints.hpp(42) : see reference to class template instantiation 'boost::SinglePassRangeConcept<T>' being compiled
1>        with
1>        [
1>            T=const std::_Vector_iterator<double,std::allocator<double>>
1>        ]
1>        c:\dev\thirdparty\boost\boost-1.48.0-windows-vc90-x32-p64925\installed\include\boost-1_48\boost/concept/detail/msvc.hpp(53) : see reference to class template instantiation 'boost::concepts::not_satisfied<Model>' being compiled
1>        with
1>        [
1>            Model=boost::SinglePassRangeConcept<const std::_Vector_iterator<double,std::allocator<double>>>
1>        ]
1>        c:\dev\thirdparty\boost\boost-1.48.0-windows-vc90-x32-p64925\installed\include\boost-1_48\boost/range/algorithm/copy.hpp(33) : see reference to class template instantiation 'boost::concepts::require<Model>' being compiled
1>        with
1>        [
1>            Model=boost::SinglePassRangeConcept<const std::_Vector_iterator<double,std::allocator<double>>>
1>        ]
1>        ..\..\..\..\..\source\yotta\libraries\snl\unittests\StackOverflow.cpp(7) : see reference to function template instantiation 'OutputIterator boost::range::copy<std::_Vector_iterator<_Ty,_Alloc>,std::back_insert_iterator<_Container>>(const SinglePassRange &,OutputIterator)' being compiled
1>        with
....

A: The problem is that remove_if (and all algorithms, for that matter) returns a single iterator, not a range, if you don't specify a range type that should be returned (which you don't seem to want).
A simple fix would be to use the adaptor filtered:
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <iterator>
#include <vector>
#include <iostream>

bool pred(double x){
  return x > 2.0;
}

int main(){

  double d[]={1,2,3,4};
  std::vector<double> x(d,d+4);
  std::vector<double> y;
  boost::copy( x | boost::adaptors::filtered(pred), std::back_inserter(y) );
  boost::copy( y, std::ostream_iterator<double>(std::cout, " ") );
}

Output: 3 4


text:
Q: Why does `allowJS` cause an unwanted `src` subdirectory in my compiled output? I'm converting a legacy node/express codebase to TypeScript, following the Microsoft TypeScript starter as a starting reference.
In this reference output is compiled to dist, however when enabling allowJS in tsconfig.json, the output is emitted to dist/src - why is that?
Here is my tsconfig.json
{
"compilerOptions": {
  "module": "commonjs",
  "target": "es6",
  "noImplicitAny": false,
  "moduleResolution": "node",
  "sourceMap": true,
  "rootDir" : "./",
  "outDir": "dist",
  "baseUrl": ".",
  "allowJs": true,
  "paths": {
    "*": [
      "node_modules/*",
      "src/types/*"
    ]
  }
},
"include": [
  "src/**/*"
]

}

*

*I tried changing rootDir to ./src but it gives an error saying 'node_modules/someModule' is not in the src root.

*I tried moving tsconfig.json to src, according to a GitHub issue I saw, but no output was generated.

AllowJS
The output was mapping correctly under /dist until allowJS flag was turned on in tsconfig.json, after which output appeared in /dist/src

A: There are two things going on here:

*

*Typescript relies on rootDir to decide the directory structure of the output (see this comment from Typescript's bossman).

*Only code within the rootDir can be compiled/emitted by tsc.

*If you don't set rootDir explicitly, it defaults to ./ (relative to tsconfig)... unless you've included something outside of ./ that needs to be compiled/emitted by tsc, in which case it forces rootDir to automatically get set to the directory that contains all the source.

*The allowJS setting tells tsc to treat .js code as source and to also emit it to the outDir.

I suspect that when you enabled allowJS, there was .js code outside of src that tsc now had to emit to outDir, and so it automatically moved rootDir one level up. Since src is now a subdir of the rootDir, this gets mirrored within outDir.
See this answer for a solution that enables you to have src remain a rootDir and also include code from outside of it.

A: Sounds like your compiler (TSC) config file may be up a level from where you want the transpiler to begin the linking process. Can you try pushing it down a level and let us know what happens?
Hope this helps.


text:
Q: Visual Studio slowness, possible reason? Im struggling with extremely slow Visual Studio. I use it to build C++ projects mostly.
Everything could be super slow. Menu's loading, intelIsense tips, builds. I've just tested building simple solution in 1 file, and build took around 5 minutes. But! I found this article about Windows Performance Analyzer which I used to trace this solution build. Despite overall time taking around 5 minutes, WPA report build took only around 0.686 seconds, attaching screenshot:

apparently I press "rebuild" in VS and build itself started ~300 seconds later(timeline).
Currently I use VS2019. Same problem I observed on VS2017. I did removed all VS components and installed VS2019 and problem is not gone. All other programs run fine. No excessive CPU load(intell 6700k), no noticeable harddrive usage(windows and VS components are on m2 ssd, lightning fast), 32 gb ram and enough free space on system disk.
Only VS extension I installed myself is QT extension for VS2019. Which actions can I take next to find the problem?

A: Things to try:
devenv /safemode from a command line starts the IDE in safe-mode with all plugins disabled.
Visual Studio Installer and repair install
Disable graphics acceleration in Visual Studio (Tools|Options|General ... there are a few "rich client visual experience" related things)
Check paths on your computer. If other apps run fine but one does not, it could be that this app tries to access a network drive or website which is not available.
Run "procmon" and "procexp" (Process Monitor/Process Explorer from Sysinternals) and take a look at what's going on.
Try VS 2022.


text:
Q: How can I add users to my new gitosis project? As a fresh Git user, I tried to install git on a server following this guide: Hosting Git repositories, The Easy (and Secure) Way. For... like 3 days in a row.
Here was the problem:
I followed that guide exactly. But when I came to the 'Creating new repositories' section, I was blocked. I simply can't understand how can you add users to a project. I mean, okay, I need a SSH key. But for all users? Or just for admin? If is for all users, how can I add another user?
The second question is about the same 'chapter'. The example is like this:
[group myteam]
members = jdoe
writable = free_monkey

Ok, I can add a member, called jdoe. But what is that name? Where do I get that name? Is it my local cygwin user? Is it a Linux user? My cygwin user is some kind of email address. If that is the user, how can I add more users? I mean how can I find out what any other users are out there ?
So after few days of trying and trying and... trying, I kinda quit because I found a great virtual machine appliance from turnkey. But the problem was... I didn't know how to add projects! I searched on their site, I found a script that add projects (the script is giving me an error, btw, but it works) but I'm back to square one: how the hell I add more users? Because right now it is a public server, with full rights. It is not a big problem right now because I run it in a virtual machine and it's only local.
Maybe you ask me why I don't use that VM? Because I kinda want to put it online and give access to several persons. So I think to move it to my VPS. But because I didn't succeed to install in a VM, I sincerely doubt that I can install it in a VPS.
(Please don't suggest me to move on GitHub.)

A: A user in Gitosis is identified by the name of the pubkey file, i.e. if you had a pubkey file called foo.pub, then the user is called foo -- and, naturally, all the users you have are simply the SSH pubkeys you have on your Gitosis installation.
All users must have their SSH pubkey on the server, as all of them use the git user on the server to push their changes to the repositories they are allowed access to.


text:
Q: XMLHttpRequest mimicking script works on one web page, but not another I am using Python.org version 2.7 64 bit on Windows 8 64 bit. I have some code that iterates through a series of XHR requests to pull down FA Cup data from a website. Each value in the dictionary 'year_tournament_map' represents the ID code for each season's FA Cup, which are parsed in turn.
The code for this is below:
import json
import requests
import time

from datetime import date, timedelta

year_tournament_map = {
    2013: 8273,
    2012: 6978,
    2011: 5861,
    2010: 4940,
    2009: 3419,
    2008: 2689,
    2007: 2175,
    2006: 1645,
    2005: 1291,
    2004: 903,
    2003: 579,
    2002: 421,
    2001: 243,
    2000: 114,
    1999: 26,
}

years = sorted(year_tournament_map.keys())
url = 'http://www.whoscored.com/tournamentsfeed/%s/Fixtures/'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}

for year in years:
    start_date = date(year, 11, 1)
    end_date = date(year + 1, 5, 31)
    delta = end_date - start_date

    for days  in range(delta.days + 1):
        time.sleep(0.5)

        test_date = start_date + timedelta(days=days)

        params = {'d': str(test_date).replace('-', ''), 'isAggregate': 'false'}
        response = requests.get(url % year_tournament_map[year], params=params, headers=headers)

        try:
            json_data = response.content.replace("'", '"').replace(',,', ',null,')
            fixtures = json.loads(json_data)

        except ValueError:
            print "Error!!!"

        else:

            if fixtures:  # If there are fixtures
                print ",\n".join([", ".join(str(x) for x in fixture) for fixture in fixtures])  # `fixtures` is a nested list

            else:
               print "No Fixtures Today: %s" %  test_date

This works great, so I decided to experiment using this method on other tournaments, for example the English Premier League. I replaced the above dictionary with the following one, which has the ID codes for the Premier League instead of the FA Cup:
year_tournament_map = {
 1999: 2,
 2000: 85,
 2001: 191,
 2002: 299,
 2003: 429,
 2004: 594,
 2005: 836,
 2006: 667,
 2007: 1256,
 2008: 1539,
 2009: 1849,
 2010: 2458,
 2011: 2935,
 2012: 3389,
 2013: 3853,
 2014: 4311, }

When run however, this does not work as anticipated. The second season produces international fixtures and the fourth some fixtures from either the Finnish league or cup. It then falls over with an error saying I am trying to print to screen none ASCII/Unicode characters.
I was advised that the item "url = 'http://www.whoscored.com/tournamentsfeed/%s/Fixtures/'" can be observed using my browser development tools, but I was unable to locate it.
What I would like to know is:
1) Am I using the correct URL for the XHR on the Premier League data
2) Where in the sourcve code reference to the above URL can be found
3) Why my code is returning irrelevant/incorrect data in relation to what is on the page that I am browsing here.
Thanks

A: This was resolved in the end once I got to grips with the Google Chrome Development Tools a little more. On the 'Console' tab of the Dev tools, if you right click you get an option to turn on XMLHTTPRequests. Once this is done, when you change the dates on the calendar you see the XHR submission to 'tournamentsdfeed'. For some reason on the Premier League data the numeric season identifiers are different than those displayed in the address bar at the top of the page. With the FA Cup data this is not the case.
The dictionary used for this should read:
year_tournament_map = {
 1999: 2,
 2000: 89,
 2001: 213,
 2002: 359,
 2003: 542,
 2004: 803,
 2005: 1208,
 2006: 937,
 2007: 2025,
 2008: 2539,
 2009: 3115,
 2010: 4345,
 2011: 5476,
 2012: 6531,
 2013: 7794,
 2014: 9155, }

Thanks


text:
Q: Parent terms missing in breadcrumb path I have a site collection named "Faculty" and a subsite named "General".
For "General", I have multiple pages in that subsite. The content of the quick launch navigation for the subsite is based on a term set and can show up to 3 levels.
This is the structure of that term set:
Page 1
  Page 1-1
  Page 1-2
    Page 1-2-1
Page 2
  Page 2-1

When I click on "Page 1-2-1", it will have the following url in the browser:
http://Faculty01:81/General/SitePages/Page%201-2-1.aspx
And it will show up like this in the breadcrumb trail:
Faculty > General > Page 1-2-1
However, I want it to show up like this:
Faculty > General > Page 1 > Page 1-2 > Page 1-2-1
Could someone help me to achieve this?
Help and/or suggestions are appreciated!

(Notes:
Publishing features have been enabled and I'm working with SharePoint Server 2013. I use SharePoint Designer 2013 to make changes in the master page.)

A: Solved it by setting the navigation to term driven navigation, this however created a new problem with the quick launch not showing the parent terms.
New solution! Please check the answer to this question.


text:
Q: Limit the number of results in an entity's one-to-many relationship in core data I have the following object graph in core data.

The Account entity has a one-to-many relationship with Transaction. It's specified as a ordered set.
I'm using NSFetchedResultsController to display a list of accounts with its transaction records in a grouped tableview. When I fetch an entity, I want to fetch only the last 10 transactions.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Account")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.shared.persistentContainer.viewContext, sectionNameKeyPath: "name", cacheName: nil)
resultsController?.delegate = self

do {
    try resultsController?.performFetch()
} catch {
    print("Failed to create NSFetchedResultsController: \(error.localizedDescription)")
}

Since the NSFetchRequest is for fetching Account objects, it's fetchLimit cannot be used to limit the transactions.
How do I limit the number of objects in a relationship?


text:
Q: How to use Behaviors.canonicalize in Akka I am doing an exercise in Reactive Programming course which requires students to decorate an Typed Actor Behavior to support stash unhandled message. This is the program I wrote so far.
package protocols

import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl._

import scala.reflect.ClassTag

object SelectiveReceive {
  def apply[T: ClassTag](bufferCapacity: Int, initialBehavior: Behavior[T]): Behavior[T] =
    Behaviors.withStash(bufferCapacity) { buffer =>
      Behaviors.setup[T] { ctx =>
        intercept(bufferCapacity, buffer, initialBehavior)
      }
    }

  /**
   * @return A behavior that interprets the incoming messages with the supplied `started`
   *         behavior to compute the next behavior. If the message has been unhandled, it
   *         is stashed in the `buffer`. If the message has been handled, the previously
   *         stashed messages are also sent to the next behavior.
   *
   * @param bufferSize Capacity of the StashBuffer
   * @param buffer     Buffer to stash unhandled messages to
   * @param started    Behavior to decorate. Must be a valid "initial" behavior.
   * @tparam T         Type of messages
   *
   * Hints: Use [[Behavior.interpretMessage]] to compute the next behavior.
   *        Use [[Behavior.isUnhandled]] to know if the message was unhandled by the behavior.
   *        Use [[Behavior.canonicalize]] to make the next behavior applicable to the
   *        `unstashAll` operation of the `StashBuffer` (otherwise, an
   *        `IllegalArgumentException` will be thrown by the actor system).
   */
  private def intercept[T: ClassTag](bufferSize: Int, buffer: StashBuffer[T], started: Behavior[T]): Behavior[T] =
    Behaviors.receive { case (ctx, message) =>
      // If the next behavior does not handle the incoming `message`, stash the `message` and
      // return an unchanged behavior. Otherwise, return a behavior resulting from
      // "unstash-ing" all the stashed messages to the next behavior wrapped in an `SelectiveReceive`
      // interceptor.
      val nextBehavior = Behavior.interpretMessage(started, ctx, message)
      if (Behavior.isUnhandled(nextBehavior)) {
        if (buffer.size == bufferSize) {
          throw new StashOverflowException("stash overflow")
        } else {
          buffer.stash(message)
          Behaviors.same
        }
      } else {
        //SelectiveReceive(bufferSize, buffer.unstashAll(Behavior.canonicalize(nextBehavior, started, ctx)))
        val current = intercept(bufferSize, buffer, started)
        val next = SelectiveReceive(bufferSize, nextBehavior)
        val canonicalizeNextBehavior = Behavior.canonicalize(next, current, ctx)
        SelectiveReceive(bufferSize, buffer.unstashAll(canonicalizeNextBehavior))
      }
    }

}

In the hint they said to use canonicalize method to avoid an exception But I have try multiple way to use this funcion in the code and cannot find a way to avoid that. So I want to ask that what is the use case of canonnicalize method of a Behavior? And how to use this method in the above code.

A: This implementation seems to work.
object SelectiveReceive {
  def apply[T: ClassTag](bufferCapacity: Int, initialBehavior: Behavior[T]): Behavior[T] ={
    Behaviors.withStash[T](bufferCapacity){ buffer =>
      intercept(bufferCapacity, buffer, Behavior.validateAsInitial(initialBehavior))
    }
  }

private def intercept[T: ClassTag](bufferSize: Int, buffer: StashBuffer[T], started: Behavior[T]): Behavior[T] =
  Behaviors.receive { case (ctx, message) =>
    val nextBehavior = Behavior.interpretMessage(started, ctx, message)
    if (Behavior.isUnhandled(nextBehavior)) {
      buffer.stash(message)
      Behaviors.same
    } else {
      val nextBehaviorCanonicalized = Behavior.canonicalize(nextBehavior, started, ctx)
      buffer.unstashAll(SelectiveReceive(bufferSize, nextBehaviorCanonicalized))
    }
  }

To be honest, I got it working mainly through trial-and-error having found the hints in the homework poorly worded and the Akka documentation (particularly around canonicalize too light). Nonetheless I'll try to talk through my understanding - and hopefully someone can correct me if I'm wrong.
Starting by taking the StashBufferDemo.scala example we have
val initial = Behaviors.withStash[String](100) { buffer =>
        Behaviors.receiveMessage {
            case "first" =>
                buffer.unstashAll(running)
            case other =>
                buffer.stash(other)
                Behaviors.same
        }
    }

val running = Behaviors.receiveMessage[String] { msg =>
        println(s"Hello $msg!")
        if (msg == "stop") Behaviors.stopped else Behaviors.same
    }

The key motivation for canonicalize is so that the apply method of SelectiveReceive can pass the validateAsInitial method as mentioned in the hints (your implementation needs to add this). The reason why we didn't need canonicalize in the StashBufferDemo.scala example is that we just had running which is just a Behaviors.receiveMessage whereas in SelectiveReceive.scala we have an initialisation of a buffer which cannot start with an initialBehavior that is Same (or Unhandled - but it shouldn't be this because we only initialize a new SelectiveReceive if Behavior.isUnhandled is false). My understanding of canonicalize is it is just a way to figure out, if you have a Behavior.same with what the Behavior actually is. We can see this in the source code where we have https://github.com/akka/akka/blob/master/akka-actor-typed/src/main/scala/akka/actor/typed/Behavior.scala
@tailrec
  def canonicalize[T](behavior: Behavior[T], current: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] =
    (behavior._tag: @switch) match {
      case BehaviorTags.SameBehavior      => current
      case BehaviorTags.UnhandledBehavior => current
      case BehaviorTags.DeferredBehavior =>
        val deferred = behavior.asInstanceOf[DeferredBehavior[T]]
        canonicalize(deferred(ctx), deferred, ctx)
      case _ => behavior
    }

which just simply replaces Same with current (i.e. the previous Behavior).
So then re: buffer.unstashAll we want to unstash all the messages in the buffer which is basically just a tail recursive way to interpretOne message at a time, generating the output Behavior from that message which becomes an input for the next and so on (see unstash and interpretOne https://github.com/akka/akka/blob/master/akka-actor-typed/src/main/scala/akka/actor/typed/internal/StashBufferImpl.scala) to our new SelectiveReceive. This however, needs to be initialized with the canonicalized nextBehavior just in case nextBehavior is Behavior.same
You approach I think gets the error as you try to canonicalize for the unstashAll method (which I think does not care about Behaviors.same) and not for the SelectiveReceive method which does


text:
Q: how to enable rotation only on video I've been looking for the past days a solution to enable rotation ONLY when MPMoviePlayerViewController is triggered, without any luck.
I tried to enable the app to all rotations, and disabling it at each view, but it didn't work either.
does any one have an idea?

A: *

*In target settings, enable all orientations

*(optional, UIViewController default is portrait only) In all the other view controllers, do the following:
// Deprecated in iOS 6, but still needed for earlier versions of iOS:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// For iOS 6 and up
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

*In the one view controller that should rotate, do the following:
// Deprecated in iOS 6, but still needed for earlier versions of iOS:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

// For iOS 6 and up
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

This is assuming the rotating view controller will not be inside the same container view controller (such as UINavigationController or UITabBarController) as the non-rotating view controllers.

A: Create a new ViewController for the player Full screen and add:
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

to your code.
Make sure you present the ViewController.
(supporting iOS 6 and above)


text:
Q: the RecyclerView I am injecting does not appear? Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:orientation="horizontal">

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dividerHeight="10dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:showIn="@layout/content_main">

        <android.support.v4.widget.DrawerLayout

            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/DrawerLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:elevation="7dp">

            <!-- Framelayout to display Fragments -->
            <FrameLayout
                android:id="@+id/frame_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <include
                    android:id="@+id/tool_bar"
                    layout="@layout/tool_bar"></include>
            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/RecyclerView"
                android:layout_width="320dp"
                android:layout_height="match_parent"
                android:layout_gravity="left"

                android:background="#ffffff"
                android:scrollbars="vertical">

            </android.support.v7.widget.RecyclerView>

        </android.support.v4.widget.DrawerLayout>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/threadRecyclerView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scrollbars="vertical" />

    </RelativeLayout>
</LinearLayout>

The main reason I did this design was to try to display the
<android.support.v7.widget.RecyclerView
                android:id="@+id/threadRecyclerView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scrollbars="vertical" />

properly. However, when it is not being displayed at all. Before adding the two relativelayouts, I have one relative layout and the recyclerview did display, but it match_parent for every item of the list and was not able to fix it. How can I display my view properly?

A: The problem probably has to do with the layout_height="wrap_content" on your RecyclerView. You need to use setAutoMeasureEnabled(true) for wrap_content to work properly with a RecyclerView.
Here's an example:
RecyclerView threadRecyclerView = (RecyclerView)findViewById(R.id.threadRecyclerView);
threadRecyclerView.getLayoutManager().setAutoMeasureEnabled(true);

And your your XML should look something like this:
<android.support.v7.widget.RecyclerView
    android:id="@+id/threadRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    app:layoutManager="LinearLayoutManager"/>

Hope that helps. :)
Note that setAutoMeasureEnabled only works properly for Android Support Library +23.2


text:
Q: How to make stages with rounded corners or dropshadows? I am just learning JavaFX, and I have found that a few years ago, some learned how to make nice (modal) stages with these styles.
JavaFX Modal Confirm Dialog Box Example: https://gist.github.com/jewelsea/1887631/155d5e052b6ec7d0eaa6f825713f98f8e542152e
I recreated this OK, but some of the code is deprecated (builders).
So I wanted to ask if I can make a stage pop up that has rounded corners (or not), and maybe even dropshadows, using the currently supported API?  My application needs many popup stages, so I want to establish a nice style.

A: I'll post the answer here for anyone who stumbles across the old examples as I did, using the CSS from the example.  I set the scene fill to transparent in Java, and not via CSS (which I do not know how to do, but that is fine).
       // initialize the stage
    primaryStage.setTitle("Modal Confirm Example");
    final WebView webView = new WebView(); webView.getEngine().load("http://docs.oracle.com/javafx/");
    primaryStage.setScene(new Scene(webView));
    primaryStage.show();

    // initialize the confirmation dialog
    final Stage util = new Stage(StageStyle.TRANSPARENT);
    util.initModality(Modality.APPLICATION_MODAL);
    util.initOwner(primaryStage);

    HBox hbox = new HBox();
    Pane pane = new Pane(hbox);
    Scene scene = new Scene(pane);
    Label label = new Label("Will you like this page?");
    Button yesButton = new Button("Yes");
    Button noButton = new Button("No");
    hbox.getChildren().addAll(label, yesButton, noButton);

    yesButton.setOnAction(ae -> {
        System.out.println("Liked: " + webView.getEngine().getTitle());
        primaryStage.getScene().getRoot().setEffect(null);
        util.close();
    });
    noButton.setOnAction(ae -> {
        System.out.println("Disliked: " + webView.getEngine().getTitle());
        primaryStage.getScene().getRoot().setEffect(null);
        util.close();
    });

    scene.setFill(Color.TRANSPARENT);
    scene.getStylesheets().add(Machine.class.getResource("modal-dialog.css").toExternalForm());
    pane.getStyleClass().add("modal-dialog-glass");
    hbox.getStyleClass().add("modal-dialog-content");

    util.setScene(scene);

    // show the confirmation dialog each time a new page is loaded.
    webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
      @Override public void changed(ObservableValue<? extends Worker.State> observableValue, Worker.State state, Worker.State newState) {
        if (newState.equals(Worker.State.SUCCEEDED)) {
          primaryStage.getScene().getRoot().setEffect(new BoxBlur());
          util.show();
          util.toFront();
        }
      }
    });

And this is from the example linked in the question... (plus a nonfunctional root class).
.root {
    -fx-background-color: transparent;
}

.modal-dialog-glass {
  -fx-effect: dropshadow(three-pass-box, derive(cadetblue, -20%), 10, 0, 4, 4);
  -fx-background-color: derive(cadetblue, -20%);
  -fx-background-insets: 12;
  -fx-background-radius: 6;
}

.modal-dialog-content {
  -fx-padding: 20;
  -fx-spacing: 10;
  -fx-alignment: center;
  -fx-font-size: 20;
  -fx-background-color: linear-gradient(to bottom, derive(cadetblue, 20%), cadetblue);
  -fx-border-color: derive(cadetblue, -20%);
  -fx-border-width: 5;
  -fx-background-insets: 12;
  -fx-border-insets: 10;
  -fx-border-radius: 6;
  -fx-background-radius: 6;
}

A: I know I am a couple years late to this conversation, but I think it might be beneficial to share the workaround I found for the sake of whoever comes across this issue.
I managed to achieve the same by adding the following lines of code to my program:
Rectangle rect = new Rectangle(500,500);
rect.setArcHeight(60.0);
rect.setArcWidth(60.0);
primaryStage.initStyle(StageStyle.TRANSPARENT);
scene.setFill(Color.TRANSPARENT);
root.setClip(rect);

Source: https://apilevel.wordpress.com/2012/10/11/java-fx-stage-with-rounded-corners-with-background-image/


text:
Q: Provide default bookmark text for mobile devices We can easily provide custom icons for bookmarks that will be used on mobile devices in HTML:
<link rel="apple-touch-icon" href="path-to-image/image.png">
<link rel="manifest" href="/manifest.json">
<!-- manifest.json -->
{
    "manifest_version": 2,
    "name": "Full App Name",
    "version": "38",
    "default_locale": "en",
    "description": "App description",
    "short_name": "Short App Name",
    "icons": [
        {
            "src": "path-to-image/image.png",
            "sizes": "192x192",
            "type": "image/png",
            "density": 4.0
        }
    ],
    "display": "standalone",
    "orientation": "portrait"
}

However, this will only change the bookmark icon and not the text. The default text will be taken from the page's title tag. This is a problem, because generally title tags are highly optimized for search engines and are not good for bookmarks used by humans.
Is there a way to change default text for bookmarks (at least on mobile devices)?


text:
Q: How to get this menu component in java? Is there a menu component like this in java? And how do I use it?
(this is a screenshot of eclipse in the android layout development interface)

(source: vikingindustries.co.za)

A: It looks like an ExpandBar, not really menu related but more an expandable composite.  See http://www.eclipse.org/swt/snippets/#expandbar for an example creating one.

A: You can easily build this using a ListView and customize the list items to look that way.


text:
Q: No me aparece error pero no se me ejecuta el código (JFrame) Estoy estudiando y haciendo una prueba con Java. Técnicamente debería salirme una ventanita con un Hola Mundo (y el resto del texto que he puesto) pero no me sale nada.
El IDE no me da error y no veo el fallo por ningún sitio, ni sé que me falta.
¿Alguna sugerencia? El código es el siguiente:
import javax.swing.JFrame;
import javax.swing.JLabel;
import sun.applet.Main;

/**
 *
 * @author
 */
public class main extends JFrame {

    public main() {
        JLabel lblSaludo = new JLabel("Hola Mundo. Creando mi primer ejemplo");
        add(lblSaludo);
        this.setSize(400,200);
        this.setTitle("JFrame");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        Main main = new Main();
    }
}

Muchas gracias, un saludo.

A: En primer lugar estas creando una instancia de una clase diferente a la que creaste, ya que en el método main tienes :
Main main = new Main();

Pero tu clase se llama main, sin mayúsculas por lo mismo debería ser
main ventana = new main();

Recuerda que Java es bastante exigente en cuanto a las mayúsculas y minúsculas.


text:
Q: Group traffic shaping with traffic control? I'm trying to limit the output bandwidth generated by an application with linux tc. This application sends me the source port of the request that I use has a filter to limit each user at a given downloadspeed. I feel that my setup could be managed way better if I had a better knowledge of linux tc.
At the application level users are categorized as members of a group, each group have a limited bandwidth.
Example :
Members of group A : 512kbit/s
Members of group B : 1Mbit/s
Members of group C : 2Mbit/s

When a user connects to the application, it retrieves the source port to the origin of the request from the user and sends me the source port and the bandwidth at which the user must be limited depending on group to which it belongs. With these informations I must add the appropriate rules so that the user (the source port in reality) is limited to the right bandwidth.
If the user that connect isn't a member of any group it should be limited at a default bandwidth speed.
I'm actually managing this by using a self made daemon that add or remove rules from when it receive a request from the application. With my little knowledge of tc I'm not able to limit other users (ones that aren't in a group, all others in fact) at a default speed and my configuration seems awful to me.
Here is the base of my tc qdisc and classes :
tc qdisc add dev eth0 root handle 1: htb
tc class add dev eth0 parent 1: classid 1:1 htb rate 100mbps ceil 125mbps

To classify a user at a given speed I have to add one subclass and then associate one filter to it :
# a member of group A
tc class add dev eth0 parent 1:1 classid 1:11 htb rate 512kbps ceil 512kbps
# tts associated filter to match his source port
tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip sport 50001 flowid 1:11

# a member of group A again
tc class add dev eth0 parent 1:1 classid 1:12 htb rate 512kbps ceil 512kbps
# tts associated filter to match his source port
tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip sport 61524 flowid 1:12

# a member of group B again
tc class add dev eth0 parent 1:1 classid 1:13 htb rate 1000kbps ceil 1000kbps
# tts associated filter to match his source port
tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip sport 57200 flowid 1:13

I already know that a source port could be the same if its coming from a different IP address the thing is the application is behind a proxy so I don't have to manage any IP address in that situation.
I would like to know how to manage the fact that for all other users (request/source port, whatever you name it) could be limited at a given speed each. I mean that each connection should be able to use at max 100kbit/s for example, not a shared 100kbit/s.
I also would like to know if there is a way to simplify my rules. I don't know if it is possible to use only one class per group and associate multiple filters to the same class so each users could be handled by one class and not one class per user.
I appreciate any advice, thanks.


text:
Q: after picking the image how save images locally in ios
when i capture the image i need to save images one by one in table view like below image .is need use nsuser defaults or use core data?
and after picking the image how to add to Array

A: You can save image in NSUserDefaults as follows,
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    if(!self.phto_arr_)
   {
     self.phto_arr_ = [[NSMutableArray alloc] init];
   }
[self.phto_arr_ addObject: chosenImage];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.phto_arr_];
[[NSUserDefaults standardUserDefaults] setObject: encodedObject forKey:@"images"];
[[NSUserDefaults standardUserDefaults] synchronize];
[picker dismissViewControllerAnimated:YES completion:NULL];
}

A: Yes, you can save the images in the document directory and keep the image file names in an array after that retrieve that images from doc. dir. just like this
// For error information
    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YOUR_IMG_FOLDER"];

    if (![fileMgr fileExistsAtPath:dataPath])
        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

    //Get the current date and time and set as image name
    NSDate *now = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss";
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSString *gmtTime = [dateFormatter stringFromDate:now];
    NSLog(@"The Current Time is :%@", gmtTime);

    NSData *imageData = UIImageJPEGRepresentation(_postImage, 0.5); // _postImage is your image file and you can use JPEG representation or PNG as your wish
    int imgSize = imageData.length;
    ////NSLog(@"SIZE OF IMAGE: %.2f Kb", (float)imgSize/1024);

    NSString *imgfileName = [NSString stringWithFormat:@"%@%@", gmtTime, @".jpg"];
    // File we want to create in the documents directory
     NSString *imgfilePath= [dataPath stringByAppendingPathComponent:imgfileName];
    // Write the file
    [imageData writeToFile:imgfilePath atomically:YES];

     **// Keep your Image file name into an mutable array here OR you can saved the array in a UserDefaults**

Then retrieve from doc. dir. from iterate the array.
//Get image file from sand box using file name and file path
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"YOUR_IMG_FOLDER"];
stringPath  = [stringPath stringByAppendingPathComponent:imgFile]; // imgFile to get from your array, where you saved those image file names
UIImage *image = [UIImage imageWithContentsOfFile:stringPath];

Thank you...happy coding.

A: Try below this code:
suppose you want to image name also display use this code,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  chosenImage = info[UIImagePickerControllerOriginalImage];
  chosenImage = [UIImage unrotateImage:chosenImage];
  addGalleryImageview.image = chosenImage;
  isCameraOn = YES;
  NSString* fileName = [NSString stringWithFormat:@"gallery%@",[Utils getDateString]];
  imageNamelbl.text = fileName;
  [picker dismissViewControllerAnimated:YES completion:NULL];}

- (UIImage*)unrotateImage:(UIImage*)image{
   CGSize size = image.size;
   UIGraphicsBeginImageContext(size);
   [image drawInRect:CGRectMake(0,0,size.width ,size.height)];
   UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return newImage;}


text:
Q: Переход между активностями Доброго времени суток. В приложении имеется две активности и между ними осуществляется переход в обоих направлениях. В обеих активностях используется один и тот же файл разметки activity_main.xml. Создаю так:
Первая активити (MainActivity.java):
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Intent toOfflineMode = new Intent(MainActivity.this, OfflineActivity.class);
..//

И вторая активити (OfflineActivity.java):
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Intent toOnlineMode = new Intent(OfflineActivity.this, MainActivity.class);
..//

И на соответствующие кнопки вешаю startActivity(toOfflineMode); и startActivity(toOnlineMode); соответственно. Так вот получается, что если перейти во вторую, а затем обратно в первую, те данные, которые были отображены в первой теряются. Складывается ощущение, что при каждом нажатии кнопки постоянно создается новый экземпляр активити(на экране новое окно выбегает справа налево). Если же нажать кнопку "назад" из второго активити первая возвращается(слева направо на экране) и данные на ней все остаются как положено. Подскажите пожалуйста, как осуществить переход между двумя этими активностями по кнопке без потери данных в обоих? Спасибо.

A: Раз разметка одинаковая для обоих активити, то проще сделать все в одной активити. А для данных создать отдельный класс, и хранить данные в объектах этого класса. По кнопке уже подгружать данные в разметку из соответствующего объекта.

A: Вы можете воспользоваться методом onSaveInstanceState().


text:
Q: Word files downloaded using AWS S3 pre-signed url opens in "Protected view" mode I have a files (docx) in the s3 bucket.
I am downloading it using the S3 pre-signed url. It is getting downloaded.
But when i download and open the file it is getting opened in "Protected View" mode.
Can anyone help me to resolve this issue or give me any hint what can I do to open this docx file in normal read only mode?


text:
Q: Provision a GCP VM instance with Static IP via Terraform I have edited my main.tf and variable.tf file as suggested by @Claire Bellivier but still getting the same error, please have a look.
Main.tf:
# Path to the authentification to GCP json file
provider "google" {
 credentials = "${file("${var.path_gcp_auth_json_file}")}"
 version     = "~> 2.2"

}

resource =  "google_compute_address" "test-static-ip-address" {
 count  = "${var.gcp_ip_count}"
 name   = "${var.gcp_project_id}-gke-ip-${count.index}"
 region = "${var.region}"
 }

resource "google_compute_instance" "tests" {
 name         = "project-tests"
 project      = "xyz"
 machine_type = "f1-micro"
 zone         = "us-west1-a"

 tags = ["gcp"]

 boot_disk {
 initialize_params {
  image = "ubuntu-os-cloud/ubuntu-1804-lts"
   }
 }

network_interface {
 network = "default"

  access_config {
   nat_ip = "${google_compute_address.test-static-ip-address.address}"

   }
 }

  metadata {
   sshKeys = "local:${file(var.ssh_public_key_filepath)}"
  }

}

resource "google_compute_firewall" "firewalls" {
 name    = "firewalls"
 project = "video-library-228319"
 network = "default"

 allow {
  protocol = "tcp"
  ports = ["80", "443"]
 }

  source_ranges = ["0.0.0.0/0"]
}

Variable.tf
# Path to the authentification to GCP json file
variable "path_gcp_auth_json_file" {
  description = "Path to the authentication JSON file"
 default = "account.json"
}

variable "ssh_public_key_filepath" {
 description = "Filepath to local ssh public key"
 type = "string"

 default = "local.pub"
}

variable "gcp_ip_count" {
 default = "1"
}

variable "gcp_project_id" {
  default = "xyz"
}

variable "region" {
 default ="us-west1-a"
}

Error: Unknown root level key: test-static-ip-address
Error: resource 'google_compute_instance.tests' config: unknown resource 'google_compute_address.test-static-ip-address' referenced in variable google_compute_address.test-static-ip-address.address
Please help

A: Could you copy paste this one and delete the second block?
resource "google_compute_address" "test-static-ip-address" {
  count  = "${var.gcp_ip_count}"
  name   = "${var.gcp_project_id}-gke-ip-${count.index}"
  region = "${var.region}"
}

As mentioned there is a = too many, so it cannot work.
The pattern is always for the main.tf file:
resource "<kind of GCP Resource>" "<the name of your resources> {
  <list of arguments you need>
  # ...
}

A little trick if you need help with the Terraform syntax, you can proceed some tests with those commands: terraform format to get the proper indentation, and terraform validate to make sure everything is right in your code.

A: First of all, you can try to configure the Google Cloud provider like that:
# Configure the Google Cloud provider
provider "google" {
  credentials = "${file("${var.path_gcp_auth_json_file}")}"
  version     = "~> 2.2"
}

With a variables.tf file
# Path to the authentification to GCP json file
variable "path_gcp_auth_json_file" {
  description = "Path to the authentication JSON file"
  default = "YOUR_PATH_TO_YOUR_JSON_KEY"
}

if you want to be quick and do not add you default values to a terraform.tfvars file.
Secondly, you missed a { in the end of the tests resource:
resource "google_compute_instance" "tests" {
  name         = "project-tests"
  project      = "video-library-228319"
  machine_type = "f1-micro"
  zone         = "us-west1-a"

  tags = ["gcp"]

  boot_disk {
    initialize_params {
      image = "ubuntu-os-cloud/ubuntu-1804-lts"
    }
  }

  network_interface {
    network = "default"

    access_config {
      nat_ip = "${google_compute_address.test-static-ip-address.address}"
    }
  }
}

And then, to generat IPs you need to properly declare the compute resource to Terraform:
# Generate IPs
resource "google_compute_address" "test-static-ip-address" {
  count  = "${var.gcp_ip_count}"
  name   = "${var.gcp_project_id}-gke-ip-${count.index}"
  region = "${var.region}"
}

Each "${var.[...] need to be refered to the variables.tf previously mentionned.
The count value depends on how many IPs you need. Hope it'll help.


text:
Q: Use of Classes and Objects as wrappers for reducing the number of imports in Javascript In my React project, I have a pretty good number of items with their respective actions:
/user/edit/:id
/users/search
....
/group/view/:id
/group/edit/:id
/groups/search/

when defining the Routes (I am using React Router) I find myself importing a lot of constants and almost the same React Components across the routes files of each item:
import {USER_VIEW_CONSTS,USER_EDIT_CONSTS} from '....'
import {ItemViewContainer} from '...'
import {ItemEditContainer} from '...'

<Route path={`${URL_USER}${URL_SEGMENT_VIEW}:id } render={props => <ItemViewContainer {...{...props, itemConsts:USER_VIEW_CONSTS}} />
<Route path={`${URL_USER}${URL_SEGMENT_EDIT}:id } render={props => <ItemEditContainer {...{...props, itemConsts:USER_EDIT_CONSTS}} />
.....
import {GROUP_VIEW_CONSTS,GROUP_EDIT_CONSTS} from '....'
import {ItemViewContainer} from '...'
import {ItemEditContainer} from '...'

<Route path={`${URL_GROUP}${URL_SEGMENT_VIEW}:id } render={props => <ItemViewContainer {...{...props, itemConsts:GROUP_VIEW_CONSTS}} />
<Route path={`${URL_GROUP}${URL_SEGMENT_EDIT}:id } render={props => <ItemEditContainer {...{...props, itemConsts:GROUP_EDIT_CONSTS}} />

I have just realised that may be I can take advantage of javascript Classes for wrapping the Constans ant the React.components I am using in each route file of each item (user,group...):
import CustomReactClassWithAllContainersAsMethods from '....'
import userConstsWrappedInObjectAsProps from ''

const CustomReactObjectWithAllContainerForEachRoute = new CustomReactClassWithAllContainersAsMethods(userConstsWrappedInObjectAsProps);

<Route path={`${userConstsWrappedInObjectAsProps.urlView}:id } render={CustomReactObjectWithAllContainerForEachRoute.viewItem} />
<Route path={`${userConstsWrappedInObjectAsProps.urlEdit}:id } render={CustomReactObjectWithAllContainerForEachRoute.editItem} />

There, my CustomReactClassWithAllContainersAsMethods and my userConstsWrappedInObjectAsProps:
class CustomReactClassWithAllContainersAsMethods {

constructor(itemProps){
this.itemProps = itemProps;
}

viewItem() => props =>  <ItemViewContainer {...{...props,itemConsts:this.itemProps}}
editItem() => props =>  <ItemEditContainer {...{...props,itemConsts:this.itemProps}}

}

So is not this second class approach cleaner and better? I have only made two imports and I can have the logic centralized. The reason why I have my doubts is that I have not found in the internet a single case of React.Components wrapped as methods in a custom javascript class... Is it because it is very expensive in term of resources?
The same applies in the case of the Constants, would not be better to import a single object with the constants as props?
I have not found any policies regarding this issues in the best practices suggestions I have come to read...
Thank you for your time and apologies for the length.


text:
Q: Count DIVs, Add Wrapper with jQuery I'm writing a web page that needs to display content in boxes, like this:
[ 1 ] [ 3 ] [ 5 ]
[ 2 ] [ 4 ] [ 6 ]

Because of varying screen sizes, sometimes the number of rows will vary. For example, a screen that allows for more row to be shown would be arranged like this:
[ 1 ] [ 4 ]
[ 2 ] [ 5 ]
[ 3 ] [ 6 ]

The problem I'm running in to is that when I just float the DIVs to the left, they show up like this:
[ 1 ] [ 2 ] [ 3 ]
[ 4 ] [ 5 ] [ 6 ]

My plan to fix this is to wrap each column in a div, and float that to the left. But because there can be a varying number of rows depending on screen size, I need to accomplish this with jQuery.
I've already counted the number of rows with jQuery, I just can't figure out how to wrap a certain number of divs in a wrapper. Here's my script so far:
var pageHeight = $("body").innerHeight() - 157; // 157 being the height of the page title
var rowCount = Math.floor(pageHeight / 295); // 295 being the height of each item
var itemCount = $("#itemWrapper").children(".item").length;each item
$("#itemWrapper").height(pageHeight);

So, if rowCount = 3, then I need to wrap the each set of three .items in

. And of course remember that there may be only two, or one .item left over.
This seems pretty simple, but I'm having trouble even finding where to begin. As I research this some more, if I figure anything out, I'll be sure to update my question.
UPDATE 1: Looks like I may be able to use the .wrap() function of jQuery. I just need to figure out how to use it on more than one DIV.
UPDATE 2: I found this bit of code, that looks promising, but I can't figure out how to make it change based on the number of rows:
for (var i = 0;i < itemCount;i+=3) {
    $(".item").filter(':eq('+i+'),:eq('+(i+1)+'),:eq('+(i+2)+')').wrapAll('
');
};

It seems like for each additional div, it needs to add anther :eq('+(i+1)+') with one number higher. Not sure how to write script that does that, but I'm still researching. If I just change the 3' torowCount` it doesn't properly close all the added divs.

A: You can use CSS3 column properties for browsers that support them.
Here's a column wrapping script that will work cross browser. I used a css rule for column class based on column count to set width in percentage
var colCount = 3,/* hard coded for demo, use your calcs for dynamic*/
    $items = $('.item'),
    items_per_col = Math.ceil($items.length / colCount),
    start = 0;

for (i = 0; i < colCount; i++) {
    var endSlice = start + items_per_col;
    $items.slice(start, endSlice).wrapAll('
');
    start += items_per_col;
}

DEMO: http://jsfiddle.net/MkGyu/1

A: I can't comment yet, so sorry for posting this as an answer.
You should really look into responsive web design using media queries. Here's an article to get you started.

A: if (jQuery and wantsColumns) {
   return [Masonry](http://masonry.desandro.com/demos/basic-multi-column.html);
}


text:
Q: Circuit heating I am using 14.8 Volts 21Ah Lithium ion battery to control a circuit.
The circuit consists of a controller, LM2596 buck converter (set to 5.5 Volts), 5v relay driver , 5v electromagnectic relays,  and DC Johnson geared motors ( 4  to 8 Johnson geared DC motors connected in parallel).
When I connect all together everything works fine for a few minutes but then after some time the complete circuit gets fully heated.
After sometime the circuit stops working.
If I remove the motors and try to check operation without load then the relay gets activated and works properly. But If I connect load a DC motor then the working of the circuit will be normal. If I connect many motors then gradually Relay, Circuit all components , buck converter everything gets heated up.
Any advice on possible causes of the overheating and ways to reduce it to an acceptable level would be appreciated.

A: The LM2596 is a 3A regulator. At max load it is 73% efficient, which is kind of low for a DC-DC, so it will be shedding 4W between the regulator and other losses. That's a tremendous amount of heat, so the regulator is going into thermal shutdown to protect itself.
What is the load for each motor? I could easily imagine that with a large number of them, likely you are exceeding what that regulator can do.
Consider breaking up your circuit to use multiple DC-DC converters for the multiple relays and motor sets.


text:
Q: How to execute flyway where in scripts & flyway services are stored in different repositories?
Since we have many applications & services that are going to leverage flyway, I have created 2 separate project repositories:
 - migration-service, To store migration scripts.
 - flyway-service, to execute the scripts.
The Problem:

All teams are going to check in migration scripts in the migration-service(GITHUB), & then using flyway-service API they can run the migrations.

How can I always execute flyway-service with this design?

Technology used: Java, Springboot, flyway.

Please help!


text:
Q: Discord JDA Emote in EmbedBuilder Im currently working on a discord bot and Im trying to display a custom server emote inside the embed message, it should appear in "insert emote_icon" but Im not able to get it done. Is it even possible and if yes, how?
if (member.hasPermission(Permission.ADMINISTRATOR)) {
            if (args.length == 2) {
                if (args[1].contains("test")) {
                    try {

                        Guild guild = tChannel.getGuild();
                        EmbedBuilder embedBuilder = new EmbedBuilder();

                        embedBuilder.setColor(Color.GRAY);
                        embedBuilder.setAuthor("~Jokers Rival | Rufus");
                        embedBuilder.setTitle("----= **Title** =----");
                        embedBuilder.setDescription("Test title");

                        embedBuilder.addField("test1", "<insert emote_icon>", true);

                        tChannel.sendMessage(embedBuilder.build()).queue();
                        return;

                    } catch (Exception e) {}
                }
            }
            return;
        }
``

A: You can put custom emotes in text components by using the correct message format. To get this format you can simply post the emote in a channel and put a backslash \ before it:

Then you can use that in your code:
embedBuilder.addField("test1", "<:vim:414776062380343296>", true);

The bot has to be in the guild where this emote is from and it must have access rights. Twitch subscriber emotes are only available to twitch subscribers etc.


text:
Q: How do I make separate columns from one column that contains null and multiple values? I have this file converted from PDF to CSV to train a model. three columns from the pdf file have merged into one in the csv e.g the ProductID, Commodity and country.
I was trying to separate these columns with the help of regular expression, but I am not quite sure how the columns will go.
This set of data is what I am dealing with:
                   country/commodity Unit        Quantity      Value
1     0011101 BREEDING BULLS (OXEN)   NO            NaN          75
2                             DUBAI  NaN            NaN          75
3  0011102 BREEDING BULLS (BUFFALO)   NO            248        1921
4                         SRI LUNKA  NaN            248        1921
5          0011103 BUFFALO,BREEDING   NO            NaN          90
6                         SRI LUNKA  NaN            NaN          90
7             0011104 COWS BREEDING   NO           1249   258921665
8                             AJMAN  NaN            NaN         NaN
9                            CYPRUS  NaN            NaN         NaN

I need this data to be in this format:
0    ProductID      Commodity           Country     Unit  Quantity    Value
1     0011101    BREEDING BULLS (OXEN)   DUBAI      NaN    NaN          75
3     0011102   BREEDING BULLS (BUFFALO) SRI LUNKA  NaN    248         1921
4     0011103   BUFFALO,BREEDING         SRI LUNKA  NaN    NaN          90
7     0011104   COWS BREEDING            AJMAN      NaN    NaN         NaN
8     0011104   COWS BREEDING            CYPRUS     NaN    NaN         NaN
9     0011104   COWS BREEDING            CHINA      NaN    590         3290

A: First we make your columns ProductID, Commodity, Country by substracting the information from the country/commodity column with:

*

*str.split

*str.extract

*Series.where

*Series.mask

*str.contains
Then we GroupBy on ProductID to get the information of the corresponding products together and we use named aggregation for this, which is new since pandas 0.25.0:
# Extract information from country/commodity
df['ProductID'] = df['country/commodity'].str.split(' ', 1).str[0].str.extract('(\d+)').ffill()
df['Commodity'] = df['country/commodity'].str.split('\d+').str[-1].where(df['Unit'].notna())
df['Country'] = df['country/commodity'].mask(df['country/commodity'].str.contains('\d+')).fillna('')

# Groupby ProductID to get information together
df_new = df.groupby(['ProductID']).agg(
    Commodity=('Commodity', 'first'),
    Country=('Country', ', '.join),
    Unit=('Unit', 'first'),
    Quantity=('Quantity', 'first'),
    Value=('Value', 'first')
).reset_index()

# Remove unnecessary comma's
df_new['Country'] = df_new['Country'].str.lstrip(', ')

Output
  ProductID                  Commodity        Country Unit  Quantity  \
0   0011101      BREEDING BULLS (OXEN)          DUBAI   NO       NaN
1   0011102   BREEDING BULLS (BUFFALO)      SRI LUNKA   NO     248.0
2   0011103           BUFFALO,BREEDING      SRI LUNKA   NO       NaN
3   0011104              COWS BREEDING  AJMAN, CYPRUS   NO    1249.0

         Value
0         75.0
1       1921.0
2         90.0
3  258921665.0


text:
Q: Editing an attribute value of SVG through Node results in an error I want to change the value of the style attribute of element rect on the basis of an id. The code is given below. The compiler says that node is null.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg xmlns:osb="http://www.openswatchbook.org/uri/2009/osb" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="10.2332in" height="11.252161in" viewBox="0 0 920.98797 1012.6946" id="svg2" version="1.1" inkscape:version="0.91 r13725" sodipodi:docname="map.svg">
    <defs id="defs4">
        <linearGradient inkscape:collect="always" id="linearGradient6146">
            <stop style="stop-color:#f2f2f2;stop-opacity:1;" offset="0" id="stop6148" />
            <stop style="stop-color:#f2f2f2;stop-opacity:0;" offset="1" id="stop6150" />
        </linearGradient>
        <linearGradient id="linearGradient6140" osb:paint="solid">
            <stop style="stop-color:#000000;stop-opacity:1;" offset="0" id="stop6142" />
        </linearGradient>
        <linearGradient inkscape:collect="always" xlink:href="#linearGradient6146" id="linearGradient6152" x1="757.7793" y1="1019.3268" x2="1032.8184" y2="1019.3268" gradientUnits="userSpaceOnUse" />
        <linearGradient inkscape:collect="always" xlink:href="#linearGradient6146" id="linearGradient6154" gradientUnits="userSpaceOnUse" x1="757.7793" y1="1019.3268" x2="1032.8184" y2="1019.3268" />
    </defs>
    <sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="0.41986485" inkscape:cx="665.09998" inkscape:cy="547.70001" inkscape:document-units="px" inkscape:current-layer="layer1" showgrid="false" units="in" fit-margin-left="-2" fit-margin-right="0" fit-margin-top="-1" fit-margin-bottom="0" inkscape:window-width="1366" inkscape:window-height="705" inkscape:window-x="-8" inkscape:window-y="-8" inkscape:window-maximized="1" width="7.5in" height="9000in">
        <inkscape:grid type="xygrid" id="grid3336" originx="-49.686342" originy="-348.02656" />
    </sodipodi:namedview>
    <metadata id="metadata7">
        <rdf:RDF>
            <cc:Work rdf:about="">
                <dc:format>image/svg+xml</dc:format>
                <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
                <dc:title>
                </dc:title>
            </cc:Work>
        </rdf:RDF>
    </metadata>
    <g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(141.31935,-164.56211)">
        <ellipse style="fill:#000000;fill-rule:evenodd;stroke:#000000;stroke-width:1.47842932px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" id="path3349" cx="179.14752" cy="213.21657" rx="21.40518" ry="14.970306" />
        <ellipse style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1.47842932px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" id="path3349-5" cx="178.278" cy="548.51111" rx="21.40518" ry="14.970306" />
        <path style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1.18673158px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 178.10765,231.18477 c -2.42669,297.78248 -2.42669,297.78248 -2.42669,297.78248 l 0,-1.11949 2.42669,1.11949 0,0" id="path4175" inkscape:connector-curvature="0" />
        <rect style="fill:#ffffff;fill-opacity:1" id="rect4182" width="157.72238" height="44.910931" x="-20.258638" y="180.71774" />
        <rect style="fill:#ffffff;fill-opacity:1" id="rect4184" width="76.607979" height="37.4258" x="175.63919" y="74.562111" />
        <rect style="fill:#ffffff;fill-opacity:1" id="rect4186" width="135.19063" height="52.396061" x="-90.107155" y="203.17317" />
        <path style="fill:#000000;fill-rule:evenodd;stroke:#000000;stroke-width:1.05582392px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" d="m 148.7296,547.49026 -220.637008,0 0,0" id="path4288" inkscape:connector-curvature="0" />
        <g style="font-style:normal;font-weight:normal;font-size:40px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" id="flowRoot4302" />
        <ellipse style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1.47842932px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" id="path3349-1-0" cx="-87.03698" cy="863.2276" rx="21.40518" ry="14.970306" />
        <rect style="fill:#f2f2f2;fill-opacity:1" id="rect4192-1-1-9-1" width="110.40601" height="60.835773" x="-976.95081" y="39.450497" transform="matrix(0,-1,1,0,0,0)" />
        <rect style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-opacity:0.98224852" id="rect4192-1-1-9-6" width="110.40601" height="60.835773" x="-758.51715" y="-46.298756" transform="matrix(0,-1,1,0,0,0)" />
        <rect style="fill:#f2f2f2;fill-opacity:1;stroke:#000000;stroke-opacity:0.98224852" id="rect4192-1-1-9-6-0" width="110.40601" height="60.835773" x="-759.53809" y="53.483723" transform="matrix(0,-1,1,0,0,0)" />
    </g>
</svg>

This is the code error is this the node contain null why???
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      var doc = XDocument.Load("map.svg");
      var node = doc.Descendants("rect").FirstOrDefault(cd => cd.Attribute("id").Value == "rect4182");
      node.SetAttributeValue("style", ""fill:#f2f2f2;fill-opacity:1"");
      doc.Save("Q317664.xml");
      Console.ReadLine();
    }
  }
}

A: You failed to specify your namespace:
var node = doc.Descendants(XName.Get("rect", "http://www.w3.org/2000/svg")).FirstOrDefault(cd => cd.Attribute("id").Value == "rect4182");...


text:
Q: Tracking reductions in reputation and their reasons I am curious about reductions in reputation that are not due to removed posts, changes in accepted answers, or recalculations of reputation scores--in short, reductions in reputation that can be attributed more directly to the user who experienced a drop in reputation. An example might be flags for rudeness.
Is there any way to view such reputation changes and immediately identify their cause (e.g. type of flag)?
I realize that downvotes to questions/answers are easily accessible on a user's profile, but the reason for such downvotes are not immediately clear. One could go to the respective question/answer and hope for a comment that explains the downvote or otherwise try to figure out why a question might be downvoted, but such a strategy seems rather tiresome. Hence my search for a more immediate/direct way.
Some of my attempts:

*

*I can find a history of my flags, but as far as I understand this history only contains flags that I assigned, not flags that others assigned to me. In addition, based on this feature-request I believe that even if there was a way to view flags assigned to me, this might not mean I can also see the flags assigned to other users.

*I can view the reputation changes of users (myself and others) by replacing username and userid in http://stackoverflow.com/users/userid/username?tab=reputation. There I can see downvotes. As flags for rudeness result in a 100 point reduction in reputation, I should theoretically be able to infer from reductions in reputation whether a flag was assigned (although I might not be able to infer which flag has been assigned, so that would still not solve my problem).

A: After a lot of digging, I found an example of what the abusive flag looks like in a (another) user's reputation history:

Note that the -100 rep penalty is NOT listed as an event. (I'm a normal user; I only know that it was an abusive flag because of the accompanying meta question/rant. I suspect mods may see something different... Can a mod confirm?)
I have no clue what it looks like to the person getting the penalty; I suspect it's obvious, however.

Once upon a time, people could see if there were flags on their posts. It lead to disaster. It was removed, and you're not going to get it back.

As for why people cast their votes, that's one of life's mysteries. Yes, there have been plenty of suggestions to require comments for down votes (and variations), but it's not happening.


text:
Q: Fast search for unconnected nodes in big neo4j graph So, i've created a Neo4j graph database out of a relational database. The graph database has about 7 million nodes, and about 9 million relationships between the nodes.
I now want to find all nodes, that are not connected to nodes with a certain label (let's call them unconnected nodes). For example, i have nodes with the labels "Customer" and "Order" (let's call them top-level-nodes). I want to find all nodes that have no relationship from or to these top-level-nodes. The relationship doesn't have to be direct, the nodes can be connected via other nodes to the top-level-nodes.
I have a cypher query which would solve this problem:
MATCH (a) WHERE not ((a)-[*]-(:Customer)) AND not ((a)-[*]-(:Order)) RETURN a;

As you can imagine, the query will need a long time to execute, the performance is bad. Most likely because of the undirected relationship and because it doesn't matter via how many nodes the relationship can be made. However, the relationship directions don't matter, and i need to make sure that there is no path from any node to one of the top-level-nodes.
Is there any way to find the unconnected nodes faster ? Note that the database is really big, and there are more than 2 labels which mark top-level-nodes.

A: You could try this approach, which does involve more operations, but can be run in batches for better performance (see apoc.periodic.commit() in the APOC procedures library).
The idea is to first apply a label (say, :Unconnected) to all nodes in your graph (batch execute with apoc.periodic.commit), and then, taking batches of top level nodes with that label, matching to all nodes in the subgraphs extending from them and removing that label.
When you finally have run out of top level nodes with the :Unconnected label (meaning all top level nodes and their subgraphs no longer have this label) then the only nodes remaining in your graph with the :Unconnected label are not connected to your top level nodes.
Any approach to this kind of operation will likely be slow, but the advantage again is that you can process this in batches, and if you get interrupted, you can resume. Once your queries are done, all the relevant unconnected nodes are now labeled for further processing at your convenience.
Also, one last note, in Neo4j undirected relationships have no arrows in the syntax ()-[*]-().

A: MATCH (a)
WHERE
 not (a:Customer OR a:Order)
 AND shortestPath((a)-[*]-(:Customer)) IS NULL
 AND shortestPath((a)-[*]-(:Order)) IS NULL
RETURN a;

If you could add rel-types it would be faster.
One further optimization could be to check the nodes of an :Customer path for an :Order node and vice versa. i.e.
NONE(n in nodes(path) WHERE n:Order)
In general, this might be rather a set operation, i.e.
expand around all order and customer nodes in parallel into two sets
and compute the overlap between the two sets.
Then remove the overlap from the total number of nodes.
I added an issue for apoc here to add such a function or procedure
https://github.com/neo4j-contrib/neo4j-apoc-procedures/issues/223


text:
Q: IBM SQL Sum and Group By I am trying to do a join and get the total (sum) of Line Items in Purchase orders. It is a grid on a web page. I am displaying all the info of the PO but I also want the Total dollar per line items per PO's.
I get the following error message:
SQL0122 Column  or expression in SELECT list not valid.
I am not sure what I am doing wrong?
Tables:
Table @HPO (PO):
PO#   Vendor  Status
123   aaa     Approved
321   bbb     Approved
456   ccc     Pending
654   ddd     Draft

Table HPO (line Items in PO):
PO#  Total Price
123  100.00
123  25.00
321  75.00
456  25.00
654  10.00
654  90.00

Table AVM (Vendor):
Vendor Vendor#
aaa     444
bbb     555
ccc     777

Here is my code:
    EXEC SQL Declare RSCURSOR1 cursor for
          SELECT A.*, B.*, SUM(C.PECST) as POTOTAL
          FROM @HPO A
          INNER JOIN AVM B on A.HPOVNO = B.VENDOR
          INNER JOIN HPO C on A.HPOORD = C.PORD
          GROUP BY C.PORD
          ORDER BY HPOORD DESC

          OFFSET (:StartingRow - 1) * :NbrOfRows ROWS
          FETCH NEXT :NbrOfRows + 1 ROWS ONLY;

          EXEC SQL  Open RSCURSOR1;

          EXEC SQL SET RESULT SETS Cursor RSCURSOR1;

Update code:

EXEC SQL Declare RSCURSOR1 cursor for
      SELECT A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, SUM(C.PECST) as POTOTAL
      FROM @HPO A
      INNER JOIN AVM B on A.HPOVNO = B.VENDOR
      INNER JOIN HPO C on A.HPOORD = C.PORD
      GROUP BY A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, C.PECST
      ORDER BY HPOORD DESC

      OFFSET (:StartingRow - 1) * :NbrOfRows ROWS
      FETCH NEXT :NbrOfRows + 1 ROWS ONLY;

      EXEC SQL  Open RSCURSOR1;

      EXEC SQL SET RESULT SETS Cursor RSCURSOR1;

A: specify column names in select list as well as in group by clause
DEMO
SELECT A.PO#,Vendor,Status, SUM(C.PECST) as POTOTAL
      FROM @HPO A
      INNER JOIN AVM B on A.HPOVNO = B.VENDOR
      INNER JOIN HPO C on A.HPOORD = C.PORD
      GROUP BY A.PO#,Vendor,Status
      ORDER BY HPOORD DESC

AS per your code - remove C.PECST from group by
SELECT A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM, SUM(C.PECST) as POTOTAL
      FROM @HPO A
      INNER JOIN AVM B on A.HPOVNO = B.VENDOR
      INNER JOIN HPO C on A.HPOORD = C.PORD
      GROUP BY A.HPOORD, A.HPORNB, A.HPORBY, A.HPODTO, A.HPOSTS, A.HPOVNO, A.HPOURG, B.VNDNAM
      ORDER BY HPOORD DESC


text:
Q: Windows 10 IoT Raspberry - VirtualBox I want to run the Windows 10 IoT(check here) Raspberry on VirtualBox.
I followed all steps explained here
I'm getting this error:
Failed to open a session for the virtual machine w10IoT.

Failed to open image 'G:\VM_Workstations\wIoTTest\kmdF41E.vhd' for writing due to wrong permissions (VERR_VD_IMAGE_READ_ONLY).

Failed to attach driver below us! Image is read-only. (VERR_VD_IMAGE_READ_ONLY).

AHCI: Failed to attach drive to Port0 (VERR_VD_IMAGE_READ_ONLY).

Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}

I tried for both MinnowBoardMax and also for Raspberry.
I have no Raspberry board, so help needed to run this on VirtualBox.


text:
Q: refactoring tests that use assert_raises I have a test block:
describe 'without' do

  describe 'author' do
    let(:author)  {nil}
    it('fails')   {assert_raises(ArgumentError) { excerpt }}
  end

  describe 'title' do
    # same content as above, but testing title
  end

  describe 'content' do
    # same content as above, but testing content
  end

end

This works fine and the tests pass - but since there's a lot of repetition here, I wanted to refactor:
describe 'without' do

  describe 'author' do
    let(:author)  {nil}
    it('fails')   {assert_failure(excerpt} # added a method in this line
  end

  describe 'title' do
    # same content as above, but testing title
  end

  describe 'content' do
    # same content as above, but testing content
  end

  # and the method here
  def assert_failure(instance)
    assert_raises(ArgumentError) { instance }
  end

end

However this doesn't work - my tests fail with the following error:
construction::without::author#test_0001_fails:
ArgumentError: Excerpt cannot be built: Author missing

Which is the error that I would expect to be raised with missing information - and is exactly what I'm testing.  So it seems that when this assertion is extracted, the ArgumentError is being raised and stopping the test before assert_raises can make any kind of comparison.  I looked into the code for this assertion, but I can't make out why this would happen when the code is extracted into another method, but not when it's in-line.

A: When you write with the following syntax:
assert_raises(ArgumentError) { excerpt }

What you are actually passing to assert_raises is a block. This means that the code (excerpt) is not evaluated until the method itself decides it wants to evaluate it.
With this syntax, though:
assert_failure(excerpt)

excerpt is evaluated before assert_failure starts.
If you want to duplicate the above behavior, you need to pass assert_failure a block:
def assert_failure(&block)
  assert_raises(ArgumentError, &block)
end

  describe 'author' do
    let(:author)  {nil}
    it('fails')   { assert_failure { excerpt } }
  end


text:
Q: Boost Regulator LDO bucking voltage I'm trying to use the LT3048-5 to get a steady 5V output from a battery that outputs 4.2->3.0V
I connected together the following setup from the datasheet:

But what I'm getting when I input 4.2V is ~3.7V (Normally 0.5V less than the input for typical input voltages). The LDOOUT value and the BSTOUT have the same value with this input voltage, however, if I turn up the voltage to ~6V I actually get a regulated 5V output (~6V BSTOUT).
I'm confused, shouldn't I be seeing ~6.1V at the BSTOUT pin boosted from a proper input voltage and then a steady 5V at the LDOOUT pin?
And there's a part of the datasheet which seems strange to me (http://cds.linear.com/docs/en/datasheet/3048fa.pdf):
under Electrical Characteristics, BSTOUT-VIN Regulation Voltage: there is a condition that LDOUT < VIN
That seems contradictory to the idea of a boosting regulator to me

A: This is going to hurt, but I am guessing you forgot to pull the EN pin high.  (or you did pull it high but there is a broken connection somewhere)
Here's the chip block diagram from the datasheet:

With the EN pin low, the boost converter is disabled but the LDO portion not affected (at least, if the block diagram is honest). Then DC conduction through the inductor and the switching diode (between the SW and BSTOUT pins) will produce a voltage on BSTOUT about 0.5 to 0.7 V below the input voltage (like you saw). This would normally put the LDO into dropout, but when you get this voltage sufficiently above 5 V, the LDO will work normally. Again, this is exactly the behavior you observed.
If you just left the EN pin floating, there is nothing in the datasheet that says which way the pin will default. So you will need to actively pull it high to enable the chip.