text:
Q: How to access getter/setter accessors from angular 4 in template binding? Lets say I have the following getter/setter methods

get next() {
  console.log(this.people[this._index], this._index);
  return this.people[this._index];
}

set next(i: any) {
  this._index = (+i) + 1;
  this._index = (+i) % this.people.length;
}

and I want to call this in the following way:

<ng-template ngFor let-person="$implicit" [ngForOf]="people" let-i=index let-last=last>
  <app-card [cardItem]="people[i]" [nextCard]="next(i)"></app-card>
</ng-template>

PS: Think of this as circular array. Where by I need prev, current, and next items.
However I get the following Error

Angular: Member 'next' in not callable

Why is that? And whats the solution?
Thanks
Edit
Thank you guys for your help and explanation. With your help i managed to make it work:

<app-card [currentCard]="people[i]" [nextCard]="people[i === people.length - 1 ? 0: i + 1]" [prevCard]="i == 0 ? people[people.length - 1] : people[i - 1]"></app-card>

So its pretty much circular array.
Lets assume we have the following:
people["James Dan", "Aluan Haddad", "Jota Toledo"]
So few conditions:

*

*If I stand in the beginning of the array (i.e. index = 0) - then my prev will be people[people.length - 1] which is the last element in the array. And if my current is on index 1, then my prev will be index 0 and next will be index 2.

A: The Angular template syntax is, in general, a subset of JavaScript syntax with some notable differences and with many restrictions.
However what you have here is actually invalid in JavaScript as well. It is not valid to call a property accessor. Ever.
Given the following property
get p() {
  console.info('read p');
  return this.wrapped;
}
set p(value) {
  console.info('wrote p');
  this.wrapped = value;
}

The get accessor is invoked implicitly when the property thusly named is read.
For example:
console.log(o.p); // read p

The set accessor is invoked implicitly when the property thusly named is written.
For example:
o.p = x; // wrote p;

The same rules apply in Angular templates.
However, your example of
<app-card [cardItem]="people[i]" [nextCard]="next(i)">

suggests that a property is not what you want here.
The correct usage of a property implies the following syntax
<app-card [cardItem]="people[i]" [nextCard]="next = i">

Which I do not believe is supported by the Angular template syntax and even if it is doesn't make a lot of sense and would be hard to read.
Instead you should create a method that returns a value
getNext(i: number) {
  this._index = i + 1;
  this._index = i % this.people.length;
  return this.people[this._index];
}

Then used in your template as
<app-card [cardItem]="people[i]" [nextCard]="getNext(i)">

Having said that, I think the entire design is questionable. You seem to be going through contortions to store excess mutable state independently of the array that naturally maintains it.
I believe you would be much better served by removing the method and the property entirely and using
<app-card
  *ngFor="let person of people; let i = index"
  [previousCard]="people[i === 0 ? people.length - 1 : i - 1]"
  [cardItem]="person"
  [nextCard]="people[i === people.length - 1 ? 0 : i + 1]">

If you want a cleaner syntax, you might define a property, with a get accessor only, that returns a view of your array as objects with previous, current, and next properties.
get peopleAsPreviousCurrentAndNextTriplets() {
  return this.people.map((person, i) => ({
    previous: this.people[i === 0 ? this.people.length - 1 : i - 1],
    current: person,
    next: this.people[i === this.people.length - 1 ? 0 : i + 1]
  }));
}

This can be more readable in complex code because its abstracts away the index for more semantic properties that we can use directly. Perhaps more importantly, it enables TypeScript's world-class tooling to validate the computation.
<app-card
  *ngFor="let item of peopleAsPreviousCurrentAndNextTriplets"
  [previousCard]="item.previous"
  [cardItem]="item.current"
  [nextCard]="item.next">

And thus we come full circle. Note how we define the get accessor and how we read the property it defines without (), implicitly invoking that accessor.
The last example is probably overkill for this scenario but I think it's useful nonetheless.


text:
Q: Push new key element into subdocument of mongodb I have a mongo collection with the following structure:
{
   "_id" : ObjectId("..."),
   history : {

   }
}

Now I have to update such collection pushing into history subdocument new associative object so it should look like:
{
   "_id" : ObjectId("..."),
   history : {
        "06/04/2015" : {}
   }
}

What's the right way of doing this?

A: Given that data-format:
> db.test.insert({_id: oid, history: {} })

It is pretty easy to add a new field in the embedded document history. You just need the $set update operator and you will have to use dot-notation to specify the field:
> db.test.update({_id:oid},{$set: { "history.06/04/2015": "6 of june"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Producing:
> db.test.find({_id:oid},{_id:0})
{ "history" : { "06/04/2015" : "6 of june" } }

Please note the $set operation is idempotent:
> db.test.update({_id:oid},{$set: { "history.06/04/2015": "6 of june"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.test.find({_id:oid},{_id:0})
{ "history" : { "06/04/2015" : "6 of june" } }

That being said, as explained in comments, this is probably not the best way to store history. Just to mention that, it will prevent proper indexing of your history by date, for example.
In fact, there are many different ways to store your history data. Just few examples. All of them have (probably) pros and (definitively) cons:
{
  history: [
    { "06/04/2015": "6 of June" },
  ]
}

{
  history: {
    "2015" : [
      { "06/04": "6 of June" },
    ]
  }
}

{
  history: {
    {
      year: "2015";
      data: [
        { "06/04": "6 of June" },
      ]
    }
  }
}

etc.

BTW, using a proper date object is probably better than using a string to store date. I use that later here only to avoid making the examples more cumbersome.

A: change your schema (lets call it 'Collection' for this example):
{
   _id : ObjectId,
    history : [{
   date: *some date*
   data: {*data data data data*}
  }]
}

and then push to the history array objects that contain two keys, the first being date whose value is the string "mm/dd/yyyy" and then the second is data whose value is the data object associated with that date.
now when you want to add a subdoc of
{date: "05/01/1944",
 data: {
   event: "foo",
   duration: "bar"
}

to a doc with
{
  _id: {$oid: 1},
 history: []
}

all you do is:
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var collections = mongoose.model('Collection');
var id = *_id of what you want to add to, in this case "1"*;
var change =  {date: "05/01/1944",
 data: {
   event: "foo",
   duration: "bar"
}

collections.update({
  _id: new ObjectId(id)
}, {$push:{history: change}});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating instances of a class during Rails startup I'm trying to create multiple instances of a class while Rails loads, and to keep those instances available. (I'm loading the data from a YAML file, but I've abstracted away that detail for this question.) I have a non-ActiveRecord model with an instantiate class method that loads the data. When I call instantiate from config.after_initialize and/or from a custom initializer, the instances are created, but by the time rails console finishes loading, they are gone. Where can I instantiate the data so that it will be available within rails console (and the server)?
# app/models/test.rb
class Test
  include ActiveModel::Model
  attr_accessor :name

  class << self
    include Enumerable

    def each
      ObjectSpace.each_object(self).each do |object|
        yield object
      end
      self
    end

    def find_by_name(input)
      find { |object| object.name.to_s == input.to_s }
    end

    def instantiate
      new(name: 'Alice')
      new(name: 'Bob')
    end
  end

  def initialize(*parameters)
    super(*parameters)
    freeze
  end

  delegate :to_s, to: :name
end

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.after_initialize do
      p "Test instances before after_initialize: #{Test.count}"
      Test.instantiate
      p "Test instances after after_initialize: #{Test.count}"
    end
  end
end

# config/initializer/test_initializer.rb
p "Test instances before test_initializer: #{Test.count}"
Test.instantiate
p "Test instances after test_initializer: #{Test.count}"

$ rails console
"Test instances before test_initializer: 2"
"Test instances after test_initializer: 4"
"Test instances before after_initialize: 0"
"Test instances after after_initialize: 2"
Loading development environment (Rails 4.2.6)
irb(main):001:0> Test.count
=> 0
irb(main):002:0> Test.instantiate
=> #<Test:0x007fad2204d8b0 @name="Bob">
irb(main):003:0> Test.count
=> 2

A: Ruby garbage collector removes the instances from the memory. There exists no direct links that references the newly created instances, so Ruby deems them unnecessary.
You can try this by adding:
module MyApp
  class Application < Rails::Application
    config.after_initialize do
      GC.disable # Disable garbage collector
      p "Test instances before after_initialize: #{Test.count}"
      Test.instantiate
      p "Test instances after after_initialize: #{Test.count}"
    end
  end
end

But disabling garbage collector is not a good idea. If you would reference the instances somehow they will not get sweeped and they will be available after the startup through references.

A: In reference to the solution that you posted. Since you are in control of the instantiation process, you don't need to use the ObjectSpace at all. If you want the Test class to remember just two instances created in the #instantiate method, you could something like this:
class Test
  @objects = []

  include ActiveModel::Model
  attr_accessor :name

  class << self
    include Enumerable

    def each
      if block_given?
        objects.each { |o| yield o }
      else
        objects.to_enum
      end
    end

    def find_by_name(input)
      find { |object| object.name.to_s == input.to_s }
    end

    def instantiate
      objects << new(name: 'alice')
      objects << new(name: 'Bob')
    end

    private

    attr_accessor :objects
  end

  def initialize(*parameters)
    super(*parameters)
    freeze
  end

  delegate :to_s, to: :name
end

If you want the Test class to remember all the objects that were instantiated. You could change the lines:
...
    def instantiate
      new(name: 'alice')
      new(name: 'Bob')
    end
  end

  def initialize(*parameters)
    super(*parameters)
    freeze
    self.class.objects << self
  end
...

A: [rewritten / updated code]
@Laura Paakkinen thanks very much for your answer. You're correct that the underlying problem was garbage collection of instances that were not referenced. And, you were also correct that since my class is doing the instantiating, it can simply keep an instance variable to track all members of the class.
Unlike your approach below, I decided to add memoization via an all method. In particular, I was finding that on running reload! in rails console, the contents of the Criteria class would be erased. My solution is to add a test in all and to instantiate if the memoized instance variable is empty or nil. This also means that the initializer is no longer necessary, as the Class now instantiates on first use. Note that each calls all, and via the Enumerable mixin, all other class methods invoke each.
Thanks again for your thoughtful replies, which brought me to a much better answer.
class Test
  include ActiveModel::Model
  attr_accessor :name, :value

  class << self
    include Enumerable

    def [](key)
      instantiate if @test.blank?
      @test[key.to_sym]
    end

    def all
      instantiate if @test.blank?
      @test.values
    end

    def each
      all.each do |object|
        yield object
      end
      self
    end

    def keys
      map(&:name)
    end

    def instantiate
      @test = {}
      @test[:Alice] = new(name: 'Alice', value: 1)
      @test[:Bob] = new(name: 'Bob', value: 2)
    end
  end

  # Instance Methods

  def initialize(*parameters)
    super(*parameters)
    freeze
  end

  delegate :to_s, to: :name
end


text:
Q: Twitter typehead auto-complete for remote source with dynamic values I am trying to use typeahead.js 0.9.3 https://github.com/twitter/typeahead with remote option, Basically I wanted to apply auto-complete on 5-6 fields and I wanted to add dynamic value based on the id of the current field in my remote url and valuekey.
This is what i am trying.
jQuery(function($) {
$( ".posts_autocomplete" ).each(function() {
  var fid = $(this).attr("id");
  var field = fid.replace("post_", "");
  $(this).typeahead({
    name: 'posts_search',
    remote: '/posts/search?q=%QUERY&field='+field,
    valueKey: field,
    minLength: 2,
    limit: 10
  });
});
});

I have also tried replace Bootstrap 3 typeahead.js - remote url attributes but it doesn't seem to work.

A: Resolved it using a unique name for typehead inside each iteration.
jQuery(function($) {
$( ".posts_autocomplete" ).each(function(i) {
  var fid = $(this).attr("id");
  var field = fid.replace("post_", "");
  $("#"+fid).typeahead({
    name: i,
    remote: '/posts/search?q=%QUERY&field='+field,
    valueKey: field,
    minLength: 2,
    limit: 10
  });
});
});


text:
Q: How can I avoid having too many arguments in Spring Java controllor In my Spring web application:
    @RequestMapping(value = NEW)
public String addProduct(@RequestParam String name, @RequestParam(required = false) String description,
                         @RequestParam String price, @RequestParam String company, ModelMap model,
                         @RequestParam(required = false) String volume, @RequestParam(required = false) String weight) {
    try {
        productManagementService.addNewProduct(name, description, company, price, volume, weight);
        model.addAttribute("confirm", PRODUCT_ADDED);
        return FORM_PAGE;
    } catch (NumberFormatException e) {
        logger.log(Level.SEVERE, INVALID_VALUE);
        model.addAttribute("error", INVALID_VALUE);
        return FORM_PAGE;
    } catch (InvalidUserInputException e) {
        logger.log(Level.SEVERE, e.getMessage());
        model.addAttribute("error", e.getMessage());
        return FORM_PAGE;
    }
}

What are the possible ways to reduce/bind total number of arguments.

A: create Form Class i.e
class MyForm{
String name;
String price;
String description;
...
 // Getters and setters included
}

and do like
@RequestMapping(value = NEW)
public String addProduct(@ModelAttribute MyForm myForm)

instantiation of MyForm and binding of request parameters to its properties and adding to ModelMap is done by spring behind the scenes.
Source: Spring Docs

An @ModelAttribute on a method argument indicates the argument should
  be retrieved from the model. If not present in the model, the argument
  should be instantiated first and then added to the model. Once present
  in the model, the argument's fields should be populated from all
  request parameters that have matching names. This is known as data
  binding in Spring MVC, a very useful mechanism that saves you from
  having to parse each form field individually.

A: Create a class, encapsulate all the attributes in that class and then accept that class object as your @ModelAttribute. Something like:
public class MyData {

    private String name;

    private String description;

    private String price;

    private String company;

    private String volume;

    private String weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getVolume() {
        return volume;
    }

    public void setVolume(String volume) {
        this.volume = volume;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

}

And then modifying your addProduct method like this:
public String addProduct(@ModelAttribute MyData myData, ModelMap model)


text:
Q: How to include just enough locale data with an app to be able to format dates in three locales? I would like to be able to format java.util.Date objects in a "long" English, Spanish, and German date format. By "long" I mean the locale-dependent date format that corresponds to the LONG style pattern constant in java.text.DateFormat:
DateFormat.getDateInstance(DateFormat.LONG, myLocale).format(myDate);

With a standard JRE, I get date strings like:
November 22, 2010
22 de noviembre de 2010
22. November 2010

as expected. On Android 1.5, however, I get:
November 22, 2010
2010 11 22
2010 11 22

Is there a way that I can include just enough locale information with my app to be able to format dates correctly in long English, Spanish, and German formats using java.text.DateFormat?

A: First of all, the dates formatting in JRE is known for incorrect behavior for many locales (invalid Polish, Czech and Russian long dates, invalid Polish short date; And this are just examples of what I know for sure). So I wouldn't trust this source of information much.
If you want to implement your own long date formatting logic, here is what I would do:
String spanishDatePattern = "{0,number,00} {1} {2,number,####}";
String spanishLongDateMonthNameNovember = "de noviembre de";

Object[] arguments = { new Integer(date.getDate()),
                       spanishLongDateMonthNameNovember,
                       new Integer(date.getYear()) };
String formattedDate = MessageFormat.format(spanishDatePattern,
                arguments);

In this case you will need 13 messages per language (12 month ~names and 1 pattern). Not that much, I believe.
Of course this was just an example, in reality you would probably need to also add logic to resolve month names (having keys with name ending with month number, i.e. longDateFormatMonthName.0=January?).


text:
Q: Ultra slow BIOS boot on Samsung NP530 notebook PC I purchased a Samsung laptop model NP530U4C from Amazon in December 2012 and just two days ago it has suddenly developed a slow BIOS boot.
The laptop has a Phoenix BIOS.
I have made NO hardware changes and have Fast Boot enabled.  The laptop previously took 20 seconds to boot into Windows, but now it takes nearly 10 minutes for the Windows boot process to start.  At the end of the BIOS boot process a blue bar appears across the bottom of the screen (next to the Phoenix logo) before Windows starts booting up.
On a couple of separate occasions, when Windows installed I was greeted by a message telling me that Windows is installing device drives for the CD/DVD drive as well as the SanDisk i100 SSD 24gb cache drive.
When I manage to press F2, after waiting nearly 2 minutes for the key press to register the BIOS navigation is painfully slow taking nearly 20-30 seconds to register the key presses.
I have taken the hard drive out to see if this speeds up the BIOS boot, just in case the hard drive is failing, but the problem still persists.  I even installed CrystalDiskInfo and it reported the drive health is good with an operating temperature of 36C.
I have filled out a support request to Samsung so I don't know how long I'll be waiting for an answer.
This all seem to have started after I plugged a laptop cooling board into the USB port.
I am wondering whether the USB laptop cooler has somehow shorted out the USB port, or has done some damage to the motherboard.
Also, to turn on the laptop I used to have to hold the power key down for 1 second, but now I just need to tap it for a fraction of a second for it to power up.  I am not sure what this means.
Has anyone got any ideas to explain why my laptop developed this sudden problem?


text:
Q: smoothing of auto-correlated time series data with ggplot2 Is there a way to incorporate smoothing function for an auto-correlated time series in ggplot2?
I have time series data that is auto-correlated for which I currently use a manual process to determine 95% CI for the fitted spline.
Usage and Date are in a data frame AB. The main components of the model I use are as follows:
    d<-AB$Date
    a<-AB$Usage

    o<-order(d)
    d<-d[o]
    a<-a[o]

    id<-ts(1:length(d))
    a1<-ts(a)

    a2<-lag(a1-1)
    tg<-ts.union(a1,id,a2)
    mg<-lm(a1~a2+bs(id,df=df1), data=tg)

From this model I obtain fitted means and standard errors of the fit which are used to work out the 95% CI for the fitted spline.
I have seen examples of the lm method in ggplot2 with a term to specify the model formula.
Is this kind of time series model achievable when the time series is auto-correlated?
Thanks.

A: The CI will be biased if you use the simple formula in ggplot2 for adding any model fit if there is dependence in the residuals.
If I were doing this, I would fit whatever model I wanted outside of gpplot2. Then predict from that model over a grid evenly spaced points in the range of the covariates. Compute confidence intervals for those predictions and combine these and the fitted values and the data into a single data frame. From there you can use geom_line() and geom_ribbon() for the fitted model and confidence interval respectively. This allows you to compute proper confidence intervals that account for the lack of independence in the residuals.
One issue I foresee is that you have a model that includes two covariates, whereas ggplot() would normally consider the relationship between a response and a single covariate. For example, if you are plotting a1 vs id in ggplot but the model is for a2 + bs(id) then you'd need to account a2 in some manner first, say be predicting for a range of values in id but keep a2 fixed at some reasonable value, say the sample mean.


text:
Q: Element.closest() returns null on existing HTML element For one of my study project, I have to create a cart system. On the cart.html page, the cart is supposed to be displayed. Until there, I am good.
When the user changes the quantity of one of the item, I am supposed to update it, using Element.closest().
My problem is : when I change the quantity of one of the products, the console displays null whereas it should display the correct element.
Where is the problem coming from ?
I wrote the following code :
  article = document.getElementsByTagName('article'),
  quantity = document.getElementsByClassName('itemQuantity');

const cartContent = getLocalStorage('totalCart');
let i = 0,
  array = [],
  datasetArray = [];

window.addEventListener('load', function () {
  cartContent.map((element) => {
    fetch(`http://localhost:3000/api/products/${element.id}`)
      .then((response) => response.json())
      .then((data) => {
        displayContent(data, element);
        convertCollectionToArray(article);
        addListenerOnCollection(quantity, 'change');
      });
  });
});

/**
 * Displays elements on cart page
 * @param { Object } cart Contains fetched elements according to id stored in localStorage
 * @param { Object } storageElement Contains id, color and quantity of storaged products
 */
function displayContent(cart, storageElement) {
  cartItems.insertAdjacentHTML(
    'beforeend',
    `

${cart.name}

${storageElement.color}

${cart.price}€

Qté :

            <input type="number" class="itemQuantity" name="itemQuantity" id="quantity" min="1" max="100" value="${storageElement.quantity}">

Supprimer

`
  );
}

function convertCollectionToArray(htmlCollection) {
  array = Array.from(htmlCollection);
}

function getDataset(array) {
  array.map((element) => {
    datasetArray.push(element.dataset);
  });
}

function addListenerOnCollection(collection) {
  for (var index in collection) {
    collection[index].onchange = function () {
      updateCartQuantity(article.item(index).dataset);
    };
  }
}

function updateCartQuantity(dataset) {
  let elementToUpdate = cartItems.closest(
    `.cart__item[data-id="${dataset.id}"][data-color="${dataset.color}"]`
  );

}

function getQuantity() {
  let newQuantity;
  for (index in quantity) {
    newQuantity = quantity.item(index).value;
  }
  return newQuantity;
}


text:
Q: How to count DbSet rows added to in a DbContext Looked high and low but cannot find the syntax to count the number of rows in a [DbContext].[DbSet Entity] by the change status of the row. Specifically, I would like to know how many rows in one entity/table were added and are pending SaveChanges().

A: You can use one of the DbContext.ChangeTracker.Entries method overloads (similar to EF6):
var addedCount = db.ChangeTracker.Entries<YourEntity>()
    .Count(e => e.State == EntityState.Added);

A: (First answer, so be gentle)
I had a similar problem. One approach is to override the context SaveChanges method as proposed here: https://www.exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/
But in your situation a special method on your context class might be more appropriate:
public virtual Tuple<int, int> CountChanges()
{
    var modified = ChangeTracker.Entries().Where(x => x.State == EntityState.Modified).Count();
    var added = ChangeTracker.Entries().Where(x => x.State == EntityState.Added).Count();
    return new Tuple<int, int>(modified, added);
}


text:
Q: In R, how can I use a variable as the character after the extraction operator ($) in a user written function? I have the following two data frames (the real data frames are much larger). I would like to determine at which position(s) both data frames contain a 3 (in this example spot [2,1] only).
a<-c(1,3,5)
b<-c(2,3,4)
c<-c(3,3,4)
d<-c(2,4,7)
e<-cbind(a,b)
f<-cbind(c,d)
colnames(e)<-c("a","b")
colnames(f)<-c("a","b")

Results:
e
## a b
## 1 2
## 3 3
## 5 4

f

## a b
## 3 2
## 3 4
## 4 7

I've tried to use the following function, but it doesn't work.
fun<-function(x)
{ifelse(e$x==3 & f$x==3, "yes","no")}
Vs<-c("a","b")
lapply(Vs, fun)

Does anyone have any ideas, specifically on how use a variable as the character after the extraction operator ($) in a user written function?

A: Here you go:
fun <- function(x) { ifelse(e[,x] == 3 & f[,x] == 3, "yes", "no") }
Vs <- c("a", "b")
lapply(Vs, fun)


text:
Q: Wcsession session expired and error 7007 I am new in WatchKit and I am working on one of my app, but I am facing one problem regarding connection with Apple watch.
my source code is below:
-(BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ //create a session using wcsession
    if ([WCSession isSupported]) {
        [[WCSession defaultSession] setDelegate:self];
        [[WCSession defaultSession] activateSession];
    }

    return YES;
}

Send message action in my viewcontroller:
[[WCSession defaultSession] sendMessage:dict replyHandler:^(NSDictionary *replyHandler)
{
    NSLog(@"Replay %@",replyHandler);
}
errorHandler:^(NSError *error) {
    NSLog(@"Error %@",error);
}];

Also I activate the wcsession at watch side in complication controller
]if ([WCSession isSupported]) {
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
}

and
-(void)session:(nonnull WCSession *)session
    didReceiveMessage:(nonnull NSDictionary<NSString *,id> *)message
    replyHandler:(nonnull void (^)(NSDictionary<NSString *,id> * __nonnull))replyHandler {
    [extensionDelgate InsertIntoTideMaster:message];
    [self requestedUpdateDidBegin];
    dispatch_async(dispatch_get_main_queue(), ^{
    });
}

This works first time when I am launching the app, but after that I got 7007 code error ... can you tell me what is missing here?
Thanks in advance.


text:
Q: $\sum (f(\frac{k}{n})) + \sum (f^{-1}(\frac{k}{n}))$ I would appreciate some help with the following Putnam preparatory problem (you can google Putnam 2010, Week 3, inequalities, problem 13):
Let $f$ be a continuous and monotonically increasing function such that $f(0) = 0$ and $f(1) = 1$. Prove that:
$f(0.1)+f(0.2)+···+f(0.9)+f^{−1}(0.1)+f^{−1}(0.2)+···+f^{−1}(0.9) ≤ 9.9$ (here $f^{−1}$ is the inverse function of $f$).
I've made two attempts and came up with either a more relaxed bound (10.0) or a tighter bound (9.5) but for a special case (when $f(x)$ doesn't change convexity). I can present those if anyone interested (I used $\int_a^b f(x)dx+\int_{f(a)}^{f(b)} f^{−1}(x)dx=bf(b)−af(a)$ and lower Darboux sums or trapezoidal method), but bottom line is I couldn't prove the general 9.9 bound.
Thanks in advance.

A: I present and idea on how you could start: We start the same way as you probably already did, but then take care of a detail.
The core idea is following:
What we're trying to do here is making use of the fact that the red square is always ignored in the summation: (The yellow rectangles represent the sums.)

Surely $$\int_0^1 f(x) dx + \int_0^1 f^{-1}(x) dx = 1 \qquad (1)$$
Let $x_k = 0.1\cdot k$. Then define the piecewise constant step function $g(x) = f(x_k)$ for $ x \in [x_k,x_{k+1})$ and similarly $g^{-1}(x) = f^{-1}(x_k)$ for $x \in [x_k, x_{k+1})$. (Note that I just use the symbol $g^{-1}$ for symmetry reasons, but $g^{-1}$ does not denote the inverse of $g$.)Then surely $g(x) \leq f(x)$ and $g^{-1}(x) \leq f(x) \forall x \in [0,1]$.
Therefore
$$\frac{1}{10}(f(0.1)+f(0.2)+\ldots+f(0.9))=\int_{0.1}^1 g(x) dx \leq \int_{0.1}^1 f(x)dx \qquad (2)$$
and
$$\frac{1}{10}(f^{-1}(0.1)+f^{-1}(0.2)+\ldots+f^{-1}(0.9))=\int_{0.1}^1 g^{-1}(x) dx \leq \int_{0.1}^1 f^{-1}(x)dx \qquad (3)$$
Now note that $$G:=\int_0^{0.1} g(x) dx + \int_0^{0.1} g^{-1}(x)dx = 0 \qquad (4)$$
Now we just have to consider $$F:=\int_0^{0.1} f(x) dx + \int_0^{0.1} f^{-1}(x)dx \qquad (5)$$
So now we can add $(2)$ and $(3)$ and multiply by $10$ and get
$$\sum_{k=1}^9 f(x_k) + f^{-1}(x_k)  \overset{(2) \& (3)}{\leq} 10\int_{0.1}^1 f(x) dx + 10\int_{0.1}^1 f^{-1}(x) dx \overset{(1)\& (5)}{=} 10(1-F) $$
It remains to show that $F \geq 0.01$:
Let $a=0$ and $b=0.1$.
Then $$\begin{align*}F  &=  \int_0^b f(x)dx+\int_{0}^{b} f^{−1}(x)dx  \\
 & \geq \int_0^b \min\{f(x),b\} dx+\int_{0}^{b} \min\{f^{−1}(x),b\}dx \\
& =b^2 = 0.01
\end{align*}$$
This completes the proof.


text:
Q: How to add attribute to the script in php I have a link to the script in my HTML
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly" defer></script>

I need to add attribute "defer" in my php when using "wp_dequeue_style"
wp_enqueue_script('google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly', [], $version, true);

is it any options?

A: You can't do it using wp_enqueue_script you will have to use some other script loader hooks and add the defer.
Please check this article it has the explanation and code that will help you.

A: Please add this in your functions.php file and check again.
add_action( 'wp_enqueue_scripts', 'qcpd_wp_script_to_scripts', 20, 1);
if (!function_exists('qcpd_wp_script_to_scripts')) {
    function qcpd_wp_script_to_scripts(){

        wp_enqueue_script('google-map', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCrAbBwliakQCs7vDgLGilKQnicEc0-8hA&callback=initMap&v=weekly', [], '', true);
    }
}

add_filter( 'script_loader_tag', 'qcpd_wp_script_defer_load_js', 100, 3 );
if (!function_exists('qcpd_wp_script_defer_load_js')) {
function qcpd_wp_script_defer_load_js( $tag, $handle, $src ) {
    //$defer_load_js = true;

        $handles = array(
                        'google-map'
                    );

        if ( ! wp_is_mobile() && in_array( $handle, $handles ) ) {

            return str_replace(' src', ' defer src', $tag);

        }

        return $tag;

    }
}


text:
Q: definition $\epsilon$ de $\limsup_{t\to+\infty}$ Please what is the $\epsilon$ definition of this limit $$\limsup_{t\to+\infty}\frac{|f(t)|}{|t| |g(t)|}<+\infty$$
is it $$\forall \varepsilon>0, \exists A>0,\forall t\in\mathbb{R}, |t|>A\Rightarrow |f(t)|<\varepsilon |t| |g(t)| +\ell$$
thank you

A: As pointed out in the comments, not quite. Here's a definition. There exists an $l$ such that for every $\varepsilon > 0$ there exists $M$ such that $t > M$ implies
$$
\frac{|f(t)|}{|t||g(t)|} < l + \varepsilon
$$
and for infinitely many $t$,
$$
\frac{|f(t)|}{|t||g(t)|} > l - \varepsilon
$$

A: $$\forall \varepsilon>0, \exists B > 0, \forall A > B, \exists t>A,|t||g(t)|(\ell-\varepsilon) < |f(t)|< |t| |g(t)| (\ell + \epsilon)$$


text:
Q: A code is executed faster in the activated tab This code rotates favicon:
function removeAllIcons() {
    var allIcons = document.querySelectorAll("link[rel='icon']");
    for (let i = 0; i < allIcons.length; i++) {
        allIcons[i].remove();
    }
}

removeAllIcons();

var favicon_images = [
                    '/n-static/img/animated-favicon/tmp-0.gif',
                    '/n-static/img/animated-favicon/tmp-1.gif',
                    '/n-static/img/animated-favicon/tmp-2.gif',
                    '/n-static/img/animated-favicon/tmp-3.gif',
                    '/n-static/img/animated-favicon/tmp-4.gif',
                    '/n-static/img/animated-favicon/tmp-5.gif',
                    '/n-static/img/animated-favicon/tmp-6.gif',
                    '/n-static/img/animated-favicon/tmp-7.gif',
                ];
var image_counter = 0; // To keep track of the current image

setInterval(function() {
    // Remove if favicon exist.
    if(document.querySelector("link[rel='icon']") !== null) {
        document.querySelector("link[rel='icon']").remove();
    }
    // Add new favicon image
    document.querySelector("head").insertAdjacentHTML('beforeend', '<link rel="icon" href="' + favicon_images[image_counter] + '" type="image/gif">');

    // If last image then goto first image
    // Else go to next image
    if(image_counter == favicon_images.length -1)
        image_counter = 0;
    else
        image_counter++;
}, 200);

The problem with it is that when a tab in the browser is activated, then rotation is faster than when another tab is activated. In other words, if our web site is open in the current tab of the browser, the rotation is rather smooth. When another tab is activated, the rotation is much slower.
I have checked in Chrome and Firefox. What might be the reason for this?

A: Use the requestAnimationFrame function for this purpose.
The delay of timer functions in inactive tabs is intentional. You can find in MDN that:

To reduce the load (and associated battery usage) from background
tabs, browsers will enforce a minimum timeout delay in inactive tabs.

If you need a  constant speed for your animation, it needs to be done when the browser repaints.
requestAnimationFrame(function() {
    // Remove if favicon exist.
    if(document.querySelector("link[rel='icon']") !== null) {
        document.querySelector("link[rel='icon']").remove();
    }
    ...
    ...

Use an external counter if you need to change the speed.


text:
Q: how to generate X-Amzn-Trace-Id for Golang in the simplest way I have been seeing this documentation by AWS
Is there any simple way to generate "X-Amzn-Trace-Id" with X-Ray?
the func NewIDGenerator() doesn't produce the format of Root xxx.
or can we just use a trusted library for it? Thank you

A: First Create a Trace using OpenTelemetry's tracer and then inject that context to XRAY Propagator to get TraceId as per AWS's ID specification.
func GetAmazonTraceId(ctx context.Context) string {
    propogator := xray.Propagator{}
    carrier := propagation.HeaderCarrier{}
    propogator.Inject(ctx, carrier)
    traceId := carrier.Get("X-Amzn-Trace-Id")
    return traceId
}

A: Or, you can write your code to convert standard trace id(String) to xray trace id.
private static final String TRACE_ID_VERSION = "1";
private static final char TRACE_ID_DELIMITER = '-';
private static final int TRACE_ID_DELIMITER_INDEX_1 = 1;
private static final int TRACE_ID_DELIMITER_INDEX_2 = 10;
private static final int TRACE_ID_FIRST_PART_LENGTH = 8;

public static String toXRayTraceId(String traceId) {
    return TRACE_ID_VERSION
        + TRACE_ID_DELIMITER
        + traceId.substring(0, TRACE_ID_FIRST_PART_LENGTH)
        + TRACE_ID_DELIMITER
        + traceId.substring(TRACE_ID_FIRST_PART_LENGTH);
  }


text:
Q: Why can't I change the JButton (disabled) text color? I started programming Java. This is my first window application. I did a simple tic-tac-toe game and I want the "o" button font color to be a different color. But it doesn't work. I can change the background color, but not the fonts, why?
package moje;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.print.PrinterJob;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JTextField;

public class Kolko_i_krzyzyk extends JFrame implements ActionListener {

    static JTextField tekst;
    static JLayeredPane ekran = new JLayeredPane();
    static JButton button = new JButton();
    static int licznik=0;

    public Kolko_i_krzyzyk () {
        super("Kółko i krzyżyk");
        ekran = new JLayeredPane();
        setVisible(true);
        setSize(800, 800);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        //Siatka podzielona 3 na 3
        setLayout(new GridLayout(3,3));

        //Tworzenie 9 przycisków
        for(int i = 1; i<=9; i++) {
        JButton button = new JButton();
        add(button);
        button.addActionListener(this);
        }
    }

    public static void main(String[] args) {
        JFrame okno = new Kolko_i_krzyzyk();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
    JButton  button = (JButton) e.getSource();
    if(licznik%2==0 ) {
        button.setText("x");
        button.setFont(new Font ("Arial", Font.BOLD, 90));
    }
    else {
        button.setText("O");
        button.setForeground(Color.RED);
        button.setFont(new Font ("Arial", Font.BOLD, 90));
    }
    button.setEnabled(false);
    licznik++;
    }
}

A: The issue here is the default behavior when disabling the JButton via setEnabled(false).
This will grey out the button and ignore any color formatting you did to the text (foreground).
There are several workarounds to modify this behavior (as seen in this similar question).
Here is a short demonstration (without the final game logic of course) , which changes the UI of the JButton via setUI().
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;

public class Test {

    private int counter = 0;

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> new Test().buildGui());
    }

    private void buildGui() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.add(panel);
        panel.setLayout(new GridLayout(3, 3));

        for (int i = 1; i <= 9; i++) {
            JButton button = new JButton() {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(150, 150);
                }
            };
            button.setFont(new Font("Arial", Font.BOLD, 90));
            panel.add(button);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (counter % 2 == 0) {
                        button.setText("X");
                        button.setUI(new MetalButtonUI() {
                            // override the disabled text color for the button UI
                            protected Color getDisabledTextColor() {
                                return Color.BLUE;
                            }
                        });
                    } else {
                        button.setText("O");
                        button.setUI(new MetalButtonUI() {
                            protected Color getDisabledTextColor() {
                                return Color.RED;
                            }
                        });
                    }
                    button.setEnabled(false);
                    counter++;
                }
            });
        }
        frame.pack();
        frame.setVisible(true);
    }

}

Result:

Another (simpler) way to do it would be to build some ImageIcons for "X" and "O", then set these on the buttons via setIcon()/setDisabledIcon(). This would save you the trouble from modifying the button UI.


text:
Q: How to manage what to display in a gridview from a dropdown list? First time posting here.
I have a specific problem with a simple webapplication, where i got stuck on having a gridview bind to a dropdownlist and displaying the contents of the selected item in the ddl.
I can bind the gridview to the ddl fine, and it will display the information that is contained within all of the items of the ddl.  But i cant for the life of me figure out how to only display the selected objects information in the gridview.
And ive also been unable to re-fire the databind from the ddl's onSelectedItemChanged.
    protected void ddlPersons_SelectedItemChanged(object sender, EventArgs e)
    {
        Label1.Text = "message";
        this.GridView1.DataSource = Persons;
        this.GridView1.DataBind();
    }

(Persons is the a list of objects which i have confirmed to contain the information that i require. the label is simply there to see if the method fires. which it also does but the databind will not.)
I have tried many different answers from stackoverflow but none seems to work on my project and im completely lost as to what i should do.
Updated
heres my page load. in the method loadList() i fill the Persons list. its contents will not change.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
        loadList();
        }
    }

As for using ddlPersons.SelectedItem to filter which contents, i have no idea how that is done. I mean i have tried using different ways to access the selected object, but still unsuccessful.
Update 2
The markup of the gridview and dropdownlist
<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField HeaderText ="Nr">
            <ItemTemplate>
                <%# DataBinder.Eval(Container, "DataItem.getSetFirstName") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText ="Namn">
            <ItemTemplate>
                <%# DataBinder.Eval(Container, "DataItem.getSetFirstName") %>
                <%# DataBinder.Eval(Container, "DataItem.getSetLastName") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText ="Ålder">
            <ItemTemplate>
                <%# DataBinder.Eval(Container, "DataItem.getSetAge") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

 <asp:DropDownList ID="ddlPersons" runat="server" OnSelectedItemChanged="ddlPersons_SelectedItemChanged" AutoPostBack="True" OnSelectedIndexChanged="ddlPersons_SelectedItemChanged">
</asp:DropDownList>

A: Since you are manually binding the GridView, you need to use ddlPersons.SelectedValue to filter the contents of the Persons collection.
As for why your GridView isn't populating, it's not a problem with the code you have posted.  You might want to include your GridView and DropDownList markup and whatever code you're using to populate Persons.
Edit:
Assuming you want to filter Persons on one of its properties called category, you can filter a List<Person> for instance, using LINQ with a function like this:
private List<Person> FilterPersonsByCategory(List<Person> liPersons, string strCategory)
{
    return liPersons.Where(p => p.Category = strCategory);
}

Then you could use the function like this:
GridView1.DataSource = FilterPersonsByCategory(Persons, ddlCategory.SelectedValue);

Having said all that, this is assuming your collection Persons is a List<T>, and also keep in mind that the above solution will load the entire result set from the database and filter the list in the web server's memory.  If your data retrieval function returns IQueryable<T>, the function above can be modified slightly to make the DB query more efficient.  Let me know if you're interested in that.
Edit #2
I can't find the reference documentation offhand, but if memory serves GridView.DataSource requires an object that implements IEnumerable interface so the DataBind() process can get an enumerator object to iterate over the data.  Based on your comment it looks like this is part of the problem.

A:  protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
          loadList();
          BindGrid();
        }
    }

Public void BindGrid()
   {
   // Code to Bind Gridview.
   }

See since you have kept your Person as static and it's value never changes,  and you have provided your gridview datasource as Person in ddlPersons_SelectedItemChanged event .So your gridview content do  not changes .
2 . To filter out values You can do one thing on RowDataBound event you can hide all other rows accept one which is related to your dropdown.SelectedValue .
Or create different methods to populate your gridview .
 protected void ddlPersons_SelectedItemChanged(object sender, EventArgs e)
    {
        //Label1.Text = "message";
        //this.GridView1.DataSource = Persons;
       // this.GridView1.DataBind();
       int ddlVal = Convert.toint32(ddlPersons.SelectedValue);
       BindGridUsingDdl(ddlVal);
    }

 Public void BindGridUsingDdl(int ddlVal)
   {
      //Your code to populate gridview
       // Gridview.Datasource = filter your list according
      // to selected value of dropdown.
   }


text:
Q: ServiceBroker - What is sense of types of message? Can anyone to tell me one thing ?
It is about ServiceBroker.
https://gallery.technet.microsoft.com/scriptcenter/Using-Service-Broker-for-360c961a
Following this short tutorial we can come across two thnigs:

CREATE MESSAGE TYPE [//SBM/RequestMessage] VALIDATION=WELL_FORMED_XML;
CREATE MESSAGE TYPE [//SBM/ReplyMessage] VALIDATION=WELL_FORMED_XML;

What is aim of this stuff ?  What benefit from separating messages to two types ?  And second thing:  Is it possible to check if queue was disabled by poison ? I know that then queue is blocked, but I would like to be able to check it.

A: One thing I use message types for is to know how I should process the message without actually having to look at the message itself. Let's say we're creating a system that will deal with conversations from disparate applications that service both the HR and Finance teams. You could argue that those belong in separate queues, but let's assume that all of those messages are going into one queue. In the procedure that I use to dequeue messages from the queue, I would have something like this (simplified):
declare @message_type_name sysname, @message_body xml);
RECEIVE TOP (1)
    @message_type_name = [message_type_name],
    @message_body = CAST([message_body] AS XML)
FROM [repl].[CoreQueue]

IF (@message_type_name = 'TimeOffRequest')
    EXEC dbo.ProcessTimeOffRequest @message_body;
ELSE IF (@message_type_name = 'ReimbursementRequest')
    EXEC dbo.ProcessReimbursementRequest @message_body;

Note I'm employing some anti-patterns here (RECEIVEing only one message at a time, no error handling, etc) in the interest of clarity around your actual question.
Because I know something about the content of the message based on the message type, I can quickly route the message to something that can handle it. Add to that the ability to bundle message types into contracts which can be prioritized with broker priorities and you have a fairly flexible system.


text:
Q: Inversion of control container What is the most important features a IOC container should contain? You can easily create containers in 15 lines of code, but what should it include to be "useful" in a project?

A: In descending order of importance:

*

*Allow at least setter and constructor injection,

*Separate configuration from code,

*Allow different styles of configuration (XML or annotations),

These will require more than 15 lines of code, but those seem key to me.

A: This is a pretty wide open topic, and given to a lot of subjectivity, but I will try and answer from a very pragmatic point of view. Given the projects that I have worked on, and my experience with IoC, I would say that there are at least three biggies to look for in terms of usefulness.

*

*Configuration - Any IoC that you use needs to have some central location that allows you to configure the behavior of that container. Whether that be a config file or a nice set of API calls that can be wrapped up in a global class somewhere, if the container isn't easily configurable then it is going to be a headache.

*Lifetime Management - You really want a container that has the ability to allow for varied object lifetimes. You might want a certain object to always get a new IPersonCreator, but you only want one IPersonService in existence at any given time.

*Automatic Dependency Injection - Ok, so Dependency Injection is the concept that IoC is built on top of, but you don't want to have to manage this yourself. The idea here is that if you ask for an IPersonCreator for the first time, it should resolve all it's dependencies, and their dependencies and so on automatically.

Overall what you need depends on the project, but there are several containers out there that will suit your needs just fine.


text:
Q: How to make a search bar that search content of an external .txt file? Please scroll down as I did update the content, or read from here to understand what I want.
I was wondering if an expert could help me out :)
I'm making a website (not my very best side :D ) that lets users search for their ID if they are banned or not.
Basically this is how it should work:

*

*Users put in 'data'. (ex. 123456789987654321 )

*User press 'Search' button.

*The search script begins after here.

*'It', 'The Web script that I want', goes to the custom URL to search (ex. www.website.com/bans.txt) (URL that I want needs to be uneditable - Only I can edit the URL so users never know the URL or can change it)

*If 'it' finds the 'data' than he gives response to client. (If he finds it he says: 'You are banned.' |OR| If he doesn't find it he says: 'You are not banned.')
I did make a lot of search work. But I couldn't find anything to get to work. I even followed tut's from YouTube but they were all over searching from a file that was already on the machine. What I search is it searches from a URL. (it is also a txet file but on a external site than the search script will be on.)
I did try my best to explain what I try to make. I hope someone will help me out, did spend 5 hours to find something...
--UPDATE--
I did make a searchbar that looks like this:
<div class="search-container">

                            <form action="search.php">
                                <input type="text" placeholder="Add your UID here" name="search">
                                <button type="submit">Search | Am I Banned?</button>
                            </form>
                        </div>

Than I did add a php file like @Justin T. said and it looks like this:
    <?php

$userSearchString = $_POST['searchStrFromForm'];

$secretURL = "censored";
$urlContents=file_get_contents($secretURL);

if(strstr($urlContents,$userSearchString)!=FALSE){
  //found
  echo "You are banned.";
}else{
  //not found
  echo "You are not banned.";
}

?>

However this is not wirking I always get - You are not banned. - as response even if the UID (string that the user searches) exist on that peac of .txt file.
If you want a demo pleas go here and type 'asdasd' wich is not exist in the UID's list and than try typing '76561198151285096' wich it is in the list but still you will see -> You are not banned.

A: I would handle the user's input using PHP and use file_get_contents() to load the contents from the URL you specify into a variable, then search through the variable for the search text using strstr() and other PHP search functions.
Your PHP code would look something like this...
<?php

$userSearchString = $_POST['searchStrFromForm'];

$secretURL = "http://www.yoursecreturl.com";
$urlContents=file_get_contents($secretURL);

if(strstr($urlContents,$userSearchString)!=FALSE){
  //found
  echo "You are banned.";
}else{
  //not found
  echo "You are not banned.";
}

?>

I have not tested this and it may need some tweaking, but should hopefully get you down the right path. Good luck!


text:
Q: Why is ManimCE plotting a different graph than the one provided? I'm trying to create a graph for the function (1+1/x)^x.
I wrote it in python like this:
def func(x):
    return pow(1+(1/x),x)

I then plotted it like this:
graph = axes.plot(lambda x: func(x), color=BLUE, stroke_width=2, x_range=[0,X_MAX])

(X_MAX is a variable that equals 1000)
but for some reason Manim is plotting something else.
When I plotted the function in Desmos I got this graph:

And Manim gave me this one:

(I know the scales are different the main focus is the hump at the top)

A: you need to use small values of dt.
class drawgraph(Scene):
    def construct(self):
        axes= Axes()
        def func(x):
            return pow(1+(1/x),x)
        graph = axes.plot(lambda x: func(x),dt = 0.001, color=BLUE, stroke_width=2, x_range=[0,5])
        self.add(axes, graph)

A: It is the default smoothing that causes these weird oscillations; basically this happens because the function changes too fast in a (relatively) small interval.
Try either passing use_smoothing=False to your call of plot -- and/or alternatively, try refining the step size by passing a third number to the x_range list.


text:
Q: Can someone please explain what this bit of javascript code is doing? So I'm completely new to programming and trying to understand what this piece of javascript code is doing specifically lines 3 and 4 am I right in assuming it's checking the array for the randomly generated number and if it's not present in the array it adds it and then if it's true it will place that number in the document ID?

var numarray = new Array(76);
do {
  var rannum = Math.floor(Math.random() * 76) + 1;
} while (numarray[rannum]);
numarray[gNumber] = true;
document.getElementById(cellID).innerHTML = rannum;

A: var numarray= new Array(76);

It will create array with 76 elements,
do {
           var rannum= Math.floor(Math.random() * 76) + 1;

This will assign a number with in 76
        } while (numarray[rannum]);

This will loop through element of rannum is defined, in your case it will undefined always

var numarray= new Array(76);
do {
           var rannum= Math.floor(Math.random() * 76) + 1;
console.log(rannum);
        } while (numarray[rannum]);
console.log(numarray)

A: Overall, it's picking a random number between 1 and 76 and will continue to do so as long as an item in the array that matches the index of the last generated random number has a non-falsy value.
In your case, the array is only declared to have 76 indexed positions, but the array is never populated, so the array is full of undefined items.
The while part of the loop says that the loop condition is numarry[random], which is a way of testing to see if the item is any "truthy" value (anything that does not implicitly convert to a "false" or "falsy" value like 0, undefined, null, NaN, false, ""). Since your array is full of undefined items, the loop condition is not satisfied the very first time it is checked and the loop only winds up iterating once, thereby generating only one random number.
See the comments inline for details.

var numarray = new Array(76);   // Create new array with 76 indexed positions (or, a .length of 76)

// Start a loop
do {
  // Math.random() - Get a random number between 0 (inclusive) and 1 (exclusive)
  // * 76 - Take the random and multiply by 76 to get a random between 0 (inclusive)
  //        and 76 (exclusive)
  // Math.floor()  - Round the number down to the next whole number
  // + 1 - Instead of the range being 0 (inclusive) and 76 (exclusive) add an offset
  //       so that the final number will be between 1 (inclusive) and 77 (exclusive)
  var rannum = Math.floor(Math.random() * 76) + 1;
} while (numarray[rannum]); // Keep the loop going as long as the array item matching the random
                            // isn't undefined, false, 0, NaN, null or "" (i.e. "truthy").
                            // In this case, the array is empty so the loop will only
                            // iterate one time.

// Set the array item that matches the gNumber value to true.
// You haven't provided any code that declares or initializes gNumber,
// so this line of code really is meaningless in this context.
numarray[gNumber] = true;

// Change the inner content (HTML and text) of the element with an id that matches
// the value in cellID to the random number
document.getElementById(cellID).innerHTML = rannum;

Resources:

*

*new Array()

*Math.random()

*Math.floor()

*do...while

*truthy

*falsy


text:
Q: how to use two arrays in for each loop in php?  foreach($this->input->post('option') as $key => $val and $this->input->post('option_hindi') as $key => $val_hindi){

     if($this->input->post('score')==$key){
         $score=1;
     }else{
         $score=0;
     }

$userdata=array(
 'q_option'=>$val,
 'q_option_hindi'=>$val_hindi,
 'qid'=>$qid,
 'score'=>$score,
 );
 $this->db->insert('savsoft_options',$userdata);

 }

I want to combine these two arrays option and option_hindi and insert them in db


text:
Q: How to use multiple Git repositories in Visual Studio 2017 My solution involves three Git repositories in a self-hosted Bitbucket Server. One repository for the iOS project, one repository for the shared project type such as libraries shared among other projects like Android, and then the company shared repository with more class libraries not project specific.
In Visual Studio 2015 I could go to the Team Explorer and connect to the various repositories, so I could view the commit history and have source control access to commit or pull from Git. In Visual Studio 2017 when I connect to one of the other repositories I am taken out of my solution back to the start page.
How can I manage multiple repositories that make up one Visual Studio 2017 solution? My only option right now is using an external tool such as Sourcetree.

A: The design for Team Explorer has always been to close the solution if the containing Git repository was closed and a different repository was opened. If you were seeing different behavior in Visual Studio 2015, it was unintentional.
We would like to support multiple Git repositories open at the same time in Team Explorer, but that feature has not yet been added.
The Team Explorer extension provides the Git integration for Visual Studio. Regardless of whether you use VSTS or not, you'll still use Team Explorer for Git operations in the IDE. I completely agree that it would be great to support multiple repositories for a single solution. Features are prioritized and this one simply hasn't been built yet.

A: This is currently still unsupported so you will have to drop out to the command line or open multiple instances of Visual Studio.
However, support for this feature has been reported as "planned" and you can vote to increase the priority of this feature on the Visual Studio User Voice site.

A: Both Visual Studio 2015 and Visual Studio 2017 will close a solution if you switch to another Git repository. But you can open three Visual Studio windows to handle these three git repositories at the same time.
Assume the three Git repositories located in D:\Dev\git1, D:\Dev\git2 and D:\Dev\git3, and Visual Studio (works both for Visual Studio 2015 and Visual Studio 2017) is connect with D:\Dev\git1.
You can connect git2 by opening the folder D:\Dev\git2 in Windows Explorer, and open .sln file in D:\Dev\git2 by the same version of Visual Studio, and then Visual Studio will connect with D:\Dev\git2 in another Visual Studio window. You can connect with D:\Dev\git3 by the same way. And you will find three Visual Studio windows opened to connect with the three Git repositories.


text:
Q: What is a fast alternative to HashMap for mapping to primitive types? First of all let me tell you that i have read the following questions that has been asked before Java HashMap performance optimization / alternative and i have a similar question.
What i want to do is take a LOT of dependencies from New york times text that will be processed by stanford parser to give dependencies and store the dependencies in a hashmap along with their scores, i.e. if i see a dependency twice i will increment the score from the hashmap by 1.
The task starts off really quickly, about 10 sentences a second but scales off quickly. At 30 000 sentences( which is assuming 10 words in each sentence and about 3-4 dependences for each word which im storing) is about 300 000 entries in my hashmap.
How will i be able to increase the performance of my hashmap? What kind of hashkey can i use?
Thanks a lot
Martinos
EDIT 1:
ok guys maybe i phrased my question wrongly ok , well the byte arrays are not used in MY project but in the similar question of another person above. I dont know what they are using it for hence thats why i asked.
secondly: i will not post code as i consider it will make things very hard to understand but here is a sample:
With sentence : "i am going to bed" i have dependencies:
(i , am , -1)
(i, going, -2)
(i,to,-3)
(am, going, -1)
.
.
.
(to,bed,-1)
These dependencies of all sentences(1 000 000 sentences) will be stored in a hashmap.
If i see a dependency twice i will get the score of the existing dependency and add 1.
And that is pretty much it. All is well but the rate of adding sentences in hashmap(or retrieving) scales down on this line:
dependancyBank.put(newDependancy, dependancyBank.get(newDependancy) + 1);
Can anyone tell me why?
Regards
Martinos

A: Trove has optimized hashmaps for the case where key or value are of primitive type.
However, much will still depend on smart choice of structure and hash code for your keys.
This part of your question is unclear: The task starts off really quickly, about 10 sentences a second but scales off quickly. At 30 000 sentences( which is assuming 10 words in each sentence and about 3-4 dependences for each word which im storing) is about 300 000 entries in my hashmap.. But you don't say what the performance is for the larger data. Your map grows, which is kind of obvious. Hashmaps are O(1) only in theory, in practice you will see some performance changes with size, due to less cache locality, and due to occasional jumps caused by rehashing. So, put() and get() times will not be constant, but still they should be close to that. Perhaps you are using the hashmap in a way which doesn't guarantee fast access, e.g. by iterating over it? In that case your time will grow linearly with size and you can't change that unless you change your algorithm.

A: Google 'fastutil' and you will find a superior solution for mapping object keys to scores.

A: Take a look at the Guava multimaps: http://www.coffee-bytes.com/2011/12/22/guava-multimaps They are designed to basically keep a list of things that all map to the same key. That might solve your need.

A:
How will i be able to increase the performance of my hashmap?

If its taking more than 1 micro-second per get() or put(), you have a bug IMHO.  You need to determine why its taking as long as it is.  Even in the worst case where every object has the same hasCode, you won't have performance this bad.

What kind of hashkey can i use?

That depends on the data type of the key. What is it?

and finally what are byte[] a = new byte[2]; byte[] b = new byte[3]; in the question that was posted above?

They are arrays of bytes.  They can be used as values to look up but its likely that you need a different value type.

A: An HashMap has an overloaded constructor which takes initial capacity as input. The scale off you see is because of rehashing during which the HashMap will virtually not be usable. To prevent frequent rehashing you need to start with a HashMap of greater initial capacity. You can also set a loading factor which indicates how much percentage do you load the hashes before rehashing.
public HashMap(int initialCapacity).
Pass the initial capacity to the HashMap during object construction. It is preferable to set a capacity to almost twice the number of elements you would want to add in the map during the course of execution of your program.


text:
Q: A layout is set, but the QWidget still looks empty I'm currently working on a basic school project, and I can't figure how to solve a problem that I'm currently encountering. Please keep in mind that I'm a beginner in both C++ and Qt, so the error might be trivial (and I'd like it to be!)
I'm trying to use a class which I developed recently: ArticleEditor. This class inherits from QWidget and is basically meant to be a small window where you can edit articles (a title and a text) and save modifications. For now, I've managed to use this class in a basic way, by creating an instance of ArticleEditor and show it in a main.cpp file, but now I'm trying to do something more tricky.
The point is to open an ArticleEditor widget/window after picking a file. I've achieved the file picking part without issues, but when I've chosen my file, the ArticleEditor widget opens and... is totally empty. The size which I set in a setSize inside its constructor is taken into account, but the widgets I'm setting and adding into the layout, also in the constructor, are not present, nor visible.
Here is my code, which should help you to understand the situation :
ArticleEditor.cpp :
enableSave() is meant to enable the save button when you edit one of the two text fields, saveArticle() is another method which is not important here.
ArticleEditor::ArticleEditor(Article* article, QWidget *parent) :
    QWidget(parent)
{
    title = new QLineEdit();
    title->setFixedWidth(180);
    title->move(10,10);

    text = new QTextEdit();
    text->setFixedSize(180,110);
    text->move(10,45);

    save = new QPushButton();
    save->setText("Save");
    save->setFixedWidth(80);
    save->move(10,170);
    save->setEnabled(false);

    title->setText(article->getTitle());
    text->setText(article->getText());

    QObject::connect(save, SIGNAL(clicked()), this, SLOT(saveArticle()));
    QObject::connect(title, SIGNAL(textChanged(const QString)), this, SLOT(enableSave()));
    QObject::connect(text, SIGNAL(textChanged()), this, SLOT(enableSave()));

    layout = new QVBoxLayout;
    layout->addWidget(title);
    layout->addWidget(text);
    layout->addWidget(save);

    this->setFixedSize(200,200);
    this->setLayout(layout);
}

ArticleEditor.h
class ArticleEditor : public QWidget
    {
        Q_OBJECT
    public:
        explicit ArticleEditor(Article* article, QWidget* parent);

    private:
        QLineEdit* title;
        QTextEdit* text;
        QPushButton* save;
        QVBoxLayout* layout;
        Article* ressource;

    public slots:
        void saveArticle();
        void enableSave();

    private slots:

    };

After picking a file (I'm not gonna give details about this because getting the path is working fine already), I do something like:
ArticleEditor aE(&a, articleWidget); // calling the constructor with an article I've fetched using the path, and setting articleWidget (a private attribute) to be the parent
articleWidget->show(); // showing the result

Here, articleWidget is an attribute of my class, created to be the articleEditor instance's parent widget.
I've also tried setting directly the layout to the parent widget (parent->setLayout(layout) instead of this->setLayout(layout), but whenever I do this, the content of the widget shows, but my signals/slots connections are not working anymore...
If someone could explain me what I'm doing wrong, I'd be very grateful.
EDIT : I just noticed that even after adding the widgets to my layout, when I try layout->isEmpty(), I get true as return value...

A: I think in ArticleEditor.cpp you need to make your layout a child of the widget
layout = new QVBoxLayout(this);

Your widgets should also be children of the ArticleEditor widget; i.e. title, text and save.

A: The class itself is fine, though, you really should use approach, that koan recommended, it gives a lot more clarity to the code.
Your problem is that you set parent of your ArticleWidget, but didn't added layout to it. So istead of
ArticleEditor aE(&a, articleWidget);
articleWidget->show(); // showing the result (by the way, if you are not using new, when create widget, it shuold be articleWidget.show();)

Do something like this:
ArticleEditor aE=new ArticleEditor(&a, articleWidget); //creating articleEditor aE with articleWidget as parent

QVBoxLayout* articleWidgetLayout=new QVBoxLayout(articleWidget); // creating layout in articleWidget
articleWidgetLayout->addWidget(aE); //adding aE to it

articleWidget->show(); // showing the result


text:
Q: Node.js consumption of json from Rails app I have a json string (coming from my Rails app):
http://localhost:3000/employees/1.json

How do I get my Node.js app to consume this data?
This is the code I have in my Node.js app right now:
var employees = JSON.parse("http://localhost:3000/employees.json")

This is the error I'm getting:

prompt$ node app.js

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
SyntaxError: Unexpected token h
    - at Object.parse (native)
    - at Object. (/Documents/Coding/dustin/employees.js:19:22)
    - at Module._compile (module.js:441:26)
    - at Object..js (module.js:459:10)
    - at Module.load (module.js:348:31)
    - at Function._load (module.js:308:12)
    - at Module.require (module.js:354:17)
    - at require (module.js:370:17)
    - at Object. (/Documents/Coding/dustin/app.js:34:17)
    - at Module._compile (module.js:441:26)

A: See this question:
Using Node.JS, how do I read a JSON object into (server) memory?
You should read the file first and then parse it.
var employees = JSON.parse(fs.readFileSync('employees.json', 'utf8'));

If for some reason your Rails app runs on some other machine, you need to make a http request for that. You could try this:
var site = http.createClient(port, host);

var request = site.request("GET", pathname, {'host' : host});
request.end();

request.on('response', function(response) {
  var json = '';

  response.on('data', function(chunk) {
    json += chunk;
  });

  response.on('end', function () {
    employees = JSON.parse(json);
  });
});


text:
Q: Acceptable types to use as keys in a HashTable I must admit to having only a rudimentary understanding of how HashTables work, although from what little I do know it seems fairly straightforward. My question is just this: it seems that the conventional wisdom is to use simple, basic value types such as integers for the keys in a HashTable. However, strings are also often used, even though in many languages they are implemented as reference types. What I feel is generally not encouraged is using complex reference types; I'm guessing this is because doing so would necessitate a slower hash function? But then why are strings so commonly used? After all, isn't a string internally a char[] array (again, in most languages)?
In the end, what value types are generally regarded as the "best" (or even simply "acceptable") choices to use as keys in a HashTable? And are there any commonly used choices that are actually regarded as "bad" (like strings, possibly)?

A: It's not a matter of strings versus integers, or value versus reference, but of mutable keys versus immutable keys. As long as the keys are immutable (and thus their hashing value never change) they are OK to index a hash table. For instance, strings in Java are immutable and thus perfectly suited as hashtable keys.
By the way, if a data type is simpe enough to be always passed by value (like scalars), then it will of course be OK.
But now imagine that you use a mutable type ; if you give me a reference to one of these objects as a key, I will compute its hash value and then put it in one of my hashtable buckets. But when you later modify the object, I will have no way to be notified ; and the object may now reside in the wrong bucket (if its hash value is different).
Hope this helps.

A: Most string implementations, while they might appear as references types in managed environments their implementation is typically an immutable type.
What the hash function does is that it maps a very large number of states onto a smaller number of states.
That is why string hashing is good for testing string equality. You can map the value to an index of an array, and look up some information about that value very quickly. You don't need to compare every character with every other character in every other string. And you can say just about the same thing about anything. It's all about reducing, or fingerprinting an arbitrary number of bytes in some manner which is useful.
This is where the discussion about the type of key you use in a hash table becomes invalid, because it's the mapping of that value into a smaller state space and how that's utilized internally which makes it useful. An integer is typically hardware friendly, but 32-bits isn't really a large space and collisions are likely within that space for arbitrary inputs.
In the end, when you do use a hash table, the cost of calculating the hash value is irrelevant compared to the time it would take to compare every value with every other value in every other possible position (assuming that your hash table contains hundreds of items).

A: As long as a suitable hash function is provided all types will do as keys. Remember after all a hash table is just a linear array. The hash function takes a key of a certain type and computes an index in the hash table array (called bucket) where the value gets stored (there are some issues with collisions though).
So the real tricky part is finding a hash function. Of course it should have certain properties, like being simple to compute, chaotic (nearly identical keys should be mapped to completly different hash table buckets), deterministic (same keys means same hash table bucket), uniformity (all possible keys are mapped evenly to the buckets), or surjectivity (all buckets of the hash table should be used).
It seems it is easier to define such a function for simple types like integers.

A: The best hash keys are those that

*

*Have good (as in low collisions) hashes (see Object.GetHashCode for .NET, Object.hashcode for Java)

*Have quick comparisons (for when there are hash collisions).

All that said, I think Strings are good hash keys in most cases, since there are many excellent hash implementations for Strings.

A: If you were to use a complex type as a key then:

*

*It would be hard for the hash table implementation to group items into buckets for fast retrieval; how would it decide how to group a range of hashes into a bucket?

*The hash table may need to have intimate knowledge of the type in order to pick a bucket.

*There is the risk of the properties of the object changing, resulting in items ending up in the wrong buckets. The hashes must be immutable.

Integers commonly used because they are easy to split into ranges that correspond to the buckets, they are value types and therefore immutable, and they are fairly easy to generate.


text:
Q: How to create a table by iterating words in sentence in python? For the example given below, I would like to create a table for the list of 'Directors' and 'Stars'. The idea is to iterate the sentences, detect words which exist between word 'Director:' and 'Stars:' and put into respective cells.
The sentence.
Director:
Peter
Jackson,
John
Marsh
Stars:
Elijah
Wood,
Ian
McKellen,
Orlando
Bloom,
Sean
Bean

Full list of words
https://justpaste.it/3qjc4
Table to create

Director
Stars

Peter Jackson
Elijah Wood

John Marsh
Ian McKellen

Orlando Bloom

Sean Bean

A: Try this:
import pandas as pd

l=[]
with open('yourtxtfile.txt') as f:
    for i in f:
        l.append(i)

l=[i.replace('\n', '') for i in l]

Director=l[1:l.index('Stars')]
Stars=l[l.index('Stars')+1:]

for i in range(len(Director)-len(Stars)):
    Director.append('')

df=pd.DataFrame({'Director':Director, 'Stars':Stars})


text:
Q: AngularJS nested views & controllers Below is my application layout:

app.html code is below:
<!DOCTYPE html>

    <title>My AngularJS App</title>

Admin

Sales

Purchase

/static/app/controllers.js is:
var app = angular.module('MyApp', []);

app.controller('AppCtrl', ['$scope', '$location',
    function ($scope, $location) {

        $scope.$watch(
            function () {
                return $location.path();
            },
            function (path) {
                var moduleName = path.split("/")[1];
                if (moduleName) {
                    $scope.view = { url: "/static/app/" + moduleName + "/" + moduleName + ".html" };
                }
            });

    } ]);

Now let say admin.html is:

Admin

and sales.html, and purchase.html are just about the same. Then my app's navigation works just as expected; when admin link is clicked, admin.html is loaded and shown.
But if admin.html is as follows:

Admin

and /app/admin/controllers.js is
var admin = angular.module('MyApp.Admin', []);

admin.controller('AdminCtrl', ['$scope', '$location',
    function ($scope, $location) {

    } ]);

then when admin link is clicked, the following error is thrown in Google Chrome console:
Error: Argument 'AdminCtrl' is not a function, got undefined
    at Error (<anonymous>)

If I move AdminCtrl to /app/controllers.js, then it works; but I would prefer it to be in its own directory. Can someone help me with this? Also, next step is to display "subView", similar way as "view" is navigated. Any hint on this will be much appreciated.

A: You need to connect your MyApp module (in its definition) with your MyApp.Admin modulelikes this:
angular.module('MyApp', ["MyApp.Admin"]);
But for a larger app, you might want to look at the UI-Router project instead...


text:
Q: tornado/graphlab Cannot assign requested address in docker Running gl.canvas.set_target('ipynb') throws following exeption in docker container.
Even with gl.canvas.set_target('ipynb', port=28892) where 28892 is an open port, the error stays the same.
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-257-3f215a521352> in <module>()
----> 1 gl.canvas.set_target('ipynb')

/opt/conda/envs/gl-env/lib/python2.7/site-packages/graphlab/canvas/utils.pyc in set_target(target, port)
    102             # and to preserve backwards compatibility/other use cases
    103             # (running a notebook exported to .py, for instance)
--> 104         _active_target = targets[target]()
    105
    106     # track metrics on target

/opt/conda/envs/gl-env/lib/python2.7/site-packages/graphlab/canvas/target.pyc in __init__(self, port)
     25         self.state = graphlab.canvas.state.State()
     26         # TODO server is not necessary in static IPython/Jupyter Notebook
---> 27         self.server = graphlab.canvas.server.Server(self.state, port)
     28         # add data objects to left nav
     29         DataView = graphlab.canvas.views.data_objects.DataObjectsView()

/opt/conda/envs/gl-env/lib/python2.7/site-packages/graphlab/canvas/server.pyc in __init__(self, state, port)
     44
     45         #Will raise exception if port cannot be bound
---> 46         self.__bind_socket(port)
     47
     48     # methods

/opt/conda/envs/gl-env/lib/python2.7/site-packages/graphlab/canvas/server.pyc in __bind_socket(self, port)
     93     # Raises exception if socket cannot be bound on requested port
     94     def __bind_socket(self, port=None):
---> 95         sockets = tornado.netutil.bind_sockets(port,"localhost")
     96         self.__server.add_sockets(sockets)
     97         with self.__port_lock:

/opt/conda/envs/gl-env/lib/python2.7/site-packages/tornado/netutil.pyc in bind_sockets(port, address, family, backlog, flags, reuse_port)
    194
    195         sock.setblocking(0)
--> 196         sock.bind(sockaddr)
    197         bound_port = sock.getsockname()[1]
    198         sock.listen(backlog)

/opt/conda/envs/gl-env/lib/python2.7/socket.pyc in meth(name, self, *args)
    226
    227 def meth(name,self,*args):
--> 228     return getattr(self._sock,name)(*args)
    229
    230 for _m in _socketmethods:

error: [Errno 99] Cannot assign requested address

It looks like more of a docker/tornado problem than graphlab issue, because in host machine the same command works.
I started my docker container using following command:
sudo docker run -it -v /path/to/data:/root/data \
    -v ~/code/work/src:/root/src \
    -p 8888:8888 -p 28892:28892 company/graphlab \
    /bin/bash -c "source activate gl-env && jupyter notebook --notebook-dir=~/src --ip='*' --port=8888 --no-browser"

Is there a way to figure out this port so that I can open it or any other way to fix this issue?

A: Editing your /etc/hosts file (inside the container) to only contain 1 ip address value for localhost solves the issue for me. It only works if you edit it on the running container. Editing it when building the image does not solve the problem.
At start-up from the container my /etc/hosts have the lines:
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback

I had to change those to:
127.0.0.1   localhost
::1 ip6-localhost ip6-loopback

A: The other answer by ForcaeLuz is on the good path, but only treats the symptoms.
Seems like it was recently fixed in Tornado in this commit, where the comments are very useful to see (how Docker's default configuration gives rise to this, for example).

On some systems (most notably docker with default configurations), ipv6 is partially disabled: socket.has_ipv6 is true, we can create AF_INET6 sockets, and getaddrinfo("localhost", ..., AF_PASSIVE) resolves to ::1, but we get an error when binding.

It's not yet released (as of the time of this writing), but could get it installing tornado from its master branch, e.g. by running
pip install --upgrade git+https://github.com/tornadoweb/tornado.git@master#egg=tornado

(or similar), or waiting for (I think) version 6.1.0 that should include this change. Tried it with some other projects that use tornado underneath and running into issues when within Docker, and it was all good after this.


text:
Q: Aggregate data when dealing with both continuous and categorical data I have the following data:

There are six customers who took out loans multiple times offered by Agents. Agents serve multiple customers. For example Agent 306 provided loans to Customer 1 and 2. Similarly, Agent 309 provided loans to Customer 5 and 6. I would like to aggregate the amount of loans each customer took and get something like in the table below. It is important I see the gender of the customer and agent after aggregation.

I tried the following code:

import pandas as pd

data = {'Customer_ID': [1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 5, 6, 6],
      'Loan': [200, 250, 300, 400, 300, 500, 150, 150, 400, 250, 150, 300, 200, 200],
     'CustomerGender': ['M', 'M', 'M', 'F', 'F', 'M', 'M', 'M', 'F', 'F', 'F', 'F', 'F', 'F'],
     'Agent_ID': [306, 306, 306, 306, 306, 307, 308, 308, 309, 309, 309, 309, 309, 309],
     'AgentGender': ['F', 'F', 'F', 'M', 'M','M', 'M', 'M', 'F', 'F', 'F', 'F', 'F', 'F'],
     'settlement_value': [23.5, 30.99, 306, 86, 50, 307.35, 1200.54, 25, 48.88, 400, 2100.10, 30, 1309.10, 500.50]}

# transform to dataframe

data = pd.DataFrame(data)

# declare the two gender columns categorical

data['AgentGender']=data['AgentGender'].astype('category')

data['CustomerGender']=data['CustomerGender'].astype('category')

# aggregate the data by Customer_ID to see the total amount of loan each customer took.

data.groupby(data['Customer_ID']).sum()

What I get is the following:

How can I aggregate by Customer_ID and be able to see the gender of customers and agents please? Many thanks.

A: choose all the columns you need within a groupby and sum Loan amount
df.groupby(['Customer_ID','Customer_Gender','Agent_ID', 'Agent_Gender'])['Loan'].sum().reset_index()

or
if you are converting the columns to categories, add observed=True parameter
df.groupby(['Customer_ID','Customer_Gender','Agent_ID', 'Agent_Gender'], observed=True)['Loan'].sum().reset_index()

    Customer_ID     Customer_Gender     Agent_ID    Agent_Gender    Loan
0   1                       M                306    F                750
1   2                       F                306    M                700
2   3                       M                307    M                500
3   4                       M                308    M                300
4   5                       F                309    F                1100
5   6                       F                309    F                400


text:
Q: How can I detect a SQL table's existence in Java? How can I detect if a certain table exists in a given SQL database in Java?

A: You can use DatabaseMetaData.getTables() to get information about existing tables.
This method works transparently and is independent of the database engine. I think it queries information schema tables behind the scenes.
Edit:
Here is an example that prints all existing table names.
DatabaseMetaData md = connection.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
  System.out.println(rs.getString(3));
}

A: For ALL ANSI-compliant databases:
(mySQL, SQL Server 2005/2008, Oracle, PostgreSQL, SQLLite, maybe others)
select 1 from information_schema.tables where table_name = @tableName

A: Use java.sql.DatabaseMetaData.getTables(null, null, YOUR_TABLE, null). If the table exists, you will get a ResultSet with one record.
See DatabaseMetaData.getTables

A: This is not a language-specific, but a database-specific problem. You'd query the metadata in the database for the existence of that particular object.
In SQL Server for instance:
SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[table]')
   AND type in (N'U')

A: Write a query that queries the table/view that will list the tables (this is different depending on DB vendor). Call that from Java.
Googling information_schema.tables will help a lot.

A: Depending on the DB, you can do (MySQL)
SHOW TABLES

or (Oracle)
SELECT * FROM user_objects WHERE object_type = 'TABLE'

or another thing for SQL Server.  Cycle through the results for MySQL or further filter on the Oracle one.

A: Why not just see if it is in sysobjects (for SQL Server)?
SELECT [name] FROM [sysobjects] WHERE type = 'U' AND [name] = 'TableName'

A: There is a JDBC feature, database vendor independent - see [java.sql.DatabaseMetaData#getTables()][1]
You can get the DatabaseMetaData instance by calling java.sql.Connection#getMetaData()
[1]: http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String, java.lang.String, java.lang.String, java.lang.String[])

A: This is what worked for me for jdbc:derby:
//Create Staff table if it does not exist yet
String tableName = "STAFF";
boolean exists = conn.getMetaData().getTables(null, null, tableName, null).next();
if(!exists){
    s = conn.createStatement();
    s.execute("create table staff(lastname varchar(30), firstname varchar(30), position varchar(20),salary double,age int)");
    System.out.println("Created table " + tableName);
}

Note that tableName has to be all caps.

A: For MS Access:
Select Count(*) From MSysObjects
Where type=1 And name='your_table_name_here'


text: Q: How to programmatically switch display from browser to standalone mode in pwa I would like to restrict my user base that can display the PWA in standalone mode, to standalone mode. Is it possible to trigger this action via a button like the install prompt?


text:
Q: Gradle cannot resolve symbol while it does I've the following build.gradle file:
import org.jetbrains.kotlin.gradle.tasks.FatFrameworkTask

apply plugin: 'kotlin-multiplatform'
apply plugin: 'com.android.library'

android {
    compileSdkVersion 28
    defaultConfig {
        minSdkVersion 19
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.jetbrains.kotlin:kotlin-test'
    testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
    testImplementation 'com.google.truth:truth:0.42'

    androidTestImplementation 'junit:junit:4.12'
    androidTestImplementation 'org.jetbrains.kotlin:kotlin-test'
    androidTestImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
    androidTestImplementation 'com.google.truth:truth:0.42'
}

kotlin {
    targets {
        jvm("jvm")
        android("android")
        iosArm32("ios32")
        iosArm64("ios64")
        iosX64("emulator")

        configure([ios32, ios64, emulator]) {
            binaries.framework('HyModule')
        }
    }

    sourceSets {
        commonMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib-common'
        }
        jvmMain.dependencies {
            api 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
        }
        androidMain.dependencies {
            implementation 'org.jetbrains.kotlin:kotlin-stdlib'
        }
        androidMain.dependsOn jvmMain
    }

    task fatFramework(type: FatFrameworkTask) {
        // the fat framework must have the same base name as the initial frameworks
        baseName = "HyModule"

        final File frameworkDir = new File(buildDir, "xcode-frameworks")
        destinationDir = frameworkDir

        // specify the frameworks to be merged
        from(
                targets.ios32.binaries.getFramework('HyModule', 'RELEASE'),
                targets.ios64.binaries.getFramework('HyModule', 'RELEASE'),
                targets.emulator.binaries.getFramework('HyModule', 'RELEASE')
        )

        doLast {
            new File(frameworkDir, 'gradlew').with {
                text = "#!/bin/bash\nexport 'JAVA_HOME=${System.getProperty("java.home")}'\ncd '${rootProject.rootDir}'\n./gradlew \$@\n"
                setExecutable(true)
            }
        }
    }
}

// workaround for https://youtrack.jetbrains.com/issue/KT-27170
configurations {
    compileClasspath
}

tasks.build.dependsOn fatFramework

import org.jetbrains.kotlin.gradle.tasks.FatFrameworkTask is marked in red with an error

Cannot resolve symbol 'FatFrameworkTask'

Even though everything works just fine, I don't like having error in my project.

A: Try
import org.jetbrains.kotlin.gradle.tasks.*

I was facing same problem,
Don't know why this works

A: If the Gradle Task is working fine can be a visual bug in IntelliJ, this happens normally with me.
Try to restart the IntelliJ or Android Studio

A: In my case, don't use import, use class full path instead, for ex, following org.jetbrains.kotlin.gradle.tasks.KotlinCompile
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
    kotlinOptions {
        freeCompilerArgs = ['-Xjsr305=strict']
        jvmTarget = '17'
    }
}


text:
Q: Build Lite and Full Version of app I'm creating an app that will have a Lite and a Full version of it, one being free and the other having a small fee. Since I don't want to have to distinct projects to avoid updating errors (like updating a module in one version only) I set up a boolean in my Application class.
I was wondering how can I determine the value of that boolean with information from the app. I know I can create app with different Flavors and Build Types but I'm kind of lost in all that. Can you help?
Thanks!

A: I assume you're using Gradle and AndroidStudio, right?
You can create BuildConfig values for each flavor and/or buildType:

*

*Goto your app/build.gradle file

*If you prefer to put your variable at
a. buildType:
buildTypes {
    debug {
        versionNameSuffix "-beta"
        buildConfigField "Boolean", "PAYED", "false"
    }
}

b. flavor
productFlavors {
    premium {
        buildConfigField "Boolean", "PAYED", "true"
    }
}

And than, after a sync & build you can access those variables in your code depending on build/flavor you've chosen:
if (BuildConfig.PAYED) {
    // Do your stuff
    ...
}


text:
Q: Gulp doesn't notice my file changes I'm working on a project with a few others. While they get Gulp to work, it doesn't seem to work on my computer, even through our code is identical.
When I write the 'gulp' command, I get this:
[10:51:17] Starting 'browserify'...
[10:51:19] Finished 'browserify' after 2.37 s
[10:51:19] Starting 'default'...
[10:51:19] Finished 'default' after 17 μs

But when I save the changes in the files Gulp is suppose to be watching, the 'update' event doesnt seem to be triggered.
Here is the Gulp file
var gulp        = require("gulp"),
jest        = require("gulp-jest"),
source      = require('vinyl-source-stream'),
browserify  = require('browserify'),
watchify    = require('watchify'),
reactify    = require('reactify');
require("harmonize")();

var paths = {
   scripts: "src/**/*.js",
   tests: "__tests__"
};

gulp.task("jest", function () {
    return gulp.src(paths.tests).pipe(jest({
        scriptPreprocessor: "preprocessor.js",
        unmockedModulePathPatterns: [
            "../node_modules/react"
        ],
        testPathIgnorePatterns: [
            "node_modules",
            "spec/support"
        ],
        moduleFileExtensions: [
            "js",
            "json",
            "react"
        ]
    }));
});

gulp.task('browserify', function() {
    var bundler = browserify({
        entries: ['./src/js/TopLevel.js'],
        transform: [reactify],
        debug: true,
        cache: {}, packageCache: {}, fullPaths: true
    });
    var watcher  = watchify(bundler);

    return watcher
    .on('update', function () { // When any files update
        var updateStart = Date.now();
        console.log('Updating!');
        watcher.bundle() // Create new bundle that uses the cache for high performance
        .pipe(source('main.js'))
        .pipe(gulp.dest('./public/assets/js'));
        console.log('Updated!', (Date.now() - updateStart) + 'ms');
    })
    .bundle() // Create the initial bundle when starting the task
    .pipe(source('main.js'))
    .pipe(gulp.dest('./public/assets/js'));
});

gulp.task("watch", function() {
  gulp.watch("src/**/*.js", ["jest"]);
  gulp.watch("__tests__/*.js", ["jest"]);
});

gulp.task("default", ["browserify"]);

However, I don't think there is anything wrong with the code, as it works for my other team members.
Any help and comments are highly appreciated!

A: Try this:
gulp.task("watch", function() {
  gulp.watch("./src/**/*.js", ["jest"]);
  gulp.watch("./__tests__/*.js", ["jest"]);
});

A: If you are only running gulp in the command line the watch task will not trigger since the default task is only running browserify, just change your default task to this.
gulp.task("default", ["browserify", "watch"]);


text:
Q: Query Enum type on Prisma I am trying to run a query on a simple prisma entity User.
Model:
model User {
  id           Int              @id @default(autoincrement())
  name         String?
  email        String           @unique
  role         Role             @default(USER)
}

Entity User includes a prop called Role with a type of enum.
Role enum:
enum Role {
  USER
  ADMIN
}

Except doing it in raw SQL query, how is this possible to do with Prisma where API:
const whereNameIs = await prisma.user.findMany({
  name: 'Rich',
  role: ?
})

Any custom enum type written in TS or conversion won't match. Is there any workaround in typescript for this?

A: Prisma library gives named export of any enum types you have defined in the schema file:
import { Role } from '@prisma/client'

app.get('users', async (req, res) => {
  const users = await prisma.user.findMany({
    name: 'Rich',
    role: Role.ADMIN
  });
});

if you receive the value dynamically, say through a query string, then it would be as follows:
const { role } = req.query;

const users = await prisma.user.findMany({
  name: 'Rich',
  role: Role[role as keyof typeof Role]
});


text:
Q: Find all homomorphic images of $\mathbb{Z}_{36}$ up to an isomorphism I think there is exactly one homomorphic image of $\mathbb{Z}_{36}$ up to an isomorphism, for each divisor of the group's order: $\{1, 2, 3, 4, 6, 9, 12, 18, 36\}$, as the group $\mathbb{Z}_{36}$ being abelian implies that each of its subgroups is normal. Therefore, there exists a homomorphism $\mathbb{Z}_{36} \rightarrow \mathbb{Z}_{36}/\mathbb{Z}_{k}$ for each divisor $k$.
I don't know how to proceed from there. In particular:

*

*How to give an example of such homomorphism for each of the divisors?

*How to construct a general isomorphism between the images of homomorphisms possible for a divisor?

*How to prove there aren't any more homomorphic images?

A: The quotient maps you suggest are already examples of such homomorphisms. Though the subgroups of $\Bbb{Z}_{36}$ aren't of the form $\Bbb{Z}_k$, they are only isomorphic to $\Bbb{Z}_k$ for some $k$ dividing $36$.
To prove that there aren't any more homomorphic images, you might use the isomorphism theorem. This also tells you that if two homomorphisms from $\Bbb{Z}_{36}$ have the same kernel, then their images are isomorphic.

A: Hint: The image of a cyclic group is cyclic. The image of finite group of order $n$ is a finite group of order $d$ with $d$ a divisor of $n$.

A: Hint :  If you were to seek all homomorphic images of a group G you could do it by never leaving G as follows :
Find all normal subgroups N of G and construct all groups G/N. The set of groups so constructed yields all homomorphic images of G (up to isomorphism).