text:
Q: Spit max entity from query How do I get max model given parameter from query?
What i want is get xs parameter, compare xs max in ndb.
If max_ndb(xs) is higher return the max_model, otherwise return 204
   @MyModel.query_method(requests_fields('xs',),
                               name='infofest',
                               path='mymodel',
                               http_method='GET'
                               )
    def get_model(self,query):
        return max(query, key=MyModel.xs)#??

Of course query itself is not iterable,and i may not use query_method instead,
Something like.
@MyModel.method(request_fields=('xs',),
                  path='mymodel/{xs}', http_method='GET', name='mymodel.get')   def MyModelGet(self, my_model):
     if not my_model.maxXS_from_datastore:
        return model_with_maxXS
     return 204

Or can we use GQL in endpoints-proto-datastore? Thanks

A: If what you mean is "grabbing the max xs from datastore", it is not doable directly, but it can be easily achieved by using a sort on your query, and taking the first result.
Something like (this is more/less pseudo code, I never used python's ndb, I usually work with java's objectify, but the logic is the same) :
myModel.query().sort("xs descending");
At this point, the first result of that query will simply be your highest "xs" object. You can do your comparison on that first object.


text:
Q: Close a GUI window from button in AutoHotKey GUI window not working I have the AutoHotKey EnterPad Keyboard/Pad with 120 Programmable Keys

It works by sending a Hotkey press for each key to an AutoHotKey script which has a Label function for each key named 001 through 120
Below is my AHK Label function called when key 115 is pressed.
My code allows me to select rows in any Windows Listview component and it will show a popup GUI window with a textbox filled in with the data from the selected rows with each column separated with a TAB space.  I can then copy or save it or view it whatever I like.
;---------------------------------------------------------------------115-----
; Copy Selected Windows Listview Items to Tab Spaced Text - Show popup Window Gui
; https://superuser.com/questions/814831/copy-to-clipboard-from-table-list-in-a-program-on-windows
115:
    Gui, SelectedListRowsTextGui:Destroy
    MouseGetPos, , , , ListView_hwnd, 2     ;2 means return HWND
    ControlGet, selected_row_text, List, Selected, , ahk_id %ListView_hwnd%
    Gui, SelectedListRowsTextGui: +ToolWindow +AlwaysOnTop -Caption
    Gui, SelectedListRowsTextGui:Add, Edit, vUnused_variable x11 y15 w950 h66, %selected_row_text%
    Gui, SelectedListRowsTextGui:Add, Button, x62 y84 w140 h30 +Center, Close
    Gui, SelectedListRowsTextGui:Show, ,
    return

    ButtonClose:
    Gui, SelectedListRowsTextGui:Destroy
    return

Return

Problem
My issue is that once the popup window is opened from my AHK GUI, my CloseButton label dose not get called when I click the close button.
I realize it likely has something to do with it being nested under the key 115s label function. How can I best achieve the desired result?
I tried moving the CloseButton label outside of the 115 label however it still is not called from the GUI's Close button click.
You can see I have named the GUI SelectedListRowsTextGui this is to allow this Enterpad.ahk script to contain many GUI windows for different actions it will perform.

Preview of the GUI window this script creates when listview items are selected and this Label function is called:

A: I got it now....
Since my GUI is named SelectedListRowsTextGui I had to add that name in front of my CloseButton label name so it is now SelectedListRowsTextGuiButtonClose and works great

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syntax error in prolog I am trying to write the following formula into swi prolog but get an error,
Here is the code/query I am typing
[X, Y, Z] ins 0 .. 4, X #= Y + 1.

and here is the error I am getting
ERROR: Syntax error: Operator expected
ERROR: [X, Y, Z]
ERROR: ** here **
ERROR:  ins 0..4, X #= Y + 1 .

Could someone let me know what I did wrong.

A: The problem was that I forgot to import the library [library(clpfd)] so basically had to use the following statement use_module(library(clpfd)). This was spotted by @CapelliC


text:
Q: Handling Dynamic Database Connections My applications requirement is to create database connections on the fly. Database connection details are not known at compile time and are provided to the application at run time only. Only one connection is required to process one request and the scope of the connection is up to the request execution cycle only. Same user may or may not post a new request with the database connection details. We can have hundreds of such users, hence if suppose all of them post request at the same time, my application will have to create hundreds of such database connections.
Based on this scenario, I have got below questions/need clarifications-

*

*Connection pooling will not work here as database connections are
    dynamic?

*What is the best way to create database connections in this scenario? A pure JDBC connection will be best here?

*Creating hibernate session factory for every request, just to create a single connection will cause overhead? Or can we do that?

*What are others possible good ways to handle such a scenario?

Edit:
My application is a component of a bigger web application. This bigger Web application has its own storage on the cloud. Any user can create a sandbox on this storage. Hence, while placing a request for the data load user has to pass on the credentials.
I am new to hibernate and spring. Please help me in deciding the best possible architecture for this.

A: I think you might find the Open Session in View Pattern interesting for your use case. You would just have to suppress the private SessionFactory sf; field and build a new one at each call.
Or if you have a big heap and a big probability that a same user will call several times, you could implement some sort of static HashMap associating a given user with a given SessionFactory and reuse it if already existing.
No then about your questions:

*

*Connexion Pooling will not be possible unless you implement it yourself. But before thinking about it, ask yourself is there is a probability for a same user needing several connections at once.

*I think that the solution I suggested is among the least worst, provided you need hibernate support for managing your entities

*It will cause overhead and there is no way around it beside hacking deep in the framework with probable undesirable side effects. For instance you could imagine using a ThreadLocal to assign a SessionFactory to each thread (from the pool managed by tomcat), then on each call, set the datasource corresponding to the user, see code below

*You will have to give a lot more details about your application and its internal before I can (maybe) advise you on this point.

Here is the code I spoke about in 3. Keep in mind this is bad design. Also I took some shortcuts to make the trick quickly understandable. No Idea if it would actually work, but you can give it a try
public class HibernateSessionRequestFilter implements Filter {

    private static Logger log = LoggerFactory.getLogger(HibernateSessionRequestFilter.class);
    private static ThreadLocal<LocalSessionFactoryBean> lsfbth = new ThreadLocal<LocalSessionFactoryBean>();
    private static final Map<Object, DataSource> datasourceMap = new HashMap<>();

    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("Initializing filter...");
        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
        lsfb.setHibernateProperties(null); // TODO: add correct values
        lsfbth.set(lsfb);
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {

        LocalSessionFactoryBean lsfb = lsfbth.get();
        String credentials = null; //TODO: get user login from request
        DataSource dataSource = datasourceMap.get(credentials);
        if( dataSource==null){
            // TODO: build datasource here
            datasourceMap.put(credentials, dataSource);
        }
        lsfb.setDataSource(dataSource);
        SessionFactory sf = lsfb.getObject();


text:
Q: Meteor application building weird files; No js/css resources When I build my Meteor application, it is not creating valid js or css files. This happens both when I do meteor run ios and meteor build ~/builddir --server=http://app.myserver.com:80/
The snippet below contains the actual CSS, JS and HTML files in respective order. The html is not even properly formatted, which seems super weird to me. Am I missing something completely obvious?
An interesting thing to note is that the names of the files do not seem to change. What I mean is that is the css file is always named 68656e12cb5647ccd9e1ca30f039055f336a08d2.css and the js file is always named 83f43fb0b048a87151b782ce0ae04a95ecbae2e7.js.
I did a find . | grep js and a find . | grep css to try and find these files but I'm pretty sure that they don't exist.
Here is my package list:
ground:db                 0.3.9* Ground Meteor.Collections offline
iron:router               1.0.9  Routing specifically designed for Meteor
meteor-platform           1.2.2  Include a standard set of Meteor packages in your app
momentjs:moment           2.10.3  Moment.js (official): parse, validate, manipulate, and display dates - official Meteor packaging
mrt:fittext               1.2.0  FitText packaged for Meteor.
pauloborges:mapbox        2.1.4_3  Mapbox.js for Meteor apps
reactive-var              1.0.5  Reactive variable
u2622:persistent-session  0.3.5  Persistently store Session data on the client

<!DOCTYPE html >
< html >
< head >
< meta charset = "utf-8" >
< meta name = "format-detection" content = "telephone=no" >
< meta name = "viewport" content = "user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" >
< meta name = "msapplication-tap-highlight" content = "no" >
< link rel = "stylesheet" type = "text/css" class = "__meteor-css__" href = "/68656e12cb5647ccd9e1ca30f039055f336a08d2.css?meteor_css_resource=true" >
< script type = "text/javascript" >
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.1.0.2%22%2C%22PUBLIC_SETTINGS%22%3A%7B%22othersetting%22%3A%22anothervalue%22%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdateVersion%22%3A%22bcf325756930a7028774c23bd28b4cc053de29ba%22%2C%22autoupdateVersionRefreshable%22%3A%22393b25460d4096237fe166edc70a833659c1d58b%22%2C%22autoupdateVersionCordova%22%3A%227c4f521c660011a4692d147b69dc64a13f578719%22%2C%22DDP_DEFAULT_CONNECTION_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%7D"));

if (/Android/i.test(navigator.userAgent)) {
    // When Android app is emulated, it cannot connect to localhost,
    // instead it should connect to 10.0.2.2
    // (unless we're using an http proxy; then it works!)
    if (!__meteor_runtime_config__.httpProxyPort) {
        __meteor_runtime_config__.ROOT_URL = (__meteor_runtime_config__.ROOT_URL || '').replace(/localhost/i, '10.0.2.2');
        __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL = (__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL || '').replace(/localhost/i, '10.0.2.2');
    }
}
< /script>
< script type = "text/javascript" src = "/cordova.js"></script>
< script type = "text/javascript" src = "/83f43fb0b048a87151b782ce0ae04a95ecbae2e7.js"></script>

< meta charset = "utf-8" >
< meta http - equiv = "X-UA-Compatible" content = "IE=edge" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title > Nature Based Therapeutics < /title>
< /head>
< body >

< /body>
< /html>
< !DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
<meta name="msapplication-tap-highlight" content="no">
<link rel="stylesheet" type="text/css" class="__meteor-css__" href="/68656e12cb5647ccd9e1ca30f039055f336a08d2.css?meteor_css_resource=true">
<script type="text/javascript">
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.1.0.2%22%2C%22PUBLIC_SETTINGS%22%3A%7B%22othersetting%22%3A%22anothervalue%22%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdateVersion%22%3A%22bcf325756930a7028774c23bd28b4cc053de29ba%22%2C%22autoupdateVersionRefreshable%22%3A%22393b25460d4096237fe166edc70a833659c1d58b%22%2C%22autoupdateVersionCordova%22%3A%227c4f521c660011a4692d147b69dc64a13f578719%22%2C%22DDP_DEFAULT_CONNECTION_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%7D"));

if (/Android/i.test(navigator.userAgent)) {
    // When Android app is emulated, it cannot connect to localhost,
    // instead it should connect to 10.0.2.2
    // (unless we're using an http proxy; then it works!)
    if ( !__meteor_runtime_config__.httpProxyPort) {
        __meteor_runtime_config__.ROOT_URL = (__meteor_runtime_config__.ROOT_URL || '').replace(/localhost/i, '10.0.2.2');
        __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL = (__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL || '').replace(/localhost/i, '10.0.2.2');
    }
}

</script>
<script type="text/javascript" src="/cordova.js"></script>
<script type="text/javascript" src="/83f43fb0b048a87151b782ce0ae04a95ecbae2e7.js"></script>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nature Based Therapeutics</title>
</head>
<body>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="format-detection" content="telephone=no">
  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="stylesheet" type="text/css" class="__meteor-css__" href="/68656e12cb5647ccd9e1ca30f039055f336a08d2.css?meteor_css_resource=true">

  <script type="text/javascript">
    __meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.1.0.2%22%2C%22PUBLIC_SETTINGS%22%3A%7B%22othersetting%22%3A%22anothervalue%22%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdateVersion%22%3A%22bcf325756930a7028774c23bd28b4cc053de29ba%22%2C%22autoupdateVersionRefreshable%22%3A%22393b25460d4096237fe166edc70a833659c1d58b%22%2C%22autoupdateVersionCordova%22%3A%227c4f521c660011a4692d147b69dc64a13f578719%22%2C%22DDP_DEFAULT_CONNECTION_URL%22%3A%22http%3A%2F%2Fnbt.otterhive.com%2F%22%7D"));

    if (/Android/i.test(navigator.userAgent)) {
      // When Android app is emulated, it cannot connect to localhost,
      // instead it should connect to 10.0.2.2
      // (unless we're using an http proxy; then it works!)
      if (!__meteor_runtime_config__.httpProxyPort) {
        __meteor_runtime_config__.ROOT_URL = (__meteor_runtime_config__.ROOT_URL || '').replace(/localhost/i, '10.0.2.2');
        __meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL = (__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL || '').replace(/localhost/i, '10.0.2.2');
      }
    }
  </script>

  <script type="text/javascript" src="/cordova.js"></script>
  <script type="text/javascript" src="/83f43fb0b048a87151b782ce0ae04a95ecbae2e7.js"></script>

  <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Nature Based Therapeutics</title>
</head>

<body>

</body>
</html>

A: When you use meteor build it will create a tarred bundle containing a node application.
The css and js files are minified and concatenated.
If you untar the bundled tar.gz files you will find the css, js and other static files in bundle/programs/web.browser
Keep in mind the output is an application not a set of files that are intended to be edited.
If you want to edit the files use your project, not the files created by meteor build.

A: So I got it to work, but I would still really like to know what is happening. That was my original question after all. If any one knows what's going on here, please let me know.
I manually deleted the application and reinstalled it. That worked for me. My guess is that old versions of the files were cached for some reason.


text:
Q: tex1Dfetch unexpectedly returning 0 I don't believe this is the same issue as reported here :
Bound CUDA texture reads zero
CUDA 1D texture fetch always return 0
In my CUDA application I noticed that tex1Dfetch is not returning the expected value, past a certain index in the buffer. An initial observation in the application was that a value at index 0 could be read correctly, but at 12705625, the value read was 0. I made a small test program to investigate this, given below. The results are a little bit baffling to me. I'm trying to probe at what index the values no longer are read correctly. But as the value arraySize is changed, so does the "firstBadIndex". Even with arraySize =2, the second value is read incorrectly! As arraySize is made bigger, the firstBadIndex gets bigger. This happens when binding to arrays of float, float2, or float4. If the data are read from the device buffer instead (switch around the commented lines in FetchTextureData), then everything is fine. This is using CUDA 6.5, on a Tesla c2075.
Thanks for any insights or advice you might have.
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>

#define FLOATTYPE float4
texture<FLOATTYPE,cudaTextureType1D,cudaReadModeElementType> texture1D;

const unsigned int arraySize = 1000;
FLOATTYPE* host;
FLOATTYPE* device;
FLOATTYPE* dTemp;
FLOATTYPE hTemp[1];

__global__ void FetchTextureData(FLOATTYPE* data,FLOATTYPE* arr,int idx)
{
    data[0] = tex1Dfetch(texture1D, idx);
    //data[0] = arr[idx];
}

bool GetTextureValues(int idx){

    FetchTextureData<<<1,1>>>(dTemp,device,idx);

    // copy to the host
    cudaError_t err = cudaMemcpy(hTemp,dTemp,sizeof(FLOATTYPE),cudaMemcpyDeviceToHost);
    if (err != cudaSuccess) {
        throw "cudaMemcpy failed!";
    }

    if (cudaDeviceSynchronize() != cudaSuccess) {
        throw "cudaDeviceSynchronize failed!";
    }

    return hTemp[0].x == 1.0f;
}

int main()
{

    try{

        host = new FLOATTYPE[arraySize];
        cudaError_t err = cudaMalloc((void**)&device,sizeof(FLOATTYPE) * arraySize);
        cudaError_t err1 = cudaMalloc((void**)&dTemp,sizeof(FLOATTYPE));
        if (err != cudaSuccess || err1 != cudaSuccess) {
            throw "cudaMalloc failed!";
        }

        // make some host data
        for(unsigned int i=0; i<arraySize; i++){
            FLOATTYPE data = {1.0f, 0.0f, 0.0f, 0.0f};
            host[i] = data;
        }

        // and copy it to the device
        err = cudaMemcpy(device,host,sizeof(FLOATTYPE) * arraySize,cudaMemcpyHostToDevice);
        if (err != cudaSuccess){
            throw "cudaMemcpy failed!";
        }

        // set up the textures
        cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<FLOATTYPE>();
        texture1D.addressMode[0] = cudaAddressModeClamp;
        texture1D.filterMode = cudaFilterModePoint;
        texture1D.normalized = false;
        cudaBindTexture(NULL, texture1D, device, channelDesc, arraySize);

        // do a texture fetch and find where the fetches stop working
        int lastGoodValue = -1, firstBadValue = -1;
        float4 badValue = {-1.0f,0.0f,0.0f,0.0f};

        for(unsigned int i=0; i<arraySize; i++){

            if(i % 100000 == 0) printf("%d\n",i);
            bool isGood = GetTextureValues(i);

            if(firstBadValue == -1 && !isGood)
                firstBadValue = i;

            if(isGood)
                lastGoodValue = i;
            else
                badValue = hTemp[0];
        }

        printf("lastGoodValue %d, firstBadValue %d\n",lastGoodValue,firstBadValue);
        printf("Bad value is (%.2f)\n",badValue.x);

    }catch(const char* err){
        printf("\nCaught an error : %s\n",err);
    }
    return 0;
}

A: The problem lies in the texture set up. This:
cudaBindTexture(NULL, texture1D, device, channelDesc, arraySize);

should be:
    cudaBindTexture(NULL, texture1D, device, channelDesc,
                                   arraySize * sizeof(FLOATTYPE));

As per the documentation, the size argument is the size of the memory area in bytes, not the number of elements. I would have expected that with the clamped addressing mode, the code would still work as expected. With border mode, you should get a zero value which looks like it would trigger your bad value detection. I haven't actually run your code, so perhaps there is a subtley I'm missing somewhere. For such a simple repro case, your code structure is rather convoluted and hard to follow (at least on the mobile phone screen I am reading it on).
EDIT to add that between the time I started writing this and finished, @njuffa pointed out the same mistake in comments


text:
Q: chrome.storage.sync.set won't update the storage anymore I am using chrome.storage.sync for some of my chrome extensions, great tool!
But I have an issue now, after updating the storage like 10 times. It blocks and does not update anymore... No error or anything so I do not know where the problem is.
FYI: I still have space in the storage.
The code:
Storage.get_all = function(callback) {
    STORAGE_SYNC.get('key', function(items) {
        callback(items.gifs_v2);
    });
};

Storage.post = function(id, item, callback) {
    var THIS = this;

    THIS.get_all(function(items) {
        if(items) {
            items[id] = item;
            STORAGE_SYNC.set({'key': items}, callback);
        } else {
            THIS.post_all({}, function() {
                THIS.post(id, item, callback);
            });
        }
    })
};

A: There are several quotas published in the official documentation. Look it up. You probably run out of one of them. Remember that sync also goes into google's sync servers so abusing them will block you for a while. If you dont need to sync among devices use the regular local storage instead of sync.


text:
Q: How to style TreeCell children? First, some context: I have a TreeView in my JavaFX application, with a custom TreeCell implementation. This implementation adds a HBox to display a label (using LabeledText) and one (or more) icons / status indicators to the right.
The label and icons also get tooltips attached to them. When inspected with Scenic View, the result is something like this:

As you can see in the image above, a cell contains a HBox with the label (LabeledText), spacing region, and in this example one icon (using a font hence the Glyph+LabeledText). More icons might be added using either a font or at some point maybe images.
Depending on the status of the item represented, I want to style the label differently (eg different text color, italics, ...). The resulting TreeView currently looks like this:

Actual question: I have tried a couple of variants of my approach, but the logical solution doesn't work properly even though it seems it should. Am I missing something? Have I perhaps discovered a bug in JavaFX CSS handling?
I have a workaround which currently works (but may cease to do so if I add certain features to my TreeView) so I would still like to know why this doesn't work as expected.
Basic approach
Depending on the item displayed and it's status, apply relevant CSS classes to the TreeCell. Using CSS selectors, style the inner label. For example:
.mystatus > HBox > .text {
    -fx-font-style: italic;
}

/* the following variants give mostly the same result */
.mystatus > HBox > LabeledText {
    -fx-font-style: italic;
}
.mystatus .text { /* only difference: this messes up my icons */
    -fx-font-style: italic;
}

The issue I have is that the CSS selection of children of a TreeCell seems not to work reliably once the user starts manipulating the TreeView in the UI. CSS gets applied to nodes which do not match the given CSS rules. For example, after expanding/collapsing some items, labels which do not match the CSS selectors get italicised anyway.
So, if you look at the image above and suppose that is a correct display for my items. Collapsing/reopening the Item 1-node might result in, say Item 3 suddenly becoming italicised even though no such CSS was ever added to that node.
I verified the applied classes using Scenic View to ensure I was setting/clearing classes properly: there are LabeledText nodes inside a CustomTreeCellImpl without the mystatus class that still get italicised.
Alternative 1: using pseudoclasses instead of regular classes
Same issue as the basic approach above
Example CSS:
*.tree-cell:mystatus > HBox > .text {
    -fx-font-style: italic;
}

Alternative 2: apply classes or pseudoclasses directly to LabeledText instead of TreeCell
Same issue as the basic approach above
Example CSS:
.text:mystatus {
    -fx-font-style: italic;
}

Alternative 3: directly apply CSS properties to the created label through code
Again, this runs into the same issue as before: after manipulating the tree, styles get applied where they shouldn't.
Here is the relevant part of the method that populates/updates the TreeCell:
// add label
LabeledText text = new LabeledText(this);
text.setText("Item 1");
if(someCondition) {
    text.setStyle("-fx-font-style: italic;");
}
hbox.getChildren().add(text);

The LabeledText object never has its text changed: a new one is always created. Even then I get incorrect results.
This strikes me as especially odd as this has nothing to do with CSS selectors any more - style is applied directly to the node, but the problem still persists.
The workaround
For those who are interested in how I managed to work around the problem - for now: apply classes or pseudoclasses to the entire TreeCell, and add exceptions/overrides for child elements I do not want styled to restore default layout.
This mostly works but might become cumbersome if/when I add more elements to the cells. Also, I speculate this only works because here all the child elements (aside from the label) have the exact same style applied, regardless of the status of the item they are displaying (eg all Glyphs are black normal font, etc).
If/when I want to customize the style of these (eg change Glyph color depending on context, instead of just using different Glyph characters), I speculate I may again run into this issue - this time with no clue how to solve it as my workaround will no longer be applicable.

Update: I put a project on GitHub which demonstrates the issue.
The demo data in the project is supposed to put items 1.1 and 1.3 in italics, with all others shown normal. When expanding/collapsing item 1, items which shouldn't get italicised anyway (on Windows).
Also, when creating this example I noticed that on OS X none of the items get italicised (the CSS itself gets loaded properly, a different style I added temporarily to test did get applied). On Windows, the issue as described above happens.

A: The mistake was to use the com.sun.javafx.scene.control.skin.LabeledText for displaying your item text.
If you use the normal javafx.scene.control.Label.Label or javafx.scene.text.Text instead everything works fine in your example.
The LabeledText internally uses a StyleablePropertyMirror that attaches itself as a listener to various properties of the TreeItem and applies these style changes to itself (the LabeledText).
To explain: The TreeView is basically just a customized ListView with some indenting. Note that both rely on the concept of recycling cells as much as possible.

And if we look at your structure before collapsing:

*

*(1) Item 1

*

*(2) Item 1.1 (highlighted)

*(3) Item 1.2

*(4) Item 1.3 (highlighted)

*(5) Item 1.4

*(6) Item 2

And after collapsing:

*

*(1) Item 1

*(2) Item 2 (highlighted)

Now it shouldnt surprise you that Item 2 now has the same highlighting that Item 1.1 had before because it is basically the same cell (at the same index position) now displaying a different item.


text:
Q: Shifting in pixel after subsetting with gdalwarp I am trying to subset multiple image to smaller Area of interest
I have tried with gdal_translate & gdalwarp in commandline but it causes slight shift in pixel in the output raster after cropping/sub-setting image into smaller place by using 1st command.
my 1st command is
gdal_translate -projwin 5.83 47.86 10.98 45.65 -of GTiff inputraster.tif outputraster.tif

I have also tried in qgis (which is basically same thing) by clip raster by extent which also causes shift in pixel from original.
My 2nd command
gdalwarp -tr 0.01 0.01 -te 5.83 47.86 10.98 45.65 -s_srs "EPSG:4326" -t_srs "EPSG:4326" -r near -tap -of GTiff input.tif output.tif outputraster.tif

which causes changes in pixel value the highest raster value decreases in 210 from 215 in original raster


text:
Q: Left invariant Vector Field on $S^2$ How intuitively look like all left invariant vector fields on this manifold: the 2 dimensional unit sphere
$S^2$ with the smooth structure inherited from $\mathbb R^3$?
Why all left invariant vector fields on $\mathbb R^n$ are constant?
One answer to the second question might be, that they are invariant under all translations; but why this is so by the definition of left-invariance?


text:
Q: Update just 'Comments' MembershipUser Property I am trying to update just the 'Comments' property in ASP. NET MembershipUser and want to leave all other property untouched. Here is my codes
MembershipUser userComments = Membership.GetUser(sUserName);
userComments.Comment = "Need Change Password";
Membership.UpdateUser(userComments);

It throws an expection 'The E-mail supplied already exists in the database for the application' at Membership.UpdateUser(userComments)
How can I just update only the 'Comments' without changing emails or any other properties?

A: Based on your comment, it is throwing configuration exception. You can ignore this validation by setting requiresUniqueEmail to false in your web.config.
<add name="AspNetSqlMembershipProvider"
  ....
  requiresUniqueEmail="false"
  ....
/>

However it is possible that you have a duplicate email in your database and the framework doesn't know for which one you're trying to update Comment. So to get rid of the duplicate might be a better option.


text:
Q: overloading '>' as a non member function I'm trying to write a program where I can compare two employees gross pay with an overloaded greater than operator. In order to get gross pay I have a member function that returns the gross pay. For some reason whenever I go to compare the two gross pays I get:

Error 1   error C2662: 'double employeeclass::Employee::grosspay(void)' : cannot convert 'this' pointer from 'const employeeclass::Employee' to 'employeeclass::Employee &'

and

2 IntelliSense: the object has type qualifiers that are not compatible with the member function object type is: const employeeclass::Employee

I have included the segments of code that are giving me the issues.
The .cpp:
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;
#include "Employee.h"
namespace employeeclass {
    bool operator> (const Employee &e1, const Employee &e2) {
        if (e1.grosspay() > e2.grosspay())
            return true;
        else
            return false;
    }
}

The .h file
namespace employeeclass {
    class Employee {
        friend bool operator> (const Employee &e1, const Employee &e2);
    }
}

A: Add const to header and cpp files for grosspay()
double employeeclass::Employee::grosspay(void) const;

The const specifier ensures the instance to use the function in a const declaration. Basically, const means this function is not going to make changes and is read only.


text:
Q: Spring Boot and OAuth2 client refresh token grant I want to configure spring boot with oauth2 to work in the flow Refresh token grant. All I need is to send request with grant type set as "refresh_token" and with field refresh token, where I want to put my token. In response I receive access token.
For the flow Resource owner credentials grant, I had such configuration:
@EnableOAuth2Client
@Configuration
public class AuthConfig {
    @Value("${conf.client-id}")
    private String clientId;
    @Value("${conf.client-secret}")
    private String clientSecret;
    @Value("${conf.access-token-uri}")
    private String tokenUrl;
    @Value("${conf.grant-type}")
    private String grantType;
    @Value("${conf.refresh-token}")
    private String refreshToken;
    @Value("${conf.username}")
    private String username;
    @Value("${conf.password}")
    private String password;

    @Bean
    public OAuth2ProtectedResourceDetails resourceDetails() {
        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId(clientId);
        resource.setClientSecret(clientSecret);
        resource.setGrantType(grantType);
        resource.setPassword(password);
        resource.setUsername(username);
        return resource;
    }

    @Autowired
    private OAuth2ClientContext oauth2Context;

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(
        OAuth2ClientContext oauth2Context, OAuth2ProtectedResourceDetails details
    )
    {
        return new OAuth2RestTemplate(details, oauth2Context);
    }
}

Is it possible to build OAuth2ProtectedResourceDetails with refresh token and without username and password?
I'm newbie in SpringBoot but I read a lot of topics and I can't find the answer.


text:
Q: How to Access values from mydata.values() in django? i am selecting data using django Query.Query is
 mydata=MyModel.objects.all().values()
  for newmydata in mydata:
        return HttpResponse(newmydata .values())

newmydata .values() is printing all my values.its not printing keys.i want to access each values.and also i Want to add some extra values into this (newmydata .values()) array.How to do that?

A: I'm unsure of what you want but here goes:
MyModel.objects.values() will return the objects in a dict-like object like so:
[
  {
    'id': 1,
    'first_name': 'Brian',
    'last_name': 'Johnson',
  },
  {
    'id': 2,
    'first_name': 'Mary',
    'last_name': 'Johnson',
  },
  ...
]

If you then take one of the items and do .values() on it, you'll get values returned like when you are using a dict, so you'd get:
(1, 'Brian', 'Johnson') for the first iteration of your loop. I imagine you simply want to do:
for newmydata in mydata:
    return HttpResponse(newmydata)

You can then add extra data like:
for newmydata in mydata:
    newmydata.update(foo='bar', this='that')
    return HttpResponse(newmydata)

Does that make sense?


text:
Q: Not able to pass down an object to history.push() Basically, I have an object name as currentUser generated from chatkit server. This object contains all the information as well as some methods of currently logged in user.
I want to pass this object as a prop to another component. I tried passing it to history.push by initially stringifying it, but after parsing the object at receiving end, I am not able to access the methods of the object. I know that json.stringify does exclude functions. Is there any other way that the stringify method does include the methods as well?
Can anyone suggest another way for passing down this object as props. I have seen something called localStorage. I am not sure how to use it. I would be grateful for any help.

A: Try this one
this.props.history.push({
  pathname: '/your url',
  state: { anyKeyName: yourObject }
})


text:
Q: Handling java exceptions thrown by listeners Take a situation where you are writing a library for objects meant to run asynchronously. To notify the caller of the status of the asynchronous object, the caller has to implement the listener interface.
Now, when using listeners, there's a chance that the listener will do something wrong which will cause an exception to be thrown in the library object.
Example
public interface SomeListener {
    public void progressNotification(int status);
}

public class SomeClass {
    SomeListener listener = null;
    …
    public void setListener(SomeListener listener) {
        this.listener = listener;
    }
    …
    public void someRandomMethod() {

        int progressStatus = 0;
        //Do some stuff here that updates progressStatus

        //then notify the caller
        if (listener != null) {
            listener.progressNotification(progressStatus);
        }
    }
}

public class CallerClass implements SomeListener{
    public void progressNotification(int status) {
        //do something that will throw an exception
        //e.g assume status is 0
        int x = 200/status; //this will throw an ArithmeticException because of division by zero
    }
}

If SomeClass doesn't catch the exception and deal with it, this will cause any code after listener.progressNotification(progressStatus); to not be executed leaving the object in an "incorrect" state.
So my question is, what is the best way to deal with this kind of exception within the library?
I have seen one library that does this:
    if (listener != null) {
        try {
            listener.progressNotification(progressStatus);
        }catch (Thrwowable th) {
            System.err.println("An uncaught throwable " + th);
        }
    }

which doesn't look right to me.

A: To me, the contract of the listener should be well-defined:

*

*it must return fast (i.e. not pause or sleep the thread, etc.),

*it must not throw any runtime exception.

If it does throw a runtime exception, the listener breaks the API contract, and it's thus a bug of the client code of your API, not a bug of the API itself.
I wouldn't do anything other than defining and documenting the contract clearly, and explaining the potential impact of breaking the contract (i.e. undeterministic state, whatever). If the client really wants to protect himself against a programming error, he can still wrap all the listener code inside a try/catch as your example shows.

A: It is same for all, there is nothing we can do for RuntimeException. And this is why they are marked unchecked exception. Here is a nice read regarding unchecked exception.
It clearly specifies this:

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

So, no need to worry about it.
But obviously if it there is any scenario there might be any Checked exception, they needs to be handled properly.
Additionally it is a good practice to document possible exception which might be raised by a method.

A: If you don't want a badly-behaved listener to stop all notifications for everybody, then that kind of exception-handling is what you need to do. I do have some nitpicks. I'd log it instead of writing it to stderr, of course. And catching Throwable is not great, there are some things (out of memory errors, for one thing) you might as well let go uncaught. But the basic idea is ok.


text:
Q: Extract Month Name and Year from string in SQL server and pivot on them I want to Extract Month Name and Year from string in SQL server and pivot on them.I am having data in below format
Id   | Reason
123  |  Post-Close QC Audit - December 2015
124  |  Pre Fund Fraud Prevention
125  |  Post-Close QC Audit - November 2015
126  |  Post-Close QC Audit - October 2016
127  |  Post-Close QC Audit - November
128  |  Post-Close QC Audit - December 2015

I need two result set from this.
One is all valid date and year
Example:
REASON
December 2015
November 2015
October 2016

And second output in format
December 2015  |  November 2015  |  October 2016
123  |  125  |  126
128  |  NULL |  NULL

A: Here's one way to tackle this:
-- Your sample data
DECLARE @table TABLE (ID int, Reason varchar(100));
INSERT @table
VALUES
(123, 'Post-Close QC Audit - December 2015'),
(124, 'Pre Fund Fraud Prevention'),
(125, 'Post-Close QC Audit - November 2015'),
(126, 'Post-Close QC Audit - October 2016'),
(127, 'Post-Close QC Audit - November'),
(128, 'Post-Close QC Audit - December 2015');

-- solution
WITH DateExtract AS
(
  SELECT ID, Reason, Mo =
    SUBSTRING
    (
      Reason, start, PATINDEX('% [0-9][0-9][0-9][0-9]%', SUBSTRING(Reason,start,8000))+5
    )
  FROM
  (
    SELECT
      ID, Reason, start = NULLIF(MAX(PATINDEX('%'+Mo+'% [0-9][0-9][0-9][0-9]%', Reason)),0)
    FROM @table
    CROSS JOIN
    ( VALUES ('January'),('February'),('March'),('April'),('May'),('June'),('July'),
             ('August'),('September'),('October'),('November'),('December')) M(Mo)
    GROUP BY ID, Reason
  ) prep
),
DateMatrix AS
(
  SELECT
    [December 2015] = MAX(CASE Mo WHEN 'December 2015' THEN ID END),
    [November 2015] = MAX(CASE Mo WHEN 'November 2015' THEN ID END),
    [October 2015]  = MAX(CASE Mo WHEN 'October 2016'  THEN ID END)
  FROM DateExtract
  GROUP BY ID
)
SELECT *
FROM DateMatrix
WHERE NOT([December 2015] IS NULL AND [November 2015] IS NULL AND [October 2015] IS NULL);


text:
Q: Sum $\sum_{n=1}^\infty \frac{(2^n+2^{n+1})^2}{5^{n-1}+5^n}$ $$\sum_{n=1}^\infty \frac{(2^n+2^{n+1})^2}{5^{n-1}+5^n}$$
How should I get the sum to infinity? I tried using to find |r| but I am unsure how to do so. Can I have hints on how to approach this qn?

A: $$\sum\limits_{n=1}^\infty\frac{(2^n+2^{n+1})^2}{5^{n-1}+5^n}=\sum\limits_{n=1}^\infty\frac{2^{2n}+2^{2n+2}+2^{2n+2}}{6\cdot5^{n-1}}=6\sum\limits_{n=1}^\infty\left(\frac45\right)^{n-1}=6\cdot5=30$$

A: Just note that
$$\frac{(2^n+2^{n+1})^2}{5^{n-1}+5^n} = \frac{9 \cdot 4^n}{6 \cdot 5^{n-1}} = \frac{15}{2} \cdot \left(\frac 45\right)^n. $$


text:
Q: Store each function call argument's value in array I want to store the arguments of abc(10) andabc(15) which is 10 and 15 respectively inside an array var store = [].
var store = [];
function abc(a){
    for (var i = 0; i < 2; i++) {
        store[i] = a;
    }
    console.log(store)
}
abc(10)
abc(15)

Above code's console.log(store) gives me this array  [10, 10] and [15, 15]. I want one  single array [10, 15] and so on if I call abc(20) 20 array must be added to array and outputs [10, 15, 20].

A: You could add the parameter to the array with Array#push. Your approach changes the values for each call.

function abc(a) {
    store.push(a);
    console.log(store);
}

var store = [];

abc(10);
abc(15);

A: Firstly you don't need a loop to add values in store. Seconfly you just need to push the values you get in the parameter of abc in store by using store.push(a).
var store = [];
function abc(a){
   store.push(a);
}
abc(10)
abc(15)


text:
Q: ¿Cómo puedo hacer para mostrar campos de dos modelos diferentes? Tengo el campo Precio de venta (list_price) del modelo product.template y el campo cantidad (amount) del modelo account.tax.template.
Quiero multiplicar esos dos campos en una vista: product.template.product.form
¿Cómo prodría hacerlo?
class product_model(models.Model):

    _name = 'product.template'
    total = fields.Float(compute='_total', store=True)

    @api.multi
    @api.depends('list_price')
    def _total(self):
        for r in self:
            test = self.env['account.tax'].search([])
            rec = test.campo['amount']
            r.total = r.list_price * rec

class tax_model(models.Model):

    _name = 'account.tax'
    amount = fields.Float(string='iva')

    @api.multi
    def read_ut(self, cr, uid, ids):
        rec = self.browse(cr, uid, 1)
        var = rec.amount
        return var

No me tira ningún error y tampoco me saca el resultado que necesito


text:
Q: Service Unavailable when Load Testing Azure APIM I am trying to perform a load testing using NBomber and JMeter of an .Net 6 API hosted on Azure App Service with default 10 minimum instances.
So when I load test the App Service API directly using NBomber I always gets 100% result like Ok()
But when I load test the same API via Azure APIM my more than 95%(yes random request do succeed) or some sometimes even 100% results fail either due to socket exhaust or SSL or sometimes service unavailable(even though App Service is up and I can see no logs in the log stream).
My APIM is in Premium Plan.
No policy has been set
No Rate Limit or Throttling has been set.
Struggling to figure it out.
(Well the same issue I am facing when exposing an AKS Cluster External IP via APIM)


text:
Q: Why does org.springframework.beans.BeanUtils work with MockitoExtension I only define MockitoExtension. The code inside createMyService() uses org.springframework.beans.BeanUtils. My question is that why it works. Because I didn't use SpringExtension nor SpringBootTest.
@ExtendWith(MockitoExtension.class)
class MyServiceTest {

    @InjectMocks
    MyService myService;

    @Mock
    MyRepository myRepository;

    @Test
    public void createMyTest() throws BusinessException {

        myService.createMyService();
    }
}

void createMyService(){

    BeanUtils.copyProperties(createdDocumentType, documentTypeCreateResponse);
}

A: BeanUtils is a standard Java class that contains only static methods. It is not defined as a Spring bean that has to be injected and you're calling a static method of the class, so Spring context and it's mechanisms are not at all involved. The only requirement for this class to work, as any other Java class, is that it needs to be present on the classpath, which is apparently the case. If you're using for example Maven, it takes care of putting dependencies on the project's classpath.
If you were to use a class instance from any Spring library, you could also do that if you created the instance yourself. Using SpringExtension/SpringBootTest automates this process as during Spring context creation and startup the beans are configured automatically by Spring. Still - they're just Java classes that can be used in any way, Spring only automates the whole process and prepares the configuration and instances for us.
Further reading:

*

*Baeldung

*Spring docs


text:
Q: Bridging headers importing framework into viewcontroller I am new to IOS coding and I am trying to use the AWS SDK which is written in objective C.
After trying all day to get the SDK working for a simple table scan in with swift, I am now trying just use objective C.
I set it up using the AWS Mobile manager which already has the headers and framework in the project

So I am working in my RateSongsViewController.swift file and I want to import the frame work and write my code to access DynamoDB in objective C.
I thought I could just import it and start writing on Obj C in my swift file like this:
import Foundation
import UIKit
#import <AWSDynamoDB/AWSDynamoDB.h>

class RateSongsViewController: UIViewController {

but I am getting th error:
Consecutive statements on a line must be separated by ';'

What am I doing wrong? and Will I have to create new Objective C files to grab the data from AWS or will I be able because of the header import to write in Objective C in the swift file?
Thanks

A: First, make sure the project has the Swift header, if not you can create it manually from,
Build Settings > Swift Compiler > Objective-C Bridging Header
then import the Objective-C Classes into this Bridging Header file which you want to access in the .Swift classes, that is, now you can access the Objective-C classes in every .Swift class. You do not need to import the class in the .Swift class.
Hope it helps you.


text:
Q: Downloading the App images in iPhone Application settings In my App i download the images and save it in the App. I want that downloading option in iPhone Application settings using Settings.bundle. I dont know if it is possible and would like to get help from others.
Thanks in Advance


text:
Q: TFS to VSTS Migration error: TF400898: An Internal Error Occurred I am working on migrating our on premise TFS system to VSTS but I am getting a rather generic error that does not give me much to go on. I did not find anything related in the troubleshooting guide
[Error] TF400898: An Internal Error Occurred. Activity Id: c47a7fd7-2b13-4d47-8aa8-00a7b09367ca
See our documentation for assistance: https://aka.ms/VSTSMigrationTroubleshooting
Microsoft.VisualStudio.Services.DataImport.WebApi.InvalidDataImportRequestException: TF400898: An Internal Error Occurred. Activity Id: c47a7fd7-2b13-4d47-8aa8-00a7b09367ca.
                          at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.HandleResponse(HttpResponseMessage response)
                          at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.d__48.MoveNext()
...
Some details:

*

*The data source is a SQL Server instance hosted in Azure since one table in the collection is larger than recommended for doing a DACPAC import.

*This a DryRun import

*I am using AAD credentials to create the account on our corporate tenant.

*I manually created a test VSTS account to make sure it was not a permission issue.

Update
I re-ran the prepare process but opted out of including Release Management and Package Management. Since we are on TFS 2017 Update 3 these are in 'Preview' and TFSMigrator asks to include them or not. I was able to successfully perform an import to VSTS with that configuration. We do use Release Management extensively so I need to get that working. My current theory is that our Networking and Security teams did not give all the VSTS IP addresses needed access to the SQL VM.
Note: Our networking team has verified that the documented IP addresses are not blocked in our firewall.


text:
Q: How to tell WHETHER two line segments intersect from the coordinates of both line segments only? I have to write a function that calculates which of the lines of the polygon (shown in the picture), if any, will be intersected by a user-drawn line.
Given the polygon below...
I. polygon with line
These are the coordinates for the Polygon: const polygonPoints = [ {x: 100, y: 100}, {x: 200, y: 50}, {x: 300, y: 50}, {x: 400, y: 200}, {x: 350, y: 250}, {x: 200, y: 300}, {x: 150, y: 300}, ]
And for example sake, here are the coordinates for the user-drawn line: [{"x":13,"y":276},{"x":480,"y":84}]
II. polygon with user drawn line coordinates
How would one determine which of the lines of the Polygon would be intersected based on only the coordinates alone? i.e without drawing the polygon and the user drawn line out on a graph
Additional context: Background and motivation - the background is that computers need to be able to check whether lines intersect without the freedom to draw it out oon a graph, by hand, making it relevant to motion tracking and 2d/3d space detection. Your current progress - my current progress is trying to take the x and y coordinates of both lines and seeing whether there is a pattern between the ones that do appear to intersect and the ones that don't. However I am sure there is a mathematical solution to this that I do not know which is much easier.

A: Plug the coordinates of every vertex in turn in the implicit line equation, to get $n$ numbers
$$ax_i+by_i+c$$
If all these numbers have the same sign, there is no intersection. There is no shortcut, in general you have to try all vertices. (More precisely, the number of changes of sign tells you the number of intersection points. Intersections occur along the edges with a change of sign.)

If the polygon is known in advance to be convex, you can solve this faster, as the angle between the sides and the line varies periodically and makes only two changes of sign. You can find one by dichotomic search, and this allows you to test for intersection by looking at just $O(\log n)$ vertices instead of $O(n)$. This is only worth for large $n$.

Addendum:
If the line is given by two points, you can solve this easily with complex arithmetic. Consider the transformation
$$T(z)=\frac{z-z_0}{z_1-z_0}$$ which applies $z_0$ to the origin and $z_1$ to $(0,1)$, hence the line to the axis $x$.
Now for every vertex you consider $\Im(T(v_i))=\Im(w_i)$ and detect the changes of sign between two consecutive transformed vertices. When one occurs, the coordinates of the intersection point are
$$w_i-\Im(w_i)\frac{w_{i+1}-w_i}{\Im(w_{i+1}-w_i)}$$ (as you can check, the imaginary part is zero). That point belongs to the segment iff its abscissa lies in $[0,1]$.
The inverse transformation is easy:
$$T^{-1}(z)=(z_1-z_0)z+z_0.$$

A: If you have a line in the form $ax+by+c=0$ it can be easily verified if two points lie on the same side of the line or on the opposite sides:
say points are $P_1(x_1,y_1)$ and $P_2(x_2,y_2)$ -- if $ax_1+by_1+c$ and $ax_2+by_2+c$ have the same sign, the points lie on the same side (and segment $P_1P_2$ do not intersect the line), if different signs, then $P_1$ and $P_2$ are on the different sides of the line.
How to build the normal equation $\mathbf{n}.(\mathbf{x}-\mathbf{a})=0$ passing through points $\mathbf{a}(a,b)$ and $\mathbf{b}(c,d)$:
the directing vector of the line will be $\mathbf{b}-\mathbf{a}=(c-a,d-b)$ and a normal vector will be then $\mathbf{n}=(-(d-b),c-a)$.
Then the equation of the line will be $\mathbf{n}.(\mathbf{x}-\mathbf{a})=0$ $\Leftrightarrow$
$$-(d-b)(x-a)+(c-a)(y-b)=0$$
However, if we need to know if a segment intersect with another, then we need to parametric form $\mathbf{x}=\mathbf{a}+t\mathbf{l}$ of both too and ensure that $t$ are within some margins (usually $0\le t\le 1$).

A: Here is how I would do it.
We have two lines: the user's line $AB$ between points $(A_x,A_y)$ and $(B_x,B_y)$, and an edge $PQ$ of the polygon between points $(P_x,P_y)$ and $(Q_x,Q_y)$.
We want to transform $AB$ into $A'B'$, where $A'$ and $B'$ have a simple form: specifically, $A'=(0,0)$ and $B'=(\beta,0)$ for some $\beta$. We then transform $PQ$ into $P'Q'$ using the same transformation. And now, because of the simple forms of $A'$ and $B'$, it is a simple matter to check whether $A'B'$ and $P'Q'$ intersect.
So: first we translate all points by subtracting $(A_x,A_y)$ from them. This sends $A$ to $(0,0)$, which is what we want:
$$A''=(0,0)$$
$$B''=(B_x-A_x,B_y-A_y)$$
$$P''=(P_x-A_x,P_y-A_y)$$
$$Q''=(Q_x-A_x,Q_y-A_y)$$
Now we could rotate $A''B''$ to bring $B_y''$ onto the $x$-axis, but it is computationally simpler to perform a vertical shear transformation to achieve the same thing. This transforms the point $(v,w)$ to the point $(v,w-\lambda v)$ for some $\lambda$; to bring $B''$ down onto the $x$-axis we choose
$$\lambda=\frac{B_y''}{B_x''}$$
so that $B'=(B_x'',B_y''-\lambda B_x'')$ has a $y$-coordinate of $0$.
At this point, it simplifies the exposition if we assume that $B_x'$ is positive; so if not, we add a reflection about the $y$-axis to the list of transformations, replacing $B_x'$ with $-B_x'$. (If $B_x'$ is zero, or close to it, we can use a horizintal shear instead $-$ see below.)
Now we compute $P'$ and $Q'$ using the same translation, shear, and reflection. All our transformations preserve the crossedness or not of the two line segments, so finally we just need to check whether the transformed line $P'Q'$ cuts the $x$-axis between $0$ and $B_x'$. For this, we need:

*

*$P_y'$ and $Q_y'$ have different signs; and

*$0<\dfrac{P_x'Q_y'-P_y'Q_x'}{Q_y'-P_y'}< B_x'$.

You only need to compute $\lambda$ once, for the user's line, and you can use it to transform every point on the polygon. This will be very fast, and not too taxing to program.
There are a couple of issues that you will need to address, to do with rounding and overflow.
Firstly, if $B_x''$ is too small, then $\lambda$ might become too big. The solution here is to use a horizontal shear transformation when the line $AB$ is closer to the vertical than the horizontal (i.e. when the absolute value of the slope of $AB$ is greater than $1$).
Secondly, computing $\dfrac{P_x'Q_y'-P_y'Q_x'}{Q_y'-P_y'}$ might lead to overflow issues if $Q_y'-P_y'$ is small. To avoid this, instead of checking whether $\dfrac{P_x'Q_y'-P_y'Q_x'}{Q_y'-P_y'}< B_x'$, you can check whether $P_x'Q_y'-P_y'Q_x' < (Q_y'-P_y')B_x'$ (except that you have to swap the sense of the comparison if $Q_y'-P_y'$ is negative).


text:
Q: Convert NSData to base64encoded AND a byte array in C# I'm implementing in-app purchasing for our iOS app for various auto-renewable subscriptions.  When the payment is complete we need to send the transaction information to our server (cloud) to record the information so that we can verify the receipt on a set interval to make sure the subscription is valid, not cancelled/refunded, or renewed.  We are going to make the JSON calls from the server on a set interval to do this via the in-app purchasing guide and our shared secret, have yet to get to that but before we do we need to have the relevant data from the purchase, i.e. the TransactionReceipt which is an NSData object.
We want to send two parameters to our web service for the TransactionReceipt (among other items such as the ProductID purchased, etc.).  We want to send this as a base64encoded value which is what we believe needs to be sent in the JSON request for validation, so we'll store that in SQL Server.
HOw, using MonoTouch / C# can we convert the NSData "TransactionReceipt" to base64encoded and also a byte[]?
Thank you.

A: There's two easy way to get data out of NSData, using a Stream or the Bytes and Length properties. The stream version would look like:
public byte[] ToByte (NSData data)
{
    MemoryStream ms = new MemoryStream ();
    data.AsStream ().CopyTo (ms);
    return ms.ToArray ();
}

the Bytes and Length version would be:
public byte[] ToByte (NSData data)
{
    byte[] result = new byte[data.Length];
    Marshal.Copy (data.Bytes, result, 0, (int) data.Length);
    return result;
}

Getting the base64 output string remains identical:
public string ToBase64String (NSData data)
{
    return Convert.ToBase64String (ToByte (data));
}

A: That works too :
string yourDataInBase64 = Convert.ToBase64String(yourData.ToArray());


text:
Q: How to remove budgie environment safely? I've changed my OS from Windows to Ubuntu for my very first time. I chose the Budgie desktop environment because it looked really pretty to me.
After a while, I installed gnome-desktop via apt install gnome-desktop and I don't need Budgie any more.
How can I remove the Budgie environment safely with all components from Budgie? My system is encrypted by Ubuntu.


text:
Q: AngularJS Directive element method binding - TypeError: Cannot use 'in' operator to search for 'functionName' in 1 This is the controller of the main template:
app.controller('OverviewCtrl', ['$scope', '$location', '$routeParams', 'websiteService', 'helperService', function($scope, $location, $routeParams, websiteService, helperService) {
    ...
    $scope.editWebsite = function(id) {
        $location.path('/websites/edit/' + id);
    };
}]);

This is the directive:
app.directive('wdaWebsitesOverview', function() {
    return {
        restrict: 'E',
        scope: {
            heading: '=',
            websites: '=',
            editWebsite: '&'
        },
        templateUrl: 'views/websites-overview.html'
    }
});

This is how the directive is applied in main template:
<wda-websites-overview heading="'All websites'" websites="websites" edit-website="editWebsite(id)"></wda-websites-overview>

and this is method is called from directive template (website-overview.html):
EDIT

QUESTION: When EDIT is clicked, this error appears in the console:

TypeError: Cannot use 'in' operator to search for 'editWebsite' in 1

Does anyone know what goes on here?

A: TL;DR; - You are assuming that the bound function is being passed to the child component, as it would be in React. This is incorrect. In fact, AngularJS is parsing the string template and creating a new function, which then calls the parent function.
This generated function expects to receive an object with keys and values, rather than a plain variable.
Longer Explanation
This happens when you have bound a function using '&', and have tried to call that function from your controller, passing a plain variable rather than an object containing the name of the plain variable.
The object keys are needed by the templating engine to work out how to pass values into the bound function.
eg. you have called boundFunction('cats') rather than boundFunction({value: 'cats'})
Worked Example
Say I create a component like this:
const MyComponent = {
  bindings: {
    onSearch: '&'
  },
  controller: controller
};

This function (in the parent) looks like this:
onSearch(value) {
  // do search
}

In my parent template, I can now do this:
<my-component on-search="onSearch(value)"></my-component>

The binding here will be parsed from the string. You're not actually passing the function. AngularJS is making a function for you which calls the function. The binding created in the template can contain lots of things other than the function call.
AngularJS somehow needs to work out where to get value from, and it does this by receiving an object from the parent.
In myComponent controller, I need to do something like:
handleOnSearch(value) {
  if (this.onSearch) {
    this.onSearch({value: value})
  }
}

A: Since you defined an expression binding (&), you need to explicitly call it with an object literal parameter containing id if you want to bind it in the HTML as edit-website="editWebsite(id)".
Indeed, Angular needs to understand what this id is in your HTML, and since it is not part of your scope, you need to add what are called "locals" to your call by doing:
data-ng-click="editWebsite({id: website.id})"

Or as an alternative:
data-ng-click="onClick(website.id)"

With the controller/link code:
$scope.onClick = function(id) {
  // Ad "id" to the locals of "editWebsite"
  $scope.editWebsite({id: id});
}

AngularJS includes an explanation of this in its documentation; look for the example involving "close({message: 'closing for now'})" at the following URL:
https://docs.angularjs.org/guide/directive


text:
Q: Issue using JXL.jar Issue - Getting following error when using JXL.jar to write to the excel file:-
jxl.common.AssertionFailed
at jxl.common.Assert.verify(Assert.java:37)
at jxl.write.biff.CompoundFile.readAdditionalPropertySets(CompoundFile.java:398)
at jxl.write.biff.CompoundFile.<init>(CompoundFile.java:209)
at jxl.write.biff.File.close(File.java:116)
at jxl.write.biff.WritableWorkbookImpl.close(WritableWorkbookImpl.java:456)

Read forums and looks like it has something to do with the version of the JXL.jar file. Hence, downloaded the latest version. Also, the excel file is closed while running the code. So, that issue is ruled out.

A: Resolved this issue. The excel file that the code was writing to had 'Read-only' property set. Once that was removed, the code was able to write to the excel file just fine.


text:
Q: Show multiple joined rows I have a simple relational MySQL database with users, cars an a log table. Everything works fine. In the log table I want to 'register' the users of a car. But a car can have two users at the same time.
My question: How can I show multiple users in the log table, using the relational database?
My database structure:
Table users
user_id  name   phone
-------  -----  -----
1        john   123
2        kevin  456

Table cars
car_id  nr   brand
------  ---  -----
1       666  Ford
2       999  Dodge

Table log
log_id  car_id  user_id1  user_id2
------  ------  --------  --------
1       1       1         2

The car.car_id is related to log.car_id and users.user_id is related to log.user_id1 and log.user_id2.
Supposed SQL:
SELECT log.*, cars.*, users.*
FROM log
LEFT JOIN cars ON log.car_id=car.car_id
LEFT JOIN users ON log.user_id1=users.user_id
LEFT JOIN users ON log.user_id2=users.user_id

PHP (in loop of course):
echo $row["brand"];
echo $row["name"]; // user_id1
echo $row["name"]; // user_id2

It's working for only one name. How to show the names of user_id1 and user_id2 in the same "log" row?

A: Try using aliases like this:
SELECT l.*, c.*, u1.*, u2.*
FROM log l
LEFT JOIN cars c ON l.car_id=c.car_id
LEFT JOIN users u1 ON l.user_id1=u1.user_id
LEFT JOIN users u2 ON l.user_id2=u2.user_id

(Note that it's bad practice to use "SELECT *" except for ad-hoc queries. So you should instead enumerate the exact columns you want to select.)


text:
Q: Выделить в тег small дробные число прайса Как можно с помощью JavaScript взять в тег small дробные число, то есть копейки
пример как должен быть

630.01 ₽

2 последние цифры, кроме символа рубль  (₽)

630.01 ₽

50.00 ₽

150.55 ₽

A:

document.querySelectorAll('.price').forEach(el => {
    let text = el.textContent;
    let indexOfPoint = text.indexOf('.');
    let result = `${text.substr(0, indexOfPoint + 1)}<small>${text.substr(indexOfPoint + 1, 2)}</small>${text.substr(indexOfPoint + 3)}`;

    el.innerHTML = result;
})
.price small {
  color: blue;
}

630.01 ₽

50.00 ₽

150.55 ₽

A:

let regexp = /((\.|\s|,)[0-9]{1,2})/;
document.querySelectorAll(".price").forEach(elem => {
  elem.innerHTML = elem.innerHTML.replace(regexp, '$1')
});

630 01 ₽

50.00 ₽

150,55 ₽

let regexp = /(\.[0-9]{1,2})/;
document.querySelectorAll(".price").forEach(elem => {
  elem.innerHTML = elem.innerHTML.replace(regexp, '$1')
});

630.01 ₽

50.00 ₽

150.55 ₽


text:
Q: How to fill dots between equation and tag(equation numbers) in align environment? Actually I searched this forum already and found some helpful answers under this link:
How to get dots in between equation and equation numbers with equation is centrally aligned?
I applied these tricks in an equation environment
\def\equation{\old@equation\small\hskip\textwidth minus 0.87\textwidth}
\def\endequation{\hbox{ }\leaders\hbox{$\cdot\,$}\hskip \textwidth minus
 \textwidth\old@endequation}

It works fine in this new equation environment. However, when I tried to use these tricks in an align environment, it does not work. I also tried to rewrite the \maketag@@@ macro as following:
\def\maketag@@@#1{\hskip -\textwidth \leaders\hbox{ }\hskip 0.5\textwidth \hbox{} \leaders\hbox{$\cdot\,$}\hskip\alignsep@\hbox{\m@th\normalfont#1}}

It works some how not so perfectly, because some '...' overlaps with the equation:

And after defining the \maketag@@@ macro, the equation environment is also destroyed.

What I really want is the equation looks like this picture:

I know there is a trick to realize this function in align environment like this:
\begin{align}
  e^x&=1+x\multido{\i=2+1}{6}{+\es{\i}}\notag\\
  \hskip 0.1\textwidth
     &\multido{\i=8+1}{6}{+\es{\i}}+\cdots\leaders\hbox{$\cdot$\,}\hskip
     0.18\textwidth\hskip
     -0.18\textwidth\label{eq:etoXseries}
\end{align}

But I think it is not user friendly, because I must add additional codes in each line. I want to realize this function in the align environment, which means one can use like this:
\begin{align}
  e^x&=1+x\multido{\i=2+1}{6}{+\es{\i}}\notag\\
       &\multido{\i=8+1}{6}{+\es{\i}}+\cdots
     \label{eq:etoXseries}
\end{align}

and the align environment will fill $\cdot$ between the equation and number automatically.
I hope that I have explained my questions clear enough for you all.
Waiting for your answers. Thanks a lot!


text:
Q: Spring boot unable to run schema.sql I am on spring boot 2.3, and have following in my schema.sql
CREATE TABLE customer (id SERIAL PRIMARY KEY, first_name VARCHAR(255), last_name VARCHAR(255));

Pom file has h2 dependency.
When I run application, I get error:
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "CUSTOMER" not found; SQL statement:
INSERT INTO customer (first_name, last_name) VALUES ($1, $2) [42102-200]

Is some change needed in application.properties to make spring boot execute schema.sql?

A: You can drop table if exist before creation :
DROP TABLE IF EXISTS customer;

CREATE TABLE customer (id SERIAL PRIMARY KEY, first_name VARCHAR(255), last_name VARCHAR(255));


text:
Q: Trigger php files using javascript? I have a like button. The php behind it works as it should. But it refreshes the page. Is it possible to write a javascript between the HTML and the PHP? For example: HTML:
<input type="button" id="like_button"><?php echo $getVideo["likes"];?></button>

And when clicking on that button, the javascript triggers the file like_button.php, which looks like this:
<?php
require_once "data_inc/database.php";

   $like = new videos();
   $like->likeButton($_GET["id"]);

No link out there shows how it would look like, while having OOP php. If someone could provide a javascript, it would help everyone who are currently facing this. How would the javascript look like?
Thanks.

A: You should make AJAX call. for example:
<input type="button" onclick="get_like()" id="like_button"><?php echo $getVideo["likes"];?></button>

You can read more on fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Otherwise you can use any ajax call, for example from jQuery if you like.
For this purpose I would also consider using <button> instead of <input>


text:
Q: Is this inclusion-exclusion rule for counting elements of finite unions true? FYI

"For any finite set A, N(A) denotes the number of elements in A."

"It can be shown using mathematical induction (see exercise 48 at the end of this section) that formulas analogous to those of Theorem 9.3.3 hold for unions of any finite number of sets."

Source: Discrete Mathematics With Applications, Susanna S. Epp
If we consider the theorem 9.3.3. is the same as the exercise 48, the right hand sides of $N(A_1 ∪ A_2)$ by theorem 9.3.3. and by the equation given in exercise 48 should be the same.
If n=2
$N(A_1\cup A_2) = [N(A_1)+N(A_2)] - N(A_1 ∩ A_2)$ $\color{blue}{\text{
By theorem 9.3.3.}}$
and
$N(A_1 ∪ A_2) = ∑ \limits_{1≤i≤2} N(A_i) - ∑ \limits_{1≤ i <j ≤ 2} N(A_i ∩ A_j) + ∑ \limits_{1≤i<j<k≤2} N(A_i ∩ A_j ∩ A_k) - \cdots + (-1)^{2+1} N(A_1 ∩ A_2 ∩ \cdots ∩ A_2)$
"For all integers i with $1≤i≤2$" means integers 1, 2
"For all integers i, j with $1≤ i <j ≤ 2$" means integers i=1, j=2
"For all integers i, j, k with $1≤i<j<k≤2$" means integers i=1, j=2 and no integer k. hence $A_k= \emptyset$
= $ [N(A_1)+N(A_2)] - N(A_1 ∩ A_2) + N(A_i ∩ A_j ∩ Ø)- \cdots + (-1)^{2+1}N(A_1 ∩ A_2 ∩\cdots ∩A_2 $
= $ [N(A_1)+N(A_2)] - N(A_1 ∩ A_2) + 0 - \cdots - N(A_1 ∩ A_2 ∩\cdots ∩A_2)$
= $ [N(A_1)+N(A_2)] - 2N(A_1 ∩ A_2)$ $\color{blue}{\text{by the equation in exercise 48}}$
So the right hand side by the equation of exercise 48 is not the same as the right hand side of two sets in the equation theorem 9.3. when we substitute n=2 to
$N(A_1∪A_2 ∪\cdots ∪A_n)$
$\space\space\space  = ∑\limits_{1\le i \le k} N(A_i) - ∑\limits_{1≤i <j≤n} N(A_i ∩ A_j) + ∑\limits_{1≤ i <j<n} N(A_i ∩ A_j ∩ A_n) - \cdots + (-1)^{n+1} N(A_1 ∩ A_2 ∩ \cdots ∩ A_n)$

A: Okay, no.   The ellipsis means "continue on in this pattern".   When $n=2$ there is no need to continue; the sequence is complete.   The last term was $N(A_1\cap A_2)$.   There is no need to repeat it.
$$\begin{align}N(A_1\cup A_2) = & N(A_1)+N(A_2)-N(A_1\cap A_2)
\\[3ex] N(A_1\cup A_2\cup A_3) = & N(A_1)+N(A_2)+N(A_3)-N(A_1\cap A_2)\\ & -N(A_1\cap A_3)-N(A_2\cap A_3) + N(A_1\cap A_2\cap A_3)
\\[2ex]  = & \sum_{1\leq a\leq 3}N(A_a)-\sum_{1\leq a<b\leq 3}N(A_a\cap A_b) ~+~ N(A_1\cap A_2\cap A_3)
\\[3ex] N(A_1\cup A_2\cup A_3\cup A_4) = & \sum_{1\leq a\leq 4}\!\!N(A_a)-\!\!\sum_{1\leq a<b\leq 4}\!\!N(A_a\cap A_b) \\ & +\!\!\!\!\sum_{1\leq a<b<c\leq 4}\!\!\!\! N(A_a\cap A_b\cap A_c)-N(A_1\cap A_2\cap A_3\cap A_4)
\\[3ex] N(A_1\cup A_2\cup A_3\cup A_4\cup A_5) = & \sum_{1\leq a\leq 5}\!\!N(A_a)-\!\!\sum_{1\leq a<b\leq 5}\!\!N(A_a\cap A_b) +\!\!\!\!\sum_{1\leq a<b<c\leq 5}\!\!\!\! N(A_a\cap A_b\cap A_c) \\ & -\!\!\!\!\sum_{1\leq a<b<c<d\leq 5}\!\!\!\! N(A_a\cap A_b\cap A_c\cap A_d)+N(A_1\cap A_2\cap A_3\cap A_4\cap A_5)
\\[3ex] \textsf{et cetera}
\end{align}$$


text:
Q: How to convert the binary text generated in my .PDF to a string? I am using this code:
from PyPDF2 import PdfFileReader

def text_extractor(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)

        # get the first page
        page = pdf.getPage(0)
        print(page)
        print('Page type: {}'.format(str(type(page))))

        text = page.extractText()
        print(text)

if __name__ == '__main__':
    path = 'XEROX.pdf'
    text_extractor(path)

But this return me:
{'/Type': '/Page', '/MediaBox': [0, 0, 612, 792], '/Parent': IndirectObject(3, 0),
 '/Resources': {'/ProcSet': ['/PDF', '/ImageB', '/Text'],
 '/ExtGState': IndirectObject(47, 0), '/Font': IndirectObject(48, 0)},
 '/Contents': IndirectObject(5, 0)}
Page type: <class 'PyPDF2.pdf.PageObject'>
 !ˆ"#$
[Finished in 0.9s]

Where is the data?
I think that this pdf has binary symbols instead of ascii. How can I read this information in ascii or string type?

This is the result when I apply copy and paste in the PDF' information:

A: I found it:
I clone the textraxt repository from gibhub. I installed textract (with some problems but i achieved) and work very good. I will edit this answer for include my code.
Regards


text:
Q: How do I list only the numbers that have '3' in them from an array? The exercise says that I have to use a loop to check the array for numbers that contain the number '3'. The program must keep looping until all the numbers are listed. Currently it wont stop looping.
The exercise hints at making the numbers in array into a string. And also hints at the use of .indexOf() method.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];

var number_as_string = "" + some_array;

while (number_as_string.indexOf("3"))
{

  process.stdout.write ("\n  " + number_as_string);

}

process.exit();

The expected result is to list the numbers: 23, 36 and 300.

A: You could change your loop to a for loop, as below.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
var result = [];
const numToLookFor = "3";

for(var i = 0; i > some_array.length; i++) {
    var num = some_array =
    if (num.toString().includes(numToLookFor)) {
        result.push(some_array[i]);
    }
}

You could also use an array.filter() method to achieve the same result.
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
const numToLookFor = "3";

var result = some_array.filter(num => num.toString().includes(numToLookFor));

A: Try this
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];

var number_as_string = "" + some_array;

some_array.forEach(element => {
  if (element.toString().includes("3")) {
      console.log(element);
  }
});

or
const ELEMENT_TRHEE = "3";

number_as_string.split(",").forEach(element => {
   if (element.indexOf(ELEMENT_TRHEE) > -1) {
      console.log(element);
   }
});

A: This line of code won't convert your array od numbers into array of string. Instead it will convert the whole array into string
var number_as_string = "" + some_array;

This will output value as
"12,23,45,36,300,55,66,78"

and secondly, the while loop has not any termination condition that's why it is going into an infinite loop as indexOf will return some value always.
This code might help:
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
for (let num of some_array){
    let num_in_string = num.toString()
    if (num_in_string.indexOf("3") !== -1){
        console.log(num_in_string)
    }
}
process.exit();

Here I am looping through the array and getting each number in num variable as a number.
Then I am converting the number into a string using .toString() method.
The indexOf() method return either the index if present in the string or -1 is not found.
Thus the if block executes only if the returned value from indexOf is not -1 that means the "3" is present in the number and simply outputting it to console.
In case you are not familiar with toString() method, here is an alternative:
var some_array = [12, 23, 45, 36, 300, 55, 66, 78];
    for (let num of some_array){
        let num_in_string = num + ""
        if (num_in_string.indexOf("3") !== -1){
            console.log(num_in_string)
        }
    }
    process.exit();


text:
Q: PHP5.3 (as Apache module) unable to write into /var/www///cache Please, be patient while reading, because the problem is seems to be transparent but just only seems.
The situation is:
1.
OS:     fedora-16 (latest),
httpd:  apache-2.2.21,
php:    php-5.3.8 (works as apache's module)

2.
    host information:
DOCUMENT_ROOT: /var/www/[site-name]/public_html
Kohana-3.2.0 (latest stable) installed this way:

$ pwd
/var/www/<site-name>

$ ls -alp
drwxr-xr-x.  6 apache apache 4096 Jan   7 20:35 ./
drwxr-xr-x.  8 apache apache 4096 Jan   7 20:08 ../
drwxr-xr-x.  9 apache apache 4096 Jul  25 03:26 application/
drwxr-xr-x. 10 apache apache 4096 Jul  25 03:26 modules/
drwxr-xr-x.  2 apache apache 4096 Jan   7 20:35 public_html/
drwxr-xr-x. 11 apache apache 4096 Jul  25 03:26 system/

$ cd application/; ls -alp
drwxr-xr-x. 9 apache apache 4096 Jul  25 03:26 ./
drwxr-xr-x. 6 apache apache 4096 Jan   7 20:35 ../
-rwxr-xr-x. 1 apache apache 3612 Jul  25 03:22 bootstrap.php
drwxrwxrwx. 2 apache apache 4096 Jan   8 20:14 cache/
drwxr-xr-x. 4 apache apache 4096 Jul  25 03:26 classes/
drwxr-xr-x. 2 apache apache 4096 Jul  25 03:26 config/
drwxr-xr-x. 2 apache apache 4096 Jul  25 03:26 i18n/
drwxrwxrwx. 2 apache apache 4096 Jul  25 03:26 logs/
drwxr-xr-x. 2 apache apache 4096 Jul  25 03:26 messages/
drwxr-xr-x. 2 apache apache 4096 Jul  25 03:26 views/

Command `top` says that Apache is really starts under `apache` user privileges.

So how can I have that application/cache and application/logs directories are unwritable? - I've checked them also with
var_dump(fopen($_SERVER['DOCUMENT_ROOT'] . '/../application/cache/something.txt', 'w+'));

Same result. Have no idea how it could be. No symlinks, no mounted drives etc.
Have anyone met such a situation?

A: Disable selinux (http://www.crypt.gen.nz/selinux/disable_selinux.html).
BTW from security standpoint, it's a very bad idea to make apache owner of .php files


text:
Q: Duplicate NSView at runtime Is it possible to duplicate a NSView at runtime? I use it as a popover showing text messages and I'd like to show it "twice" (with different messages) simultaneously.

A: If you create the NSPopover instance programmatically, then you can define the NSView in a nib of its own (that is the simplest way to create an NSPopover anyway) and then just instantiate two different NSViewControllers with the same nib file.


text:
Q: Skipped 49 frames! The application may be doing too much work on its main thread I am inflating Views (not fragments) in my viewpager implementation. My main class extends Activity.
I face this error when I try to swipe screen from my app or
at com.example.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
and
01-04 16:44:35.5278614-8614/com.parsizabanan.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4195ee48)
01-04 16:44:35.5278614-8614/com.parsizabanan.app E/AndroidRuntime﹕ FatAL EXCEPTION: main
Process: com.parsizabanan.app, PID: 8614
android.view.InflateException: Binary XML file line #6: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInfl    ater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.parsizabanan.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:110)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1021)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:16574)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1406)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:697)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16574)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1955)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1151)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1333)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1038)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5890)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5118)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInfl ater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.parsizabanan.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:110)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1021)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:16574)
at android.widget.RelativeLayout.measureChildHorizontal(Rel    ativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1406)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:697)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16574)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1955)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1151)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1333)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1038)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5890)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5118)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
at android.graphics.drawable.Drawable.cre    ateFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2150)

CustomPagerAdapter:
public class CustomPagerAdapter extends PagerAdapter {

public Object instantiateItem(View collection, int position) {

    LayoutInflaterinflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLatER_SERVICE);

    int resId = 0;
    switch (position) {
        case 0: {
            resId = R.layout.lab;
            break;
        }
        case 1: {
            resId = R.layout.lab;
            break;
        }
        case 2: {
            resId = R.layout.etela;
            break;
        }
        case 3: {
            resId = R.layout.ticket;
            break;
        }
        case 4: {
            resId = R.layout.product;
            break;
        }
        case 5: {
            resId = R.layout.about;
            break;
        }

    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);

}

@Override
public Parcelable saveSt    ate() {
    return null;
}

@Override
public int getCount() {
    return 6;
}

MyActivity:
public class MyActivity extends Activity {
ViewPager myPager = null;
ImageButton contact = null;
ImageButton about = null;
ImageButton lab = null;
ImageButton product = null;
ImageButton ticket = null;
ImageButton etela = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    CustomPagerAdapter adapter = new CustomPagerAdapter();
    myPager = (ViewPager) findViewById(R.id.customviewpager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(5);

    myPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        public void onPageScrolled(int i, flo    at v, int i2) {
        }

        public void onPageSelected(int i) {
        }

        public void onPageScrollStateChanged(int i) {
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    switch (myPager.getCurrentItem()) {
                        case 0:
                            break;
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                    }
                }
            });
            t1.start();
        }
    });

}

and is it lab layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/lab1"/>
</LinearLayout>

A: Using large images could cause this error. Its highly recommended to reduce images sizes and then load them to ImageViews.
Also there is an other way to request android to give your application more memory by adding the following to the manifest . But this is not recommended. For more information look at here and here.
<application
    ...
    android:largeHeap="true"
    ...
>

...

</application>


text:
Q: IOException when sending request right after httpclient is created I looked around and couldn't find any similar question for this though it sounds like a dummy question. The problem is I get IOException every time why sending request immediately after creating a default httpclient.
HttpClient httpClient = new DefaultHttpClient();
// This throws IOException
httpClient.execute(httpPost);

However it works well if I sleep some time after creating httpclient and before sending the request.
HttpClient httpClient = new DefaultHttpClient();
try {
  Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
}
// This works.
httpClient.execute(httpPost);

This is java 1.7 and apache httpclient 4.2.3. Any idea why? Thanks in advance!


text:
Q: outer measure and Cartesian product Let $A$ be a subset of $\mathbb{R}^n$, and let $B$ be a subset of $\mathbb{R}^m$. Note that the Cartesian product $\{(a, b) : a \in A, b\in B\}$ is then a subset of $\mathbb{R}^{n+m}$. Show that $m^{*}_{n+m} (A \times B) \le m^{*}_n(A)m^{*}_m(B)$.
$m^*_n$ denotes an n-dimensional outer measure.
The definition of an outer measure is that $m^*_{n+m}(A \times B) = \inf \{\sum_{j \in J} \text{vol}(C_j) : A \times B \subseteq \bigcup_{j \in J} C_j\}$ and similarly $m^{*}_n =  \inf \{\sum_{i \in I} \text{vol}(A_i) : A  \subseteq \bigcup_{i \in I} A_i\}$ and $m^{*}_m(B) = \inf \{\sum_{k \in K} \text{vol}(B_k) : B  \subseteq \bigcup_{k \in K} B_k\}$.
I can also observe that the Cartesian product of a cover of $A$ and a cover of $B$ covers $A \times B$, but I am not sure how to proceed from here. I appreciate if you give some help.


text:
Q: How to get an entity between two dates in appengine datastore for I have an appointment table with appointment date as one of the columns. I want to retrieve all the appointments between two dates in appengine datastore using JPA. can please let me know how to achieve this? I tried with following query but it did not work.
select a from Appointment a where (apptSts='p' or apptSts='a') and (apptDate>=:fromDate or apptDate<=:toDate)

A: Make the property as a list property.  Then you can query between two dates.
See the following test code done in Objectify.  I think you can use the same technique in JPA also.
https://github.com/stickfigure/objectify/blob/master/src/test/java/com/googlecode/objectify/test/QueryExoticTypesTests.java

A: To retrieve appointments between 2 dates, you need to change your query logic to include "and" instead of "or" :
select a from Appointment
where apptDate>=fromDate and apptDate<=toDate

You CAN have inequality filers on the same property in appengine, but they can't be combined with OR.
See examples in gql reference, which should also apply to JPA.

A: You can apply multiple inequality but they should be on the same field (variable).I guess whats going wrong here is that app engine doesn't allow to use the bracket things ,,,i mean
(conditionA AND conditionB .....) OR (conditionC AND conditionC .....)
//--this is not allowed.

By the way following is allowed(i tried it)
(conditionA AND conditionB .....) AND (conditionC AND conditionC)
//--allowed(although its bracket are meaning less here)

A: You can only do one greater than or less than query, so one way to do it is to do a greater than query, and walk through the results and manually filter out the ones that don't match the less than query.


text:
Q: How do you grab a certain string of text through a link in java? Is it possible to grab a certain piece of text through Java in a website? like for example, https://weather.com/weather/today/l/41.93,-88.25?par=google&temp=f , how would i be able to figure out the temp that it displays in java?

A: The practical answer to your question is: You don't wanna do that.
Let me try to answer it, at which point you'll realize why you don't want to:
How do I programatically parse a website?
It's complicated. Just about every browser has an option to right click and 'view source'. Presumably the number(s) you want are in here; you can parse this text to find them. It's NOT easy though. You'll probably be tempted to use something like a regular expression or a simple 'find me this exact string of text' trick to find what you need. It may work. But generally that means the day that this site changes the style or just does some basic updates, your code ceases to work.
You'll need to put in your agenda to check, every day if you have to, if your code still works. That's 5 minutes out of your day, every day, for the rest of the life of this project. That sounds incredulously expensive, which is why you don't want this.
If you must, there are ways to tighten up your parsing code. If you use libraries like jsoup, that helps a bit. If you toss the entire site through a 'browser emulator', you can deal with javascript making ajax requests and the like (these days websites are like little programs, and to truly observe programmatically what the site shows to human eyes, you need to run that program to get the job done. If you're very lucky, you can inspect the 'source code' of the little program and that's all you need, but you're not always that lucky).
But, as I said, that just helps a bit. The day will come the weather channel changes their site and breaks your code. They won't announce it. It is not considered immoral or technically dubious to do so. Maybe you can update your agenda to check if your code works down to once a week instead of daily, but it'll be a permanent maintenance burden. You DO NOT WANT THIS.
Okay, forget that. How does this really work?
Sites that are designed to let you read this stuff have an API. They'll document it someplace. This is a 'website' made specifically for code. It has no formatting, and a well defined specification. Send it this specific simple string, and this specific simple answer comes out, and the site has tooling to let you know when they change it (for example, an 'API version') - all luxuries the site meant for human consumption will not have.
You're in luck. The weather channel has an API.
What you really want, is to read all that, figure out how that API works, and use that.
The API will not break when the weather channel decides that today is a good day to slightly change the shade of the background image.


text:
Q: Notepad++ replace all ( | ) this char with comma <Etiketler>banko sistem nedir|normal sistemle banko sistem arasındaki fark nedir|sistem|sistem kazançlı mıdır|sistem nasıl oynanır|sistem ne işe yarar|sistem nedir|sistem sıfır nasıl oynanır | bahiskritik.com </Etiketler>

i have this case in my xml file. and i try raplace with this
<Etiketler>(.*?)[\|](.*?)<\/Etiketler\>

with this
<Etiketler>$1 , $2</Etiketler>

but only changing first " | " case. Can you please help me?


text:
Q: Bunyan stdout truncated I have Bunyan logger writing to both a file and stdout.  However, before the logger can finish writing everything to stdout, the node process exists and the logs to stdout are truncated.
Is there anyway to wait for the logs to finish printing before exiting fully?

A: Some where in your node code you might have used process.exit() due to which the process exists before doing the work which runs on a different process thread(i.e. I/O) or which take time. So if you've used something like that, you can set a few seconds timeout for that, so that all other tasks are done before exit.


text:
Q: Адаптация таблицы для мобильных устройств Есть следующая таблица:

            Экономный тариф30 руб.
            Стандартный тариф60 руб.
            Безлимитный тариф120 руб.

             Фича раз
             -
             -
             +

            Фича два
             -
             +
             +

            Фича три
             +
             +
             +

На планшетах и мобильных устройствах (<768px) должен отображаться всего лишь один столбец с тарифом (примерно так) с тремя кнопками-переключателями:
          Экономный тариф
          30руб.
Фича раз  -
Фича два  -
Фича три  +

При нажатии на вторую кнопку должен показываться второй столбец, при нажатии на третью -- третий. При нажатии на первую кнопку должен вновь показываться первый столбец.
Подскажите, как это можно реализовать?

A:

$(document).ready(function() {
  $('.first-btn').on('click', function(event) {
    // При клике на первую кнопку - показываем первую колонку.
    // Потом скрываем вторую и третью
    // Подобный механизм при клике на вторую и третью кнопку
    event.preventDefault();
    $('.first').show();
    $('.second').hide();
    $('.third').hide();
  })
  $('.second-btn').on('click', function(event) {
    event.preventDefault();
    $('.second').show();
    $('.first').hide();
    $('.third').hide();
  })
  $('.third-btn').on('click', function(event) {
    event.preventDefault();
    $('.third').show();
    $('.second').hide();
    $('.first').hide();
  })
})
// Используем медиа запрос для экранов меньше 768 px, прячем блок с кнопками на экранах большего размера
@media (max-width:768px) {
  .buttons {
    display: block;
  }
  .second {
    display: none;
  }
  .third {
    display: none;
  }
}

.buttons {
  display: none;
}

  <button class="first-btn">Экономный тариф</button>
  <button class="second-btn">Стандартный тариф</button>
  <button class="third-btn">Безлимитный тариф</button>

      Экономный тариф30 руб.
      Стандартный тариф60 руб.
      Безлимитный тариф120 руб.

       Фича раз
       -
       -
       +

      Фича два
       -
       +
       +

      Фича три
       +
       +
       +

Проверяйте код на экранах с расширением меньше чем 768px.