text:
Q: Model field value does not get updated m2m_changed(Django) I have been searching for an answer for hours, however every answer I found does not work. Also trying to find a bug on my own didn't bring me any results.
I have created a receiver function which should update model's total_likes attribute(based on number of users_like attribute) every time user click on the like button of the specific image. (This is a part of 'Django by Example` book). But the field's value stays always the same and is equal to default value of 0. Even if I try to assign the value to the field manually, in the django's shell, it does not change(code example in 'Update' section).
Can someone please have a look at the code and point me in the right directions if I am doing something wrong?
I am using Django 1.9.
# models.py
class Image(models.Model):
    ...
    users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    related_name='images_liked',
                                    blank=True)
    total_likes = models.PositiveIntegerField(default=5)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
            super(Image, self).save(*args, **kwargs)

# signals.py
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Image

@receiver(m2m_changed, sender=Image.users_like.through)
def users_like_changed(sender, instance, **kwargs):
    instance.total_likes = instance.users_like.count()
    instance.save()

# apps.py
from django.apps import AppConfig

class ImagesConfig(AppConfig):
    name = 'images'
    verbose_name = 'Image bookmarks'

    def ready(self):
        # import signal handlers
        import images.signals

# __init__.py
default_app_config = 'images.apps.ImagesConfig'

Update:
When I run code below from django shell, this does change the total_likes value, but it looks like it do just temporary:
from images.models import Image
for image in Image.objects.all():
    print(image.total_likes)
    image.total_likes = image.users_like.count()
    print(image.total_likes)
    image.save()
    print(image.total_likes)

Output from code above:
0 #initial/default value of 0
3 #current number of users who like the picture
3

Because when I run the for loop code again, to see the results(or even check the field value in admin interface) i still get the initial/default value of 0.
Can someone see the problem why the field does not get updated?

A: Ok, so the problem was with the custom save() method on the model class.
I needed to call the save() method of the parent class like this:
def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title)
    super(Image, self).save(*args, **kwargs)

and it made it work.


text:
Q: would rather eat or ate? Would rather (but not would prefer to) is also followed by a past tense when we want to involve other people in the action, even though it has a present or future meaning. Study the following:
a.Shall we go out for dinner tonight? ~ No, I'd rather we ate at home, if you don't mind.
b.My rephrased:  Shall we go out for dinner tonight? ~ No, I'd rather we eat at home, if you don't mind.
I have extracted the italic parts from a grammar site, but would you tell me if the bold part is correct, too? If so, what is the difference between a. and b. semantically?

A: I believe you asked about a special use of would rather.
Without trying to explain the grammar point on my own, I will let you read what the author says about this special usage.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: how to check entries with white spaces in a dataframe? I have a dataframe df containing the information of car brands. For instance,
df['Car_Brand'][1]
'HYUNDAI                       '

where the length of each entries is the same len(df['Car_Brand'][1])=30. I can also have entries with only white spaces.
df['Car_Brand']

0          TOYOTA
1          HYUNDAI
2
3
4
5          OPEL
6
7          JAGUAR

where
df['Car_Brand'][2]
'                              '
I would like to drop from the dataframe all the entries with white spaces and reduce the size of the others. Finally:
df['Car_Brand'][1]
'HYUNDAI                       '

becomes
df['Car_Brand'][1]
'HYUNDAI'

I started to remove the withe spaces, in this way:
tmp = df['Car_Brand'].str.replace(" ","")

A: using str.strip and convert it to bool to filter the empty ones
df['Car_Brand'] = df['Car_Brand'].strip()

df[df['Car_Brand'].astype(bool)]

A: It seems need:
s = df['Car_Brand']
s1 = s[s != ''].reset_index(drop=True)
#if multiple whitespaces
#s1 = s[s.str.strip() != ''].reset_index(drop=True)
print (s1)
0     TOYOTA
1    HYUNDAI
2       OPEL
3     JAGUAR
Name: Car_Brand, dtype: object

If multiple whitespaces:
s = df[~df['Car_Brand'].str.contains('^\s+$')]


text:
Q: Using np.array on Reportlab, Python I am doing a script to generate a report on PDF after some image analysis, the problem is that reading the examples of reportlab they load an image by filename and then generate it on the report, but I have the image as a np.array and don't want to save it because there will be a lot of images, and when I tried to do this reportlab command
#asd is the image variable
asd=plt.imread(imagen_fl)
#then do some image processing....
canvas.drawImage(asd, 1*cm, 3*cm, 10*cm, 10*cm )

I get the next error:
AttributeError: 'numpy.ndarray' object has no attribute 'rfind'

Any solution or recomendation?


text:
Q: KeyError when parsing JSON results in Python I am encountering a KeyError when parsing JSON results in Python.  I've searched other questions relating to KeyError, but none of the answers has helped so far.  When I make the web request
https://property.melissadata.net/v4/WEB/LookupProperty?id=MY_LICENSE_KEY&t=&cols=GrpPrimaryOwner&format=json&ff=5933 NE Garfield Avenue, Portland, OR, 97211

from a web browser, it returns the result
{"Version":"5.0.1.1043","TransmissionResults":"","TotalRecords":1,"Records":[{"Results":"YS02,YS07,YC01","Parcel":{"FIPSCode":"41051","UnformattedAPN":"R243379","FormattedAPN":"R243379"},"Legal":{},"PropertyAddress":{},"ParsedPropertyAddress":{},"PrimaryOwner":{"Name1Full":"PORTLAND PIEDMONT GUESTHOUSE L","Name1First":"","Name1Middle":"","Name1Last":"PORTLAND PIEDMONT GUESTHOUSE L"...
The result of the Python code
import requests
import pprint
# api-endpoint
URL = "https://property.melissadata.net/v4/WEB/LookupProperty?id=MY_LICENSE_KEY&t=&cols=GrpPrimaryOwner&format=json"
# location given here
location = "5933 NE Garfield Avenue, Portland, OR  97211"
# defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}
# sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)
# extracting data in json format
data = r.json()
pprint.pprint(data)
name = data['Records'][0]['PrimaryOwner'][0]['Name1Full'][0]
print('name: ' + name)

is
{'Records': [{'Results': 'YE01'}],
 'TotalRecords': 1,
 'TransmissionResults': '',
 'Version': '5.0.1.1043'}
>>> name = data['Records'][0]['PrimaryOwner'][0]['Name1Full'][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'PrimaryOwner'
>>> print('name: ' + name)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "list") to str

I would like to extract the Name1Full value of "PORTLAND PIEDMONT GUESTHOUSE L" from the JSON results.  I appreciate any help you can provide.
Solution:
This works when PARAMS = {'address':location} is replaced with PARAMS = {'ff':location}

A: Given the piece of json you provide I believe you should try with:
full_name = data['Records'][0]['PrimaryOwner']['Name1Full']

Let's see how this work:
[Records][0] access:
{"Results":"YS02,YS07,YC01","Parcel":{"FIPSCode":"41051","UnformattedAPN":"R243379","FormattedAPN":"R243379"},"Legal":{},"PropertyAddress":{},"ParsedPropertyAddress":{},"PrimaryOwner":{"Name1Full":"PORTLAND PIEDMONT GUESTHOUSE L","Name1First":"","Name1Middle":"","Name1Last":"PORTLAND PIEDMONT GUESTHOUSE L"...

We then need see that Name1Full is a value for the PrimaryOwner key, therefore [`Records'][0]['PrimaryOwner'] access:
{"Name1Full":"PORTLAND PIEDMONT GUESTHOUSE L","Name1First":"","Name1Middle":"","Name1Last":"PORTLAND PIEDMONT GUESTHOUSE L"...

Finally we add the key Name1Full to access the specific value [`Records'][0]['PrimaryOwner']['Name1First']:
Returning:
"PORTLAND PIEDMONT GUESTHOUSE L"

A: The JSON you pretty print in the second part of your question doesn't have a 'PrimaryOwner' field which is why you are getting a key error.
{'Records': [{'Results': 'YE01'}],
 'TotalRecords': 1,
 'TransmissionResults': '',
 'Version': '5.0.1.1043'}

I think the question is: Why is your program getting different JSON data than your web browser? I can't help you further with that but perhaps someone else can.

A: I simplified the problem.  You are not getting what you think you are getting back.  This snippet below reproduces the problem, I have removed the extraneous code.
data = {'Records': [{'Results': 'YE01'}],
 'TotalRecords': 1,
 'TransmissionResults': '',
 'Version': '5.0.1.1043'}

name = data['Records'][0]['PrimaryOwner'][0]['Name1Full'][0]
print('name: ' + name)

A: This works when PARAMS = {'address':location} is replaced with PARAMS = {'ff':location}


text:
Q: Jenkins Android Build Error: FAILURE: Build failed with an exception I have been trying to do CI using Jenkins for my Android application. I am new to this. After following some of the tutorials, I am able to atleast set up and run the build now option. It download every pom required but while building it give below error.
============================================
C:\Windows\System32\config\systemprofile.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\e796469c387c11565d873216f24c3b6f\res\drawable\abc_ic_go_search_api_material.xml: error: file not found.
C:\Windows\System32\config\systemprofile.gradle\caches\transforms-1\files-1.1\play-services-base-15.0.1.aar\7207fbd3bdb6cb696445cfc77c16e5ed\res\drawable-hdpi-v4\googleg_standard_color_18.png: error: file not found.
C:\Windows\System32\config\systemprofile.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\e796469c387c11565d873216f24c3b6f\res\layout\select_dialog_singlechoice_material.xml: error: file not found.
Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
:app:mergeDebugResources FAILED
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
======================================================
Can you please let me know how to resolve it?
Do let me know if anything else is required.

A: Maybe the path is too long. Try this:

*

*Jenkins --> Project --> Project Configuration --> Build

*Select advanced option

*Check the option box "Force GRADLE_USER_HOME to use workspace"

*Build your project

I solved my problem by this way, good luck!

A: Try updating your android gradle plugin version to 3.2.0-alpha12 or newer. AAPT2's version included in these versions contains many fixes for path support on Windows which resulted in similar errors.

A: you can solve this by separating into smaller group of task
make separate invoke gradle script under build tab

*

*clean build assembleDebug

*test

*connectedAndroidTest

i had similar issues, when i ran assembleDebug and test together in Jenkins as a single task

A: When using Jenkins with Window to build Android, I face this problem myself.
I fix by add GRADLE_USER_HOME to Environment Variable:
GRADLE_USER_HOME = C:\Users\*MyUserName*\.gradle

hope this help,


text:
Q: How to serialize ANY Object into a URI? My basic question: is there anything built that already does this automatically (doesn't have to be part of a popular library/package)? The main things I'm working with are Spring (MVC) and Jackson2.
I understand there are a few manual ways to do this:

*

*Create a method in each class that serializes its specific properties into property=value& form (kind of stinks because it's a bunch of logic duplication, I feel).

*Create a function that accepts an object, and uses reflection to dynamically read all the properties (I guess the getters), and build the string by getting each. I'm assuming this is how Jackson works for serialization/deserialization in general, but I really don't know.

*Use some feature of Jackson to customly serialize the object. I've researched custom serializers, but it seems they are specific to a class (so I'd have to create one for each Class I'm trying to serialize), while I was hoping for a generic way. I'm just having trouble understanding how to apply one universally to objects. A few of the links:

*

*http://techtraits.com/Programming/2011/11/20/using-custom-serializers-with-jackson/

*http://wiki.fasterxml.com/JacksonHowToCustomSerializers

*Use ObjectMapper.convertValue(object, HashMap.class);, iterate over the HashMap's key/value pairs, and build the string (which is what I'm using now, but I feel the conversions are excessive?).

*I'm guessing there's others I'm not thinking of.

The main post I've looked into is Java: Getting the properties of a class to construct a string representation
My point is that I have several classes that I want to be able to serialize without having to specify something specific for each. That's why I'm thinking a function using reflection (#2 above) is the only way to handle this (if I have to do it manually).
If it helps, an example of what I mean is with, say, these two classes:
public class C1 {
    private String C1prop1;
    private String C1prop2;
    private String C1prop3;

    // Getters and setters for the 3 properties
}

public class C2 {
    private String C2prop1;
    private String C2prop2;
    private String C2prop3;

    // Getters and setters for the 3 properties
}

(no, the properties names and conventions are not what my actual app is using, it's just an example)
The results of serializing would be C1prop1=value&C1prop2=value&C1prop3=value and C2prop1=value&C2prop2=value&C2prop3=value, but there's only one place that defines how the serialization happens (already defined somewhere, or created manually by me).
So my idea is that I will have to end up using a form of the following (taken from the post I linked above):
public String toString() {
    StringBuilder sb = new StringBuilder();
    try {
        Class c = Class.forName(this.getClass().getName());
        Method m[] = c.getDeclaredMethods();
        Object oo;
        for (int i = 0; i < m.length; i++)
        if (m[i].getName().startsWith("get")) {
            oo = m[i].invoke(this, null);
            sb.append(m[i].getName().substring(3) + ":"
                      + String.valueOf(oo) + "\n");
        }
    } catch (Throwable e) {
        System.err.println(e);
    }
    return sb.toString();
}

And modify it to accept an object, and change the format of the items appended to the StringBuilder. That works for me, I don't need help modifying this now.
So again, my main question is if there's something that already handles this (potentially simple) serialization instead of me having to (quickly) modify the function above, even if I have to specify how to deal with each property and value and how to combine each?
If it helps, the background of this is that I'm using a RestTemplate (Spring) to make a GET request to a different server, and I want to pass a specific object's properties/values in the URL. I understand I can use something like:
restTemplate.getForObject("URL?C1prop1={C1Prop1}&...", String.class, C1Object);

I believe the properties will be automatically mapped. But like I said, I don't want to have to make a different URL template and method for each object type. I'm hoping to have something like the following:
public String getRequest(String url, Object obj) {
    String serializedUri = SERIALIZE_URI(obj);
    String response = restTemplate.getForObject("URL?" + serializedUri, String.class);
    return response;
}

where SERIALIZE_URI is where I'd handle it. And I could call it like getRequest("whatever", C1Object); and getRequest("whateverElse", C2Object);.

A: Lets we have c1.
c1.setC1prop1("C1prop1");
c1.setC1prop2("C1prop2");
c1.setC1prop3("C1prop3");

Converts c1 into URI
    UriComponentsBuilder.fromHttpUrl("http://test.com")
            .queryParams(new ObjectMapper().convertValue(c1, LinkedMultiValueMap.class))
            .build()
            .toUri());

After we will have
    http://test.com?c1prop1=C1prop1&c1prop2=C1prop2&c1prop3=C1prop3

A: I think, solution number 4 is OK. It is simple to understand and clear.
I propose similar solution in which we can use @JsonAnySetter annotation. Please, see below example:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        C1 c1 = new C1();
        c1.setProp1("a");
        c1.setProp3("c");

        User user = new User();
        user.setName("Tom");
        user.setSurname("Irg");

        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.convertValue(c1, UriFormat.class));
        System.out.println(mapper.convertValue(user, UriFormat.class));
    }
}

class UriFormat {

    private StringBuilder builder = new StringBuilder();

    @JsonAnySetter
    public void addToUri(String name, Object property) {
        if (builder.length() > 0) {
            builder.append("&");
        }
        builder.append(name).append("=").append(property);
    }

    @Override
    public String toString() {
        return builder.toString();
    }
}

Above program prints:
prop1=a&prop2=null&prop3=c
name=Tom&surname=Irg

And your getRequest method could look like this:
public String getRequest(String url, Object obj) {
    String serializedUri = mapper.convertValue(obj, UriFormat.class).toString();
    String response = restTemplate.getForObject(url + "?" + serializedUri, String.class);
    return response;
}


text:
Q: how to find the "cutoff" index in a vector? I have a vector that contains "chuncks" of data , seperated by "chuncks" of almost-zero ( < epsilon)
for example:
[ 18, 19, 34, 27, 0.1, 0.02, 0.04, 0.15 , 19, 23, 20, 34 ]

lI would like to find the indexes where the almosא-zeros sequence begin and ends,
i.e: the index of 0.1 (5) and the index of 0.15 (8)
an important obsevastion is that there could be some almost-zeroes before the "cutoff" , but not a "long" sequence
for examle, if i have the vector:
[30 , 14, 15 , 89, 0.3, 17 , 40, 0.4, 0.05, 0.1, 0.2, 80, 16, 40, 1, 22]

i would like to get back the indexes: 8, 11
any suggestion for a goos loop-avoiding way to do that?
thank you

A: In Matlab, this kind of simple problems can be vectorized without any loops like so:
x = [30 , 14, 15 , 89, 0.3, 17 , 40, 0.4, 0.05, 0.1, 0.2, 80, 16, 40, 1, 22];
epsilon = 0.5;
close_to_zero = x < epsilon;  % logical vector

% get logical vectors indicating 0-1 and 1-0 transitions
start = ~close_to_zero(1:end-1) & close_to_zero(2:end);
stop = close_to_zero(1:end-1) & ~close_to_zero(2:end);

% get indices of transitions
istart = find(start) + 1;
istop = find(stop);

% get length of sequences and kick out short ones
sequence_length = istop - istart + 1;
long_sequence = sequence_length > 2;  % logical vector
istart = istart(long_sequence)
istop = istop(long_sequence)

Result:
istart = 8
istop = 11

Note that this only works when the vector x does not start or end with a sequence close to zero. To solve this problem, you should pad close_to_zero with a False on the beginning and the end (close_to_zero = [false, x < epsilon, false];) and adjust the indices accordingly by subtracting 1.


text:
Q: Bash to send variable value to csv? I've the following data. I've only given 2 servers here for the sake of simplicity. This servers list might be change from time to time, the same goes with the variable value.
hostname = 'server1'
var1 = 'abc'
var2 = 'xyz'
var3 = 'def'

hostname = 'server7'
var1 = 'ghi'
var2 = 'mno'
var3 = 'jkl'

Would it be possible to send it to csv format, probably something like this?
output.csv
Hostname    Variable    Value
server1     var1        abc
server1     var2        xyz
server1     var3        def
server7     var1        ghi
server7     var2        mno
server7     var3        jkl

At the moment, I copy paste the value manually to Ms Excel. I would like to automate this process, but not sure about the implementation yet.
I really appreciate if you could share some ideas or sample code.

A: Using awk:
awk -F"[=' ]" -v OFS=, '
$1=="hostname"{ hn=$5; next }
!hdr && hn    { print "Hostname", "Variable", "Value"; hdr=1 }
NF   && hn    { print hn, $1, $5 }' infile >output.csv

with -F"[=' ]", we defined either of =, ' and Space characters as the field separators, so awk will split the lines to the fields based on these separators.
with OFS=,, the output generates in comma delimited fields to produce a simple csv file, change this to some other characters based on your need.

A: Using Miller and running
<input.txt sed "s/'//g" | mlr --x2c --ips "=" clean-whitespace then reshape -r "var" -o variable,value

you will have
hostname,variable,value
server1,var1,abc
server1,var2,xyz
server1,var3,def
server7,var1,ghi
server7,var2,mno
server7,var3,jkl

A: The answer is pretty the same as @αғsнιη.
I use a BEGIN block to write the header and an assignement $0 = "" ot empty the line when this hold the server name.
awk -F"[= ']" -vOFS=, 'BEGIN {print "Hostname", "Variable", "Value"} $5~/^server[0-9]+$/ && h=$5 {$0 = ""} $0!~/^$/ {print h, $1, $5}' data


text:
Q: How to split a statement based on dots ('.'), while excluding dots inside angular brackets(< . >) using regular expressions in python? I want to split statements by dots using regex in python, while excluding certain dots inside the angular brackets.
eg:
Original Statement :
'my name 54. is <not23.> worth mentioning. ok?'

I want to split it into following sentences:
Statement 1 : 'my name 54'
Statement 2 : ' is <not23.> worth mentioning'
Statement 3 : ' ok'

I have attempted
re.split(r'[^<.>]\.','my name 54. is <not23.> worth mentioning. ok?')

But, it's not ignoring dot inside <>,
so the result am getting is:
['my name 5', ' is <not23', '> worth mentioning', ' ok?']

A: Easy if you can user the newer regex module (it provides the (*SKIP)(*FAIL) functionality):
import regex as re

string = 'my name 54. is <not23.> worth mentioning. ok?'
rx = re.compile(r"<[^>]*>(*SKIP)(*FAIL)|\.")

parts = rx.split(string)
print(parts)
# ['my name 54', ' is <not23.> worth mentioning', ' ok?']

A: Split on the following regex:
\.(?![^<]*>)

Live demo
import re

str = 'my name 54. is <not23.> worth mentioning. ok?'
regex = re.compile(r"\.(?![^<]*>)")
arr = regex.split(str)

print(arr)


text:
Q: Japanese/chinese email addresses? I'm making some site which must be fully unicode.
Database etc are working, i only have some small logic error.
Im testing my register form with ajax if fields are valid, in email field i check with regular expressions.
However if a user has a email address like 日本人@日人日本人.com it isn't coming trough.

*

*This type of mail addresses exist?

Are email addresses always like this? (a-z A-Z 0-9) @ (a-z A-Z 0-9).(a-z A-Z 0-9)

A: As per RFC 5322 ("Internet Message Format"), section 3.4.1 ("Addr-Spec Specification") you can't use non US-ASCII characters such as those you've listed. However, characters such as...
! # $ % & ' * + - / = ? ^ _  { | } ~

...are legal, as well as the full stop/period character as long as there's only one in a row.
For more information see the above RFC and indeed the Wikipedia article on email addresses, specifically the "syntax" section.
UPDATE
There's also a newer, albeit experimental, RFC 5336 (now obsoleted by RFC6531) which handles the now legitimate international domains containing UTF-8 characters, etc.

A: You must be very careful when you try to match/validate email addresses on a regex. In some cases you reject email addresses which however are valid. Basically its:

Show me one regex and I show you one email which doesn't match.

For that reason if I check email addresses I use a very simple regex like .+@.+(\..+)* (user part anything, host part got at least one dot). Anything else results in false positives and false negatives.
Its better not to match email addresses (only check trivial stuff like "@") but instead send opt-in emails instead.

A: Usually address are in the form
[_a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[_a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)+

on in other words \w+(\.\w+)*@\w+(\.\w+)+. Also this site have useful information about email address patterns:
http://www.regular-expressions.info/email.html

A: Seems like not that many people mentioned the existence issue. People before me have given beautiful regular expressions, so I won't repeat those.
I don't know much about the Japanese side, but at least as a native Chinese speaker who has been using Chinese for main Internet browsing language, I have never seen email address in Chinese. There was once a while domains with Chinese characters are popular. But I believe it was accomplished at the DNS side and it was a commercial bubble. Now you can rarely seen domains with Chinese character in real use any more. So are the Email addresses.

A: Many years have passed since original question. If you want copy-paste and actually working good answer, use one provided here https://emailregex.com/
It handles many edge cases and also some not. If you want to catch all edge cases, for example completely valid "@v@"@example.com, you need to make regex even longer. Example of regex taken from website above in my C++ code looks like this:
std::regex(
             "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/"
             "=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-"
             "\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:"
             "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-"
             "z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:"
             "25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:["
             "\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\["
             "\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])",
             std::regex::nosubs | std::regex::ECMAScript | std::regex::icase)


text:
Q: SQL query is overlooking a WHERE condition when filtering information from database The following section of code is used to to filter data from an html page in real time from an SQL database using ajax. For some reason the condition in the SQL statement ignores the following condition samples_database.sample_storage != 'discarded' but it works in the second part of the else statement.
if(isset($_POST["query"])) {
    $search = mysqli_real_escape_string($conn, $_POST["query"]);
    $query .= "
    SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id
    WHERE samples_database.sample_storage != 'discarded'
    AND samples_database.env_sam_id LIKE '%".$search."%'
    OR samples_database.c_sam_id LIKE '%".$search."%'
    OR samples_database.sample_type LIKE '%".$search."%'
    OR storage_database.storage_name LIKE '%".$search."%'
    ORDER BY samples_database.env_sam_id;";
} else {
    $query .= "
    SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id WHERE sample_storage != 'discarded' ORDER BY samples_database.env_sam_id;";
}

Can anybody help me this this silly problem please?

A: There's an order of precedence: AND is calculated before OR:
if(isset($_POST["query"])) {
    $search = mysqli_real_escape_string($conn, $_POST["query"]);
    $query .= "
    SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id
    WHERE samples_database.sample_storage != 'discarded'
    AND (samples_database.env_sam_id LIKE '%".$search."%' OR
         samples_database.c_sam_id LIKE '%".$search."%' OR
         samples_database.sample_type LIKE '%".$search."%' OR
         storage_database.storage_name LIKE '%".$search."%')
    ORDER BY samples_database.env_sam_id;";
} else {
    $query .= "
    SELECT * FROM samples_database JOIN storage_database on samples_database.storage_location=storage_database.id WHERE sample_storage != 'discarded' ORDER BY samples_database.env_sam_id;";
}

A: In the else part you have only 1 condition:
sample_storage != 'discarded'

so it can't be "ignored".
But in the if part you have something like this:
A and B or C or D or E...

If one of C or D or E... is true then the result is true and you think that A is "ignored".
So make use of parentheses around each part that suits your needs.
maybe something like this:
A and (B or C or D or E...)


text:
Q: Best Way to Read a File in Chunks of Characters in Java Let's say I have a class File which contains a reference to a file:
public class Streamer {
    [...]
    File f = new File(path)
    [...]
}

What would be the easiest way to implement a method readNextBlock()? This method would return the first n characters of the file if executed once. If executed a second time, it would return the next n characters, and so on, until it reaches the end of the file. For example:
public class Main {

    public static void main(String[] args) {
        Streamer streamer = new Streamer();
        String block1 = streamer.readNextBlock() //Return first n characters
        String block2 = streamer.readNextBlock() //Return next n characters
        [...]
        String blockn = streamer.readNextBlock() //Returns NULL if end of file is reached
    }
}

I tried implementing the iterator interface but I'm not sure if I'm on the right track.

A: A simple way to do this is to wrap another Reader with a simple class like this:
/**
 * Read fixed-sized chunks from an underlying {@link Reader}
 */
public class ChunkReader {
    private final int chunkSize;
    private Reader reader;

    public ChunkReader(Reader reader, int chunkSize) {
        if (chunkSize <= 0) {
            throw new IllegalArgumentException("Chunk size must be > 0");
        }
        this.reader = reader;
        this.chunkSize = chunkSize;
    }

    public String readChunk() throws IOException {
        if (reader == null) {
            return null;
        }
        char[] cbuf = new char[chunkSize];
        int off = 0;
        int read = 0;
        while (read < chunkSize) {
            int ret = reader.read(cbuf, off, chunkSize-off);
            if (ret == -1) {
                reader = null;
                if (read == 0) {
                    return null;
                }
                break;
            }
            read += ret;
        }
        return new String(cbuf, 0, read);
    }
}

You could turn it into an Iterator fairly easily if you want, but there's one small caveat: we don't quite know if the next readChunk call will return null if the last one succeeded fully (i.e. read a full chunk), because the underlying Reader could immediately return -1 on the first call. So we'll need to do some sneaky look-aheads for this:
public class ChunkIterator implements Iterator<String> {
    private final int chunkSize;
    private Reader reader;
    private String next;

    public ChunkIterator(Reader reader, int chunkSize) {
        if (chunkSize <= 0) {
            throw new IllegalArgumentException("Chunk size must be > 0");
        }
        this.reader = reader;
        this.chunkSize = chunkSize;
    }

    private String readChunk() throws IOException {
        // same as above
    }

    @Override
    public boolean hasNext() {
        if (next != null) {
            return true;
        }
        if (reader == null) {
            return false;
        }
        try {
            next = readChunk();
        } catch (IOException e) {
            // could also return false, depending on your requirements
            throw new RuntimeException(e);
        }
        return next != null;
    }

    @Override
    public String next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return next;
    }
}


text:
Q: Outputting searched data to another form I'm currently building a system which gets a unique value and uses that as a login i.e a reference number. The reference number then searches the database and outputs all corresponding data to another page, I am struggling with this, my code is:
Index.PHP

<input name="search_box"  type="text" class="auto-style1" id="search_box" style="width: 240px; height: 30px" maxlength="12">

<input type="submit" name="search" value="Enter" class="auto-style1" style="width: 63px; height: 30px">
<?php $reasons = array("search_box" => "Please Enter Valid Reference Number", "" => "Error"); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>

</form>

Check.php
 <?php
include "conn.php";

mysql_connect("localhost","root") or die(header("location:index.php?loginFailed=true&reason=search_box"));
mysql_select_db("DB1") or die(header("location:index.php?loginFailed=true&reason=search_box"));

$reference1 = $_POST['search_box'];

$sql = "SELECT * FROM test_table1 WHERE No =$R1";
$result = mysql_query($sql) or die(mysql_error());
    if ($result)
    $count = mysql_num_rows($result);
    else
    $count = 0;

if($count == 1)
 {
  session_register('search_box');
  header("location:result.php");
  }
else
{
echo (header("location:index.php?loginFailed=true&reason=search_box"));
 }
 ?>

Output.php
 <?php
include "conn.php";

$sq2 = "SELECT * FROM test_table1";
if (isset($_POST['search']))
 {
    $search_term = mysql_real_escape_string($_POST['search_box']);

    $sq2 .= "WHERE No =  '{$search_term}'";
}

$query= mysql_query($sq2, $con);

while($row = mysql_fetch_array($query)) { ?>
  Ref Number:    <?php echo $row['No']; ?>

  Location:   <?php echo $row['Country']; ?>

<?php
mysql_close($con);
?>

Any help you guys could give would be highly appreciated, Thanks.
Qwerty.

A: You problem (the one you are probably wondering about right now (as there seems to be a few more potencial ones and exploits)) is in Output.php.
At the time you call that file from Login_check.php (because you are redirecting te browser) you'r $_POST array does no longer contain any data.
To make it easier on yourself, why not include "Output.php"; instead of redirecting the browser by headers()? That way you would not need to reinitialize the session or database in the Output.php again.
If you require this redirect however, store your $_POST['search'] to $_SESSION['search'] after your session is initialized and then reffer to $_SESSION['search'] in Output.php instead of (as you have it now) to $_POST['search']
Hope that helps a little.

A: So i am assuming that you have one table donations where you have some donId (reference No.) of the donation, donName of the person donating, donCountry the country the donator is from and donAmount how much money they donated.
Your file would look something like this (i will not bother with all the proper headers for html, so the result will not be a w3c valid html but it should work in your browser without problems.
I think i MUST say that you should not use the mysql_query and all other mysql_... functions use instead mysqli_*. The following code though is still using the old these days already deprecated mysql_ functions, so it's in your interest to upgrade it accordingly to mysqli (that's a home work ;) lol )
File donInfo.php:

<form action='donInfo.php' method='post'>
    Reference No.:
    <input type='text' size='6' name='donId' id='donId' value='' />
    <input type='submit' name='do' value='  Show me!  ' style='margin-left:2em;'/>
</form>

<?php
    /* table definition:
    CREATE TABLE donations (
        donId int unsigned not null,
        donCountry varchar(80) not null,
        donName varchar(80) not null,
        donAmount numeric(11,2) not null,
        PRIMARY KEY (donId)
    )
    */
    if (!isset($_POST['do']) || !isset($_POST['donId']) || !$_POST['donId'])
        exit;

    require_once 'connection.php';

    $don=mysql_fetch_assoc(
        mysql_query('SELECT * '.
            'FROM donations '.
            'WHERE donId="'.mysql_real_escape_string($_POST['donId'],$con).'"',$con));
    if ($don===false || !$don['donId'])
        print '
Donation id #'.$_POST['donId'].' does not exist!
';
    else {
        print '
Information about donation id #'.$_POST['donId'].'
'.
            'State: '.$don['donCountry'].'
'.
            'Donator: '.$don['donName'].'
'.
            'Amount: $ '.number_format($don['donAmount'],2).'
'.
            '
';

        $sumP=mysql_fetch_assoc(
            mysql_query('SELECT SUM(donAmount) total, COUNT(*) donx '.
                'FROM donations '.
                'WHERE donName="'.mysql_real_escape_string($don['donName'],$con).'" '.
                'GROUP BY donName',$con));
        print '
Donations from '.$don['donName'].':
'.
            'Total Amount: $ '.number_format($sumP['total'],2).'
'.
            'Donated '.number_format($sumP['donx'],0).' times to date.
'.
            '
';

        $sumC=mysql_fetch_assoc(
            mysql_query('SELECT SUM(donAmount) total, COUNT(DISTINCT donName) donators, COUNT(*) donx '.
                'FROM donations '.
                'WHERE donCountry="'.mysql_real_escape_string($don['donCountry'],$con).'" '.
                'GROUP BY donCountry',$con));
        print '
Donations from '.$don['donCountry'].':
'.
            'Total Amount: $ '.number_format($sumC['total'],2).'
'.
            'Total of '.number_format($sumC['donx']).' donations from '.number_format($sumC['donators'],0).' donators.
'.
            '
';

        $sumW=mysql_fetch_assoc(
            mysql_query('SELECT SUM(donAmount) total, COUNT(DISTINCT donName) donators, COUNT(DISTINCT donCountry) countries, COUNT(*) donx '.
                'FROM donations '.
                'GROUP BY 1=1',$con));
        print '
Donations Total:
'.
            'Total Amount: $ '.number_format($sumW['total'],2).'
'.
            'Total of '.number_format($sumW['donx']).' donations from '.number_format($sumW['countries'],0).' countries and '.number_format($sumW['donators'],0).' donators.
'.
            '
';
    }
?>

I have tested the code, so it should work well. i'm using your connection.php script where (i guess) you are initializing your database.
short description of what it does:
Asks for an ID, then when submited it checks whether it exist or not and if yes, it will print information about THAT donation id, information about user of that id, about country of that id and total donation statistic. If the donation Id does not exist, it will just say: does not exist while waiting for another ID to be entered.


text:
Q: Absolute file path of assets in Rails' asset pipeline I can get the absolute path of a resource like so:
Rails.root.join("public", ActionController::Base.helpers.asset_url('image.jpg').sub("/",""))

# => #<Pathname:/Users/Benjamin/apps/app1/public/image.jpg>

This will work with the asset pipeline (I think) but it doesn't feel like a nice way to do this. Any suggestions on how I could do this better?

A: You can try this.
File.expand_path('image.jpg')


text:
Q: How to move the whole window when mouse is on the window's custom widget in Qt? Let's say I have a custom widget and add it to the main window in qt.

As you can see, the red area is the custom widget. What I want to do is when the mouse is pressed in the red area and moved, the whole window will move as well.
I know how to simply implement mousePressEvent and mouseMoveEvent; but when dealing with a window with the custom widget, I do not know how to move the whole window when mouse is pressed on the custom widget.
Also I want to mention that I only want the window movable when mouse is pressed and moved in the red area, and when mouse is pressed and moved in the rest part of the main window area, nothing will happen.
This is what my CustomWidget class looks like:
CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent)
{
    setFixedSize(50, 50);
    setStyleSheet("QWidget { background: red; }");
}

void CustomWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
}

void CustomWidget::mousePressEvent(QMouseEvent *event)
{
    xCoord = event->x();
    yCoord = event->y();
}

void CustomWidget::mouseMoveEvent(QMouseEvent *event)
{
    move(event->globalX() - xCoord, event->globalY() - yCoord);
}

In case you wonder why I want to do this, in my app, I hid the title bar and drew a custom title bar by myself. But the window is not movable, so I want to make the whole window movable when mouse is pressed and moved on the title bar.
Hope I explained myself clearly.

A: To move the window from any widget it is necessary to be able to access the window, and for this we use the method window() that returns the top level, it is not necessary to separate the coordinates x() and y(), the following code implements the solution:
customwidget.h
#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H

#include <QWidget>

class CustomWidget : public QWidget
{
    Q_OBJECT
public:
    explicit CustomWidget(QWidget *parent = nullptr);
protected:
    void paintEvent(QPaintEvent *);
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
private:
    QPoint startPos;
};

#endif // CUSTOMWIDGET_H

customwidget.cpp
#include "customwidget.h"

#include <QMouseEvent>
#include <QPainter>
#include <QStyleOption>

CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent)
{
    setFixedSize(50, 50);
    setStyleSheet("QWidget { background: red; }");
}

void CustomWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
}

void CustomWidget::mousePressEvent(QMouseEvent *event)
{
    startPos = event->pos();
    QWidget::mousePressEvent(event);
}

void CustomWidget::mouseMoveEvent(QMouseEvent *event)
{
    QPoint delta = event->pos() - startPos;
    QWidget * w = window();
    if(w)
        w->move(w->pos() + delta);
    QWidget::mouseMoveEvent(event);
}

A: If you are working on Windows, can use it:
#include "mywidget.h"
#include <windows.h>
#include <QWindow>

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
}

MyWidget::~MyWidget()
{

}

void MyWidget::mousePressEvent(QMouseEvent* event)
{
    if (event->buttons().testFlag(Qt::LeftButton))
    {
        HWND hWnd = ::GetAncestor((HWND)(window()->windowHandle()->winId()), GA_ROOT);
        POINT pt;
        ::GetCursorPos(&pt);
        ::ReleaseCapture();
        ::SendMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, POINTTOPOINTS(pt));
    }
}

A: void QHexWindow::mousePressEvent(QMouseEvent *event)
{
    QLabel *child = static_cast<QLabel*>(childAt(event->pos()));
    if (child!=mTitleBar)        //mTitlebar is the QLabel on which we want to implement window drag
    {
        return;
    }
    isMousePressed = true;
    mStartPos = event->pos();
}

void QHexWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(isMousePressed)
    {
        QPoint deltaPos = event->pos() - mStartPos;
        this->move(this->pos()+deltaPos);
    }
}

void QHexWindow::mouseReleaseEvent(QMouseEvent *event)
{
    QLabel *child = static_cast<QLabel*>(childAt(event->pos()));
    if (child!=mTitleBar)
    {
        return;
    }
    isMousePressed = false;
}

I have implemented the above in one of my github project https://github.com/VinuRajaKumar/AVR-HEX-Viewer where QLabel is used as TitleBar for the window.


text:
Q: "modifying the autolayout engine from a background thread" (swift 3) I have the following code. It worked fine in Swift 2.3:
 self.newsScrollView.contentSize = CGSize(width: self.newsScrollView.frame.size.width * CGFloat(topics.count), height: self.newsScrollView.frame.size.height)
    for i in 0..<topics.count {
        let frame = CGRect(x: CGFloat(i) * self.newsScrollView.frame.size.width, y: 0, width: self.newsScrollView.frame.size.width, height: self.newsScrollView.frame.size.height)
        let topic = topics[i]
        let newsView = TrendingTopicView(topic: topic, frame: frame)
        newsView.delegate = self
        self.newsScrollView.addSubview(newsView)
    }

Now, I receive a warning in the debugger:
  This application is modifying the autolayout engine from a background thread after
  the engine was accessed from the main thread.
  This can lead to engine corruption and weird crashes.

So, I tried editing it to this:
 DispatchQueue.main.async {
     self.newsScrollView.addSubview(newsView)
 }

But I still receive the warning. I have also tried the DispatchQueue.main.async(execute:) as well. What am I doing wrong? If I'm not mistaken, the DispatchQueue.main.async inSwift 3 is the equivalent of dispatch_async(dispatch_get_main_queue) in Swift 2.x right?
Any help is appreciated. Thanks


text:
Q: How to get first number from file name, find folder matching the number and move file to folder? I've been trying to do the following.
Lets say I have 3 files in a folder named Documents:
123 Car.pdf
456 Dog.pdf
987 Lion.pdf

I want to create a batch file (.bat) that

*

*read the file names in the folder "documents" but only till the space
(read: 123, 456, 987)

*then search the drive for folders matching with the searched file
name (123, 456, 987)

*and if a folder that is named with 123, 456, 987 is found then move
the file 123 Car.pdf to folder 123, file 456 Dog.pdf to folder
456, 987 Lion.pdf to folder 987 and so on.

A: I managed to make it take the first part of the filename and move the file to a folder named the same but i can not make it search for such a folder and then move the file in it. it just creates it by itself and moves it.
@ECHO OFF
SETLOCAL
SET "sourcedir=C:\Desktop\TEST AREA\"
PUSHD %sourcedir%
FOR /f "tokens=1*" %%a IN (
    'dir /b /a-d "* * *.txt"'
) DO (
    MD %%a
    MOVE "%%a %%b" "C:\Desktop\TEST AREA\%%a\"
)
PAUSE
POPD
GOTO :EOF

I need it to search for the folder and move it there, not creat it and move it.


text:
Q: fullcalendar, deleting event on button click i am trying delete events when i click in button "x", but not work, and not getting any error.
I assign the function click in parameter "eventRender".
This is my code with JavaScript:
$('#calendar').fullCalendar({
        locale: 'es',
        weekends: false, //ocultar fines de semana
        defaultView: 'agendaWeek',
        allDaySlot: false,
        header: {
            left: 'month,agendaWeek,agendaDay,listDay',
            center: 'title',
            right: 'prev,next today'
        },
        height: 'auto',
        minTime: "10:00:00",
        maxTime: "20:00:00",
        editable: true,
        //droppable: true, // this allows things to be dropped onto the calendar
        dayClick: function(date, jsEvent, view) {
            console.log('Clicked on: ' + date.format());
            console.log('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
            console.log('Current view: ' + view.name);
            var hoy = moment();
            if(date.format("YYYY-MM-DD HH:mm") >= hoy.format("YYYY-MM-DD HH:mm")){
                asignarCita(date);
            }else{
                swal({
                    title: "Cita no disponible",
                    text: "La fecha u hora seleccionada ya ha pasado."
                });
            }
        },
        eventRender: function(event, element) {
            element.prepend( "

" );
            //element.append( "X" );
            console.log(element.find('closeon'));
            element.find(".closeon").click(function() {
                $('#calendar').fullCalendar('removeEvents',event._id);
            });
        },
        events: [
            {
                title: 'All Day Event',
                start: '2014-10-01'
            },
            {
                title: 'Long Event',
                start: '2014-10-07',
                end: '2014-10-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2014-10-09T16:00:00'
            },
        ],
    });

Where is the problem?

A: Try this:
eventRender: function(event, element, view) {
        if (view.name == 'listDay') {
            element.find(".fc-list-item-time").append("X");
        } else {
            element.find(".fc-content").prepend("X");
        }
        element.find(".closeon").on('click', function() {
            $('#calendar').fullCalendar('removeEvents',event._id);
            console.log('delete');
            });
    },

https://jsfiddle.net/vc9ytv2k/

A: The current version of FullCalendar has different API
eventRender: function(info) {
      $(info.el).append("X");
      $(info.el).find(".removebtn").click(function() {
        info.event.remove();
      });
    }


text:
Q: Agent VS2017 is stuck at connecting. It never gets out of Queue We have tried to run a release a number of time. Agent VS2017 is stuck at connecting. It never gets out of Queue
It gets stuck at:

A: This seems a issue caused by our side. I think you can also see the message which shows Waiting for agent cloud to provision agent in the agent pool page, right?

This message means the image for hosted agent was being allocated, which will take a longer time if the image hasn't been cached yet in that data center. Our team rolled out a new image last week, which likely the reason for this delay.
You can check https://status.dev.azure.com/_history to follow the latest Pipelines status. During the past few days, Azure Devops have had repeated issues in a few areas, which we have mitigated this issue for now, but still continue to dig in to get the root cause.

If this issue still occurred and keeping long time, you can go Ubuntu Hosted Agent Stuck, and comment with your region and organization name. Our engineer will take look this and help you investigate further.


text:
Q: Load data from ES and store as avro in HDFS using pig I have some data on ElasticSearch that I need to send on HDFS. I'm trying to use pig (this is the first time I'm using it), but I have some problem to define a correct schema for my data.
First of all, I tried loading a JSON using the option 'es.output.json=true' with org.elasticsearch.hadoop.pig.EsStorage, and I can load/dump data correctly, and also save them as a JSON to HDFS using STORE A INTO 'hdfs://path/to/store';. Later, defining an external table on HIVE, I can query this data. This is the full example that is working fine (I removed all SSL attributes from the code):
REGISTER /path/to/commons-httpclient-3.1.jar;
REGISTER /path/to/elasticsearch-hadoop-5.3.0.jar;

A = LOAD 'my-index/log' USING org.elasticsearch.hadoop.pig.EsStorage(
'es.nodes=https://addr1:port,https://addr2:port2,https://addr3:port3',
'es.query=?q=*',
'es.output.json=true');

STORE A INTO 'hdfs://path/to/store';

How can I store my data as AVRO to HDFS? I suppose I need to use AvroStorage, but I should also define a schema loading the data, or the JSON is enough? I tried to define a schema with LOAD...USING...AS command and setting es.mapping.date.rich=false instead of es.output.json=true (my data is quite complex, with map of maps and things like that), but it doesn't work. I'm not sure if the problem is on the syntax, or in the approach itself. Would be nice to have an hint on the correct direction to follow.
UPDATE
This is an example of what I tried with es.mapping.date.rich=false. My problem is that if a field is null, all fields will be in a wrong order.
A = LOAD 'my-index/log' USING org.elasticsearch.hadoop.pig.EsStorage(
  'es.nodes=https://addr1:port,https://addr2:port2,https://addr3:port3',
  'es.query=?q=*',
  'es.mapping.date.rich=false')
  AS(
    field1:chararray,
    field2:chararray,
    field3:map[chararray,fieldMap:map[],chararray],
    field4:chararray,
    field5:map[]
  );

B = FOREACH A GENERATE field1, field2;

STORE B INTO 'hdfs://path/to/store' USING AvroStorage('
{
  "type" : "foo1",
  "name" : "foo2",
  "namespace" : "foo3",
  "fields" : [ {
    "name" : "field1",
    "type" : ["null","string"],
    "default" : null
  }, {
    "name" : "field2",
    "type" : ["null","string"],
    "default" : null
  } ]
}
');

A: For future readers, I decided to use spark instead as it is much faster than pig. To save avro files on hdfs, I'm using the databrick library.


text:
Q: randomizer only generating up to 99 c++ So I am trying to generate 10,000 random numbers from 1-100, but it is only generating up to 99 numbers because when I display it I can only see from 1-99, unless it is my code for finding it. What is happening in my code is i am trying to find how many times the number is generated. Basically a frequency/histogram.
EDIT:I am generating 100, but its not displaying, i get a error
Here is my code:
vector<int> vint;

for (int i = 0; i < 10000; i++)
{
    int x = (rand() % 100) + 1;
    vint.push_back(x);
}

frequency(vint);

void frequency (vector<int> v1)
{
int counter = 1;
int max = 0;
int mode = v1[0];
int numbercheck = 0;
for (int pass = 0; pass < 10000-1 ; pass++)
{
    if (v1[pass] == v1[pass + 1])
    {
        counter++;
        numbercheck++;

    }
    else
    {
        cout << v1[pass] << ": " << counter << "..................." << endl;
        counter = 1;

    }
}

A: If you are using a c++11 compatible compiler then avoid using rand() and use the Mersenne-Twister engine instead for higher quality random sequences. Here is a code snippet example:
#include <random>

int main(void) {
     std::random_device rd; // for random seed
     std::seed_seq seed{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
     std::mt19937 eng(seed);

     const int min = 1;
     const int max = 100;

     // used to generate ints in interval [min,max] (inclusive)
     std::uniform_int_distribution<int> dist(min,max);

     int randomInt = dist(engine); // generate random int using dist and mtengine

     return 0;

}

See this (entertaining) video for some reasons on why rand() is bad:
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

A: You should accept ArchBishop's answer. Here is a simpler program for you.
#include <iostream>
#include <vector>
#include <cstdlib>

using namespace std;

int main()
{
    vector<int> vint;

    for(int i=0; i<10000; ++i)
    {
        vint.push_back(rand()%100 + 1);
    }

    for(const auto&e: vint)
        cout << e << endl;

    return 0;
}

It generated 100 for me but might not generate for you.


text:
Q: How to assign addEventListener as ON in JavaScript? How to assign addEventListener as on
in pure JavaScript? Not jQuery.

// i can do this
// assigning document as d
// assigning querySelector as $

const d = document
const $ = x => d.querySelector(x)

//but how to do this

$('button').addEventListener('click',doSomething)

//to

$('button').on('click',doSomething)

//assiging addEventListener as on

A: You could create your own on() function -
function on(object, event, callback) {
    object.addEventListener(event, callback);
}

Or you could look into prototyping for object functions - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

A: Not sure what you mean by saying simple, but here is the alternative way:
document.getElementById("id").onclick = doSomething;


text:
Q: how to change bluetooth popup message language? I want to show the bluetooth pairing korean message in my iPhone app.
I set General >> International >> Language >> korean in iPhone Settings.
But my app uses Bluetooth function. When pairing, pairing popup message is in English language.
How to change its popup message language?
Need to localize viewcontroller?

A: Yes you need to localize the strings in your app. Here is a great tutorial: http://www.raywenderlich.com/2876/localization-tutorial-for-ios


text:
Q: Genetic algorithm not producing better results I'm running a genetic algorithm to train a set of Hunters to learn to capture as many Elephants as possible. Basically, there's ~20 Hunters that move around in a 2D Grid environment, and 4 Hunters must surround an Elephant to capture it (there's ~20 Elephants in the world). Each time this simulation runs, all Hunters and Elephants are placed in random starting locations. Hunters' movement controlled by its chromosome, Elephants' movements are random.
All of the Hunters have the same chromosome (homogeneous), so I run this simulation each time when assigning a fitness to a chromosome.
My fitness function simply rewards the chromosome for the total number of Elephants captured in the simulation:
double fitness = totalElephantsCaptured() * 100;

The results of the generations' fitnesses are basically random. The most fit individual in each generation does not become more fit as generations progress, and the total fitness of each generation does not increase. I sense that my fitness function is too primitive, but I'm not sure how to change it to yield better results. It does not seem like the Hunters are learning anything.
Details on my GA (Numbers in a range because I've tried various values):

*

*Population size: 64 or 128.

*Generation cap: 500 - 1000.

*Elitism: 5% - 10% of population

*Mutation:  1% - 4%

*Chromosome size: 180

*Selection: Roulette wheel.

*Crossover: Simple crossover in middle of chromosome.
The chromosome is designed in 'blocks' of movement rules based on sensor data:
Each block has a sensor criteria (e.g. "if nearest Elephant is X distance away") and a movement rule (e.g. "move towards nearest Elephant for Y amount of time"). Hunters can either move towards nearest Elephant or towards nearest teammate Hunter.
Does anyone have any suggestions to make the fitness of the Hunters gradually increase as generations increase?


text:
Q: Cannot play video on iOS Device and Device Browser I am developing an iOS application with the function stream video from server. I think the problem come from my video url It cannot load video to simulator or iOS device, but the url working fine when I access on browser PC.
Could anyone help me on this issue? Here is my code:
NSURL *videoURL = [NSURL    URLWithString:@"http://192.168.1.210:12345/WallPost/Download?filename=TheEmpressOfChinaOriginalSoundtrack1422348924923.mp4"];

     _moviePlayer = [[MPMoviePlayerViewController alloc] init];

     _moviePlayer.moviePlayer.contentURL = videoURL;

     _moviePlayer.view.frame = CGRectMake(10.0, 10.0, 300.0, 200.0);

     _moviePlayer.moviePlayer.movieSourceType = MPMovieSourceTypeFile;

     [_moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleDefault];

     [self.view addSubview:_moviePlayer.view];

     [_moviePlayer.moviePlayer setAllowsAirPlay:YES];

     _moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

     [_moviePlayer.moviePlayer prepareToPlay];


text: Q: Can I fetch data on every reload for a static React website served from Github pages? I have a react static website served from Github Pages that fetches some data from a database but when I update the data it takes about 5min to 10min to be updated on the front-end. Does this has to do with how Github cache works?


text:
Q: Localization of app doesn't change language of cocoapods used within app I am doing localization in my app. When I change the language it updates everywhere in my app except in pods that I have used. If I restart the app, pod's language is updated. Is there any way I can change the language of pods when I change the app's language.

A: You would need to swap the mainBundle of your application as soon as the user changes their language preferences inside the app.
The idea is to have a custom Bundle and extension:
var bundleKey: UInt8 = 0

class AnyLanguageBundle: Bundle {

override func localizedString(forKey key: String,
                              value: String?,
                              table tableName: String?) -> String {

    guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,
        let bundle = Bundle(path: path) else {
        return super.localizedString(forKey: key, value: value, table: tableName)
    }

    return bundle.localizedString(forKey: key, value: value, table: tableName)
  }
}

extension Bundle {

class func setLanguage(_ language: String) {

    defer {
        object_setClass(Bundle.main, AnyLanguageBundle.self)
    }

    objc_setAssociatedObject(Bundle.main, &bundleKey, Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }
}

And when you would like to update your app language:
func updateAppLanguageToIT() {
    UserDefaults.standard.set("it", forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    // Update the language by swaping bundle
    Bundle.setLanguage("it")

    // Done to reintantiate the storyboards instantly
    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController()
}

A few references on how to achieve this are available already in some posts/github pages like those two:

*

*https://github.com/maximbilan/Language-Manager-iOS

*http://www.codebales.com/how-programmatically-change-app-language-without-restarting-app


text:
Q: Portugal representative or Portugal's represntative There is a company in USA (let's call this company "ABU")and a person from Portugal became a manager of the representative of ABU in Portugal.
How is the right way to describe this representative?
Can I say "Portugal representative" in this case?
Is it better to say "ABU representative in Portugal"

A: You wouldn't normally say Portugal representative because you would not use Portugal as a modifier, but instead use Portuguese:

Portuguese representative

Then in your case you could say:

the Portuguese representative of ABU

or

the ABU representative in Portugal
ABU's representative in Portugal


text:
Q: DKIM and Reverse Dns with sub-domain of onmicrosoft.com When you sign up with Outlook 365 you get allocated a sub-domain like contoso.onmicrosoft.com. If you send an email from user@contoso.onmicrosoft.com should it not automatically be signed with DKIM or do you need to do anything extra?
Emails are not being signed with DKIM and also the reverse DNS check is failing, whereas I would have expected both of these to work as standard.

A: DKIM should be enabled by default with your .onmicrosoft domain. There is nothing to do as far as the .onmicrosoft domain is concerned.  I would put in a support request if you are not seeing your outgoing messages signed.
As for reverse DNS, that seems to work fine.  I tried multiple IP's resolved from lookup and each one resolves back to the Microsoft servers. I'm not sure where you are testing from, but you may want to validate from a few a few different places and make sure it's not a local device causing your issue. If you have some sort of edge device modifying message headers before it reaches you, that could be the issue in both cases.


text:
Q: Counting and matching process I have a matching problem with awk :(
I will count first column elements in main.file and if its value is more than 2 I will print the first and the second column.
main.file
1725009 7211378
3353866 11601802
3353866 8719104
724973 3353866
3353866 7211378

For example number of "3353866" in the first column is 3, so output.file will be like that:
output.file
3353866 11601802
3353866 8719104
3353866 7211378

How can I do this in awk?

A: If you mean items with at least 3 occurrences, you can collect occurrences in one array and the collected values as a preformatted or delimited string in another.
awk '{o[$1]++;v[$1]=v[$1] "\n" $0}
    END{for(k in o){if(o[k]<3)continue;
        print(substr(v[k],1)}' main.file

Untested, not at my computer. The output order will be essentially random; you'll need another variable to keep track of line numbers if you require the order to be stable.
This would be somewhat less hackish in Perl or Python, where a hash/dict can contain a structured value, such as a list.

A: Another approach is to run through the file twice: it's a little bit slower, but the code is very neat:
awk '
  NR==FNR {count[$1]++; next}
  count[$1] > 2 {print}
' main.file main.file

A: awk '{store[$1"-"lines[$1]] = $0; lines[$1]++;}
  END {for (l in store) {
    split(l, pair, "-"); if (lines[pair[1]] > 2) { print store[l] } } }'

A: One approach is to track all the records seen, the corresponding key $1 for each record, and how often each key occurs. Once you've record those for all the lines, you can then iterate through all the records stored, only printing those for which the count of the key is greater than two.
awk '{
    record[NR] = $0;
    key[$0] = $1;
    count[$1]++
}

END {
    for (n=1; n <= length(record); n++) {
        if (count[key[record[n]]] > 2) {
            print record[n]
        }
    }
}'

A: Sort first, and then use awk to print only when you have 3 times or more the 1st field:
cat your_file | sort -n | awk 'prev == $1 {count++; p0=p1; p1=p2; p2=$2}
prev != $1 {prev=$1; count=1; p2=$2}
count == 3 {print $1 " " p0; print $1 " " p1; print $1 " " p2}
count > 3 {print $1 " " $2}'

This will avoid awk to use too much memory in case of big input file.

A: based on how the question looks and the Ray Toal edit, I'm guessing you mean based on count, so something like this works:
awk '!y[$1] {y[$1] = 1} x[$1] {if(y[$1]==1) {y[$1]==2; print $1, x[$1]}; print} {x[$1] = $2}'


text:
Q: Best way for verifying server compliance to Apple's ATS / TLS 1.2 requirement So Apple requires TLS 1.2 with Forward Secrecy for URLs beginning iOS 9.  Independent of the app, what's the best way to verify that a server meets all the requirements?
nscurl just outright doesn't work - or I don't know how to use it.  My output simply repeatedly says CFNetwork SSLHandshake failed, even though I know the server is compliant.
TLSTool works to some extent but I cannot force the Forward Secrecy (FS) ciphers to be used.
openssl can specify specific cipher for the client mode, but the version I have doesn't have FS ciphers. How do I upgrade openssl?
What's the best way?  So far I've had to ssllabs.com's analyze.html.  Any suggestions?

A: Basically nscurl --ats-diagnostics <url> just tries all possible variants of connection to server and responses with PASS/FAIL results for each test. You should just find which tests pass for your server and set ATS configuration accordingly.
Here's a good article on ATS and checking server compliance, it also contains an nscurl example.

A: Using nscurl (available in macOS El Capitan and higher), you can use the --ats-tls-version switch to test specifically for TLS 1.2 compliance, e.g.:
nscurl --ats-diagnostics --ats-tls-version TLSv1.2 <url>
This will also test for Perfect Forward Secrecy. If you want to disable testing for PFS, use the --ats-disable-pfs switch.
nscurl --ats-diagnostics --ats-tls-version TLSv1.2 --ats-disable-pfs <url>

A: Method 1:
If the URL you want to test is publicly accessible, you can use a public SSL testing service such as the one below:
SSL Server Test
After entering the URL, the section titled "Handshake Simulation" lists "Apple ATS 9 / iOS 9" and will indicate if TLS 1.2 was successfully negotiated and which connection cipher suite was used. If the cipher suite used is listed below under the Technical ATS Requirements and TLS 1.2 was successfully negotiated, then the server is properly configured for ATS.
Method 2: (this was mentioned by others as well)
On a Mac running OS X El Capitan, run the following command in Terminal:
/usr/bin/nscurl --ats-diagnostics https://<url>

After running the command, look for the section near the top labeled, ATS Default Connection. A result of PASS indicates the server is properly configured for ATS.
Method 3:
For URLs which are not publicly accessible, use Wireshark to monitor the communication to the URL. You can use a Wireshark filter to display only TLSv1.2 packets with the following:
ssl.record.version == 0x0303

You will see packets that use the TLSv1.2 protocol if the server has been configured for TLS version 1.2. If you only see a Client Hello packet when monitoring requests coming into the URL, then TLSv1.2 was not negotiated between the mobile device and the URL.

A: All the methods listed here work, but require some manual labor. The best method I found was testing the server with SSL Labs and comparing the results to Apple's requirements. This seemed like something that could be automated so I created a tool that does just that: https://apptransport.info
If you pass your domain in as a parameter (e.g. https://apptransport.info/craigslist.com) you'll get the following information:

*

*Whether or not your server is ATS compliant

*How to fix your server if necessary

*How to add ATS exceptions if necessary

*The results From SSL Labs


text:
Q: Reading text from Mac OS terminal window through Java code? This is the code I am using:
String cmd="tell application \"Terminal\" to do script \"cd  "+ path +" && "+ command +" \" ";
System.out.println(cmd);
ProcessBuilder builder = new ProcessBuilder("osascript","-e",cmd);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));

It's giving null. How can I read from the terminal window?

A: You can accomplish this with Apache Commons Exec.
import java.io.ByteArrayOutputStream;
import org.apache.commons.exec.*;

class CMDTest {
    public static void main(String[] args) {
       try{
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
         CommandLine command = new CommandLine("/bin/sh");
         command.addArguments(new String[] {
           "-c",
           "ls '-al'"
         },false);
         DefaultExecutor exec = new DefaultExecutor();
         PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
         exec.setStreamHandler(streamHandler);
         exec.execute(command);
         System.out.println(outputStream.toString());
       }
       catch(Exception e){
         System.out.println("error");
       }
    }
}


text:
Q: CSS transforms VS transitions What are the key differences between CSS transformations and transitions?
Both of those are used to change the current shape/state of an object. (you can do pretty animations with JS etc..)
But it's still not clear to me which one to use where and for what.

A: transition and transform are separate CSS properties, but you can supply transform to transition to "animate" a transformation.

transition
The CSS transition property listens for changes to specified properties
(background-color, width, height, etc.) over time.
transition Property Syntax:
selector {
    transtion: [property-name] [duration] [timing-function] [delay]
}

For example, the below styles will change the color of a div's background to orange over a period of 1 second upon hover.

div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  transition: background-color 1s;
  /* timing function and delay not specified */
}
div:hover {
  background-color: orange;
}

transform
The CSS transform property rotates/scales/skews an element over the X,Y, or Z axes. Its behavior does not relate to transition. Simply put, on page load, the element will just appear rotated/skewed/scaled.
Now if you wanted the rotating/skewing/scaling to happen, say when a user hovered over the element, you would need to "transition" the "transformation".
Here's how: since the transition property's functionality is to listen to changes in other css properties, you can actually supply transform as an argument to transition and "animate" the transformation based on desired trigger (for example, a hover action).
transform Property Syntax
select {
    transform: [rotate] [skew] [scale] [translate] [perspective]
}

For example, the below styles will rotate a div over a period of 1 second upon hover.

div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  transition: transform 1s;
  /* timing function and delay not specified */
}
div:hover {
  transform: rotate(30deg);
}

A: They're completely different things.
Transitions:

CSS Transitions allows property changes in CSS values to occur smoothly over a specified duration.

Transforms:

CSS transforms allows elements styled with CSS to be transformed in two-dimensional or three-dimensional space.


text:
Q: React Leaflet : ugly Warning: Each child in a list should have a unique "key" prop I've set an leaflet map component that iterate through users fetched from db that contains, for each of them, coordinates.
Devtool throw me:

Warning: Each child in a list should have a unique "key" prop.

Not the first time I got this warning and I usually find easily how to fix it but this time I can't find a solution.
All is working fine but this warning keeps triggering me
Console Warning:

I've tried to put the key as Marker component identifier, Popup component identifier, both of them.
I've seen a post that recommend to put the key as Fragment identifier for each element of my map function. I tried in a div component (seems equal to Fragment to me?) still not working.
<MapContainer  id={!isMobile ? "browser-leaflet" : "mobile-leaflet"} center={POSITION} zoom={15} scrollWheelZoom={true}>
    <TileLayer
    attribution='© OpenStreetMap contributors'
    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?lang=fr"
    />
    {contacts.map(contact => (

 <-- last try here
            <Marker //also tried here// position={[contact.lat, contact.lon]} icon={new Icon({iconUrl: contact.is_client ? markerIconClient : markerIconProspect, iconSize: [25, 41], iconAnchor: [12, 41]})}>
                <Popup //also tried here// offset={[0, -15]}>

                        {contact.raison_sociale}

                    <Button variant="sub" className="mx-auto" style={{border: "teal", borderRadius: "15px", fontSize: "1em", display: "flex", justifyContent: "center"}}>

                            Allez-y

                    </Button>
                </Popup>
            </Marker>

    ))}
    <SetMap />
</MapContainer>

Error seems to be located @Geolocalisation.jsx (my whole page compo) line:102 which is where I set style and navbar based on client device.
return ( <--- here l:102
        <>
            {!isMobile ? (
                [
                    <BrowserSidenav />,

                ]
            ) : (

            )}

Does someone knows how to fix it?
(P.S: sorry for bad English, not native and not using online translator)
Whole return from my component Geolocalisation.jsx : (funcs are just a users fetch, a useEffect that delete users with no lat/lon.
return (
        <>
            {!isMobile ? (
                [
                    <BrowserSidenav />,

                ]
            ) : (

            )}

            <MapContainer  id={!isMobile ? "browser-leaflet" : "mobile-leaflet"} center={POSITION} zoom={15} scrollWheelZoom={true}>
                <TileLayer
                attribution='© OpenStreetMap contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?lang=fr"
                />
                {contacts.map(contact => (

                        <Marker position={[contact.lat, contact.lon]} icon={new Icon({iconUrl: contact.is_client ? markerIconClient : markerIconProspect, iconSize: [25, 41], iconAnchor: [12, 41]})}>
                            <Popup offset={[0, -15]}>

                                    {contact.raison_sociale}

                                <Button variant="sub" className="mx-auto" style={{border: "teal", borderRadius: "15px", fontSize: "1em", display: "flex", justifyContent: "center"}}>

                                        Allez-y

                                </Button>
                            </Popup>
                        </Marker>

                ))}
                <SetMap />
            </MapContainer>
        </>
    )

A: Check if there are same emails in data 'contacts'. Make sure each key for div is unique.

A: Remember that undefined is also a key-value.
If you have unique emails in your DB, but not required, then there might be several people without email.
I normally go for the _id/id or concider using several fields to build a key.
You could also do key={contact.email ?? contact.phone} Or another attribute if email is undefined...


text:
Q: Convert a jason file to a matrix form I apologize in advance if my question is too standard. I tried my best to google the answer but could not find a satisfying one.
I have a distance matrix file in Jason with the following format
{"A": {"A":0, "B": 1, "C": 2}, "B":{"A": 1, "B": 0, "C": 1}, "C":{"A": 2, "B":1, "C":0}}
This tells the distance between any two pairs. For example, the distance from A to B is 1. How can I convert this one into a matrix form in Python?
Thank you!

A: Before coding, we can overview your data and define your problem:
You have vertices:
vertices = ["A", "B", "C"]
So the expected matrix is a 3 x 3 2d-array (3 = number of your vertices)
It looks like:
matrix = [
[0, 1, 2],  // edges's values staring from vertex A (edges: AA, AB, AC)
[1, 0, 1], // edges's values starting from vertex B (BA, BB, BC)
[2, 1, 0], // edges's values starting from vertex C (CA, CB, CC)
]

Your mission is now to build the matrix above by code, not by eyes :D.
So the solution is:

*

*Define your vertices

*Build (number_of_vertices x number_of_vertices) matrix

data = {'A': {'A': 0, 'B': 1, 'C': 2}, 'B': {'A': 1, 'B': 0, 'C': 1}, 'C': {'A': 2, 'B': 1, 'C': 0}} # Just a quick example, you can search how to read from file later

vertices = data.keys() # Your vertices is the dictionary's keys, use Python built-in method.
number_of_vertices = len(vertices)  # Count your vertices

matrix = []

for vertex1 in vertices:
  row = []  # Initialize a row represent values for edges starting from vertex1 to other vertices
  for vertex2 in vertices:
    row.append(data[vertex1][vertex2])  # Edge "vertex1" -> "vertex2"
  matrix.append(row)  # Add to our matrix

print(matrix)
# [[0, 1, 2], [1, 0, 1], [2, 1, 0]]

I used two for ... in loops for clearer demonstration. When you get used to, you can shorten by searching & using List Comprehension in Python.


text:
Q: display email body of selected email in outlook as a message box in excel? I am using excel 2010 and have created the following vba code which finds emails which contain the word test in their subject heading and then in excel it shows a message box with the body of that email:
Sub GetFromInbox()

    Dim olApp As Outlook.Application
    Dim olNs As Outlook.Namespace
    Dim olFldr As Outlook.MAPIFolder
    Dim olItms As Outlook.Items
    Dim olMail As Variant
    Dim i As Long

    Set olApp = New Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")
    Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
    Set olItms = olFldr.Items
    Set objItem = olApp.ActiveExplorer.Selection.Item(1)

    olItms.Sort "Subject"

    i = 1

    For Each olMail In olItms
     If InStr(olMail.Subject, "Test") > 0 Then
            MsgBox olMail.Body
            i = i + 1
        End If
    Next olMail

    Set olFldr = Nothing
    Set olNs = Nothing
    Set olApp = Nothing

End Sub

My ultimate aim here is to add more if conditions to the code, so that only the currently selected email or opened email in outlook has its email body displayed in my excel message box
An example of this is say we have several emails with the subject "test" as it currently stands the code will show the body of all these emails which have the subject "test" one after another in a different message box.
But there should only ever be one message box displayed for the currently selected/opened email in outlook if that emails subject is "test".
Please can someone show me how I can do this?

A: You can use the Application.ActiveInsepctor property to get the opened email or use the Application.ActiveExplorer property to get a selected, but unopened, email
Sub GetFromInbox()

    Dim olApp As Outlook.Application
    Dim olMail As Outlook.MailItem

    Set olApp = New Outlook.Application

    'If it's not an MailItem or there's no
    'ActiveInspector, error is ignored
    On Error Resume Next
        Set olMail = olApp.ActiveInspector.CurrentItem
    On Error GoTo 0

    'If nothing is open, see if a MailItem is selected
    If olMail Is Nothing Then
        On Error Resume Next
            Set olMail = olApp.ActiveExplorer.Selection.Item(1)
        On Error GoTo 0
    End If

    If Not olMail Is Nothing Then
        If InStr(olMail.Subject, "Test") > 0 Then
            MsgBox olMail.Body
        Else
            MsgBox "Selected/active email does not have correct subject"
        End If
    Else
        MsgBox "Active item is not an email or no email selected"
    End If

End Sub

First, it looks for the active, opened item. If that's not an email, then it looks at the first selected item in whatever "Explorer" is active. If that's not an email, then it gives you a message.
If the open, active item is an email, it uses that and tests the subject. In that case it doesn't look at any selected items. Only if there's nothing open or the open item is not a Mailitem (like it's a CalendarItem), does it look at what's selected.
If you're in, say, the calendar, then that's the active explorer and it's likely that any selection is not a MailItem. It also doesn't care if you're in the Inbox of another folder. It only cares if the first item selected is a MailItem. You could check olapp.ActiveExplorer.CurrentFolder to make sure you're in the Inbox if that's important to you.
You can have Items in your mail folders that are not MailItems. If it's not a MailItem that's selected, then you'll get a message.
Finally, you can select any number of items in your Inbox. This only looks at the first items selected. If you want to process all the items, you can look through them using .Selection.Count and .Selection.Item(i) to process each one in turn.