text:
Q: How do I find the path of a file on another computer on my network? I would like to access files from another computer on the same network in the Terminal. But I am not sure of the path to those files. How do I find it?

A: It would depend on how you want to access the file. Here's what I do:

*

*Initiate the connection to the remote computer (I do it via Finder -> Go -> Connect to Server [or Command+K]) but you can also do via terminal using the mount command

*Connect to the shared folder/volume available to your user

*When connecting to those in Terminal, you would now use the path /Volumes/[name of folder]/[rest_of_path_here] to access them.

For example, if you connected to a folder called Stuff with a subfolder called Things, and ultimately file jackpot.txt on ip 10.10.1.5, first connect via smb to the server (10.10.1.5), choose the folder Stuff, and then reference that path in Terminal as /Volumes/Stuff/Things/jackpot.txt
EDIT: You can also run a Find command (Command + F) inside of Finder while you are connected to the share if you still don't know where the file is. Do the following:

*

*Open Finder, connect to the server/volume (Steps 1+2 above)

*Run Command+F to Find, enter your search term

*Above the Finder section where files display, switch the search to "Shared" - this will run the search against connected volumes

*Locate the file you want, and then drag+drop it into an open Terminal window

*The path will be shown in Terminal

A: In addition to drag and drop, you can right click on any Finder window, select "Customize Toolbar," and add the "Path" drop-down button.
It won't show a path you can copy-paste like in Windows, but it will give a better idea of the path to a folder you're in.


text:
Q: Error converting large size image to base64 string cordova android I am implementing some functionality in my hybrid app where I am capturing image from camera using cordova api. I get the path of image, which I convert to base64 for uploading to some server. I used file reader api's readAsDataURL method to convert local image path to base64. Everything works fine until the image size exceeds some particular limit in this case it fails for more than 2MB size images. I get following error in my logcat

Refusing to load URL as it exceeds 2097152 characters

which is I think my base64 string which is large. Can anybody give me some idea how to overcome this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flask: button to update value in database so I currently pull a value from a database and display it on the screen. I have a HTML button right next to it that is supposed to increase the score on the screen by 1 every time I click it. Currently, when I click the button nothing happens. The number on the screen stays the same.
Python file
@app.route('/')
def layout():
    db = get_db()
    try:
        cur1 = db.execute('SELECT score FROM {tn} where name="Tyler"'.format(tn="Score"))
        score1 = cur1.fetchone()
        if request.method == 'POST':
            db.execute('UPDATE {tn} SET score=score+1 WHERE name="Tyler"'.format(tn="Score"))
            db.commit()
    except:
        flash("This person doesn't exist in our database!")
    return render_template('layout.html', score1=score1)

HTML file
  <form action="{{ url_for('layout') }}" method="post">

Tyler

        {{ score1.score }}

      <button type="button">+1</button>

  </form>

Any help is appreciated. Thank you.
Edit: updated view and HTML. Same issue.

A: Your two view functions are mapped to the same route; but a URL can only be served by one view.
Either map your increaseScore1 function to a different route, or combine the logic in one function which checks if the method is POST and updates the score if so, otherwise just displays it.


text:
Q: Error: Content Security Policy: The page's settings blocked the loading of a resource I've been trying to move a simple program I made in jQuery/HTML to a Firefox WebExtension for easy deployment. The error I am getting is:
Content Security Policy: The page's settings blocked the loading of a resource at https://code.jquery.com/jquery-1.12.4.js ("script-src moz-extension://ef8f1295-1912-4912-ab2e-121053b6781a").

I'm sure I'm just not doing the manifest.json file right, but for the life of me I don't know where:
{
  "description": "Makes tasks from different underwriters uniform",
  "manifest_version": 2,
  "name": "Task Creator",
  "version": ".5",
  "permissions": [
    "http://*/*", "tabs", "https://*/*"
  ],

  "icons": {
    "48": "icons/page-48.png"
  },
  "web_accessible_resources": [
    "style/popUpStyle.css",
    "script/popUpTask.js",
    "script/logicTaskFiller.js",
    "js/autosize.js",
    "style/https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css",
    "js/https://code.jquery.com/jquery-1.12.4.js",
    "js/https://code.jquery.com/ui/1.12.1/jquery-ui.js"
  ],

  "background": {
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icons/page-32.png"
  }
}

A: By default, extensions cannot load scripts, or other object resources, from the Internet. All CSS and JavaScript content used by your extension should be part of the extension package.
(This documentation is from Chrome, but the exact same policies apply to Firefox WebExtensions.)
It's possible to relax these restrictions somewhat, but this should generally be avoided -- loading resources from a remote server will make your extension fail to work properly if the user does not have Internet access, or if they are behind a restrictive firewall. Additionally, addons.mozilla.org will not accept addons which execute remotely hosted Javascript.


text:
Q: Navigation in a Lightbox2 doesn't work well on older IE versions (IE10 and lower) Navigation in a custom Lightbox2 is only clickable if I enter the element vertically, not horizontally. This only occurs on IE8 and lower.
The element that gets the focus if I enter the navigation horizontal is the "

I tried to fix this with z-index, but it didn't work

CSS
/* line 63, ../sass/lightbox.sass */
.lb-nav {
  position: absolute;
  top: 0px;
  left: 0;
  height: 100%;
  width: 100%;
  z-index: 10;
  margin-bottom: -150px;
}

/* line 71, ../sass/lightbox.sass */
.lb-container > .nav {
  left: 0;
}

/* line 74, ../sass/lightbox.sass */
.lb-nav a {
  outline: none;
}

/* line 77, ../sass/lightbox.sass */
.lb-prev, .lb-next {
  width: 40%;
  height: 100%;
  cursor: pointer;
  z-index: 20;
  /* Trick IE into showing hover */
  display: block;
}

/* line 84, ../sass/lightbox.sass */
.lb-prev {
  margin-left: 30px;
  left: 0;
  float: left;
}
/* line 87, ../sass/lightbox.sass */
.lb-prev:hover {
    background: url("../images/lightbox/links-blauw.png") left 48% no-repeat;
}

/* line 90, ../sass/lightbox.sass */
.lb-next {
  margin-right: 30px;
  right: 0;
  float: right;
}
/* line 93, ../sass/lightbox.sass */
.lb-next:hover {
  background: url("../images/lightbox/rechts-blauw.png") right 48% no-repeat;
}

HTML (appended in lightbox JS)

                    Venster sluiten

A: You have to add a transparent background image to the lb-prev and lb-next containers, so they can trigger the hover.
.lb-prev, .lb-next {
width: 49%;
height: 100%;
cursor: pointer;
/* Trick IE into showing hover */
display: block;
z-index:101;
position:relative;
background-image:url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== );
}


text:
Q: Drupal6: In theme_preprocess_page(&$vars), where do $vars come from? (How to manipulate breadcrumb) I want to remove the breadcrumb when it's just one entry ("Home"). I'm in my theme's theme_preprocess_page(&$vars) function. $vars['breadcrumb'] is available, but it's just HTML. This is a bit to clumsy to work with. I'd rather get it as an array of items in the breadcrumb list, and do something like this:
if (count($breadcrumb) == 1) {
    unset($breadcrumb);
}

Where does $vars come from? How can I override the code creating it originally?

A: A $vars array is passed on between all preprocess functions. In case of the _preprocess_page functions, most of the values in $vars are created in template_preprocess_page (see http://api.drupal.org/api/function/template_preprocess_page/6). In that function, you'll see:
  $variables['breadcrumb']        = theme('breadcrumb', drupal_get_breadcrumb());

Here, drupal_get_breacrumb returns an array of breadcrumb elements, which is then themed by the theme_breadcrumb() function (or its override).
The easiest way to get what you want is to override the theme_breadcrumb function. To do that, you take the original theme_breadcrumb function (http://api.drupal.org/api/function/theme_breadcrumb/6), copy it to your template.php, replace 'theme' in the function name with the name of your theme and alter the code so it looks like this:
function THEMENAME_breadcrumb($breadcrumb) {
  if (count($breadcrumb) > 1) { // This was:  if (!empty($breadcrumb))
    return '
'. implode(' » ', $breadcrumb) .'
';
  }
}

For a better understanding of Drupal theme overrides and preprocess functions, see About overriding themable output and Setting up variables for use in a template (preprocess functions).


text:
Q: WAN security and port forwarding for IoT I have an esp8266 board that I've set up as a little server. To access it over the web (first forays into making a smart home and IoT) I've used no-ip to deal with dynamic DNS and opened up WAN access with port forwarding (80) on my home router. My question is how secure is this? I've tried only allowing a certain IP address but smart phones use dynamic IPs.

A: When dealing with TCP/IP connections, there are 65535 ports available to listen on.
Generally, port 80 is used for standard HTTP connections, while port 443 is used for HTTPS.
If you need to open up a common port to the world, be ready to server any request that is made to it.
Another option would to be changing the port you are listening on, this should be a number between 5000 and 65535. By randomizing this port, only you will know how to connect. ( you will need admin access to bind to any port < 1024 )
If you wtill want to server standard HTTP data, the URL would simply be

http://my.no-iphost.com:55933/my_script

Where 55933 is my secret port.


text:
Q: DAX Query to get average of a column within the same table We have a table named MetricsTable which has columns A1 and Group simply.
We want to add a calculated column AvgA1 to this table which calculates the average of column A1 filtered by the value of Group . What should be our DAX query? The point is that we want to claculate the average from the values within the same table.
| id | A1| Group | AvgA1
| -- | --- | --- ------| ----
| 1  | 20  | Group1| 20
| 2  | 10  | Group2| 30
| 3  | 50  | Group2| 30
| 4  | 30  | Group2| 30
| 5  | 35  | Group3| 35
Regards

A: Likely you should use a measure and put that measure into a pivot table's 'Values' section:
AverageA1:=
AVERAGE( Metrics[A1] )

Then it will be updated based on filter and slicer selections in the pivot table, and subtotaled appropriately across various dimension categories.
If it strictly needs to be a column in the table for reasons not enumerated in your question, then the following will work:
AverageA1 =
CALCULATE(
    AVERAGE( Metrics[A1] )
    ,ALLEXCEPT( Metrics, Metrics[Group] )
)

CALCULATE() takes an expression and a list of 0-N arguments to modify the filter context in which that expression is evaluated.
ALLEXCEPT() takes a table, and a list of 1-N fields from which to preserve context. The current (row) context in the evaluation of this column definition is the value of every field on that row. We remove the context from ALL fields EXCEPT those named in arguments 2-N of ALLEXCEPT(). Thus we preserve the row context of [Group], and calculate an average across the table where that [Group] is the same as in the current context.


text:
Q: Python like Slicing operation in c++ I have following code, where 'Snap.JPG' is a RGB format type.
import cv2

img = cv2.imread("./Snap.JPG")

img[:,:,:2] = 255

cv2.imshow("Img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

I want to convert this code into c++. What is the fastest way to implement img[:,:,:2] = 255 part of the code? Channel splitting and merging is one of the options i know, but is there any smarter way to do slicing in c++?
Edit:
Apologies, i should have mentioned what i want in the output. I need a fading effect, because i wanted to overlay a drawing on top of it.

A: This is an example of how to change pixels:
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

int main(int argc, char** argv) {
    cv::Mat src_image = cv::imread("image.jpg", CV_LOAD_IMAGE_COLOR);

    if(!src_image.data) {
        std::cout << "Error: the image wasn't correctly loaded." << std::endl;
        return -1;
    }

    cv::Mat image = src_image.clone();

    // We iterate over all pixels of the image
    for(int r = 0; r < image.rows; r++) {
        // We obtain a pointer to the beginning of row r
        cv::Vec3b* ptr = image.ptr<cv::Vec3b>(r);

        for(int c = 0; c < image.cols; c++) {
            ptr[c] = cv::Vec3b(255, 255, ptr[c][2]);
        }
    }

    cv::imshow("Inverted Image", image);
    cv::waitKey();

    return 0;
}

A: Thanks for @Manuel's reply, it works quite well. but i could achieve the same result with faster speeds. I have added my code snippets inline your code.
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <iomanip>

int main(int argc, char** argv) {
    clock_t start, end;

    cv::Mat src_image = cv::imread("Snap.JPG", CV_LOAD_IMAGE_COLOR);

    if(!src_image.data) {
        std::cout << "Error: the image wasn't correctly loaded." << std::endl;
        return -1;
    }

    /* 1st method */
    cv::Mat image = src_image.clone();

    start = clock();
    // We iterate over all pixels of the image
    for(int r = 0; r < image.rows; r++) {
        // We obtain a pointer to the beginning of row r
        cv::Vec3b* ptr = image.ptr<cv::Vec3b>(r);

        for(int c = 0; c < image.cols; c++) {
            ptr[c] = cv::Vec3b(255, 255, ptr[c][2]);
        }
    }
    end = clock();

    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
    std::cout << "Time taken by 1st method : " << std::fixed << time_taken << std::setprecision(5);
    std::cout << " sec " << std::endl;

    /* 2nd Method */
    start = clock();
    src_image = src_image | cv::Scalar(255, 255, 0);
    end = clock();

    time_taken = double(end - start) / double(CLOCKS_PER_SEC);
    std::cout << "Time taken by 2nd method : " << std::fixed << time_taken << std::setprecision(5);
    std::cout << " sec " << std::endl;

    bool isEqual = (sum(src_image != image) == cv::Scalar(0,0,0,0));
    if (isEqual)
    {
        std::cout << "\nIdentical Mats !" << std::endl;
    }

    cv::imshow("Inverted Image", image);
    cv::waitKey();

    return 0;
}

output is following:
Time taken by 1st method : 0.001765 sec
Time taken by 2nd method : 0.00011 sec

Identical Mats !


text:
Q: In usb C to audio jack systems, is the DAC in the dongle or in the host? I'd like to design my usb-c audio preamp, but that would be possible only if the analog audio comes directly from the phone, so that my piece of hardware can take the power supply from the usb-c and spit out an amplified version of that signal
I looked around the internet and found a lot of contrasting information.
Do the dongles receive a digital stream and convert it to analog audio, or are the dongles just a mechanical conversion between connectors and the dac is in the system (typically a phone)?
What is the industry standard practice?  What does the USB-IF say about audio via usb-c?  How an host can recognize when an analog output is required?

A: It depends.  There are a few different ways to send audio over USB-C.
The first way is the same way USB to Audio dongles work right now:  The dongle is an actual USB device itself, one that supports one of the USB Audio profiles.  This is a DAC that appears on a USB bus as an audio device, and will work just as readily on a desktop or any other device with USB-C and an OS that supports it.
So, in this case, the DAC is very much in the dongle itself.  It's more like a USB 'sound card', and will often be a little bulkier and more expensive.
However, for most phones with a USB-C to 3.5mm dongle, the DAC is in the host device, meaning that the signals going out of the USB-C port and into the dongle are, in fact, analog ones.  They're the exact same signals that get sent through any other 3.5mm headphone jack, and generated in the exact same way, by some kind of DAC inside the device with the USB C port.  So in most cases, yes, the dongle is merely an electrical/mechanical connection that is adapting a USB-C port to a 3.5mm audio jack directly.
It would not make much sense to use a dongle that had an entire DAC and USB audio profile chipset inside it, as this would incur a good deal of cost, consume more power, and be physically bulkier.  If the device is a phone, then it already must have a DAC of some kind or it would be unable to drive the speaker that lets you hear the person on the other end of a phone call.  These usually come in the form of single chip solutions and will include multiple input and output channels, so this can be done effectively for free.
I do not know why, but there seems to be a ton of misinformation regarding this online which it sounds like you've likewise encountered.  What I see most often is something along the lines of 'USB-C is digital audio only' or 'USB-C doesn't have any audio pins'.
...and neither statement is true, at least according to the USB-IF, the only body who has any authority on the matter.

Or just download the official PDF (warning, 20MB .zip) and scroll down to page 213, there is a whole section on it.


text:
Q: Progressive Company: Do you need Active Directory for a 100 person company? We are a progressive company (about 100 employees) and would like to hear other's input.
In today's XaaS/cloud world where most of the services and applications are in the cloud (file sharing, calendar, crm, cms, erp, email/gmail, etc...) do you still need Active Directory?
The entire notion of getting Windows Servers to manage single sign on, software updates, restrict user access to their machines, seems all very IT 1.0.
If you assume that 80+% of your applications/services are in the cloud, and you run a mixed environment (win, mac, linux) what value does Active Directory, and the rest of the Windows stack really bring?
Other than employ more Windows IT VARs/Consultants?
Aren't these desktops basically just thin clients that have a web browser?   Sure you will have some applications such as MS Office, or perhaps some Graphical tools like Photoshop or alike, but other than that most everything that is "mission critical" is in the cloud.  These desktops are essentially disposable.
Why would one need Active Directory?

A: You don't need it —  you never did, there were always other ways — but you will find that Active Directory is exceptionally helpful at keeping 100 workstations operational, efficient, and working together. You will also find there are some things you do need, such as dns and dhcp services, that Active Directory makes very easy.
Once you're up past about 50 machines, your name resolution and dhcp services aren't going to live on a consumer level cable modem any more. You're gonna need a old-school server of some kind to handle this. Active Directory can do that for you.  Of course, so could OS X server, CentOS, or a few other free linux alternatives.
What Active Directory is really good at for a Windows shop that the alternatives don't do yet is that, as an administrator, when you join your computers to the domain a random person off the street can't just walk up and log in to one of your employees machines. There's a certain amount of real security there. This isn't a whole lot out of the box, as there are tools that can trivially reset passwords, but if you're willing to go with whole-disk encryption, which AD can enforce, you can get there. At the same time, as an administrator you can walk up to any machine you're responsible and log in with an account that will grant you administrator privileges on the machine. Your users will be able to log in to any computer you control (including the brand new one you just gave them because they broke their old one) and easily find their old files. If you want to restrict the users to only their assigned computer, that's easy to do also.
As the company grows, this kind of segmentation will become more important. Most data breaches are inside jobs, and one of the functions of IT that is important is to help prevent this kind of leak.


text:
Q: Filtering nested arrays and selecting specific properties using az cli JMESPath I am trying to query a response from the following az command:
az provider operation show --namespace Microsoft.KeyVault

I want to query all operations that relate to secrets to be able to build a custom role for a RBAC enabled key vault. This is a short excerpt from the entire response:
{
    "displayName": "Microsoft Key Vault",
    "id": "/providers/Microsoft.Authorization/providerOperations/Microsoft.KeyVault",
    "name": "Microsoft.KeyVault",
    "operations": [
      {
        "description": "Registers a subscription",
        "displayName": "Register Subscription",
        "isDataAction": false,
        "name": "Microsoft.KeyVault/register/action",
        "origin": null,
        "properties": null
      },
      {
        "description": "Unregisters a subscription",
        "displayName": "Unregister Subscription",
        "isDataAction": false,
        "name": "Microsoft.KeyVault/unregister/action",
        "origin": null,
        "properties": null
      }
    ],
    "resourceTypes": [
      {
        "displayName": "Secret",
        "name": "vaults/secrets",
        "operations": [
          {
            "description": "View the properties of a secret, but not its value.",
            "displayName": "Read Secret Properties",
            "isDataAction": false,
            "name": "Microsoft.KeyVault/vaults/secrets/read",
            "origin": null,
            "properties": null
          },
          {
            "description": "Creates a new secret or updates the value of an existing secret.",
            "displayName": "Write Secret",
            "isDataAction": false,
            "name": "Microsoft.KeyVault/vaults/secrets/write",
            "origin": null,
            "properties": null
          }
        ]
      }
    ],
    "type": "Microsoft.Authorization/providerOperations"
}

I would like to extract the description as well as the name from the object in the array resourceTypes where resourceTypes.name=="vaults/secrets".
I am trying to build this gradually, but I am stuck on even filtering out this object. This is where I'm at, and I've derived this from the JMESPath documentation on filtering arrays:
az provider operation show --namespace Microsoft.KeyVault --query "[?resourceTypes.name=='vaults/secrets']"

This is just empty however.
The end result I am after is a tabular output with the description and name from each operation within the operations array.
Any help would be greatly appreciated.

A: The issue in your current query is that doing [] would assume you address an array at the root of your JSON, when what you have at the root of your JSON is a map:
{
  "resourceTypes": [
    {
      "name": "vaults/secrets",
    }
  ]
}

So, the beginning of the query to address your JSON should rather be
resourceTypes[?name == 'vaults/secrets']

While your query would work on a JSON looking like:
[
  {
    "resourceTypes": {
      "name": "vaults/secrets",
    }
  }
]

From there on, you need to query the operations array, so operations[] and do a multiselect hash to trim down the map to the fields you are looking for.
We end with the query:
resourceTypes[?name == 'vaults/secrets']
  .operations[]
  .{
    description: description,
    name: name
  }

And, lastly, to format it in table, you can use the table output format of the Azure client.
We end up with the line:
az provider operation show \
  --namespace Microsoft.KeyVault \
  --query "resourceTypes[?name == 'vaults/secrets']
    .operations[]
    .{
      description: description,
      name: name
    }" \
  --out table


text:
Q: How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a' How to add a check constraint in django model that a field value startwith letter 'c' or 'e' or 'a'
like the bellow SQL check constraint
CREATE TABLE Account (
    account_no varchar(12),
    FirstName varchar(255),
    Age int,
    City varchar(255),
    CONSTRAINT CHK_Person CHECK (SUBSTR(account_no,1,1) = 'c' OR SUBSTR(account_no,1,1) = 'e' OR SUBSTR(account_no,1,1) = 'a' )
);

i try with meta class of model. but i don't know how to specify the or case
  class Meta:
        constraints = [
            CheckConstraint(
                check = Q(account_no___startswith=F('')),
                name = 'check_start_wtih',
            ),
        ]

A:   class Meta:
        constraints = [
            CheckConstraint(
                check = Q(account_no___startswith='c') | Q(account_no___startswith='e') | Q(account_no___startswith='a'),
                name = 'check_start_wtih_cea',
            ),
        ]


text:
Q: Is it OK to create 2 instances of C# MongoClient connecting to the same replica set? I used to create an instance of MongoClient from the official driver and register it in the DI as a singleton. But now because of design issues, I have to create another MongoClient instance in the other place to connect to the very same Replica Set.
Are there any potential problems? Do the two instances will use the same connection or create two separate connections?
Project is written in ASP.NET Core 3.1
MongoDB driver's version 2.8
MongoDB server uses 4.2

A: Currently, if all client options are the same, it will work since the underlying mongo client's data is stored on the cluster level. And as it was mentioned in the comments above, mongoClient constructor tries to retrieve this data from the static storage each time when you create a new client.
However, there is a restriction, your MongoClientSettings should not contain the configured ClusterConfigurator option. Otherwise, it will lead to creating two different clusters with all related stuff for example connection pools.
Also, see Re-use section here: https://mongodb.github.io/mongo-csharp-driver/2.10/reference/driver/connecting/


text:
Q: find all permutations of non-overlapping polygons in R (sp or sf objects) I have a spatial object (say a Multipolygon in sf or a SpatialPolygons in sp) and I want to find all the possible permutations of non-overlapping features. Here are some diagrams that illustrate what I am after. Let's say I have the following polygons.
library(sf)

# points
a <- st_as_sf(data.frame(lon = c(1,2,3.5,3,6), lat = c(0,1,0,1.5,-3)), coords = c('lon', 'lat'))

# circles
b <- st_buffer(a, 1)

# colors
cols = c('grey', 'red', 'green', 'yellow', 'blue')
cols = adjustcolor(cols, alpha.f = .5)

# plot
plot(b, col = cols)

I am after a routine that would create the following 3 objects whose plots would look like:
a.

b.

c.

Ideally, the routine would also allow for a threshold on the intersection of polygons.
I think whatever routine I could write myself would take prohibitively long even for moderate-sized objects (say, 150 polygons, yielding lots of possible combinations). I was hoping that someone have already figured this problem out.

A: M <- st_overlaps(b, sparse = FALSE) * 1
(M <- 1 - M)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    1    1    1
# [2,]    0    1    0    0    1
# [3,]    1    0    1    0    1
# [4,]    1    0    0    1    1
# [5,]    1    1    1    1    1
colnames(M) <- c('grey', 'red', 'green', 'yellow', 'blue')

library(igraph)
A <- graph_from_adjacency_matrix(M)
max_cliques(A)
# [[1]]
# + 2/5 vertices, named, from dae1f9f:
# [1] red  blue
#
# [[2]]
# + 3/5 vertices, named, from dae1f9f:
# [1] grey   blue   yellow
#
# [[3]]
# + 3/5 vertices, named, from dae1f9f:
# [1] grey  blue  green
cliques(A)
# ...
# Omitted, 13 cliques in total

First we use st_overlaps to get a kind of adjacency matrix, M, where two polygons are adjacent in this graph if they overlap in your data. But actually we are going to need 1 - M, where two polygons are adjacent in this new graph if they don't overlap. That's useful because what you are looking for then corresponds to (maximal) cliques in this graph:

cliques find all complete subgraphs in the input graph, obeying the
  size limitations given in the min and max arguments.
max_cliques finds all maximal cliques in the input graph. A clique in
  maximal if it cannot be extended to a larger clique. The largest
  cliques are always maximal, but a maximal clique is not neccessarily
  the largest.

In this case cliques are sets of polygons where none of the polygons overlap with any of the rest.
Also, as to apply this to sp objects, you only need to compute a corresponding M. I believe that over helps with that.
Bonus
As to add the possibility for thresholds, we just need to recompute M.
aux <- function(x) if (length(x) == 1) x else 0
M <- matrix(1, nrow(a), nrow(a))
for(i in 1:nrow(a))
  for(j in 1:nrow(a))
    M[i, j] <- aux(st_area(st_intersection(b[i, 1], b[j, 1])))
diag(M) <- 0

Then, for instance, if we count two polygons as intersecting only if the intersection area is greater than 0.2, we run
M <- 1 * (M > 0.2) # Getting threshold-overlaps
M <- 1 - M # The needed adjacency matrix


text:
Q: por que o FloatingActionButton está transparente? Estou com um problema depois que atualizei a lib support.design:22.2.0 para 23.0.1, o floatingActionButton passou a ser transparente quando executado na API 10.
Aqui está o código:
<android.support.design.widget.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    app:borderWidth="0dp"
    android:src="@drawable/ic_mode_edit_white_24dp"
    app:layout_anchor="@id/appBar"
    app:layout_anchorGravity="bottom|right|end"
    android:elevation="2dp"
    android:id="@+id/btnClick"
    app:fabSize="normal"
    android:backgroundTint="@color/colorFAB"
    android:layout_gravity="right|bottom" />

A: Me parece que isso é um bug do Android 10 que foi corrigido na versão 14, de uma olhada na issue #183315 mas que apareceu durante a versão 23.0.0 da design library.
Existem duas soluções, uma simples e outra que depende de uma sobreescrever o comportamento do FAB.
1) Voltar para a versão 22.2.1.
As vezes isso é comum (infelizmente). Se existe um bug da biblioteca, e que não tem solução, basta regredir se não usar nenhuma função específica da versão.
2) Criar uma classe que herda do FloatActionButton da design library como um "workaround", sugerido pelo comentário #9:
public class TintFloatingActionButton extends FloatingActionButton implements TintableBackgroundView {

    static final int[] PRESSED_ENABLED_STATE_SET = {android.R.attr.state_pressed,
            android.R.attr.state_enabled};
    static final int[] FOCUSED_ENABLED_STATE_SET = {android.R.attr.state_focused,
            android.R.attr.state_enabled};

    private static final int[] TINT_ATTRS = {
            android.R.attr.background
    };

    private TintInfo mBackgroundTint;

    public TintFloatingActionButton(Context context) {
        super(context);
    }

    public TintFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TintFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (TintManager.SHOULD_BE_USED) {
            TintTypedArray a = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                    TINT_ATTRS, defStyleAttr, 0);

            if (a.hasValue(0)) {
                setSupportBackgroundTintList(createColorStateList(a.getResourceId(0, -1)));
            }

            a.recycle();
        }
    }

    private static ColorStateList createColorStateList(int selectedColor) {
        final int[][] states = new int[3][];
        final int[] colors = new int[3];
        int i = 0;

        states[i] = FOCUSED_ENABLED_STATE_SET;
        colors[i] = selectedColor;
        i++;

        states[i] = PRESSED_ENABLED_STATE_SET;
        colors[i] = selectedColor;
        i++;

        // Default enabled state
        states[i] = new int[0];
        colors[i] = Color.TRANSPARENT;
        i++;

        return new ColorStateList(states, colors);
    }

    @Override
    public void setSupportBackgroundTintList(ColorStateList tint) {
        if (mBackgroundTint == null) {
            mBackgroundTint = new TintInfo();
        }
        mBackgroundTint.mTintList = tint;
        mBackgroundTint.mHasTintList = tint != null;
        applySupportBackgroundTint();
    }

    @Nullable
    @Override
    public ColorStateList getSupportBackgroundTintList() {
        return mBackgroundTint != null ? mBackgroundTint.mTintList : null;
    }

    @Override
    public void setSupportBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
        if (mBackgroundTint == null) {
            mBackgroundTint = new TintInfo();
        }
        mBackgroundTint.mTintMode = tintMode;
        mBackgroundTint.mHasTintMode = tintMode != null;
        applySupportBackgroundTint();
    }

    @Nullable
    @Override
    public PorterDuff.Mode getSupportBackgroundTintMode() {
        return mBackgroundTint != null ? mBackgroundTint.mTintMode : null;
    }

    private void applySupportBackgroundTint() {
        if (getBackground() != null && mBackgroundTint != null) {
            TintManager.tintViewBackground(this, mBackgroundTint);
        }
    }
}

Código completo neste gist: https://gist.github.com/arturgaleno/5cca1934ed324bd2d9a7


text:
Q: React Router v4 not loading component For some reason, my web app is not directing to the component whenever I go to the parameters. Specifically, it is not going to the Battle component.
Here is what the navigation looks:
    import React from 'react';
import Header from './components/Header/Header';
import SelectPlayers from './pages/SelectPlayers/SelectPlayers';
import Popular from './pages/Popular/Popular'
import Battle from './pages/Battle/Battle'

import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

function App() {
  return (
      <Router>

              <Switch>
                  <Route exact path={'/'} component={Popular}/>
                  <Route exact path={'/battle/select-player'} component={SelectPlayers} />
                  <Route exact path={'/results?playerOne=:playerOne&playerTwo=:playerTwo'} component={Battle} />
              </Switch>

      </Router>
  );
}

export default App;

In the SelectPlayers component, whenever the user presses a button it runs:
    import React, {useState} from 'react';

function SelectPlayers(props) {

    const [playerOne, setPlayerOne] = useState('');
    const [playerTwo, setPlayerTwo] = useState('');

    function setPlayerName(event, player){

        if (player === 1){
            setPlayerOne(event.target.value)

        } else if (player === 2) {
            setPlayerTwo(event.target.value)
        }
    }

    function goToBattle(event){

        event.preventDefault();

        props.history.push(`/results?playerOne=${playerOne}&playerTwo=${playerTwo}`)

    }

    return (

Player One

                    <input onChange={(e) => setPlayerName(e, 1)} type="text" placeholder={'github username'} className={'input-reset pa1 w-100 h2 ba b--black br2'}/>

Versus

Player Two

                    <input onChange={(e) => setPlayerName(e, 2)}  type="text" placeholder={'github username'} className={'input-reset pa1 w-100 h2 ba b--black br2'}/>

                    <button onClick={(e) => goToBattle(e)} className={'input-reset pa1 h2 fw1 bg-black white ba w-100 b--black br2'}>Battle</button>

    );
}

export default SelectPlayers;

On the Battle component, I write some console.log stuff just to check if the Component loaded. However, whenever I go to that parameter, none of the code in my componentDidMount is running. I don't see any of the console.logs I wrote in componentDidMount in my developer console. Here is the component:
import React, {Component} from 'react';

class Battle extends Component {

    constructor(props){
        super(props)
    }

    componentDidMount() {

        console.log('runngins');

        console.log(this.props);
    }

    render() {
        return (

        );
    }
}

export default Battle;

You can see the code at this repo: https://github.com/tarekgabarin/github_compete
It would be greatly appreciated if anyone helped me.

A: As per your new comment that code is working without queryset, looks like there is some problem with your queryset parameters.
As suggested in comment box, don't define Router with queryset.
<Switch>
              <Route exact path={'/'} component={Popular}/>
              <Route exact path={'/battle/select-player'} component={SelectPlayers} />
              <Route exact path={'/results'} component={Battle} />
          </Switch>

In your SelectPlayers component, navigate to next page with queryset.
props.history.push("/results?playerOne=" +playerOne+ "&playerTwo=" +playerTwo)

On Battle component, use (query-string) to read the parameter. For example:
const values = queryString.parse(this.props.location.search);
const player_one = values.playerOne
const player_two = values.playerTwo

Please note that my above code is not tested.
Thanks


text:
Q: Position polyfill sticky not working correctly with columns I am trying to make my sidebar sticky when the navbar touches the sidebar. However, it does not seem to be working for some reason I don't know if it is an issue with flexbox but I have no idea why it does not become sticky.
My HTML:

Nav

Tell me tommorrow

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Lorem ipsum, dolor sit amet consectetur adipijjsicing elit. Voluptates error aperiam ratione dolorem amet sequi iste et deserunt nisi laudantium, architecto quaerat necessitatibus suscipit est! Fugit illo vero et odio?

Sidebar

          This is a link
          This is a link
          This is a link

My CSS/Sass:
html,
body{
  padding: 0;
  margin: 0;
}
.container{
  width: 90%;
  margin: 0 auto;
  max-width: 1107px;
  position: relative;
}
.nav{
  position: fixed;
  width: 100%;
  top:0;
  background-color: grey;
  height: 100px;
  z-index: 9;
  h1{
    margin: 0;
  }
}

.m01{
  margin-top: 150px;
  &__grid{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    &__text{
      width: calc(70% - 40px);

    }
    &__sidebar{
      width: calc(30%);
    }
  }

  &__sidebar{
    position: sticky;
    &__links{
      display: block;
    }
  }
}

The codepen to my problem is https://codepen.io/mrsalami/pen/oNXQYOx. Any help will be appreciated.

A: Add offset on your sidebar, due to your nav.
&__sidebar{
    position: sticky;
    top: 100px;
    &__links{
      display: block;
    }
  }


text:
Q: Why does +!{}[true] output 1 in javascript I was watching this video
http://www.youtube.com/watch?v=Trr95ij1358
And Mr Baranovskiy emphasizes that javascript developers
should know what this evaluates to:
+!{}[true]
So I gave it a shot.
It outputs 1
Can anyone give me a reason for this?

A: This gets read as
cast the negated (bool cast) value of the property accessor of {} identified by the toString value of true, into a number
So, it becomes
+!{}["true"]
+!undefined
+true
1


text:
Q: What are these PCB calibration standards? I found these shunt resistors in a paper that uses them to calibrate AC equipment for EIS testing. They used the "frequency dependent complex impedance response" of these standards to calculate the error coefficients.
I'm interested in implementing the same method myself but am having trouble finding these. I tried looking up PCB calibration standard, PCB shunt resistor but couldn't find anything with known inductive properties.
Not sure if these are custom PCBs or if they are commercially available and would really appreciate it if someone could point me to where I can find/make some of these.

A: The term "standard" is not the thing that you first thought of, such as IEC-... or EN-... . Yes, sounds confusing.
A standard is basically a reference for error-corrected measurements and measurement devices. All of its useful properties (complex impedance, delay, thermal-related, loss factor, etc.) are known and don't change from measurement to measurement. So it can be used as a reference.
A standard can be a SHORT (Zero Ohms), OPEN (Infinite Ohms), LOAD, etc. But in practice we know that nothing can be exactly zero Ohms, or infinite Ohms (because we don't know what number is) or 10.0000000000000000000000000000000000....00 milliohms.
So, the standards are created to have parameters which are "constant" and "close enough to desired value", just to define the zero, max, and error of a measurement and/or a device i.e. to say, for example, "0.003 milliohms is my zero". Hence the name standard.


text:
Q: Why is a slice category a category? I don't understand why the Hom-sets in a slice category are disjoint.
Let $C$ be a category and $A$ an object of $C$, then the slice category $C_{A}$ has as objects all morphisms $f\colon Z \to A $ where $Z$ is an object of $C$.
For two objects of $C_A$, $f_1 \colon Z_1 \to A$ and $f_2 \colon Z_2 \to A$,  the elements of $Hom_{C_A}(f_1,f_2)$ are given by the elements of $\sigma \in Hom_{C}(Z_1,Z_2)$ that satisfy $f_1=f_2 \circ \sigma$.
The definition of a category entails that $Hom_{C_A}(f,g)$ and $Hom_{C_A}(f',g')$ have to be disjoint unless $(f,g)=(f',g')$.
Now let $Z$ be an object in $C$ and let $f_1,f_2 \in Hom_{C}(Z,A)$ such that $f_1 \neq f_2$
Then the identity morphism $id_Z \in Hom_C(Z,Z)$ satisfies $f_1=f_1\circ id_Z$ and $f_2=f_2\circ id_Z$.
Hence $id_Z \in Hom_{C_A}(f_1,f_1)$ and $id_Z \in Hom_{C_A}(f_2,f_2)$, implying that $C_A$ is not a category.
What am i getting wrong here? I've had this problem since i read the definition of  a slice category in Aluffi's book, which i find a bit unclear.
At first i thought that maybe the morphisms contain the information of their source and target and that instead of elements in $Hom_C(f_1,f_2)$ they would be something like tuples of the form $(f_1,f_2,\sigma)$ where $\sigma \in Hom_C(f_1,f_2)$.
But according to the definition given on Wikipedia for example (https://en.wikipedia.org/wiki/Comma_category#Definition), this doesn't seem to be the case.

A: There are two ways you can define the morphism part of a category $\mathcal{C}$. Either:

*

*Define a set $\mathrm{mor}(\mathcal{C})$ of morphisms and functions $\mathrm{dom}, \mathrm{cod} : \mathrm{mor}(\mathcal{C}) \to \mathrm{ob}(\mathcal{C})$; or

*Define sets $\mathrm{Hom}_{\mathcal{C}}(A,B)$ for each $A,B \in \mathrm{ob}(\mathcal{C})$.

To translate from the first definition into the second, you can define $\mathrm{Hom}_{\mathcal{C}}(A,B)$ to be $\{ f \in \mathrm{mor}(\mathcal{C}) \mid \mathrm{dom}(f) = A \text{ and } \mathrm{cod}(f) = B \}$. Then the hom sets are automatically disjoint since the domain and codomain are encoded in the morphism.
In the second case, however, the hom sets don't need to be disjoint, since we haven't explicitly required disjointness of the hom sets. Thus the second case is more general than the first case. This is why some people require hom sets to be disjoint—namely, so that $\mathrm{dom}(f)$ and $\mathrm{cod}(f)$ are well-defined.
However, you can always turn a specification of a category without disjoint hom sets into a specification of a category with disjoint hom sets, by replacing $\mathrm{Hom}_{\mathcal{C}}(A,B)$ by $\{A\} \times \{ B \} \times \mathrm{Hom}_{\mathcal{C}}(A,B)$, so that a morphism $f : A \to B$ is then 'officially' a triple $(A,B,f)$.
This is equivalent to defining $\mathrm{mor}(\mathcal{C})$ to be the disjoint union $\bigsqcup\limits_{(A,B) \in \mathrm{ob}(\mathcal{C}) \times \mathrm{ob}(\mathcal{C})} \mathrm{Hom}_{\mathcal{C}}(A,B)$ and taking $\mathrm{dom}$ and $\mathrm{cod}$ to be the respective projection maps to $\mathrm{ob}(\mathcal{C})$.
Under this encoding, a morphism $\sigma : (f_1 : Z_1 \to A) \to (f_2 : Z_2 \to A)$ in $\mathcal{C}/A$ is 'officially' a triple $(f_1,f_2,\sigma)$ where $\sigma : Z_1 \to Z_2$ and $f_2 \circ \sigma = f_1$. The morphisms $\mathrm{id}_Z : f_1 \to f_1$ and $\mathrm{id}_Z : f_2 \to f_2$ are then 'officially' triples $(f_1,f_1,\mathrm{id}_Z)$ and $(f_2,f_2,\mathrm{id}_Z)$, so you don't have any issues.
However, in practice, it's easier to define $\mathrm{Hom}_{\mathcal{C}}(A,B)$ without worrying about whether the hom sets are disjoint, and rest easy with the knowledge that the hom sets could be made disjoint if you wanted them to be.


text:
Q: Unable to open fstream when specifying an absolute path I know this is rather laughable, but I can't seem to get simple C++ ofstream code to work.  Can you please tell me what could possibly be wrong with the following code:
    #include <fstream>

    ...

    ofstream File("C:\temp.txt");

    if(File)
       File << "lolwtf";

Opening the ofstream fails whenever I specify an absolute path.  Relative paths seems to work with no issues.   I'm really uncertain as to what the issue is here.

A: The problem is in your string, you are not escaping the backslash.
 ofstream File("C:\\temp.txt");

A: Even though Windows people seem to prefer the non-standard '\' character as a path separator, the standard '/' works perfectly and avoids annoying problems like this.
So, my advice is to stick to forward slashes...
std::ofstream File("C:/temp.txt");

A: Your path is invalid:
"C:\temp.txt"

The \ is escaping the "t" as a horizontal tab character, so the path value ends up as:
"C:    emp.txt"

What you want is:
"C:\\temp.txt"

or
"C:/temp.txt"


text:
Q: Collaboration from PlayN client with server I have written a game in PlayN, which has to communicate with a JavaEE-Server with Seam.
First of all I only need the game running in HTML5.
The current issue is the communication between the PlayN-client and the JavaEE-Server
1) First I tried to communicate over the PlayN.net() interface exchanging information using JSON. Since PlayN is running on port 8888 and the server on 8080 I correctly run into problems with the same-origin-policy.
2) Now I'm looking for a working solution. Which one would you recommend? Do you have other ideas?
a) I'm trying to work with RPC as described in How to handle RPCs in client-server PlayN game?
, using GWT-syncproxy.
b) I try that playN runs on the same port as the server i.e. 8080 - so I don't have problems with the same-origin-policy any more. Question: Can the HTML5 playN app run on the same port?
So when I start the JavaEE-Server using Eclipse it should also start the PlayN web application, both on port 8080, right?
Is this possible?
c) The most hacky solution (currently working): The server writes the JSON-String into a file and the playN client reads this file out.
What do you recommend? I'd like to implement solution 2, since it is the cleanest solution, but I don't know how hard it is and how it works.
Thanks for your help!

A: I think the problem is that you are "running" PlayN, separated from your Seam server.
If I understood you correctly, you execute the Maven task to run your game as HTML and on the other hand you run Jboss (or whatever Java EE server), what you should do is run
mvn package
which will create the war of the game, and then publish that war on your Java EE server, then you can use the PlayN.net package with no problems whatsoever, running in a single server

A: This is how we currently handle our client / server communication. We are using a stateless JavaEE architecture and provide everything as REST services. This allows us to scale horizontally by adding more servers and simply adding them to the cluster entry in the Glassfish config.
However due to missing reflection or a working JSON lib, it forces us to implement a toJson()method in every data transfer object BY HAND (be carfull with case sensitivity). We added our server project as a module to the PlayN metaproject and added the core as a dependency to the server. So you can place every DTO on the core project (which is quite awesome). Placing them on the server results in people trying to annotate the classes as entities, which will result in failure during the html build. I am currently thinking about adding a shared project to the build, like in GWT projects.
This is how we send data to the server (for this example without any abstraction, do yourself a favor and implement one):
private void loadMapFromServer() {
    SessionDto session = this.main.getSessionCtrl().getSessionMdl();

    PlayN.net().post("http://localhost:8080/server/rest/map/mapMdl",
        session.toJson(),
        new Callback<String>() {

            @Override
            public void onSuccess(String result) {
                mapMdl = new MapDto();
            }

            @Override
            public void onFailure(Throwable cause) {
                PlayN.log().error("fail " + cause.getMessage());
            }
        });
}

Notice how we bastardize the POST argument with session.toJson(). This is because of the missing MIME type feature and passing JSON strings via GWT will fail.
And this is how it looks on the server:
package com.fact.server;

//I also posted the imports, for clarity.
import com.fact.core.map.MapDto;
import com.fact.core.user.SessionDto;
import com.fact.server.game.map.MapCtrl;
import com.google.gson.Gson;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;

@Stateless
@Path("/map")
public class MapSrvs {

@Inject
Logger logger;

@Inject
MapCtrl mapCtrl;

Gson gson = new Gson();

@POST
@Path("/mapMdl/")
@Produces( MediaType.APPLICATION_JSON )
public MapDto getMapMdl(String sessionDtoStr) {
            //logger.info("map was requested: " + sessionDtoStr);

    // Use gson to deserialize the class. Jersey would do this, if PlayN
    // would allow to set a correct MIME type (and @Consumes was set).
    // We could simply write: getMapMdl(SessionDto sessionDto)
    SessionDto sessionDto = gson.fromJson(sessionDtoStr, SessionDto.class);
    if(sessionDto == null) {
        return null;
    }

    // [...] check for a valid session

    MapDto mapMdl = new MapDto();
    mapMdl.foo = "message from server";
    return mapMdl;
}
}

This would be a bit nicer, if PlayN would allow you to set the MIME type, so that you won't have to cast the String using Gson. However this works quite well. We use Jersey on the server side to handle all the REST stuff. To get it running I had to put the following into the web.xml:
<servlet>
    <!-- We need jersey for the REST stuff -->
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>
        com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.fact.server</param-value>
    </init-param>
    <init-param>
        <!-- This took me hours to find :(. It is needed to automatically
        map POJOs to JSON code. -->
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jersey-serlvet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Also Jersey is already included into the Java-EE-Api, so it works out of the box. I hope this helps. If anyone knows how to do client side JSON parsing , please look at this question: How do I convert a POJO to JSON in PlayN?


text:
Q: is there any script which can stop to show ALT="text" as a tooltip in IE 6 and 7? is there any script which can stop to show ALT="text" as a tooltip in IE 6 and 7?

A: I wouldn't worry too much about it. It's a known bug and it's fixed in IE8.

A: $('img').each(function (i, el) {
  if (!el.hasAttribute('title')) {
    el.setAttribute('title', '');
  }
});

That should give all images without a title attribute an empty one. I'm not sure if it will fix the problem for IE6 and IE7 but I think they support title and this might override it.

A: <!--[if IE]><script>for(i =0;i<document.images.length;i++){document.images[i].alt='';}</script><![endif]-->

at the end of the page should do it.

A: In IE before IE8 the only way to avoid the browser to show images alt text as tooltip are:

*

*not to use the alt attribute (which is not a good idea because it's not valid HTML and it's not good even for Google SEO and text readers that can not see your images).

*place in each image a title="" empty attribute.
In order to accomplish point (2) using a simple Javascript with no jQuery, you have to place this small piece of code before ending BODY tag, like this:
   <!--[if lt IE 8]>
      <script>
         for(var i = 0, imgs = document.images, len = imgs.length; i < len; ++i)
            if(!imgs[i].title)
               imgs[i].title = "";
      </script>
   <![endif]-->
</body>

You can write it in one line if you prefer.
The advantaghe of this code is that it does not screw up the alt tag attributes of your images, it simply sets the title attribute to empty string, unless a title attribute is already defined in this last case I suppose the title attribute was defined because you want to show whatever you wrote in title attribute as a tooltip (which is a cross-browser behaviour).

A: $$('img').set('alt', '');

No other way, apart from setting the title attribute.

A: You could do the following but it would be very intrusive (and a bit slow):
$('*').attr('alt', '');

A: Presumably for alt attribute, you just mean image elements?
$('img').removeAttr('alt');

You may also consider removing the title attribute from elements in the DOM
$('*').removeAttr('title');

A: Do screan reader run javascript? If not then why bother with this mod?
Setting alt to "" would hide the alt "tooltip" in IE < 8 which seems to be all you are after. Plus this should be done anyway for all image or else screen readers have a habit of of rendering out a default "image placeholder" speech. If you set it to blank then it won't bother and will skip it, ideal for images that are simply used for design rather than content.
Unfortunately there is no special flag or switch you can flick via JS or any other method to tell IE to behave any differently in this regard which is what I believe you are asking for.
An alternative is to switch any alts you find in images to be titles but this does not get rid of the tooltips, you just end up making them appear in all browsers then rather than just IE.
So the final fix is to simply clear all alt attributes in images (and there are scripts in other answers here that do just that). You asked the question but I think you should ponder about what it is you are trying to achieve and more importantly, why and is it that essential?


text:
Q: Visual Basic Mob AI Wander? Right now my mob just moves around randomly, I need it to walk in strait lines like 30 pixels then turn, but I don't really know where to start...
    Function mob()
        Application.DoEvents()
        Randomize()
        Dim value As Integer = CInt(Int((4 * Rnd()) + 1))
        If value = 1 Then
        ElseIf value = 2 Then
    If Me.mob2.Location.Y < 549 Then
        Me.mob2.Location = New Point(Me.mob2.Location.X, Me.mob2.Location.Y + 1)
    End If
        ElseIf value = 3 Then
    If Me.mob2.Location.X > 12 Then
        Me.mob2.Location = New Point(Me.mob2.Location.X - 1, Me.mob2.Location.Y)
    End If
        ElseIf value = 4 Then
    If Me.mob2.Location.X < 750 Then
        Me.mob2.Location = New Point(Me.mob2.Location.X + 1, Me.mob2.Location.Y)
    End If
        End If

End Function

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    mob()
End Sub


text:
Q: Android app debug apk does not ask for permissions on some devices On some devices, the app correctly asks permissions while sidloading. On others (Android 6.0), it does not ask permissions while sideloading at all. The permissions are listed in the manifest.xml (below) and work perfectly for some devices (Android 5.0). On other devices (Android 4.0, 6.0.1), it asks permissions as it should but does not seem to incorporate all of them. The popup below is an example of what happens when a button to send an sms is clicked.
I have only had limited testing and the problems seems to be a little different depending on which android version the device is running. That being said, it could be stemming from something different, I wouldn't know.
Does anyone know why this is happening?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.catalizeapp.catalize_ss25">

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="Catalize"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".LoginActivity"
        android:label="Catalize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.default_searchable"
            android:value="Contacts" />
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>
    <activity android:name=".Contacts" />

    <activity android:name=".Account"
        android:theme="@style/SuperCoolAppBarActivity"/>
        <meta-data android:name = "android.support.PARENT_ACTIVITY"
            android:value= ".Contacts"/>

    <activity android:name=".ReportBug">
        <meta-data android:name = "android.support.PARENT_ACTIVITY"
            android:value=".Contacts"/>
    </activity>
</application></manifest>

(IMAGE) When a button that should send a text message is clicked, this pops up instead of executing the action of the button

A: According to the documentation:
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
That's the reason why althought you have declared the permissions in your manifest file you still need to ask for them at runtime.
As a workaround you can set a minSdkVersion < 23, but also as the documentation says:
Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.
Also, according to the Permissions Best Practices you should test against both permission models to provide a better user experience.


text:
Q: PHP form creates a Postgresql entry when web page is opened. How can this be prevented? I have a php/html script to update my postgresql database. The form works alright, that is it inserts data into the database. Problem is that each time I open the web page to do an insert an empty entry is created into the database. I have tried to add a "SELECT setval(...)" to repair the sequence. This did have the effect of getting rid of empty rows it does however not prevent the sequence to get out of line. This is what I have got sofar:
.
.
.
<?php
$db = pg_connect("host=localhost port=5432 dbname=crewdb user=postgres password=XXXXXX");
$query1 = "INSERT INTO access(access_name) VALUES ('$_POST[access_name]')";
$result1 = pg_query($query1);
$query2 = "SELECT setval('access_accessid_seq', (SELECT MAX(accessid) FROM access))";
$result2 = pg_select($query2);
pg_close($db)
?>

However the problem still is not solved. I get a table like this:
 accessid |             access_name
----------+--------------------------------------
        1 | good ride on mower access throughout
        2 | n\a
        3 | no ride on mower acces
        4 | partial ride on mower acces
        5 | fenced off
        7 | Obtacles

As you can see accessid is out of wack. Does anyone know how to solve this problem in the most efficient way?
Table specs are:
  Column    |  Type   | Collation | Nullable |           Default            | Storage  | Stats target | Description
-------------+---------+-----------+----------+------------------------------+----------+--------------+-------------
 accessid    | integer |           | not null | generated always as identity | plain    |              |
 access_name | text    |           | not null |                              | extended |              |

I am a bit new to this so thanks for your help.


text:
Q: Handle Template Error using ErrorHandler in angular2 Following this question , i get to know that after using Errorhandler in our module angular will not throw any such error and our app works somthly,
i did the same process and works fine,
Problem :- After handling template parse error using ErrorHandler  will make all buttons/dropdown on that page and other pages not working properly, is there any kind of method in angular2 by using which neither angular will throw error nor webapp stuck (like buttons are not working in template) ?


text:
Q: RoundCube not found @ Debian 8 & ISPConfig 3 I have installed ISPConfig with Apache via this repo: https://github.com/servisys/ispconfig_setup.
After them i was switch PHP 5.6 to PHP 7 - apps working fine. But roundcube on url: https://IP:8080/webmail missing = 404.
How can I fix it this problem?
What can I try check?
Thanks

A: I got it ...
https://github.com/servisys/ispconfig_setup/issues/145
Is but about bad redirecting with :8080 port.


text:
Q: How to get data from DialogFragment to Fragment and survive recreation activity My application has this chain: the activity that creates fragment. In this fragment there is a button click which calls a DialogFragment. DialogFragment allows user to select  camera or choose image from device memory.
Than DialogFragment calls intent which sends image to crop at new activity. And finaly path to croped image send back to DialogFragment via onActivityResult.
The resulting path should be passed to fragment and i exercise this using Interface through activity like in this lesson
This solution works fine until user no changes the orientation of the device.
When device rotated on DialogFragment stage or crop activity stage , first activity recreated and fragemnt recreated and instance of the DialogFragment is destroyed. So my callback not running and and nothing happens. Let me show you code:
SettingUnitActivity
FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        addNewUnitFragment = new AddNewUnitFragment();
        fragmentTransaction.replace(R.id.single_unit_fragment_container,addNewUnitFragment,"myff");
        fragmentTransaction.commit();

//My callback

@Override
public void call(String string) {
    AddNewUnitFragment addNewUnitFragment = (AddNewUnitFragment)
            getFragmentManager().findFragmentById(R.id.single_unit_fragment_container);
    if(addNewUnitFragment != null) {
        addNewUnitFragment.changeFragImage(string);
    } else {

    }
}

AddNewUnitFragment
public void onClick(View v) {
    switch (v.getTag().toString()) {
        case "add_image":
            DialogImageSelect imageSelDialog = DialogImageSelect.newInstance(0);
            imageSelDialog.show(getFragmentManager(),"imageSelDialog");
            break;

...

//Function which should be called from SettingUnitActivity

public void changeFragImage (String string) {
//Do something with string
}

DialogImageSelect
public static interface dateCallBack {
    public abstract void call(String string);
}

static DialogImageSelect newInstance(int id) {
    DialogImageSelect di = new DialogImageSelect();
    Bundle args = new Bundle();
    args.putInt("id", id);
    di.setArguments(args);
    return di;
}

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

}

//Here we take and send image path from croper activity

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

if(resultCode != Activity.RESULT_CANCELED) {
        if(requestCode == FROM_CROPPER) {
            if(data != null) {
                croppedFilePath = data.getStringExtra("filePath");
                System.out.println("CALL "+callerActivity);
                    this.callerActivity.call(croppedFilePath);
                dismiss();
            }
        }
    }
}

How can I send data to fragment retaining it when device rotated ?
UPD: The answer to my question is partially revealed in this topic but there is no explanation how I could pass data using interface callback from DialogFragment through Activity to Fragment if Activity recreated after rotate.

A: Basically you need to save the instance state on fragment in onSaveInstanceState() method . then use this retained state inside the Base Activity's onCreate() method.
See:
Once for all, how to correctly save instance state of Fragments in back stack?
and
http://emuneee.com/blog/2013/01/07/saving-fragment-states/
You can google more on this and search stackoverflow. There are plenty of questions like yours with proper answers.


text:
Q: De-Activate Physics on SpriteKit i wanna dis-activate the physic of node for a while .Please help me figure that out .
  SKSpriteNode * node = [SKSpriteNode spriteNodeWithImageNamed:@"blade.png"];
    node.size = CGSizeMake(30, 30);
    node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
    node.physicsBody.dynamic = YES;
    node.physicsBody.collisionBitMask = CharacterCategory;
    node.physicsBody.categoryBitMask = ObjectCategory;
    node.physicsBody.contactTestBitMask = CharacterCategory;
    node.position = nd.Position;
    node.physicsBody.mass = 10000;
    SKAction * actfadein = [SKAction fadeInWithDuration:nd.FadeInDuration];
    SKAction * actfadeout = [SKAction fadeOutWithDuration:nd.FadeOutDuration];
    SKAction * wait = [SKAction waitForDuration:3];
    SKAction * removephy = [SKAction runBlock:^(void){
        // i tried to removeFromParent but it never comes back
    }];
    SKAction * activatephy = [SKAction runBlock:^(void){
        //[self addChild:node];
    }];
    SKAction * myActions = [SKAction sequence:@[actfadeout,removephy,wait,activatephy,actfadein]];
    [node runAction:[SKAction repeatActionForever:myActions]];
    [FadeObjects addChild:node];

A: Just set the physicsBody property of the SKSpriteNode to nil. If you later need to apply physics again, just assign another physicsBody.

A: Set this:
node.physicsBody.dynamic = NO;


text:
Q: Как восстановить место в справке Vim? Допустим, я читал некий топик во встроенной справке Vim. Как вернуться к месту чтения после закрытия и повторного запуска Vim? При этом использовался Session.vim. Опция 'sessionoptions' слово "help" содержит.
Окно со справкой восстанавливается. Проблема в том, что файл справки в этом окне после восстановления становится обычным файлом, в котором забыты теги переходов, да и сами теги по ^] перестают работать. Выручает копирование тега, :h <вставка_тега>. Открывается новое окно справки. При этом предыдущее окно с сохранённой справкой вновь становится окном справки. Вот.
Можно ли сделать это проще?
Vim 7.4 в Linux и Cygwin

A: Это баг. "Починить" теги можно принудительно установив опцию :h 'buftype' и др. Например:

~/.vim/after/ftplugin/help.vim

if &buftype !=# 'help'
    setl buftype=help iskeyword=!-~,^*,^\|,^\",192-255
    setl foldmethod& tabstop&
    setl noarabic nobinary nobuflisted nocursorbind nodiff nofoldenable nolist
    setl nomodifiable nonumber norelativenumber norightleft noscrollbind nospell
endif

UPD. Пропатчено Vim 8.2.4007.


text:
Q: How do I use Entity framwork on an existing database with out migrations? I have an existing database that has tables like Surface, that hold different surfaces (not plural like EF seems to like).
I have created a type that uses data annotations thus:
[Table("Surface")]
public class Surface
{
    [Key]
    public Guid SurfaceKey { get; set; }
    public string SurfaceType { get; set; }
}

And I've create an entity framework context, and repository etc. Now when I access this in an MVC view, I get a message that the

'The model backing the 'EFDbContext' context has changed since the database was created...'

What difference does it make if it's changed? I might not have typed in something or another.
So what? I'm not asking EF to use my database. I have an existing database, I need to map it to classes, Entity Framework should quietly oblige, with no stupidity of migration. I'm not migrating. Every time I do a rebuild, it should start from scratch.
I just want to access my existing database, and if I compile with a typo, it should be forgotten when I correct the error and recompile.
How do I do this?

A: You configure this feature in the context class that you create.
public class MyContext : DbContext
{
    static MyContext()
    {
        Database.SetInitializer<MyContext>(null);
    }

    //....
}

Here's a useful link regarding database initialisers


text: Q: How to write custom test client of django? I read the documents about objects but cannot really figure out how to make custom class of test client. There is a document that describes how to make custom test client. but cannot make it. I want to make the client to enforce csrf check. How can I make it? Thanks in advance.


text:
Q: How can I connect my java phone's internet to my pc? Itried a lot to connect my java mobile for sharing internet in my phone. But I don't know how to make the connection true. How can I connect my mobile phone(java) as a mobile broadband to share internet to my computer?

A: You have to search on google: active tethering and router wifi and so you will have istructions .
Before you can see if you model support you option on this site
Update:
see this guide official of samsung because you model can share internet

A: This is really going to depend on the phone. In some instances you are going to have to install a program in the google market place to download a tethering app. In other cases, tethering is already included in the phone. If I go to settings, more networks, and go to tethering and mobile hotspot it will give the option for me to tether my phone using usb, or wifi. This is also going to depend on your service provider because some service providers lock down tethering unless you have a plan aka MetroPCS. In some cases, like one of my older phones you can get around this using one of the tethering apps, but in other cases the phone is really locked down and the only options are to either pay or to root your phone using something like multirom.


text:
Q: WPF: complex tab focus behavior My control is constructed from nested list boxes and tree views.
Each list box / tree view item also contains rich text boxes and other controls.
I want to define a 'tab' focus behavior such that when the user clicks 'Tab' the next focusable item (according to an order i define) will become focused.
Currently it doesn't work as i accept (it only works partially).
My question is not specific to my case - rather on how to define such behavior at all.
As an extreme example, let's say i want to completely control this and make the focus jump between items not physically near.
Anyone might know how this can be controlled?

A: Joe,  this mechanism is smarter than i thought, check this nesting - it works perfectly:
<ListBox KeyboardNavigation.TabNavigation="Continue">
    <ListBoxItem Focusable="False">
        <ListBox KeyboardNavigation.TabNavigation="Continue">
            <ListBox.Items>
                <ListBoxItem Focusable="False">
                    <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                </ListBoxItem>
                <ListBoxItem Focusable="False">
                    <TextBox Width="300" KeyboardNavigation.TabIndex="2" Focusable="True"/>
                </ListBoxItem>
                <ListBoxItem Focusable="False">
                    <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                </ListBoxItem>
            </ListBox.Items>
        </ListBox>
    </ListBoxItem>
    <ListBoxItem Focusable="False">
        <ListBox KeyboardNavigation.TabNavigation="Continue">
            <ListBox.Items>
                <ListBoxItem Focusable="False">
                    <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                </ListBoxItem>
                <ListBoxItem Focusable="False">
                    <StackPanel>
                        <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                        <Border BorderBrush="Red">
                            <ListBox KeyboardNavigation.TabNavigation="Continue">
                                <ListBoxItem Focusable="False">
                                    <ListBox KeyboardNavigation.TabNavigation="Continue">
                                        <ListBox.Items>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="2" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                                            </ListBoxItem>
                                        </ListBox.Items>
                                    </ListBox>
                                </ListBoxItem>
                                <ListBoxItem Focusable="False">
                                    <ListBox KeyboardNavigation.TabNavigation="Continue">
                                        <ListBox.Items>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="2" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                                            </ListBoxItem>
                                        </ListBox.Items>
                                    </ListBox>
                                </ListBoxItem>
                            </ListBox>
                        </Border>
                    </StackPanel>
                </ListBoxItem>
                <ListBoxItem Focusable="False">
                    <StackPanel>
                        <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                        <Border BorderBrush="Red">
                            <ListBox KeyboardNavigation.TabNavigation="Continue">
                                <ListBoxItem Focusable="False">
                                    <ListBox KeyboardNavigation.TabNavigation="Continue">
                                        <ListBox.Items>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="2" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                                            </ListBoxItem>
                                        </ListBox.Items>
                                    </ListBox>
                                </ListBoxItem>
                                <ListBoxItem Focusable="False">
                                    <ListBox KeyboardNavigation.TabNavigation="Continue">
                                        <ListBox.Items>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="1" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="2" Focusable="True"/>
                                            </ListBoxItem>
                                            <ListBoxItem Focusable="False">
                                                <TextBox Width="300" KeyboardNavigation.TabIndex="3" Focusable="True"/>
                                            </ListBoxItem>
                                        </ListBox.Items>
                                    </ListBox>
                                </ListBoxItem>
                            </ListBox>
                        </Border>
                    </StackPanel>
                </ListBoxItem>
            </ListBox.Items>
        </ListBox>
    </ListBoxItem>
</ListBox>

A: Are you looking for the KeyboardNavigation.TabIndex property?


text:
Q: Troubles in if-else statement in Rcpp With the following simplified code I wish to simulate from the N(0,1) distribution and return a list with the simulated values as well as a vector which depends on the simulated normals (see the code below). The problem is that the if-else statement is not working at all! Please, could somebody help me understand where is the problem?
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::depends(RcppArmadillo)]]

//[[Rcpp::export]]

List cond(arma::vec epsilon, IntegerVector Nsim) {
int iNsim = Nsim[0];
arma::vec ans(1);
arma::vec epsil(epsilon);
arma::vec vans  = arma::zeros(iNsim);
arma::vec vcond = arma::zeros(iNsim);
LogicalVector cond;
RNGScope scope;

for (int i=0; i<iNsim; i++) {

  ans = Rcpp::rnorm(1, 0.0, 1.0);
  vans.row(i) = ans[0];
  cond = abs(ans) >= epsil;
  if (cond) {
    vcond.row(i) = 10;
  } else {
    vcond.row(i) = -10;
  }
}

return List::create(
    _["sim"] = vans,
    _["cond"] = vcond);
}

I run it in R by saving it to file.cpp and then by sourceCpp("file.cpp").

A: The original code is confused about where to use a vector, and where to use a scalar.
He is shorter and repaired version:
#include <Rcpp.h>

using namespace Rcpp;

//[[Rcpp::export]]
DataFrame cond(double epsil, int iNsim) {
  double ans;
  NumericVector vans(iNsim);
  NumericVector vcond(iNsim);
  RNGScope scope;

  for (int i=0; i<iNsim; i++) {
    ans = R::rnorm(0.0, 1.0);
    vans[i] = ans;
    if (fabs(ans) >= epsil) {
      vcond[i] = 10;
    } else {
      vcond[i] = -10;
    }
  }

  return DataFrame::create(_["sim"] = vans,
                           _["cond"] = vcond);
}

Besides using (and passing) scalars where scalars were meant to be used, it also corrects abs() to fabs() -- a common C/C++ problem. I also reverted to Rcpp vectors - as much as I like to use Armadillo, it wasn't needed here.
Here is example output given a random seed:
 R> sourceCpp("/tmp/erlis.cpp")
 R> set.seed(1)
 R> cond(1.0, 6)
         sim cond
 1 -0.626454  -10
 2  0.183643  -10
 3 -0.835629  -10
 4  1.595281   10
 5  0.329508  -10
 6 -0.820468  -10
 R>

A: Here is the solution:
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;

//[[Rcpp::depends(RcppArmadillo)]]

//[[Rcpp::export]]

List cond(arma::vec epsilon, IntegerVector Nsim) {
int iNsim = Nsim[0];
arma::vec ans(1);
arma::vec epsil(epsilon);
arma::vec vans  = arma::zeros(iNsim);
arma::vec vcond = arma::zeros(iNsim);
LogicalVector cond;
RNGScope scope;

for (int i=0; i<iNsim; i++) {

  ans = Rcpp::rnorm(1, 0.0, 1.0);
  vans.row(i) = ans[0];
    bool go_ = true;
    for(int i = 0; i < ans.size(); i++)
        if(abs(ans[i]) < epsil[0])
            go_ = false;

  if (go_) {
    vcond.row(i) = 10;
  } else {
    vcond.row(i) = -10;
  }
}

return List::create(
    _["sim"] = vans,
    _["cond"] = vcond);
}


text:
Q: VB.net "There is already an open DataReader associated with this Connection which must be closed first." when entering Visual Studio Debug My boyfriend and I have spent the last 2 hours trying to get this to work, we have tried putting all the data connections into try's, changing the the connections to gloabal's but whatever we do we end up back at the same problem. The page will load fine when loaded via localhost, but when we try to get in via debug it hits this error.
If we put the code that fails into a try it goes through each connection and then will load, but each part will have been caught in the catch.

An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
There is already an open DataReader associated with this Connection which must be closed first.

Here's the code, each sub or function that uses MySQL connection has a close in the same as this function. We are out of ideas to what it causing it, as only does it we try and enter debug in Visual Studio.
    Public Function getID()

        Dim cmd As New MySqlCommand()
        Dim reader As MySqlDataReader
        Dim rtr As Integer

        cmd.CommandText = "MySQLSTATEMENT"
        cmd.Connection = CON_STRING

        Connection.Open()
        reader = cmd.ExecuteReader
        If (reader.HasRows()) Then
            reader.Read()
            rowID = reader.Item(0)
        End If

        Connection.Close()
        reader.Close()
        cmd.Dispose()
    End Function

A: You Should Close reader first and then you can close the connection.
I would recommend Using Statement for connection that will take care of closings the connection.


text:
Q: how to compare two strings in pandas large dataframe (python3.x)? I have two DFs from 2 excel files.
1st file(awcProjectMaster)(1500 records)
projectCode    projectName
  100101       kupwara
  100102       kalaroos
  100103       tangdar

2nd file(village master)(more than 10 million records)
villageCode    villageName
   425638          wara
   783651          tangdur
   986321          kalaroo

I need to compare the projectName and villageName along with the percentage match.
The following code works fine but it is slow. How can I do the same thing in a more efficient way.
import pandas as pd
from datetime import datetime

df = pd.read_excel("C:\\Users\\Desktop\\awcProjectMaster.xlsx")
df1 = pd.read_excel("C:\\Users\\Desktop\\prjToVillageStateWise\\stCodeVillage1To6.xlsx")

def compare(prjCode, prjName, stCode, stName, dCode, dName, sdCode, sdName, vCode, vName):
    with open(r"C:\\Users\\Desktop\\prjToVillageStateWise\\stCodeVillage1To6.txt", "a") as f:
        percentMatch = 0
        vLen = len(vName)
        prjLen = len(prjName)
        if vLen > prjLen:
            if vName.find(prjName) != -1:
                percentMatch = (prjLen / vLen) * 100
                f.write(prjCode + "," + prjName + "," + vCode + "," + vName + "," + str(round(percentMatch)) + "," + stCode + "," + stName + "," + dCode + "," + dName + sdCode + "," + sdName + "\n")
            else:
                res = 0
                # print(res)
        elif prjLen >= vLen:
            if prjName.find(vName) != -1:
                percentMatch = (vLen / prjLen) * 100
                f.write(prjCode + "," + prjName + "," + vCode + "," + vName + "," + str(round(percentMatch)) + "," + stCode + "," + stName + "," + dCode + "," + dName + sdCode + "," + sdName + "\n")
            else:
                res = 0
                # print(res)
    f.close()

for idx, row in df.iterrows():
    for idxv, r in df1.iterrows():
        compare(
            str(row["ProjectCode"]),
            row["ProjectName"].lower(),
            str(r["StateCensusCode"]),
            r["StateName"],
            str(r["DistrictCode"]),
            r["DistrictName"],
            str(r["SubDistrictCode"]),
            r["SubDistrictNameInEnglish"],
            str(r["VillageCode"]),
            r["VillageNameInEnglish"].lower(),
        )

A: Your distance metric for the strings isn't too accurate, but if it works for you, fine. (You may want to look into other options like the builtin difflib, or the Python-Levenshtein module, though.)
If you really do need to compare 1,500 x 10,000,000 records pairwise, things are bound to take some time, but there are a couple things that we can do pretty easily to speed things up:

*

*open the log file only once; there's overhead, sometimes significant, in that

*refactor your comparison function into a separate unit, then apply the lru_cache() memoization decorator to make sure each pair is compared only once, and the subsequent result is cached in memory. (In addition, see how we sort the vName/prjName pair – since the actual order of the two strings doesn't matter, we end up with half the cache size.)

Then for general cleanliness,

*

*use the csv module for streaming CSV into a file (the output format is slightly different than with your code, but you can change this with the dialect parameter to csv.writer()).

Hope this helps!
import pandas as pd
from datetime import datetime
from functools import lru_cache
import csv

df = pd.read_excel("C:\\Users\\Desktop\\awcProjectMaster.xlsx")
df1 = pd.read_excel("C:\\Users\\Desktop\\prjToVillageStateWise\\stCodeVillage1To6.xlsx")

log_file = open(r"C:\\Users\\Desktop\\prjToVillageStateWise\\stCodeVillage1To6.txt", "a")
log_writer = csv.writer(log_file)

@lru_cache()
def compare_vname_prjname(vName, prjName):
    vLen = len(vName)
    prjLen = len(prjName)
    if vLen > prjLen:
        if vName.find(prjName) != -1:
            return (prjLen / vLen) * 100
    elif prjLen >= vLen:
        if prjName.find(vName) != -1:
            return (vLen / prjLen) * 100
    return None

def compare(prjCode, prjName, stCode, stName, dCode, dName, sdCode, sdName, vCode, vName):
    # help the cache decorator out by halving the number of possible pairs:
    vName, prjName = sorted([vName, prjName])
    percent_match = compare_vname_prjname(vName, prjName)
    if percent_match is None:  # No match
        return False
    log_writer.writerow(
        [
            prjCode,
            prjName,
            vCode,
            vName,
            round(percent_match),
            stCode,
            stName,
            dCode,
            dName + sdCode,
            sdName,
        ]
    )
    return True

for idx, row in df.iterrows():
    for idxv, r in df1.iterrows():
        compare(
            str(row["ProjectCode"]),
            row["ProjectName"].lower(),
            str(r["StateCensusCode"]),
            r["StateName"],
            str(r["DistrictCode"]),
            r["DistrictName"],
            str(r["SubDistrictCode"]),
            r["SubDistrictNameInEnglish"],
            str(r["VillageCode"]),
            r["VillageNameInEnglish"].lower(),
        )


text:
Q: В unity как-нибудь можно повесить несколько спрайтов на один объект? У меня есть объект, который нужно раскрасить разными цветами. Пусть будет квадрат - верхнюю часть нужно сделать синей, нижнюю - красной. Я в графическом редакторе нарисовал две половинки квадрата таким образом, что при наложении друг на дуга они образовывают квадрат. Назвал их sprite1 и sprite2.
SpriteRenderer sr = GetComponent<SpriteRenderer> ();

sprite1 = Resources.Load ("sprite1", typeof(Sprite)) as Sprite;
sprite2 = Resources.Load ("sprite2", typeof(Sprite)) as Sprite;

И окрашиваю их так:
sr.color = new Color32 (199, 1, 0, 255);

Это значит, что спрайт, который принадлежит компоненту SpriteRenderer, окрашивается в этот цвет. А мне нужно разные спрайты окрашивать в разные цвета, но так, чтобы они принадлежали одному объекту. Пока мысль такая: создать столько дочерних объектов, сколько спрайтов, и так смогу красить каждый отдельно. Но смущает, что будут лишние объекты. Может, есть способ в коде сначала указать, какого цвета сделать спрайт, а потом объединить их в один, который можно будет использовать на одном объекте?
P.S заранее сделать 1 спрайт нужного цвета не получится, возможных вариантов раскраски очень много = нужно делать много спрайтов. Так что только программно

обновление:
При запуске генератор случайных чисел определяет, какой цвет будет у объекта. Дело в том, этот самый объект должен быть раскрашен разными цветами, но выбор цвета происходит только 1 раз (если это важно)

Обновление: Мой ответ не подходит. Дело в том, что у меня при выполнении некоторых условий у объекта отключается BoxCollider, а у RigidBody отключается Kinematic и Gravity. В этом случае у объектов на одной оси Z возможно наложение дочерних объектов друг на друга. Пример: Коробка и Ящик находятся на Z = 0. 2 дочерних объекта коробки и ящика находятся на Z = -1 и Z = -2 соответственно (по отношению к родительским объектам!), но у ящика дополнительно есть еще 1 дочерний объект на Z = -3. И вот, когда отключаются BoxCollider и RigidBody для одного из объектов (а то и для всех - не важно), дочерние объекты одного из них могут наложиться на другой объект (т.е на ящике будет виден дочерний объект коробки). Если у дочерних объектов будут координаты Z = 0, но при этом в SpriteRenderer изменять значение Order in Layer, то происходит то же самое.
Что делать?

A: А я бы сделал еще проще. Сделал бы спрайтшит(анимацию из нескольких кадров с разными цветами) и просто переключал кадры по мере необходимости.

A: Я бы посоветовал все же не пытаться вот так в реалтайме создавать спрайт из двух других.
Во первых, на GameObject может иметь более одного экземпляра SpriteRenderer.
Поэтому можно добавить 2 SpriteRenderer на объект. Передать их в качестве ссылок скрипту.
public SpriteRenderer Sprite1;
public SpriteRenderer Sprite2;

//...В вашем методе
sprite1 = Resources.Load ("sprite1", typeof(Sprite)) as Sprite;
sprite2 = Resources.Load ("sprite2", typeof(Sprite)) as Sprite;
Sprite1.source = sprite1;
Sprite2.source = sprite2;

В данном случае, будет выполняться тот функционал, о котором вы написали.

A: Пока что вот такое собрал (но опять же, хочу избежать создания кучи объектов, поэтому жду ответ):
На сцене создал пустой GameObject, на который повесил мой скрипт
public class TEST : MonoBehaviour {

    public Sprite[] bag;
    public Sprite box;

    // Use this for initialization
    void Start () {

        CreateChildObjects ();

    }

    void CreateChildObjects()
    {
        int rnd = Random.Range (0, 2);

        if (rnd == 0) {
            GameObject go = new GameObject (); // создаю объект
            go.AddComponent<SpriteRenderer> (); // добавляю ему компонент SpriteRenderer
            go.transform.SetParent (gameObject.transform); // делаю новый объект дочерним
            go.GetComponent<SpriteRenderer> ().sprite = box; // говорю, какой спрайт использовать
            go.GetComponent<SpriteRenderer> ().color = new Color32 (215, 111, 14, 255); // говорю, какой цвет использовать
        } else {
            // ну тут аналогично, но добавляется for по количеству используемых спрайтов
            for (int i = 0; i < 4; i++) {
                GameObject go = new GameObject ();
                go.AddComponent<SpriteRenderer> ();
                go.transform.SetParent (gameObject.transform);
                go.transform.position = new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y,
                    - 0.1f * i);
                go.GetComponent<SpriteRenderer> ().sprite = bag[i];
            }
            transform.GetChild(1).GetComponent<SpriteRenderer>().color = new Color32  (215, 111, 14, 255);
            // GetChild(1), а не (0), потому что для наглядности я заранее сделал моему объекту дочерний
            // - посмотреть, как они сортируются
            // то же для остальных спрайтов
        }
    }

    // Update is called once per frame
    void Update () {

    }
}


text:
Q: change html with jquery select to ui slider slide event So I've got a select and a function to convert it to a slider using http://filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/
<select id="{{ section }}-anonymity-select">
    <option value="anonymous"></option>
    <option value="uw-student"></option>
    <option value="username"></option>
</select>

function setup_form(section){
    $("#"+section+"-anonymity-select").selectToUISlider({tooltip: false, labels: 0, sliderOptions: {
        slide: function(event, ui){
            alert(ui.value);
        }
    }
    }).hide();

What I would like to do is (for now, later I want to change the innerHtml of another element based on the value) alert the current value of the slider as the user is sliding.
The code does almost what I want, except that the slide event "is triggered on every mouse move during slide.", which means about 10 times for one little slide. Very annoying. Not what I want. And it seems to programmatically change the value, too-- my handle keeps jumping all over the place.
I also tried change, but it's only triggered on stop, so if the user is just sliding back and forth but not releasing their mouse button, it won't alert. bad.
How do I handle this? I guess I need something like "on value change" as an event? But how to implement that without constantly checking for it?

A: Rather than using the slide event, you should use the change event which only fires once the user stops interacting with the widget:
Change:
    slide: function(event, ui){
        alert(ui.value);
    }

To:
    stop: function(event, ui){
        alert(ui.value);
    }

Walaa! :)

This event is triggered when the user stops sliding.

Source: http://jqueryui.com/demos/slider/#event-stop
Update
You could use the slide event and set a timeout to alert the value so when the user keeps sliding no alert will appear (due to canceling the timeout):
var slidervalue = 0,
    timer;

function setup_form(section){
    $("#"+section+"-anonymity-select").selectToUISlider({tooltip: false, labels: 0, sliderOptions: {
        slide: function(event, ui){
            clearTimeout(timer);
            setTimeout(function () {
                if(ui.value!=slidervalue){
                    $("#"+section+"-anonymity-header").html("Select anonymity level: "+$(this).slider('values', ui.value));
                    slidervalue = ui.value;
                }
             }, 100);
        }
    }
    }).hide();

A: of course 2 minutes after I post I realize a solution.
var slidervalue = 0;

function setup_form(section){
    $("#"+section+"-anonymity-select").selectToUISlider({tooltip: false, labels: 0, sliderOptions: {
        slide: function(event, ui){
            if(ui.value!=slidervalue){
                $("#"+section+"-anonymity-header").html("Select anonymity level: "+ui.value);
                slidervalue = ui.value;
            }
        }
    }
    }).hide();


text:
Q: improving performance in sqoop apart from basic settings I want to improve performance in sqoop import. I am using sqoop version 1.4.7 and source db is oracle. I have one fact tbale which is having almost more than 100 million rows. I want to load this data into hadoop.
There are couple things where we can do like below
increase mappers by using --m option.
using boundary query
fetch size
I can't use direct query.(since this works on MYSQL and postgres)
Apart from these is there any oyher way to improve the performance.
Thanks in advance
Kumar

A: Hey you could refer below site for the Performance tuning in sqoop
https://community.cloudera.com/t5/Community-Articles/SQOOP-Performance-tuning/ta-p/248260