text:
Q: Azure Active Directory Authentication 401, Bearer Token The signature is invalid I have Web API application in .NET CORE 5 and client app in Angular 10. I have registered both application in Azure Active Directory for Authentication purpose. I have successfully generate token in Angular app by providing the user credential but get 401 error when I make the API call. The http response confirms the The signature is invalid. I have tried various things but no luck. I am using library @azure/msal-angular' on angular side
error

www-authenticate: Bearer error="invalid_token", error_description="The signature is invalid"

Web API
appsettings.json
AzureAd": {
"Domain": "MyDomain.onmicrosoft.com",
"Tenant": "MyDomain.onmicrosoft.com",
"TanantId": "3xxxxxxx-zzzz-yyyy-bwww-00000000000",
"Instance": "https://login.microsoftonline.com/",
"ClientId": "8f9c5e55-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Audience": "8f9c5e55-xxxxxxxxxxxxxxxxxxxxxxxxxxx",
"Issuer": "https://login.microsoftonline.com/3xxxxxxx-zzzz-yyyy-bwww-00000000000/v2.0",
"ResourceId": "https://MyDomain.onmicrosoft.com/8f9c5e55-xxxxxxxxxxxxxxxxxxxx",
"CallbackPath": "/signin-oidc"

Starup.cs
 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(jwtConfig =>
            {
                jwtConfig.Audience = configuration["AzureAdB2C:ResourceId"];
                jwtConfig.Authority = $"{configuration["AzureAdB2C:Instance"]}{configuration["AzureAdB2C:TanantId"]}";
                jwtConfig.SaveToken = true;
                jwtConfig.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidAudience = jwtConfig.Audience
                };
                jwtConfig.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = AuthenticationFailed,
                    OnMessageReceived = OnMessageReceived,
                    OnTokenValidated = OnTokenValidated
                };
            });

   services.AddCors(options =>
          options.AddPolicy("CorsPolicy", builder =>
          {
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

   private static Task AuthenticationFailed(AuthenticationFailedContext context)
   {

   }

   private static Task OnMessageReceived(MessageReceivedContext context)
   {
   }

   private static Task OnTokenValidated(TokenValidatedContext arg)
   {
   }

Angular
following code call the API along with token in header
const myheaders = new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${this.token}`,
});

this.http.get('https://localhost:44362/v2/Site/GetSecureMessage', {headers: myheaders})
    .subscribe((data)=>{
        console.log(data);
    })

}
Current Scope on Web API Application

A: You need to make sure that when you are acquiring the token, you use a scope defined for your API and not e.g. "User.Read".
You seem to have received an access token for Microsoft Graph API, which won't work with your API.


text:
Q: Exponential distribution Max(X,Y) This problem appeared in a past Quiz. I'm still not able to solve it:
Note(λ = 1/B). Suppose X~exponential(λ = 1), Y ~ exp(λ = 1) and Z ~ exp ( λ = 3)
Find P(max(X,Y) > 10) and E(max(X,Z)).
I know that for exponential distribution
max(X,Y) = min(X,Y) + R. (Where R is the remaining lifetime).
However I don't know how to use this fact to solve a problem

A: \begin{align}
& \frac d {dx} \Pr( \max\{X,Z\} \le x) = \frac d {dx} \Pr(X\le x\ \&\ Z\le x) \\[10pt]
= {} & \frac d {dx} \big( (1 - e^{-x})(1-e^{-3x}) \big) = \frac d{dx}( 1 -e^{-x} - e^{-3x} + e^{-4x}) \\[8pt]
= {} & e^{-x} + 3e^{-3x} - 4e^{-4x}.
\end{align}
So look for $\displaystyle\int_0^\infty x(e^{-x} + 3e^{-3x} - 4e^{-4x}) \, dx,$ remembering that $\displaystyle\int_0^\infty xe^{cx} \, dx = \frac 1 {c^2}. $

redpajama_set_name: RedPajamaStackExchange


text:
Q: A big list of Narayana-enumerated objects By a Narayana-enumerated object I mean an object whose count is given by the Narayana number $N(n,k)=\frac{1}{n} {n \choose k} {n \choose k-1}$. Can you give me a reference to some good big list of Narayana-enumerated objects? I have found two Narayana-enumerated objects (the two objects being closely related one to another) and would like to see whether my two objects are in the list.

A: Elements of the sets enumerated by super-Catalan numbers contains many Narayana-enumerated objects. (The super-Catalan number $s_n$ is related to the Narayana numbers by $s_n=\sum_{k=1}^n 2^{k-1}N_{n,k}$.)
Some examples:
The following five parameters of Dyck paths are enumerated by Narayana numbers:
(i) number of high peaks;
(ii)number of valleys;
(iii)number of doublerises;
(iv) number of rises at an even level;
(v) number of nonfinal ascents and descents of length greater than 1.
132-avoiding permutations with given number excedances ($a_i > i$) are counted by Narayana numbers, as well as those with given number descents ($a_i<i$).


text:
Q: Method "session:peer:didChangeState" I read that article : " http://www.devx.com/wireless/Article/43502/0/page/1 "
I want to integrate in my application Bluetooth. I had a problem. I want to connect 2 devices and i want to know if the function "session:peer:didChangeState" is called on the both device. In my opinion i think it is called on the both devices.
I want to know if the method session:peer:didChangeState is called on the both devices .
I want to send via bluetooth a structure:
My structure is following :
typedef struct Package
{
    tip_Comunicare_Enum type;
    union mesaj_Comunicare
    {
        Msg_Cerere_Struct msg_Cerere;
        Msg_Raspuns_Struct msg_Raspuns;
        Msg_Initializare msg_Initializare;
    }mesaj_Comunicare;
}
Package ;

My serializer looks like that :
-(void) SendData:(Package *) pachet
{
NSLog(@"Send DATA pachet");

printf("%d\n",sizeof(*pachet));

NSData * myData = [[NSData dataWithBytes:pachet
                                  length:sizeof(*pachet)] autorelease];
[self mySendDataToPeers:myData];
}

If i use like that it is doesn't work and i give SIGKILL or something like that.
Thant for the time spent with me :)

A: NSData * myData = [[NSData dataWithBytes:pachet
                                  length:sizeof(*pachet)] autorelease];

myData is already autoreleased. You have to write:
NSData * myData = [NSData dataWithBytes:pachet
                                  length:sizeof(*pachet)];

Remember: autorelease message is sent as many times as it is called.


text:
Q: Extracting images from PSD for use in iOS app I'm not sure if this is the best forum for this, because it's not a programming question per se, but here goes.
I am the developer for an iOS application, and we contracted the design out to a third-party.  They delivered to us a massive PhotoShop file with all of the the individual pieces of artwork done on individual layers, at double resolution.  To get the artwork into XCode, my workflow is as follows:

*

*Show only the layers containing a particular unit of artwork

*Select all

*Copy Merged

*Create New image (fortunately, the dimensions are taken care of automatically)

*Paste

*Deselect pasted layer and delete Background, to preserve transparency

*Save image as x.psd

*Save copy as x@2x.png

*Set image size to 50% of original dimensions

*Save copy as x.png

*Discard changes

This app is pretty large, so it's quite tedious to do this process for every little image.  I'm not very Photoshop savvy, so I'm wondering if there is a better way.  It seems to me that it should be easy enough to combine steps 3-11 into one macro or script or something.  The only thing that  changes in each iteration over these steps is the output name.  Any suggestions?

A: Normal workflow is exactly as you described. You can write a Photoshop script to do the layer exporting and Apple provides an Automator tool that will allow you to resize those graphics from 2x down 50%. Great tutorial here. This can help get your graphics to scale quickly.
There are solutions to automate what your trying to accomplish. This video tutorial allows you to take your PSD or PNG and port it into an Xcode with all of the layers properly placed in a view for you, create view controllers, and segues.
Disclaimer - I am associated with the JUMPSTART Platform as mentioned in the video.

A: You can script Photoshop with Javascript and I've written scripts in the past to perform similar series of steps, it wasn't too hard to figure out even for someone like me who'd never written any Javascript before. Photoshop also has 'Actions' which are like macros and you can probably do something simple like this with Actions as well but it's not something I've personally tried. Check out the Adobe docs on scripting Photshop: Adobe Photoshop Scripting.


text:
Q: Refactoring methods that share similar code I have 6 methods in a helper that share very similar code:
module CategoriesHelper

  def item_count(category)
    items = []
    category.items.each do |item|
      if !item.completed
        items << item
      end
    end
    items.count
  end

  def total_items
    items = []
    @user.items.each do |item|
      if !item.completed && !item.content.nil?
        items << item
      end
    end
    items.count
  end

  def overdue_items
    items = []
    @user.items.each do |item|
      if (!item.completed && item.deadline_date &&
          item.deadline_date < Time.now)
        items << item
      end
    end
    items.count
  end

  def week_items
    items = []
    @user.items.each do |item|
      if (!item.completed && item.deadline_date &&
         item.deadline_date - Time.now < 7.days)
        items << item
      end
    end
    items.count
  end

  def today_items
    items = []
    @user.items.each do |item|
      if (!item.completed && item.deadline_date &&
         item.deadline_date.today?)
        items << item
      end
    end
    items.count
  end

  def completed_items(category)
    items = []
    category.items.each do |item|
      if item.completed == true
        items << item
      end
    end
    items.count
  end
end

I was wondering if there was any way of refactoring this as it seems to violate the DRY principle quite heavily. The only thing that varies in each one is the if statement and whether @user or category is used. I've tried putting a lambda in for the iteration:
Iterator = ->(object, if_statement) do
  object.items.each do |item|
    if if_statement
      items << item
    end
  end
  items.count
end

Iterator.call(@user, !item.completed && !item.content.nil?)

but that doesn't work as the if statement contains 'item', so when I try to call the lambda it doesn't recognise item as it hasn't been defined yet. Is there any way of defining items as an empty array in all of the methods in one go?


text:
Q: Atom editor is not executing programs Hello my atom software is not executing programs . i would love to know how i can solve this problem
::When i execute i am given the following error
[          ^^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:606:28)
    at Object.Module._extensions..js (module.js:653:10)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:504:12)
    at Function.Module._load (module.js:496:3)
    at Function.Module.runMain (module.js:683:10)

    at startup (bootstrap_node.js:196:16)
    at bootstrap_node.js:622:3][1]

A: To execute a program in Atom I would first try downloading and installing the Script package. After installing this package, open your file and go to the packages menu. You'll see the newly installed script. Select this to run your script. See image below.

A: Do all your lib/*.js files have at the top this line?
'use babel';


text:
Q: Cakephp 2.1 - AjaxHelper I am using latest(2.1.1)version of cakePhp.
I was trying to implement ajaxHlper(http://www.cakephp.4uk.pl/) . but stuck in between.

<?php echo $this->Form->create('Employee');?>
<fieldset>
    <legend><?php echo __('Add Employee'); ?></legend>
<?php
    echo $this->Form->input('first_name');
    echo $this->Form->input('last_name');
    //echo $this->Form->input('age');
    echo $this->Form->input('age', array('class' => 'required number'));
    echo $this->Form->input('sex');
    echo $this->Form->input('Adress.first_line');
    echo $this->Form->input('Adress.second_line');
    echo $this->Form->input('Adress.city');
    echo $this->Form->input('Adress.state');
    echo $ajax->autoComplete('Department.name', '/ajax/autoComplete')
?>
</fieldset>
   <?php echo $this->Form->end(__('Submit'));?>

<?php echo __('Actions'); ?>

<?php echo $this->Html->link(__('List Employees'), array('action' => 'index'));?>

<?php echo $this->Html->link(__('List Adresses'), array('controller' => 'adresses', 'action' => 'index')); ?>

<?php echo $this->Html->link(__('New Adress'), array('controller' => 'adresses', 'action' => 'add')); ?>

This is my add.ctp file where Department.name I am trying to autocomplete using ajaxHelper.
In my EmployeesController.php I have autocomplete function which is like
 function autoComplete() {
    echo $this->params['url']['q'] . "---";
    $this->loadModel("Department");
    $this->set('departments', $this->Department->find('all', array(
        'conditions' => array(
            'Department.name LIKE ' => '%'.$this->params['url']['q'].'%'
        ),
        'limit' => $this->params['url']['limit'],
        'fields' => array('name')
    )));
    $this->layout = 'ajax';
}

It's not working. What could be the mistake I am doing?
it gives me following error:
Notice (8): Undefined variable: ajax [APP\View\Employees\add.ctp, line 84]
Fatal error: Call to a member function autoComplete() on a non-object in C:\xampplite\htdocs\cakephp\app\View\Employees\add.ctp on line 84

A: Assuming you have added the helper to the $helpers array of your controller, you have to access the helper with $this->Ajax->autoComplete() instead of $ajax->autoComplete().


text:
Q: Science fiction/horror - Survivor floating in the water leads to deaths including impalement by swordfish A ship out at sea comes across a guy floating in the water, the crew pick him up and soon, one by one, the crew starts dying in strange accidental ways. In one of the deaths, the victim is impaled by a swordfish. At the end, the guy they picked up ends up back in the ocean for a new ship to pick up.
The film goes back over deaths and you get to see what really happened to them and it alludes to the guy being the devil. It is a 70s-80s film that might have something to do with the Bermuda triangle.

A: Could it possibly be Satan's Triangle?

A USCG pilot and his winchman Haig (Doug McClure) answer an SOS call at sea and arrive at a derelict schooner called the Requoit. Haig lowers himself to the ship, where he finds three dead bodies along with one survivor, Eva (Kim Novak), cowering in the cabin. As the pilot attempts to retrieve Haig and Eva with a rescue basket, the line breaks, plunging the two into the ocean. After they swim back to the boat, the pilot informs Haig that he must return to base because his fuel is borderline. Eva and Haig spend the night on the boat, during which time she recounts the story of the storm that killed everyone else aboard. One man was hurled through a hatch; one is hanging from the ship's mast; another vanished before her eyes; and a fourth man is in an aft compartment, floating in the air. Eva attributes the deaths to supernatural causes, but Haig has a practical explanation for everything, including the man who appears to be floating in the air. In the morning, the pilot returns along ...

There's a swordfish death (the man seemingly floating). Ironically enough, it's a lot easier to find the complete movie online (although any individual link eventually gets shut down) than it is to find a trailer.
Matching points:

*

*Initial person picked up by the people on the yacht was a male floating in the ocean.

*Final survivor recovered after a rescue call.

*Deaths get explained.

*Impalement by swordfish

*Film was released in 1975

*Title mentions a triangle and Satan.

*It does end with the lone survivor back in the ocean, about to be picked up by another ship as he laughs sinisterly.

Parts that don't match:

*

*Survivor is apparently female (although later revealed to be the priest who was initially rescued and was thought dead, hanging from the mast).

*The Devil allusion happens much later, after the rescue, although Eva discusses her fear of the Devil being behind it all throughout the movie.

I found the movie mentioned in a Movies SE question (no longer available).

A: I think it might be The Bermuda Triangle from 1978.
From the Horror.com forum it describes the movie as follows:
Horror.Com description

Several people are on a yacht when they see what appears to be a priest floating on a piece of wreckage from a boat. They take him on-board, but one by one they start dying in gruesome ways (swordfish sword through the eye etc.) The Coast Guard comes to rescue them, but the priest is the only survivor. In the final scene, shot from the helicopter, you can see somebody dressed in black hanging by his neck from a mast.

Then...

The Coast Guard crewman still on the yacht radios to the helicopter "I thought you said you had the priest with you. We have him here hanging from the mast". The pilot turns around to face the "survivor" and says into his radio " if you have the priest there, who do we have here?" The camera zooms in on the priests' face as he lets out the most chilling and frightening laugh I have ever heard. The helicopter then continues flying away with the devil on board.


text:
Q: Modeling Upvotes / Likes - one table per type, or one big table? I'm modeling a system that will have "upvotes" across various entity types - Reports, Reviews, and Collections.
These are the only three entities that can be upvoted, though there may be more in the future.
Currently, the db schema has ReportUpvotes, ReviewUpvotes, and CollectionUpvotes.
I'm wondering if it would be better to bring all of these tables together into a single Upvotes table, with an enum for Type.
What should I be considering when evaluating this kind of decision?

A: Just like in software development, requirements should strongly influence what you should do.
Do you need to be able to display all upvotes/likes together or in one place?
Do you envisage adding many more types of upvotes?
Answering yes to either of these two would make me lean towards a single table.
Apart from this, just like in software development, if tables are very similar in structure and purpose, they can be "refactored" into a single table. For this reason also, I would lean towards having a single table.

A: The idea of storing entities of the same type (Upvotes) in one table makes perfect sense to me. However, it may be implemented in different ways. Right of the bat I can tell about 3 ways.
The first one that is proposed in the question (unless I misunderstood it) results in polymorphic association, a practice generally considered as bad. Correct me if I'm wrong, but it seems that you want to have something like CREATE TABLE Upvotes (..., type enum ('Report','Review',...), entity_id int) where entity_id refers to one of the Report,Review, etc tables based on value of type column. There is no way you can enforce such constraint without triggers.
Second is exclusive arcs. A bit better approach (referential integrity can be enforced), but still quite ugly. If you go this way, you will have something like
CREATE TABLE Upvotes(..., report_id INT , review_id INT, ....,
CONSTRAINT FK_REPORT FOREIGN KEY (report_id) REFERENCES Report(report_id),
CONSTRAINT FK_REPORT FOREIGN KEY (review_id) REFERENCES Review(review_id)
);

First of all you need to ensure that only one of (report_id,review_id, etc) is not null for any row. Secondly, adding new entity type that can be upvoted means adding new column to Upvotes.
The third way is a "common parent" approach.  You are creating a new table, say UpvotableEntity (bad name, just for illustration). Then make it parent table  for existing  ReportUpvotes, ReviewUpvotes, and CollectionUpvotes. Finally, Upvotes table stores upvotable_entity_id.


text:
Q: How to use SubjectPublicKeyInfo encrypt data? I'm newer to RSA and used BC get SubjectPublicKeyInfo from a public key.
String key = "-----BEGIN RSA PUBLIC KEY-----\n" +
             "........\n" +// Multiple lines here
             "-----END RSA PUBLIC KEY-----\n";

Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) reader.readObject();

And then I want encrypt datas. I found some one use RSAEngine to do it:
AsymmetricKeyParameter aKey = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);
AsymmetricBlockCipher engine = new RSAEngine();
engine.init(false, aKey);
byte[] dataEncrypted = engine.processBlock(data, 0, data.length);

After I run those code, I found the result isn't equal to the expection. So I want to know is there any mistake in my code?

A: Finally I found my way out.
If anyone is familiar with BouncyCastle, he can point me the low-level mistakes.
Firstly, to encrypt data should init Engine with true at first arg in init function.
Secondly, my public key is start with '-----BEGIN RSA PUBLIC KEY-----'. It's PKCS#1 format RSA public key and should use BouncyCastle to read in, but encrypt data should have padding. So, I shouldn't use RSAEngine directly, use PKCS1Encoding instead.
At last , post my encrypt code and decrypt code:
Encryption:
Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) reader.readObject();
RSAKeyParameters rsaKeyParameters = (RSAKeyParameters)
PublicKeyFactory.createKey(subjectPublicKeyInfo);
PKCS1Encoding engine = new PKCS1Encoding(new RSAEngine());
engine.init(true, rsaKeyParameters);
return engine.processBlock(data, 0, data.length);

Decryption:
public static byte[] decryptByPublicKey(String data, String key) throws Exception {
    byte[] rawData = Base64.decode(data);
    Security.addProvider(new BouncyCastleProvider());
    PEMParser reader = new PEMParser(new StringReader(key));
    PEMKeyPair pemKeyPair = (PEMKeyPair) reader.readObject();
    SubjectPublicKeyInfo publicKeyInfo = pemKeyPair.getPublicKeyInfo();
    PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();
    RSAKeyParameters rsaKeyParameters = (RSAKeyParameters)
    PrivateKeyFactory.createKey(privateKeyInfo);
    PKCS1Encoding engine = new PKCS1Encoding(new RSAEngine());
    engine.init(false, rsaKeyParameters);
    return engine.processBlock(rawData, 0, rawData.length);
}

For encryption , you can use modulus and public exponent to create a key that support by JDK:
    Security.addProvider(new BouncyCastleProvider());
    PEMParser reader = new PEMParser(new StringReader(key));
    PemObject obj = reader.readPemObject();
    org.bouncycastle.asn1.pkcs.RSAPublicKey rsaPublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(obj.getContent());
    BigInteger modulus = rsaPublicKey.getModulus();
    BigInteger publicExponent = rsaPublicKey.getPublicExponent();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");//This line should use right padding.For PKCS#1 format RSA key , it should be this.
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(data);

See Also:Basic RSA example.


text:
Q: Quorum: If a contract is publicly deployed in one node, can I hide the data of the contract later from other nodes? I have deployed a common smartcontract for all 5 nodes in a quorum network. If I do a transaction of smartcontract from node 1 provide privateFor as public id of node 2, will my transaction be hidden from other three nodes?
Any insight in the right direction will be helpful. Thanks in advance.


text:
Q: OpenOffice - понять как составить формулу Есть два столбца с ячейками.
A1:A100 - цифры от 1 до 100
B1:B100 - текстовые данные
Нужно получить в список данные ячеек B1:B100 где A1:A100 >=20 и A1:A100<=50
Не могу понять какой функцией(ями) это можно сделать, а именно задать два условия одному range ячеек


text:
Q: Is there a way to export only the Firestore delta or changes (the differences) since the last export? I am doing a daily export of my Firestore records to Google's bucket storage using this scheduled export code (cron): https://firebase.google.com/docs/firestore/solutions/schedule-export#deploy_the_app_and_cron_job
Is there a feature or code or API that is available yet to export only the delta differences or the changes made since the last export or does it only do full backups all the time?

A: There is not currently a way to do incremental backups.  The export mechanism described in the documentation is not really a "backup" in the way that most people would think of that word.  It's just an export, to be used to make it easy to recover from disaster, or make copies to bootstrap other databases for immediate use.

A: Here's an approach to get the segmented data using a temporary collection /exportData

Reminder that the necessary read, write, & delete calls for this still fall under standard billable usage

As part of the scheduled script, run following async sequence:

*

*Empty collection /exportData

*Run a filtered query to get the delta data

*Write the delta data you want to export to collection /exportData

*Export just that collection /exportData
As per the docs "You can export all documents or just specific collections." https://firebase.google.com/docs/firestore/manage-data/export-import


text:
Q: Call different models's method while value of different model's changed - odoo There are two models, one to keep master entity and other is transaction model.

Master model contains unique records, combinations of product and
  warehouses and First stock date on which date that product is in in
  stock in that warehouse. Everyday one cron runs and it will store
  stock entry in that table, product - warehouse and period combination.

class parameter_view(models.Model):
    _name = "parameter.view"
    _description = "Reorder Parameter View"
    _order = "product_id, warehouse_id"

    @api.multi
    def _set_first_date(self):
        for rec in self:
            if not rec.first_stock_date:
                domain = [('warehouse_id','=',rec.warehouse_id.id),('product_id','=',rec.product_id.id), ('qty_available','>',0)]
                stock = self.env['warehouse.product.daily.stock'].search(domain, order='stock_date', limit=1)
                if stock and stock.stock_date:
                    rec.first_stock_date = stock.stock_date

    first_stock_date = fields.Date(string="First on Stock Date")
    product_id = fields.Many2one(comodel_name='product.product', string='Product')
    warehouse_id = fields.Many2one(comodel_name='stock.warehouse', string='WH')

Transaction model.
class warehouse_product_daily_stock(models.Model):
    _name = 'warehouse.product.daily.stock'
    _order = 'stock_date desc, product_id, warehouse_id'
    _description = "Daily Product Stock Warehouse Wise"

    stock_date = fields.Date('Date')
    period_id = fields.Many2one(comodel_name='reorder.account.period', string='Period')
    product_id = fields.Many2one(comodel_name='product.product', string='Product')
    warehouse_id = fields.Many2one(comodel_name='stock.warehouse', string='Warehouse')
    qty_available = fields.Float('Qty On Hand')

Problem:
In starting phase if the product is not in stock then the first on
  stock date set to null but after few days if product available in
  warehouse then the first on stock date will be set automatically. But
  that's not done. How can we call function of different model while
  value of other model's record has been updated.

How can I call method of parameter view while the record of daily stock view updated. Manually I know. But is there any automatic way to call interdependent object's method.


text:
Q: Clicking on button to redirect to another html page I have tried many diff ways like using forms or script but i still cannot get it. this are my current codes. Thank you
<button name="nextpg" onclick="redirect()" class="mb-3 signup-btn" >Reset my password</button>

 <script type="text/javascript">
function redirect()
{
var url = "http://127.0.0.1:8080/cfmemail.html";
window.location(url);
}
</script>

A: you can try this. It might do the trick for you
<input type="button" onclick="window.location.href = 'http://127.0.0.1:8080/cfmemail.html';" value="Redirect"/>

A: Use this code:
<!DOCTYPE html>
<html>
<body>

<button onclick="redirect()">Redirect</button>

<script>
function redirect() {
  location.replace("http://127.0.0.1:8080/cfmemail.html")
}
</script>

</body>
</html>


text:
Q: Calculating dust attraction to a charged surface Even though dust particles are neutral, they tend to be attracted to a charged surface. I am guessing this is due to charge induction.
Is there a way I can compute the attraction? how will it vary based on:

*

*separation distance.
I think the distance will affect as inverse square law (1/r^2) [Coulomb's law]. But to calculate the force, I need to know how much charge has been induced ( how do I find that?) and does that vary due to separation distance.

*type of dust.
Do all material act the same , or are some material gets more charge induced? ( metals, for example with more free electrons)

*the size of dust particles.
Intuition suggests that bigger particles will be induced less, but I am not sure.

A: The attraction is that between a charge and an induced dipole. If the charged object is a sphere, the field is $QE\over 4\pi r^2$, in units where $\epsilon_0=1$. This field is what induces the dipole and causes the attraction.
Once you get a dipole moment in the dust, the dust dipole is attracted to regions of stronger field with a force that goes like the derivative of the E field. The total dipole is neutral, so you get net opposite positive and negative forces which only fail to cancel out to the extent that the E field is stronger in the regions of induced positive charge. The magnitude of the force is (in the nearly perfect small-dust approximation) $ d \cdot \nabla E$, the dipole moment can be thought of as defined by this equation (although that's not the definition--- the dipole moment vector d is the sum of qx over all the little infinitesimal regions in the dust, where q is the charge of the region, which sums to zero over the dust particle, and x is the position).
So if the dipole moment is of fixed size, the force is $2Qd\over r^3$. But the dipole itself is proportional to E, with a coefficient that I'll call "p" for polarizability, so you get a force which is
$$ {2 Q \over 4\pi r^3} { pQ\over 4\pi r^2} = {2pQ^2\over 16\pi^2 r^5}$$
and this is the force between a sphere and a dipole (in units where $k={1\over 4\pi\epsilon_0} = 1$). You see it falls off as $1/r^5$, two powers of r for the induced dipole strength, proportional to the E field, and another three powers from the force, which is as the gradient of E.
To calculate p requires knowing something about the material, namely it's dielectric polarizability constant for DC electric fields. This is radically different for different materials, depending on whether the molecules are polar themselves, and how mobile they are, whether it's liquid or solid. In general, you can figure this out from the extent to which the electric field in the interior of the dust is reduced from the exterior, assuming a bulk block of dust material. This is the dielectric constant $\epsilon$ of the dust.
For a solid block of dust in a constant electric field E perpendicular to the plane surface of the dust-block, the electric field in the interior of the dust block is $E\over \epsilon$ where $\epsilon$ for DC fields is always bigger than 1. For a metal, the field in the interior is zero, and this corresponds to infinite $\epsilon$. I will calculate the polarization constant in an order of magnitude for metal dust, but for the largely nonpolar typical carbon-chain dust material, the actual answer will range from 1%-10% of the metal answer.
For the metal, there is a nice useful trick for getting the induced dipole moment magnitude, which is the method of images/conformal maps. A dipole at the origin is conformally equivalent by an inversion around a sphere of certain radius to a constant electric field at infinity, so if you place a dipole at the origin, and the equal electric field inverted, the result makes the sphere have the same potential.
The electric potential of a dipole is by differentiating the electric potential of a point charge:
$$ \phi = {dz \over 4\pi r^3}$$
The potential of constant z-direction electric field is
$$ \phi = Ez$$
adding the two, the surface at potential zero (only a zero potential stays an equipotential under inversion) is a sphere:
$$ Ez - {dz\over 4\pi r^3} = 0$$
This is solved by a sphere (away from the z=0 plane which is an accidental equipotential by symmetry)
$$ d = 4\pi E r^3 $$
and so the induced dipole moment is proportional to the cube of the sphere size. The coefficient p is $4\pi a^3$ for a metal spherical dust of radius a.
So the answer for an ideal resistive metal dipole (perfectly screening object, zero response time to adjust to a new field, these are good assumptions for this situation) is
$$ F = {Q^2 a^3 \over 4\pi \epsilon_0 r^5} $$
Where I restored $\epsilon_0$ in the final answer. For a non-metal resistive dipole, the induced moment is less by the facor $(1-{1\over \epsilon})$. For hydrocarbons, the dielectric constant is about 2, so you get 1/2 the force. Note than when r is of order a, the maximum force goes up as the object gets small.


text:
Q: Strange CoreData compile error My project can't be compiled today suddenly, the error is at
CoreDataDefines.h
COREDATA_EXTERN double NSCoreDataVersionNumber;

The error info is
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk/System/Library/Frameworks/CoreData.framework/Headers/CoreDataDefines.h:71: error: expected '=', ',', ';', 'asm' or 'attribute' before 'extern'
I don't know how this happen. Because this file belongs to the SDK, i can't modify it.
I have tried clean, etc, but no use.
can someone help?

A: well, I saw this post
Objective-C error: expected '=', ',', ';', 'asm' or '__attribute__' before 'class'
it actually has nothing to do with CoreData, I just mistakely typed a character in the very beginning of a class header file who import CoreData.
removed that character, everything is fine


text:
Q: union() method giving weird dataset values I want to pile up the rows of many datasets into one. The datasets are stored in array and i use union() to add the rows of the previous dataset, given the array of datasets i described :
ArrayList<Dataset<Row>> dropped_added_cols_dataset_list = ...

i do it like so :
AD = dropped_added_cols_dataset_list.get(0);
for (int i = 1; i < dropped_added_cols_dataset_list.size(); i++) {

    AD = AD.union(dropped_added_cols_dataset_list.get(i));
   }

But it seems as the final AD is showing weird values not related to those in each sub-dataset from the array described previously.
Anyone has an idea why ?

A: Let's say we have the following n (here n == 3) number of Datasets as input stored in your dropped_added_cols_dataset_list list.
df1:
+---+----+----+
| _1|  _2|  _3|
+---+----+----+
|  0|cat1|30.9|
|  2|cat2|22.1|
|  0|cat3|19.6|
|  1|cat4| 1.3|
+---+----+----+

df2:
+---+----+----+
| _1|  _2|  _3|
+---+----+----+
|  1|cat5|28.5|
|  2|cat6|26.8|
|  1|cat7|12.6|
|  1|cat8| 5.3|
+---+----+----+

df3:
+---+-----+----+
| _1|   _2|  _3|
+---+-----+----+
|  1| cat9|39.6|
|  2|cat10|29.7|
|  0|cat11|27.9|
|  1|cat12| 9.8|
+---+-----+----+

We can apply the unions for all of them in the list without any user-specific loop, by using reduce (Java docs for Dataset's specified reduce here, working for the ArrayList through the InterruptibleIterator class that inherits reduce from the scala.collection.TraversableOnce interface as seen here) to merge the Datasets together in couples at a time.
// Java (`dropped_added_cols_dataset_list` is of type ArrayList)
list.reduce((ReduceFunction<Dataset>) (v1, v2) -> v1.union(v2));

// Scala (`dropped_added_cols_dataset_list` is of type List)
dropped_added_cols_dataset_list.reduce(_ union _)

The resulting Dataset will look like this:
+---+-----+----+
| _1|   _2|  _3|
+---+-----+----+
|  0| cat1|30.9|
|  2| cat2|22.1|
|  0| cat3|19.6|
|  1| cat4| 1.3|
|  1| cat5|28.5|
|  2| cat6|26.8|
|  1| cat7|12.6|
|  1| cat8| 5.3|
|  1| cat9|39.6|
|  2|cat10|29.7|
|  0|cat11|27.9|
|  1|cat12| 9.8|
+---+-----+----+

Of course, for the unions to be successful, you need to be extra careful that all of the Datasets stored in your list have the exact same column schema.
It also needs to be said that this solution's performance is heavily dependent on the number of Datasets being merged, so a relatively large number of unions can result to non-linear time complexity.


text:
Q: Block rest of the view except a particular element Sorry for the title couldn't come with a better one...Okay here's is my doubt, when we display a javascript alert using  alert("Some text")  we see the alert dialog , Now the enter UI except the dialog box is unresponsive unless we hit Ok or close the alert window, Same goes for the confirm dialog. I am trying to build a widget to display my custom Confirm dialog using HTML elements but I don't know how to block the UI, The user if he wants can ignore the dialog & click other elements on the UI, Any suggestions or workarounds on blocking?

A: You could build a simple overlay with your dialog.  Your dialog could be absolutely positioned on the screen, allowing users to either click it or other elments to the side of it.
http://www.emanueleferonato.com/2007/08/22/create-a-lightbox-effect-only-with-css-no-javascript-needed/


text:
Q: Getting data from popped view controller to parent view controller I have a problem where I am able to pass all data to a push view controller using
[self performSegueWithIdentifier:@"Expense" sender: self];

and
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

However I do not know how to get back data when the view controller is popped out. I have a couple of arrays that need to be passed from a popped view controller to parent view controller.

A: Create a class to serve as the data model for your application and have it include the arrays you need to pass around.  Create an object of that class in your first controller, share it with the second controller during prepareForSegue:, let the second controller update it, and read the new values when the parent's view appears again.

A: You should use segues to pass data forward and Delegate Methods to send data back in your navigation stack. That is the recommended approach. I answered a similar question earlier. Although the question may sound different, the underlying solution should work in your case as well.


text:
Q: Fixing onClick Closure Bug Secrets of the JavaScript Ninja shows the following example:
HTML
<button id="test">Click me!</button>
JavaScript
var button = {
    clicked: false,
    click: function() {
        this.clicked = true;
        console.log("this:", this, "button.clicked?", button.clicked);
    }
};

var elem = document.getElementById("test");
elem.addEventListener("click", button.click, false);

When testing this out (http://jsfiddle.net/4hdQF/), false gets printed out.
After replacing the console.log statement with ...,this.clicked?", this.clicked)`, it seems to work successfully - http://jsfiddle.net/YG8ST/.
The book mentions using bind to fix the first buggy app. But, is the replacement of button.clicked with this.clicked a valid fix? It seems to be since, when the click function gets called, it will use this to check if the current, in-context button was clicked.

A: No, using this is not the same as using button.  In the event handler, this will be bound to the DOM node, not that object.
If you're OK with having this be the DOM node, then it's fine to use it of course. However, that "clicked" property of the button object won't be affected by that code.
By setting up the event handler with a bound function:
elem.addEventListener("click", button.click.bind(button), false);

you ensure that this in the handler will be the button object, despite the fact that the runtime will try to invoke the handler the same way it always does. The function returned from bind basically overrides what the called did to set this.


text:
Q: sending extra argument to event handler with event argument i have this input with onchange event handler
  <input accept="image/*" type='file' id="imgInp" @change="imageChange" />

my imageChange method is like
  methods : {
   imageChange(e ){
      const file = e.target.files[0];
      console.log(file);
      URL.createObjectURL(file);
      this.model.image = URL.createObjectURL(file);

     } ,

  }

basically setting model.image value on change now i want to have multiple images on my model ... so i want to change the image property to array and have an input for each image

  <input accept="image/*" type='file' id="imgInp" @change="imageChange" />

now i need to send the imaeg index in the array to my function as well so i can replace that index image like
and change my method to
  imageChange(e , index ){
      console.log(`event ->`);
      console.log(e);
      console.log(`index ->`);
      console.log(index);
      //URL...
      this.model.images[index] = URL.createObjectURL(file);
  }

but this will result in undefined event here is the output
event ->
undefined
index ->
0

how can i send extra argument to event handler without losing event argument ?

A: Just execute the function inside with @change event, and pass the Vue provided $event params first then index param.

  <input accept="image/*" type='file' id="imgInp" @change="imageChange($event, index)" />


text:
Q: Merging overlays and camera pictures to create high quality images in Android I'm trying to emulate something that is working in an app called InstaWeather. They have numerous overlays that you can switch through, that merge with the picture you take to produce a custom weather image that you can share.
It doesn't seem like these are canvas drawn on, and I can never get anywhere near as clear and high res drawing things on via canvas. Does anyone have any idea how the overlay and taken camera image are merged? Bearing in mind the overlays are based on the current weather data so aren't pre-existing.
I'm not sure if this will be regarded as too general, but I do have a specific issue in that the images I create often suffer hugely from being drawn on via canvas.


text:
Q: java swing won't display I'm currently trying to add animation to a program that has various objects moving around and interacting in a 2D space. I've finally gotten to where the timer works, and the program has the objects moving and interacting the way I want them to...but the display panel it opens remains frustratingly blank. I've been trying to use code from examples found online, but I must still be missing something...
    public class Populus2 extends JPanel
{
    /**
     * @param args
     */

        static float[] xCoordinates;
        static float[] yCoordinates;
        static int duration;
        static int iteration = 1;
        static int graphSize = 500;
        ..............

        static JFrame frame;
        static JLabel lbl;
        JPanel panel;
        static Timer timer;

        public static void main(String[] args) throws IOException {
            final Populus2 pop = new Populus2();

            frame = new JFrame("Animation Frame");
            lbl = new JLabel();
            Panel panel = new Panel();
            panel.add(lbl);
            frame.add(panel, BorderLayout.CENTER);
            frame.setSize(graphSize, graphSize);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            ActionListener timeStep = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    System.out.println("at time " + iteration);
                    spendTime();
                    pop.repaint();
                    if(iteration>duration)
                        timer.stop();
                }
            };

        timer = new Timer(100, timeStep);
        timer.setInitialDelay(0);
        timer.start();
    }

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        System.out.println("******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n");
        Graphics2D g2d = (Graphics2D) g;
        paintCell(g, 1);  //eventually, I want to call this method for every "cell" in the program
        g.drawLine(30, 30, 80, 80);  //this line's basically a test to see if I can display anything at all
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

      public void actionPerformed(ActionEvent e) {
        repaint();
    }

    public void paintCell(Graphics graphics, int cellNumber)
    {
        graphics.setColor(Color.black);
        graphics.fillOval((int)(graphSize*xCoordinates[cellNumber]/size), (int)(graphSize*yCoordinates[cellNumber]/size), 5, 5);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        for(int i = 0; i < types.length; i++)
            paintCell(g, i);
    }

    public static void spendTime()
    {
        //advances the iteration counter and recalculates the coordinates of all the cells
    }

}

Ultimately, I want the program, on each iteration of the timer, to call paintCell() for every one of the cells in the simulation, each one representing a moving object. For now, though, the screen remains blank. The message I had paint() calls through System.out.println() doesn't display, for the record.
Thoughts?

A:
I've been trying to use code from examples found online, but I must still be missing something...

Don't use AWT suggestions in a Swing program. Swing is different from AWT. Don't use a Panel. In Swing you use a JPanel. In Swing your override the paintComponent() method, not the paint() method. Right now your code attempts to override both methods.
Read the Swing tutorial on Custom Painting for more information and proper examples.
frame.setSize(graphSize, graphSize);

Don't use frame.setSize() the frame size includes the borders and title bar so your graph will not be the size you want. Instead, override the getPreferredSize() of the JPanel where you do the custom painting to return the size of the panel. Then you would do frame.pack().
But the reason the panel doesn't show is because you don't add the panel to the frame.
//frame.add(panel, BorderLayout.CENTER);
frame.add(pop, BorderLayout.CENTER);

The code below does nothing since the label has no value. You should be using a JPanel, but there is no need for the panel since you can add a label directly to the content pane of the frame.
lbl = new JLabel();
Panel panel = new Panel();
panel.add(lbl);


text:
Q: ADF Lookup query create schema and select I am trying to run a create Shema/table query in the ADF lookup activity, with a dummy select in the end.
CREATE SCHEMA [schemax] AUTHORIZATION [auth1];
SELECT 0 AS dummyValue
but I got the below error
A database operation failed with the following error: 'Parse error at line: 2, column: 1: Incorrect syntax near 'SELECT'.',Source=,''Type=System.Data.SqlClient.SqlException,Message=Parse error at line: 2, column: 1: Incorrect syntax near 'SELECT'.,Source=.Net SqlClient Data Provider,SqlErrorNumber=103010,Class=16,ErrorCode=-2146232060,State=1
Data factory pipeline
I was able to run a similar query without SELECT query in the end but got another error mandating lookup must return a value.

A: You can only write select statements in lookup activity query settings.
To create schema or table, use copy data activity pre-copy script in sink settings. You can select a dummy table for the source and sink dataset and write your create script in pre-copy activity as below.
Source settings: (using dummy table which pulls 0 records)

Sink settings:
Pre-copy script:  CREATE SCHEMA test1 AUTHORIZATION [user]


text:
Q: How to group of 2 arrays I have 2 arrays like this
$head = array(7, 1, 1, 1, 1, 14, 14, 14, 9, 9, 9, 13, 13, 13, 3, 3, 5, 8, 8, 8, 2, 2); //count =22

$customer = array(1, 7, 9, 13, 14, 1, 9, 13, 1, 13, 14, 1, 9, 14, 2, 8, 8, 2, 3, 5, 3, 8); //count=22

And I want to group this 2 arrays by consider at $customer,  if $customer[0]=1 in $customer[1-21] and $head[1-21] will not have a value 1, such as in the $head[1] have a value 1, So delete at $head[1] and $customer[1]. And then consider at $customer[6]. The value is 9. It means in $head[7-21] and $customer[7-21] will not have a value 9.
I am trying to write a code for this concept like this. Here is my code
for ($i = 0; $i < count($head); $i++) {
    for ($j = $i + 1; $j < count($customer); $j++) {

        if ($customer[$i] == $head[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
        if ($customer[$i] == $customer[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
    }
}

print_r($head);

print_r($customer);

the result is of $head and $customer is:
Array ( [0] => 7 [6] => 14 [7] => 14 [13] => 13 [14] => 3 [15] => 3 [16] => 5 [17] => 8 [18] => 8 [19] => 8 [20] => 2 [21] => 2 )

Array ( [0] => 1 [6] => 9 [7] => 13 [13] => 14 [14] => 2 [15] => 8 [16] => 8 [17] => 2 [18] => 3 [19] => 5 [20] => 3 [21] => 8 )

I found that it's wrong. Because the real result should be:
Array ( [0] => 7 [6] => 14 [7] => 14  [14] => 3 [15] => 3  )

Array ( [0] => 1 [6] => 9 [7] => 13  [14] => 2 [15] => 8  )

Please help me to fix this problem.

A: Your logic is all ok but when you unset a particular index then all other index after when you iterate it again then i index is missing. Just open the error and warning then you will see

Notice: Undefined offset

I have just replaced your uset to assign it to ''. So you can understand it
<?php

$head = array(7, 1, 1, 1, 1, 14, 14, 14, 9, 9, 9, 13, 13, 13, 3, 3, 5, 8, 8, 8, 2, 2); //count =22

$customer = array(1, 7, 9, 13, 14, 1, 9, 13, 1, 13, 14, 1, 9, 14, 2, 8, 8, 2, 3, 5, 3, 8); //count=22

for ($i = 0; $i < count($head); $i++) {
    for ($j = $i + 1; $j < count($customer); $j++) {

        if ($customer[$i] == $head[$j]) {
            $head[$j] = '';
            $customer[$j] = '';
        }
        if ($customer[$i] == $customer[$j]) {
            $head[$j] = '';
            $customer[$j] = '';
        }
    }
}

print_r(array_diff($head, [''])); // remove all the '' entries

print_r(array_diff($customer, [''])); // remove all the '' entries

A: The problem is that count() only returns a count of the set elements in the array. So if you unset them it will be reduced and you won't arrive at the end of the array. To fix, calculate the count at the start and store in a variable:
$headcount = count($head);
$customercount = count($customer);
for ($i = 0; $i < $headcount; $i++) {
    for ($j = $i + 1; $j < $customercount; $j++) {

        if ($customer[$i] == $head[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
        if ($customer[$i] == $customer[$j]) {
            unset($head[$j]);
            unset($customer[$j]);
        }
    }
}


text:
Q: Memory pool: force allocating resources (map / vector) to reallocate for continuity I have a memory pool of fixed size. A custom allocator is used to put std::vector and std::unordered_map elements into that pool. Over time the memory pool gets fragmented and even though there might be enough memory available if you scrap all the free pieces together, it might not be accessible as one single contiguous block as required for std::vector.
Question: How can I defragment this pool (by shifting buckets and vector arrays around) and update all pointers held by std::vector and std::unordered_map to reflect new contiguous memory locations? Is it possible somehow? Other question: Is it sensible?

A: In general, fragmentation is a hard problem without a clear solution, except switching to a compacting garbage collector.
If your use case involves allocating many same-sized objects, consider separating their allocation into a dedicated bin and allocate memory for that bin with few large allocations. At least this will keep the small objects clustered together rather than spreading out over the whole memory arena. You can have a look at how the Linux kernel does it with its Slab allocator.
There is also a very interesting paper that uses memory mapping tricks to merge fragmented memory. Check out Powers, Bobby, et al. "Mesh: Compacting memory management for C/C++ applications." Proceedings of the 40th ACM SIGPLAN Conference on Programming Language Design and Implementation. 2019.
Other workarounds exist. std::list and std::deque with their mostly small, same-sized allocations are able to operate under conditions of extreme memory fragmentation longer than std::vector since their allocations are less likely to fail.
Also, you may be able to implement something like memory compacting on an application level: Separate your memory pool in two. Periodically (or when required) invoke an operation that recursively copies all existing objects into new containers, switching memory pools in the process. A poor man's garbage collector.


text:
Q: Merge jsonb objects and sum their values over multiple rows I save visits to my database. In my database I have a table with aggregations of visits called visits_agg. This table has one row per hour per hostname. Both are fields in the table which will be used to query the rows needed for viewing statistics.
For example I will query for the visits in the last 24 hours:
SELECT * FROM visits_agg WHERE hostname = 'example.com' AND hour > NOW() - INTERVAL '24 hours'

To create the structure I used this query:
CREATE TABLE IF NOT EXISTS visits_agg (
  id          serial primary key,
  hour        timestamp without time zone default (now() at time zone 'utc'),
  hostname    text not null,
  visits      integer default 0,
  referrers   jsonb not null default '{}'::jsonb,
  paths       jsonb not null default '{}'::jsonb,
  widths      jsonb not null default '{}'::jsonb
);

With some dummy data:
INSERT INTO "visits_agg" ("hour", "hostname", "visits", "referrers", "paths", "widths") VALUES
('2019-01-16 09:00:00', 'example.com', '6', '{"example2.com": 4}', '{"/": 5, "/about": 1}', '{"1280": 5, "1283": 1}'),
('2019-01-16 14:00:00', 'example.com', '7', '{"google": 6}', '{"/": 1, "/about": 3, "/article/title1": 1, "/article/title2": 2}', '{"360": 3, "1398": 1, "1680": 1, "2560": 1}'),
('2019-01-16 15:00:00', 'example.com', '6', '{"google": 6}', '{"/about": 1, "/article/title1": 1, "/article/title2": 3, "/": 1}', '{"360": 3, "1280": 2, "1920": 1}'),
('2019-01-16 16:00:00', 'example.com', '6', '{"facebook": 1, "example2.com": 1}', '{"/": 4, "/about": 1, "/article/title1": 1}', '{"360": 1, "1440": 2, "1680": 2, "1920": 1}');

I would like to get the rows from a certain period and sum all referrers, paths, and widths.
So the result of the above records should be something like this
'example.com',
'25',
'{"example2.com": 4, "google": 12, "facebook": 1}',
'{"/": 11, "/about": 6, "/article/title1": 3, "/article/title2": 5}',
'{"360": 7, "1398": 1, "1440": 2, "1680": 3, "2560": 1, "1280": 7, "1283": 1, "1920": 2}'),

The keys in the jsonb objects can be any string and the values are always numbers. I tried to merge the objects, but can't figure out how to sum the values inside the jsonb objects.

A: As I pointed out in comments I think this job would be easy to accomplish working with a disaggregated data, because now IMHO you must disaggregate it again:
For example to get aggregated values for referrers:
SELECT
    hostname,
    r.key as ref_name,
    r.value::int as ref_value
FROM
    visits_agg
CROSS JOIN LATERAL
    jsonb_each(referrers) r;

hostname    | ref_name     | ref_value
:---------- | :----------- | --------:
example.com | example2.com |         4
example.com | google       |         6
example.com | google       |         6
example.com | facebook     |         1
example.com | example2.com |         1

Now you can get acumulated values grouped by ref_name, and then you must build the jsonb array again.

SELECT   hostname, jsonb_agg(jsonb_build_object(ref_name, ref_value)) as referrers
FROM     (SELECT hostname, r.key as ref_name, SUM(r.value::int) as ref_value
          FROM   visits_agg
          CROSS JOIN LATERAL jsonb_each(referrers) r
          GROUP BY hostname, r.key) t1
GROUP BY hostname;

This is my approach, perhaps some Postgres guru can give you a better answer.
SELECT row_to_json(t0, true)
FROM
    (
    SELECT t1.hostname, t1.visits, t2.referrers, t3.paths, t4.widths
    FROM   (SELECT   hostname, SUM(visits) as visits
            FROM     visits_agg
            GROUP BY hostname) t1
    JOIN   (SELECT   hostname, jsonb_agg(jsonb_build_object(ref_name, ref_value)) as referrers
            FROM     (SELECT hostname, r.key as ref_name, SUM(r.value::int) as ref_value
                      FROM   visits_agg
                      CROSS JOIN LATERAL jsonb_each(referrers) r
                      GROUP BY hostname, r.key) t1
           GROUP BY hostname) t2
           ON t1.hostname = t2.hostname
    JOIN   (SELECT   hostname, jsonb_agg(jsonb_build_object(path_name, path_value)) as paths
            FROM     (SELECT hostname, p.key as path_name, SUM(p.value::int) as path_value
                      FROM   visits_agg
                      CROSS JOIN LATERAL jsonb_each(paths) p
                      GROUP BY hostname, p.key) t1
            GROUP BY hostname) t3
           ON t1.hostname = t3.hostname
    JOIN   (SELECT   hostname, jsonb_agg(jsonb_build_object(width_name, width_value)) as widths
            FROM     (SELECT hostname, w.key as width_name, SUM(w.value::int) as width_value
                      FROM   visits_agg
                      CROSS JOIN LATERAL jsonb_each(widths) w
                      GROUP BY hostname, w.key) t1
            GROUP BY hostname) t4
           ON t1.hostname = t4.hostname
    ) t0;

And this is the result:
{
 "hostname":"example.com",
 "visits":25,
 "referrers":[{"google": 12}, {"facebook": 1}, {"example2.com": 5}],
 "paths":[{"/about": 6}, {"/article/title2": 5}, {"/article/title1": 3}, {"/": 11}],
 "widths":[{"1680": 3}, {"1398": 1}, {"2560": 1}, {"360": 7}, {"1280": 7}, {"1440": 2}, {"1920": 2}, {"1283": 1}]
}

db<>fiddle here


text:
Q: Left align div to centered container I have a container centered with a max width as follow:
#container {
   margin-left: auto;
   margin-right: auto;
   max-width: 900px;
}

Now I want to create a new div just below the contained one, but I want this new div to align to the left and expand beyond the right side of the container. Something like that:
            ||||||||||||||||||||||||||||||||||||                                #container
            |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||     #div 2

The difficulty is that #container margins are auto, so how can I force #div to follow #container left margin as the browser resizes?!
NOTE: I am looking for a pure CSS solution WITHOUT JAVASCRIPT
EDIT: It was not clear in my explanation but, my goal was to make the #div ADJACENT to the #container. Like this:

I ended up refactoring my html to use @bananabran solution with absolute positioning which simply uses parent-child structure:

A: You don't have to force the div to follow its container's left margin. Divs naturally start at the top-left of their container (unless otherwise specified or affected by). You also do not need to use Grid or FlexBox. CSS3, and even CSS2 can do this natively.
See working CodePen example: https://codepen.io/bananabrann/pen/QWWdXQZ
Assuming you have no other code affecting your code...

#container {
  background-color: blue;
  position: relative;
  margin: 0 auto;
  width: 900px;
  height: 300px;
}
#my-div {
  background-color: red;
  position: absolute;
  bottom: 0;
  width: 500px;
  height: 20px;
}

A: CSS-Grid can do that:

.wrap {
  display: grid;
  grid-template-columns: 1fr minmax(auto, 400px) 1fr;
  /* 400px for demo purposes */
}

.container {
  padding: 1em;
  background: pink;
  grid-column-start: 2;
}

.wide-r {
  padding: 1em;
  background: lightgreen;
  grid-column: 2 / span 2;
}

Container

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, similique, maxime aspernatur dolorum quod recusandae possimus fuga blanditiis laudantium delectus quis magni. Veniam, consequuntur dolores facilis cupiditate fugiat ullam aspernatur!
      Corporis excepturi quos esse voluptatem voluptatibus corrupti ea, tempora culpa magni, hic aspernatur pariatur molestias itaque doloremque assumenda ad fugiat!

Wide Right


text:
Q: Question about accessing variables inside partials I want to iterate through an array of objects
<% @users.each do |user| %>
  <%= render "member_list" %>
<% end %>

My question is how do I pass the user object to the partial, and how do I reference it in the partial.  I know how to do it if it's just a single object, but I don't know how to pass the single object from the array to it.
I tried passing user to it and reference user in the partial, but it doesn't recognize user in the partial.

A: <% for user in @users %>
  <%= render "member_list" , locals => {:user => user}%>
<% end %>

in partial:
Hello. I'm <%= user.name %>

A: You might do it without loop - pass it as a :collection parameter. To use a custom local variable name within the partial, specify the :as option in the call to the partial:
<%= render :partial => "member_list", :collection => @users, :as => :member %>

With this change, you can access an instance of the @users collection as the member local variable within the partial.


text:
Q: How to set conditional breakpoint with OR operator in Spyder? I am debugging python code in Spyder. How can I set a conditional breakpoint that stops when the var_name is either 'var1' or 'var2'?
I tried following condition on breakpoint, it didn't work.
var_name == 'var1' or 'var2'


text:
Q: Server Block with 2 ports and 2 root directory's? server {
    listen 27700;
    index index.php index.html index.htm;
    root /home/application/app_purple_code/admin/;

    location ~ \.php$ {
        limit_req zone=one burst=8;
        try_files $uri =404;
        fastcgi_index index.php;
        fastcgi_pass php;
        include fastcgi_params;
        fastcgi_buffering on;
        fastcgi_buffers 96 32k;
        fastcgi_buffer_size 32k;
        fastcgi_max_temp_file_size 0;
        fastcgi_keep_conn on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    }
}

}
I have this server block above, but is there a way to use TWO ports for two different root folders.
So i want,
The default above and also another port with e.x
listen 28800;

and pointing to;
root /home/application/app_purple_code/admin2/;

....
I want to be able to go to http://IP.com:27700 and http://IP.com:28800
so basically like having a official admin release on 1 port and a beta admin portal on the other.
Thank you.

A: Well, what you just described here are two server {} blocks. So, to accomplish what you want, you have to create them individually, each one with a distinct listen and a root directives.
Here's an example:
# /etc/nginx/sites-available/site1
# Be sure to run sudo ln -s /etc/nginx/sites-available/site1 /etc/nginx/sites-enabled/site1 after you've created the file below
server {
    listen 28800;
    root /var/www/site1/public_html;
}

# /etc/nginx/sites-available/site2
# Be sure to run sudo ln -s /etc/nginx/sites-available/site2 /etc/nginx/sites-enabled/site2 after you've created the file below
server {
    listen 27700;
    root /var/www/site2/public_html;
}

After that, restart the Nginx service with sudo nginx reload or systemctl restart nginx.service.
Best regards.


text:
Q: Power supply for a solenoid to open a secret compartment I'm an avid DIYer, I don't know anything about circuits, meters, mathmatical equations etc. I have created a secret storage compartment so the door has no visible hinges, handles or locks, It's made of wood and weighs around 10 kg, it's held closed with medium strength magnets. I'm looking at using a push solenoid with a spring to return the pin back to starting position connectted to a doorbell type button via the main lighting circuit using 1.5 cable. 2 problems. Firstly can this be done, do I have to add a transformer into the mix,if so how? Secondly how will I know if the power of the solenoid will be able to detach the door from the magnets to open? Only place that sells solenoids in lamens terms is Amazon so this is where I'll be purchasing it from.

A: I think you may be using the wrong mechanism for the lock. Maglocks (magnetic locks) are widely used for this type of application in building security. They come in two modes: release when power off (suitable for most applications) and require power to release (prisons, etc.).

Figure 1. Maglock with magnetic poles exposed and keeper.
It seems to me that the three poles are arranged as south-north-south (or vice-versa) and that the coil is wound, pushed into the black slots and potted in position. Once the (electro) magnet hits the keeper the magnetic circuit is closed. As anyone who has played with a horseshoe magnet will know, opening the closed loop is very difficult.

Figure 2. Cross-sectional view.
Here we can see that with the lock open the exposed faces are poles of the electro-magnet. Note also that the magnetic path is twice as wide in the centre pole as on the upper and lower poles so that flux density is fairly constant. Once the lock closes the flux forms a loop through the iron core.

Some of the suggestions had ways that didn't consume power to hold it in place but still needed it to unlock it.

The "normally locked" version requires power to unlock. The coils are typically 12 or 24 V so that the controller can run with a small lead-acid battery backup. You would need to check the datasheets to learn how much current they consume and purchase a suitable power supply.

Figure 3. A compact cylindrical magnetic lock.
The locking force will probably be rated in newtons (N). You can convert this to kg-force by dividing by 10. (Actually 9.81 m/s², the acceleration due to gravity but 10 is close enough.) Remember that you want the "energise to release" type. These are not the usual types sold.

A: Solenoids will have specs that tell you how hard they can push and how long the travel is. See if you can figure out how much pull is needed to push against the magnets to open it. (Use a string and some known weights to figure it out.) Then find a solenoid that has more push than that. Travel of a half inch or more should do it. Then once you've found the solenoid, look at what type of power it needs. If it needs like 24 volts AC, then you will need to get a transformer. If it needs DC, then you need a power supply. The solenoid will also have an amperage rating. Your transformer or power supply needs to be able to supply more than that.


text:
Q: get value from xml with r by attribute I'm trying to get values from xml that looks like this:
<data>
    <result name="r">
        <item>
            <str name="id">123</str>
            <str name="xxx">aaa</str>
        </item>
        <item>
            <str name="id">456</str>
            <str name="xxx">aaa</str>
        </item>
    </result>
</data>

So far, I can get the id value in the following way:
xmlfile <- xmlParse(url)
data <- xmlRoot(xmlfile)
result <- xmltop[["result"]]
for (i in xmlSize(result)) {
  print(xmlValue(result[[i]][[1]]))
}

This seems highly inefficient and only works if "id" is stored in the first child element. So, is there a way to get the value of an element (123, 456) by searching for the attribute (name) and value (id)?

A: The xml2 package is very good for solving this type of problem.
library(xml2)
page<-read_xml('<data>
    <result name="r">
               <item>
               <str name="id">123</str>
               <str name="xxx">aaa</str>
               </item>
               <item>
               <str name="id">456</str>
               <str name="xxx">aaa</str>
               </item>
               </result>
               </data>')

#find all str nodes
 nodes<-xml_find_all(page, ".//str")
#filter out the nodes where the attribute name=id
 nodes<-nodes[xml_attr(nodes, "name")=="id"]
#get values (as character strings)
 xml_text(nodes)

Update
Using Xpath selectors everything can be accomplished in 1 line
#R verison >4.0
xml_find_all(page, ".//str[@name='id']") |> xml_text()

Here is a link to a handy xpath path cheat sheet:
https://www.red-gate.com/simple-talk/development/dotnet-development/xpath-css-dom-and-selenium-the-rosetta-stone/


text:
Q: Excel VBA - Copy andpaste formula without incrementing I have a number of formulas similar to this one:
=MID('Sheet1'!O40,1,5)

I'm trying to copy and paste this formula to a blank cell without incrementing the cell reference and updating the worksheet reference.
Desired End Result:
=MID('Sheet2'!O40,1,5)

I've used the below code as a test sample but the copied formula auto increments the cell reference. Is there anyway to copy and paste formulas without incrementing?
Range("E2").Copy
Range("E126").PasteSpecial xlPasteFormulas

A: I've come up with a solution below:
Range("E126").Formula = Range("E2").Formula
Set r = Range("E126").SpecialCells(xlCellTypeFormulas)
r.Replace What:="Sheet1", Replacement:="Sheet2", LookAt:=xlPart


text:
Q: Why is this error in Image Component of React-Native? I would like to background black opacity.
I've wrote this code.
<Image source={require('../assets/images/test_img1.png')} style={[s.lastReviewImage]}>
  <View style={s.blackOverlay}/>
</Image>

lastReviewImage: {
    flex:1,
    width: null, height: null
  },
  blackOverlay: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    backgroundColor: 'red',
    opacity: 0.3
  },

But, this is give me a error.

Error: The Image component cannot contain children. if you want to render content on top of the image, consider using absolute positioning.

I know what this error means but I've surely set absolute property in blackOverlay.
I've refer this guides.
Text Overlay Image with Darkened Opacity React Native
https://snack.expo.io/S15Lt3vjg
But, It's not working for me with the error.

A: If you want to set some background color or an image as the Screen Background, you need to use ImageBackground in place of Image.
 <ImageBackground
      source={yourSourceFile}
      style={s.blackOverlay}>
        <....yourContent...>
    </ImageBackground>


text:
Q: how can i do this simple entity relationship diagram? i'm needing help to build an entity relationship diagram efficiently for a project. This is the most important part of my problem:
There are organizations, which can have many challenges inside like for example: they are very small and is very uncomfortable for the employees to work there, they have very old resources to work with, etc.
On the other hand, this challenges can have many ideas to solve them. This ideas can be published by regular clients and employees of the organization too. Also, the idea can be evaluated by many employees of type evaluator. This employees (normal type) belong to an specific organization, except for the type evaluator which can be in many, so i can evaluate many ideas from different org.
So my problem is... in the current version of the diagram, the team related a table user to employees and clients (both tables), this way the user is the one that publishes and idea and then we can see at it's type to check in what table the information is (client or employee). But an idea can have many evaluations, and they have to be done by one or many employees of type evaluator. So an user publish an idea, and an user evaluates and idea? i mean, is enough in the diagram just to specify the relationship between user and idea? do i need to show the relationship user and evaluation to? and if that's so, isn't that like strange in the diagram?
On the other side, i see a bit of recurrence too in the part where they relate organizations with employee, employee with user, user with idea, organization with challenges, challenges with idea. Is that ok in a ERM diagrama?
I just need a little explanation of why you can or cannot do it this way. I'm a bit confused.
I hope you can help me. Thanks!

A: It seems to me like you are creating an ideas management system.
a quick search on google for '"idea management" entity relationship diagram' brought this up, which seems quite close to your mark;

Also, just append the table Company to user and project.


text:
Q: How to replace multiple empty fields into zeroes using awk I am using the following command to replace tab delimited empty fields with zeroes.
awk 'BEGIN { FS = OFS = "\t" } { for(i=1; i<=NF; i++) if($i ~ /^ *$/) $i = 0 }; 1'

How can I do the same, if I have the following input that is not tab delimited and have multiple empty fields ?
input
name              A1348138      A1086070      A1080879      A1070208      A821846       A1068905      A1101931
g1                5       8       1       2       1       3       1
g2                   1       3       2       1       1       2

desired output
name              A1348138      A1086070      A1080879      A1070208      A821846       A1068905      A1101931
g1                5       8       1       2       1       3       1
g2                   1       3       2       1       1       2       0

A: I'd suggest using GNU awk for FIELDWIDTHS  to solve the problem you appear to be asking about and also to convert your fixed-width input to tab-separated output (or something else sensible) while you're at it:
$ cat file
1   2   3
4       6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS='\t' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i=($i==""?0:$i)}; print}' file
1   2   3
4   0   6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS=',' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i=($i==""?0:$i)}; print}' file
1,2,3
4,0,6

$ gawk -v FIELDWIDTHS='4 4 4' -v OFS=',' '{for (i=1;i<=NF;i++) {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$i); $i="\""($i==""?0:$i)"\""}; print}' file
"1","2","3"
"4","0","6"

Take your pick of the above.


text:
Q: CSRF/XSRF Protection for serverless .NET Web API running in AWS Lambda / API Gateway We are looking to run .NET Web API projects as serverless applications hosted in AWS Lambda behind API Gateway [following an approach like this: https://aws.amazon.com/blogs/developer/deploy-an-existing-asp-net-core-web-api-to-aws-lambda/].
For applications that require authentication on the API with a JWT, we have been researching the methods for storing JWTs in local storage vs cookies in our front end SPAs that talk to the API.
It seems like one of the big caveats of using cookies for storing JWTs, specifically the AccessToken, is the potential for XSRF/CSRF attacks.  With server side render apps, the use of anti-forgery tokens embedded in the html payload seems to help mitigate this risk.  However with a SPA and our Web API running within Lambda - with each client request potentially being handled by any currently executing Lambda context (or a new one spun up if needed) this seems like it may be hard to achieve since there would be no persisted state between client request/response from the server.
It seems like generating an analogous temporary secret based on the scopes found in the user's access token might be a way to handle this in a stateless environment. However, with everything related to security, rolling your always seems like a terrible idea.
My question is if there are any known packages/libraries or approaches for this type of use case that can help mitigate CSRF/XSRF for .NET running in a distributed, serverless environment such as AWS Lambda.  Or is the recommended approach to use local storage?


text:
Q: Optimal Search criteria in this array? I just wrote this exam, in which there was question: Consider a array of size 2n, where the numbers in odd positions are sorted in ascending order and the the numbers in even positions in descending order. Now, if I have to search for a number in this array, which is a good way to do this? The options were:

*

*Quick sort and then binary search

*Merge the two sorted arrays and then binary search

*Sequential search

In 1, Quick Sort takes O(n log n) and binary search, O(log n)
In 2, Merge takes O(n) and then O(log n) for binary search
In 3, it takes O(n).
So 3 turns out to be the way to go. Is that correct? Is there a better choice which might not have been given?
EDIT: I accepted Lukas's answer since he was the first. Sigh, that was the other option. I get a -1. :(

A: You can do two binary searches -- that's O(log n), because you ignore constants (2 in this case).

A: Would it not be easier if you just did a binary search on both sets? Thus O(log n) and O(log n)?
Would that not be easier, so if found in the first, the second step is not even required?

A: Check whether it's even or odd, and binary search on the part of the array you're interested in. O(log n).

A: I think second option fits your criteria.
Merge sort: We can easily get full array of sorted numbers from two half sorted arrays with time complexity of O(n)
And then binary search will have time complexity of O(logn)


text:
Q: Laravel 5 access to ajax Post Data I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault();     // Disable normal behaviour of the element (Form)

var formData = {
    form: $("#newCustomerForm").serialize()     // Transmit all input data of the form serialized
}

console.log(formData);      // Log to the console the Input data

$.ajax({
    type: 'post',           // POST Request
    url: 'save',            // Url of the Route (in this case user/save not only save)
    data: formData,         // Serialized Data
    dataType: 'json',       // Data Type of the Transmit
    beforeSend: function (xhr) {
        // Function needed from Laravel because of the CSRF Middleware
        var token = $('meta[name="csrf_token"]').attr('content');

        if (token) {
            return xhr.setRequestHeader('X-CSRF-TOKEN', token);
        }
    },
    success: function (data) {
        // Successfuly called the Controler

        // Check if the logic was successful or not
        if (data.status == 'success') {
            console.log('alles ok');
        } else {
            console.log(data.msg);
        }
    },
    error: function (data) {
        // Error while calling the controller (HTTP Response Code different as 200 OK
        console.log('Error:', data);
    }
});

Route:
Route::post ('user/save', 'CustomerController@createNewCustomer');

Controller:
public function createNewCustomer (Request $request)
{
    $inputArray = $request->all();

    print_r ($inputArray['form']);

    // Set JSON Response array (status = success | error)
    $response = array ('status' => 'success',
                       'msg' => 'Setting created successfully',);
    // Return JSON Response

    return response ()->json ($response);
}

In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}

I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?

A: The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.

A: You can access like this
$request['name of field'];

A: i think you need to receive the data in the controller as json:

    $request->json('field_of_interest')

A: The problem is your formData variable. Instead of:
var formData = {
    form: $("#newCustomerForm").serialize()
}

it should be
var formData=$("#newCustomerForm").serialize();


text:
Q: What is the Max value of n when 185! is divided by (189^n) will give an Integer Value?
What is the Max value of n when $185!$ is divided by $(189^n)$ will give an Integer Value?

Options are
a) $91$
b) $30$
c) $36$
d) $24$
MyApproach:
$189$=$3^3$ . $7$
When $185$/$3$=$61$
$61$/$3$=$20$
$20$/$3$=$6$
$6$/$3$=$2$
Its Remainder Sum=$89$
$185$/$7$=$26$
$26$/$7$=$3$
Its Remainder Sum=$29$
So,3^89 . $7$^$29$
$27$^$29$ . $7$^$29$
I am getting $29$ as the final Ans.
Required Ans is 30
Why i am getting the Ans wrong?
Also,
Is there any better approach i can solve this problem.

A: Well,
Prelude> let m = product [1 .. 185] :: Integer
Prelude> m `mod` (189^29)
0
Prelude> m `mod` (189^30)
37470960172551150153411831285317353601062526805310229978097429296724

it's not you who is wrong. Your result is correct, the required answer is incorrect.

Is there any better approach I can solve this problem?

Not really, counting the (relevant) prime powers dividing the factorial is the best method generally.

A: Your answer is right. Here is how I do it:
As $189=3^3\cdot 7$, $\;185!$ is divisible by $189^n=3^{3n}\cdot7^n$ if and only if
$$v_3(185!)\ge 3n\enspace\text{and}\enspace v_7(185!)\ge n$$
(for a prime number $p$, $v_p(n)$ denotes the $p$-adic valuation of $p$ in $n$, i.e. the exponent of $p$ in the decomposition of $n$ into its prime factors)
We can use Legendre's formula to find the valuations of a factorial:
$$v_p(n!)=\biggl\lfloor\frac np\biggr\rfloor+\biggl\lfloor\frac n{p^2}\biggr\rfloor+\biggl\lfloor\frac n{p^3}\biggr\rfloor+\dotsm$$
(this sum is actually finite). In the present case we obtain:
$$v_3(185)=61+20+6+2=89,\quad v_7(185)=26+3=29,$$
hence we must have $\;3n\le 89$ and $n\le 29$. The greatest $n$ that satisfies both conditions is indeed $29$.

A: The problem can be analize of a different approach. If we analize $185!$ taking advantage that $7$ is prime, we see that
$$
185!=n(7*14*21*28*35*42*49*56*63*70*77*84*\ldots*175*182).
$$
The number of factors that contains $7$ are $[185/7]=26$. But, there others factors that altes our result such that
$$
49,98,147.
$$
In summary, there existe $m\in\mathbb{Z}$ co-prime with $7$ such that
$$
185!=m*7^{26+1+1+1}=7^{29}m.
$$
If $189^n$ divides $185!$ is neccesary that $7^n$ divides $185!$. For our last result $n\leq 29$. So if $189^n$ divides $185!$, then $n\leq 29$.
If we analize for $3$ we have:
$[185/3]=61$.
$[185/9]=20$.
$[185/27]=6$.
So, we have that $185!=3^{61+20+6}r=3^{87}r=27^{29}r$. With $r$ does not contain $3$. For all of this we have
$$
185!=27^{29}7^{29}k=189^{29}k,
$$
where $k$ doesn't contain $189$. This means that the max $n$ such that $189^n$ divides $185!$ is 29.
The options are wrong.


text:
Q: Migration of tables to database screenshot of Error i am getting>Illuminate\Database\QueryException SQLSTATE[HY000] [1049] Unknown database 'hiring' (SQL: insert into hirings (name, email, subject, message, updated_at, created_at) values (, , , , 2018-01-24 19:31:19, 2018-01-24 19:31:19))
Portfolio is my database name
In .env file is the same, my model name is hiring, my table name is create_hiring_table everything looks fine to me. Anything I am missing?
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:9ALfdXT6SdgOkZ3gFVCExTFY4z/8yzOfbuCuB7dA1h0=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=portfolio
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

my model name hiring.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class hiring extends Model
{
    use Notifiable;
protected $fillable = [
    'name','email','subject','message'
];

protected $hidden = [
    'password', 'remember_token',
];
}

my controller named mainController
<?php
namespace App\Http\Controllers;
use App\hiring;
use Illuminate\Http\Request;

class mainController extends Controller
{
    public function index(){
        return view('main.main');
    }
    public function store(Request $request){
        $hiring = new hiring;

        $hiring-> name = $request->name;
        $hiring-> email = $request->email;
        $hiring-> subject = $request->subject;
        $hiring-> message = $request->message;

        $hiring-> save();
        return view('main.main');
    }
}

My table is following named create_hiring_table
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateHiringsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hiring', function (Blueprint $table){
            $table->increments('id');
            $table->timestamps();
            $table->string('name');
            $table->string('email');
            $table->string('subject');
            $table->string('message');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('hiring');
    }
}

This is config/databse.php
<?php

 return [

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => env('DB_CONNECTION', 'mysql'),

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => [

    'sqlite' => [
        'driver' => 'sqlite',
        'database' => env('DB_DATABASE', database_path('database.sqlite')),
        'prefix' => '',
    ],

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'prefix' => '',
        'schema' => 'public',
        'sslmode' => 'prefer',
    ],

    'sqlsrv' => [
        'driver' => 'sqlsrv',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '1433'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'prefix' => '',
    ],

],

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => [

    'client' => 'predis',

    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => 0,
    ],

],

];

A: just add protected $table = 'hiring';
    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class hiring extends Model
{
use Notifiable;

protected $table = 'hiring';

protected $fillable = [
    'name','email','subject','message'
];

protected $hidden = [
    'password', 'remember_token',
];
}

A: i found the mistake ever in web.php the rout should be Route::post('/main', 'mainController@store'); instead of Route::get('/main', 'mainController@store');


text:
Q: What is the best practice to deal with Google Play Store Security Alert? I have received the following error from Google Play developer console:
"Please address this vulnerability as soon as possible and increment the version number of the upgraded APK. To properly handle SSL certificate validation, change your code to invoke SslErrorHandler.proceed() whenever the certificate presented by the server meets your expectations, and invoke SslErrorHandler.cancel() otherwise."
I guess the issue is caused by my implementation of "onReceicedSslError()". I always proceed with "handler.proceed()" without any checking.
I would like to know what is the best practice to deal with SSL error. And if I do some domain checking, will Google Play still show me such alert?
Thanks in advance.

A: You should just remove your onReceivedSslError implementation and use the default behavior, which is to cancel.
The best practice is to treat it like you couldn't connect to the server. Most people have no reason to override certificate checking at all.


text:
Q: Which child view will be called first under parent state in AngularJS? I want to know sequence of call of below nested views if declared under parent view. Which nested view is called first?
.state('index',
{
    url: '/index',
views: {
 '': {
    templateUrl: 'AngularJS/Templates/indexView.html',
    controller: 'indexController'
 },
 'view1@index': {
     templateUrl: '/AngularJS/Templates/View1.html',
     controller: 'View1Controller'
 },
 'view2@index': {
     templateUrl: '/AngularJS/Templates/View2.html',
     controller: 'view2Controller'
 },
 'view3@index': {
     templateUrl: '/AngularJS/Templates/View3.html',
     controller: 'view3Controller'
 }

I want to know which will be called first, (view1 or view2 or view3). they have their respective controller.js file. I want to alter the sequence of call because it calls any random view. I have one logic which needs view3 to be called first and then view1 and view2
Please suggest.


text:
Q: Sound Waves and the Boltzmann Distribution Imagine a sound wave traveling linearly in a given direction through a monatomic ideal gas.
Based on gas laws and the wave equation, we have that the wave should travel, in that given direction, at a speed of $\sqrt{\frac{5k_bT}{3m}}$, where $k_b$ is Boltzmann's Constant, $T$ is the temperature, and $m$ is the molecular mass.  However, we have, per the Boltzmann Distribution, that the root-mean-square molecules in that dimension is merely $\sqrt{\frac{k_bT}{m}}$.  In other words, this means that the sound wave (and, consequently, the molecules carrying the sound wave) are moving faster than the air molecules are moving in general in a given dimension.  Theoretically, this means that the kinetic energy of the gas molecules is vastly increasing in the presence of sound, which would in turn cause a vast temperature increase, something that does not match up with real-life experience in a noisy room (to be fair, air is mostly diatomic, but changing the coefficient from $\frac{5}{3}$ to $\frac{7}{5}$ doesn't fundamentally change things).
What am I missing?

A: You seem to be interested in reconciling the molecular view with the view of continuum theory.
The average velocity in the direction of sound propagation, which you estimate to be
$$ \bar{v}_x=\sqrt{\langle v_x^2\rangle} = \sqrt{\frac{k_BT}{m}}$$
amounts to about 300 m/s, which is already quite close to the actual speed of sound. You may regard this number as an estimate for the speed at which pressure variations in the gas can be 'communicated' among gas molecules along the wave.
Note, however, that a sound wave is a collective excitation of gas molecules. Individual packets of a large number of air molecules oscillate back and forth with a typical speed much (i.e. orders of magnitude) smaller than the thermal motion of individual molecules or the speed of sound. For a sound wave of 60 dB SPL, I find a speed of these wave packets of 68 $\mu$m/s. This low speed (compared to the thermal molecular speed of about 500 m/s) does clearly not cause any significant temperature increase.
The continuum description is possible, because a large number of molecules within one packet exert an effective pressure on the neighboring packet by intermolecular collisions combined with their thermal speed.

A: I think the problem with your argument is that it is possible to define a whole series of "average speeds" with variations between them of several percent (most probable speed, rms speed, mean speed...). So, taking one of these speeds, you can believe that the sound wave has changed the speed of molecules of several percent, which is not the case.
What we can say is that the speed of sound is of the order of magnitude of the speed of the molecules and it is in agreement with the idea of a very weak perturbation, propagated by the molecules.
(Sorry for my english)

A: The (phase) speed of the sound wave is not the speed of the particles in the wave nor the speed with with macroscopic parcels of the gas move around. The  velocity of the macroscopic parcels of is is much lower than the phase speed of the wave. Both have no direct relation to the average thermal speed distribution. (Further, a sound wave is not an equilibrium phenomenon, so deviations from the equilibrium behaviour should not be surprising per se.)
The drift velocity (so to say, the macroscopic velocity of the gas) in a sound wave can be obtained by applying the continuity equation for the mass current:
$$ \dot \rho + \nabla \cdot \vec j = 0. $$
The dependency of the mass current on the drift velocity is
$$ \vec j = \rho \vec v_D. $$
The mass profile in a plane wave with wave number $k$ travelling with the speed of sound $c$ in $x$-direction is given by (where $\delta$ is the amplitude and assumed small compared to the density $\rho_0$ since otherwise we will get out of the validity of the assumption of a linear density-pressure response – remember that we use the adiabatic compressibility to derive the phase velocity):
$$ \rho(\vec r, t) = \rho_0 + \delta \cos(ckt - kx). $$
Using the continuity equation we can determine the mass current, and from that the drift velocity, by calculating the derivative:
$$ \partial_t \rho = -\nabla \cdot \vec j = -\delta c k \sin(ckt-kx) $$
and then the anti-derivative:
$$ \vec j = \vec j_0 - \delta c \cos(ckt - kx). $$
The anti-derivative allows for an additional global mass current (a wind blowing through all our system), which we can just set zero (because it has nothing to do with the sound wave, but can be removed by Galilei transforming the system).
So the drift velocity of the gas at a fixed location (let's say zero, all locations should be roughly equivalent in a plane wave) is (remember: we assumed $\delta \ll \rho_0$):
$$ \vec v_D(\vec 0, t) = \delta c \cos(ckt) / \rho(t) \approx \delta c \cos(ckt)/\rho_0 \approx \frac {cp} {p_0} \cos(ckt). $$
So the macroscopic parcels of the gas oscillate around with a maximal drift speed that is proportional to the relative amplitude of the wave and the speed of sound, so it is always lower than the speed of sound in the gas (and the validity of the linear wave equation is no longer given long before that – if the speed of the gas in the wave approaches the speed of sound there will be shock waves not sound waves).


text:
Q: Native Base Toast does not work in Live mode We're using NativeBase in a React Native app. We're trying to show a Toast component based on an error that is set in a redux action because it happens via a call to the API.
It works perfectly in debug mode but does not work in Live build. Please, suggest what can we do?
Code:
export const toastr = {
  showToast: (message, duration = 2500) => {
    Toast.show({
      text: message,
      duration,
      position: 'bottom',
      textStyle: { textAlign: 'center' },
      buttonText: 'Okay',
    });
  },
};

And then
toastr.showToast('Verication code is invalid.');