Q: Initializing class object I am new to Java. I apologize if I ask a simple thing.
I wrote the below code but it seems that it doesn't initialize properly. because when I print the size of list1 it show the size = 0!! However, it should be 4!
public static class MyClass{
        public List <Integer> list1

        // Class Constructor
        public MyClass(int n){
            list1 = new ArrayList <Integer> (n);
            System.out.println("Size = " + list1.size() );
                    // prints Size = 0 !!!why???
        }

        public void init(int n){
            for(int cnt1 = 0; cnt1 < list1.size(); cnt1++){
            list1.set(cnt1 , cnt1);
            }
        }
        ...}

public static List<Integer> Func1(int n){
        MyClass = new myclass (n);
        myclass.init(n);
        ... }

public static void main(String args[]){
        int n = 4;
        result = Func1 (n);
        ...}

Why the size of the list1 is 0? It should be 4, because I pass 4 to Func1, and then it creates MyClass object with size n.
I would be thankful if someone can help me about this problem.

A: Array lists in Java have both a size and a capacity.

*

*Size tells you how many items are there in the list, while

*Capacity tells you how many items the list can hold before it needs to resize.

When you call ArrayList(int) constructor, you set the capacity, not the size, of the newly created array list. That is why you see zero printed out when you get the size.
Having a capacity of 4 means that you can add four integers to the list without triggering a resize, yet the list has zero elements until you start adding some data to it.

A: You have used the ArrayList constructor that determines its initial capacity, not its initial size.  The list has a capacity of 4, but nothing has been added yet, so its size is still 0.
Quoting from the linked Javadocs:

Constructs an empty list with the specified initial capacity.

Also, don't use set to add to the list.  That method replaces an element that is already there.  You must add to the list first (or use the other overloaded add method).


Q: Is this a proper way of using AJAX with jQuery and PHP? I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
    <option value="1">Yellow</option>
    <option value="2" selected="selected">Red</option>
    <option value="3">Blue</option>
</select>

So here is what I do:
$(document).on('change', 'select.update-db', function() {

// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();

    // Perform the request
    $.ajax({
        method: 'POST',
        url: 'update-db.php',
        data: { id: id, 'original-value': originalValue, 'new-value': newValue }
    });

  // Then, if everything is okay, change the "original value" of the select element
  // so that we can perform the updating operation again without having to refresh the page
  .done(function() {
      select.attr('data-original-value', newValue);
  });

});

Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?


Q: Convert array of objects into number for inject sum I am using Ruby 1.9.2, Rails 3.1. I have the following:
# review.rb
def calculate_rating
  all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id)
  all_rating.inject(:+)
end

# reviews_controller.rb
def create
  @reviewable = find_reviewable
  @review = @reviewable.reviews.where("user_id = ?", current_user).first
  if @review.save
    @review.calculate_rating
    redirect_to :id => nil
  else
    flash[:error] = 'Error saving review. Please try again.'
    redirect_to :id => nil
  end
end

The idea behind this is that when a new review with rating is submitted and saved, it will find all ratings for all @reviewable, sum all the ratings and divide by the total number of ratings.
Problem that I am facing currently is this line: all_rating = Review.select("rating").where("reviewable_id = ?", self.reviewable_id) where all_rating returns an array of objects, like below:
[#<Review rating: #<BigDecimal:1050f0a40,'0.3E1',9(18)>>, #<Review rating: #<BigDecimal:1050f0928,'0.1E1',9(18)>>]

which I can't do any arithmetic calculation to it. I need it to be an array of numbers before I could use the inject to sum it and divide by the number of ratings.
Please advise me how I can get the inject to work. Many thanks!

A: AR/SQL (faster):
Review.select("rating").where(:reviewable_id => self.reviewable_id).sum(:rating)

Ruby (slower):
Review.select("rating").where(:reviewable_id => self.reviewable_id).map(&:rating).sum

A: How about just doing this:
def calculate_rating
  all_rating = Review.select(:rating).where(:reviewable_id => reviewable_id).map(&:rating)
  all_rating.inject(:+) # or you could just do all_rating.sum
end


Q: How can I select specific parts of an image in android? If you have used photoshop, they have a tool that allows you to select parts of an image in order to edit specific locations within an image. Such as having a picture of a basketball and selecting that basketball with the use of the lasso tool in photoshop so you can make the rest of the image black and white.
I was wondering if there is any pre-defined class in the Android resource library that can make this sort of selection. Or would i have to make my own class that would look for a pattern in an image? Basically is there a tool available in android that can make these image selections that I can use inside my app?
It would also be helpful if someone can point me towards a reading on the subject of image selection programming or a third party library. I can't seem to find anything specific.


Q: What is good naming form for variables in loops JS? Hi so as I mentioned in the title I have a bunch of loops within loops in my code and most of them use a variable to loop through stuff. I call my variables ia, then ib then ic and so on. What is good form for the naming of these variables?
Here is some code that might help make sense of what I am saying

for (var ic = 0; ic <= currState.length; ic++) { //loop the columns and check if there is a
  if (currState[ic] == 0) {
    for (var id = 1; id <= currState.length; id++) { //loop the rows of a column

      tryPos = [id, ic + 1]; //id -> row | ic -> column

      if (checkClash(currState, tryPos) == false) {

        currState[ic] = id
        break;
      }
    }
  }
}

A: The name of your variables requires good descriptive skills and a shared cultural background.
In this case you should use row and col but don't forget the scope of your variables.
I would like recommend you read the Book: Clean Code.
Especially you can review some of the proposed rules on this post (http://www.itiseezee.com/?p=83).

A: looping over a table or grid, row and column are perfectly fine variable names.
for more generic nested loops i, j, and k (in that order) are typical counter variables even though they are less aptly named


Q: C++ code execution time depends on code structre I came across this great youtube tutorial and in one of the slides I saw something I didn't understand. Why is this happening? Is this compiler related?
Version #1 looks like this:
const int N = 5000;
float a [N*N];

for (int x=0; x<n; ++x)
     for(int y=0; y<N; ++y)
          sum+=a[x+y*N];

and takes about 239.4ms to execute.
And version #2 looks like this:
const int N = 5000;
float a [N*N];

for (int y=0; y<n; ++y)
     for(int x=0; x<N; ++x)
          sum+=a[x+y*N];

and takes about 79.5ms to execute.
Why is this happening?

A: The second example demonstrates better data locality since it accesses elements in the same row. Basically it performs sequential memory read, while first example jumps over sizeof(float) * N bytes on each iteration putting extra stress on CPU cache / memory.


Q: Using where clause for R Variable in R script to use it in SQL statement I have two tables; viz
table1 = PID (primary key) + 20 other columns & 200 records from database1 AND
table2 = [Serial no] (primary key) + 10 other columns  & 300 records from database2.
I am trying to extract values from table2 where PID = [Serial no].
Note: PID = [SCK34ICV7, NSCK876DL, ......].
I refered "Pass string Variable in R script to use it in SQL statement"
t1 <- sqlquery(db1, "select * from table1")
r1 <- t1$PID
class(r1) = 'factor'
t2 <- sqlquery(db2, "select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

I also tried other functions viz paste0(), fn$ from gsubfn and sprintf() and getting error like - 'c is not a recognized built in function name' ; 'Incorrect syntax'.
Please suggest the best way to do it.
Reg,
Mrutyunjaya

A: Your query is off. See here for what the proper format should be.
r1 <- c("PID1","PID2","PID3")

wrong
paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")

output:
[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "

correct
paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")

Output:
[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "

So the query becomes:
t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))

Hope this helps.


Q: PGM image not opening I have a pgm file which is well formatted like this
P2
# CREATOR: GIMP PNM Filter Version 1.1
19 19
0 71 73 74 73 73 74 73 71 70 71 74 72 69 68 71 72 66 69
70 70 74 70 69 69 69 69 71 68 70 72 66 70 71 69 65 68 69
66 72 73 74 74 73 70 73 72 66 70 68 67 68 68 68 67 66 69
66 72 78 74 74 73 71 71 70 70 68 70 66 69 66 65 66 62 62
62 72 76 72 73 75 72 71 68 74 71 68 66 70 65 67 62 56 57
66 70 72 71 72 69 72 73 74 69 65 66 60 64 68 93 99 139 225
240 68 71 70 70 69 70 71 64 64 46 60 57 86 153 206 233 240 244
245 72 69 70 68 67 68 68 68 61 58 82 178 229 236 236 229 238 244
245 74 67 67 70 68 66 69 65 64 97 218 240 242 235 234 240 243 244
244 75 74 73 72 69 68 73 74 128 223 239 242 239 242 243 242 244 241
244 72 76 74 72 69 71 68 83 155 234 242 240 237 242 237 241 240 245
243 72 75 75 71 68 69 65 68 127 237 241 240 241 243 245 244 244 245
244 72 71 69 71 66 66 63 63 107 239 240 244 245 245 246 245 246 246
246 72 70 70 67 64 63 60 74 218 242 245 245 245 245 246 246 247 246
245 73 72 71 70 70 66 61 201 241 244 245 246 245 246 247 246 247 246
247 71 69 71 68 63 61 115 236 239 244 244 245 245 246 246 246 246 246
245 78 72 73 73 68 63 167 243 244 244 245 245 245 246 246 246 246 246
245 75 72 69 71 67 61 218 245 245 246 246 246 246 246 246 246 247 246
246 76 72 72 68 65 74 238 246 246 246 247 246 246 246 246 246 246 246

But trying to open it with "visionneur d'images" on ubuntu i get an error :

Please help me.. I don't know what is the issue.

A: The number after image dimensions is supposed to be the maximum value in the image. You have it as '0'. Scanning quickly through the data, the value should be 247. Just replace the 0 with 247, using a text editor.


Q: Is there a destructor for a pointer in c++? string * str=new string;
delete str;

when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?
What would the pointer's destructor do?

A: The concept of destructor is applicable only to objects (i.e. entities defined with class or struct), not to plain types, like a pointer is. A pointer lives just like a int variable does.

A: The pointer it self doesn't been destructed by the delete statement. but as any scope variable it's been destroyed when the scope ends.
Example:
void Function()
{
    string * str=new string;
    delete str; // <-- here the string is destructed
} // <-- here the pointer is "destructed", which is mean it's memory freed from the stuck but no actual destruction function is called..

A: delete just causes the object that the given pointer is pointing at to be destroyed (in this case, the string object. The pointer itself, denoted by str, has automatic storage duration and will be destroyed when it goes out of scope like any other local variable.
Note, however, that non-class types do not have destructors. So even when you use delete with non-class types, no destructor is called, but when the pointer goes out of scope, it gets destroyed as normally happens with any other automatic variable (means the pointer just reaches the end of its lifetime, though the memory pointed to by the pointer is not deallocated until you  use delete to explicitly deallocate it.).

A:
when I delete 'str' which points to an object, do two destructors get called - one for the pointer itself, and one for the object it points to?

No. delete takes a pointer argument. It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to. You must previously have used new to allocate the memory and create the object there.
The pointer itself is not affected; but it no longer points to a valid object, so you mustn't do anything with it. This is sometimes known as a "dangling pointer".

What would the pointer's destructor do?

Nothing. Only class types have destructors.

A: The destructor for a raw pointer, like your example of std::string*, is trivial (just like the destructors for other primitive types: int, double, etc.)
Smart pointer classes have non-trivial destructors that do things like free resources, adjust reference counts, etc.

A: I like the simplification you get from the notion that every type has a destructor. That way you don't have a mental glitch with a template that explicitly destroys a stored value, even if the type of that stored value is an int or a pointer:
template <class T> struct wrapper {
    unsigned char data[sizeof(T)];
    wrapper(T t) { ptr = new (data) T; }
    ~wrapper() { (T*)&data->~T(); } // ignore possible alignment problem

wrapper<int> i(3);

However, the destructors for ints and pointers are utterly trivial: they don't do anything, and there is no place you can go to see the definition of the destructor, because the definition doesn't exist. So it's also reasonable to say that they don't have destructors.
Either way, when a pointer goes out of scope it simply disappears; no special code runs.


Q: Prevent table cells from breaking across page when converting html to pdf Using Google Apps Script, I have an html template that I fill and then send out (via fax and/or email) as a pdf.  The template includes a two-column table with questions/answers.
If there are enough rows, the table breaks across pages in the pdf, and the page breaks usually happen in the middle of cells; I'd like to avoid this.
I've tried using break-inside: avoid; in both the
 and  elements, with no effect.
Here's the template:

      Question
      Response

  <? rows.forEach(function(row){ ?>

       <?= row.question ?>
       <?!= row.answer ?>

  <? }) ?>

and here's the Apps Script code that converts it to pdf:
var html = '
' + subject + '
'
var tableTemplate = HtmlService.createTemplateFromFile('response-table-template')
tableTemplate.rows = rows;
html += tableTemplate.evaluate().getContent();

var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);

and then the blob is attached to an email/fax.  All of that works fine except for my question: Is there a way to avoid breaking table rows over the pages?  Possibly another way to convert the html to pdf that respects the break-inside property?  Or an html/css solution that will be respected by Apps Script when converting the html blob to pdf?

A: Unfortunately, in the current stage, it seems that break-inside is not reflected to Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF). But I'm not sure whether this is the current specification. So as a workaround, in your case, how about the following flow?

*

*Prepare HTML data.

*

*This has already been prepared in your script.

*Convert HTML data to Google Document.

*

*In this case, Drive API is used.

*Convert Google Document to PDF data.

*Create blob as a file.

When your script is modified, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
From:
var blob = Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF);

To:
// 1. Prepare HTML data.
var blob = Utilities.newBlob(html, MimeType.HTML, subject);

// 2. Convert HTML data to Google Doc
var id = Drive.Files.insert({title: subject, mimeType: MimeType.GOOGLE_DOCS}, blob).id;

// 3. Convert Google Document to PDF data.
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=" + id;
var pdf = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}}).getBlob().setName(subject);
DriveApp.getFileById(id).setTrashed(true);

// 4. Create blob as a file.
DriveApp.createFile(pdf);

Reference:

*

*Files: insert

A: By experimentation I found that Utilities.newBlob(html, MimeType.HTML, subject).getAs(MimeType.PDF) will respect page-break-inside: avoid; (rather than break-inside: avoid;) but only if it's applied to an entire table.  So I had to treat each table row as a separate table.  This version of the html template solved the problem:

      Question
      Response

<? rows.forEach(function(row){ ?>

         <?= row.question ?>
         <?!= row.answer ?>

<? }) ?>

For the record, converting to a Google Doc and then to pdf did not solve the problem; it appears that Google Doc also allows table cells to break across pages.  However, writing the data to a Google Sheet and then downloading as pdf does prevent breaking cells across pages; Sheets seems to take care of this automatically, so that's an alternate solution.


Q: Random number generator for python based discord bot What I am trying to do is when someone enters the command !random (argument) I want the bot to generate a number between 1 and what they put as the argument. But whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me. My current code for this command is below.
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
    arg = random.randint(1, number)
    if number:
        await Bot.say(arg)
    else:
        await Bot.say('Please select a valid number')

A: I guess number is passed as a string, so:

*

*you need to cast it to an integer before passing it to randint

*probably need to cast it to a string again before "saying" it

What's more, you're not using the correct way to check for wrong integer values; if number will never be False because your randint call will only return integers greater than 0 (or raise an error).

A fixed version would be something like:
@Bot.command(pass_context=True)
async def random1and10(ctx, number):
    try:
        arg = random.randint(1, int(number))
    except ValueError:
        await Bot.say("Invalid number")
    else:
        await Bot.say(str(arg))

Your mileage may vary, I didn't run it. I'm not sure about the decorated function signature.

whenever I try to do this it gives me around 6 different errors that are very long and make no sense to me.

Maybe they can make sense to others :) I'm relatively new to this site, but I think including them in your post would have been better. Cheers !


Q: Example for customizing the ignored pattern list in Django's collectstatic Like other questions here, I want to ignore my .scss files when running collectstatic. But because I'm using Heroku, which runs a collectstatic automatically, I would rather customize collectstatic's ignore pattern list rather than change the management command.
Django 2.2 provides a way to do this, as documented below:

The default ignored pattern list, ['CVS', '.', '~'], can be
  customized in a more persistent way than providing the --ignore
  command option at each collectstatic invocation. Provide a custom
  AppConfig class, override the ignore_patterns attribute of this class
  and replace 'django.contrib.staticfiles' with that class path in your
  INSTALLED_APPS setting:

from django.contrib.staticfiles.apps import StaticFilesConfig

class MyStaticFilesConfig(StaticFilesConfig):
    ignore_patterns = [...]  # your custom ignore list

My problem is that, this being my first Django project, I don't quite know how to provide a custom AppConfig class (and diving into the AppConfig docs hasn't helped). I mean, should I add this class to a whole new app or use an existing one? Is this class going to be in a apps.py file? If so, what should be the best app to do so? So I'm asking if anyone could provide me with an example of the best practice.
For reference, right now my app structure is like this (with all templates, assets and apps grouped together in their own folders rather than within each app):
-- project_name
  -- assets
    -- app1
  -- templates
  -- project_name
    -- app1
    -- app2
    -- __init__.py
    -- settings.py
    -- urls.py
    -- wsgi.py

UPDATE:
As Nico suggested, I've created an app called static in project_name.project_name with only an init.py file and an apps.py. The apps.py is exactly like the doc example:
from django.contrib.staticfiles.apps import StaticFilesConfig

class StaticConfig(StaticFilesConfig):
    name = 'static'
    ignore_patterns = ['CVS', '.*', '*~', '*.scss']

However, I'm running into errors when replacing 'django.contrib.staticfiles' from INSTALLED_APPS.

*

*Replacing it for 'project_name.static' makes the terminal not understand the collectstatic management command.

*Adding 'project_name' after 'django.contrib.staticfiles' (i.e.
not removing the later) makes it ignore the overwrite and collect the
.scss files.

*Replacing for 'project_name.static.apps.StaticConfig' throws a
Cannot import 'static'. error

UPDATE 2:
After I rollbacked the app creation, I tried is again, but now, instead of using the startapp with the file path, I created the app on the project root, tested it, then moved it manually to my apps' folders, and tested it again. For some reason I don't quite understand, this time I replaced 'django.contrib.staticfiles' for 'project_name.static' and now it worked.

A: You can add it to some other app, or even create just a file called static in the root of project_name and refer to the class inside this file in your settings.INSTALLED_APPS directly, but the recommended way to provide AppConfigs is inside an apps.py file inside the application package.
If you have no app where this AppConfig could be placed, I think the best practice would be to create a package under project_name.project_name called static, with only an init.py file and an apps.py file.
In this file you can create your AppConfig in the way you described.
Your file structure will then look like this:
-- project_name
  -- assets
    -- app1
  -- templates
  -- project_name
    -- app1
    -- app2
    -- static
       -- __init__.py
       -- apps.py
    -- __init__.py
    -- settings.py
    -- urls.py
    -- wsgi.py


Q: Revoke drive access through Google Play Services Is there a way to revoke drive access granted through Google Play Services?
Referring to this article:
https://developer.android.com/google/auth/api-client.html
I granted access to g drive from my app like so:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();

My question is, is there a clean way to revoke g drive access
i.e. without needing to do credential.getToken() and making http call to https://accounts.google.com/o/oauth2/revoke?token=
I'm looking for something like Drive.DriveApi.revokeAccessAndDisconnect();
I know there is one for g plus, but i cant find one for g drive.
http://developer.android.com/reference/com/google/android/gms/plus/Account.html

A: Yes, there is an method for revoking of Google Drive scope.
GoogleSignInClient googleSignInClient = buildGoogleSignInClient();
googleSignInClient.revokeAccess().addOnCompleteListener(onCompleteListener);

where
private GoogleSignInClient buildGoogleSignInClient() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_FILE)
                    .build();
    return GoogleSignIn.getClient(this, signInOptions);
}

For more information, you can check this reference


Q: Django - deleting users with on_delete=models.CASCADE causes problems with signals.post_delete We are using Django 3.1 for our websites. We have a model, User, which is related to two SiteProfile models for two websites, and is also related to other models such as Friend and UserEmailAddress. All the relations are with on_delete=models.CASCADE. We also have models.signals.post_delete signals for models such as Friend, to update the number of friends a user has, which is saved in one of the SiteProfile models. But the problem is, when deleting a user, the signal is called and then the SiteProfile object is saved, and then I get an exception for django.db.utils.IntegrityError - violations of foreign keys. We used to have the same problem with the UserEmailAddress model (a user's email address), which I fixed with the following code:
def delete(self, *args, **kwargs):
    if ((self.is_staff) or (self.is_superuser)):
        warnings.warn('Can’t delete staff user.')
        return False
    else:
        with transaction.atomic():
            for user_email_address in self.email_addresses.all():
                user_email_address.delete()
            return_value = super().delete(*args, **kwargs)
        return return_value

But I would like to know, is there a better way to delete a user with all its related objects which have on_delete=models.CASCADE, but without saving the counters in models.signals.post_delete to the database? Can I check something in models.signals.post_delete to know if the user is being deleted and then don't save the counters? Since I don't want to specifically delete any related object in the def delete method - there are at least 5 such models not including the two SiteProfile models.


Q: F# unit of measure to model area How can I use F# unit of measure to model the area of certain geometries.
The code i have so far is this but it isn't quite compiling.
[<Measure>] type radius
[<Measure>] type PI
[<Measure>] type area

let convertRadiusToArea (r:float<radius>) : float<area>  =
    // let pi = System.Math.PI
    let a:float<PI> = 3.14<PI>
    r * r * System.Math.PI

A: There are several things here:

*

*You need to define area as being a square length with type area = radius * radius. Otherwise the compiler has no way to match your input and output units.

*Pi, when used like this, is dimensionless, which is represented in F# as <1> or just no unit suffix.

[<Measure>] type radius
[<Measure>] type area = radius * radius

let convertRadiusToArea (r:float<radius>) : float<area>  =
    let pi = System.Math.PI
    r * r * pi

A: A better example of using F#'s unit of measure would be this:
[<Measure>] type cm

let convertRadiusToArea(r:float<cm>) : float<cm^2> =
    r * r * System.Math.PI

The idea being that you get benefits of the units of measurement in your calculations and derivations. You're not getting that by creating a unit of measure called 'radius'. Is it in meters? Feet? Centimetres? And that is why you would introduce them into an F# function, to be non-ambiguous about the unit of measurement for the inputs and outputs.
Units of measure in F# should IMO be modelled the way we use units of measurement in any other calculations or real world example like speed, temperature, force etc.


Q: NSG Configuration Management I am looking for a tool or some way to manage the Azure NSG configuration. NSG rules are changed manually on ad-hoc basis at the moment. I am looking to implement this NSG config change in more scripted fashion so that I can track the changes history as well.
I am looking at Git based repository of NSG where all ARM templates for NSG with different parameter files and run via those via Azure powershell or running as part of Azure Devops CI/CD pipeline.
I am not sure if Ansible can help with this management of NSGs or Terraform can help.
I love to think about Ansible for this. Anyone knows about this requirement how NSG can be managed.
Thank you

A: You can manage Azure NSG configuration via ARM template, Teffaform and Ansible.

*

*ARM template

1,You can check out below examples to create ARM Template to manage Azure NSG.
Create a Network Security Group.
How to create NSGs using a template
Please check the official document for more examples.
2, After the ARM template is created and pushed to your git repo. You can create azure pipeline to automate the deployment. See tutorial here.
3, Then you need to create an azure Resource Manager service connection to connect your Azure subscription to Azure devops. See this thread for an example.
4, In your azure devops pipeline. You can use ARM template deployment task to deploy the ARM template.
steps:
- task: AzureResourceManagerTemplateDeployment@3
  displayName: 'ARM Template deployment: Resource Group scope'
  inputs:
    azureResourceManagerConnection: 'azure Resource Manager service connection'
    subscriptionId: '...'
    resourceGroupName: '...'
    location: 'East US'
    csmFile: azuredeploy.json
    csmParametersFile: azuredeploy.parameters.json

*

*Teffaform

1, Create Teffaform configuration file. See example here.
Check out terraform-azurerm-network-security-group module for more information.
2, Upload Teffaform configuration file to git repo. Create Azure devops pipeline
3, Create azure Resource Manager service connection like above using ARM template.
4, Use Terraform task in the azure devops pipeline.
steps:
- task: ms-devlabs.custom-terraform-tasks.custom-terraform-installer-task.TerraformInstaller@0
  displayName: 'Install Terraform 0.12.3'

- task: ms-devlabs.custom-terraform-tasks.custom-terraform-release-task.TerraformTaskV1@0
  displayName: 'Terraform : azurerm'
  inputs:
    command: apply
    environmentServiceNameAzureRM: 'azure Resource Manager service connection'

*

*Ansible

1, Create Ansible playbook with plugin azure.azcollection.azure_rm_securitygroup
Please check out the example here.
2,Upload ansible playbook to git repo. Create Azure devops pipeline. Use Ansible task in your pipeline.
Please check out this detailed tutorial for more information about how to run ansible playbook in azure devops pipeline.

*

*Azure powershell/Azure CLI commands

You can using azure powershell or azure cli commands to manage azure nsg. And run the commands in Azure powershell task or azure cli task in azure devops pipeline.
Please check out this document for more information.


Q: Macosx yosemite installing mysql-python config error I am trying install mysql-python but always throw error. The command is "pip install mysql-python". I searched in google and tried everything but i am still getting error.
I am using mamp, MAMP's path is "/Applications/MAMP". I tested mysql with php and there is no error, mysql is working. I also connected to mysql by navicat. I am sure that mysql is installed and it is working.
I put the error screenshoot.

A: You need libmysqlclient.so library to be able to install MySQLdb,
Which come with MySQL Server and client and can also be downloaded with MySQL Connector/C.
Locate the library and set your DYLD_LIBRARY_PATH to have the path where libmysqlclient.so is present.


Q: How do i make a println list of random numbers with no duplicates? is there a way I can make the drawerList() method look at the output from the drawerNumber() and add them to an array. I want to store the outputs into an array list in order to find the duplicates and print out both the stored values and possibly make an if else statement that finds duplicates of the random numbers and mark those outputs as "already drawn" This is my first semester of CS and i am in the learning stages so i feel like what i'm trying to do is out of my knowledge and I'm not sure what to do.
import java.util.Scanner;

import java.util.Random;

class RandomNumbers{
    public static void main(String [] args){

 System.out.println(drawerNumbers());
}

//drawerNumbers()-draws new numbers

public static int drawerNumbers(){
    Random rand = new Random();
    int num = rand.nextInt(75)+1;
    return num;
}

//  drawerList()- List of numbers drawn
 public static int drawerList(){ //Method.
  String p = Integer.toString(drawerList()); //Convert method into string in order to be put in array
int[] numbers = new int[p.length()]; // creates the array to store the values

//

After this not sure how to make the outputs be listed to the console and how to make the program find the duplicate random numbers.

`

*

*Heading

` ##

A: It seems your intention is to randomly pick numbers between 1 and 75 without repeating a number. This is most easily done by inverting the problem to randomly ordering the numbers 1-75 then iterating through them:
List<Integer> nums = new ArrayList<Integer>(75);
for (int i = 1; i < 75; i++)
    nums.add(i);
Collections.shuffle(nums);

Now they are in random order, just use them one by one:
for (Integer i : nums) {
    // use i
}


Q: How does this endian conversion work? A QNX library called gfpr.h contains the line
#define ENDIAN_LE16(__x)    (__x)

which is used as follows
var1 = ENDIAN_LE16(var1);

to convert the endianness of (unsigned short) var1.  How does this work?  __x and x__ must have some special meaning to the preprocessor?

A: __x does not have a special meaning.  ENDIAN_LE16 is a macro that makes a place to change endianness without changing your source code.  Each build target can have a different version of gfpr.h specific for that target.
You must be compiling for a little-endian machine, so ENDIAN_LE16 doesn't need to make any changes.  It just leaves its argument (__x) unchanged.  If you were compiling for a big-endian target, ENDIAN_LE16 would be defined to swap the bytes of its argument.  Something like:
#define ENDIAN_LE16(__x) ( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) )

That way, by changing which target's gfpr.h file you include, you get the right results without having to change your source code.
Edit Per the file you're probably looking at, ENDIAN_BE32 invokes ENDIAN_RET32, which twiddles bits in a way similar to what I showed above.


Q: Live Reload of SCSS in React JS using Webpack I would like to ask if there's a way that the compiling of .scss file to .css is included in webpack hot reload, I use to always run npm run build to convert my .scss to .css
Here's my webpack.config:
var autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: './app/main.js',
    output: {
        path: './',
        filename: 'index.js'
    },
    devServer: {
        inline: true,
        port: 3333
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: '/node_modules/',
                loader: 'babel',
                query: {
                    presets: ['es2015','react']
                }
            },
            {
                 test: /\.scss$/,
                 loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('[name].css',{
            allChunks: false
        })
    ],
    postcss: [
        autoprefixer({
          browsers: ['last 2 versions']
        })
    ]
}


Q: Can the argument for Switch statement have an expression to eliminate a variable used for comparison? This program simulates a simple menu driven calculator with +, -, *, and / operations
#include <stdio.h>
#include <conio.h>
int main()
{
    float a = 0, b = 0;
    printf(" Enter two numbers: ");
    scanf(" %f %f",&a ,&b);

    puts(" Enter choice number of operation: ");
    puts(" 1)Addition ");
    puts(" 2)Subtraction ");
    puts(" 3)Multiplication ");
    puts(" 4)Division ");

    flushall();    //To clear the trailing '\n'
    switch( getchar() - 48 )
    {
        case 1: printf("The Sum of %.2f and %.2f is : %.2f",a,b,(a+b));
            break;
        case 2: printf("The Difference of %.2f and %.2f is : %.2f",a,b,(a-b));
            break;
        case 3: printf("The Product of %.2f and %.2f is : %.2f",a,b,(a*b));
            break;
        case 4: if ( b != 0 ) printf("The Quotient of %.2f and %.2f is : %.2f",a,b,(a/b));
            else puts("Error, divide by zero not possible.");
            break;
        default: puts("Error, Invalid choice");
    }
    return 0;
}

Is it better this way? As I have avoided the usage of a variable, and equivalently described why the program crashes when the last input is not a valid choice, I don't think there is any need to add info about what was entered. It adds an extra variable into the picture.

A: Yes, switch statement can take an expression for the value on which you switch. Your code should work fine, except that getchar() would read the leftover '\n' character from scanf of the operands.
Add another call to getchar() before the switch to read and discard that extra character.

A: While the code is valid and correct, I'd do the following to make it more readable:
switch(getchar()) {
    case '1': // ...
    case '2': // ...
    case '3': // ...
    case '4': // ...
}

Or
switch(getchar() - '0') {
    case 1: // ...
    case 2: // ...
}

This is to avoid using the magic number 48, which may not be understood easily by readers.
Furthermore, you can discard input until the next \n using a simple while loop:
while(getchar() != '\n') ;

In addition to the \n, this will also read and discard anything before the newline.

A: switch ( expression )

So you have a valid expression and you can have a expression like you have if you really have a need for something like this.
Else
char ch = getchar(); /* or scanf(" %c",&ch); (Better)*/
int a = ch - '0';

switch(a)
{
}

A: For your answer : Yes the switch can accept an expression in its arguments but it should returns only one of these types char int short long int long long int it can be also signed or unsigned !
There is no need to make a cast for the expression getchar() - 48  because getchar() returns int and 48 is an int so th result would be an int
now after compiling you have to add 3 number one for the variable a and the second for the variable b and the third for the switch statement... for instance
$./executable_file
Enter two numbers: 1 2 3

A: Switch formatting
This is a suggested formatting of your switch statement.  I disagree with the idea of using getchar() in the switch statement (though it is technically legal, it is simply a bad idea in practice), so I've replaced that with c:
int c;

/* c is set by some input operation.
** It might be char c; if you read its value with scanf(), but it must be int if you use getchar()
*/
switch (c)
{
    case 1:
        printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
        break;
    case 2:
        printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
        break;
    case 3:
        printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
        break;
    case 4:
        if (b != 0)
            printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
        else
            fputs("Error, divide by zero not possible.\n", stderr);
        break;
    default:
        fprintf(stderr, "Error, Invalid choice %c\n", c);
        break;
}

Note the use of break; after the default: label too; it protects you against future additions to the code and is completely uniform.  (The default: label does not have to be last, though that is the conventional place for it to go.)  Commas get a space after them; so do if, for, while, switch, but function calls do not get a space between the name and the open parenthesis.  You don't normally need a space after an open parenthesis or before a close parenthesis.  Errors are reported to standard error.
Personally, I like the actions of the switch to be indented just one level, not two levels, so I'd use:
switch (c)
{
case 1:
    printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
    break;
case 2:
    printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
    break;
case 3:
    printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
    break;
case 4:
    if (b != 0)
        printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
    else
        fputs("Error, divide by zero not possible.\n", stderr);
    break;
default:
    fprintf(stderr, "Error, Invalid choice %c\n", c);
    break;
}

Many people disagree, so you're certainly not under an obligation to do that.


Q: docker push doesn't use the correct repository and fails I'm trying to push a docker image to an Azure container repository and even after successfully "logging in" the push command tries to push it to docker.io and then fails.

Note: I am using Windows 10 Pro and have set up docker to to use the minikube docker dameon

How do I tell docker push to use my Azure container repo?
See the output:

A: You must tag your image with the Docker Registry URL and then push like this:
docker tag design-service dockerregistry.azurecr.io/design-service
docker push dockerregistry.azurecr.io/design-service

Note: The correct term is registry and not repository.  A Docker registry holds repositories of tagged images.


Q: Custom DetailView like function returns the same set of data - Django I have a view with a list of items and want to create a  detail view of those items so i can update, enable or disable items, the problem I have is I always get the same set of data no matter what item I click on to get the details of.
I've posted this here multiple times now but never had an answer, maybe I am failing to explain my issue.
View that handles the details
def detalle_Items(request, pk):
    model = Transaccion
    template_name = 'inventario/carrito/test-template.html'
    try:

        items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
    except Transaccion.DoesNotExist:
        raise Http404()

    return render(request, template_name, {'items_update':items_update})

This is where the function gets trigerred  by the green "actualizar" button

No matter what button I press this is what I get:

This is my views.py set of functions for carrito:
# =========================================================================== #
#   LOGICA PARA CREAR CARRITOS
# =========================================================================== #
# ===================> Logica relacinado con Cortadores <=====================#

def home_carrito(request):
    template_name = 'inventario/carrito/createcarrito.html'
    model  = Carritos

    carritos = Carritos.objects.all()
    if carritos:
        return render(request, template_name, {'carritos':carritos})
    else:
        return render(request,template_name)

class CarritoCreate(CreateView):
    model = Carritos
    fields = [
        'no_carrito',
        'empleado',
        'activo',
    ]

class ItemCreate(CreateView):
    model = Transaccion
    fields = [
        'carrito',
        'herramienta',
    ]

def detalle_carrito(request, pk):
    model = Carritos, Transaccion
    template_name = 'inventario/carrito/detalles_carrito.html'

    carritos = Carritos.objects.filter(pk=pk)
    # GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE ACTIVE
    # TRY TO GET ALL ACTIVE ITEMS THAT BELONG TO CARRITO = PK AND AGREGATE TOTAL ITEMS PER TYPE
    cantidades = Transaccion.objects.values('herramienta__description').annotate(Sum('cantidad')).filter(activo=True, carrito_id=pk)

    # GEST ALL TOOLS ASSIGN TO CARRITO'S PK THAT ARE NOT ACTIVE
    eliminados = Transaccion.objects.filter(activo=False,carrito_id=pk)

    return render(request,template_name, {'carrito':carritos, 'trans':cantidades, 'eliminados':eliminados})

class CarritoUpdate(UpdateView):
    model = Carritos
    fields = [
        'no_carrito',
        'empleado',
        'activo',
    ]
    template_name_suffix = '_update_form'

def detalle_Items(request, pk):
    model = Transaccion
    template_name = 'inventario/carrito/test-template.html'
    try:

        items_update = Transaccion.objects.filter(activo=True, carrito_id=pk, herramienta_id=pk)
    except Transaccion.DoesNotExist:
        raise Http404()

    return render(request, template_name, {'items_update':items_update})

class ItemUpdate(UpdateView):
    model = Transaccion
    fields = [
        'carrito',
        'herramienta',
        'cantidad',
        'tipo',
        'motivo',
        'activo',
    ]
    template_name_suffix = '_update_form'

class ItemDelete(DeleteView):
    model = Transaccion
    success_url = reverse_lazy('item-herramienta')

And these are my models.py for carritos:
# =========================================================================== #
#   MODELO PARA CREAR CARRITOS
# =========================================================================== #

class Carritos(models.Model):
    no_carrito = models.CharField(max_length=3, unique=True)
    empleado = models.OneToOneField(Empleados, on_delete=models.CASCADE)
    # empleado = models.ManyToManyField(Empleados,  through='Transaccion')
    items = models.ManyToManyField(Item, through='Transaccion', related_name='carritos')
    f_creacion = models.DateTimeField(auto_now_add=True)
    f_actualizacion = models.DateTimeField(auto_now=True)
    activo = models.BooleanField(default=True)

    def get_absolute_url(self):
        return reverse('inventario:carrito')#, kwargs={'pk': self.pk})

    class Meta:
        verbose_name_plural = "Carritos"

    def __str__(self):
        return self.no_carrito

class Transaccion(models.Model):

    carrito = models.ForeignKey(Carritos, on_delete=models.CASCADE, related_name='items_carrito')
    herramienta = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='items_carrito')
    cantidad = models.PositiveSmallIntegerField(default=1)
    activo = models.BooleanField(default=True)
    tipo = models.CharField(max_length=10, choices=CONSUMIBLE, blank=True, null=True)
    motivo = models.CharField(max_length=10, blank=True, null=True)

    def get_absolute_url(self):
        return reverse('inventario:carrito')#, kwargs={'pk': self.pk})

Template for image #1
{% extends "inventario/base.html" %}

    {% block lista %}

                {% if carrito %}
                    {% for c  in carrito %}

Carrito:

{{c.no_carrito}}

Asignado a:

{{c.empleado.nombre}} {{c.empleado.apellido}}

                                {% if eliminados %}

                                {% else %}

No hay elementos eliminados

                                {% endif %}

                            Ver reporte de daños

                                    Contenido de carrito
                                    cantidad
                                    actualizar

                                {% for i in trans %}

                                        {{i.herramienta__description}}
                                        {{i.cantidad__sum}}
                                        Actualizar

                                {% endfor %}

                            Agregar

                    {% endfor%}
                {% else %}

No hay articulos por vencer

                {%endif%}

    {% endblock lista%}

Template for image #2
{% extends "inventario/base.html" %}

    {% block lista %}

                    Contenido de carrito
                    cantidad
                    actualizar

                {% for i in items_update %}

                        {{i.herramienta}}
                        {{i.cantidad}}
                        Actualizar

                    {% endfor %}

    {% endblock lista%}


Q: multiple triggered subsystem + algebraic loop, initialisation problem I have a Simulink diagram which contains multiple triggered subsystem with different timestamp. In this model I also got a feedback loop inducing an algebraic loop. Therefore the signal must be initialised, in order to do that, I used a Memory block.
The problem is on the feedback loop, the value of the signal seems to be not initialised.
I believe the origin of this problem is that it is indeed initialised by the memory block for the first timestamp, however, the trigger on the next subsystem did not occur. By default, this subsytem puts its out signal value to be 0. The loop is therefore broken there.

Did someone already encounter this situation ? Any Tips ?
Thank you for your time.

A: You could add initialization blocks for your trigger values? I don't know about what SubSystem0 looks like inside, but its output could use an initialization block as well, this way you guarantee that you have an input to Subsystem


Q: Should Job/Step/Reader/Writer all be bean? As fars as all the examples from the Spring Batch reference doc , I see that those objects like job/step/reader/writer are all marked as @bean, like the following:
@Bean
public Job footballJob() {
    return this.jobBuilderFactory.get("footballJob")
                     .listener(sampleListener())
                     ...
                     .build();
}

@Bean
public Step sampleStep(PlatformTransactionManager transactionManager) {
    return this.stepBuilderFactory.get("sampleStep")
                .transactionManager(transactionManager)
                .<String, String>chunk(10)
                .reader(itemReader())
                .writer(itemWriter())
                .build();
}

I have a scenario that the server side will receive requests and run job concurrently(different job names or same job name with different jobparameters). The usage is to new a job object(including steps/reader/writers) in concurrent threads, so I propabaly will not state the job method as @bean and new a job each time.
And there is actually a differenence on how to transmit parameters to object like reader. If using @bean , parameters must be put in e.g. JobParameters to be late binding into object using @StepScope, like the following example:
@StepScope
@Bean
public FlatFileItemReader flatFileItemReader(@Value(
"#{jobParameters['input.file.name']}") String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}

If not using @bean , I can just transmit parameter directly with no need to put data into JobParameter,like the following
public FlatFileItemReader flatFileItemReader(String name) {
return new FlatFileItemReaderBuilder<Foo>()
.name("flatFileItemReader")
.resource(new FileSystemResource(name))
}

Simple test shows that no @bean works. But I want to confirm formally:
1、 Is using @bean at job/step/reader/writer mandatory or not ?
2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?
Thanks!

A:
1、 Is using @bean at job/step/reader/writer mandatory or not ?

No, it is not mandatory to declare batch artefacts as beans. But you would want to at least declare the Job as a bean to  benefit from Spring's dependency injection (like injecting the job repository reference into the job, etc) and be able to do something like:
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
Job job = context.getBean(Job.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
jobLauncher.run(job, new JobParameters());

2、 if it is not mandatory, when I new a object like reader, do I need to call afterPropertiesSet() manually?

I guess that by "when I new a object like reader" you mean create a new instance manually. In this case yes, if the object is not managed by Spring, you need to call that method yourself. If the object is declared as a bean, Spring will call
the afterPropertiesSet() method automatically. Here is a quick sample:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestAfterPropertiesSet {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(TestAfterPropertiesSet.class);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.sayHello();
    }

    static class MyBean implements InitializingBean {
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("MyBean.afterPropertiesSet");
        }

        public void sayHello() {
            System.out.println("Hello");
        }
    }

}

This prints:
MyBean.afterPropertiesSet
Hello


Q: Android ViewPager2 FragmentStateAdapter shows Menu from every Fragment i have an activity with bottom navigation view with 3 Fragments associated.
One of them is a Fragment with a ViewPager2 that uses a  FragmentStateAdapter.
Inside the createfragment(int position) method of the Adapter I return a couple Instances of another Fragment which has an Options Menu and inside it's onCreate() i call setHasOptionsMenu(true).
The Problem is that on initialization of the adapter, the menu from all fragments are visible not just the menu of the currently visible fragment.
After the first swipe it seems that the menu gets invalidated and everything is as it should be.
The problem also occurs if i notify the adapter about changes that another fragment is added, then another menu item appears for the newly added fragment.
I saw a similar question but the answer was to call setHasOptionsMenu() inside the onResume() method of the fragment but that doesn't seem to be the right behavior to handle this. In a comment another user suggested to upgrade ViewPager2 to another version but I am using the latest version.
Can anybody tell me how to handle this?

A: I joined StackOverflow just to reply to this question as I've also wasted time on this exact issue.
The fix is to update to the latest alpha01 version of ViewPager2.
implementation "androidx.viewpager2:viewpager2:1.1.0-alpha01"

See: https://developer.android.com/jetpack/androidx/releases/viewpager2#1.1.0-alpha01

Fixed FragmentStateAdapter issue with initial fragment menu visibility when adding a fragment to the FragmentManager. (I9d2ff, b/144442240)

A: I tried updating to the latest viewpager2 alpha as suggested in the currently accepted answer, but it didn't help.
I have seen answers to similar questions where they say to clear the entire menu first. That should work, too, but I have some menu items that are loaded in the Activity, which do not duplicate, and some that load in the fragment, which do duplicate. I want to keep the ones inflated in the Activity and remove only all the ones from all fragments (not just the current fragment, just in case).
My work-around, therefore, is to each time remove only the items added in all fragments, checking to make sure each is actually there (not null) before removing each one. Then, once those have been removed, I inflate the menu(s) needed for all/each fragment.
Note that the existing menu is removed item by item (R.id...) while the inflated one is added by menu (R.menu...) as usual.
In the below sample, the search menu will always be inflated, while the second menu to be inflated will depend on which fragment it currently active.
    @Override public void onCreateOptionsMenu (@NonNull Menu menu, @NonNull MenuInflater
        inflater)
{
    super.onCreateOptionsMenu (menu, inflater);

    removeMenuItemIfPresent (menu, R.id.menu_search);
    removeMenuItemIfPresent (menu, R.id.menu_sample_filter1);
    removeMenuItemIfPresent (menu, R.id.menu_sample_filter2);

    inflater.inflate (R.menu.menu_search_menu, menu);
    inflater.inflate (mCurrentSection == 0 ? R.menu.menu_frag0 : R.menu.menu_frag1, menu);
}

private void removeMenuItemIfPresent (@NonNull Menu menu, int resourceIDToRemove)
{
        MenuItem menuItemToRemove = menu.findItem (resourceIDToRemove);

        if (menuItemToRemove != null) {
            menu.removeItem (menuItemToRemove.getItemId ());
    }
}

A: I am not sure if it worked before but now im having issues with ViewPager2. When, I add fragments, each with different menuitems, the menuitem does not reflect on the first fragment added.
It works when offscreenpagelimit is not set. However, its performance is bad. Didnt have issues with ViewPager.


Q: Riverpod: How to read provider after async gap I am trying to build a simple login screen. For this I have set up a StateProvider to indicate whether to show a loading indicator:
final loginIsLoadingProvider = StateProvider<bool>((ref) => false);

When a button is pressed I call the following function:
void logInUser(WidgetRef ref) async {
    ref.read(loginIsLoadingProvider.notifier).state = true;
    await Future.delayed(1.seconds); //login logic etc.
    ref.read(loginIsLoadingProvider.notifier).state = false; //Exception
return;

But calling ref.read(...) after awaiting the future throws the following exception:

FlutterError (Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)

Why cant I call ref.read() after an async gap? Is there any way to do this?

A: A solution is to read your providers before the async gap, but not use them immediately.
For example:
Future<void> logInUser(WidgetRef ref) async {
  final isLoadingNotifier = ref.read(loginIsLoadingProvider.notifier);
  isLoadingNotifier.state = true;

  await someAsyncOperation();

  isLoadingNotifier.state = false;
}


Q: How to Calculate statistics PDR, Delay ,Broadcast Success rate For Protocol works in Phy Layer ,Link Layer using OMNET 5.0,VEINS 4.4? What are The Programming instructions that can be written in omnet.ini file or .ned file for calculating the statistics Packet Delivery Ratio, Delay ,Broadcast Success rate For Protocol works in Physical Layer ,Link Layer using OMNET 5.0 ,VEINS 4.4???
Please reply ...


Q: Printing a generator in python tensor flow I am trying to follow the tensor flow tutorial as described in this link
I am trying to print the predicted result as described :
print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))

But I am not able to print the result. I am getting the following error.
    print ("Predicted %d, Label: %d" % (classifier.predict(test_data[0]), test_labels[0]))
TypeError: %d format: a number is required, not generator

How do I print the generator in python.
I tried to write a loop and iterate over the elements it didn't work and I tried to use next to print the generator. That also didn't work. How do I print it ?

A: This is how I solved it
new_samples = np.array([test_data[8]], dtype=float)

y = list(classifier.predict(new_samples, as_iterable=True))
print('Predictions: {}'.format(str(y)))

print ("Predicted %s, Label: %d" % (str(y), test_labels[8]))

A: No tensorflow here, so let's mock up a generator and test it against your print expression
In [11]: def predict(a, b):
    ...:     for i in range(10):
    ...:         yield i, i*i
    ...:

In [12]: print('a:%d, b:%d'%(predict(0, 0)))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-29ec761936ef> in <module>()
----> 1 print('a:%d, b:%d'%(predict(0, 0)))

TypeError: %d format: a number is required, not generator

So far, so good: I have the same problem that you've experienced.
The problem is, of course, that what you get when you call a generator function are not values but a generator object...
You have to iterate on the generator objects, using whatever is returned from each iteration, e.g.,
In [13]: print('\n'.join('a:%d, b:%d'%(i,j) for i, j in predict(0,0)))
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81

or, if you don't like one-liners,
In [14]: for i, j in predict(0, 0):
    ...:     print('a:%d, b:%d'%(i,j))
    ...:
a:0, b:0
a:1, b:1
a:2, b:4
a:3, b:9
a:4, b:16
a:5, b:25
a:6, b:36
a:7, b:49
a:8, b:64
a:9, b:81

In other words, you have to explicitly consume what the generator is producing.

A: From the documentation:

Runs inference to determine the class probability predictions.
  (deprecated arguments)
SOME ARGUMENTS ARE DEPRECATED. They will be removed after 2016-09-15.
  Instructions for updating: The default behavior of predict() is
  changing. The default value for as_iterable will change to True, and
  then the flag will be removed altogether. The behavior of this flag is
  described below.

Try:
classifier.predict(x=test_data[0])


Q: task shedule, sharing form label variable I am writting some easy program in Java FX. I am begginer in Java.
I would like make,
You fill textbox (time in minutes) and run it.
And than it run timer.schedule that it will every minute refresh label with time. Something like stopwatch.
(You set time whitch you want remember time).
I have Controller
public class Controller implements Initializable  {

    @FXML
    public Label label;

    @FXML
   private TextField timeEnd;
    .
    .

And method onClick
@FXML
private void handleButtonAction(ActionEvent event) {
    Integer timeEndVal = Integer.parseInt(timeEnd.getText());
    Date startDate = new Date();
    Date endDate = new Date();
    endDate.setTime(startDate.getTime() + (timeEndVal * 60000));

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            long currentMinutes = currentTime().getTime() - startDate.getTime();

            System.out.println(currentMinutes / 60000 + " / " + timeEndVal + " min");
            label.setText(String.valueOf(currentMinutes / 60000 + " / " + timeEndVal + " min"));

        }
    }, 0, 60000);

But I don't know, how I get label variable to timer.schedule.
What I do wrong. Thank for helping.

A: Here is a non Controller version that you can use to get some ideas from. I suggest you use TimeLine instead of Timer. This is not a complete program!
import java.util.concurrent.atomic.AtomicInteger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication267 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        AtomicInteger timeInSeconds = new AtomicInteger();
        TextField textField = new TextField();
        Label label = new Label(Integer.toString(timeInSeconds.get()));
        Button btn = new Button("Play");

        textField.setPromptText("Enter the number of minutes");
        textField.textProperty().addListener((obs, oldValue, newValue) -> {
            //This assume the input is corret!
            timeInSeconds.set(Integer.parseInt(newValue) * 60);//Number of minutes times 60 seconds
            label.setText(getMinsSeconds(timeInSeconds.get()));
        });

        Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {
            if (timeInSeconds.get() > 0) {
                label.setText(getMinsSeconds(timeInSeconds.decrementAndGet()));
            }
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);

        btn.setOnAction((ActionEvent event) -> {
            switch (btn.getText()) {
                case "Play":
                    timeline.play();
                    btn.setText("Pause");
                    textField.setEditable(false);
                    break;
                case "Pause":
                    timeline.pause();
                    btn.setText("Play");
                    textField.setEditable(true);
                    break;
            }
        });

        VBox root = new VBox(label, btn, textField);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    String getMinsSeconds(int seconds)
    {
        return String.format("%02d:%02d", (seconds / 60), (seconds % 60));
    }
}


Q: Different themes for different languages in Visual Studio Code I've tried searching for the answer to this but am coming up blank.
In sublime text, it's possible to have different themes for different file types as specified in the preferences file. For example, you can have a light coloured theme for Markdown/Plain text files and a normal Monokai type theme for all other languages. I find this very useful as I prefer to have different fonts and settings when typing compared to when coding.
As far as I can see, this functionality isn't present in VSCode. Am I wrong or is there a way to achieve the above?

A: You are right, there is no way to do that.
You can however, define different themes (color and icon) for each workspace (Preferences: Open Workspace Settings). It's not exactly what you are looking for, but it may be useful if your different languages are located/related in different workspaces.

A: It's now possible to do using an extension called "Theme by language" from Julien Saulou. It can be downloaded from Visual Studio Code Marketplace.


Q: Spring Data Rest: Null Pointer If-Modified-Since Header Present and Resource Not Auditable If a Client makes a request for a Resource and specifies the If-Modified-Since header when the mapped Entity does not have any of the Spring Data JPA auditing annotations (@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate ) then this appears to result in a null-pointer exception in the class org.springframework.data.rest.webmvc.HttpHeadersPreparer:
public boolean isObjectStillValid(Object source, HttpHeaders headers) {

    Assert.notNull(source, "Source object must not be null!");
    Assert.notNull(headers, "HttpHeaders must not be null!");

    if (headers.getIfModifiedSince() == -1) {
        return false;
    }

    //THE WRAPPER IS NULL IF NO AUDITING ANNOTATIONS PRESENT
    AuditableBeanWrapper wrapper = auditableBeanWrapperFactory.getBeanWrapperFor(source);
    long current = wrapper.getLastModifiedDate().getTimeInMillis() / 1000 * 1000;

    return current <= headers.getIfModifiedSince();
}

Is this a bug and, short of adding a field to the Entity to prevent this, is there any other workround.

A: If fetching the entity doesn't emit a Last-Modified header, then I would say this is a bug in the client, not SDR.
If none of your entities support Last-Modified, maybe create a filter that strips If-Modified-Since from the request or catches it early and responds appropriately.
All of that said, I also don't think a NPE is acceptable and a SDR bug should be filed.


Q: hide the name of app in windows task manager
Possible Duplicate:
Hide a C# program from the task manager?

Hi.
I write WinForms app and i want to hide my app name in this place windows Task Manager>>Applications .how can hide when i run my app??
thanks.

A: The application name that Task Manager shows is the Window text of the taskbar window. If you want to hide it you'll just have to set that text to an empty string.
If a blank string is no good, and you don't want your app to appear in the list at all, then don't register a taskbar button.
If you don't want your app to appear in the process list, then don't start it.


Q: VB.Net Listview Groups I am new here and come up with my first question:
I have a listview with some groups, every groups has some items.
I added a ContextMenuStrip to the Listview, and when I rightclick on the selected item, I like to get the Name of the Group which it belongs to.
Can someone help me how to do this?
If LV1.SelectedItems(0).Text = LV1.Groups(0).ToString Then
    MsgBox("Hi")
End If

A: Get LV group name for the item the mouse is down over:
Private thisGroupName As String = ""

Private Sub MouseDown(sender, e As MouseEventArgs)...
    If e.Button = MouseButtons.Right Then
        thisGroupName = GetLVGroupAt(e.X, e.Y)
    End If
End Sub

Private Function GetLVGroupAt(X As Integer, Y as Integer) As String
    Dim theGrp As String = ""

    Dim ht As ListViewHitTestInfo = myLV.HitTest(X, Y)
    ' the mouse might be down over a NON item area, like a blank "row"
    ' AND if the items does not belong to a Group, 'Group' will
    ' be Nothing:
    If (ht.Item IsNot Nothing) AndAlso (ht.Item IsNot Nothing) Then
         theGrp = ht.Item.Group.Name
    End If

    Return theGrp
End Function

Evaluating the Group name is left for the consuming code.


Q: Where are SKNode positioned in the responder chain? SKNode inherits from NSResponder but I'm having trouble understanding how nodes are included in the responder chain and where they are inserted.
For example, how does a SKNode receive the mouseDown: message?
When a view is clicked, a hit testing process occurs to determine the deepest view at the hit location and then mouseDown: is sent up the responder chain from that point.
SKNodes are not views so they cannot get send this message directly (because it it handled by the SKView). So how are they included in the responder chain?


Q: Django: query filter I have two models that are related: one is a list of participants.  The other is a list of times they have checked in or out of an office.
The table (Checkin) has one record for every checkin/checkout pair.  So, there can be many records for any participant.
How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template?
From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record?
Thank you.
Models:
class Participant(models.Model):

    first_name = models.CharField(max_length=50)
    middle_initial = models.CharField(max_length=50, blank=True)

class CheckIn(models.Model):
    adult = models.ForeignKey(
        Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin')

    checkin = models.DateTimeField(blank=True, null=True)
    checkout = models.DateTimeField(blank=True, null=True)

View snipit:
    p_checkins = Participant.objects.all().order_by('created')

    queryset = p_checkins

    context_object_name = "the_list"

    template_name = 'list_of_checkins.html'

A: You can fetch data through most recent checkin or checkout.
For checkin :
p_checkins = CheckIn.objects.all().order_by('-checkin')[0]

For checkout :
p_checkins = CheckIn.objects.all().order_by('-checkout')[0]

To get the participant name by :
name = p_checkins.adult.first_name

A: When you use (-) your latest update will be query from database.
p_checkins = CheckIn.objects.all().order_by('-checkin')

or
p_checkins = CheckIn.objects.all().order_by('-checkout')

A: you can annotate the latest value via a subquery to the participant
from django.db.models import OuterRef, Subquery
checkin_q = CheckIn.objects.filter(adult=OuterRef('pk')).order_by('-checkin')
queryset = Participant.objects.annotate(last_checkin=Subquery(checkin_q.values('checkin')[:1]))

see https://docs.djangoproject.com/en/4.0/ref/models/expressions/#subquery-expressions

A: Most of the answers so far are correct in several aspects. One thing to note is that if your check_in or check_out values (whichever you use) isn't chronological (and by "most recent", you mean the last added), you'll want to add a created_at datetime field with auto_now option True, or order by the pk.
In addition to the other answers provided and my comment above, you can also get the most recent check in by using the related manager on the participant object.


Q: Is there a way to show an Android dialog without graying out the back drop? I want to pop open a DatePickerDialog in a certain screen, but I am required to not grey out the rest of the screen (the view behind the dialog) when the DatePickerDialog window opens. Is there a way to achieve this?

A: You probably would want to create your own custom dialog.  You can extend DialogFramgent and change it accordingly.
See the Android doc HERE for a great example.
Or, use PopupWindow if you want a popover dialog with control of the background, see this SO post.


Q: format JSON object into array like structure I am quite new to Python but trying to do some machine learning with it.
My problem is to format a received JSON object into an array like structure to submit this to my predictor function of the ML model.
JSON object looks like when I do a print of it
{u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}

what i need is
[0.62739, 0, 395.62, 8.47, 56.5, 307, 4, 0, 0.538, 19.9, 5.834, 8.14, 21, 4.4986]

Can anybody help here
thanks
Peter

A: try:
json_var = {u'CRIM': 0.62739, u'ZN': 0, u'B': 395.62, u'LSTAT': 8.47, u'AGE': 56.5, u'TAX': 307, u'RAD': 4, u'CHAS': 0, u'NOX': 0.538, u'MEDV': 19.9, u'RM': 5.834, u'INDUS': 8.14, u'PTRATIO': 21, u'DIS': 4.4986}
value_array = json_var.values()

A: What you are looking for is
d = {'a':1, 'b': 2, 'c': 3}
num_list = d.values()

# num_list = [1,2,3]


Q: SQL Query to match a subset of data I have a table that looks like:
CLASS   VALUE
1       A
1       B
1       C
2       A
2       C
3       B
3       D
4       A
5       C
5       A

I have a user-submitted data-set of values that I want to find any classes whose values are a subset of the user-submitted data-set.
For example,
If data-set was A, B, and C then the results would be class 1, 2, 4, and 5.
If data-set was A and C the results would be class 2, 4, and 5.
If data-set was A, then result would be class 4.
The platform I am on is SQL Server, but really any SQL-based answer would be best.

A: As per the comment It's passed as a table. - assuming the table is the variable @UserInput with a single column of Value, you can use a WHERE EXISTS clause to check for the existence of that value in the user-input fields, and pull the DISTINCT Class values.
Select  Distinct Class
From    YourTable   T
Where Exists
(
    Select  *
    From    @UserInput  U
    Where   T.Value = U.Value
)

Your SQL syntax will vary, but this should point you in the right direction, syntactically.
A full example of how to implement this would be as follows:
Creating the User-defined Table Type
Create Type dbo.UserInput As Table
(
    Value   Varchar (10)
)
Go

Creating the Stored Procedure
Create Proc dbo.spGetClassesByUserInput
(
    @UserInput dbo.UserInput ReadOnly
)
As Begin
    Select  Distinct Class
    From    YourTable   T
    Where Exists
    (
        Select  *
        From    @UserInput  U
        Where   T.Value = U.Value
    )
End
Go

Calling the Stored Procedure with user input
Declare @Input dbo.UserInput
Insert  @Input
Values  ('A'), ('B'), ('C')

Execute dbo.spGetClassesByUserInput @Input

A: You can create a stored procedure an pass the user entry as it as string for ex. A,B,C
Create Procedure dbo.GetClasses
@v_UserEntry Varchar(200)
As
Begin
    Declare @SQLQuery AS NVarchar(1000)
    Declare @ParamDefinition AS NVarchar(300)

    SET @v_UserEntry= REPLACE(@v_UserEntry,',',''',N''')
    Set @SQLQuery ='Select Class'
    Set @SQLQuery = @SQLQuery + ' From TableName'
    Set @SQLQuery = @SQLQuery + ' Where Value in (N'''+@v_UserEntry+''')'
    Set @SQLQuery = @SQLQuery + ' Group By Class'
    Execute sp_executesql @SQLQuery
End
Go


Q: Can python read this type of config file? good morning. I want you help. I'm making a  project using python but i want know if python2 can read this type of config file. Example:
[SETTINGS]
{
  "Name": "SKY",
  "SuggestedBots": 50,
  "MaxCPM": 3000,
  "LastModified": "2019-11-03T23:24:24.0854425-03:00",
  "AdditionalInfo": "",
  "Author": "KATO",
  "Version": "1.1.4",
  "IgnoreResponseErrors": false,
  "MaxRedirects": 8,
  "NeedsProxies": true,
  "OnlySocks": false,
  "OnlySsl": false,
  "MaxProxyUses": 0,
  "BanProxyAfterGoodStatus": false,
  "EncodeData": false,
  "AllowedWordlist1": "",
  "AllowedWordlist2": "",
  "DataRules": [],
  "CustomInputs": [],
  "ForceHeadless": false,
  "AlwaysOpen": false,
  "AlwaysQuit": false,
  "DisableNotifications": false,
  "CustomUserAgent": "",
  "RandomUA": false,
  "CustomCMDArgs": ""
}

I tryed with tutorials from internet but doesn't work. I think it's JSON.

A: If you drop the first line, then it can be used in python.
import json

test = '''{
  "Name": "SKY",
  "SuggestedBots": 50,
  "MaxCPM": 3000,
  "LastModified": "2019-11-03T23:24:24.0854425-03:00",
  "AdditionalInfo": "",
  "Author": "KATO",
  "Version": "1.1.4",
  "IgnoreResponseErrors": false,
  "MaxRedirects": 8,
  "NeedsProxies": true,
  "OnlySocks": false,
  "OnlySsl": false,
  "MaxProxyUses": 0,
  "BanProxyAfterGoodStatus": false,
  "EncodeData": false,
  "AllowedWordlist1": "",
  "AllowedWordlist2": "",
  "DataRules": [],
  "CustomInputs": [],
  "ForceHeadless": false,
  "AlwaysOpen": false,
  "AlwaysQuit": false,
  "DisableNotifications": false,
  "CustomUserAgent": "",
  "RandomUA": false,
  "CustomCMDArgs": ""
}'''

json.loads(test)

# {u'AlwaysQuit': False, u'Author': u'KATO', u'LastModified': u'2019-11-03T23:24:24.0854425-03:00', u'DataRules': [], u'AlwaysOpen': False, u'Version': u'1.1.4', u'DisableNotifications': False, u'NeedsProxies': True, u'CustomInputs': [], u'EncodeData': False, u'BanProxyAfterGoodStatus': False, u'SuggestedBots': 50, u'ForceHeadless': False, u'RandomUA': False, u'AdditionalInfo': u'', u'Name': u'SKY', u'CustomUserAgent': u'', u'MaxRedirects': 8, u'CustomCMDArgs': u'', u'OnlySocks': False, u'MaxProxyUses': 0, u'IgnoreResponseErrors': False, u'AllowedWordlist1': u'', u'AllowedWordlist2': u'', u'OnlySsl': False, u'MaxCPM': 3000}


Q: pymodm can't find an object, while pymongo successfully finds it I have a problem getting an object from the mongodb instance. If I search for this object with pymongo interface, everything is fine - object can be found. If try to do the very same thing with pymodm - it fails with error.
Here is what I'm doing:
from pymodm import connect, MongoModel, fields
from pymongo import MongoClient

class detection_object(MongoModel):
    legacy_id = fields.IntegerField()

client = MongoClient(MONGODB_URI)
db = client[MONGODB_DEFAULT_SCHEME]
collection = db['detection_object']
do = collection.find_one({'legacy_id': 1437424})
print(do)

connect(MONGODB_URI)
do = detection_object.objects.raw({'legacy_id': 1437424}).first()
print(do)

The first print outputs this: {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424}. However, during the execution of this command: do = detection_object.objects.raw({'legacy_id': 1437424}).first() interpreter fails with the following error:
    Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 127, in first
    return next(iter(self.limit(-1)))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/konsof01/PycharmProjects/testthisfuckingshit/settings.py", line 29, in <module>
    do = detection_object.objects.raw({'legacy_id': 1437424}).first()
  File "/usr/local/lib/python3.7/site-packages/pymodm/queryset.py", line 129, in first
    raise self._model.DoesNotExist()
__main__.DoesNotExist

How can this be? I'm trying to query the very same object, with the same connection and collection. Any ideas, please?

A: you could try it as follows:
detection_object.objects.raw({'legacy_id': "1437424"} ).first()

probably the legacy_id is stored as string.
Othewise, make sure the db name is present at the end of the MONGO_URI as it is underlined in the docs.

A: Each document in your 'detection_object' collection requires to have '_cls' attribute. The string value stored in this attribute should be
    __main__.classname

(class name according to your code is detection_object).
For example a document in your database needs to look like this:
    {'_id': ObjectId('5c4099dcffa4fb11494d983d'), 'legacy_id': 1437424, '_cls': '__ main __.detection_object'}


Q: Django Elasticbeanstalk: Cannot access static files when Debug = False My static files are served with no issue when Debug = True.  I have read the documentation on https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ but still cannot get it to work when Debug = False.  These are my settings (works fine when Debug = True):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = 'myapp/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"myapp","static","static-only")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR),"myapp","static"),
)

I have edited the config file to be:
container_commands:
   collectstatic:
      command: "myapp/manage.py collectstatic --noinput"

option_settings:
  "aws:elasticbeanstalk:application:environment":
     DJANGO_SETTINGS_MODULE: "myapp.settings"
     PYTHONPATH: "/opt/python/current/app/myapp:$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
     WSGIPath: "myapp/myapp/wsgi.py"
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "myapp/static/"

I have been banging my head on this for some time so any help would be much appreciated!

A: I don't have a direct answer to your question, other than to ask you why are you trying to do it this way. The best practice is to move your static files to S3 or ideally, CloudFront (or another non-AWS solution).
Use django-storages-redux (https://github.com/jschneier/django-storages) to use static files from S3 for production. Google 'django s3 static' and you will find several blogs explaining the process. The documentation is here.

A: collectstatic command would have collected all your static file to STATIC_ROOT which you had set as "/PATH/TO/myapp/static/static-only.
So I suspect that you pointed your static files to the wrong directory in the config file.
Try "/static/": "myapp/static/static-only"


Q: running load testing on selenium and api tests in Visual studio Team Services I am trying to run load tests on my existing selenium web tests and my api(unit) tests. The tests run in Visual studio using load test editor but does not collect all the metrics like response time and requests per seconds. Are there any additional parameters that I need to add to collect all the metrics ?

A: Load testing; how many selenium clients are you running? One or two will not generate much load. First issue to think about; you need load generators and selenium is a poor way to go about this (unless you are running grid headless but still).
So the target server is what, Windows Server 2012? Google Create a Data Collector Set to Monitor Performance Counters.
Data collection and analysis of same is your second issue to think about.  People pays loads of money for tools like LoadRunner because they provide load generators and sophisticated data collection of servers, database, WANs and LANS and analysis reports to pinpoint bottlenecks.  Doing this manually is hard and not easily repeatable.  Most folks who start down your path eventually abandon it.  Look into the various load/performance tools to see what works best for you and that you can afford.


Q: git remote /home/username/www/lorem.git
How can I use /home/username/www/example.git with remote add command?
if I use this:
git remote add origin user@example.com:/home/user/www/example.git
git push origin master

I got this error:
error: src refspec master does not match any.
error: failed to push some refs to 'user@example.com:/home/user/www/example.git'

A: Default behaviour of git push is just to push "matching refs", i.e. branches which are present both in the local and the remote repository. In your example, there are no such branches, so you need to tell git push which branches to push explicitly, i.e. via
git push origin branch-to-be-pushed

or, if you want to push all branches,
git push --all origin


Q: No runtime warning when content compression/hugging constraints conflict with specific width/height constraints Example
A UIButton that has:

*

*1000 priority width constraint (say width = 20)

*1000 priority horizontal compression resistance priority

*wide content that is bigger than 20

I don't get any runtime warning (the one in debugger), but for me it seems that i should. The content (button title) gets truncated. Why there is no warning and how do i enable it?


Q: Can you write a generic function that will compare any numeric type (e.g. int, float, double) against zero? We're trying to write a simple gain/loss function to return a color based on a value relative to zero.  If it's positive, we return green. If negative, we return red. If zero, we return gray.
The current function is written specifically to take a double, like so:
func getChangeColor(value:Double) -> UIColor {

    if value > 0 {
        return Theme.Colors.gain
    } else if value < 0 {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

But I'm wondering if it can be updated to take any numeric value?
My first thought was to write it against Comparable but the problem is we need to compare it against zero in that same type, whatever it is.
In other languages like C#, you can get the default value for a type, which in the case of numerics, is zero.  Does Swift have anything similar? If so, we could do this...
func getChangeColor<T:Comparable>(value:T) -> UIColor {

    let defaultValue = default(T.self)

    if value > defaultValue {
        return Theme.Colors.gain
    } else if value < defaultValue {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

...or is this approach wrong in the first place?

A: My solution adds a second protocol conformance: Numeric provides basic arithmetic operators for scalar types.
Then you are able to calculate the zero value in the generic type
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    if value > zero {
        return Theme.Colors.gain
    } else if value < zero {
        return Theme.Colors.loss
    } else {
        return Theme.Colors.noChange
    }
}

or with a switch statement
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    switch value {
    case zero:  return Theme.Colors.noChange
    case zero...: return Theme.Colors.gain
    default: return Theme.Colors.loss
    }
}

or with the ternary operator (added by OP)
func getChangeColor<T : Comparable & Numeric>(value:T) -> UIColor {

    let zero = value - value

    return value > zero
        ? Theme.Colors.gain
        : value < zero
            ? Theme.Colors.loss
            : Theme.Colors.noChange
}


Q: SQL Query Return Entries with no Occurences in Other Table I have two tables, orders and customers, and I am trying to return the customerID and name of customers with no orders.
customers
customerID: integer
name: string

orders
orderID: integer
itemID: integer
customerID: integer
date: date

What I currently have is not returning any results:
SELECT customers.customerID, customers.fName, orders.date
FROM orders INNER JOIN customers
ON orders.customerID = customers.customerID
GROUP BY orders.customerID
HAVING COUNT(*) = 0

A: You need a LEFT OUTER JOIN to accomplish this:
SELECT customers.customerID, customers.fName
FROM customers LEFT OUTER JOIN orders on customers.customerID = orders.customerID
WHERE orders.customerID IS NULL


Q: Nearby Messages using an IntentService Initially I setup a BroadcastReceiver to receive intents from the Nearby Messages API.
class BeaconMessageReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        Nearby.getMessagesClient(context).handleIntent(intent, object : MessageListener() {
            override fun onFound(message: Message) {
                val id = IBeaconId.from(message)
                Timber.i("Found iBeacon=$id")
                sendNotification(context, "Found iBeacon=$id")
            }

            override fun onLost(message: Message) {
                val id = IBeaconId.from(message)
                Timber.i("Lost iBeacon=$id")
                sendNotification(context, "Lost iBeacon=$id")
            }
        })
    }

    private fun sendNotification(context: Context, text: String) {
        Timber.d("Send notification.")
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val notification = NotificationCompat.Builder(context, Notifications.CHANNEL_GENERAL)
                .setContentTitle("Beacons")
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification_white)
                .build()

        manager.notify(NotificationIdGenerator.nextID(), notification)
    }

}

Then registered this receiver in my MainActivity after location permissions have been granted.
class MainActivity : AppCompatActivity() {

    // ...

    private fun onLocationPermissionsGranted() {
        val filter = MessageFilter.Builder()
                .includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
                .build()

        val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()

        Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
    }

    private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
            this, 0, Intent(context, BeaconMessageReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)

}

This worked well while the app was open, but does not work when the app is closed. So I found this example, that demonstrates how to setup an IntentService to receive messages while the app is in the background.
The example does use the Nearby.Messages class, which was deprecated in favor of the MessagesClient. So I replaced the deprecated code with the MessagesClient implementation.
class MainActivity : AppCompatActivity() {

    // ...

    private fun onLocationPermissionsGranted() {
        val filter = MessageFilter.Builder()
                .includeIBeaconIds(UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FEED"), null, null)
                .build()

        val options = SubscribeOptions.Builder().setStrategy(Strategy.BLE_ONLY).setFilter(filter).build()

        Nearby.getMessagesClient(context).subscribe(getPendingIntent(), options)
            .addOnSuccessListener {
                Timber.i("Subscribed successfully.")
                startService(Intent(this, BeaconMessageIntentService::class.java))
            }.addOnFailureListener {
                Timber.e(exception, "Subscription failed.")
            }
    }

    private fun getPendingIntent(): PendingIntent = PendingIntent.getBroadcast(
            this, 0, Intent(context, BeaconMessageIntentService::class.java), PendingIntent.FLAG_UPDATE_CURRENT)

}

And this is the IntentService (which is almost identical to my BroadcastReceiver).
class BeaconMessageIntentService : IntentService("BeaconMessageIntentService") {

    override fun onHandleIntent(intent: Intent?) {
        intent?.let {
            Nearby.getMessagesClient(this)
                    .handleIntent(it, object : MessageListener() {
                        override fun onFound(message: Message) {
                            val id = IBeaconId.from(message)
                            Timber.i("Found iBeacon=$id")
                            sendNotification("Found iBeacon=$id")
                        }

                        override fun onLost(message: Message) {
                            val id = IBeaconId.from(message)
                            Timber.i("Lost iBeacon=$id")
                            sendNotification("Lost iBeacon=$id")
                        }
                    })
        }
    }

    private fun sendNotification(text: String) {
        Timber.d("Send notification.")
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val notification = NotificationCompat.Builder(this, Notifications.CHANNEL_GENERAL)
                .setContentTitle("Beacons")
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification_white)
                .build()

        manager.notify(NotificationIdGenerator.nextID(), notification)
    }

}

onHandleIntent is called, and the Intent is not null; yet for some reason onFound() and onLost() are never called. Why would this be the case?

A: It's not really a solution but what I found is this (credit to this answer):
I've tried a few configurations including a BroadcastReceiver and adding a JobIntentService to run the code in the background, but every time I got this the onExpired callback which you can set to the SubscribeOptions:
options.setCallback(new SubscribeCallback() {
    @Override
    public void onExpired() {
        super.onExpired();
        Toast.makeText(context.get(), "No longer Subscribing!", Toast.LENGTH_SHORT).show();
    }
}

When the subscribe occurred in the background it was delayed, but it was still called.
Notes:
1. When I've tested with Strategy.BLE_ONLY I did not get the onFound callback.
2. From Google's documentation:

Background subscriptions consumes less power than foreground
  subscriptions, but have higher latency and lower reliability

When testing I found this "lower reliability" to be an understatement: onFound was rarely called and I never got the onLost.

A: I know this is a late reply, but I had the same problem and found out by debugging that it is an issue related to this error: "Attempting to perform a high-power operation from a non-Activity Context". This can be solved when calling Nearby.getMessagesClient(this) by passing in an activity context instead of this.
In my case I added a class extending Application which helps in returning this context (the below is in java but should be translatable to kotlin easily)
public class MyApplication extends Application {
    private Activity currentActivity = null;

    public Activity getCurrentActivity(){
        return currentActivity;
    }
    public void setCurrentActivity(Activity mCurrentActivity){
        this.currentActivity = mCurrentActivity;
    }
}

And in my base activity, from which all activities extend, I set the current activity by calling ((MyApplication) this.getApplicationContext()).setCurrentActivity(this); in the constructor.
My service can then call getMessagesClient with the correct context like below:
final Activity context = ((MyApplication)getApplicationContext()).getCurrentActivity();
Nearby.getMessagesClient(context).[...]

Do not forget to register your Application class in the AndroidManifest:
<application
android:name="com.example.xxx.MyApplication"`


Q: Scanf doesn't work with fork in a loop after the second iteration I don't understand why scanf won't wait for input the second time in the loop. it only works in the first iteration. Also somewhat wait(&Status) won't print the correct Status.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[5];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");
        scanf("%d", &x);

        int child = fork();
        if (child != 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", Status);
        }
    }
}

A: Like the comment posted above says, there are two problems here:

*

*You're running the command in the parent, rather than the child. See the fork manual.

*wait does not give you the return code. It gives you an integer that you need to decode. See the wait manual.
Here's the corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
    int x ;
    int Status =-99;
    char* cmds[6];
    cmds[1] = "who";
    cmds[2] = "ls";
    cmds[3] = "date";
    cmds[4] = "kldsfjflskdjf";
    int i=10;
    while (i--) {
        printf("\nMenu:\n");
        printf("1)who \n"); printf("2)ls  \n");printf("3)date\n");
        printf("choice :");
        scanf("%d", &x);

        int child = fork();
        if (child == 0) {
            execlp(cmds[x], cmds[x], NULL);
            printf("\nERROR\n");
            exit(99);
        } else {
            wait(&Status);
            printf("Status : %d", WEXITSTATUS(Status));
        }
    }
    return 0;
}