text:
Q: Azure IoT hub connection string not working anymore - Does azure update the connection string? For some reason today after 2 months my IoT hub connection string did not work anymore which gave me a :

Exception when sending message:{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":""}

I later found out that my connectionString changed in the IoT for which I use a free license. Even though I updated my connectionString to the new one I still get the same error which makes me wonder:

*

*Does Azure IoT hub require you to change your connectionString every now and then? If yes does anyone know a best practice to do this automatically?

*Does IoT Hub require you to have the most recent SDK's from Microsoft.azure.devices. and Microsoft.Azure.devices.client ?
As far as I know it just randomly stopped working over the weekend without any explanation and I have no clue why because there where 0 changes in the code or in Azure from me.

A: Event Hub relies on keys for access. Is there is a chance someone regenerated the key from the Shared Access Policy or via PowerShell?
You also mentioned you are using a free account - if you are sure you have the correct key, is there a chance your free trial has expired or exceeded the quota of 8,000 messages per day - see the pricing calculator.
As far as you questions are concerned:

*

*Key cycling is not enforced by default.

*I do not believe that the latest SDK must always be used.

Note that Event Hub is still in preview, so breaking changes are possible. I see you did mention IOT Hub, which works the same way for access control, but is a production service. It should be solid.


text:
Q: Displaying data from Firebase in React without arrays I am new to both React and Firebase. I struggled a bit to get data from the database, even though the instructions on the Firebase website were pretty straightforward.
I managed to print data in the view by using this code:
Get data from DB and save it in state:
INSTRUMENTS_DB.once('value').then(function(snapshot) {
        this.state.instruments.push(snapshot.val());
        this.setState({
            instruments: this.state.instruments
        });

From Firebase, I receive and Object containing several objects, which correspond to the differen instruments, like shown in the following snippet:
Object {
    Object {
        name: "Electric guitar",
        image: "img/guitar.svg"
    }
    Object {
        name: "Bass guitar",
        image: "img/bass.svg"
    }
    // and so on..
}

Currently, I print data by populating an array like this:
var rows = [];
    for (var obj in this.state.instruments[0]) {
        rows.push(<Instrument name={this.state.instruments[0][obj].name}
                              image={this.state.instruments[0][obj].image}/>);
    }

I feel like there's a better way to do it, can somedody give a hint? Thanks

A: I user firebase a lot and mu solution is little ES6 helper function

const toArray = function (firebaseObj) {
return Object.keys(firebaseObj).map((key)=> {
    return Object.assign(firebaseObj[key], {key});
})

};

I also assign the firebase key to object key property, so later I can work with the keys.

A: The native map function only works for arrays, so using directly it on this object won't work.
What you can do instead is:
Call the map function on the keys of your object using Object.keys():
getInstrumentRows() {
  const instruments = this.state.instruments;
  Object.keys(instruments).map((key, index) => {
    let instrument = instruments[key];
    // You can now use instrument.name and instrument.image
    return  <Instrument name={instrument.name} image={instrument.image}/>
  });
}

Alternatively, you can also import the lodash library and use its map method which would allow you to refactor the above code into:
getInstrumentRowsUsingLodash() {
  const instruments = this.state.instruments;
    _.map(instruments, (key, index) => {
    let instrument = instruments[key];
    // You can now use instrument.name and instrument.image
    return  <Instrument name={instrument.name} image={instrument.image}/>
  });
}

Side note:
When you retrieve you data from Firebase you attempt to update the state directly with a call on this.state.instruments.  The state in React should be treated as Immutable and should not be mutated with direct calls to it like push.

A: I would use map function:
_getInstrumentRows() {
    const instruments = this.state.instruments[0];
    if (instruments) {
        return instruments.map((instrument) =>
            <Instrument name={instrument.name}
                        image={instrument.image}/>);
    }
}

In your render() method you just use {_getInstrumentRows()}  wherever you need it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combine two wild card hashmaps into a wild card hashmap I want to combine two hash maps with wild cards into a single hash map which still contains dynamic values.
I have SharedPreferences in two different places in my Android application - I need to combine the entire set into a single hash map to pass to a function.
I have tried putAll() and merge functions, but the wild cards keep causing issues.
Currently I have two functions which return the values, but I really need to combine them into a single function.
private HashMap<String, ?> getAppPrefs() {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
   return (HashMap<String, ?>) prefs.getAll();
}

private HashMap<String, ?> getScorePrefs() {
   SharedPreferences scoreprefs= this.getSharedPreferences("scoreprefs", 0);
   return (HashMap<String, ?>) scoreprefs.getAll();
}

My expected result is something like:
private HashMap<String, ?> getAllPrefs() {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
   HashMap<String, ?> map1 = (HashMap<String, ?>) prefs.getAll();
   SharedPreferences scoreprefs= this.getSharedPreferences("scoreprefs", 0);
   HashMap<String, ?> map2 = (HashMap<String, ?>) prefs.getAll();
   HashMap<String, ?> map3 = map1.merge(map2);  // <-- Or something else
   return map3;
}

If I use merge, I get:
error: no suitable method found for merge(HashMap<String,CAP#1>)
  HashMap<String, ?> map3 = map1.merge(map2);
                                ^
method Map.merge(String,CAP#2,BiFunction<? super CAP#2,? super CAP#2,? extends CAP#2>) is not applicable
  (actual and formal argument lists differ in length)
method HashMap.merge(String,CAP#2,BiFunction<? super CAP#2,? super CAP#2,? extends CAP#2>) is not applicable
  (actual and formal argument lists differ in length)
  where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends Object from capture of ?

A: With the unknown wildcard (<?>), the only assumption that can safely be made is that instances are a subtype of Object.
We cannot take objects of an unknown type and put them in another collection of another unknown type because the two types might be incompatible.
However, we can put them in a collection of <Object> as this is always safe, and then declare that this collection is of a third unknown type.
For instance, with the type of your example:
public static HashMap<String, ?> merge(HashMap<String ,?> map1, HashMap<String, ?> map2) {
    HashMap<String, Object> merged = new HashMap<>();
    merged.putAll(map1);
    merged.putAll(map2);
    return merged;
}


text:
Q: VBA cell formatting of .summary I have a piece of code that needs to have a different format. The main area of interest at the moment is the wording/format of the subject line in the email. Here is what I have so far.
    ActiveWorkbook.EnvelopeVisible = True
    With .Parent.MailEnvelope
        .Introduction = ""

       With .Item
            .to = "Somebodysemail@whatever.com;"
            .to = "Somebodysemail@whatever.com;"
            .CC = ";"
            .BCC = ""
            .Subject = Date & " Completion " & summary.[B8] & "% """
            .send
            .display
        End With

My main subject line as of now when running the Macro is:
7/26/2018 completion 0.992%
and I want it to read:
7/26/2018 completion 99.2%
When calling upon the contents of cell B8, it is already in the format of 99.2 in my excel workbook. I do not understand why it is not copying the exact contents of the cell. Any help would be greatly appreciated! :)

A: This isn't really a programming question so may have been better suited to a related site like SuperUser, but it's such a quick answer I might as well...

Replace this line in your code:
.Subject = Date & " Completion " & summary.[B8] & "% """

...with:
.Subject = Date & " Completion " & Format(summary.[B8],"0.0%")

To answer your question, you are correct in saying:

"cell B8, it is already in the format of 99.2"

"Format" being the key word.  Numbers in Excel are stored as just numbers, and without formatting.  When you change the formatting of a cell, that's only changing the way that the number is displayed, not the actual number itself.  This is a good thing for several reasons.
I highly recommend taking the time do check out a tutorial such as this one. A little bit of time invested now will save a lot of time later.
Good luck!


text:
Q: Trying to check a string that satisfies these conditions Trying to use following code to check a string:
def check_password(x):
  if has_unique_letters(x) == False:
    print "Warning! Please ensure letters are not repeated."
  if has_even_vowels(x) == False:
    print "Warning! Please ensure password contains an even number of vowels."
  if has_special_character(x) == False:
    print "Warning! Please ensure password contains at least one of {@, #, *, $}"
  if has_divisible_numbers(x) == False:
    print "Warning! Please ensure all numbers are divisible by 2 or 3."
  print "Sorry, your password does not meet our criteria."
print "Congratulations, your password meets our criteria."

x = raw_input("Please set your password:")
check_password(x)

However I am confused about how to make:
print "Sorry, your password does not meet our criteria."

and:
print "Congratulations, your password meets our criteria."

these two sentences show correctly.
I intend to show every "Warning!..." along with "Sorry,..." when one of these conditions is not meet, while show "Congratulation,..." when all of conditions are meet.
But with what I have, "Sorry,..." line will always shows and "Congratulations,..." line is not showing.
I know I must done wrong but how can I fix this?
Thanks!

A: Create a list that contains all errors in the password.  If there are errors, state that the password does not meet the criteria and then print all of the password error types.  Otherwise, print that it meets the criteria.
def check_password(password):
    errors = []
    if not has_unique_letters(password):
        errors.append("Warning! Please ensure letters are not repeated.")
    if not has_even_vowels(password):
        errors.append("Warning! Please ensure password contains an even number of vowels.")
    if not has_special_character(password):
        errors.append("Warning! Please ensure password contains at least one of {@, #, *, $}")
    if not has_divisible_numbers(password):
        errors.append("Warning! Please ensure all numbers are divisible by 2 or 3.")
    if errors:
        print "Sorry, your password does not meet our criteria."
        for e in errors:
            print(e)
    else:
        print "Congratulations, your password meets our criteria."

password = raw_input("Please set your password:")
check_password(password)

A: EDIT: I like the last code example the most, and I think it is probably the best practice for something like this.
A simple way to solve the problem would be to do something like this:
def check_password(x):
    bad_password = False
    if has_unique_letters(x) == False:
        print "Warning! Please ensure letters are not repeated."
        bad_password = True
    if has_even_vowels(x) == False:
        print "Warning! Please ensure password contains an even number of vowels."
        bad_password = True
    if has_special_character(x) == False:
        print "Warning! Please ensure password contains at least one of {@, #, *, $}"
        bad_password = True
    if has_divisible_numbers(x) == False:
        print "Warning! Please ensure all numbers are divisible by 2 or 3."
        bad_password = True

    if bad_password == True:
        print "Sorry, your password does not meet our criteria."
    else:
        print "Congratulations, your password meets our criteria."

x = raw_input("Please set your password:")
check_password(x)

Simply adding a bool to set if the password is bad saves you from needing to do any weird nested logic and doesn't overly complicate the code.
However, there are some more elegant ways to solve that problem. Let me know if you would like to see some of them. But as far as functionality the above code should work for your needs.
Here is a slightly more functional way to handle the errors based on Alexander's answer.
def check_password(password):
    # by adding an array of error messages it enables you to pass all of the errors to other functions that can handle
    #   everything an independent way.
    errors = []
    if not has_unique_letters(password):
        errors.append("Warning! Please ensure letters are not repeated.")
    if not has_even_vowels(password):
        errors.append("Warning! Please ensure password contains an even number of vowels.")
    if not has_special_character(password):
        errors.append("Warning! Please ensure password contains at least one of {@, #, *, $}")
    if not has_divisible_numbers(password):
        errors.append("Warning! Please ensure all numbers are divisible by 2 or 3.")
    return errors

def handle_password_errors(errors):
    # A function that can handle all of the password errors. This can print the errors or set flags in a GUI or any
    # number of other things with out having to change any of the other functions.
    if errors:
        print "Sorry, your password does not meet our criteria."
        for e in errors:
            print(e)
    else:
        print "Congratulations, your password meets our criteria."

password = raw_input("Please set your password:")
check_password(password)

This is my prefered method. Now the question is how do you pass the PASSWORD_ERRORS list to the functions that need it? If these methods are all in a class I like making the const a part of the init or just declared at the top of the class (inside of the class).
# Using a dictionary like this to store all of the possible password errors makes it easier if you want to change a
#   specific error message in the future. It also enables you to add more associations to your errors. For example you
#   can add a error flag to pass to a UI or function call.
PASSWORD_ERRORS = {
    'unique_letter_error': {
        'text': "Warning! Please ensure letters are not repeated.",
    },
    'even_vowels_error': {
        'text': "Warning! Please ensure password contains an even number of vowels.",
    },
    'special_character_error': {
        'text': "Warning! Please ensure password contains at least one of {@, #, *, $}",
    },
    'divisible_numbers_error': {
        'text': "Warning! Please ensure all numbers are divisible by 2 or 3."
    }
}

def check_password(password):
    # by adding an array of error messages it enables you to pass all of the errors to other functions that can handle
    #   everything an independent way.
    errors = []
    if not has_unique_letters(password):
        errors.append(PASSWORD_ERRORS['unique_letter_error'])
    if not has_even_vowels(password):
        errors.append(PASSWORD_ERRORS['even_vowels_error'])
    if not has_special_character(password):
        errors.append(PASSWORD_ERRORS['special_character_error'])
    if not has_divisible_numbers(password):
        errors.append(PASSWORD_ERRORS['divisible_numbers_error'])
    return errors

def handle_password_errors(errors):
    # A function that can handle all of the password errors. This can print the errors or set flags in a GUI or any
    # number of other things with out having to change any of the other functions.
    if errors:
        print "Sorry, your password does not meet our criteria."
        for e in errors:
            # Here you can print the text or if the PASSWORD_ERRORS has more attributes you can handle the
            #   errors in different ways.
            print(e['text'])
    else:
        print "Congratulations, your password meets our criteria."

password = raw_input("Please set your password:")
check_password(password)

A: I actually prefer over-engineering this a bit. Try the following:
class BadPasswordError(ValueError):
    pass

def check_password(p:str, *validators:'(lambda p: True, "Error message")') -> bool:
    for validator, err in validators:
        if not validator(p):
            raise BadPasswordError(err)
    return True

This lets you write any number of custom validators and pass them all at once.
password_validators = [(has_unique_letters, "Warning! Please ensure letters are not repeated."),
                       (has_even_vowels, "Warning! Please ensure password contains an even number of vowels."),
                       (has_special_characters, "Warning! Please ensure password contains at last one of {@, #, *, $}."),
                       (has_divisible_numbers, "Warning! Please ensure all numbers are divisible by 2 or 3.")]

try:
    ok = check_password(user_inputted_password, password_validators)
except BadPasswordError as e:
    print(e)

You could even create a custom decorator to create your password validators in-place.
import functools

def password_validator(errmsg):
    def wrapper(f):
        @functools.wraps(f)
        def wrapped(*args):
            if f(*args):
                return True
            else:
                raise BadPasswordError(errmsg)
        return wrapped
    return wrapper

@password_validator("Warning! Please ensure letters are not repeated.")
def has_unique_letters(p):
    return len(set(p)) == len(p)

# repeat for each validator....

Then all you'll have to do is run each validator in turn and catch BadPasswordErrors.
validators = [has_unique_letters, has_even_vowels, has_special_characters, has_divisible_numbers]
for validator in validators:
    try:
        validator(p)
    except BadPasswordError as e:
        print(e)

A: Maybe you can try like this; IN this code you'll see warning message till you fix your password, but for ex, if there are 2 errors, then first error message will be something from top(from if-elif blog) , then whenever you fix your top error, you'll receive second error message which below first error and you'll also fix it, while fixing them 1 by 1 you'll receive congrats msg at last.
def check_password(x):
problem = 0
if has_unique_letters(x)==False:
    problem = 1
elif has_even_vowels(x)==False:
    problem = 2
elif has_special_character(x)==False:
    problem = 3
elif has_divisible_numbers(x)==False:
    problem = 4

if(problem == 1):
    print "Warning! Please ensure letters are not repeated."
elif(problem ==2):
    print "Warning! Please ensure password contains an even number of vowels."
elif(problem==3):
    print "Warning! Please ensure password contains at least one of {@, #, *, $}"
elif(problem==4):
    print "Warning! Please ensure all numbers are divisible by 2 or 3."
elif(problem==0):
    print "Congratulations, your password meets our criteria."


text:
Q: How to get the address on clicking in the google map? Is it possible to get the address and pin code in the billing address field in account object from google maps when the user clicks on the map.If the user clicks on different address it should get updated with that address.

A: I have put together a simple solution using Google Map API. Here I am passing the value of Latitude and Longitude from click event on the map to the Google Maps Geocoding API and it is returning me the address of the location in JSON format. In the JSON, there are different address_components available as mentioned below. I am using these values to populate new account address.
"types": [ "street_number" ] // Street No
"types": [ "route" ] // Street Name
"types": [ "administrative_area_level_1", "political" ]// the state
"types" : [ "locality", "political" ]//the city
"types": [ "postal_code" ] //Zip code

You have to pass an account ID to see the result.
VF Page
<apex:page standardController="Account" >

    <apex:form id="accountform" >
        <apex:pageBlock id="accountblock">
            <apex:pageBlockSection title="Account details">
                <apex:outputField Value="{!Account.Name}"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection id="addressblocksection" title="Address details" columns="2">
                <apex:inputField id="BillingStreet" value="{!Account.BillingStreet}" />
                <apex:inputField id="BillingCity" value="{!Account.BillingCity}" />
                <apex:inputField id="BillingState" value="{!Account.BillingState}" />
                <apex:inputField id="BillingPostalCode" value="{!Account.BillingPostalCode}" />
                <apex:inputField id="BillingCountry" value="{!Account.BillingCountry}" />
            </apex:pageBlockSection>
        </apex:pageBlock>

Hello

    </apex:form>
</apex:page>

Screen 1 Current Account Location

Screen 2 Location changed after clicking on a different area


text:
Q: The provided issuer certificate does not have an associated private key I'm trying to write a method for creating a certificate which is not CA certificate using the RequestCertificate class and method Create.
I've used this code, it created additional CA but I don't need it because I already have one:
public static void CreateCertificate4(string username, string password)
{
    var ecdsa = ECDsa.Create(); // generate asymmetric key pair

    var r = new CertificateRequest("cn=" + username, ecdsa, HashAlgorithmName.SHA256);

    var cert = r.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
    var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));

    string path1 = (AppDomain.CurrentDomain.BaseDirectory + @"\" + username + ".pfx");
    string path2 = (AppDomain.CurrentDomain.BaseDirectory + @"\" + username + ".cer");

    // Create PFX (PKCS #12) with private key
    File.WriteAllBytes(path1, cert.Export(X509ContentType.Pfx, password));

    // Create Base 64 encoded CER (public key only)
    File.WriteAllText(path2,
        "-----BEGIN CERTIFICATE-----\r\n"
        + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
        + "\r\n-----END CERTIFICATE-----");
}

I've tried to modify it and came up with this:
public static void CreateCertificate(string username, string password)
{
    var certCA = GetCertificateFromStorage(StoreName.Root, StoreLocation.LocalMachine, "TestCA");

    var ecdsa = ECDsa.Create();

    var proba = new CertificateRequest("cn=" + username, ecdsa, HashAlgorithmName.SHA256);

    var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));

    string path1 = (AppDomain.CurrentDomain.BaseDirectory + @"\"+username+".pfx");
    string path2 = (AppDomain.CurrentDomain.BaseDirectory + @"\"+username+".cer");

    File.WriteAllBytes(path1, cert.Export(X509ContentType.Pfx, password));

    // Create Base 64 encoded CER (public key only)
    File.WriteAllText(path2,
        "-----BEGIN CERTIFICATE-----\r\n"
        + Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
        + "\r\n-----END CERTIFICATE-----");
}

There is an error in line:
var cert = proba.Create(certCA, DateTimeOffset.Now, DateTimeOffset.Now.AddYears(2), Encoding.ASCII.GetBytes(password));  as stated in the title.


text:
Q: Version control for Custom Postgres Function in Django I have a custom postgres function in my Django app. Keeping it up to date with migrations works, but is very hard to code review / move changes from the DB to the migration, because each migration is an entire new block of SQL, like so:
def update_func(apps, schema_editor):
    schema_editor.execute(
        """
        CREATE OR REPLACE FUNCTION
            public.function()
        .... ect

Does anyone have a similar situation and know a better way to version control the function?


text:
Q: Firebase android how to get data from List of keys at once I am using firebase geofire library to fetch key's based on location but because of thousands of keys are returned in onKeyEntered() event every time I have to take the key refer firebase and get the object back and set it to listview becoming very slow.  I tried commenting all other work in onKeyEntered() to see how fast geofire is then I was surprised withing 900 milli's all callbacks received.
So now what is the best optimized way to get the data from firebase using the key passed in onKeyEntered() callback and set it to listview so that even for thousands of entries listview should load fast
I thought of AsyncTask in every callback give the fetching data work to AsyncTask and proceed with next callback key and do same, but not sure thats correct.
Or load only few and then load as scroll's is also good idea but geofire returns keys from all over the database so there is no option to get only few latest one so not sure how to implement it.
This is what I am trying but list view loads very slow.
  @Override
public void onKeyEntered(String key, GeoLocation location) {
    Log.d("geoevent", key);
    mDatabaseTemp = FirebaseDatabase.getInstance().getReference("/posts/" + key);
    mDatabaseTemp.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Post post = new Post();
            post = dataSnapshot.getValue(Post.class);
            mPosts.add(post);
            mPostAdapter.notifyDataSetChanged();
            mRecycler.smoothScrollToPosition(mPosts.size() - 1);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getActivity(), "error" + databaseError, Toast.LENGTH_LONG).show();

        }
    });
}

A: Question of the type "how to best" are notoriously difficult to answer. But I'll give a few hints about the general behavior of the system that you may not be aware of.

*

*the Firebase Database client interacts with the network and disk on a separate thread. When data is available for your client, it calls your handlers on the main/UI thread. This means that putting your calls in an AsyncTask is only useful if you'll be doing significant work in the callback.

*the Firebase Database client pipelines the calls to the server over a single connection. To read more about why that affects performance, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

*loading thousands of items into a mobile device over the network is in general not a good idea. You should only load data that you'll show to the user and thousands of items is well beyond what can be reasonably presented on a mobile screen. When developing a location based app, you could show a map where the user indicates a hotspot and you use Geoqueries to only request items around that spot.


text:
Q: Image with src inside ng-repeat I have a template like this

    .....

Each time this is regenerated it results in the browser clearing out the img and placing it back in again and will therefore redownload from source. The result is clunky looking ajax. How do I place an image inside an ng-repeat?

A: Use the ngSrc directive. It it used to get around this exact issue.
https://docs.angularjs.org/api/ng/directive/ngSrc

A: Since the accepted answer is incorrect and i can't comment ill make a new answer.
The correct answer is to use track by
For example

    .....

this causes the elements and images not to be redrawn but rather just the changes.


text:
Q: Making perfect circular divs with CSS As you can see here I have two divs. Each div has different text in it. Both the divs have the same styling but the div with id days is perfectly circular but the div with id hour is like an oval. How can I make the hour also circular?
Here is my code:

 .component {
   color: white;
   border: 1px solid white;
   border-radius: 50%;
   display: inline;
   padding: 20px;
 }
 body {
   background-color: black;
   margin: 20px;
 }

71

5

A: This is because when you say something like :
border-radius: 50%;

the "percentages for the horizontal axis refer to the width of the box" according to MDN documentation ( https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius )
So since you are displaying your elements inline, the width of your .component elements is exactly the width of their content. One of the solutions would be to display the elements inline-block and force them to be squares so that applying the border-radius:50% property will make them both perfect circles, no matter the size of their content.
Here's the solution I suggest :
1) Display the .components elements inline-block so that I can act on their width and height.
2) Give them a width and height that is exactly the size of the padding so that they don't stretch too far.
3) Apply text-align: center to make sure the numbers are properly centered (it was problematic for the second number).
Here's a demo of the code I suggest :

.component{
    color:white;
    border:1px solid white;
    border-radius:50%;
    display:inline-block;
    padding:20px;
    height: 20px;
    width: 20px;
    text-align:center;
}

body {
   background-color: black;
   margin: 20px;
 }

71

5

Hope this helps !

A: You have to use fixed width for this situation. The first div has higher width compare to the second div because of content(71 vs 5).
Jsfiddle

.component {
  color: white;
  border: 1px solid white;
  border-radius: 50%;
  display: inline-block;
  width: 60px;
  text-align: center;
  padding: 20px 0;
}
body {
  background-color: black;
  margin: 20px;
}

71

5

A: .component{
   color:white;
   border:1px solid white;
   border-radius:50%;
   display:inline-block;
   height:50px;
   line-height:50px;
   width:50px;
   text-align: center;
}

Update your css to this. Cheers!
See sample fiddle: Circular Div

A: This did the trick for me, not sure if thats the solution you were looking for tho :

 5


text:
Q: Bubble sort not working as expected C++ I wrote a simple bubble sorting algorithm, however it is returning strange results when ran...
I am attempting to sort parallel vectors (not sure if that is correct terminology, I'm taking the concept of parallel arrays and applying it to vectors so I can modify the size at runtime) that make up a contact list.
The code pertaining to the vectors and bubble sort:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char** argv) {

    vector <long long int> numbers;
    vector <string> names;

    names.push_back("jack");
    numbers.push_back(6515551234);
    names.push_back("jill");
    numbers.push_back(6515554321);
    names.push_back("bob");
    numbers.push_back(6515557777);
    names.push_back("aaron");
    numbers.push_back(6665559999);
    names.push_back("fred");
    numbers.push_back(1115552222);

    int index = -1;
    long int temp = -1;
    int pass = -1;
    string tempName;
    int sortChoice;

    for (pass = 0; pass < names.size(); pass++) {
        for (index = 0; index < names.size() - pass; index++) {
            if ( names[index] > names[index + 1] ) {

            temp = numbers[index];
            numbers[index] = numbers[index + 1];
            numbers[index + 1] = temp;

            tempName = names[index];
            names[index] = names[index + 1];
            names[index + 1] = tempName;

            }
        }
   }

   for(int i = 0; i < numbers.size(); i++) {
       cout << names[i] << ": " << numbers[i] << endl;
   }

    return 0;

}

And the output:
: 465675315720
aaron: 6665559999
bob: 6515557777
fred: 1115552222
jack: 6515551234

And it seems that no matter how I change the vectors themselves, the last one is always cut off, and put at the beginning with no name and a (seemingly) random number. Has anyone seen this before?
The only thing I can think of is that while the sort is processing, something goes awry in memory, causing pointing to incorrect memory locations?... And the fact that it is always the last element makes me think the issue pertains to the last iteration of the loop.
Also, I made a version of this to sort by numbers rather than names, and it works perfectly every time. It's the same code but using numbers[index] in place of names[index] in the algorithm loop.
P.S. - I'm still rather new to StackOverflow and coding in general, so if I made any mistakes in formatting this post let me know and I will change them. And I hope I provided enough information.
Thank you in advance!

A: for each loop, you should compare each neighborhood, from the first to the end.
your error:

for (index = 0; index < names.size() - pass; index++) {

should be

for (index = 0; index < names.size() - 1; index++) {

here is a sample
start: 5 4 3 2 1
loop: 0
index: 0 : [5 4] 3 2 1   =>   [4 5] 3 2 1
index: 1 :4  [5 3] 2 1   =>  4  [3 5] 2 1
index: 2 :4 3  [5 2] 1   =>  4 3  [2 5] 1
index: 3 :4 3 2  [5 1]   =>  4 3 2  [1 5]
loop: 1
index: 0 : [4 3] 2 1 5   =>   [3 4] 2 1 5
index: 1 :3  [4 2] 1 5   =>  3  [2 4] 1 5
index: 2 :3 2  [4 1] 5   =>  3 2  [1 4] 5
index: 3 :3 2 1  [4 5]   =>  3 2 1  [4 5]
loop: 2
index: 0 : [3 2] 1 4 5   =>   [2 3] 1 4 5
index: 1 :2  [3 1] 4 5   =>  2  [1 3] 4 5
index: 2 :2 1  [3 4] 5   =>  2 1  [3 4] 5
index: 3 :2 1 3  [4 5]   =>  2 1 3  [4 5]
loop: 3
index: 0 : [2 1] 3 4 5   =>   [1 2] 3 4 5
index: 1 :1  [2 3] 4 5   =>  1  [2 3] 4 5
index: 2 :1 2  [3 4] 5   =>  1 2  [3 4] 5
index: 3 :1 2 3  [4 5]   =>  1 2 3  [4 5]
loop: 4
index: 0 : [1 2] 3 4 5   =>   [1 2] 3 4 5
index: 1 :1  [2 3] 4 5   =>  1  [2 3] 4 5
index: 2 :1 2  [3 4] 5   =>  1 2  [3 4] 5
index: 3 :1 2 3  [4 5]   =>  1 2 3  [4 5]
final result: 1 2 3 4 5

A: the code that you have written above is not bubble sort !
however , try this instead , this is bubble sort:
for (pass = 0; pass < names.size(); pass++) {
        for (index = pass+1; index < names.size(); index++) {
            if ( names[pass] > names[index] ) {

            temp = numbers[index];
            numbers[index] = numbers[pass];
            numbers[pass] = temp;

            tempName = names[index];
            names[index] = names[pass];
            names[pass] = tempName;

            }
        }
   }

i offer you use a pair instead of two vectors


text:
Q: Async Post in ASHX Handler I'm having issues with ASHX handler. The following piece of code works correctly on a local machine, but it is not working on the server.
public void ProcessRequest(HttpContext context)
{
    ...... More code
    // convert class to namevaluecollection
    NameValueCollection formFields = payloadData.ToNameValueCollection();

    using (var client = new WebClient())
    {
        //client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        client.UploadValuesAsync(new Uri("http://server/accept"), "POST", formFields);
    }
}

I'm getting the following error:
Exception type: InvalidOperationException
    Exception message: An asynchronous operation cannot be started at this time.
    Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle.
    If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.
    This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing.
    Instead, the asynchronous method should return a Task, and the caller should await it.

EDIT:
One thing I found that it may be the version impact on the codebase. Can some one confirm that UploadValuesAsync behaves differently on framework 4.5 vs 4.6

A: This will post asynchronously:
Task.Run(() => PostAsync());

A: Update
After more investigation, I found that there is a configuration on the server which was leading to the error. Also What's the meaning of "UseTaskFriendlySynchronizationContext"? question was helpful.
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

The key mentioned is having default value as False in machine.config and in the web.config it set as true.

A: Have your handler implement IHttpAsyncHandler.


text:
Q: Linux/bash parse text output, select fields, ignore nulls in one field only I've done my requisite 20 searches but I can't quite find an example that includes the 'ignore null' part of what I'm trying to do.  Working on a Linux-ish system that uses bash and has grep/awk/sed/perl and the other usual suspects.  Output from a job is in the format:
Some Field I Dont Care About        = Nothing Interesting
Another Field That Doesnt Matter    = 216
Name                                = The_Job_name
More Useless Stuff                  = Blah blah
Estimated Completion                = Aug 13, 2015 13:30 EDT
Even Yet Still More Nonsense        = Exciting value
...

Jobs not currently active will have a null value for estimated completion time.  The field names are long, and multi-word names contain spaces as shown.  The delimiter is always "=" and it always appears in the same column, padded with spaces on either side.  There may be dozens of jobs listed, and there are about 36 fields for each job.  At any given time there are only one or two active, and those are the ones I care about.
I am trying to get the value for the 'Name' field and the value of the 'Estimated Completion' field on a single line for each record that is currently active, hence ignoring nulls, like this:
Job_04 Aug 13, 2015 13:30 EDT
Job_21 Aug 09, 2015 10:10 EDT
...

I started with <command> | grep '^Name\|^Estimated' which got me the lines I care about.
I have moved on to  awk -F"=" '/^Name|^Estimated/ {print $2}' which gets the values by themselves. This is where is starts to go awry - I tried to join every other line using awk -F"=" '/^Name|^Estimated/ {print $2}'| sed 'N;s/\n/ /' but the output from that is seriously wonky.  Add to this I am not sure whether I should be looking for blank lines and eliminating them (and the preceding line) to get rid of the nulls at this point, or if it is better to read the values into variables and printf them.
I'm not a Perl guy, but if that would be a better approach I'd be happy to shift gears and go in that direction.  Any thoughts or suggestions appreciated, Thanks!
Some Field I Dont Care About        = Nothing Interesting
Another Field That Doesnt Matter    = 216
Name                                = Job_4119
More Useless Stuff                  = Blah blah
Estimated Completion                =
Even Yet Still More Nonsense        = Exciting value
...

A: I can't comment, not enough reputation...
But I think something like this will work, in your print command
{printf "%s,",$2;next}{print;}

Or use paste command?
paste -s -d",\n" file

A: You can do something like:
awk -F"=" '/^Name/ {name=$2} /^Estimated/ { print name, $2}' file

if they always come in the same order: name first, estimate next.
You can then add a NULL check to the last field and don't print the line if it matches like:
awk -F"=" '/^Name/ {name=$2} /^Estimated/ { if($2 != "") {print name, $2}}' file

A: $ awk -F'\\s*=\\s*' '{a[$1]=$2} /^Estimated/ && $2{print a["Name"], $2}' file
The_Job_name Aug 13, 2015 13:30 EDT

Replace \\s with [[:space:]] if you aren't using gawk, i.e.:
$ awk -F'[[:space:]]*=[[:space:]]*' '{a[$1]=$2} /^Estimated/ && $2{print a["Name"], $2}' file

and if your awk doesn't even support character classes then GET A NEW AWK but in the meantime:
$ awk -F'[ \t]*=[ \t]*' '{a[$1]=$2} /^Estimated/ && $2{print a["Name"], $2}' file


text:
Q: Dictionary> not allowed in staruml I am using whitestaruml 5.4
with class diagram, i can't seem to be able to type this attribute
ServiceCategory: Dictionary<string,List<service>>

But Dictionary<string,List<service>> is a valid type for C#, how to get over this?

A: I suppose you are getting a lexical error on '<' as currently the input analyzer in WhiteStarUML does not accept embedded delimiters ( <[( style ) in the entity names to better handle matching opening/closing at lexer level. In the future this may get more sophisticated but currently the best way to skip parsing is to select the attribute in Model Explorer and fill the "Type" field in Property Inspector. As no parsing happens there it will be accepted. Just make sure not to modify the attribute in the Model View on the Diagram again.

A: It's June 2022 - still not fixed. Very disappointing.
When directly entering attributes, I just put a placeholder type (e.g., 'foo'). After which, you can go click on the attribute on the right pane and go down to the Editors / type field and replace it with what you want.
I use a lot of map<string,string> and have to do this often. If you try to directly edit a method and its arguments later, it will block you again and you'll have to repeat the procedure - but it can be done to make your diagrams correct. It's just a PITA.


text:
Q: Nesting angular routeProvider resolves So I have a service that returns a data set based on a passed parameter. Lets say
"red widgets", "blue widgets", "glossary"
I need to call glossary the first time this route is selected which will always call the data for the red widgets as well.
.config( ['$routeProvider', function( $routeProvider ){
    $routeProvider.when('/compare/:comparetype', {
        controller: 'compareController',
        templateUrl: 'compare/compare.tpl.html',
            resolve: {
            responseData: function(myService, $route){
                return myService.getData(
                    $route.current.params.comparetype
                );
            }
        }
    });
}])

This code works to get the first data set based on the passed comparetype ("red Widgets") but how would I also call myService.getData('Glossary'). I think it is a asycn thing but I am still learning about routes and resolve. Below is something like what I would like. I understand this is wrong but I hope it illistrates my intended purpose.
.config( ['$routeProvider', function( $routeProvider ){
    $routeProvider.when('/compare/:comparetype', {
        controller: 'compareController',
        templateUrl: 'compare/compare.tpl.html',
            resolve: {
            responseData: function(myService, $route){
                var route = $route.current.params.comparetype;
                var resp = myService.getData(route);
                if (route === 'red widget') {
                    resp.glossary = myService.getData('glossary');
                }
                return resp;
            }
        }
    });
}])

As a side note, resp.glossary will eventually be placed in $rootScope.glossary if it is in responseData. This part isn't the problem. I just need to know how why myService.getData() isn't working the way I want it to.
Here is my factory method:
.factory('myService', function($http) {
    var myService = {
        getData: function(compare) {
            var promise = $http({
                url: "/data.json",
                method: "GET",
                cache: false,
                params: {
                    compare: compare
                },
                transformResponse: function(response) {
                    // do some stuff...
                    return resp;
                }
            })
            .then(function(response) {
                return response.data;
            });
            return promise;
        }
        return myService;
    }
});

A: You would have to create your own promise and return that for the resolve function. They you would have to resolve the promise you created when complete data is available. Something like
resolve: {
            responseData: function(myService, $route,$q){
                var defer=$q.defer();
                var route = $route.current.params.comparetype;
                myService.getData(route).then(function(data){
                      resp=data;
                      if (route === 'red widget') {
                          myService.getData('glossary').then(function(glossary){
                               resp.glossary=glossary;
                               defer.resolve(data);
                          });
                      }

                });
                return defer.promise;
            }

I am assuming that your getData is a async method that return promise.


text:
Q: why does .htaccess rewrite behave differently based on form content? I am doing a post transaction with "having x," in the form field being submitted. My .htaccess is ensuring https: and www.  My redirect is changing the post to a get for the previously mentioned data.  If I change pretty much anything it redirects the post just fine.
What I'm looking for is for it to act like test 2, in other words forward as a post transaction with the associated post data.  It seems really odd that the content of the form could affect the behavior of the rewriting.  Any ideas are very welcome.  Thanks!

EDIT:
Per the accepted answer below, this was the host running mod-security to guard against sql injection attacks.  I could have asked them to turn it off, but decided to leave it and just check $_SERVER['REDIRECT-STATUS'] for a '403' in order to respond with an appropriate message.

Here is the code for my test, which I invoke with /test uri to get the form.
<?php
$uri = $_SERVER['REQUEST_URI'];

if ($uri == '/test') {
?>
<html>
<head>

</head>
<body>
    <form
        name="testForm"
        method="post"
        action="/testpost">

    <input type="text"
           name="testName"
           value="having x,"/>

    <input type="submit" name="submit" id="submit" value="test" />

    </form>
</body>
</html>
<?php
} elseif ($uri == '/testpost') {
echo '<pre>';
var_dump($_POST);
var_dump($_SERVER);
}

And here are the tests, showing the $_POST data and the relevant portions of $_SERVER:

Test 1 having x,

array(0) {
}
array(56) {
  ["CONTENT_TYPE"]=>
  string(33) "application/x-www-form-urlencoded"
  ["CONTENT_LENGTH"]=>
  string(2) "32"
  ["HTTP_USER_AGENT"]=>
  string(120) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
  ["HTTP_X_FORWARDED_PROTO"]=>
  string(5) "https"
  ["HTTP_X_HTTPS"]=>
  string(2) "on"
  ["REDIRECT_REDIRECT_HTTPS"]=>
  string(2) "on"
  ["REDIRECT_REDIRECT_SERVER_PORT"]=>
  string(3) "443"
  ["REDIRECT_REDIRECT_REQUEST_METHOD"]=>
  string(4) "POST"
  ["REDIRECT_REDIRECT_STATUS"]=>
  string(3) "403"
  ["REDIRECT_HTTPS"]=>
  string(2) "on"
  ["REDIRECT_SERVER_PORT"]=>
  string(3) "443"
  ["REDIRECT_STATUS"]=>
  string(3) "403"
  ["HTTPS"]=>
  string(2) "on"
  ["SERVER_PORT"]=>
  string(3) "443"
  ["REQUEST_SCHEME"]=>
  string(5) "https"
  ["CONTEXT_PREFIX"]=>
  string(0) ""
  ["REMOTE_PORT"]=>
  string(5) "39916"
  ["REDIRECT_URL"]=>
  string(10) "/403.shtml"
  ["SERVER_PROTOCOL"]=>
  string(8) "HTTP/1.1"
  ["REQUEST_METHOD"]=>
  string(3) "GET"
  ["QUERY_STRING"]=>
  string(0) ""
  ["REQUEST_URI"]=>
  string(9) "/testpost"
  ["SCRIPT_NAME"]=>
  string(10) "/index.php"
  ["PHP_SELF"]=>
  string(10) "/index.php"
}

Test 2 havng x,

In test 2 notice the misspelling of having as havng
array(2) {
  ["testName"]=>
  string(8) "havng x,"
  ["submit"]=>
  string(4) "test"
}
array(51) {
  ["CONTENT_TYPE"]=>
  string(33) "application/x-www-form-urlencoded"
  ["CONTENT_LENGTH"]=>
  string(2) "31"
  ["HTTP_USER_AGENT"]=>
  string(120) "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
  ["HTTP_X_FORWARDED_PROTO"]=>
  string(5) "https"
  ["HTTP_X_HTTPS"]=>
  string(2) "on"
  ["REDIRECT_HTTPS"]=>
  string(2) "on"
  ["REDIRECT_SERVER_PORT"]=>
  string(3) "443"
  ["REDIRECT_STATUS"]=>
  string(3) "200"
  ["HTTPS"]=>
  string(2) "on"
  ["SERVER_PORT"]=>
  string(3) "443"
  ["REQUEST_SCHEME"]=>
  string(5) "https"
  ["CONTEXT_PREFIX"]=>
  string(0) ""
  ["REMOTE_PORT"]=>
  string(5) "42046"
  ["REDIRECT_URL"]=>
  string(9) "/testpost"
  ["SERVER_PROTOCOL"]=>
  string(8) "HTTP/1.1"
  ["REQUEST_METHOD"]=>
  string(4) "POST"
  ["QUERY_STRING"]=>
  string(0) ""
  ["REQUEST_URI"]=>
  string(9) "/testpost"
  ["SCRIPT_NAME"]=>
  string(10) "/index.php"
  ["PHP_SELF"]=>
  string(10) "/index.php"
}

It will also work with:
having x
having,
aving x,
having something else,
etc.

But will not work with
having something,
having somethingelse,

Here is the htaccess code:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ /index.php [NC,L]

A: Your host is blocking having x. It thinks this is a SQL injection attack on your server. You need to talk to your host if you want them to allow this.


text:
Q: can I perform a query inside of JPA entity to get back a single column I have a dumb question.  It would be great if this could be done, but I am not holding my breath.
I need a single column from a table linked to my JPA entity to be a collection in said JPA entity.  Is there any way, that I can just get back that column alone that is related to that entity, instead of having to get back an entire table (which could be very costly?)
Can I perform a query inside that JPA entity that will be performed and loaded eagerly into a collection?
I am trying to avoid having to make several calls to the database by just executing a couple of queries.
What are your thoughts on this?

A: @ElementCollection(fetch=FetchType.EAGER)
        @CollectionTable(name="QUICK_LAUNCH_DISTLIST",joinColumns=@JoinColumn(name="QUICK_LAUNCH_ID"))
        @Column(name="LIST_ID")
private List<Long> distListIDs;

The ElementCollection attribute is what I was looking for.  It seems to work pretty well in addition to that.
Thanks for the help and inspiration guys.

A: Suppose a Category has many products:
select product.name from Category c inner join c.products product where ...

If that's not what you want, please show an example in your question.


text:
Q: How to specify PlotMarkers that scale when graphic is resized? A ListPlot's default markers resize as the plot is resized.
ListPlot[{{{1, 1}}, {{2, 2}}, {{3, 3}}}]

However, if you specify custom PlotMarkers that use Scaled for their dimensions then these markers do not resize as the plot is resized.
ListPlot[{{{1, 1}}, {{2, 2}}, {{3, 3}}},
 PlotMarkers -> Graphics /@ {
    Circle[{0, 0}, Scaled[.1]],
    Disk[{0, 0}, Scaled[.1]],
    Disk[{0, 0}, Scaled[.1], {0, 4}]}]

How do you specify PlotMarkers that resize when the plot is resized?
A solution that does not use Dynamic is preferred.  I am thinking that there must be a means to do this since without Dynamic it works on the default markers.

A: There is a way to specify scaled sizes of the plot markers explicitly via the PlotMarkers option. Citing the Documentation page for PlotMarkers (under the "Details" section):

With PlotMarkers -> {g, s}, the object g is scaled so that one unit of its coordinates corresponds to a fraction s of the width of the whole graphic.

This statement is slightly incorrect because the specification PlotMarkers -> {g, s} (where g has Head Graphics) is directly translated by ListPlot into
Inset[g, pos, Automatic, Scaled[{s, s}]]

(where pos is coordinates of a datapoint) what can be seen from InpuForm of generated graphics:
First@Cases[
   ListPlot[{0, 1, 3, 4, 5}, PlotMarkers -> {{Graphics[Disk[]], .1}}],
   _Inset, -1] /. _Graphics -> g

Inset[g, {1., 0.}, Automatic, Scaled[{0.1, 0.1}]]

So a more correct statement would be:

With PlotMarkers -> {g, s}, the object g with head Graphics is scaled so that its size is equal to a fraction s of the whole plotting range.

For the case in the question a solution may be written as follows:
ListPlot[{{{1, 1}}, {{2, 2}}, {{3, 3}}}, PlotRange -> {{0, 4}, All},
 PlotMarkers -> ({Graphics[#], .1} & /@ {Circle[{0, 0}, 1], Disk[{0, 0}, 1],
     Disk[{0, 0}, 1, {0, 4}]})]

Note that you don't have to use Scaled radii/coordinates in this case (although you can if you have a good reason for this).
Note also that if you wrap your primitives by List, then they will be styled automatically according to PlotStyle option:
ListPlot[{{{1, 1}}, {{2, 2}}, {{3, 3}}}, PlotRange -> {{0, 4}, All},
 PlotMarkers -> ({Graphics[{#}], .1} & /@ {Circle[{0, 0}, 1], Disk[{0, 0}, 1],
     Disk[{0, 0}, 1, {0, 4}]})]

A: Here is a post-processing approach:
ListPlot[{{{1, 1}}, {{2, 2}}, {{3, 3}}},
 PlotMarkers -> Graphics /@ {
    Circle[{0, 0}, Scaled[.1]],
    Disk[{0, 0}, Scaled[.1]],
    Disk[{0, 0}, Scaled[.1], {0, 4}]}
 ] /. Inset[g_Graphics, pos_] :> Inset[g, pos, Automatic, Scaled[1]]

Explanation. By default the inset is rendered with fixed size and your Scaled radius is calculated relative to this fixed size. When we specify the size of inset to be Scaled[1] we make the size of the inset equal to the size of the whole plotting range of the enclosing graphics. As the result when you resize the enclosing graphics (by the mouse or by changing the ImageSize option) the inset is scaled with it.


text:
Q: installer Problem in iPhone app I developed on audio based application, when i drag and drop .app file into the iTunes its not at all showing in iTunes application list.
The application size is 177 Mb.
Is there any problem with the size.
Please help me out in this issue.
thanks in advance.
Satya.

A: I don't believe size is the problem (much larger apps than that are allowed, i believe 2Gb, just not over 3G).
Anyway, did you set up a distribution certificate and edit your entitlements correctly? I belive this link will help you.


text:
Q: How do I add support of vue-apollo for IE11? I'm working on MEVN stack with GraphQL implementation. I had problems displaying my Vue application on IE11, but then I added babel-polyfill which provides support for vuetify and vue templates. Now vue application loads the vue templates but I have problems with vue-apollo.
I have tried using es6-promise and isomorphic-unfetch but I'm still facing with the vue-apollo errors
https://i.imgur.com/Ye7R7Qc.jpg "vue-apollo errors"
Please also check if my config files are correct
babel.config.js
module.exports = {
  presets: [
    [
      '@vue/app',
      {
        useBuiltIns: 'entry',
      },
    ],
    [ '@babel/preset-env' ],
  ],
  sourceType: 'unambiguous',
};

main.js
import 'babel-polyfill';
import Vue from 'vue';
import 'isomorphic-unfetch';
import 'es6-promise/auto';

vue.config.js
 transpileDependencies: ['vuetify'],

appoloConfig.js
// Create the apollo client
const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: true,
  defaultOptions: {
    query: {
      fetchPolicy: 'network-only',
    },
  },
  fetchOptions: { fetch },
});

I'm new to vue world, I'm trying to make my vue application work in IE as well, any help is much appreciated :)


text:
Q: Replacing Values in a Column on the Basis of n Consecutive Entries I have a column of data with values ranging from 0, 1, & 2. I would like to replace all instances of 1 and 2 with the value of 0 if these occurrences do not persist for n rows. If the values persist, for n rows, I would like to leave them as-is. Example, where n=4:
df = pd.DataFrame({'data': [1,0,1,2,0,0,0,1,0,2,2,2,2,2,2,0,1,0,1,0,2],
                   'desired': [0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,0,0,0,0,0,0]})

    data  desired
0      1        0
1      0        0
2      1        0
3      2        0
4      0        0
5      0        0
6      0        0
7      1        0
8      0        0
9      2        2
10     2        2
11     2        2
12     2        2
13     2        2
14     2        2
15     0        0
16     1        0
17     0        0
18     1        0
19     0        0
20     2        0

The intended functionality is to essentially "filter" the underlying data for brief changes in values. I'd like to be able to declare the number of consecutive values necessary which permit keeping the underlying data, including all values below and above 'n'. (If n = 4 and there are 6 consecutive values, I want all 6, not just the 2 that persisted beyond the cutoff of 4.). Is there a vectorized way of doing this in Pandas?

A: IIUC, you can do:
n = 6

# find where the values repeats n times
s = df['data'].diff().eq(0).rolling(n-1).sum()

# fill
df['desired'] = np.where(s.where(s>=n-1).bfill(limit=n-1).notnull(), df['data'], 0)

Output:
    data  desired
0      1        0
1      0        0
2      1        0
3      2        0
4      0        0
5      0        0
6      0        0
7      1        0
8      0        0
9      2        2
10     2        2
11     2        2
12     2        2
13     2        2
14     2        2
15     0        0
16     1        0
17     0        0
18     1        0
19     0        0
20     2        0

A: Using the cumsum of the difference, then get the size of each group:
n = 4
groups = df['data'].diff().ne(0).cumsum()
df['desired'] = df['data'].where(df.groupby(groups)['data'].transform('size').gt(n), other=0)

    data  desired
0   1     0
1   0     0
2   1     0
3   2     0
4   0     0
5   0     0
6   0     0
7   1     0
8   0     0
9   2     2
10  2     2
11  2     2
12  2     2
13  2     2
14  2     2
15  0     0
16  1     0
17  0     0
18  1     0
19  0     0
20  2     0

Timings:
# create sample dataframe of 1 million rows
df = pd.DataFrame({'data': [1,0,1,2,0,0,0,1,0,2,2,2,2,2,2,0,1,0,1,0,2]})
dfbig = pd.concat([df]*50000, ignore_index=True)
dfbig.shape

(1050000, 1)

Erfan
%%timeit
n = 4

groups = dfbig['data'].diff().ne(0).cumsum()
dfbig['data'].where(dfbig.groupby(groups)['data'].transform('size').gt(4), other=0)

268 ms ± 15.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Quang Hoang
%%timeit
n=4
s = dfbig['data'].diff().eq(0).rolling(n-1).sum()

# fill
np.where(s.where(s>=n-1).bfill(limit=n-1).notnull(), dfbig['data'], 0)

164 ms ± 3.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

piRSquared
%%timeit
a = dfbig.data.to_numpy()
b = np.append(0, a[:-1] != a[1:]).cumsum()

dfbig.data.where(np.bincount(b)[b] >= 4, 0)

62 ms ± 735 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Conlusion:

*

*piRSquared

*Quang Hoang

*Erfan

A: bincount
a = df.data.to_numpy()
b = np.append(0, a[:-1] != a[1:]).cumsum()

df.assign(desired=df.data.where(np.bincount(b)[b] >= 4, 0))

    data  desired
0      1        0
1      0        0
2      1        0
3      2        0
4      0        0
5      0        0
6      0        0
7      1        0
8      0        0
9      2        2
10     2        2
11     2        2
12     2        2
13     2        2
14     2        2
15     0        0
16     1        0
17     0        0
18     1        0
19     0        0
20     2        0


text:
Q: Как быть, если нужно где-то хранить изменения нетреканных файлов? К примеру, пишется какой-либо плагин на jQuery, разумно, если в production-ready ветку попадает уже минифицированный код. Но, чтобы было проще ориентироваться в куче коммитов и веток (в phpstorm), код в них нужно как-то оставлять оригинальным (т.е. не минифицированным)... или любая другая подобная ситуация, например, настройки htaccess (вроде и не нужны в production-ready, но и untracked их оставлять дорого). Для этой цели в develop ветку (бог с ним) вливаем эти файлы вместе с минифицированным кодом... а как потом из develop ветки влить в production-ready, чтобы смержился только минифицированный код? Т.е. чтобы оригинальный код в production-ready не попал?
PS Пример с jQuery плагином приведен исключительно для аналогии, чтобы обозначить границы вопроса.
A: IMHO конечно, но зачем минифицированный (читаем сгенерированный системой) код хранить в истории версий? Пусть он генерируется сам по себе относительно тех девелоперских версий, ветка которых на данный момент активна. Т.е. это дело автоматического скрипта/программы обфускатора, а не системы контроля версий.
Подобная проблема была при работе с LESS и выкладке минифицированного сгенерированного CSS. Решилось все именно так, на сервере (и локально у девелоперов) стоял скрипт который генерил минифицированную версию текущей ветки, а в GIT уходили только LESS файлы.


text:
Q: How to declare inner radius for input box inner radius of input box
<input type="text" class="input-text">

css
.input-text{
  border-width: 4px;
  border-color: #F85534;
  padding: 6px 14px;
  width: 540px;
  font-size: 16px;
  margin: 0px !important;
  height: 35px;
  -webkit-appearance: none;
  z-index: 5;
  position: relative;
  border-radius:0px;
  box-shadow: inset -1px 1px 2px
  rgba(43, 40, 40, 0.2),-1px 1px 0px
  rgba(43, 40, 40, 0.2),-2px 2px 0px
  rgba(43, 40, 40, 0.2);
  -webkit-box-shadow: inset -1px 1px 2px rgba(43, 40, 40, 0.2),-1px 1px 0px rgba(43, 40,40,0.2),-2px 2px 0px rgba(43, 40, 40, 0.2);
}

I need inner radius for text box, outer radius should be zero.
EDIT
Image

A: I'm not sure if you can do it without wrapping the input in a div, this is how i would do it:
HTML:

<input type="text" placeholder="text">

CSS:
.input-wrapper {
    background: blue;
    padding: 3px;
    display: inline-block;
}

.input-wrapper input {
    border-radius: 5px;
    border: none;
    font-size: 14px;
    padding: 3px;
}

Check a JS-fiddle here: http://jsfiddle.net/qCyKW/


text:
Q: Laravel Route outside of main app How can I do a laravel route on an external folder?
This is what I mean:
I have my main app pointing to mysite.com/myapp
So all my routes are like mysite.com/myapp/something
and the route is
Route::get('something',['uses'=>'someController@index']);

but I have a folder on mysite.com/subdomain which is accessed through subdomain.mysite.com
and I would like to create routes there too so i can access them as subdomain.mysite.com/abc/def with something like
Route::get('../subdomain/abc/{$someVariable}',['uses'=>'someController@someFunction']);

let me know if this makes sense and is possible in any way, thanks

A: In Laravel is not necessary to create a subfolder to do subdomain routes.
https://laravel.com/docs/5.6/routing#route-group-sub-domain-routing
You can do
Route::domain('subdomain.mysite.com')->group(function () {
    // subdomain.mysite.com/abc/def
    Route::get('abc/{someVariable}', 'someController@someFunction');
});

If you want to define routes into a file that is not the routes.php you can include_once into routes.php or include into a Service Provider


text:
Q: How do I properly add 'script wheel' to python path? I just installed Python 3.7 from python.org. I followed this StackOverflow post to change my default Python to Python 3. From there I ran the Update Shell Profile.command and Install Certificates.command
(Finder > Applications > Python 3.7).
Then I found that I couldn't run the pip command
> $ pip --version

> -bash: pip: command not found

Subsequently I ran the following 2 commands..
> $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
>
> $ python get-pip.py
Collecting pip
  Downloading https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 5.5MB/s
Collecting wheel
  Downloading https://files.pythonhosted.org/packages/81/30/e935244ca6165187ae8be876b6316ae201b71485538ffac1d718843025a9/wheel-0.31.1-py2.py3-none-any.whl (41kB)
    100% |████████████████████████████████| 51kB 12.1MB/s
Installing collected packages: pip, wheel
Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pip'
Consider using the `--user` option or check the permissions.

Then I added the --user flag
> $ python get-pip.py --user
>
> Collecting pip   Using cached
> https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl
> Collecting wheel   Using cached
> https://files.pythonhosted.org/packages/81/30/e935244ca6165187ae8be876b6316ae201b71485538ffac1d718843025a9/wheel-0.31.1-py2.py3-none-any.whl
> Installing collected packages: pip, wheel

This is what I don't understand
> The script wheel is
> installed in '/Users/kevinturney/Library/Python/2.7/bin' which is not
> on PATH.

> Consider adding this directory to PATH or, if you prefer to
> suppress this warning, use --no-warn-script-location.

What is the wheel and how do I add this to the correct path?
> $ which python

> /usr/local/opt/python/libexec/bin/python

What is the wheel and how do I add this to the correct path?


text:
Q: Logarithm of a matrix I am looking for a reference to study logarithm of an invertible triangular matrix. What is a good algorithm? Are there any good reference which studies this topic both theoretically and from an algorithm view point? I am also looking for structure of the logarithm of an upper/lower triangular invertible matrix.

A: If your matrix is triangular, you can read off the eigenvalues, and it is not hard to find the eigenvector/generalized eigenvectors. Once you have those, it is easy to find the logarithm.

A: You may want to take a look at "Functions of Matrices: Theory and Computation" by Higham. Chapter 11 is specifically devoted to the matrix logarithm. In  particular, the chapter contains a thorough comparison of four different numerical algorithms.


text:
Q: How do I know when an individual request in a curl_multi_exec() has finished in PHP? I would like to time my individual requests. They were timed before as separate curl requests. Now I would like to combine them with curl_multi_exec and continue to time how long they take. Here is my code:
$mh = curl_multi_init();
curl_multi_add_handle($mh, $ebayRequest);
curl_multi_add_handle($mh, $prosperentRequest);
$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);
$ebay = curl_multi_getcontent($ebayRequest);
$prosperent = curl_multi_getcontent($prosperentRequest);
//close the handles
curl_multi_remove_handle($mh, $ebayRequest);
curl_multi_remove_handle($mh, $prosperentRequest);
curl_multi_close($mh);

Here is the old code which timed them.
$ebayTime = microtime(true);
// $ebay = $this->ebayExecuteSearch($ebay);
Yii::warning("Ebay time: ".(microtime(true) - $ebayTime));

I thought curl_multi_info_read might help, but it doesn't look useful.


text:
Q: Only remove empty sub-folders not root I was reading this post here: https://stackoverflow.com/a/28637537/800592
one of the comments mentions in order to not delete the root folder to do
 @bricktop if ($IsEmpty) { # only remove if it is not the root if ($Path -ne $InPath) { Write-Output ">> Deleting empty folder ${InPath}" Remove-Item -Force -LiteralPath $InPath } }

BUT there's no where that sets the $InPath var ?? what am I missing here ?

A: A simple solution adapted from the original answer is to pass a recursion-depth counter to the script block, which defaults to 0 and is incremented for every recursive call.
Thus, if the counter is 0, you know that you're dealing with the original input path, and you can ignore the attempt to delete that path itself:
$tailRecursion = {
  param(
    [string] $LiteralPath,
    [int] $Depth = 0  # Helper parameter for internal use that tracks the recursion depth.
  )
  # Recurse over subdirs.
  foreach ($childDirectory in Get-ChildItem -Force -LiteralPath $LiteralPath -Directory) {
    # Note the increment to the recursion depth with -Depth ($Depth + 1)
    & $tailRecursion -LiteralPath $childDirectory.FullName -Depth ($Depth + 1)
  }
  $isEmpty = -not (Get-ChildItem -Force -LiteralPath $LiteralPath | Select-Object -First 1)
  if ($isEmpty -and $Depth -gt 0) { # dir. is empty and NOT the input dir.
    Write-Verbose "Removing empty folder at path '${LiteralPath}'." -Verbose
    Remove-Item -Force -LiteralPath $LiteralPath -WhatIf
  }
}

# Sample call: delete all empty subdirs. in the current dir.'s
# subtree, without trying to delete the current dir itself,
# should it turn to be empty too.
& $tailRecursion -LiteralPath .

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf  once you're sure the operation will do what you want.

Note that this alternative answer to the same question provides the desired functionality directly, and more elegantly; the only downside - which will rarely matter in practice - is increased memory consumption due to the up-front sorting of all directory-info objects.
Here's a slightly tweaked version:
# Uses . (the current dir.) as the sample input path.
Get-ChildItem -LiteralPath . -Recurse -Force -Directory |
    Sort-Object -Property FullName -Descending |
    Where-Object { -not ($_ | Get-ChildItem -Force | Select-Object -First 1) } |
    Remove-Item -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf  once you're sure the operation will do what you want.


text:
Q: Requiring 'fetch' is returning an empty object in a React-Native app I'm currently working on my second react-native application. Previously I had simply required fetch like so:
var fetch = require('fetch');

I never installed it with npm, as it was already available by default.
I just started a new react-native project (after updating my react native cli) and now when I require fetch in the same fashion and try to call a fetch method my app crashes and I get an error that says
Object is not a function(evaluating 'fetch(API_URL, fetchObject)')

When I console out fetch with
console.log(fetch);

I get
{}

Any suggestions?

A: Alright, it looks you don't event have to require fetch any more. It's just available globally.

A: Try to include React/RCTNetwork subspec in native.


text:
Q: Eclipse: How to set word as auto activation trigger for code completion I'd like to have as auto activation trigger for autocompletion in eclipse word "new " (with space included), not only single character. Is this possible?
Thanks
Note: This can be found under Window - Preferences - Editor - Content Assist

A: No, doesn't look like it.  And as I'm sure you already know, just a space triggers on far too many contexts.


text:
Q: Getting Updated UI in Android using Asynctask I am building a Maze game in android (for a school assignment), and am having trouble getting an automated driver to work. The Game works fine for manual maze exploration, but when I try to use a driver to explore the maze the graphics don't update to the view. I know I have to use a handler somehow, but I am a bit lost on that matter. A few codeblocks below might help make things more clear.
This is in PlayActivity:
class RobotTask extends AsyncTask<Integer , Void , Void> {

    @Override
    protected Void doInBackground(Integer... params) {
        robotDriver.setView(mazeView);
        try {

            if(robotDriver.drive2Exit()) {
                Intent finishIntent = new Intent(PlayActivity.this, FinishActivity.class);
                startActivity(finishIntent);
            }
        } catch (Exception e) {
            Toast.makeText(PlayActivity.this, "Robot Ran Out Of Power", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(PlayActivity.this , AMazeActivity.class);
            NavUtils.navigateUpTo(PlayActivity.this, intent);

        }
        return null;
    }

And then robotDriver.drive2Exit() calls a specific exploration algorithm which moves the robot, this code is below (not all of it, just where I assume I need a change):
if(forward)
            try {
                Thread.sleep(250);
                robot.move(1, true);
                this.mazeView.postInvalidate();
            } catch (HitObstacleException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                        }
else {
            try {

                robot.rotate(90); // turn then move
                this.mazeView.postInvalidate();
                Thread.sleep(250);
                robot.move(1, true);
                this.mazeView.postInvalidate();
                Thread.sleep(500);
            } catch (HitObstacleException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    break;
                }
            }

robot.move() and rotate() move the robot through the maze, and then update the two drawers classes I use to present the firstpersonview. These updates update the bitmap in mazeView, where I would hope that the postInvalidate() call would then feed these updates to the viewer.
Any thoughts would be helpful.

A: I don't think you can start the activity directly from the doInBackground() method and you can't update view from the worker thread. All these operations (Intent, Toast) have to be done in the UI thread

A: I think you problem is that you're trying to do some process that should update your UI thread on a thread that is not your UI thread.  Either you want this process to run on your UI thread and update it accordingly, or you don't.  According to the documentation postInvalidate()  causes an invalidate to happen on a subsequent cycle through the event loop.  So you should call invalidate() on the mazeview in your UI thread.  To fix this you have to reorganize your code to something like the following.  Make an async class to do your robot's moving caclulations:
    private final Robot robot;
public class RobotWorker extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        //implement locking / synchronization here
        if( forward ) {//pas as a param
            try{
                Thread.sleep(250);
                robot.move(1,true);
            }catch( HitObstacleException e ){
                e.printStackTrace();
            }
        }
    else{
            try{
                robot.rotate(90);
                Thread.sleep(250);
            }catch( HitObstacleException e ){
                e.printStackTrace();
            }
        }
        return null;
    }
}

and on your UI thread do something like this
public void myRobotMover(){
    //implement locking / synchroniztion
    new RobotWorker().execute();
    mazeView.invalidate();
}

Again, you'll have to implement some synchronization and locking.  Learn how to here.


text:
Q: get var name from this or self reference javascript I see that there are some other questions that seem to be on a similar topic but none have an answer that will help me with my particular problem. I have made a thread library in in JavaScript built around the setTimeout and setInterval functions.  This is working very well except that my thread library requires that the name of thread is past to the thread i.e when I instantiate the thread it looks like this.
t = new Thread(payload, "t")

payload is an object that defines the what the thread will do when it gets a chance to execute. This allows me to abstract the task of the thread from the underlying threads "plumbing".  In any case my problem that I have to pass name of thread because setTimeout and setInterval take a JavaScript command as a string i.e setTimeout("doStuff", 0).  As I use my thread library in more applications passing the name to the thread is becoming more of a pain.  So I would like to be able to avoid this by getting the name of the thread from within the thread class like this:
var myThreadName = this.someMagicFunction();

or
var myThreadName = someMagicFunction(this);

or some other fantastic method if anyone has any ideas for me I would be most grateful.

A: Actually, both can take a function as the first parameter, and this is the recommended usage (since the string versions do an eval).
setTimeout(doStuff, 0);

In your case, you might be able to do something like:
setTimeout(function(){
  t.payload();
}, 0);

depending how the Thread object looks.
See the MDC documentation (setTimeout, setInterval).

A: You can pass a function to setTimeout as long as it is argument-free, i.e.
function takeme()
{
    alert('workin?');
}

setTimeout(takeme, 100);

and if it is not, then you can try
function takeme(x)
{
    alert(x);
}
var test = 1;
setTimeout(function(){ takeme(test); }, 100);

But if you really need to extract a function name, then please see this post. Not exactly the same, but somewhat related.


text:
Q: 'He may need not to ...' or 'He may not need to ...' I am wondering if it is correct to say:
He may need not to ...
or should we say
He may not need to ...

A: They are both grammatical and reasonably idiomatic, and have very different meanings.

He may not need to go.

means "It is possible that he will not have to go".

He may need not to go.

(which is probably less common) means something like "It is possible that he will find that he must not go."


text:
Q: Girth and diameter of a graph with minimum degree at least 3 The problem is motivated by generalizing Moore graphs, graphs with maximum possible girth ($2\text{diam}+1$) given the diameter.
Question. Does there exist a graph $G$ with $\text{g}(G)-\text{diam}(G)>8$ and minimum degree at least $3$, where $\text{g}(G)$ and $\text{diam}(G)$ are the girth and diameter of $G$, respectively?
Remark. There's an infinite class of graphs with $\text{g}(G)-\text{diam}(G)=8$: the (point,line) incidence graphs of generalized octagons have $\text{g}(G)=16$ and $\text{diam}(G)=8$.
Bonus points (+200 bounty) for a proof that $\text{g}-\text{diam}$ is unbounded for graphs with minimum degree at least $3$.

A: The recent preprint "A randomized construction of high girth regular graphs" by Linial and Simkin suggests in its closing remarks that the answer (at least, to your bonus question) is unknown:

The possible relation between a graph's girth and its diameter is particularly intriguing. It follows from [12] and Moore's bound that
$$2 \ge \mathrm{lim\ sup} \frac{\mathrm{girth}(G)}{\mathrm{diam}(G)} \ge 1,$$
where the lim sup ranges over all graphs where all vertex degrees are $\ge 3$. Nothing better seems to be known at the moment.
Even more remarkably, we do not know whether
$$\mathrm{sup}(\mathrm{girth}(G) − \mathrm{diam}(G))$$
is finite or not. The sup is over all $G$ in which all vertex degrees are $\ge 3$.


text:
Q: How Can I use two differents CSS backgrounds in Angular? I would like to change the background based on a boolean.
If I have two backgrounds in CSS:
.background {
  background-image: url('../assets/images/Background.png');
  background-repeat: no-repeat;
  background-size: contain;
  @media screen and (max-width: 1280px) {
  }
  background-size: 100% 670px;

  @media screen and (min-width: 1920px) {
    background-size: 100% 800px;
  }
  @media screen and (min-width: 2560px) {
    background-size: 100% 1200px;
  }
}

.performance-background {
  background-image: url('../assets/images/Background-performance.png');
  background-repeat: no-repeat;
  background-size: contain;
  @media screen and (max-width: 1280px) {
  }
  background-size: 100% 335px;

  @media screen and (min-width: 1920px) {
    background-size: 100% 325px;
  }
  @media screen and (min-width: 2560px) {
    background-size: 100% 325px;
  }
}

I would like to use something similar to:
[ngClass]="{ 'background': displayBackground, 'performance-background': displayPerformanceBackground}"

Thank you so much.

A: You can add different classes depending of a boolean state using angular ngClass and a ternary operator in a HTML tag
example:
HTML:
 <div [ngClass]="boolean ? 'trueClass' : 'falseClass'"> Example Text</div>

"boolean" is a variable and if it is set to true the html tag will use "trueClass" class, else "falseClass"
CSS:
.trueClass{
background: red
}

.falseClass{
background:blue
}


text:
Q: Nested Loop Char[] Write a loop that displays all possible combinations of two letters where the letters are 'a', or 'b', or 'c', or 'd', or 'e'. The combinations should be displayed in ascending alphabetical order:
aa
 ab
 ac
 ad
 ae
 ba
 bb
 ...
 ee
Here is my code:
   Char[] letters = {'a', 'b', 'c', 'd', 'e'};

for(int i=0; i < letters.length() ; i++)
{
  for(int ii=0; ii < letters.length() ; ii++)
  {
    System.out.print(letters[i]);
    System.out.println(letters[ii]);
  }
}

A: What is Char[]?  It's likely that you meant char[] or even Character[], but I'm siding more with the former.  Remember - objects in Java are capitalized.  Primitives aren't.  You may be looking for a primitive array.
It's also the case that an array does not have a method call to length.  You may reference it simply by letters.length.


text:
Q: How to get list of keys from a JSON object in Ansible? I have a JSON like this:
"ip":{
  "192.17.130.01":{
    string:"pararam"
 }
  "192.17.130.02":{
    string:"tararam"
 }
}

How can I get a list of IPs using Ansible?

A: Here's a solution for you:
- set_fact:
    my_list_of_ips: "{{ ip | from_json | list }}"

Using a list filter on a dictionary will produce a list of its keys.
Apply from_json filter if the input is a JSON string (otherwise you can skip it).
Remember dictionaries are not sorted, so don't be surprised the order on the resulting list is different to what you see on the screen above.


text:
Q: MATCH AGAINST Query issue I have a problem with MATCH AGAINST, when i'm trying to find a record. In my users table i have a user with the following data:
first_name: Alejandra Maria de los Angeles
last_name: Quintero Barreiro Gutierrez
when i try to make the following queries:
SELECT *
FROM articles
INNER JOIN users ON articles.author_id = users.id
WHERE MATCH(first_name,last_name) AGAINST('Alejanra Gutierrez')

SELECT *
FROM articles
INNER JOIN users ON articles.author_id = users.id
WHERE MATCH(first_name,last_name) AGAINST('A Barreiro')

SELECT *
FROM articles
INNER JOIN users ON articles.author_id = users.id
WHERE MATCH(first_name,last_name) AGAINST('los angeles')

All queries are returning correct information, but if the search is replace for "de los" which is in the first_name, the query doesn't work.
Someone have some idea why or can help me with this?
P.D. The tables were in InooDB with MySQL 5.6.15 but i changed it by MyISAM. When i had InooDB this kind of queries was working but with the engine change doesn't work

A: MySQL full text search ignores words shorter than 4 characters by default.  Read about it here:

The minimum and maximum lengths of words to be indexed are defined by
  the innodb_ft_min_token_size and innodb_ft_max_token_size for InnoDB
  search indexes, and ft_min_word_len and ft_max_word_len for MyISAM
  ones. After changing any of these options, rebuild your FULLTEXT
  indexes for the change to take effect. For example, to make
  two-character words searchable, you could put the following lines in
  an option file

(Okay, that reference doesn't specify that the default is "4", but it is.)
Follow the instructions:  change the default and rebuild the index.


text:
Q: Mysql function error - unable to figure it out Please help me with Mysql Function. Code:
DELIMITER $$

CREATE FUNCTION `media`.`Return_Next_Season`(
        season VARCHAR(200) )
    RETURNS VARCHAR
    DECLARE _ids INT ;
    DECLARE _bsk VARCHAR(200);

SELECT id INTO _ids  FROM media._broadcast_seasons WHERE broadcast_season_key = '20132014_Fall';

SELECT broadcast_season_key INTO bsk FROM media._broadcast_seasons WHERE id  = ids;

    RETURN bsk;
    BEGIN

    END$$

DELIMITER ;

A: Do you think it's a good idea having that BEGIN after all the code that does something useful? :-) Or, in less obtuse language, move the BEGIN to just after the RETURNS VARCHAR, something like (select statements broken up for readability but you may have to recombine them):
DELIMITER $$
CREATE FUNCTION `media`.`Return_Next_Season`(
    season VARCHAR(200) )
    RETURNS VARCHAR(200)
    BEGIN
        DECLARE _ids INT ;
        DECLARE _bsk VARCHAR(200);
        SELECT id INTO _ids  FROM media._broadcast_seasons
            WHERE broadcast_season_key = '20132014_Fall';
        SELECT broadcast_season_key INTO bsk FROM media._broadcast_seasons
            WHERE id  = ids;
        RETURN bsk;
    END$$
DELIMITER ;

You'll notice I've also changed the return type to give it a size since I believe that's necessary as well.


text: Q: image segmentation using spatial(location) feature I am using Mean Shift Clustering algorithm for the image segmentation. I have to define a feature vector. How can I define a feature that containes location(spatial) information of each pixel in the image. I defined color and depth features already but I have no idea for the location feature. Any idea or suggestions?


text:
Q: Login users from multiple Azure AD's in Spring Security I've got a Java Spring Security project that's linked to an Azure AD via a registered Application. This way I can redirect users to Microsoft to login with their Azure account before being able to view certain pages or use certain endpoints. This is all working great.
The problem is, I have another AD (and possibly more in the future) that I also want to be able to have users log into. However as far as I can see Spring Security only allows for 1 AD to be configured, so when a user wants to log in they always have to be a part of the currently linked AD.
I've tried looking into different solutions for this, for example syncing all the users from the external AD into the active AD. For this I was able to retrieve a list of users, but when I wanted to add them to the AD, the only API endpoints I could find were to create new accounts instead of link them from an external AD. Another idea was to configure Spring Security to simply authenticate against more than 1 AD. But as far as I've seen, that's not possible.
In the end I just want to have a situation where users from both AD's can log into my application, using their existing credentials without me having to manually invite each and every one. What is the best practice when dealing with a situation like this? I'd very much appreciate some help pointing me in the right direction. Thanks in advance!


text:
Q: ASP Classic: Unmask Credit Card number I have code that mask the encrypted cardnumber like this:
dim cardNum = MaskCardNumber(rs("CCNum"))

output:
xxxxxxxxxxxx1111
Now, i want this one to unmask which is in encrypted form already. Something like this.
output:
4444qwfgrghghghhgh1111
How would I unmask the value of "cardNum"?
any ideas? thanks!

A: I am using query.maskedinput.js Version: 1.4.1 I referred https://github.com/digitalBush/jquery.maskedinput/blob/bb66bf9b1c3eddd1d2349cee103127ae08d0a877/demo/index.html
the unmasking is done by $("input").blur(function() { $("#info").html("Unmasked value: " + $(this).mask());
example Masking is
$("#pannumber").mask("aaaaa 9999 a");
Unmasking
$("#pannumber").blur(function() {
var pannumber= $(this).mask() ;


text:
Q: wxPython flat GenButton border I am designing a GUI using wxPython with flat buttons.
How can I make a thin border around the button, like button2 in the picture:
http://i.stack.imgur.com/sYo0D.png
The button that I have now looks like this:
http://i.stack.imgur.com/hz3r8.png
The code:
    import wx.lib.buttons as buttons
    [...]
    self.a = buttons.GenButton(self, 00, "0", (140, 380), size=(100, 100),style=wx.BORDER_NONE)
    self.a.SetBackgroundColour((215, 215, 215))

Thanks for help.

A: With GenButton this should work:
buttons.GenButton(pane, wx.ID_ANY, "1", wx.DefaultPosition, size=(100, 100),
                  style=wx.BORDER_SIMPLE)

or:
buttons.ThemedGenButton(pane, wx.ID_ANY, 'Themed - Drawn with native renderer')


text:
Q: When would python actually create a new variable instead of a reference? So I have been using python for quite a while without knowing some of the nuances. Recently I discovered that when assigning an old variable to a new variable, what being assigned is just a reference to the old variable instead of the actual value of it. So I did a little test:
def change_number(b):
    a=b
    a+=1
    return a, b

b=1

print(change_number(b))

def change_list(b):
    a=b
    a.append("x")

    return a,b

b=["a","b"]

print(change_list(b))

The results are:
(2, 1)
(['a', 'b', 'x'], ['a', 'b', 'x'])

It seems that when dealing with numbers, python are treating the variables separately. Whereas when dealing with lists, a single instance beneath the two references is updated regardless of which one the operation is called upon.
I am thinking that this difference might be related to the types of objects python is dealing with, but it seems that it may also have something to do with the operation being done. I have read several related answers with respect to specific problems, but I would really like to know the general rule of python dealing with new variable assignments related to existing ones under difference circumstances. Cheers

A: = always creates a new reference, and never creates a new object.
What you're seeing is the difference between += and .append().  Integers in Python are immutable, so when you try to change it you have no choice but to reference a different object - the 1 will always be 1.  On the other hand lists are mutable, so .append() can change the single list object and add something new to the end of it.


text:
Q: Gitlab api - Is there any api to edit release notes on an existing tag? I want to update release notes for an existing tag in gitlab, i am able to do it from UI(by clicking "edit release notes" against a tag) but not able to find any API in tags api documentation:
https://docs.gitlab.com/ee/api/tags.html
What is the api call for this ?

A: A tag with release-notes will create a gitlab release. To manipulate those, use the releases api endpoint as specified here: https://docs.gitlab.com/ee/api/releases/


text:
Q: getting nil:NilClass when scoping dates in Rails I'm a bit dumfounded - getting an 'undefined method `each' for nil:NilClass' error.
I've created a pretty straight-forward scope in the model
  def self.just_added
      where('created_at > ?', Time.now-7.days.ago).order("created_at desc").first(4)
  end

And a loop in my view
<% @just_added_jobs.each do |job| %>
    <%= link_to job.name, job %>
<% end %>

Not sure what's going on - I'm fairly certian I've created a scope like before that worked fine.
Also - I also plan to do some more complex scoping with dates - I have several date fields as part of a model (i.e., to loop through the jobs that are due soon, past due). Where could I read more about scoping dates?

A: *

*The result of the classmethod you show can never be nil so we must conclude you're failing to set @just_added_jobs in the controller.

*created_at > Time.now-7.days.ago makes no sense, you probably mean created_at > 7.days.ago

*Calling first(n) on a scope is a bad idea because the result is not a scope anymore but an array. You need limit(n).


text:
Q: Try[Boolean] with boolean in scala case class Employee(name :String, dept :String, empId:String, startDate:String)
val emp1 = Employee("abc","accounts", "1234","2019-09-28")
val emp2 = Employee("def","HR", "12345","2019-09-29")
val emp3 = Employee("pp","HR", "12346", "2019-09-28")
val emp4 = Employee("xyz","accounts", "12347","2019-09-20")

val list = Seq(emp1, emp2, emp3, emp4)

def isValidDate(date: LocalDateTime, e:
Employee):Boolean={
 date.isAfter(LocalDate.parse(e.startDate).atStartOfDay())
}

def isValidName(name: String, e: Employee):Boolean = e.name == name
private def test(name :String, date:String,list:Seq[Employee])={

  list.exists(e =>isValidName(name, e)&&isValidDate(LocalDate.parse(date).atStartOfDay(), e))
}

test("abc","2019-09-28", list)
test("xyz","2019-09-28", list)
test("def","2019-09-28", list)

Changing to below code gives error Boolean && Try[Boolean] do not work together instead removing isValidName makes it work
def isValidName(name: String, e: Employee):Boolean = e.name == name
private def test(name :String, date:String,list:Seq[Employee])={

list.exists{e =>isValidName(name, e)&&isValidDate(LocalDate.parse(date).atStartOfDay(), e) match{
  case Success(x)=> x
  case Failure(ex) => throw ex
}}
}

A: Could you wrap it with Try as below..
def validateDate(e:Employee) = Try {
  isValidDate(LocalDate.parse(date).atStartOfDay(), e)
} match {
  case Success(x) => x

  case Failure(ex) =>
    //handle failure the way you want
    throw ex
}

list.exists(e => isValidName(name, e) && validateDate(e))

Or you can do..
list.exists(e => isValidName(name, e) && Try(isValidDate(LocalDate.parse(date).atStartOfDay(), e)).getOrElse(false))


text:
Q: custom php.ini for domain I have global php.ini file located in /usr/local/lib folder. The custom php.ini file is in /home/petstail/public_html/ folder.
This is how my phpinfo() look like.

I am still loading global php.ini file.
How to change configuration file path, and run custom php.ini file.
Thanks.

A: You might be able to do it via .htaccess by setting an environment variable (if Apache is running mod_php):
SetEnv PHPRC /home/petstail/public_html/php.ini
However, your php.ini file should not be in the document root (where it's publicly accessible) ... at the very least store it in a directory protected with another .htaccess defining Deny from all.
OR you could deny access to php.ini using the following.
<FilesMatch "php.ini">
    deny from all
    allow from 127.0.0.1
<FilesMatch>

A: Depending on your php version you should refer the the php documentation to see if INI settings are on.
See here:
http://www.php.net/manual/en/configuration.file.per-user.php


text:
Q: Uninstalling a package that was remotely pushed to a user I've remotely pushed a package to a user and in the middle of the installation the user decided to restart their computer. This caused a kernel panic. So now I'm trying to restore the system by removing the package, however, when I run pkgutil --pkgs I can't find the package on the system. Is there an easier way to find the packages?

A: I wasn't able to get the package names and remove them that way, but I was able to reinstall macOS and keep a backup of the user data


text:
Q: How to run chef-client in daemon mode and log it to a file as it logs when run from a tty? I know how to run the chef-client in daemon mode and log it to a file.
chef-client -d -i 60 -l info -L /var/log/chef/client.log

The problem now is that it does not output the same log format as it does when it is run from a terminal. Is there a way to run chef-client in daemon mode and also obtain the same log format as it returns when run from a terminal? How to enable live_stream and capture the output in the chef-client events?

A: Use --force-formatter from the documentation.
FWIW check the doc of client.rb, most options are configurable there also.
And there's the chef-client cookbook to manage the configuration and how the client behave.


text:
Q: enforcing common initilisation steps to an abstract method I'm currently refactoring a set of class that could be simplified as follows:
public abstract class A {
    public abstract Output doStuff(Input in);
}

public class B extends A {
    public Output doStuff(Input in) {
        // dostuff and return an output
    }
}

Now, I'd like to add a field in A whose value is derived from Input in, preferably without changing anything in the subclasses (there are around 20 classes like B)
Basically I'd like to find a way to call that init method (see bellow) at every call from doStuff(), without having to implement the method in class A, nor changing things in class extending A.
Do you know any elegant ways to do this ?
public abstract class A {
    private Object property;

    public abstract Output doStuff(Input in);

    private init(Input in){
      property=in.getProperty();
    }
}

public class B extends A {
    public Output doStuff(Input in) {
        // dostuff and return an output
    }
}

A: You can simply write a method in A which calls the init() method and the doStuff() method. That way the init() method gets called for every sub class automatically.
public abstract class A {
    private Object property;

    public Output doStuffWithInit(Input in) {
         this.init(in);
         return this.doStuff(in);
    }

    public abstract Output doStuff(Input in);

    private init(Input in){
      property=in.getProperty();
    }
}

The consuming classes has to be changed to call doStuffWithInit() instead to make sure that init() is called everytime.


text:
Q: object required error vba  Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim fil As File

    With Application.FileDialog(msoFileDialogFolderPicker) 'Choosing FromPath
        .Show
        FromPath = .SelectedItems(1) & "\"
    End With

    With Application.FileDialog(msoFileDialogFolderPicker) 'Choosing ToPath
        .Show
        ToPath = .SelectedItems(1) & "\"
    End With

   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objFolder = objFSO.GetFolder(FromPath)
   For Each objSubFolder In objFolder.SubFolders
        **Set fils = fsoC.GetFolder(objSubFolder & "\").Files**

        For Each fil In fils
            If LCase(Right(fil.Name, 3)) = "zip" Then
               MsgBox "this is a zip file "
            Else

I'm getting object required error  in the marked row , and I do not understand why ? Can anyone help me please ?

A: fsoC seems to be not declared / instanciated in your script. Maybe you would like to use objFSO again ?
Edit :
Sub test()
 Dim fils As Object
 Dim fil As Object
 Dim FromPath As String
 Dim ToPath As String
 Dim objFSO As Object
 Dim objFolder As Object
 Dim objSubFolder As Object

 With Application.FileDialog(msoFileDialogFolderPicker) 'Choosing FromPath
     .Show
     FromPath = .SelectedItems(1) & "\"
 End With

 With Application.FileDialog(msoFileDialogFolderPicker) 'Choosing ToPath
     .Show
     ToPath = .SelectedItems(1) & "\"
 End With

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(FromPath)
For Each objSubFolder In objFolder.SubFolders
   Set fils = objFSO.GetFolder(objSubFolder & "\").Files

   For Each fil In fils
      If LCase(Right(fil.Name, 3)) = "zip" Then
         MsgBox "this is a zip file "
      Else
         MsgBox "NOPE"
      End If
    Next
Next
End Sub

This code works with the following folder :
A
-- A.1
---- test.txt
---- test.zip


text:
Q: Why does Chrome devtools show these folders in orange and in italics? I'm looking at the "Sources" tab in Chrome developer tools.  Some of the folders are orange and in italics.  How are those different from the "regular" folders (shown in blue)?

A: Folder color

*

*Blue - Regular folder, not contains any source maps files

*Orange - Folder contains files having source maps attached (.less/.css or
.ts/.js)

Resource color

*

*Yellow - JS

*Violet - CSS & Fonts

*Green - Images

*Grey - HTML

A: Fonts seem to be in Green.  At least .woff2