text:
Q: External IP of client I'm using MVC4, .NET 4.5, VS2012, C#, Razor
I need the public IP of client on my website. To clarify, i need the kind of IP that whatismyip shows.
I know about querying whatismyip's automation page. But, I need to obtain the IP myself rather than using some other website for it. Following is my present code.
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Web.Routing;
using System.Net.Sockets;
using System.Text;

namespace abc
{
    public class GetIP : Controller
    {
        public ActionResult GetIP()
        {
            ViewBag.ip1 = string.Empty;
            ViewBag.ip2 = string.Empty;
            ViewBag.defaultgateway = string.Empty;
            ViewBag.ip4 = string.Empty;
            ViewBag.dnsServer = string.Empty;
            ViewBag.ip6 = string.Empty;
            ViewBag.server_IPv6_address = string.Empty;

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
                ViewBag.ip1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                ViewBag.ip2 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();

            if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0)
                ViewBag.defaultgateway = System.Web.HttpContext.Current.Request.UserHostAddress;

            if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                ViewBag.ip4 = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

            if (System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] != null)
                ViewBag.dnsServer = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString();

            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"] != null)
                ViewBag.ip6 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"].ToString();

            ViewBag.server_IPv6_address = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();

            if (Request.ServerVariables["X-Forwarded-For"] != null)
                ViewBag.ip8 = Request.ServerVariables["X-Forwarded-For"];

            return View();
        }
    }
}

View
Your IP address

Ip1 : @ViewBag.ip1

Ip2 : @ViewBag.ip2

Default Gateway : @ViewBag.defaultgateway

Ip4 : @ViewBag.ip4

DNS Server : @ViewBag.dnsServer

IP6 : @ViewBag.ip6

@*Server's IPv6 Address : @ViewBag.server_IPv6_address*@
IP8 : @ViewBag.ip8

When I put this code on the server, and go the the appropriate url, I get the following result.

And when I go to whatismyip, say I get 123.45.67.89 for example.
Why is it that whatismyip can find my IP address but my server can't with all the headers that i have checked. I have also read somewhere about System.Net.Sockets class but i don't know if that would help or what.
Please help.
EDIT : Apparently this is a problem with the server configuration. When I put the same code on a different server, it works perfectly. Thanks for your help guys!

A: You're not seeing your external IP because you're accessing the server, that's in the same network as you, over the internal network.
If you visit the site from your smartphone (not over WiFi) or through an external proxy, you'll see the external IP (of the mobile network or the proxy).

A: System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] is the address the server used to respond to your request.  It is not the DNS server, as your code implies.
The value for that, "192.168.4.202", is the address the server is listening on and used to respond to your request.  If that is the result you received when you connected from the internet, that tells me that your web server is behind some kind of load balancer or filter proxy.
Outgoing connections from that machine might take a completely different path.  You might be behind a load balancer for incoming connections but not for outgoing connections.  Your ip address from whatismyip.com might be completely different from the ip address that is used to connect to your web site.
Your best bet for finding the public ip is to look up the host name of your web site using DNS.  That will tell you what ip address any remote computer (smartphone, home computer, etc) will use to connect to that web site.  You could also talk to the technical staff responsible for setting up that portion of your network.


text:
Q: while converting to data object, Moscow time is one hour behind In my application while converting to date object i am always getting one hour behind time . this issue in happening only with moscow time zone.
below is code :
    MutableDateTime mdt = new MutableDateTime(time);
    mdt.setSecondOfMinute(0);
    mdt.setMinuteOfDay(0);
    mdt.toDate()

in above code mdt.todate() returning 5/30/2021 23:00 instead of 5/31/2021 00:00.
jdk version : "1.8.0_191"

A: Edit: Why does "June 6 00:00" after conversion mdt.toDate() become "May 31 23:00"?
Your surprising observation probably comes from an old Joda-Time version with an old time zone database where Europe/Moscow was at offset +04:00 rather than +03:00. It was between 31 October 2010 and 26 October 2014. If Joda-Time "believes" that this is still the case, it sets your MutableDateTime to something like 2021-06-01T00:00:00.000+04:00 with offset +04:00 instead of +03:00. This corresponds to 2021-05-31T20:00Z UTC where the correct point in time would have been 2021-05-31T21:00Z UTC. In other words, it's an hour too early. Therefore you get a Date that is an hour too early too. Your Java 1.8 "knows" that Moscow is at offset +03:00 these days and therefore prints the time as Mon May 31 23:00:00 MSK 2021.
Solutions include:

*

*Upgrade to a newer version of Joda-Time that has an up-to-date time zone database.

*Build your Joda-Time from sources for the version that you are using only with a newer bundled time zone database. This is explained on the Joda-Time home page, see the second link below.

Original answer
Your surprising observation probably comes from an old Java version with an old time zone database where Europe/Moscow was at offset +04:00 rather than +03:00. It was between 31 October 2010 and 26 October 2014. I have reproduced your result on my Java 1.7.0_67 and verified that my Java installation "believes" that Moscow is at offset +04:00 and does not use summer time (DST), as was the case in the mentioned period.
Your Joda-Time seems to be new enough to know that Europe/Moscow is at +03:00 so correctly converts your MutableDateTime to a Date at 00:00 hours on the date in question. Only when you print this Date, Java uses its default time zone, still Europe/Moscow, but its own time zone data, and therefore incorrectly prints the time as 01:00 hours instead of 00:00.
Possible solutions include:

*

*Upgrade to a newer Java version that has up-to-date time zone data.

*Fix your current Java installation by upgrading only its time zone database. See Timezone Updater Tool in the second link below.

Setting the time to the start of the day
Edit: you added:

Here MutableDateTime time =new MutableDateTime(new Date().getTime());

To get a Date representing the start of today's date using Joda-Time:
    Date oldfashionedDateObject = LocalDate.now(DateTimeZone.getDefault()).toDate();
    System.out.println(oldfashionedDateObject);

Output just now:

Mon May 31 00:00:00 MSK 2021

Original aside: As an aside, the simpler and safer way to set the time to the start of the day is:
    mdt = mdt.toDateTime().withTimeAtStartOfDay().toMutableDateTime();

If you need to keep the same MutableDateTime object, instead do:
    mdt.setMillis(mdt.toDateTime().withTimeAtStartOfDay().toInstant());

First of all I would be worried that your code may run in a time zone and on a day that in that time zone has a transition at 00:00 so that the first moment of the day is 01:00 or something else. In this case I b believe that your code would throw a surprising exception. Also I find setting individual fields low-level and prefer to set everything in one method call even if it requires further operations to determine the argument to pass to that method.
Links

*

*Time Zone in Moscow, Russia (Moskva).

*Joda-Time Updating the time zone data.

*Timezone Updater Tool on Oracle's web site.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I show an element only if the page is not an article? I have a code snippet in an override off the mod_breadcrumbs/default.php, in order to NOT show the last li element of the Breadcrumb when the view is an article.
The code is:
<?php if( JRequest::getVar( 'view' ) != 'article' ): ?>
        <li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem" class="breadcrumb-item active"><?php echo $breadcrumbItem; ?>
            <meta itemprop="position" content="<?php echo $key + 1; ?>">
        </li>
        <?php endif; ?>

Now with Joomla 4 the JRequest is creating the  error:

Class "JRequest" not found

and we must use another code.
Any help?
Thanks

A: JRequest was deprecated in Joomla 3 as well, in favour of JInput
$value = JFactory::getApplication()->input->get('view');

input->get supports three params, only the first is required; full syntax is :
input->get('name','default','filter').

A: Well the working solution is:
  <?php if( $app->getInput()->get('view') != 'article' ): ?>


text:
Q: Automatic facebook wall post, access token keep expire I have to automatic post on my facebook page wall. So far so good... but the access token keep expire. I did the automatic post with my App and with the Graph Explore and I have the same problem with both.
To post on facebook wall, I create a Cron job on my server, but after some hours the access token expire and I have to create a new one every time manually, and it's not the idea of automatic service :)
I read most of answers here with similar problem of mine, but can't find the answer already.
So, I just need a way to get a new access token, every time the cronjob call my php file.

A: You could have the cron job email you an authorization link a day or two before the token expires. Using exchange_token you can get a 60-day token, so you only have to re-authorize it every other month.


text:
Q: What should I do with multiple swapchains in DXGI? It's confusing here. Is it that one swap chain cannot be accessed concurrently, or DXGI is completely not thread safe?
If I have 2 swap chains for 2 display on one card, what is the best way I swap them? I can hardly find any resource on multiple swap chains.

A: Please check this link : http://msdn.microsoft.com/en-us/library/windows/desktop/ee417025(v=vs.85).aspx#multiple_monitors When you want to display different windows on two or more monitors, you should create two or more swapchains, each for one monitor.


text:
Q: Apostrophe, caret, or quote mark appear depending on cell alignment in MS Excel worksheet There is one computer in our department which is having this problem, which causes me to think that a default setting has been changed. I am asking for any advice or recommendations. This setting is screwing up the VBA code I've written, causing it to be useless for that computer.
Problem: every single cell's value in the worksheet has a leading character which changes depending on its alignment. Left aligned cells receive an apostrophe ('), centered cells receive a caret (^), and right aligned cells receive a double quote mark ("). Every single web page says to change the format from Text to General, but that doesn't fix it (if the solution is different from selecting Home tab, Number section, dropdown -> select General, then let me know).
This issue is happening with every single worksheet opened on this computer and occurs no matter what type of data is entered, and it needs to stop.
Left Alignment Photo,
Centered Alignment Photo
(I would add the Right Alignment Photo, but I need more posts before I gain permission)
I'm in need of a solution to stop having these characters appear. I don't know what is causing them therefore I don't know how to deactivate it. But I do know that it is automatic, and nobody is inserting those characters.
Any help is greatly appreciated. Thank you in advance.
My options as I see it:

*

*Preferred: Fix the problem,

*Second: Uninstall and re-install MS excel,

*Last resort: change the code...

A: From: http://ask.brothersoft.com/what-does-a-caret-symbol-mean-in-microsoft-excel-77529.html

Converted Lotus 1-2-3 Worksheet
You may see a ^ in the Formula Bar if
you open a Lotus 1-2-3 spreadsheet. Lotus 1-2-3 uses special
characters to indicate formatting. These characters appear in Excel's
Formula Bar; however, they do not affect the cell. The characters are
the apostrophe ('), which means the text is left-aligned, the
quotation mark (") for right-aligned text, the caret (^) for centered
text and the backslash () for justified text.

Check the settings under: Excel Options > Advanced > Lotus Compatibility


text:
Q: mongodb native how to work with query I'm trying to retrieve data from my mongolab DB using Node-mongodb-native
var findAll = function () {
   var ddocs;
   collection.find({}).each(function (arr, docs) {
    ddocs = docs;
   });
   console.log(ddocs);
};

But it seems that when I log ddocs, it will give me undefined, but if I log docs it will show me the data.
Please help
How should I use this function ?
Thanks
Tzelon Machluf

A: You're basically trying to create a function that will return all of the documents in a collection? If so, the below should do work. However, I agree with @hgoebl and that you should work on your understanding of node as this is not likely the best way to accomplish what you're trying to do.
var ddocs;

var findAll = collection.find().toArray( function(err, docs) {
    if(err)
        throw err;
    console.log('Collection returned');
    return ddocs = docs;
});

setTimeout( function(err) {
    if(err) throw err;
    console.log(ddocs);
    db.close();
}, 1000);

One thing in particular to note: collection.find is asynchronous, so the problem in your code (why it says ddocs is undefined) is that you're logging ddocs before the collection.find ever finished; thus, it's initialized, but no assigned any values. The Node convention is to nest callbacks so that everything happens in the right order and when it's ready.


text:
Q: Creating an auth ConfigMap using python sdk I'm trying to set a ConfigMap on my cluster using the python SDK. I'm planning on provisioning clusters on AWS EKS automatically, so want to be able to set the ConfigMaps using code.
I'm struggling to understand what format the data object should be in. I've been following the AWS EKS documentation and manually applied an auth configmap, and the output from kubectl looks like this:
data:
  mapRoles: |
    - rolearn: arn:aws:iam::XXXXXXXXXX:role/dev-eks-workers-NodeInstanceRole
      username: system:node:{{EC2PrivateDNSName}}
      groups:
        - system:bootstrappers
        - system:nodes

I'm trying to set the structure in the following way (with an extra role for my local AWS user role):
body = client.V1ConfigMap()
body.api_version = 'v1'
body.kind = 'ConfigMap'
body.metadata = {
    'name': 'aws-auth',
    'namespace': 'kube-system'
}

body.data = {
  'mapRoles': [
    {
      'rolearn': 'arn:aws:iam::XXXXXXXXXX:role/dev-eks-workers-NodeInstanceRole',
      'username': 'system:node:{{EC2PrivateDNSName}}',
      'groups': [
        'system:bootstrappers',
        'system:nodes'
      ]
    },
    {
      'rolearn': 'arn:aws:iam::XXXXXXXXXX:role/Admin',
      'username': 'admin',
      'groups': [
        'system:masters'
      ]
    }
  ]
}

That code is rejected by the API. I guess its because the docs here specify that data is to be a dict(str, str)
I tried a multi-line string, and while it does appear to set the configmap, it formatting is completely bust and it doesn't actually work with the roles defined.
apiVersion: v1
data:
  mapRoles: "\n- rolearn: arn:aws:iam::XXXXXXXXXXXX:role/dev-apollo-eks-workers-NodeInstanceRole\n
    \ username: system:node:{EC2PrivateDNSName}\n  groups:\n    - system:bootstrappers\n
    \   - system:nodes\n\n- rolearn: arn:aws:iam::XXXXXXXXXXXX:role/Admin\n  username:
    admin\n  groups:\n   - system:masters\n    "
kind: ConfigMap

Can anyone give me an example of how I'm supposed to do this in python

A: After trying multiple ways, using this format works.
rolesString = ['- rolearn: ',
              f'{nodeRoleName}\n',
               '  username: system:node:{{EC2PrivateDNSName}}\n',
               '  groups:\n',
               '    - system:bootstrappers\n',
               '    - system:nodes\n',
              f'- rolearn: arn:aws:iam::{accountId}:role/Admin\n',
               '  username: admin\n',
               '  groups:\n',
               '    - system:masters\n'
               ]

body.data = {
   'mapRoles': ''.join(rolesString)
}


text:
Q: SQL error after updating CakePHP3 (minor version upgrade) After updating CakePHP I'm getting the following error on my development machine:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'stockapi.Products.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

The SQL command is: SELECT Products.id AS Products__id FROM products Products WHERE Products.delivery_id in (:c0) GROUP BY ean
It seems to be working fine on my production server, but not on my OSX development computer.
I think its because I have sql_mode=only_full_group_by turned on on my computer. I could of course turn this off, but I would like to make my code comply with only full group by. What do I need to change in my SQL code?


text:
Q: how to pass arguments to PhoneGap database transaction executeSql functions I'm new to PhoneGap I'm using database and its working fine with below code
db = window.openDatabase("Sample", "1.0", "PhoneGap Demo", 200000);
    db.transaction(getDetails, transaction_error);

function transaction_error(tx, error) {
    $('#busy').hide();
    alert("Database Error: " + error);
}

function getUserDetails(tx) {
var sql = "select id, Name,  DisplayName from details where Name=Name";
    try {
        tx.executeSql(sql, [],getList_success);
    }
    catch(err)
    {
        alert(err);
    }
}

function getList_success(tx, results)
{
    var len = results.rows.length;
    for(var i=0; i <len; i++)
    {
        //Some code goes here
        }
    db = null;
}

Now i want to use the functions getUserDetails and getList_success by passing paramenters, i tried the below code its giving error
db = window.openDatabase("Sample", "1.0", "PhoneGap Demo", 200000);
    getUserDetails(db);

function getUserDetails(tx) {
var sql = "select id, Name,  DisplayName from details where Name=Name";
    try {
        tx.executeSql(sql, [],getList_success);
    }
    catch(err)
    {
        alert(err);
    }
}

the error is TypeError:'undefined' is not a function in the catch block, can any one help me to get through this?.
Thanks in advance

A: The executeSql function need 4 parameters, try this:
function errorCallback(err){
//show error
}
...
tx.executeSql(sql, [],getList_success,errorCallback);

A: The problem is that you are handing over a callback function to db.transaction. If you want to provide some data to the callee you have to provide this in the context of the caller by using a closure.
var db = window.openDatabase("Sample", "1.0", "PhoneGap Demo", 200000);
var context = {val1: 'x', val2: 'y'};
db.transaction(function(tx){
        myfunction(tx,context);
    },
    tx_error,
    tx_success);

function myfunction(ty,context){
    tx.executeSql(query,[context.val1,context.val2],myf_success,myf_error);
}

Keep in mind that this happens in a new thread! So if you call db.transaction be aware that this happens concurrently to the caller. If e.g. you are calling db.transaction() from inside the success callback of a jQuery.ajax() call the ajax thread will run on and the complete callback may be executed while the transaction is still in progress.

A: Look at your code:
db.transaction(getDetails, transaction_error);
getDetails!
Look at the functions you declared:
function getUserDetails(tx) {...}
function getList_success(tx, results) {....}
getDetails is not getUserDetails....
That's why you are getting the error.


text:
Q: Need help with configuring Mutual Authentication While understanding Mutual Authentication with Salesforce, found the below link, which mentions a option to upload the certificate:
https://help.salesforce.com/articleView?id=security_keys_uploading_mutual_auth_cert.htm&type=0 .
But in my Salesforce developer organization I don't see that option. I verified my user has the necessary permission("Customize Application"). What can be done?

A: You need to open a case in Salesforce support to enable this feature.
The documentation clearly states that

If you don't see this option on the Certificate and Key Management
  page, contact Salesforce to enable the feature.

However, to have access to Salesforce support, you need to have Premier Support with production user. So you need a production instance or you can ask your employer or your client to open such ticket for you.
We have opened a ticket and after that the link "Upload Mutual Authentication Certificate" has appeared on sandbox instance which organization id we included into ticket.


text:
Q: Is iptables enough security, if port 80 is the only unblocked port and apache is setup correctly? We are using PHP,MySQL,SVN, and Apache. I want to know if I assume the local subnet trusted, and allow all ports on our subnet using iptables, then allow only port 80 as open to "anyone". If it is "good security" taking that the subnet is trusted as a premise. This is also assuming good PHP code etc, and that apache is configured correctly.
This is using CentOS 5.

A: No defiantly not.  In fact port 80 is probably the most dangerous port you can open on a modern system.  Also not having https:// (tcp 443) means all of your session id's are being leaked.  Not using https is a clear violation of A3: "Broken authentication and session management" in the OWASP top 10 for 2010.
A good thing you can do to protect your self is to run a Web Application Firewall(WAF) like Mod_Secuirty. A WAF is is a very different  from a "packet filter firewall" like iptables.
I also recommend running a vulnerability scan against your system such as Acunetix or wapiti.  Make sure your system is regularly updated: yum upgrade.   Run PhpSecInfo and configure your php.ini such that no RED appears. PHP's default config is horribly insecure,  it has gotten better (disabling remote file includes and register_globals by default) but its still really bad.

A: I would actually say the problem lies in:
"Assuming good PHP Code."
You can't take this for granted.  Ideally, that server will go in a DMZ where the LAN can access it, but the DMZ can't access the LAN.  The idea is that you assume your public facing server will get compromised, and then you want to limit the damage.  By having a separate firewall between your LAN and the DMZ you likely limit the damage.  So with a DMZ setup, subversion is probably not going to be on the public facing server.  If you can't afford this extra server, creating a virtual machine and having the public facing server in that might be a sort of poor man's DMZ.
I also would take the extra step to only open up the ports to the local subnet that are needed (You probably need to trust you LAN more, but still limit it if you can).  It probably won't be that many if you are using the state module (redhat/centos default setup).
Also, don't forget about security updates for the OS and applications.

A: If everything is secure, then you have enough security. Unfortunately the first part of that sentence is rarely true. Open only the ports that are required, even to a trusted network.

A: well.. do not just limit incoming connections. filter outgoing too.
and filter them both locally on OUTPUT table but also on router.
there are so many holes in popular scripts... minimize the casualties in case your server gets owned.
allow outgoing ESTABLISHED,RELATED [obviously], probably to few hosts with OS updates, maybe to your smtp relay server... and that's it. so you prevent box from downloading malicious payload, spreading spam etc.

A: I concur with @The Rook on this - the real danger is all that big fat functionality lurking behind 80. If you are writing web app code, regardless of language, I would hastily recommend you learn quickly how to write secure code and create secure designs. No amount of firewall defense will protect you from a crappy web app.


text:
Q: pptpd mostly works, but strange internet/dns behavior I'm running Centos 6.4, and I got pptpd working, for the most part. I am connecting from a Windows 7 machine, and once connected I can access all the intranet sites as well as sites that are already open, or have been opened recently, like google.com. What I can't access is new sites (like when I tried connecting to serverfault), so I think it is related to DNS. I have been able to access a few sites by their IP, but most seem to redirect the IP to the domain name, which then fails. From cmd, I can ping new sites, so it is resolving DNS there. Is the command line resolving DNS through the LAN while Chrome tries to do it through the VPN?
I've searched many forums and blogs looking for an answer, but still haven't found anything that fixed it for me. I have tried disabling selinux and also iptables (both non-persistently), just to reduce the number of variables.
Possibly related: these lines keep showing up in /var/log/messages
GRE: read(fd=7,buffer=6097c0,len=8260) from network failed: status = -1 error = Protocol not available
CTRL: GRE read or PTY write failed (gre,pty)=(7,6)

Here are some config files that might be relevant in determining what is wrong:
pptpd.conf
ppp /usr/sbin/pppd
option /etc/ppp/options.pptpd
logwtmp
remoteip 192.168.16.36-49 #these are reserved, not used by dhcp
localip 192.168.16.35

options.pptpd
name pptpd
refuse-pap
refuse-chap
refuse-mschap
require-mschap-v2
require-mppe-128
ms-dns 192.168.16.2 #domain controller, dns server
ms-wins 192.168.16.2
proxyarp
lock
nobsdcomp
novj
novjccomp
nologfd
auth

A: I discovered this problem after changing to a router with a lower default mtu, having problems you describe, but being baffled when small 404 pages and ssh made it through.
I solved it by setting the ppp server mtu lower in /etc/ppp/options by adding:
mtu 1300

Also, apparently windows can be a bit funny about mtu sizes over ppp.
Good luck.


text:
Q: Not able to search for $ in datadog logs I am searching for the occurrence of character $ in a log file on datadog log explorer which uses lucene syntax. It's pretty similar to kibana. I have logged a string for testing Testing $ pattern datadog but when I search for $ it doesn't show any results. On searching for Testing I get Testing $ pattern datadog in response. Please tell me how can list the occurrences of $ any help is much appreciated.

A: One solution would be to setup in logs > configuration > pipelines a category processor to add a new attribute that could be made searchable.

edit: 19th Nov 2019
Step 1:
Add grok parser to extract sign:
rule: detect_dollar .*%{regex("[$]+"):dollarSign}.*

Step 2:
Then you can setup a category processor as indicated above. This could look for the attribute @dollarSign:$ and set the attribute hasDollarSign to True and set it to false otherwise.

Step 3:
Create a facet on dollarSign attribute. Following logs can then be searched for.
For logs with no $
-@dollarSign:$

For logs with $
@dollarSign:$

You can do the same with the hasDollarSign attribute and set it as a facet.


text:
Q: Weird encoding in executable files in ios apps I'm trying to see how does certain ios apps executable files look like, what I do is export the app files to my computer using iexplorer, I then took a look at the info.plist to see the executable files, after that I opened them with my notepad to use the UTF-8 Encoding, but here how does things look like in both files-in the opening of both of the files I see english words that are expressing directories:
Sample of file 1:
‹"Ò.(?!ÑNÓU£C°îXjøe"Ú5O•½°{^ÿÝŒEÌrôðæ$@[3,ÔÜ£æ»8I˜hGw!*aHÒQ•tœl²þ"™AÍçßÍ憴³)è:cÌ7H5æß-eFç¯î&Ø\n,$Ë$y»¥ÁB^6ÙP; i(q,AÅ
âðð·'©=Ÿa"v!PBÛÚ"¤¬‹Wj·;ËsÌŽÚâZüŠ–ÇüÉ;ÜA´sI«¸Üæ¿÷ ›'‰.êøLž

Sample of file 2:
ßꪧgö«húDªÝn¡±CÅÁ¹ â=؉ˆ4|®b¡  JeW-ɯðó<n!¿mªJŒS£šŠ¿)ÙP"㢜ÛôRW³tÖÙiŠ/7'¬(.æIó£™\NÒèË0¾jDçéM«Q/rªa`NÌhó¾ByUkézAµI—Ê6èøÁœ.gÄkß±ŠÊbN¬9ó9XˆU_ô°Š Y—9cÍq²Xi"¢•¢^+3بñTÒ¦"¦Ø+PEOÖ–lci5^?÷¤(131dv°t]†™6>¦xgýgeéÀXœH7ßJÉ" 3‡rÜ6ÒI_   ƒr cdÅá¸|íð¼l;Töl±"›MÛ˜±o/ôÇô#¬RS;Y¥!ÜzGò"vî©6ØR¡'>Ì0m5
ŸzrPÐiDMÊ|Þ·9âëYß,p؃‹£x—.àN5îüÝrjœG]Æ·

Ironically in the second file I can see a huge block of english words absolutely fine, but I dont get it why I don't see the whole file very good? I have also tried to open the files in an objective-c compiler after I have made them .m but that again was useless?

A: iOS applications consist of compiled code and additional support files, you would need decompilation tools of some kind to get back from the compiled code to readable source. As a starter see

*

*IPA File Format

*.ipa (file extension)

*Bundle Programming Guide/Bundle Structures
If you just want to understand how iOS apps are developed you might be better of by looking at sample code within Apple's Developer Documentation and/or some of the various online repositories/courses.


text:
Q: Converter HTML como imagem Possuo uma string com o HTML da página, há alguma maneira de salvá-la como uma imagem? Renderizar a página toda como uma imagem, e se possível, armazená-la em um MemoryStream.

A: HtmlRenderer
É uma biblioteca em C#. Recomendo por que não precisa de nada a mais além da própria DLL, sem outras dependências, se quiser salvar em imagem.
Exemplo (retirado daqui, em inglês):
namespace HtmlToBmpImageDemo
{
     class Program
     {
         static void Main(string[] args)
         {
               Bitmap m_Bitmap = new Bitmap(400, 600);
               PointF point = new PointF(0, 0);
               SizeF maxSize = new System.Drawing.SizeF(500, 500);
               HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                              "
This is a shitty html code
"
                                              + "
This is another html line
",
                                               point, maxSize);

               m_Bitmap.Save(@"C:\Test.bmp        }
     }
}

Também recomendo essa biblioteca pois eles tem suporte para salvar direto em *.pdf. Dá uma pesquisada no Nuget por HtmlRenderer.PdfSharp.
Exemplo (retirado daqui, em inglês)
public static Byte[] PdfSharpConvert(String html)
{
    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
        var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
        pdf.Save(ms);
        res = ms.ToArray();
    }
    return res;
}

wkhtmltopdf
O wkhtmltopdf encapsula um aplicativo console para o .NET. Segundo a página deles no GitHub, é simples converter HTML para PDF usando a ferramenta.
Não vou entrar no assunto pois já existe uma resposta falando sobre ele.
Ele é protegido pelo LGPL, então recomendo que dê uma lida, dependendo do seu caso, pode ser uma complicação. É claro que ler o "contrato" oficial da licença é fundamental, porém existem algumas ferramentas que podem te ajudar, como o Choose a License, que julgo bastante confiável. Outro fato curioso sobre o site é que ele é opensource.

A: A forma mais fácil de você conseguir isto é utilizando um utilitário externo, no caso o WKHtmlToImage.
Para tal, você vai precisar escrever o seu HTML em disco, usando o System.IO.File.WriteAllText(string path, string contents).
O segundo passo é instanciar um System.Diagnostics.Process, setar o processo.StartInfo.FileName para o local onde se encontra o WKHtmlToImage e passar os devidos argumentos pelos processo.StartInfo.FileName
caso precise saber quais são os argumentos esperados pelo WKHtmlToImage, você pode consultar o Manual, apesar que no seu caso, acredito que wkhtmltoimage <input file> <output file> será o suficiente.
Quanto o processo finalizar, você poderá ler a imagem do disco.


text:
Q: txt файл в словарь Python В текстовом файле лежат такие строки, это часть
soler(count,min,avg,max): 0
grep_req_das: 10
grep_req_says: 12
ПРЕК.req: 20
ПРЕК RI.req: 12
laik(min):
tase.dip: 1002

Я преобразовываю в словарь так:
file = open("test.txt")
onstring = file.read().split("\n")[:-1]
dict = dict()

for item in onstring:
    key = item.split(":")[0]
    value = item.split(": ")[1:]
    dict[key] = value
file.close()

Но на выходе значения все в квадратных скобках и кавычках:
{'soler(count,min,avg,max)': [], 'grep_req_das': ['10'], 'grep_req_says': ['12'], 'ПРЕК.req': ['20'] ...

Подскажите, что я не так делаю, как сделать, что было так:
{'soler(count,min,avg,max)': 0, 'grep_req_das': 10, 'grep_req_says': 12, 'ПРЕК.req': 20 ...

A: # открываем файл, обязательно указывая режим и кодировку
with open(r'path\to\file.txt', mode='r', encoding='utf-8') as fl:
    # считываем содержимое файлам одним списком стром
    onstring = fl.readlines()

# определяем выводной словарь. Ключевое слово dict занято классом словаря,
# поэтому его использовать в качестве идентификатора переменной не рекомендуется.
# Так же не рекомендуется напрямую инициализировать его экземпляры. Для этого
# есть соответствующий синтаксический литерал
res = {}

# проходим в цикле по списку строк
for i in onstring:
    # присваиваем переменным k и v левую и правую часть подстроки,
    # разделяя по символу ':'
    k, v = i.split(':')
    # убираем лишние концевые пробелы
    v = v.strip()
    # определяем, является ли значение переменной v числом, и если да, то
    # преобразуем к целому числу, иначе оставляем строкой
    v = int(v) if v.isdigit() else v
    # добавляем в словарь соответствующие пары ключ:значение
    res[k] =  v

print(res)

A: Мои 5 копеек (с учетом исходника приведённого Вами в предыдущем вопросе и Вашего коментария на ответ @cauf):
import re

with open("test.txt", "r", encoding="utf-8") as a_string:
    lines = re.findall(r'^.+?\d+', a_string.read(), flags=re.M)

output_dict = {k: int(v) for k, v in [re.split(r'\s*:\s*', line) for line in lines]}

print(output_dict)
# {'grep_req_das': 10, 'grep_req_says': 12, 'ПРЕК.req': 20, 'ПРЕК RI.req': 12}


text:
Q: Divide Assocative array into two equal array with maximum and minmum values in php I have an array like this way
Array
(
    [0] => Array
        (
            [items] => 42
            [prize] => 122
        )

    [1] => Array
        (
            [items] => 14
            [prize] => 789
        )

    [2] => Array
        (
            [items] => 76
            [prize] => 1228
        )

    [3] => Array
        (
            [items] => 23
            [prize] => 122
        )

    [4] => Array
        (
            [items] => 15
            [prize] => 567
        )

)

From this i want to create two arrays one contains the maximum number of items and other contains minimum number of items
Expected output
array1(maximum)
[0] => Array
        (
            [items] => 76
            [prize] => 1228
        )

    [1] => Array
        (
            [items] => 42
            [prize] => 122
        )

    [2] => Array
        (
            [items] => 23
            [prize] => 122
        )

Array 2(minmal)
[0] => Array
        (
            [items] => 15
            [prize] => 567
        )

    [1] => Array
        (
            [items] => 23
            [prize] => 122
        )

n is length  original array
if(n is odd)

length firstarr=ceil(n/2);

length secondarr =n- ceil(n/2)

else

length firstarr=secondarr=n/2

So how can i spli the above with maximum and minimum range of values?

A: You should begin by sorting the array into order by number of items. We'll go with ascending order but it really doesn't matter that much.
There are a few different ways to achieve this. You could use array_multisort but I think usort with an anonymous function is a bit shorter and easier to follow.
If you have PHP 5.2 or earlier you'll have to move the anonymous function code into a named function and call it
that way. If you're lucky enough to have PHP 7 you can just do return $a["items"] <=> $b["items"]; in the function.
$array = [["items" => 42, "prize" => 122], ["items" => 14, "prize" => 789],
          ["items" => 76, "prize" => 1228], ["items" => 23, "prize" => 122],
          ["items" => 15, "prize" => 567]];
usort($array, function($a, $b) {
    return $a["items"] < $b["items"] ? -1 : ($a["items"] > $b["items"] ? 1 : 0); });

Now split it into the highest and lowest values. After the array_splice the $array variable will be left containing only the
values that haven't been removed and saved into $lowest.
In your example the highest values were in descending order but ours are in ascending order. array_reverse will fix this.
$lowest = array_splice($array, 0, floor(count($array) / 2));
$highest = array_reverse($array);

var_dump($highest);
var_dump($lowest);

A: You can use usort() and pass the values to a callback to compare, notice the use of closure in the callback,
<?php

function sort_order($key, $order=1){
    if($order==1){
        return function ($a, $b) use ($key) {
            return strcmp("$a[$key]","$b[$key]");
        };
    }
    else{
        return function ($a, $b) use ($key) {
            return strcmp("$b[$key]","$a[$key]");
        };
    }

}

$minimal = array
(
    0 => array
        (
            'items' => 42,
            'prize' => 122
        ),

    1 => array
        (
            'items' => 14,
            'prize' => 789
        ),

    2 => array
        (
            'items' => 76,
            'prize' => 1228
        ),

    3 => array
        (
            'items' => 23,
            'prize' => 122
        ),

    4 => array
        (
            'items' => 15,
            'prize' => 567
        )

);

$maximum = $minimal;

usort($minimal, sort_order('items'));
usort($maximum, sort_order('items',2));
print_r($minimal);
print_r($maximum);
?>

Here is the fiddle : https://eval.in/539270


text:
Q: Proving that $\sum_{n=0}^\infty \sum_{k=0}^n \frac{(-1)^n}{(k+1)\times (n-k+1)}$ converges How can I prove that the following summation converges?
$$\sum_{n=0}^\infty \sum_{k=0}^n \frac{(-1)^n}{(k+1)\times (n-k+1)}$$
I tried to prove that by proving that the following summation in in absolute value converges so the original one converges too, but that's incorrect.
Any other ideas?

A: If we write it this way
$$\sum_{n=0}^\infty \sum_{k=0}^n \frac{(-1)^n}{(k+1)\times (n-k+1)} = \sum_{n=0}^\infty \sum_{k=0}^n \frac{(-1)^k}{(k+1)}\times \frac{(-1)^{n-k}}{(n-k+1)}$$
Then this is the Cauchy product (discrete convolution) of $\sum_{k=0}^\infty \frac{(-1)^k}{(k+1)}$ with itself. We know that $\ln(1+x)=\sum_{k=1}^\infty \frac{(-1)^{k+1}x^k}{k}$, by changing the index $k \rightarrow k+1$ we get $\ln(1+x)=\sum_{k=0}^\infty \frac{(-1)^{k}x^{k+1}}{k+1}$ and we have $\ln(2)=\ln(1+1)=\sum_{k=0}^\infty \frac{(-1)^{k}}{k+1}$ and we can conclude that
$$\sum_{n=0}^\infty \sum_{k=0}^n \frac{(-1)^n}{(k+1)\times (n-k+1)} = \left(\ln(2)\right)^2$$
For the convergence part, this series $\color{red}{\text{does not}}$ converge absolutely. To prove this, we consider the tail's sum
$$ \sum_{r=m}^n \sum_{k=0}^r \Bigl|\frac{(-1)^r}{(k+1) (r-k+1)} \Bigr| = \sum_{r=m}^n\sum_{k=0}^r  \frac{1}{(k+1) (r-k+1)} $$
Now consider the inner sum
$$\sum_{k=0}^r \frac{1}{(k+1) (r-k+1)}  = \frac{1}{r+2}\sum_{k=0}^r \frac{(r-k+1) + (k+1)}{(k+1) (r-k+1)} \\ = \frac{1}{r+2}\sum_{k=0}^r\Bigl( \frac{1}{k+1}+\frac{1}{r-k+1} \Bigr) = \frac{2}{r+2}\sum_{k=0}^r \frac{1}{k+1} > \frac{2\ln(r+2)}{r+2}$$
using the integral test, because $ \sum_{k=0}^r \frac{1}{k+1} = \sum_{k=1}^{r+1} \frac{1}{k} > \int_1^{r+2} \frac{1}{x} dx = \ln(r+2)$
and overall we have
$$\sum_{r=m}^n\sum_{k=0}^r  \frac{1}{(k+1) (r-k+1)} > 2\sum_{r=m}^n \frac{\ln(r+2)}{r+2}$$
which we know diverges when $n\rightarrow \infty$ regardless to $m$ (Rudin, Principles of Mathematical Analysis, Theorem 3.29. for $p=-1$). But this series is alternating and it converges non-absolutely (again, Rudin, Principles of Mathematical Analysis, Theorem 3.43.). To show this, the only thing we need to show is $\sum_{k=0}^r \frac{1}{(k+1) (r-k+1)} \ge \sum_{k=0}^{r+1} \frac{1}{(k+1) (r-k+2)}$ because the alternating series is of the form of $\sum_{n=0}^\infty (-1)^n \Bigl( \sum_{k=0}^n \frac{1}{(k+1)\times (n-k+1)}\Bigr)$. Based on the above calculation we have to show
$$\frac{2}{r+2}\sum_{k=0}^r \frac{1}{k+1} \ge \frac{2}{r+3}\sum_{k=0}^{r+1} \frac{1}{k+1} \\ \Rightarrow \frac{1}{r+2}\sum_{k=0}^r \frac{1}{k+1} \ge \frac{1}{r+3}\sum_{k=0}^{r} \frac{1}{k+1} + \frac{1}{(r+2)(r+3)}  \\ \Rightarrow \Bigl( \sum_{k=0}^{r} \frac{1}{k+1}  \Bigr)\Bigl(\frac{1}{r+2} - \frac{1}{r+3}\Bigr)\ge \frac{1}{(r+2)(r+3)} \\ \Rightarrow \Bigl( \sum_{k=0}^{r} \frac{1}{k+1}  \Bigr)\Bigl(\frac{1}{(r+2)(r+3)}\Bigr)\ge \frac{1}{(r+2)(r+3)} $$
But that's obviously true $\square$.
Therefore the value of the series can be anything according to the Riemann's rearrangement theorem, but in this formation, the value of the series converges to $\left(\ln(2)\right)^2$
(P.S. if you want to get an intuition, think of it as $\int\int \frac{1}{x^2}$ that gives you $\ln x$ which we know is unbounded.)


text:
Q: how to rollback an entity from two entities to persists in jpa I want to rollback an entity from two entities to persists in a method where if one get exception then other will be rollback. Like as..
  @Autowired
  XYZDao xyzDao;

  private XYZ beanXYZ;

  @Autowired
  ABCDao abcDao;

  private ABC beanABC;

  public void saveBoth(){
    try {
        xyzDao.persist(beanXYZ);
        abcDao.persist(beanABC);

        } catch (Exception e) {
        logger.error("This is error : " + e);
        logger.fatal("This is fatal : " + e);
        }
    }

How can I rollback both entities if one is not persist.
Please Suggest me...

A: The behavior you want is provided by Transaction mechanism. You can achieve this by creating new DAO for combined operation which contains operations to save both beans in one transaction. Something like below:
persistAbcAndXyz(BeanABC beanABC, BeanXYZ beanXYZ){
    try{
        //get transaction from EMF and begin
        //emf.getTransaction().begin()

        //save beanABC
        //save beanXYZ

        //emf.getTransaction().commit()
    }
    catch( PersistenceException ex){
       //rollback transaction
       //emf.getTransaction().rollback();
    }
}

In case your DAOs refer to different databases such that they could not share same EntityManager Transaction, you can use external transaction management library like Spring Transactions.

A: You can annotate your saveBoth() method with @Transactional annotation.
@Transactional
public void saveBoth(){
try {
    xyzDao.persist(beanXYZ);
    abcDao.persist(beanABC);

    } catch (Exception e) {
    logger.error("This is error : " + e);
    logger.fatal("This is fatal : " + e);
    }
}

Do also look at this link for a better understanding of how transaction can be configured and how it works.


text:
Q: How do you prove axiom 2 when given a vector space of complex numbers? I know that axiom 2 states that (X + Y) + Z = X + (Y + Z) where X,Y, and Z are elements of the vector space and X = (a + bi), Y = (c + di), and Z = (e + fi).
My question is, how do I prove axiom 2 when given this equation?

A: Collect like terms on the LHS:
$$
((a + bi) + (c + di)) + (e + fi) = (?) + (?)i
$$
Then likewise, collect like terms on the RHS:
$$
(a + bi) + ((c + di) + (e + fi)) = (?) + (?)i
$$
If you get the same result both times, then you've proven that $\mathbb C$ satisfies axiom 2 for being a vector space.


text:
Q: Assetic dump reveals "_settings.scss failed to import not found or unreadable" I have been learning how to use assetic filters and integrating compass/foundation5 through assetics. When I attempt to use assetic:dump I get a mess of errors and despite my best efforts I have yet to find the solution. First off I think the root of the error lies here.
Output:
  error assetic_compassyGuG5K.scss (Line 13 of src/test/CoreBundle/Resources/public/scss/_settings.scss: File to import not found or unreadable: foundation/functions.
  Load paths:
    /tmp
    /home/test/.rvm/gems/ruby-2.1.2/gems/compass-0.12.6/frameworks/blueprint/stylesheets
    /home/test/.rvm/gems/ruby-2.1.2/gems/compass-0.12.6/frameworks/compass/stylesheets
    /var/www/test.local/public_html/src/test/CoreBundle/Resources/public/scss

I have attempted to do anything I can think of to clear the error (aside removing the filter completely, which would fix it). I even attempted to use foundation to load the site and though I got rid of this error it was replaced by a error stating that the foundation.xml could not be located.
My question is do I need to add the config.rb to the filter to define the locations or am I missing something all together in the filter?
# Assetic Configuration
assetic:
    debug:          "%kernel.debug%"
    use_controller: true
    bundles:        [ ]
    #java: /usr/bin/java
    filters:
        cssrewrite: ~
        compass:
            bin: /home/nathan/.rvm/gems/ruby-2.1.2/bin/compass
            apply_to: "/.scss$"
        #closure:
        #    jar: "%kernel.root_dir%/Resources/java/compiler.jar"
        #yui_css:
        #    jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"

parameters:
    assetic.ruby.bin: /home/nathan/.rvm/rubies/ruby-2.1.2/bin/ruby

A: The apply_to checks a regular expression, and \ indicates that the next character will be escaped (dot in this case), then, / should be replaced with \.


text:
Q: Cucumber and Silverlight 4 So I am wondering if anyone is familiar or has done any work with cucumber and Silverlight.  I currently have a template directory and build file that will create RSpec tests using Bacon (light weight RSpec).  I have been looking into SpecFlow and Cuke2Nuke but almost everything I have seen works with general .net code not silverlight code.
Thanks.

A: SpecFlow is an open-source project to do BDD with .NET. From version 3.1.2 it also supports Silverlight. You can check the sample at: http://github.com/techtalk/SpecFlow-Examples/tree/master/BowlingKata/BowlingKata-Silverlight-MsTest/
SpecFlow is using a plain text definition format (Gherkin - same format as cucumber), and it generates unit tests from it (in case of Silverlight, MsTest is supported).
You can also check the wiki about the SpecFlow Silvelight integration: https://github.com/techtalk/SpecFlow/wiki/silverlight-support


text:
Q: Elasticsearch: Does a query with filtering get affected by relevancy of records not in the filter? Imagine I have three sets of data (SetA, SetB, SetC) and three customers. My first customer has access to SetA and SetB, my second customer has access to SetA and SetC and the third uses SetB and SetC. I could create an elasticsearch index per-customer so each index would have the following sets of data...

Index1    Index2    Index3
------    ------    ------
SetA      SetA      SetB
SetB      SetC      SetC

I then query the correct index based on the customer. This is simple but does involve duplication of the data.
Instead of this I could create a single index with all three sets of data.

Index
-----
SetA
SetB
SetC

Then I would add filtering in the query so that only records from the correct sets are considered for the results. This would work but I am concerned that this single index solution would not give identical results for the queries as it would have for the multiple indexes approach.
I think, but am happy to be corrected if wrong, the index is going to take into account all the records in the index when it comes to internal scoring like relevancy and frequency. Therefore the single index with filtering will not given identical results to the multiple-index approach. Is this assumption correct?

A: If you are first, filtering the results based on your customer-id and then only searching, then there would be no impact on the relevance and you can and you should combine these data in Elasticsearch, rather than creating 3 different indices for this purpose.
You can read more about the query and filter context and their impact on the score.
Let me show you, by a small example:
Index def
{
    "mappings": {
        "properties": {
            "setA": {
                "type": "text"
            },
            "setB": {
                "type": "text"
            },
            "setC": {
                "type": "text"
            },
            "customer-id": {
                "type": "long"
            }
        }
    }
}

Index two sample docs for each customer
{
    "setA" : "first customer",
    "setB" : "first customer",
    "setC" : "",
    "customer-id" : 1
}

{
    "setA" : "first customer set A",
    "setB" : "first customer set B",
    "setC" : "",
    "customer-id" : 1
}

{
    "setA" : "second customer",
    "setC" : "second customer",
    "customer-id" : 2
}

{
    "setA" : "second customer set A",
    "setC" : "second customer set C",
    "customer-id" : 2
}
{
    "setB" : "third customer",
    "setC" : "third customer",
    "customer-id" : 3
}

{
    "setB" : "third customer set A",
    "setC" : "third customer set C",
    "customer-id" : 3
}

Search query by first filtering the first customer and then searching with the relevance score
{
    "query": {
        "bool": {
            "must": [ --> this would match and order according to relevance score
                {
                    "match": {
                        "setA": "first"
                    }
                }
            ],
            "filter": [ --> this is used for filtering all docs for cust-1
                {
                    "term": {
                        "customer-id": 1
                    }
                }
            ]
        }
    }
}

Search result
 "hits": [
            {
                "_index": "so_query_filter",
                "_type": "_doc",
                "_id": "1",
                "_score": 0.8025915, --> relevance is high
                "_source": {
                    "setA": "first customer",
                    "setB": "first customer",
                    "setC": "",
                    "customer-id": 1 --> only cust-1 doc
                }
            },
            {
                "_index": "so_query_filter",
                "_type": "_doc",
                "_id": "2",
                "_score": 0.60996956, -> relavance is low as more words than first
                "_source": {
                    "setA": "first customer set A",
                    "setB": "first customer set B",
                    "setC": "",
                    "customer-id": 1 --> only cust-1 doc
                }
            }
        ]


text:
Q: botocore: how to close or clean up a session or client While doing some automation around AWS-EC2 with the botocore library in Python, I noticed a lot of HTTPS connections remained established that were no longer needed by processes that were busy doing other things (so killing them or recoding them to exit is not an option).  I think the botocore session and/or client object is leaving the connections to AWS endpoints established.  The botocore documentation shows how to start or create them, but not how to close them or clean things up.  I tried a .close method but it did not exist.  How can I get these connections to gracefully close without killing the processes?

A: I had the same issue, but from a slightly different angle: When closing worker threads, my log files would get cluttered with these warnings - also due to open connections:

Exception ignored in: <ssl.SSLSocket fd=4, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('[internal ip]', 49266), raddr=('[external ip]', 443)>
ResourceWarning: unclosed <ssl.SSLSocket fd=4, family=AddressFamily.AF_INET, type=2049, proto=6, laddr=('[internal ip]', 49266), raddr=('[external ip]', 443)>

After some time down the rabbit hole, I have figured out how to close the connections correctly, before closing the threads.
I'm using SQS with boto3, so you might need to modify the call a bit for it to work with botocore.
My example to produces the warning above is:
import boto3
import boto3.session
import warnings

warnings.simplefilter('error', ResourceWarning)  # Display warnings
session = boto3.session.Session()
sqs = session.resource('sqs', region_name=AWSregion)
sqs_q = sqs.Queue(url=SQSQueueUrl)
sqs_msg = sqs_q.receive_messages(MaxNumberOfMessages=1)

The SQS connection can be closed using:
sqs.meta.client._endpoint.http_session.close()  # closing a boto3 resource
sqs._endpoint.http_session.close()  # closing a boto3 client


text:
Q: Google's new Places Library ( implementation 'com.google.android.libraries.places:1.0.0') not resolving I am attempting to migrate to the new Places SDK client, but the dependency I'm told to install in the documentation is giving me a "failed to resolve" error. I made sure to remove the old SDK and the places-compat library, followed by cleaning and rebuilding.
Here is my list of dependencies:
dependencies {
       implementation 'com.android.support:support-v4:28.0.0'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation fileTree(include: ['*.jar'], dir: 'libs')
        implementation 'com.android.support:appcompat-v7:28.0.0'
        implementation 'com.android.support:support-v13:28.0.0'
        implementation 'com.android.support:cardview-v7:28.0.0'
        implementation 'com.android.support:customtabs:28.0.0'
        implementation 'com.android.support:design:28.0.0'
        implementation 'com.android.support:support-media-compat:28.0.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        implementation 'com.android.support:recyclerview-v7:28.0.0'
        implementation 'com.android.support:multidex:1.0.3'
        implementation 'android.arch.paging:runtime:1.0.1'
        implementation 'com.google.code.gson:gson:2.8.5'
        implementation 'org.jetbrains:annotations:16.0.2'
        implementation 'com.google.android.gms:play-services-auth:16.0.1'
        implementation 'com.google.android.gms:play-services-ads:17.0.0'
        implementation 'com.google.android.libraries.places:1.0.0'
        implementation 'com.facebook.android:facebook-android-sdk:4.38.1'
        implementation 'com.google.firebase:firebase-core:16.0.4'
        implementation 'com.firebaseui:firebase-ui-auth:4.2.0'
        implementation 'com.google.firebase:firebase-firestore:18.0.0'
        implementation 'com.firebaseui:firebase-ui-firestore:4.1.0'
        implementation 'com.google.firebase:firebase-auth:16.1.0'
        implementation 'com.google.firebase:firebase-ads:17.0.0'
        implementation 'com.google.firebase:firebase-messaging:17.3.4'
        implementation('com.crashlytics.sdk.android:crashlytics:2.9.6@aar') {
            transitive = true
        }
    }

apply plugin: 'com.google.gms.google-services'

and here is my project level gradle file:
buildscript {

    repositories {
        google()
        jcenter()
        mavenCentral()
        maven{
            url 'https://maven.fabric.io/public'
        }
        maven{
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath'com.google.gms:google-services:4.2.0'
        classpath 'io.fabric.tools:gradle:1.26.1'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://maven.google.com/'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: This is not an issue from your side, but from Google's. You might have got the dependency from this link https://developers.google.com/places/android-sdk/start right? They have provided this dependency there:
dependencies {
    implementation 'com.google.android.libraries.places:1.0.0'
}

But instead you have to follow this link https://developers.google.com/places/android-sdk/client-migration, where you will get the correct dependency. which is :
dependencies {
    implementation 'com.google.android.libraries.places:places:1.0.0'
}

A: that dependency is invalid; that should be:
dependencies {
    implementation "com.google.android.libraries.places:places:1.1.0"
}

see the migration guide.


text:
Q: ruby rspec error "expected: 1 got: #'Weight converter'
Trying to get the hang of using stubs but I can't get the format right, what do I have wrong?  I know I already have the method in the code in this case but I am trying to learn how to do a stub correctly.
Test:
describe "Convert Pounds to Kilograms" do

it "should convert 3lb to 1kg" do
  weight = WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1)
  weight.should == 1
end

Code:
class WeightConverter

  def self.convert(from, what_to_what)
    if what_to_what == 'lbs_to_kgs'
      (from / 2.2).truncate
    elsif what_to_what == 'kgs_to_lbs'
      (from * 2.2).truncate
    end
  end
end

fyi - this works (without stubs)
  it "should convert 91lbs to 41kgs" do
    weight = WeightConverter.convert(91, 'lbs_to_kgs')
    weight.should == 41
  end

Error:
Failures:
 1) Convert Pounds to Kilograms should convert 3lb to 1kg
     Failure/Error: weight.should == 1
       expected: 1
            got: #<Proc:0x000000010b0468@/home/durrantm/.rvm/gems/ruby-1.9.3-p125/gems/rspec-mocks-2.10.1/lib/rspec/mocks/message_expectation.rb:459 (lambda)> (using ==)
     # ./weight_converter_spec.rb:19:in `block (2 levels) in <top (required)>'

Finished in 0.00513 seconds
7 examples, 1 failure

A: You don't want to assign to the stub, rather you should be doing something like this:
it "should convert 3lb to 1kg" do
  WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1)
  weight = WeightConverter.convert(3, 'lbs_to_kgs')
  weight.should == 1
end

However, that's a fairly useless test -- the only thing it's testing is that your stub/mock library does what it's supposed to (i.e. it's not actually testing WeightConverter at all). Since you're directly testing the internals of WeightConverter, you don't need to stub it. You should be using actual values like in your second example. However, if WeightConverter depended on another class, you might stub that other class.


text:
Q: Does this logic make sense? Property1 = Property1 My ASP.NET page has a lot of HTML elements that are visible/enabled based on conditions, for example:
Element1
Element3
Element5

visibility depends on let's say
Checkbox1
DateTime.Now

Does it make sense to encapsulate this in a property called SectionVisibility such that
private bool SectionVisibility
{
    get {condition1 && condition2 && etc...}
    set {element1, element2 etc... = value; }
}

and in Page_Load call SectionVisibility = SectionVisibility?
Assume that I have a lot of conditions.

A: I wouldn't write code like this. It violates POLS.
SectionVisibility = SectionVisibility looks like it doesn't do anything. And it should behave that way.
I would create a method called CalculateSectionVisibility (currently your getter) and one called ApplySectionVisibility (currently your setter).
If they are always used in combination you could squash them together into a method UpdateSectionVisibility.


text:
Q: Android Development and retrofit My Question is simple i want to retrieve my github repos with the help github api using retrofit in android, So i am little confuse how to pass my github username to url i have tried but it give me error message.
This is my webservice URL for retrieving my github repos :
https://api.github.com/users/mshahzaib374/repos. Here you can see my username is mshahzaib374, So how can i pass my username to url as parameter.
I hope you understand my question, I am attaching code snippets and error screen please see it, Thanks for advance.

A: Retrofit homepage contains sample code that very similar to what you want:
public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

So, to insert username in URL you have to substitute part of URL with some name in curly braces and add corresponding parameter to method marked with @Path("<your parameter name>") annotation.

A: You can make a GET API call like this
GET /users/:username/repos

Check this out the official GIT api documentation.
Hope it helps you.


text:
Q: WSO2 Registry Load Balanced URL? We have deployed WSO2 in clustered mode on two nodes. We are using external load balancer instead of internal elastic load balancer for traffic. How can we define this external load balanced URL in the config so that email notifications get the correct URL instead of individual nodes?
Thanks.

A: I found it, we need to update carbon.xml, uncomment & set HostName & MgtHostName values
<!--
Host name or IP address of the machine hosting this server e.g. www.wso2.org,   192.168.1.10 This is will become part of the End Point Reference of the services deployed on this server instance.    -->
<HostName>yourloadbalanced.yourcompany.com</HostName>
<!--    Host name to be used for the Carbon management console    -->
<MgtHostName>yourloadbalanced.yourcompany.com</MgtHostName>

Thanks


text:
Q: Best Practice For XSS Attacks in Rest Api I have read a lot about it, but couldnt really decide which way is the best.
I have a web app and a java rest application which serves to customers.
What is the best way to prevent xss attacks using parameters in rest api and frontend?

*

*Validating each parameter in both server and client side

*Filter and control request params

*On client side control before putting every data in between tags
etc...
Thank you for your time.

A: As with anything defense in depth is important, so validation and encoding should be done on any user provided input. Encoding is very important because what might be considered malicious is contextual. For example, what might be safe HTML might be an SQL Injection attack.
Parameters in a REST API may be saved which means they are returned from subsequent requests or the results may be reflected back to the user in the request. This means that you can get both reflected and stored XSS attacks. You also need to be careful about DOM Based XSS attacks. A more modern categorization that addresses overlap between stored, reflected, and DOM XSS is Server XSS and Client XSS.
OWASP has a great Cross Site Scripting Prevention Cheat Sheet that details out how to prevent cross site scripting. I find the XSS Prevention Rules Summary and the Output Encoding Rules Summary sections to be very handy.
The big take away is that browsers parse data differently depending on the context, so it is very important that you don't just HTML Entity Encode the data everywhere. This means it is important to do two things:

*

*Rule #0 - Only insert untrusted (user provided) data in allowed locations. Only insert data into an HTML document into a "slot" defined by Rules #1-5.

*When you insert data into one of the trusted slots follow the encoding rules for that specific slot. Again the rules are detailed in the previously linked Cross Site Scripting Prevention Cheat Sheet.
There is also a DOM based XSS Prevention cheat sheet. Like the server side XSS cheat sheet, it provies a set of rules to prevent DOM based XSS.

A: When it comes to XSS only possible choice is to validate user input, any kind of user input, whether it is passed from the browser or in any other way (like from terminal client).
It depends on the scenario you are following.
If it is just data without HTML content then you don't need to worry about XSS.
Otherwise, just removing <,> symbols or casting them into character encoded string would be enough.
Also you can avoid using innerHTML to append new content to the document, use innerText instead and even if there are XSS content it won't execute.
But it gets little bit complicated when api response returns HTML content as well which you need to display somewhere. In such cases avoid directly displaying user input inside HTML snippet - try to character encode or remove <, > symbols and it will be just fine


text:
Q: Python Parsing data from site using lxml I'm new to Python. That's why I'm asking help.
I need to parse ssome data from site. I'm using Python 2.7.
So here's my code:
import urllib
import lxml.html

url = 'http://www.pogoda.YANDEX.RU/MOSCOW'
sock = urllib.urlopen(url)
content = sock.read()
pageReady = u'content.decode()'
page = urllib.urlopen('http://pogoda.yandex.ru/moscow/')
xmldata = lxml.html.document_fromstring(pageReady)
temperature = xmldata.xpath('//div[@class="b-thermometer__now"]/text()')
clouds = xmldata.xpath('//div[@class="b-info-item b-info-item_type_fact-big"]/text()')
sock.close()

print('%s, %s'%(temperature[0], clouds[0]))

So I got next message:
File "weather.py", line 15, in <module> print('%s, %s'%(temperature[0], clouds[0]))
IndexError: list index out of range

A: This is because your temperature and clouds are empty lists.

A: pageReady contains just content.decode() as its content because of following line:
pageReady = u'content.decode()'

You should use page.read() to get content of the web page as follow:
import urllib
import lxml.html

# pageReady = u'content.decode()'   <----------- Remove/comment out this line.
page = urllib.urlopen('http://pogoda.yandex.ru/moscow/')
pageReady = page.read()   # <-------------------------------
xmldata = lxml.html.document_fromstring(pageReady)
temperature = xmldata.xpath('//div[@class="b-thermometer__now"]/text()')
clouds = xmldata.xpath('//div[@class="b-info-item b-info-item_type_fact-big"]/text()')
page.close()

print('%s, %s'%(temperature[0], clouds[0]))


text:
Q: The existence of an elliptic curve with a specific Galois representation induced by a character In Kevin Buzzard's survey article on potential modularity Buzzard writes:

Let us say that we have an elliptic
  curve $E$ over a totally real field $F$,
  and we want to prove that $E$ is
  potentially modular (that is, that $E$
  becomes modular over a finite extension
  field $F^{′}$ of $F$, also assumed totally
  real). Here is  a strategy. Say $p$ is
  a large prime such that $E[p]$ is
  irreducible. Let us write down a
  random odd $2$-dimensional mod $ℓ$
  Galois representation $\rho_{ℓ} :
> Gal(\overline{F}/F)  → GL(2,\mathbf{F}_ℓ )$ which is
  induced from a character; because this
  representation is induced it is known
  to be modular. Now let us consider the
  moduli space parametrising elliptic
  curves $A$ equipped with

*

*An isomorphism $A[p] \cong E[p] $

*An isomorphism $A[ℓ]\cong ρ_ℓ$

  This moduli problem will be
  represented by some modular curve,
  whose connected components will be
  twists of $X(pℓ)$ and hence, if $p$
  and $ℓ$ are large, will typically have
  large genus. However, such a curve may
  well still have lots of rational
  points, as long as I am allowed to
  look for such things over an arbitrary
  finite extension $F^{′}$ of $F$ !

It's not immediately obvious to me that there's an elliptic curve $A$ over some $F^{′}$ satisfying the second condition alone (never mind satisfying both conditions simultaneously). Is there a simple explanation for why there should be such an $A$? Did Professor Buzzard mean "consider the set of A such that $A[ℓ]\cong ρ_ℓ$ for some representation induced by a character" (as opposed to a particular one)?

A: In this context, if $\rho$ is a mod $\ell$ representation of $Gal(\overline{F} / F)$, and $A$ is an elliptic curve over an extension $F' / F$, then the statement "$A[\ell] \cong \rho$" needs a little bit of interpretation, because the two sides are representations of different things: $A[\ell]$ is a mod $\ell$ representation of the subgroup $Gal(\overline{F} / F') \subset Gal(\overline{F} / F)$. So the statement is to be read as "$A[\ell]$ is isomorphic as a $Gal(\overline{F} / F')$-representation to the restriction of $\rho$". Now, the bigger $F'$ is, the weaker this condition becomes: in particular, if we take any elliptic curve $A$ over $F$ and define $F'$ to be the extension of $F$ generated by the $\ell$-torsion points of $A$ and the splitting field of $\rho$, then the statement is automatic (both sides are the trivial representation).
(This is kind of a stupid example, but maybe you can believe now that there exist non-stupid examples as well!)


text:
Q: Managing Releases/Features with TFS Branches So, I've been scratching my head for a couple of days trying to come up with an efficient way to manage Releases/Iterations with TFS branches.
Here's the situation:
We have a project for which we have releases, and for each release we have iterations. Releases are the new versions that we put into production and iterations are just development phases that need to be tested in QA.
Iterations are a bit like features. Let's say you want to develop a web site to show items (iteration 1), and then sell them (iteration 2) and package it all in the first release. For the QA fix, it is done in the iteration branch and merged in QA. Since we don't commit in QA there's no conflict to resolve when we merge.
So the workflow looks like this (a lot of parallel work needs to be done because of the tight schedule):

*

*For Release 1

*

*Start the development of Iteration 1

*Start the development of Iteration 2

*Iteration 1 goes into QA

*Start the development of Iteration 3

*Iteration 1 QA is done

*Iteration 2 goes into QA

*Release 2 starts...

In resume, lots of parallel development, one iteration in QA at a time, when all the release's iteration went through QA it goes to production.
So we need to come up with a branching solution that allows to easily merge between development branches, and then go into a QA branch. So far, we came up with this branch structure
- Main
   |- QA_Release_1
   |  |- DEV_Iteration_1
   |     |- DEV_Iteration_2
   |        |- DEV_Iteration_3
   |- QA_Release_2
      |- ...

With this, we can easily merge between dev branches. But at some point when iteration 1 QA comes to an end, we disable the branch (either by deleting it, or deny acces to check out/in). When that time come, the strategy is to reparent the DEV_Iteration_2 to QA_Release_1.
For this to be done, we need to make a baseless merge, which creates a lot of conflicts. And if I understand correctly, a baseless merge is just a folder compare, without taking into account the change set merges that happened before.
So I guess the first question would be how much merge trouble (if any) are we getting ourselves into by doing this? Is it OK to just ignore the enormous merge and just fix the tons of conflicts when reparenting?
Second would be: is there any more efficient way to achieve that goal?
Edit: I miss git...
We continued searching for a solution, and a coworker sent me this link:
Gitflow Workflow
Which is, if you take out what's directly related to git, exactly what we need to do. It would probably look like this in TFS:
- Main
   |- Develop
      |- QA_Release_1
      |- DEV_Iteration_1
      |- DEV_Iteration_2
      |- QA_Release_2

Problem is, TFS doesn't like skipping branches. As soon as you don't merge in the parent or a child, it's considered as a baseless merge. So since the QA_Release_1 is created under Develop, it won't easily merge into the Main. This brings me back to my first question: are baseless merge a trap?

A: On my job I use the following model:
Branches:

*

*Trunk/Main branch

*

*build and automated tests are OK

*no unfinished work (if a change needs several commits, use feature branch)

*ready to become a release candidate (if a change introduces any blocker, it's not committed here)

*Feature branch

*

*created if a feature or a fix needs more than one commit

*a branch for a specific feature or a bug fix

*everything is allowed: broken build, failing tests

*eventually is merged to trunk

*occasionally trunk is merged to it (to reduce deviation between branches)

*before merge to the trunk everything should be cleaned

*Stabilization branch

*

*created for every version to be supported

*matches some revision of the trunk + merges of some changes later + workarounds

*builds for manual testing are created from here

Workflows:

*

*Small feature/fix:

*

*just commit to trunk

*Big feature/fix:

*

*create feature branch

*make many commits there

*merge to the trunk

*delete the feature branch

*Fix for a bug found by manual testing:

*

*fix in the trunk (by #1 or #2)

*merge to the stabilization branch

*Workaround (quick and dirty fix which we will clean later):

*

*fix directly in the stabilization branch

*do not merge to the trunk

I used it on SVN and TFS and it doesn't seems to create problems. Since all branches are made from the trunk TFS should have no problems with merge.


text:
Q: nlog.Docker.config doesn't override nlog.config (.NET 6) Things i have checked:

*

*nlog.Docker.config and nlog.config are at the root of the container

*'Docker' is correctly recognized as the hosting enviroment, which means appSettings.Docker.json properly overrides appSettings.json

*All .config and .json files are copied over to the root of the container

Im initializing the logger with
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();


text:
Q: Changing date format from date field in database I am using ASP.NET with SQL Server 2005.
My date get saved in the database with data type = "smalldatetime".
I am displaying the date value into a text box called txtDate with a Reader......
    Dim conn As Data.SqlClient.SqlConnection
    Dim Comm As Data.SqlClient.SqlCommand
    Dim reader As Data.SqlClient.SqlDataReader

    conn = New Data.SqlClient.SqlConnection(..............)

    Comm = New Data.SqlClient.SqlCommand( _
    ("SELECT * FROM Table1 WHERE Age = 88"), conn)

    conn.Open()

    reader = Comm.ExecuteReader()

    If reader.Read() Then

        txtDate.Text = reader.Item("theDate").ToString

    End If

    reader.Close()
    conn.Close()

But currently my date get displayed as "2008/06/30 12:00:00 AM" and i want to display it as "30 June 2008".
How can this be done?

A: Replace ToString with ToString("dd MMMM yyyy"). You might want to look in MSDN at the overloads for DateTime.ToString, and at date-time formatting strings.
Other points with your code - if you really are selecting a single value from a single row, then restrict your select list (i.e. don't use SELECT *) and consider using ExecuteScalar rather than ExecuteReader...

A: How the data is stored in the database is irrelevant - you'll be getting a DateTime back in your client code. You then just need to format that however you want.
Try something like this:
If reader.Read() Then
    Dim date as DateTime = CType(reader.Item("theDate"), DateTime)
    txtDate.Text = date.ToString("dd MMMM yyyy")
End If

Here the "dd" means "day of month", "MMMM" means "month of year in full" and "yyyy" means "4-digit year".
See MSDN on custom date and time format strings for more details. Alternatively, you could use a standard date and time format string which would take account of your current culture. (The custom ones will take account of that for each individual field, so month names will be appropriate to the culture, but the order and style of the fields to be formatted is fixed by the format string.)

A: You should use the data format to string.
Cast your value reader.Item("theDate") to a DateTime object and the use the ToString Method.
yourDateTime.ToString("dd MMMM yyyy");

Have a look at these

*

*Date and Time Format Strings

*DateTime.ToString() Patterns


text:
Q: Onchange 1st date picker, 2nd datepicker will change in my form, i have 2 datepicker (eg : date1, date2). Date1 is approval deadline and date2 is confirmation daedline. Approval deadline should be equal or more than confirmation deadline. I'm using this datepicker sample.
$myCalendar = new tc_calendar("date1", true);
$myCalendar->setIcon("calendar/images/iconCalendar.gif");
$myCalendar->setDate(date('d'), date('m'), date('Y'));
$myCalendar->setPath("calendar/");
$myCalendar->zindex = 150; //default 1
$myCalendar->setYearInterval(date('Y'), date('Y')+2);
$myCalendar->dateAllow('2011-01-01','');
$myCalendar->setSpecificDate($MalHolidays, 0, '');
$myCalendar->setSpecificJapanDate($JapHolidays, 0, '');
$myCalendar->setAlignment('right', 'bottom'); //optional
$myCalendar->writeScript();

So. I want if user change date2, date1 will automatically change accordingly (same as input for date2).
But whenever date1 is change, it will effect itself only (only date1 change). Hopefully you can understand this situation.
I think that this can be done using jquery, but i'am new in jquery, i hope that you guys can help me.
Thanks.

A: You can use the change event and then use the option to set the minDate of the approval deadline.
$("#date2").change(function(){
    var date = $(this).datepicker('getDate');
    $('#date1').datepicker('option', 'minDate', date)
});

Demo: Fiddle


text:
Q: How to update the ng-repeat view of a list? This simple fiddle displays a list using ng-repeat. But if I change the list from outside the DOM (in this case, using a timer), the list view does not get updated.
What do I have to do to fix this?

A: Because you're calling setTimeout( fn ) from outside of Angular, the digest cycle doesn't know that the variable has been updated.
Try using Angular's $timeout service so that when the function is run, Angular will know to apply the digest cycle.
Updated example
Edit: example using $scope.$apply(), in case $timeout is not what's being used.
From the comments: "Yeah, you can run if(!$scope.$$phase) $scope.$apply(). There is also $scope.$digest if you're just digesting the local scope. JSFiddle"
Code example from within controller:
$scope.lines = lines;
setTimeout(function() {
    lines.push({text: 'new text'});
    console.log('Line added: ' + lines.length);
    if ( !$scope.$$phase ) $scope.$apply();
}, 1000);


text:
Q: Java Interface Implement I am studying Java, Spring and POI. I see https://poi.apache.org/spreadsheet/quick-guide.html and follow it.
At "New WorkBook", next code exists.
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();

Running above code, it works well.
I found out that "Workbook" is NOT class BUT interface. I learned that interface HAVE TO be implemented. But I CANNOT found the implementation. Where is it implemented? What must I study to comprehend it?

A: Oficial Oracle tutorial about interfaces:
https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

A: That is interface instance. Details: Using an Interface as a Type
In short, you can create instance of interface.
Case 1: for anonymous class.
Workbook wb = new Workbook() {
// Some implementation
}

Case 2: Use it as type. (Yes! your case!)
Workbook wb = new XSSFWorkbook();

see also: Strategy Design Pattern in Java. It is very useful idea.


text:
Q: Replace a image resource URl with my domain address I don't know how exactly to explain my question.
I have a URL of image: http://hostimages.com/flower/images1.jpg. Now I want to replace this hostimages.com with my domain myhost.com. So the new URL will be like http://myhost.com/flower/images1.jpg
Is it possible to setup mydomain DNS like this? I already tried with CNAME and URL redirect, but not working.

A: If you can not host the image on your web host and to access it via the domain the other way I can think of is to create URL redirect, but with a path saving option, this way when you ask for http://myhost.com/flower/images1.jpg you will get http://myhost.com/flower/images1.jpg, but have in mind that you would probably need to create the redirect for a subdomain, if you have another service (like a web site) using http://myhost.com.
So probably it will be okay to create the redirect for images.myhost.com or resources.myhost.com


text:
Q: Parallels Plesk 12.0.18 - can not send mails using php while spf turned on I recently upgraded my Parallels Plesk Panel from version 11 to 12.0.18 running on CentOS. And i noticed i can't send mails anymore using the php function "mail" while SPF-Spamprotection is enabled. I am using postfix as mailserver and mails get always rejected becaus of wrong helo (localhost).
This is what the log says:
spf filter[2532]: Starting spf filter...
spf filter[2532]: Wrong HELO hostname: localhost
/usr/lib64/plesk-9.0/psa-pc-remote[2465]: handlers_stderr: REJECT
/usr/lib64/plesk-9.0/psa-pc-remote[2465]: REJECT during call 'spf' handler
postfix/cleanup[2515]: 4E4D620AE2: milter-reject: END-OF-MESSAGE from    localhost[127.0.0.1]: 5.7.1 Command rejected; from=<> to=<xxx@xx.xx>
postfix/cleanup[2515]: 4E4D620AE2: to=<xxx@xx.xx>, relay=none, delay=0.08, delays=0.08/0/0/0, dsn=5.7.1, status=bounced (Command rejected)

Turning off SPF Protection works and mails get delivered but thats not what i want. On previous version of Plesk everything worked just fine.
I already searched for a solution but found nothing useful.
Now my question is: how do i get this to work again?

A: Check your SPF-Records in your DNS settings for the domain you are sending from  i.ex:
xxx.xx  TXT v=spf1 +a +mx -all +a:your_host_name
Which means:

*

*all ips of the a-records are allowed to send mails under this
domainname

*all ips of the mx-records are allowed to sent mails under this domainname

*domains send over hostname are allowed to sent mails under this domainname

At least if i remember correctly you can change the HELO domain for php mail function in php.ini
From php documentation (http://php.net/manual/en/ref.mail.php):
; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting.  you can manually set the ehlo/helo name if required

hostname=


text:
Q: Where does ElasticSearch store an index by default? I am currently indexing a large volume of data into ElasticSearch and I am not entirely sure where ES is actually storing the indices. My worries are that the indices are growing too large and might take up the entire space I have available on disk. In this sense, I would like to move them elsewhere (by creating snapshots and restoring them).
In the configuration it is specified that the actual location of the indices is /path/to/data, but inside my data folder I simply cannot find them. Also, is it possible to leave ES in the current location and point it to store indices in a different place?

A: The default location for the index is < installation_folder>/data.
Yes, it is possible to change that value to something else, so you can have ES installed in one location, but the data will be in another. It is actually a best practice since it makes upgrades easier. In ES 1.6, its even possible for shadow replicas, meaning the index data can be shared by a couple of ES instances.


text:
Q: Is it a good idea to create a new "message table" for each user? Should I worry about performance if I use a single table? I'm working on an app that will have messages exchange and which have a database with several tables to all users data and preferences but I got thoughtful about the table of messages. I will have about 10k users that will exchange about 500k messages per month.
I have saw some questions in concern of this but are about of tables to store preferences and data, what I consider very different cases. So I was building the logic in this way, creating a table for each user, in a database created only for these message tables, so I can find the messages faster.
I thought: there would be 500k messages to query per month against 40~50 messages per month if having a table for each user.
What do you guys think about this?

A: 500K is not a large number of records for a relational database.  Just use a single table, index the UserID fields, and you shouldn't have to worry about performance.
It is more likely that you'll take a performance hit on the added complexity of one table per user.
Further reading
10.3 Limits on Table Size


text:
Q: Why doesn't my table accept these entries? My application can successfully post data to a server, and have that data saved to a file - to be later read by the server. However, when trying to save the data to the database nothing happens.
<?php

// Create connection`
$con=mysql_connect("exemple.com","user","password");
mysql_select_db("database");

// receive data from app's http request
$name=$_POST["name"];
$people=$_POST["people"];
$club=$_POST["club"];
$day=$_POST["day"];
$sql="INSERT INTO users (name, people, club, day) VALUES ($name, $people, $club, $day)");
mysql_query($con,$sql);
mysql_close($con);

A: your input should be like this:
$sql="INSERT INTO users (name, people, club, day) VALUES ('".$name."', '".$people."', '".$club."', '".$day."')";

else u will not save the value of each variable


text:
Q: How to pass arguments in a java action within an oozie workflow? I'm trying to create a Oozie workflow with one action, a java action to launch a program to parse an excel file inside HDFS, so, in order to this java program parse the file I need to pass it the location of the file, without the oozie workflow I just call the jar file with the arguments I need like:
   java -jar myJarFile.jar hdfs:///path/to/the/file.xlsx

Now in the java action inside the oozie workflow I need to write something like:
<action name="parse-file">
 <java>
  <job-tracker>${jobTracker}</job-tracker>
  <name-node>${nameNode}</name-node>
  <main-class>parseFile</main-class>
  <arg>path/to.the/file.xlsx</arg>
  <file>lib/myJarFile.jar#myJarFile.jar</file>
 </java>
 <ok to="sen-success-email"/>
 <error to="failed-notification-email"/>
</action>

Is this approach correct?

A: *

*The java action will execute the public static void main(String[] args) of your class. Make sure you use fully specified package name. For example a.b.c.MainClass

*You don't need the <file> tag if you store myJarFile.jar in a lib directory next your workflow.xml on HDFS. For example:

workflow_dir/workflow.xml
workflow_dir/lib
workflow_dir/lib/myJarFile.jar

*

*Make sure you also upload all dependencies with your workflow.

References:

*

*Description of the Java action: https://oozie.apache.org/docs/5.1.0/WorkflowFunctionalSpec.html#a3.2.6_Java_Action

*Sample workflow xml for a Java action: https://github.com/apache/oozie/blob/master/examples/src/main/apps/java-main/workflow.xml#L30


text:
Q: In a Salesforce Number field, how much performance impact does its length have? Does a 2,2 field perform noticeably better than a 16,2 if the same value (e.g. 24.45) is stored in the context of

*

*Apex

*DML

*Formulas

*whatever I forgot, please add

To clarify: This question assumes the manipulation of as many records as might be needed to actually perceive the impact. (Thx, Drew)

A: The only things we need to concern ourselves with are writing optimal Apex Code and Visual Flows, and trust that the platform will provide the most optimal storage and performance that it can. The only time we care about using (2,2) instead of (16,2) is for Custom Settings, where each digit configured uses additional bytes in our limited Custom Settings storage space. Custom settings should always be configured to use exactly as many digits as necessary, and no more.
Aside from Custom Settings storage, all other number fields are stored in a standardized format, which supports at least 18 digits of accuracy on the left and right size of the decimal point. In Apex Code, this translates to a usage of 28 bytes of memory per number retrieved from the database, regardless if the number is 1.0, 12345678901234567.8, or any other type of value that can be stored in a Decimal.
During a DML operation, incoming values are translated to this same standardized format, regardless of the configured display values; in this way, a (2,2) number uses the same amount of space as a (16,2) number. Formulas always operate on the internal format and then round the final result to fit in the display format of the formula (e.g. if the formula returns 2 decimal places, it will be rounded as such).
Note that because the internal storage format is much larger than any value you can configure, this can cause some strange side effects if you load values of higher precision in the database than the display precision. For example, if you add an Opportunity Product to an Opportunity, and set the Quantity to 1.499, the displayed value for Quantity will be 1.50, but the Amount on the Opportunity will be set to (Unit Price * 1.499), which will lead to a visual discrepancy.
Unlike traditional databases, the size of the record "on disk" does not reflect the amount of data storage that we're "charged" with using. For example, an Account always uses 2KB of data storage, even if it has a Description that is several pages long (which would clearly use more than 2KB by itself). So, unlike MySQL, where fine-tuning the parameters would have a performance in terms of record size or other metrics, this setting has absolutely no effect on the performance of the Salesforce application.
You should always use the most appropriate number based on business needs instead of trying to tune for performance, because it's largely out of your hands anyways. Salesforce.com works hard to make sure that the database is operating at peak efficiency with minimal effort for developers, meaning we can focus on designing applications instead of worrying about platform nuances.


text:
Q: How to know what submit button the user clicked? I'm working on my settings page, I want to add two different buttons to the form and do something different depending which the user clicked.
The documentation states I can create two buttons like this:
submit_button('Submit', 'primary large', 'primary', false);
submit_button( 'Delete', 'delete', 'delete', false );

However I don't understand how to differenciate when the user clicked each one, it seems that no matter which button clicked the form is submitted the same.
How can I do something different depending what button the user clicks?

A: The submit_button() function is a wrapper for get_submit_button(). Now that function has multiple arguments, but the most interesting for your actual problem is the 3rd argument name. It sets the HTML name attribute.
<form action="">
    <input ... etc.
    <button type="submit" name="choice-a">
</form>

Now everytime you process your form with an empty action attribute, you will point to the current request http://example.com/wp-admin/example.php. There you will be able to fetch your arguments via the super globals $_POST or $_REQUEST (which simplified is mostly a combination of $_GET and $_POST).
Then just inspect the array and do whatever you need/want to do.


text:
Q: Dynamic Vue Table I'm trying to make a dynamic table in Vue, but I'm struggling with the way I would like to show the data.
This is what I get from the API: (There are more values but I'll keep it simple.)
{id: 1, descricao: 'Ambiente 01', valor: "12.5"}
{id: 2, descricao: 'Ambiente 02', valor: "5.5"}
{id: 3, descricao: 'Ambiente 03', valor: "-2.5"}
{id: 4, descricao: 'Ambiente 01', valor: "12.2"}
{id: 5, descricao: 'Ambiente 02', valor: "5.2"}
{id: 6, descricao: 'Ambiente 03', valor: "-2.3"}
{id: 7, descricao: 'Ambiente 01', valor: "11.9"}
{id: 8, descricao: 'Ambiente 02', valor: "5.7"}
{id: 9, descricao: 'Ambiente 03', valor: "-2.8"}

This is what my vue component looks like:
<template>

          {{ descricao }}

          {{ row.valor }}

</template>

And this is what my table looks like:
Table
The problem is that the data that corresponds to each column is being displayed in a row, and I have no clue of how to change it. In order to explain it better, I will try to ilustrate the result I'm getting and the result I would like to get...
What I have...

Ambiente 01 | Ambiente 02 | Ambiente 03
---------------------------------------
12.5        | 12.2        | 11.9
---------------------------------------
5.5         | 5.2         | 5.7
---------------------------------------
-2.5        | -2.3        | -2.8

What I want...

Ambiente 01 | Ambiente 02 | Ambiente 03
---------------------------------------
12.5        | 5.5         | -2.5
---------------------------------------
12.2        | 5.2         | -2.3
---------------------------------------
11.9        | 5.7         | -2.8

I appreciate if someone explains me how to achieve this.
Thanks in advance!

A:

      {{ data[3 * (index - 1)].valor }}
      {{ data[3 * (index - 1) + 1].valor }}
      {{ data[3 * (index - 1) + 2].valor }}

data.length / 3 because you have 3 different columns.
Where data is an array of elements like this:
data: [
    { id: 1, descricao: "Ambiente 01", valor: "12.5" },
    { id: 2, descricao: "Ambiente 02", valor: "5.5" },
    { id: 3, descricao: "Ambiente 03", valor: "-2.5" },
    { id: 4, descricao: "Ambiente 01", valor: "12.2" },
    { id: 5, descricao: "Ambiente 02", valor: "5.2" },
    { id: 6, descricao: "Ambiente 03", valor: "-2.3" },
    { id: 7, descricao: "Ambiente 01", valor: "11.9" },
    { id: 8, descricao: "Ambiente 02", valor: "5.7" },
    { id: 9, descricao: "Ambiente 03", valor: "-2.8" }
]

A: <template>

          {{ descricao }}

          {{ dados[row-1] && dados[row-1].valor }}

</template>


text:
Q: HTML CSS: How to add Sliding Header? In Boostrap Slide show carousel, how would I add my descriptions to the title above instead of below at the captions sliding? I am trying to find Bootstrap functionality to conduct this, but I cannot locate it. It is sliding in the below pictures, I want to place it at the top where green box is.
Does Bootstrap allow this functionality?

.carousel-inner {
  border-style: solid;
  border-color: black;
  border-right-width: 1px;
  border-left-width: 1px;
  border-bottom-width: 1px;
}

.carouselheader {
  text-align: center;
  background-color: green;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  overflow: hidden;
  height: 32px;
  border-color: black;
  border-style: solid;
  border-top-width: 1px;
  border-right-width: 1px;
  border-left-width: 1px;
}

.carousel slide {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  overflow: hidden;
}

.carouselleftarrow {
  font-family: Material Icons;
  font-size: 36px;
  position: absolute;
  bottom: 5px;
  content: "\e408";
  color: black;
}

.carouselleftarrow:hover {
  color: black;
}

.carouselrightarrow {
  font-family: Material Icons;
  font-size: 36px;
  position: absolute;
  bottom: 5px;
  content: "\e409";
  color: black;
}

.carouselrightarrow:hover {
  color: black;
}

.carousel-indicators li {
  text-indent: 0 !important;
  width: 24px !important;
  height: 24px !important;
  margin: 3px !important;
  border-radius: 50px !important;
  bottom: 3px;
  font: 10px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  color: #999999;
  background-color: blue;
  font-size: 14px;
}

.carousel-indicators li.active {
  color: white;
  background-color: black;
}

.carousel-indicators li:hover {
  color: white;
  background-color: black;
}

.left .carousel-control {
  border-radius: 8px;
  background-image: none;
}

.right .carousel-control {
  border-radius: 8px;
  background-image: none;
  display: inline-flex;
}

.carousel-control.left {
  background-image: none;
}

.carousel-control.right {
  background-image: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<ipts-carousel>

Place Descriptions in Top Here

1

2

3

Ocean sea

Ocean Sea has nice view

Nice Houses

Neighboor houses in Chicago

Reading Books

Stack of library books

navigate_beforenavigate_next

</ipts-carousel>

A: After some adaptations...
Live example:

.carousel-inner {
  border-style: solid;
  border-color: black;
  border-right-width: 1px;
  border-left-width: 1px;
  border-bottom-width: 1px;
  display: inline-block;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.carousel slide {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  overflow: hidden;
}

.carouselleftarrow {
  font-family: Material Icons;
  font-size: 36px;
  position: absolute;
  bottom: 5px;
  content: "\e408";
  color: black;
}

.carouselleftarrow:hover {
  color: black;
}

.carouselrightarrow {
  font-family: Material Icons;
  font-size: 36px;
  position: absolute;
  bottom: 5px;
  content: "\e409";
  color: black;
}

.carouselrightarrow:hover {
  color: black;
}

.carousel-indicators li {
  text-indent: 0 !important;
  width: 24px !important;
  height: 24px !important;
  margin: 3px !important;
  border-radius: 50px !important;
  bottom: 3px;
  font: 10px;
  display: none;
  justify-content: center;
  align-items: center;
  flex-direction: row;
  color: #999999;
  background-color: blue;
  font-size: 14px;
}

.carousel-indicators li.active {
  color: white;
  background-color: black;
}

.carousel-indicators li:hover {
  color: white;
  background-color: black;
}

.left .carousel-control {
  border-radius: 8px;
  background-image: none;
}

.right .carousel-control {
  border-radius: 8px;
  background-image: none;
  display: inline-flex;
}

.carousel-control.left {
  background-image: none;
  border-radius: 8px;
}

.carousel-control.right {
  background-image: none;
  border-radius: 8px;
}

.carousel-caption {
  width: 100%;
  top: 0;
  padding: 8px !important;
  text-align: center;
  background: green;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  overflow: hidden;
  height: 69px;
  border-color: black;
  border-style: solid;
  border-top-width: 1px;
  border-right-width: 1px;
  border-left-width: 1px;
  right: 0 !important;
  left: 0 !important;
}

.carousel-caption h3 {
  margin: 0px;
}

.carousel-caption p {
  margin: 0px;
}

.carousel-inner>.item>a>img,
.carousel-inner>.item>img {
  top: 69px;
  position: absolute;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<ipts-carousel>

1

2

3

Ocean sea

Ocean Sea has nice view

Nice Houses

Neighboor houses in Chicago

Reading Books

Stack of library books

navigate_beforenavigate_next

</ipts-carousel>