text:
Q: Para que serve o comando key:generate do Laravel? Eu sempre vejo esse comando como um requerimento para rodar projetos clonados, mas qual o seu propósito?

A: O comando key:generate é usado para definir uma nova chave no seu arquivo .env, que esta localizado na pasta inicial, ele seta o valor dentro de .env em:
APP_KEY=<chave gerada>

Note que ao executar:
composer create-project --prefer-dist laravel/laravel <nome da pasta do projeto>

Ou se instalou o laravel-installer (composer global require laravel/installer):
laravel new <nome da pasta do projeto>

Ele irá executar automaticamente o comando sem precisar fazer manualmente, somente será necessário o comando acaso deseje uma nova chave ou acaso tenha clonado um projeto que use laravel, mas que não é o proprio de fato.
O uso desta chave é como dito pelos próprios comentários do código oficial:

Essa chave é usada pelo serviço de criptografia Illuminate e deve ser definida como uma cadeia aleatória de 32 caracteres, caso contrário, essas cadeias criptografadas não serão seguras. Faça isso antes de implantar um aplicativo!

Ou seja é uma chave que é usada em geral para diversas funcionalidades que exigem criptografia dentro das "APIs" do Illuminate.
Um detalhe importante, conforme o colega @Bacco mencionou, a chave não deve ser alterada em um projeto que já tenha armazenado dados baseados nesta chave (algo feito com as APIs do Illuminate), se fizer isso vai invalidar todos dados, o que vai quebrar a aplicação
Se está começando a usar um projeto de baseado em Laravel, como October ou um sistema qualquer a chave só deve ser nova se o tal projeto não possuir dados em banco ou caches e realmente estiver começando do zero.


text:
Q: Issue with UIButton in UIViewController instead of UITableView I am using the following code for a specific button in my UIView. Bare in mind that this code works perfectly in a UITableView but doesnt seem to work for me in a UIViewController. When I press the button it just hangs
 UIButton *buyButton = [[UIButton alloc] initWithFrame:CGRectMake(-1, 370, 320, 60)];
        UIImage *btnImage = [UIImage imageNamed:@"upgrade-new.png"];
        [buyButton setImage:btnImage forState:UIControlStateNormal];
        [buyButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13.0]];
        [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buyButton.titleLabel setShadowColor:[UIColor colorWithWhite:0.1 alpha:1.0]];
        [buyButton.titleLabel setShadowOffset:CGSizeMake(0, -1)];
        [buyButton addTarget:self action:@selector(buyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        buyButton.tag = 0;
        [[self view] addSubview:buyButton];

Method for button
- (void)buyButtonTapped:(id)sender {

    UIButton *buyButton = (UIButton *)sender;
    SKProduct *product = [_products objectAtIndex:buyButton.tag];

    NSLog(@"Buying %@...", product.productIdentifier);
    [[RageIAPHelper sharedInstance] buyProduct:product];

}

I'd appreciate some guidance on this!

A: It looks like there are some more people looking out for the same problem as you. Have a look at this post, the question was the same as yours.
https://stackoverflow.com/a/14175601/1141395
For me it looks like this won't work because you have to receive available products you already added to ITunesConnect. You can press your UIButton to get the process started but the products should be received inside following delegate method:
-(void)productsRequest:(SKProductsRequest *)request
    didReceiveResponse:(SKProductsResponse *)response

A: The reason why it worked before is most likely due to you handling your _products array well when you had your tableViews.
Now that you have changed this around, the chances are that something has broken with your _products array while you were trying to implement the button in your UIViewController
It hangs because either the application crashes or because your RageIAPHelper instance wasn't expecting a null object.
I suggest you follow what happens with your products array and do some debugging to find out why null is being returned. Just make sure your _products array is being populated correctly, ensure that the objects are inside the array maybe by printing it to double check its all there, and soon enough you'll find out exactly why your _products array is empty

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot write to .service file from bash command I am trying to execute this command sudo echo "banana" >> /etc/systemd/system/wallChange.service, but I am getting this error message: bash: /etc/systemd/system/wallChange.service: Permission denied. Previously, I managed to run sudo touch /etc/systemd/system/wallChange.service successfully, therefore creating the /etc/systemd/system/wallChange.service file. How can I bypass this situation? I need to add the content of the /etc/systemd/system/wallChange.service file using a bash command, as these commands are going to be run from a node.js program, which doesn't allow me to open an editor through bash, such as doing something like sudo nano /etc/systemd/system/wallChange.service

A: One of my colleagues answered me this question, thanks, Jake :)
The problem was that I was running echo command with su privileges, but I had to actually run bash in su mode. Therefore, the command which solved the problem is: sudo bash -c "echo 'banana' >> /etc/systemd/system/wallChange.service"


text:
Q: TypeError: builder.LuisRecognizer is not a constructor I tried to use the LuisRecognizer as stated in the documentation for getting the suitable intent.
Initialized the builder with:
var builder = require('botbuilder');
var luis = new builder.LuisRecognizer(luisRequest);
var intents = new builder.IntentDialog({intentThreshold:thresholds["luis"], recognizers: luis});
console.log(intents)

But I get back:
TypeError: builder.LuisRecognizer is not a constructor

Did I overlook something? The documentation seems up to date.
luisRequest is correct, I already checked.
Thank you for your help!

A: The parameter should be the URL from luis.ai > Manage > Azure Resources, represented by a string:
const luisrecognizer = new builder.LuisRecognizer(process.env.LUIS_MODEL_URL);


text:
Q: How to create 3 column layout using css without using grid(For ie 10 compatibility) How to convert following HTML, similar to the image? Do not wrap elements inside another div.  My purpose is to change the position of each elements to left, right or top using css only. Is it possible?

1

2

3

4

5

6

A:

div.container {
  width:100%;
  position:relative;
  height:100%
}
.col {
   min-heght:20px;
   float: left;
}
.col-inner {
  padding: 10px;
  background: gray;
}
.col-60 .col-inner {
  padding: 10px;
  background: blue;
}
.col-20{
  width:20%;
  position:relative;
  line-height: 60px;

}
.col-60{
 width:60%;
 position:relative;
 line-height: 60px;
}
.item {
    border: 1px solid;
    margin: 2px;
    text-align: center;
    min-height: 60px;
    border-radius: 5px;
    vertical-align:middle;
    background: #ddd;
}
.main-contain{
  min-height: 200px;
  line-height: 2000px;
}

1

2

4

6

main

3

5

A: ** EDIT 2: It's almost impossible to move arrange elements using only HTML and CSS.  There might probably be a solution for this, but the most efficient one would be to use the jQuery appendTo() function.
This article might be of great use to you: How to move an element into another element?

** EDIT: I figured out lately what you were looking for. I'll try to find an answer for your issue as soon as possible.

Based on your example, you can achieve this by creating 3 columns(in my code I used divs with "column" class) and applying display: inline-block; to them, making sure that the sum of the columns combined won't be higher than 99%.
The display: inline-block will try to use the whole width of the parent container, without the content to overflow it. When the width is larger than 99%, the last column is sent to the next row.
HTML

1.1

1.2

1.3

2.1

2.2

3.1

3.2

3.3

3.4

CSS
.column {
  text-align: center;
  vertical-align: top;
  padding: 10px 0px;
  display: inline-block;
  width: 100%;
}

@media only screen and (min-width: 900px) {
.column.one-fourth { width: 24.75%; }
.column.two-fourth { width: 49.5%; }
}

.column div {
  background: red;
  margin: 10px;
}

.column p {
  color: white;
  font-weight: bold;
  font-size: 50px;
  margin: 0px;
}

Here's a codePen to see how it works: https://codepen.io/ialexandru/pen/NWPzRZj


text:
Q: How to access Angular.js $scope from other method? For example, I have such request to my server. As a response, I will get an array of objects with parameters: id, name and position. All of these loads into a table. How can I manipulate with an array $scope.employees if i will decide to change it later?
An answer from server is:
data = [{"id":1,"name":"Jack","position":"City guard"},{"id":2,"name":"Jim","position":"Sheriff"},{"id":4,"name":"Jack","position":"Cruel genius"},{"id":7,"name":"Guy","position":"Manager"}]

And how to be sure, that request is already posted into a table, so i can perform some later operations?
angular
    .module('MyApp', [])
    .controller('MyController', ['$scope', '$http', MyController]);

function MyController ($scope, $http) {

    $http.get("/servlet").success(function(data){
        $scope.employees = data;
    });

}

function otherOperation () {
    $scope.employees.push({
        id : 5,
        name : "John",
        position : "Manager"
    });
}

HTML code:

                         ID
                         Name
                         Position

                        {{employee.id}}
                        {{employee.name}}
                        {{employee.position}}

                <button ng-click="otherOperation"> Button </button>

A: The otherOperation method should be nested inside MyController, like this:
angular
.module('MyApp', [])
.controller('MyController', ['$scope', '$http', MyController]);

function MyController ($scope, $http) {

    function otherOperation () {
         $scope.employees.push({
             id : 5,
             name : "John",
             position : "Manager"
         });
     }

     $http.get("/servlet").success(function(data){
        $scope.employees = data;
     });

}

You could also pass the $scope as a parameter, like this:
angular
.module('MyApp', [])
.controller('MyController', ['$scope', '$http', MyController]);

function MyController ($scope, $http) {

     $http.get("/servlet").success(function(data){
        $scope.employees = data;
     });

     otherOperation($scope);

}

function otherOperation ($scope) {
     $scope.employees.push({
        id : 5,
        name : "John",
        position : "Manager"
     });
 }


text:
Q: Get a multiple-index column values Let's assume we have a DataFrame df with N rows:
| multiple-index |  | ordinary columns |
I_A, I_B, I_C, I_D,  C_A, C_B, C_C, C_D

How can we extract all N values for I_B index column? df.index gives us all combinations of I_A...I_D but it is not what we need. Of course, we can iterate over it but it will cost productivity, there must be an easier, more straightforward way?
Thank you for your time.
UPDATE
E.g., we have df generated by:
data = {
    "animal": ["cat", "dog", "parrot", "hamster"],
    "size":   ["big", "big", "small", "small"],
    "feet":   [4, 4, 2, 4]
}

multi = pd.DataFrame(data)

multi.set_index(["size", "feet"], inplace = True)

and which is:
              animal
 size feet |
  big    4 |     cat
  big    4 |     dog
small    2 |  parrot
small    4 | hamster

Its index is:
MultiIndex([(  'big', 4),
            (  'big', 4),
            ('small', 2),
            ('small', 4)],
           names=['size', 'feet'])

from which we would like to get all sizes:
['big', 'big', 'small', 'small']

How can we do that?

A: I think you're looking for MultiIndex.get_level_values:
multi.index.get_level_values('size')

Output: Index(['big', 'big', 'small', 'small'], dtype='object', name='size')
Or as list:
multi.index.get_level_values('size').to_list()

Output: ['big', 'big', 'small', 'small']


text:
Q: Angular4 micro front-ends We have an application composed by multiple services, where there is a edge service routing and load balancing all request to the individual services.
The backend REST API is deployed without problem on each server, but we have one single Angular4 application that references routes to modules that are developed in conjunction with this backend REST APIs.
If we release a new version of a service, we deploy the backend and the edge server starts to route to the new version.
The problem is that, we always need to redeploy the edge server in order to replace the full Angular4 application, because the specific module were updated.
We user angular-cli and it generates (and hashes) webpack bundles automatically. All our service modules are declared as npm dependencies in the main application and bundled as one.
How can we build, package and deploy the Angular4 application and our service modules, in order to make the main application reference external bundles and keep the routing working as expected?
Thanks in advance.
PS: the backend services and edge server are Spring Cloud applications using Netflix OSS.

A: Angular-CLI 1.6 will code split your lazy-loaded feature modules into separate chunks that could, in theory, be deployed independently. ng build. Note that this only works if you are lazy-loading the feature modules.
The alternate solution would be a micro front-end architecture. Although the idea is in it infancy it is still worth exploring:
https://medium.com/@tomsoderlund/micro-frontends-a-microservice-approach-to-front-end-web-development-f325ebdadc16
https://micro-frontends.org/


text:
Q: Select query to get values from another column, based on value in original column My question title may be a little vague, but this is more or less what I'm looking to do.
I've got two columns, and I want to grab all of the values of the second column (call it hash), based on the first column (call it nid).
So whenever the nid is the same, get all values from the hash column corresponding to that nid.
Something like select hash from table where nid = the same.
How would I go about doing this?
I see that there's Group By, but that just seems to get me only one hash value. Is there a way to do this with a SQL query?
| nid | hash |
|  2  | blah |
|  2  | test |
|  2  | goof |
|  3  | next |
|  3  | word |

So for example, I'd like to select blah, test, and goof if I'm trying to get every value associated with nid 2.

A: Use GROUP_CONCAT which will return a concatenated string of all matching values from column 2
So basically something like below:
SELECT nid, GROUP_CONCAT(hash) AS hashes
FROM tablename
WHERE nid IN (<somevaluesyouwant>)
GROUP BY nid


text:
Q: Common-collector Colpitts oscillator with lossy inductor I'm trying to build a common-collector Colpitts oscillator with a resonant frequency of 8 MHz. The inductor (20 μH) has a low q factor and can't be exchanged. The two capacitors should have 33 pF and cause a resonant frequency of about 8.7 MHz. This is the circuit:

The 1 kΩ resistor represents the inductor losses. If I simulate the circuit without the resistor it oscillates as expected.
When I add the resistor the circuit only oscillates when I increase C2 to about 150 pF.
This is probably because of the increased feedback factor (at resonance) which is \$\frac{C_1 + C_2}{C_1}\$.
The circuit only oscillates when C2 is at least 150 pF. C1 can be smaller or bigger then 150 pF. Why is the circuit only oscillating with C2 bigger than 150 pF? Are there any changes I can make to get an 8 MHz oscillating frequency?
Edit: I simulated the circuit with an open loop like suggested in an answer. In the following simulation I only changed C2 in parallel with the emitter resistor:

A: You should consider opening the loop and doing an AC analysis to understand what's going on. Here's your circuit in micro-cap with the loop opened. Generator V2 is added and the emitter voltage is monitored across the spectrum 1 MHz to 30 MHz. To make things work as expected, the emitter resistor is loaded with a 33 pF thus loading it correctly. And, the effective emitter resistance is modelled as a 10 Ω resistor, R5: -

The 1 kΩ resistor across the inductor is initially set to be 1 MΩ. Here's a the AC response: -

Points to note: -

*

*It should oscillate at around 7 MHz or 8 MHz (see the green boxes I added)

*The phase angle is as near as damn it 0° hence, it's the oscillation point

*The gain is 1.091 dB hence there is enough gain to sustain oscillation

Here's what happens when I reduce R2 from 1 MΩ to 100 kΩ to 10 kΩ to 5 kΩ to 2 kΩ and finally to 1 kΩ: -

As you can see, for the lower values of R2, there is never a point when the phase change is 0° AND there is a gain greater than unity. Hence it will never oscillate with 1 k to 5 k loading.

Are there any changes I can make to get an 8 MHz oscillating
frequency?

My answer is all about helping you understand how close a given scenario is to producing oscillation. If you change components and run a transient analysis, it will either oscillate or not and, there's no quick method to figure out what that oscillation frequency is.
So, do what I have shown you; open the loop, insert a generator, load the emitter appropriately and test scenarios this way. When you are happy you are close to what you want, run it in transient analysis and it should oscillate.
You are looking for a phase angle of 0° coincident with a gain of greater than unity.

A: Is that a common collector colpitts?
This one works:

Not exactly 8MHz but close :-)


text:
Q: Where can I find the kernel logs? Anybody know the best way to write/read/commit/document/upload errors in the kernel log in Ubuntu 10.04?
Are there a tool suitable for this type of job in the UBuntu Software repositories?

A: For those with server/no monitor access you can access the logs using tail
tail -f /var/log/kern.log

A: dmesg command can also be used to display the kernel log. It can be used as follows.
dmesg -k -w

A: I guess you can also use gnome's application:
System -> Administration -> Log File Viewer

A: There is a nice graphical viewer for the kernel logs by the people at KDE.
KSystemLog


text:
Q: Is it possible to move all printers to a new Mac? I just got my wife a new MacBook Pro and I'm about finished with transitioning from her old one to the new one.
One thing I have yet to do is setup the printers.
Is there a way to move all of the connected printers from her old MBP to the new one without having to set them all up from scratch again?

A: Given the problems some people reported with printers during (early adopter) updates from 10.5 to 10.6, I'd not try to migrate the drivers...
Just plug-in the printers and see what happens?


text:
Q: site wont open in SharePoint Designer 2013 with ssl/https Any ideas why I cant get to open a sharepoint site using  SharePoint Designer 2013  when using ssl/https.
The site is using TMG.
Any ideas what to check and what to do.
I have added the site to trusted zone etc..
Looking at fiddler this is the error i have got:
/_vti_bin/shtml.exe/_vti_rpc
HTTP/1.1 401 Unauthorized ( The server requires authorization to fulfill the request. Access to the Web server is denied. Contact the server administrator.  )
Thanks in Advance

A: Well I don't know what TMG is, and there are countless things it could be.  I know this question is pretty old, but I'll give it a shot because these kinds of questions come up a lot and deserve an answer - especially since I just figured out some fixes for these kinds of issues & would like to pass them along.
The answer from
https://stackoverflow.com/questions/5272336/sharepoint-designer-unable-to-open-site :

In my case, the problem was caused by a custom IIS Http Module, who
  was doing some checking on request form variables. It was only
  checking if HttpRequest.Form property <> null, and it seems this type
  of check crashes the request made by Sharepoint Designer.

Is this what TMG is, a custom IIS Http Module?  Don't use that trash!
If it's not an IIS Http Module, or disabling/removing it doesn't work, for any authentication issue, you need to go to IIS on the server and go to the web application, select Authentication.  Ensure you have Windows Authentication enabled, the rest disabled.  If you have to make changes, ensure you recycle the Application Pool associated with the Web Application (look in the properties of either one to discover what is associated with what for your environment).
Then, try running SPD with the account that is the identity account for the application pool using a runas /user:domain\user "C:\Program Files..." and the path for SPD.  Having to put in the password for that account will ensure that the account is not locked/password hasn't expired.  If so, reset it in Active Directory.
If you still have issues after that, it's possible the account doesn't have rights as a site collection admin on the site.  Fix this in Central Admin by going to Application Management > Change site collection administrators and select the site collection you're trying to access.
While there, making sure SPD is enabled in Central Admin doesn't hurt:  Check/refresh the setting under General Application Settings > SharePoint Designer > Enable managing of the Web Site URL Structure.
Next, try taking off SSL/HTTP and just making it a port 80 binding.  Do you still get the issue?  If not, it's a certificate issue.  Ensure it is imported into the Trusted Root Certificates Store using Run > mmc, File > Add/Remove Snap-in, choose Local Computer, add the Certificates (Local Computer) snap-in, choose Next on the rest of the prompts, Finish. Navigate in the tree, find "Trusted Root Certificates Store", right-click, select Import Certificate.  Navigate to the SSL.cer file, select it, select OK, import should be successful.  Re-apply SSL/port 443.  Recycle the app pool, then try your site again.  If you get any certificate errors, be sure whether or not they are truly locking you out or if they just say something dumb like warning you about going from HTTP to HTTPS, or are saying the root certificate is not installed (which is a separate certificate you need in your Trusted Root Certificate Store, also, that is the certificate of the certificate server that authorized your web site's certificate).  If none of that works, try getting and applying a new SSL cert.
The specific error in SPD would've been nice to have.


text:
Q: Remove values from Ruby map I have an object that looks like this in Rails console:
  pry(#<User>)> favorite_foods
  => [#<FavoriteFood id: 3, food_id: 1, user_id: 1, removed: false, created_at: "2015-09-06 00:49:35", updated_at: "2015-09-06 00:49:35">,
  #<FavoriteFood id: 4, food_id: 2, user_id: 1, removed: true, created_at: "2015-09-06 12:16:56", updated_at: "2015-09-06 12:17:36">]

favorite_foods is in a polymorphic relationship with foods.
has_many :favorite_foods
has_many :favorites, through: :favorite_foods, source: :food
has_many :foods, through: :favorite_foods

In the favorite_food.rb model, I'm setting favorite foods by using this method:
 def favorited_foods
   favorite_foods.map(&:food_id).to_set
 end

I need to be able to remove all instances of favorite_foods where the field "removed" equals true.
For example: from the console session above, I want favorite_foods to include food_id 3, not food_id 4.
What is a clean way to do this in the favorited_foods method? I tried incorporating .reject and it ignored it.
Thanks for any advice!

A: You can just simply do:
FavoriteFood.where(removed: true).delete_all

which will delete all the FavoriteFood records where removed is true.
If you want to do it using map, then you can do:
favorited_foods.select { |f| f.removed == true }.map { |f| f.delete }

but this is not recommended as it will call delete method once for each record. The better way is deleting them all using delete_all as shown above.

A: Can't you do something like:
def remove_favorited_foods
  favorite_foods.each {|food| Food.destroy(food) if food.removed?}
end

You should also add has_many :foods, dependent: :destroy, through: :favorite_foods to your model to ensure that the favorite foods are destroyed accordingly. See this guide.


text:
Q: Why does it keep saying undefined method? Could someone please explain what I'm doing wrong.
fb = 2
fa = 100
def fc
    fa = fa - fb
end
puts "#{fa}"
fc
puts "#{fa}"

A: Inside your fc method, the code does not know what fb is. In that context, both fa and fb are meaningless. (fa does not throw the same error since you are also doing assignment but that's besides the point).
To use fa and fb in your fc method, you need to pass them. Try this:
fb = 2
fa = 100

def fc(fa, fb)
  fa - fb
end

puts "#{fa}"

fa = fc(fa, fb)

puts "#{fa}"

A: fa and fb variables are not defined in the context of the fc method, so, the fc method does not know anything about them. You can't use outside scope's variables inside a method like that. You need to pass the required arguments to the fc method:
fb = 2
fa = 100

def fc(fa, fb) # fc method takes two arguments: fa and fb
    fa = fa - fb # Now, fc method knows about fa and fb variables/arguments
end

p fc(fa, fb) # pass fa and fb as arguments to the fc method
# => 98

A: The function fc cannot use the variables fa or fb, as they're excluded from its scope (we say the function has no "closure" over those variables). A proc or lambda does have a closure:
    fb = 2
    fa = 100
    fc = proc {
        fa = fa - fb
    }
    puts "#{fa}"
    fc.call
    puts "#{fa}"


text:
Q: Focal plane of ideal thin lenses and spherical mirrors Recently I was studying about optical instruments and in my book I came across a point which stated that
When non axial parallel rays are incident on an ideal spherical mirror at a small angle or a parabolic mirror, the rays meet at a point on the focal plane rather than the focus point.
Also in the section about refracting telescopes, diagrams drawn show that the non axial parallel rays meet at a point on the focal plane.
Please note that I'm talking about concave mirrors and convex lenses and aberration and other non idealities are ignored.
I looked at some of the websites like this and this to understand why it is the case but an explanation is lacking everywhere.
I mean, can we show that non axial parallel rays will always converge at a point on the focal plane?
I tried to proceed by attempting to find the equation for the focal plane but I don't think that will work at all.
Could anybody please tell me a way to do this?
How do we guarantee that a group of parallel (non axial) rays incident on a spherical mirror or a lens will always converge at the focal plane (assuming ideality)?
I also saw this SE post and tried to follow the "Physics Teacher" link mentioned in comments but couldn't reach it.
Any kind of approach, either geometric or mathematical will help.
Thanks for any suggestions.

A: This sketch may give you an idea for the case of the ideal thin lens: The ray AC will continue in a straight line (going through the center of the lens), while BD, which passes through focal point F, will refract to become parallel after the lens. Simple construction shows that the point where these lines intersect is the focal plane.

A spherical mirror M can be thought of as a part of a sphere - and when you are incident "at an angle to your mirror" you could equally say you are hitting "another part of the sphere", mirror M'. As such, the rays would go through the "original" focal point F; if we consider the "actual" focal point F' for the segment of the mirror at an angle, we see that F and F' lie approximately (but not exactly) in the focal plane of M' (cyan dashed line). I indicate the error (aberration) in my diagram with $\epsilon$.


text:
Q: How to replace list items with the corresponding value from a dictionary in this example? Using python I have this list:
['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']
I want to replace the list items with the corresponding value from this dictionary:
ValueDict = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}

So the result will be a list like this:
[7, 7, 7, 7, 6, 6]
How can I do this?

A: final_list = [ValueDict[i] for i in your_list if i in ValueDict]

A: Use enumerate for adding a counter to the list, then check if the element is in dictionary, and call the value
for i,j in enumerate(l):
    if j in ValueDict:
        l[i]=ValueDict[j]
print(l)

Output:
['7', '7', '7', '7', '6', '6']

A: something like the below
lst = ['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']
ValueDict = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}
new_lst = [ValueDict.get(x,'-1') for x in lst]
print(new_lst)

A: You could do it with list comprehension.
final_list = [ValueDict[value] for value in my_list]

A: a = ['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']
b = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}
c = [b.get(i, i)for i in a]
c
['7', '7', '7', '7', '6', '6']

A: This should work:
[int(ValueDict[x]) for x in list1]

[7, 7, 7, 7, 6, 6]
:)


text:
Q: Setting VS Code light/dark theme based on system's color scheme Is it possible to configure VS Code for automatically switching between a light theme and a dark theme based on system's chosen color scheme?
The behavior I'm looking for is similar to how the web apps can use media queries in the browser.
https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
@media (prefers-color-scheme: dark) {
  /* set dark theme colors */
}


text:
Q: Why "load event not working on addEventListener()"? I tried to log something after the body element of the page is loaded, but log not appearing in the console. What am I doing wrong?

const body = document.querySelector('body');

function setInitialGradient() {
    console.log('Cant see this message on console');
    body.style.background = `linear-gradient(to right, ${color1.value},     ${color2.value})`;
    cssProperty.textContent = body.style.background + ';';
}

body.addEventListener('load', setInitialGradient);

A: Use DOMContentLoaded instead
The DOMContentLoaded event will trigger earlier and is usually considered the better option.

[the load event] should be used only to detect a fully-loaded page. It is a common mistake to use load where DOMContentLoaded would be more appropriate.

Set it on the document object.
document.addEventListener('DOMContentLoaded', setInitialGradient);

If you must use the load event
If you must use the load event, you can add a listener to window instead:
window.addEventListener('load', setInitialGradient);

But note:

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

A: load event is a property of window neither document nor body. You need to use window instead:
window.addEventListener('load', setInitialGradient);

If you want to use function on load of body or any specific html element, then you'll need to use:
body.onload = setInitialGradient;
// I would use document.onload BTW if it is for body rather than other element

A: window.addEventListener('DOMContentLoaded', function() { /*put your code here*/ });


text:
Q: Params and Variables must be at the top of a template? I'd thought that params and variables must be at the top of a template.. yet i can successfully compile this code:
   <xsl:template name="WriteOptions">
      <xsl:param name="input"/>
      <xsl:choose>
      <xsl:when test="true()">
      </xsl:when>
      <xsl:otherwise>
         <xsl:param name="head" select="substring-before($input, ',')"/>
         <xsl:variable name="tail" select="substring-after($input, ',')"/>
         <option value="{$head}"><xsl:value-of select="$head"/></option>
      </xsl:otherwise>
      </xsl:choose>
   </xsl:template>

So i was wondering what's the catch

A: Per the spec, you can write <xsl:param> as a child of <xsl:template> and <xsl:stylesheet> (or <xsl:transform>, which is the alternative top level element in XSLT).
If your stylesheet compiles, then your XSLT processor behaves non-standard.

A: Only an xsl:param within an xsl:template must be a child of the xsl:template instruction.
There is no such requirement for an xsl:variable -- the W3C XSLT 1.0 and XSLT 2.0 specifications allow them to appear at any depth in the XSLT stylesheet.


text:
Q: Calculate Rolling Sum Expense each 6 months for each customer using Pyspark I have a data set as below and I want to calculate Rolling Sum Expense each 6 months for each customer using  Pyspark.
I have using window in pyspark.sql.function but did not success.
I just wonder if anyone can help me with this.
Thank you.
In summary, the process is as follows:

Here is the sample data
d = [
    {'id': 1, 'Month': 1, 'expense': 11.0,},
    {'id': 1, 'Month': 1, 'expense': 15.0},
    {'id': 1, 'Month': 1, 'expense': 16.0},
    {'id': 1, 'Month': 2, 'expense': 12.0},
    {'id': 1, 'Month': 2, 'expense': 14.0},
    {'id': 1, 'Month': 3, 'expense': 6.0},
    {'id': 1, 'Month': 3, 'expense': 7.0},
    {'id': 1, 'Month': 3, 'expense': 4.0},
    {'id': 1, 'Month': 4, 'expense': 4.0},
    {'id': 1, 'Month': 5, 'expense': 6.0},
    {'id': 1, 'Month': 6, 'expense': 7.0},
    {'id': 1, 'Month': 7, 'expense': 8.0},
    {'id': 1, 'Month': 8, 'expense': 9.0},
    {'id': 2, 'Month': 1, 'expense': 1.0},
    {'id': 2, 'Month': 1, 'expense': 5.0},
    {'id': 2, 'Month': 1, 'expense': 6.0},
    {'id': 2, 'Month': 2, 'expense': 2.0},
    {'id': 2, 'Month': 2, 'expense': 4.0},
    {'id': 2, 'Month': 3, 'expense': 14.0},
    {'id': 2, 'Month': 3, 'expense': 17.0},
    {'id': 2, 'Month': 3, 'expense': 16.0},
    {'id': 1, 'Month': 4, 'expense': 4.0},
    {'id': 1, 'Month': 5, 'expense': 6.0},
    {'id': 1, 'Month': 6, 'expense': 7.0},
    {'id': 1, 'Month': 7, 'expense': 8.0},
    {'id': 1, 'Month': 8, 'expense': 9.0}]

A: You can use the rangeBetween function to calculate the rolling sum.
I'm defining my frame boundaries as rangeBetween(-1, 0). -1 denotes one-off before the current row, and 0 represents the current row. Aggregating over this frame gives you a two-month rolling average:
from pyspark.sql import functions as F
from pyspark.sql.functions import col
from pyspark.sql.window import Window

w = Window().partitionBy("id").orderBy('Month')

df.groupBy("id", "Month").agg(F.sum(col("expense")).alias("total_expense")) \
  .withColumn("rank", F.row_number().over(w)) \
  .withColumn("two_month_rolling_sum", F.sum(col("total_expense")).over(w.rangeBetween(-1, 0))) \
  .filter(col("rank")!=1)\
  .drop("total_expense", "rank")\
  .orderBy("id", "Month").show()

Output:
+---+-----+---------------------+
| id|Month|two_month_rolling_sum|
+---+-----+---------------------+
|  1|    2|                 68.0|
|  1|    3|                 43.0|
|  2|    2|                 18.0|
|  2|    3|                 53.0|
+---+-----+---------------------+


text:
Q: Can some one tell me Why This is Query are very slow? Can some one explain why this query with IN clause over 5000 record are too slow?
Table strucuture
    CREATE TABLE IF NOT EXISTS `wp_transactions_log` (
  `sync_sequence` bigint(20) unsigned NOT NULL COMMENT 'the sequence number of the sync process/operation that this transaction belong to ',
  `objectid` varchar(100) NOT NULL COMMENT 'the entity/record id',
  `wp_id` bigint(20) unsigned NOT NULL,
  `table_name` varchar(100) NOT NULL COMMENT 'the target wordpress table name this transaction occured/fail for some reason',
  `logical_table_name` varchar(100) NOT NULL,
  `operation` varchar(20) NOT NULL COMMENT 'inser/update/delete',
  `status` varchar(20) NOT NULL COMMENT 'status of the transaction: success,fail',
  `fail_count` int(10) unsigned NOT NULL COMMENT 'how many this transaction failed',
  `fail_description` text NOT NULL COMMENT 'a description of the failure',
  `createdon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`sync_sequence`,`objectid`,`table_name`,`operation`,`wp_id`),
  KEY `objectid` (`objectid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

This table contain 5k record.
The query :
SELECT wp_id,objectId FROM wp_transactions_log WHERE `operation` = "insert" AND `wp_id` != 0 AND `status` != "ignore" AND `table_name` ='itg_wpclass_dates' AND objectId IN (... 5k record)

even this query are same:
SELECT wp_id,objectId FROM wp_transactions_log WHERE  objectId IN (5k record)

Note: all the parameters in the IN clauses are themselves the same in the table rows.
I mean by slow it takes more than 15 Sec.

A: objectid is not indexed. Composite primary key is indexed only. Add index on objectid and then try.
ALTER TABLE wp_transactions_log ADD INDEX (objectid);

Although if you have huge data, then adding index will lock your metadata, use INPLACE algorithm to do it with minimum lock contention.
Also, before youe select statement, just add Explain and provide us the response. It will be a good metrics to identify issue in your table.

A: The query are fast it take to 200ms to exectue, but the time for processing the query and retrieving the data are the long. I think there's no way to reduce this time.


text:
Q: Windows 7 in Active Directory can not modify services I had a windows 7 enterprise client joining in my Active Directory. I found I can not start the iscsi initiator app when I login as a domain user. I also found the Microsft iSCSI Initiator Service is manual, and gray in my services. I can not start, stop, or modify the services.
So, I think this maybe a problem with AD, how can I found the solution?
BTW, my account login in to win7 is domain user in Administrators group.
Thanks.

A: I solved this problem. Because in default, domain account are not local administrators, just add them to local administrators group in domain policy  will solve this.


text:
Q: Page Reference issue in Lightning I have a command link button on Account page (Create Account). As soon as a user clicks on the button, an edit page gets populated to fill the details. Once the details are filled and hit the save button, then account gets created and redirects the user to the account record detail page that got created.
This works in Visualforce but if I switch to Lightning it doesn't redirect me to the detail page of the created record but remains on the same account page, but record gets created in Lightning as well.
The expectation is that once the record is saved , it should go to the record detail page as it works smoothly in classic but not in lightning
Apex controller:
return new pagereference('/'+acc.Id+'/e?&nooverride=1&saveURL=/apex/Address_Validation?addressType=AccountBillingAddress&id='+acc.Id+'&retURL='+acc.Id);

A: You can't utilize retURL in Lightning and I think the best answer would be to look at using a quick action on the account which can pre-populate the fields based on the current record and then displays a toast message with a link to click into the new record. You're on Lightning now so you should look at catering your customization/actions to fit the platform.
For Spring 20 coming out in a couple weeks, they actually did bring back some ability to do the pre-filling notion using a custom button/link. You can test this out in a sandbox with Spring 20 to see if it meets your needs. Below, is the example of the formula and what you can do:
/lightning/o/Account/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    AccountNumber={!Account.AccountNumber},
    NumberOfEmployees=35000,
    CustomCheckbox__c={!IF(Account.SomeCheckbox__c, true, false)}

If you do need to simply edit the VF page to support some of that functionality, you could
look at this trailhead on the difference in navigation in Lightning vs. Classic as well.
Essentially, in Lightning there's an event mechanism for navigation and messaging. This is exposed in Visualforce as a JavaScript object called sforce.one. You could use the sforce.one.editRecord(); method to pass the accId and it'll redirect you to the edit screen and automatically go on that record after the save. The missing piece is that I don't believe there's a way to pass field information to pre-fill.


text:
Q: How to set a Ruby on Rails 4+ app's default db isolation level I want to make my application serialize every transaction by default. I'd then relax isolation based on performance measurements and knowing what data particular actions/transactions use and change.
I doubt serializable by default would get into the framework, as it'd slow things down and be difficult to explain. But I don't want to deal with db corruption, and do want internally consistent aggregate calculations.
For case-by-case isolation levels there is Rails postgresql how to set transaction isolation level to serializable but I think this approach is wrong for the same reasons html-escaping to protect against xss were wrong and were dropped: whitelisting is safer than blacklisting.
Has anyone done this already?
Where would be a good place to hook into rails to do this?

A: If you want this the default, then I suggest setting it in your MySQL config. The setting is described here: https://dev.mysql.com/doc/refman/5.7/en/server-options.html#option_mysqld_transaction-isolation
[mysqld]
default-character-set = utf8
default-storage-engine = InnoDB
default-table-type = InnoDB
transaction-isolation = SERIALIZABLE

For PostgreSQL the setting is called default_transaction_isolation. You can set this in postgresql.conf.


text:
Q: How to submit and receive forms in raw Ruby I'm new to Ruby and I find it extremely difficult to learn anything in Ruby that is not related to Rails.
I wanted to know how I have to proceed to submit an HTML form to a Ruby script and get this data in the server side.
Will it work if I send it through XMLHttpRequest (AJAX)? If yes, how can I send a response to Javascript in JSON format? If not, why?
Assuming that I want to use the POST method, in PHP it would be as following
if(count($_POST)>0){ //or, isset($_POST['a_key'])
   //do something
   echo json_encode($response);
}

A: In Ruby we tend to rely on existing wheels. One that's very popular is Sinatra, which makes working with a POST request very simple:
require 'sinatra'

post '/' do
  # do something here
end

To convert something to JSON, use the JSON class:
require 'json'

foo = {'a' => 1, 'b' => 2}
puts foo.to_json
# >> {"a":1,"b":2}

Mix and match as necessary.

I read about Mechanize.

Mechanize is great when you need to navigate through a website by reading pages, filling in fields and clicking links and buttons. It doesn't do JavaScript and isn't useful when you're trying to handle incoming requests. That's where Sinatra shines.

Do you recommend using Rack instead?

Rack isn't anything close to Mechanize so there's no comparison. Rack is a middle-layer inside a HTTPd, and is very powerful. You could use Rack to build out a web server, but it's not as convenient as something like Sinatra. Both Sinatra and Rails sit on top of Rack, which should tell you something about what Rack does, and whether you want to try writing to it directly.


text:
Q: Is it possible to group nested Where inside a Eager loading on laravel with the parent? I have been looking a way to group nested wheres from inside a eager loading query in Laravel, Let's say I have 3 Models, An Order, A Review, And a Product. For simplicity the Order has one Review, and one Product.
I want to get all the orders with the reviews and the product data that either buyer_rate or seller_rate is missing (I could group them in the code, no problem there). But I also want to check that the user logged in is the one that either placed the order (user_id in the Order class) or is the seller of the product (user_id inside the Product class).
The problem is that I can't find a way to tell Eloquent that I want this logic:
('reviews'.'buyer_rate' != null OR 'reviews'.'seller_rate' != null)
AND ('orders'.'user_id' == Auth::user()->id OR 'orders'.'producto'.'user_id' == Auth::user()->id)

This is my code: (But I can't make the second condition group)
My condition fails because it won't take in count the AND logic between the 2 groups.
$reviews = App\Order::with([
    'review' => function ($q) {
        $q->Where(function($query) { // Group Where buyer or seller's rate is missing.
            $query->Where('buyer_rate', '!=', null);
            $query->orWhere('seller_rate', '!=', null);
        });
    },
    'producto' => function ($q) {
        $q->select('id', 'user_id', 'nombre', 'precio', 'descripcion')
        ->orWhere('user_id', Auth::user()->id);
    },
])
->orWhere('user_id', Auth::user()->id)
->get();

A: I think you need to use whereHas (which in turns uses an exists query). If you only use with, you're still getting every Order regardless. You're only filtering which related Review or Product are eager loaded.
Using whereHas or whereExists, you first filter the Order model and then load the relationships.
App\Order::where(function ($query) {
    $query->where('user_id', auth()->id())->orWhereHas('producto', function ($producto) {
        $producto->where('user_id', auth()->id());
    });
})
->whereHas('review', function ($review) {
    $review->whereNotNull('buyer_rate')->orWhereNotNull('seller_rate');
})
->with([
    'review',
    'producto' => function ($producto) {
        $producto->select('id', 'user_id', 'nombre', 'precio', 'descripcion');
    },
])
->get();

auth()->id() is the same as auth()->user()->id or Auth::user()->id


text:
Q: How to show that $\int_{C_R} \frac{e^{i\alpha z }}{z^2+1}dz \to 0$ as $R\to \infty$? Suppose $C_R$ is a semicircle centered at $0$ with radius $R>0$. How can we show that the integral $\int_{C_R} \frac{e^{i\alpha z }}{z^2+1}dz$ tends to zero as $R\to \infty$?
My idea is to estimate the bound of the integrand, but it seems that it only works when $\alpha \ge 0$.
It is clear that $\left| \frac{{1}}{z^2+1} \right|\le  \frac{{1}}{R^2-1}$. Then we want to show that $|e^{i\alpha z}| = |e^{-\alpha y}|\le 1$ for $y>0$.
What is the difference between the two parametric representations, $Re^{it}$ and $Re^{-it}$ ($0\le t\le \pi$)? Note that $\alpha$ can be either positive or negative.


text:
Q: Custom Navigation iOS Im developing an app in xamarin for ios but the concept for native objective c is the same I believe. I want a container view that has a bar underneath a navigation bar that will be on all UIViewControllers. I went the container class way so I ddn't have to set up the bar on all pages. Is there another more efficient way of doing this? the bar will contain icons which will be updated by live events but are not click able e.g. wifi status but not the phones wifi.
I have managed to create a custom container view that has a navigation bar and the bar I want underneath it with a view wrapper for loaded in view controls. I have the navigation working for push but pop causes an error sometimes when push back to fast across multiple screens it just stops but the nav bar continues to go back. I have used the nav bar delegate for should pop etc but can't seem to find out why the timings are off.
If anyone can point me a direction to solve this or a different way of keeping the same templat eon all views it would be much appreciated. CHeers
Code Sample:
AppDelegate
 _window = new UIWindow(UIScreen.MainScreen.Bounds);
 _window.RootViewController = new ContainerView();

ContainerViewController:
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();
    NavigationController.NavigationBarHidden = false;
        var loginView = this.CreateViewControllerFor(ContainerModel.Login) as UIViewController;

        _navController = new UINavigationController(loginView);
        _navController.SetNavigationBarHidden(true, false);
        _navController.Delegate = new NavDelegate(navBar);

            containerView.AddSubview(_navController.View);

So navBar is from a manually added navigationbar in my xib file and containerView is where i want to show each viewcontroller in the containerview

A: Use a uiview in place of navigation bar which needs to be updated on every xib by making your navigation bar hidden.

A: Could you use storyboards, with the following structure?
- nav controller view
  - container view
    - nav controller view (hide/show nav bar as necessary)
      - content


text:
Q: Set caret position predictable in contenteditable with substring replaced by image element I have a contenteditable div.  in which if I type :) than it should replace that to a emoji image other wise the text appear. when I type :) then the caret moves to left of the image. then I have set the caret position to the end manually.It is working fine if we continue writing, but If I come back and try to insert a emoji between the text than the caret position is moving to the end.
const el = document.getElementById('user-input');
  el.addEventListener("input", function (e) {
    el.innerHTML = el.innerHTML.replace(/:\)/g, `<img src=${emojis[':)']} alt=""/>`)
    el.innerHTML = el.innerHTML.replace(/(?:<|<)3/g, `<img src=${emojis['<3']} alt=""/>`)
    setCaretToEnd(el)
  }, false);

the setCaretToEnd function
 function setCaretToEnd(target) {
  const range = document.createRange();
  const sel = window.getSelection();
  if (target.childNodes.length) {
    for (let i = 0; i < target.childNodes.length; i++) {
      if (target.childNodes[i].nodeName === 'IMG') {
        range.setStartAfter(target.childNodes[i], target.childNodes[i].length)
      } else {
        range.setEnd(target.childNodes[i], target.childNodes[i].length)
      }
    }
  } else {
    range.setStart(target.childNodes[0], target.childNodes[0].length)
  }
  // range.selectNodeContents(target);
  range.collapse();
  sel.removeAllRanges();
  sel.addRange(range);
  target.focus();
  range.detach();
}

the setCaretToEnd() function is pretty messy trying different approach
1: set caret position should always allow to write new text
2: when :) is written then the caret should come to the right of the image
how to make it work.


text:
Q: How to use loggingEvent class with log4j 2.12.1 I have to migrate log4j-1.2.17 to log4j-2.12.1 in java project
In 2.12 version loggingEvent class not implement(getthreadname, loggername,logmessage) methods, but I have to use those methods for my project. Is there any similar class to call those methods

A: Best would be to follow the migration path: https://logging.apache.org/log4j/2.x/manual/migration.html
Maybe you could add the old class names to your methods which you are missing in the new version.

A: Many people who used Log4j 1.2 overrode a lot of its functionality because it was lacking features they needed. Log4j 2 is a complete rearchitecture and rewrite. It is more flexible and can do many of the things you may have been customizing out of the box. Before going down the path of just blatantly trying to convert your Log4j 1 adaptations to Log4j 2, first determine what the goals of those customizations are and then determine the best approach to implement them in Log4j 2. If you have questions on how to implement some specific feature either ask here on Stackoverflow or on one of the Apache Logging Services mailing lists. Information on the mailing lists can be found at http://logging.apache.org/log4j/2.x/mail-lists.html


text:
Q: How to set text in android, through a text watcher I have recently created a class that has a text view and an edit text.
I am using the edit text in order to get some input from an user, and I would like for my text view to display what the user types in.
I need to mention that my labels are created dynamically and I am not sure how to reference them.
C0uld you give me a clue?
public TextView itemName(Context context){
        final ViewGroup.LayoutParams lparams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final TextView itemName = new EditText(context);
        itemName.setLayoutParams(lparams);

        return itemName;
    }

    public EditText desiredQuantity(Context context) {

        final ViewGroup.LayoutParams lparams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final EditText desiredQuantity = new EditText(context);
        desiredQuantity.setLayoutParams(lparams);
        desiredQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                itemName.setText(desiredQuantity.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return desiredQuantity;
    }

enter image description here

A: onTextChanged called when user change the text from edittext.
et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        t1.setText(et1.getText().toString());
    }
});


text:
Q: Where is "Voice" on New Projects in GarageBand now? In my old GarageBand App under New Projects there was a "Voice" tab.  How do I locate that or is it no longer in the app?

A: They have taken that option out of the new project area in the latest version. You can use "Songwriter" and delete the drums and guitars, or chose "Empty Project" and add a vocal track.
If you want to get the settings you've used before you can open an old project and use "Save As..." after deleting all the audio (not tracks) to get a blank project with the settings you like.


text:
Q: Adding multiple database in Django project I tried maybe 100 samples but multiple database never worked in my projects. Please help me. I have tired more codes from various sites, but there is last codes in my project which I got from official website. All is the same with the Documentation but still not working.
Settings.py
DATABASE_ROUTERS = ['MyApp.routers.TenantRouter']
DATABASE_APPS_MAPPING = {'tenant': 'tenant'}

DATABASES = {
    'default': {
        'NAME': 'host_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': '******'
    },
   'tenant': {
        'NAME': 'tenant_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': '******'
    }
}

Routers.py
class TenantRouter:
    route_app_labels = {'tenant'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'tenant_data'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'tenant_data'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'tenant_data'
        return None

OneApp/models.py
class UserTbl(models.Model):
    username = models.CharField(max_length=50)

class Meta:
    app_label = 'tenant'
    db_table = u'UserTbl'

And using below line for migrate. But not migrating anything. It always says No migrations to apply.
python3 manage.py migrate --database=tenant

A: No migrations to apply means your project don't have any migrations files.
first you have to run python3 manage.py makemigrations OneApp it will create a migration file inside your OneApp/migrations directory then re-run python3 manage.py migrate OneApp --database=tenant
 command.


text:
Q: How to unzip s3 file through lambda and chain with other lambda functions using nodejs? Two Issues over here:-
I have a zip file which once uploaded to s3 should trigger an event and
1. unzip the file
2. After unzip second lambda should trigger and call api.

A: If you want an AWS Lambda function to "unzip to S3", then the Lambda function would need to:

*

*Download the Zip file to local storage

*Unzip the files

*Loop through the files and upload each one to Amazon S3

Please note that there is a maximum of 500MB of disk storage space available to Lambda functions (in the /tmp/ directory), and this space needs to hold both the zip file and the extracted zip files.
Also, you'll need to extend the timeout setting to give adequate time for the function to perform all of the above operations.

A: The previous answer might work but the tmp folder has limited memory so it might cause problems as your file size gets increased. Instead, you can create an event based trigger that runs a Lambda function. This Lambda can then read zip files into a buffer (instead of downloading them locally), unzip them using the zipfile library and upload the unzipped files back to s3. Here's a detailed tutorial here: https://betterprogramming.pub/unzip-and-gzip-incoming-s3-files-with-aws-lambda-f7bccf0099c9
You should increase the timeout and memory size both to the max.


text:
Q: What can I do in my React microfrontend project so that I do not need to "npm start" for every dependent microproject So, I am new to microfronteds. I have built a microfrontend project watching tutorials. This is the structure.
demo
  |--container
  |--app1
  |--app2
  |--app3

container, app1, app2 and app3 are microfrontend projects and works fine independently and also after integrating. container app is to bring together app1, app2 and app3 and switch between them using routes.
The problem is that when I want to see container output with app1,app2,app3. I have to first "npm start" all those projects and then do the same for container. Is there a way that I have to use "npm start" only once. Note: I have researched a bit myself too but I don't want to use readymade stuffs like nx, lerna, bit etc. Something only react or node based is preferable. Also if possible give only hints/resources and not whole solution.

A: You can write a custom node script like this:
import child_process from 'child_process';
import util from 'util';
const spawn = util.promisify(child_process.spawn);

const startApp = (app) =>
    spawn('npm', ['start'], {
        env: { ...process.env },
        cwd: app,
        stdio: 'inherit',
    });

await Promise.all([
    startApp('container'),
    startApp('app1'),
    startApp('app2'),
    startApp('app3'),
]);

Only native NodeJS dependencies are used above. Since ESM is used above, make sure to name it with an ".mjs" extension. Will not work with an outdated NodeJS version. E.g. start-all.mjs.
If you placed it one level above all apps, i.e. in your "demo" directory then you can run it using node start-all.mjs and all starting in parallel and are running.


text:
Q: android get url from edit text and use it in rest api to upload data Here is my android rest request code but the where i get the url from edit text using its id but "getString" gets flagged(can't be resolved). Please help
class RESTRequest
{

   //final String ADD_STROKE_URL = "";

    final String ADD_STROKE_URL = new String[]{ getString(R.id.buttonUploadURL)};

    public Boolean success = null;
    private JSONObject params;
    private String strokeId;
    private HashSet<Point> localPoints;
    private StrokeManagerCallback callback;

    public static String encode(Object x) {
        try {
            return URLEncoder.encode(String.valueOf(x),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            return(String.valueOf(x));
        }
    }

    public RESTRequest(JSONObject params,String strokeId,Set<Point> points,StrokeManagerCallback callback)
    {
        this.params = params;

        this.strokeId = strokeId;

        this.localPoints = new HashSet<Point>();
        this.localPoints.addAll(points);

        this.callback = callback;

        new ExecuteREST().execute();

    }

    private class ExecuteREST extends AsyncTask<Void, Void, String>
    {

        protected String doInBackground(Void ...arg0)
        {

            /* Build URL query */
            StringBuffer local = new StringBuffer(ADD_STROKE_URL);
            if(params != null)
            {
                local.append("?");
                Iterator<?> k = params.keys();
                while(k.hasNext()){
                    try {
                        String key = (String) k.next();
                        Object value = params.get(key);

                        local.append(encode(key));
                        local.append("=");
                        local.append(encode(value));
                        if(k.hasNext()){
                            local.append("&");
                        }
                    }
                    catch (JSONException e) {e.printStackTrace();}
                }
            }

            HttpURLConnection urlConn = null;
            StringBuffer response = new StringBuffer("error");
            try
            {
                URL url = new URL(local.toString());
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setRequestMethod("GET");
                urlConn.setDoInput(true);
                urlConn.setUseCaches(false);
                urlConn.setRequestProperty("Content-Type", "application/json");
                urlConn.connect();

                //Get Response
                InputStream is = urlConn.getInputStream();
                BufferedReader rd = new BufferedReader(newInputStreamReader(is));
                String line;
                response = new StringBuffer();
                try{
                    while((line = rd.readLine()) != null) {
                        response.append(line);
                    }
                }
                finally{
                    if(urlConn != null){
                        urlConn.disconnect();
                        urlConn = null;
                    }
                    if(rd != null){
                        rd.close();
                        rd = null;
                    }
                }

                if(callback != null){
                    callback.onSuccess(strokeId, localPoints);
                }
            } catch (ConnectException e) {
                callback.onFailure(strokeId, localPoints);
            } catch (UnknownHostException e) {
                callback.onFailure(strokeId, localPoints);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (EOFException e) {
                response = new StringBuffer("No response from server");
            } catch (IOException e) {
                e.printStackTrace();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
            finally{
                if(urlConn != null){
                    urlConn.disconnect();
                }
            }
            return response.toString();
        }
    }

A: you can get String Resources like this
Resources res = context.getResources();
final String ADD_STROKE_URL = new String[]{ res.getString(R.id.buttonUploadURL)};

and now you can pass that url in AcycncTask class like this
public RESTRequest(JSONObject params,String
                   strokeId,Set<Point>points,StrokeManagerCallback callback){

   this.params = params;
   this.strokeId = strokeId;
   this.localPoints = new HashSet<Point>();
   this.localPoints.addAll(points);
   this.callback = callback;

   new ExecuteREST(/*Pass url here that you will get in doInBackground method */)
.execute();
 }

private class ExecuteREST extends AsyncTask<String, Void, String>{

   protected String doInBackground(String ...arg0){

     //get your url in arg0 variable
     StringBuffer local = new StringBuffer(arg0[0]);

           .
           .
           .
      //Rest of yours ...


text:
Q: Gradle: How to customize Android Manifest permissions? For my build system, I need to build several app variants, each requesting a different set of permissions. How can this be done with Gradle, without invoking a separate script?

A: I just managed to do this by having different flavors in my gradle file:
    free {
        packageName 'com.sample.free'
        buildConfigField "boolean", "HAS_AD", "true"
    }

    paid {
        packageName 'com.sample.paid'
        buildConfigField "boolean", "HAS_AD", "false"
    }

and then I created a new folder under src called "free" and under that a folder called "res"
src/
 + free/
 |   + res/
 + src/

and in that folder create a new file "AndroidManifest.xml" with the following code in it:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.sample" >
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

According to Gradle Plugin User Guide on Android Tools Project Site:

Similar to Build Types, Product Flavors also contribute code and
  resources through their own sourceSets.

and

The following rules are used when dealing with all the sourcesets used
  to build a single APK:

*

*All source code (src/*/java) are used together as multiple folders    generating a single output.

*Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or
  permissions, similarly to Build Types.

*All resources (Android res and assets) are used using overlay priority    where the Build Type overrides the Product Flavor, which
  overrides    the main sourceSet.

*Each Build Variant generates its own R class (or    other generated source code) from the resources. Nothing is shared    between
  variants.

meaning that you can create a folder with each flavor name under src and put your custom files in them. If said file is an AndroidManifest gradle will merge it with the manifest in the main.


text:
Q: File upload from Azure App Service to Azure Function fails, but not every time We are using a React web app as frontend and Azure Function as backend. The user can upload a file through our frontend. The frontend then sends the file via a REST call to an Azure Function.
I observed a strange behaviour which I can't explain: I open the web app and upload a file which is 2 MB big. I trigger the REST call via button click. Nothing happens. After ~ 2,1 minutes the call stops without a response received.
When I open the web app and upload a file which is very small (~ 120 kb). I trigger the REST call via button click. The response is 200 -ok after about 20 seconds. Then I upload the same file from before (2MB big) and trigger the rest call, I receive a response in < 30 seconds with status code 200 -ok. So in general the backend can handle the file size.
Why is this happening?
Could a possible reason be azure functions cold start?
No error is present in Azure diagnostic tools.

A: I figured it out by myself after a lot of trial and error. I saw that one of my slots in azure app service did not have the issue. It was using another azure function slot. Then I made a diff between my working function slot and my not working function slot. There was one setting which differntiated: Settings -> Configuration -> Common Configuration -> Incoming client certificates
There are two settings you can make:

*

*Client certificate mode

*Certificate exclusion paths

Client certificate mode was set to 'Allow' on the function without the issue.
Client certificate mode was set to 'Ignore' on the function with the issue.
After setting to 'Ignore' the upload of big files was working without a connection reset. For me it is unclear how this setting can affect a file upload, but it did.
The correct and secure way would be to set certificate mode to 'Required' and add allowed certificate paths.


text:
Q: jQuery - Why Doesn't IE8 Like This Function? A brief overview of my site structure:
Main index php which serves up locally stored php files via ajax. (if it sounds messy, that's because it is)
I have a function in the main index file that I call from the ajax loaded scripts and it works fine everywhere except IE.
I can't get a meaningful error message:
Invalid argument.  jquery-1.4.2.min.js, line 144 character 219

N.B This question is directly related to my previous one: jQuery $el.position(...) is undefined
jQuery Function (index.php)
// nav
var $el;
var leftPos;
var newWidth;
var $mainNav = $("#navbar ul");

$mainNav.prepend("

");
var $magicLine = $("#magic-line");

function navBar() {

    // console.log('navBar start');
    function checkActive() {
        // console.log('check active');
        // Hide magic line if nav bar has no active element
        if($('#navbar ul').children('.active').length < 1) {
            $magicLine.hide();
            //console.log($('#navbar ul').children('.active').length < 1);
            //console.log($('#magic-line'));
            //console.log('hide');
        }
        else {
            $magicLine.stop().animate({
                left: $magicLine.css('left', $(".active a").css('left')),
                width: $magicLine.width($(".active a").width())
            });
        }
    }
    checkActive();
    $magicLine
        .width($(".active a").width())
        .css("left", $(".active a").position().left)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $(".active a").width());

    // $("#navbar ul li a").hover(function() {
    // apply hover function to li instead and just just el to it's child
    $("#navbar ul li").hover(function() {
        // $el = $(this);
        $el = $(this).children('a');
        // leftPos = $el.position().left;
        leftPos = $el.parent().position().left;
        newWidth = $el.width();
        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        }, 600);
    }, function() {
        if($('#navbar ul').children('.active').length < 1) {
            $magicLine.stop();
            checkActive();
        } else {
            $magicLine.stop().animate({
                left: $magicLine.data("origLeft"),
                //width: $magicLine.data("origWidth")
                width: $magicLine.width($(".active a").width())
            }, 600);
        }
    });
}

This is called in all of my scripts by simply doing:
navBar();

but for some reason, it is causing issues in IE and I can't see any reason as to why it would.

A: I'm just taking a stab here, but I would review this:
width: $magicLine.width($(".active a").width())

That's in an object being passed into .animate(). What that line is doing is setting the width of $magicLine to the .active a width, using jQuery's .width() function. What that function returns is a reference to the jQuery element you started with, $magicLine. This technique is what allows you to chain jQuery functions one after the other.
So, the line above would effectively resolve to:
width: $magicLine

What I believe you want is:
width: $(".active a").width()

Give it a shot, hope that's it!

A: Got it, seemed to be this line:
$magicLine
        .width($(".active a").width())
        .css("left", $(".active a").position().left);

Changed it to
$magicLine.stop().animate({
        left: $(".active a").parent().position().left,
        //width: $magicLine.width($(".active a").width())
        width: $(".active a").width()
});

but this was being done in the checkActive function being called just before this line anyway so I just removed it....
Thanks for your help.


text:
Q: Ajax call to servlet, get parameter I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck:
var id;
$("#scan").click(function() {
    id = 1;
    $.ajax({
        type: "POST",
        data: id,
        url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
    });
});

And:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
    reqValue: id
}, function(responseText) {
    // $('#welcometext').text(responseText);
    alert("OK!!!");
});

My servlet code is a simple log print of the request parameter, but the return value is always null:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);

How can I get this working?
The only way I've found to get the code working is manually add the parameter to servlet url, like http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1

A: i have check you code.this is my working code.
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script type="text/javascript">
    var id;

    function fun() {
        alert("aaaa");
        id = 1;

        $.ajax({
            type : "POST",
            data : {
                reqValue : id
            },
            url : "/WebProject/callAjax"
        });
    }
</script>
</head>
<body>
    <button id="scan" onclick="fun()">Sacn</button>
</body>
</html>

//Servlet
@WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("reqValue"));
    }

}

A: var id;

$("#scan").click(function() {

        id = 1;

        $.ajax({
            type: "POST",
            data: { reqValue : id},
            url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
        });
});

There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc.
I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using type : "POST" java code is unable to read the data from Request Body( in post method the data will be added to Request Body).
I suggest you to use doPost() or service() methods instead doGet().


text:
Q: How to clear a variable of type ItemScriptableObject Tell me please. I have a variable public ItemScriptableObject elementItem;. There is a function that fills it. But how to clear it from the function? Currently throwing an error: error CS0029: Cannot implicitly convert type 'string' to 'ItemScriptableObject'
using System.Collections;
using UnityEngine;
using System.Collections.Generic;

public class TestRay : MonoBehaviour {

    public ItemScriptableObject elementItem;

    void OnTriggerEnter(Collider other) {
        if (other.gameObject.GetComponent<Item>() != null)
        {
            elementItem = other.gameObject.GetComponent<Item>().item;
            print(elementItem);
        }
        else {
            elementItem = 0;
        }
    }
}

A: As said in message, the ItemScriptableObject cant be string (0, or other variable type) because its an "ItemScriptableObject" format, so you need to try to set it to be another "ItemScriptableObject". Supposing it is derived form a scriptableobject, you can give a look on the functions in the documentation https://docs.unity3d.com/ScriptReference/ScriptableObject.html. I dont understand what you are really trying to do whit this variable.


text:
Q: Swift range bug with switch-statement Hello guys I'm new here and right now I'm learning Swift by coding some fancy algorithms, which comes to my mind while reading Apples Swift book.
I was trying to compress (automatically downcast) any IntegerType value.
Here is a little snippet of my Code which almost works fine except for one case:
switch signedValue
{
case Int64(Int8.min)...Int64(Int8.max):          compressedValue = Int8(signedValue)
case (Int64(Int8.max) + 1)...Int64(UInt8.max):   compressedValue = UInt8(signedValue)
case Int64(Int16.min)...Int64(Int16.max):        compressedValue = Int16(signedValue)
case (Int64(Int16.max) + 1)...Int64(UInt16.max): compressedValue = UInt16(signedValue)
case Int64(Int32.min)...Int64(Int32.max):        compressedValue = Int32(signedValue)
case (Int64(Int32.max) + 1)...Int64(UInt32.max): compressedValue = UInt32(signedValue)
case Int64(Int.min)...Int64(Int.max):            compressedValue = Int(signedValue) // range bug #1 - workaround '..<'
default:                                         compressedValue = signedValue
}

Assume signedValue is of Type Int64 and the input value is = 10_000_000_000.
This will lead to a runtime error (in Playground):
Execution was interrupted, reason: EXC_BAD_INSTRUCTION ...

Could anyone help me out to understand what exactly is happening here. There is an workaround for this problem. Instead of '...' I could use '..<' but this not how the range should be.

A: Unlike intervals (which have two flavours, half-open or closed), Range is only ever half-open.  So when you write 1...5, the ...function increments the right-hand argument in order to create a half-open range 1..<6.
The consequence of this is you can't have a range that spans the entire length of an integer type, since 1...Int.max will result in an attempt to increment Int.max, and an overflow error.  You get a similar error with let s = "hello"; let r = s.startIndex...s.endIndex
All is not lost, however, since you shouldn't be using ranges anyway, this is a job for ClosedInterval.  Since the ... operator is used for both, and defaults to ranges (for overloading precedence reasons) you need to explicitly identify the type:
let i64interval: ClosedInterval = Int64(Int64.min)...Int64(Int64.max)
switch signedValue {
    // etc
    case i64interval:   compressedValue = Int(signedValue)
    default:            compressedValue = signedValue
}

A: Look at the documentation for the Range Type. It has the following little nugget of information that I never noticed before:

if T has a maximal value, it can serve as an endIndex, but can never be contained in a Range.

T, in that quote, is the type of value in the Range. So if you have a Range of Ints, the max value of the Int cannot be contained in the Range.
That's why it works if you put the ..< in there, instead of ....
Good question, by the way...


text:
Q: ListView databinding not populating list items im trying to bind a list-view with a generic list but it seems im doing something wrong.
this is my collection
public ObservableCollection<SharedFile> searchResults;

this is the SharedFile Class
    public class SharedFile
{
    public string FileName { get; set; }
    public long FileSize { get; set; }
    public string FileLocation { get; set; }
    public string Extention { get; set; }
    public IPAddress publicFileIpAdress { get; set; }
    public IPAddress privateFileIpAdress { get; set; }
    public string FileUserName { get; set; }
}

this is my xaml
        <ListView Name="lsbSearchBox" Grid.Row="1" ItemsSource="{Binding Path=searchResults,ElementName=SearchPageRoot}">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="340" Header="File Name" DisplayMemberBinding="{Binding FileName}" />
                <GridViewColumn Width="140" Header="Size" DisplayMemberBinding="{Binding FileSize}"/>
                <GridViewColumn Width="140" Header="User Name" DisplayMemberBinding="{Binding FileName}"/>
            </GridView>
        </ListView.View>
    </ListView>

after hitting the "search" button im filling the collection with data and at the end im setting the datacontext (but nothing happens)
lsbSearchBox.DataContext = this;

What am i doing wrong here ?

A: From here:

You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object.
You cannot bind to public fields.

Make searchResults as public property.


text:
Q: Chromium Exception: closeDescriptionPopup is not defined when  i debug Cordova APP , http://localhost:4433/index.html?enableripple=cordova-3.0.0-NexusS,the Chrom throw a error。

eval code.js 中的 ,第 3 行    JavaScript Exception:
  closeDescriptionPopup is not defined

A: This happened to me when I was using VSCODE to debug some html+javascript in chrome.
First VSCODE threw an error "Exception has occurred: ReferenceError: exampleVariable is not defined" because I had copied a line of code from inside a function (referencing a function argument) to before the function. So I just deleted that part of the code and then clicked the Restart button on the top of VSCODE to restart the debugger, but then it threw this error "Exception has occurred: ReferenceError: closeDescriptionPopup is not defined".
I'm guessing the error has to do with VSCODE trying to close the error box it showed at the point in the code that is now deleted, but I'm not completely sure. Either way, it seems to start working correctly if I stop the debugger and then start it again (or stop the debugger, close and reopen VSCODE, and then start debugging again).


text:
Q: How to get the result from the Barcodereader-Method into my constructor (to make it accessable)? how can I access the result-string which is read by my method Scan() called on the Clicked Event from my Button?
I just want to pass the data in the background and access them from one point to form them into a combined string for an interface purpose.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TDE
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Page1 : ContentPage
    {
        public Page1 ()
        {
            InitializeComponent ();

            var layout = new StackLayout()
            {
                Margin = 10,
                Spacing = 20
            };
            var label = new Label
            {
                Text = "Bitte Scannen Sie den Barcode und geben noch folgende Informationen ein, um den Vorgang abzuschließen:",
                FontSize = 30,
                FontAttributes = FontAttributes.Bold
            };
            var button = new Button
            {
                Text = "Hier Fahrzeug Scannen",
                TextColor = Color.FromHex("#004d93"),
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };
            var entry_Kraftstoffmenge = new Entry
            {
                Placeholder = "Getankte Kraftstoffmenge in Liter",
                PlaceholderColor = Color.FromHex("#004d93"),
                HorizontalTextAlignment = TextAlignment.Center
        };
            var entry_Fahrer = new Entry
            {
                Placeholder = "Hier Ihr Name / Kürze",
                PlaceholderColor = Color.FromHex("#004d93"),
                HorizontalTextAlignment = TextAlignment.Center
            };
            var entry_KMStd = new Entry
            {
                Placeholder = "KM-Stand in KM / Stunden in h",
                PlaceholderColor = Color.FromHex("#004d93"),
                HorizontalTextAlignment = TextAlignment.Center
            };
            var entry_Geraet = new Entry
            {
                Placeholder = "Gerätename",
                PlaceholderColor = Color.FromHex("#004d93"),
                HorizontalTextAlignment = TextAlignment.Center
            };

            layout.Children.Add(label);
            layout.Children.Add(button);
            layout.Children.Add(entry_Kraftstoffmenge);
            layout.Children.Add(entry_Fahrer);
            layout.Children.Add(entry_KMStd);
            layout.Children.Add(entry_Geraet);

            Content = layout;

            button.Clicked += ButtonScannen;

        }

        void ButtonScannen(object sender, EventArgs e)
        {
            Scan();
        }

        public async void Scan()
        {
            var scanner = new ZXing.Mobile.MobileBarcodeScanner();
            var result = await scanner.Scan();
            var _tankbomb = "";
            if (result != null)
            {
                _tankbomb = result.ToString();
                await DisplayAlert("Erkanntes Fahrzeug", _tankbomb, "Ok");
            }
            else
            {
                _tankbomb = "000000";
                await DisplayAlert("Fahrzeug nicht erkannt", "Es wurde ein Dummy-Fahrzeug eingetragen!", "Ok");
            }
        }

    }
}

A: The easiest approach would be to pass the value as a parameter to the constructor of Page2.
public async void Scan()
{
   var scanner = new ZXing.Mobile.MobileBarcodeScanner();
   var result = await scanner.Scan();
   var _tankbomb = "";
   if (result != null)
   {
       _tankbomb = result.ToString();
       await Navigation.PushAsync(new Page2(_tankbomb));
   }
   else
   {
       _tankbomb = "000000";
       await DisplayAlert("Fahrzeug nicht erkannt", "Es wurde ein Dummy-Fahrzeug eingetragen!", "Ok");
   }
}

Additionally you must add an attribute in Page2 constructor like this:
public Page2 (string data)
{
   string readData = data;
   Label lbl_name = new Label {
       Text ="hello "+ readData
   };
   Title="Second Page";
}

Another option is you could create a public property on Page2 and assign the value to it after you create it.


text:
Q: How to do data imputation and normalization when using polynomial regression? The question is about the practical use of polynomial regression.
Let's say there is a dataset with columns A, B, T where T is a dependent variable, A and B are independent variables. A and B contain missing values. I want to fill in the gaps with the mean, then normalize values by the formula:
(x - u) / s,
where u is the mean and s is the standard deviation.
Everything is clear when I use linear regression. What about polynomial?
A^2, B^2 and AB columns are added for a quadratic polynomial case. How to fill AB, if the values of A and B are missing?
By the product of averages? When calculating AB, should I multiply the normalized values or should I normalize the result after?

A:
I want to fill in the gaps with the mean, then normalize values

First, single imputations of missing predictor values are likely to lead to bias. See van Buuren's Flexible Imputation of Missing Data.
Second, there is usually no need to normalize the predictor values in this type of regression.
Third, for derived variables like $A^2$, $B^2$ and $AB$, van Buuren says in section 6.4.1:

The easiest way to deal with the problem is to leave any derived data outside the imputation process.

So your best choice is to do multiple imputation of the missing data on $A$ and $B$ and then just let standard design-matrix calculations produce the polynomial terms from the $A$ and $B$ values in each imputed data set.


text:
Q: Simpler way of achieving some sort of key:key:list in Redis? So, I have a list of ranks, each rank has a list of permissions. I need to store them in Redis.
The problem being is that the server downloading these ranks from Redis doesn't know how many ranks there are / the names of the ranks.
So I decided to put "ranks":list of ranks into redis, and then "rank":list of permissions, that way the server can iterate through the "ranks" list, and grab the list off permissions through the "rank" part.
However, this is a bit inefficient as I have to create two pipelines to do this.
I was wondering if there was a way to create like a key:key:list data type on Redis?
For example,
"ranks", rank0, list of permissions
"ranks", rank1, list of permissions
etc.
Currently I have
"ranks", list of ranks
"rank0", list of permissions
Hope this makes sense.

A: I can think of two options:

*

*Create a Lua script for the task. The advantage is you'll remove all the back-and-forth network round-trips you need (but you still need to execute all the LRANGE calls to all the lists)

*Save keys in a hash, and the value of the hash is a serialized version of the list (JSON, for example). In your code, you'd make one call to Redis, but you'll need to process that information somehow

Hope it helps


text:
Q: Yii2 валидация dynamic input на клиенте Есть поле формы вида
$form->field($model, 'imageFiles[]')->fileInput(['accept' => 'image/*'])->label(false)

Поля добавляются динамически на клиенте, через jQuery
$(document).on('click', '#add_image', function(e) {

        e.preventDefault();

        var id = $('.block').length;

        console.log(id);

        var image_block = '<input type="hidden" name="Item[imageFiles]['+id+']" value=""><input type="file" id="item-imagefiles-'+id+'" name="Item[imageFiles]['+id+']" accept="image/*">';

        $('.images').append(image_block);
    });

Но Yii2 в упор их не видит, как будто их вообще нет, т.е. остальные поля проходят валидацию, а этих как совсем и не уществует :(
Нашел https://github.com/samdark/yii2-cookbook/blob/master/book/forms-activeform-js.md
Пишу
$('#w0').yiiActiveForm('add', {
            'id': 'item-imagefiles-'+id+'',
            'name': 'imageFiles['+id+']',
            'container': '.field-item-imagefiles-'+id+'',
            'input': '#item-imagefiles-'+id+'',
            'error': '.help-block'
        });
Вообще ничего не происходит, хотя насколько я понял, это должно добавлять валидацию поля на клиенте ?
P.S: понятно что можно это отправить на сервер, вернуть ответ и т.д. Но интересует именно валидация на клиенте.
На клиенте не получается, отправляю на сервер, получаю ответ в формате json, 2 проблемы

*

*Как 'прилепить' сообщение к нужному элементу формы ?

*Если поле изображения не заполнено, оно его игнорит, т.к. сам Yii если пустое поле, его не учитывает, т.е. получаю изображения таким образом:
$model->images = UploadedFile::getInstancesByName('Item[images]');
Если с 5 файловых инпутов 3 оставить пустыми, то валидация пройдет только для 2, остальные 3 вообще не попадут на валидацию, хотя в модели правила задано правило
[['images'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 10]

A: Если я правильно понял вопрос,то прилепить "сообщение" можно так:
   $('#w0').yiiActiveForm('updateMessages', {
        'item-imagefiles-'+id+'': ['sometext'],
    }, true);

Лучше конечно назначить id для формы явно,использование #w0 может привести к баге,ну у меня был такой претендент,я предупредил.
Также получается что еще нужно закодить массив к примеру где хранятся все назначенные айди новых динамических инпутов,что бы можно было удобно брать их оттуда и еще навесить на них нужные вам обработчики нужных событий.
Вот еще обратите внимание на вот этот кусок кода
https://github.com/yiisoft/yii2/blob/master/framework/assets/yii.activeForm.js#L498
То есть повидимому можно использовать что то подобное:
$('#w0').yiiActiveForm('validateAttribute',$form, attribute, forceValidate, validationDelay);


text:
Q: SourceTree .gitignore extensions I'm very new to git/SourceTree. (2) other devs have committed extension files, such as .proj, .cache, etc into the master branch. I added a .gitignore file and merged that into the master branch (we have a develop branch as well now). However, after the merge, I built the project in VS, and I'm still seeing "ignored" files in my "Unstaged files" section in SourceTree.
I read here that I need to "stop tracking" the files. When I do this (for the .suo for instance), it pops it up to the "Staged files" and has the red icon next to it. Is this correct, as should I do this for all files?
I've also read about git clean.

Cleans the working tree by recursively removing files that are not
  under version control, starting from the current directory.
Normally, only files unknown to Git are removed, but if the -x option
  is specified, ignored files are also removed. This can, for example,
  be useful to remove all build products.

Would I run against the master branch in bash? Otherwise how would I go about cleaning the repository up, removing ignored files.

A: After creating and committing the .gitignore file, what I did was go into the directories and temporarily move the folders and files that needed to be excluded from git out of the project folder, so that SourceTree would pick up the changes. Then I stopped tracking on these files/folders and pushed up.

A: I had same problem. Make sure you have "Pending" filter selected in Sourcetree. If filter is all then it will show all files including ignored.


text:
Q: Why can't I hover and click the Threejs transformation tools? I'm trying to make a tool to be able to move the custom model that I created. The first step I did was to display the transform tool and perform the change action. But I can't hover or click the transform tool. Am I missing something in my code?
  activateTheTransformTool() {
    let bbox = this.viewer.model.getBoundingBox();
    this.viewer.impl.createOverlayScene("Dotty.Viewing.Tool.TransformTool");

    this.transformControlTx = new THREE.TransformControls(
      this.viewer.impl.camera,
      this.viewer.impl.canvas,
      "translate"
    );

    this.transformControlTx.setSize(bbox.getBoundingSphere().radius * 5);

    this.transformControlTx.visible = false;

    this.viewer.impl.addOverlay(
      "Dotty.Viewing.Tool.TransformTool",
      this.transformControlTx
    );

    this.transformMesh = this.createTransformMesh();

    this.transformControlTx.attach(this.transformMesh);

    this.onItemSelected();
  }

  handleMouseMove(event) {
    if (this.transformControlTx) {
      if (this.isDragging) {
        console.log(this.transformControlTx);
        if (this.transformControlTx.onPointerMove(event)) {
          return true;
        }

        return false;
      }

      if (this.transformControlTx.onPointerHover(event)) return true;
    }

    //return _transRotControl.onPointerHover(event);
  }

onTxChange() {
   console.log("onTx change");
   this.viewer.impl.sceneUpdated(true);
}

onItemSelected() {
if (this.hitPoint) {
  this.transformControlTx.visible = true;

  this.transformControlTx.setPosition(this.hitPoint);

  this.transformControlTx.addEventListener("change", this.onTxChange);

      this.hitPoint = null;
    } else {
       this.transformControlTx.visible = false;
    }
  }

A: The code you shared seems to be ok (probably taken from this TransformationExtension, right?) but since it's only a part of the implementation, it's hard to tell what's wrong there. Do you perhaps see any errors or warnings in the console?
Btw. I've recently implemented a similar transformation tool/extension in one of my code samples: https://github.com/petrbroz/forge-simple-viewer-nodejs/tree/experiment/xform-tool. You should be able to drop the TransformToolExtension.js into your Forge app, include the extension's ID when initializing the viewer (like I do here), and be good to go.


text:
Q: Does the GHC garbage collector have any special optimisations for large objects? Does the GHC garbage collector handle "large" objects specially? Or does it treat them exactly the same as any other object?
Some GC engines put large objects in a separate area, which gets scanned less regularly and possibly has a different collection algorithm (e.g., compacting instead of copying, or maybe even using freelists rather than attempting to defragment). Does GHC do anything like this?

A: Yes. The GHC heap is not kept in one contiguous stretch of memory; rather, it is organized into blocks.
When an allocated object's size is above a specific threshold (block_size*8/10, where block_size is 4k, so roughly 3.2k), the block holding the object is marked as large (BF_LARGE).  Now, when garbage collection occurs, rather than copy large objects from this block to a new one, the block itself is added to the new generation's set of blocks; this involves fiddling with a linked list (a large object list, to be precise).
Since this means that it may take a while for us to reclaim dead space inside a large block, it does mean that large objects can suffer from fragmentation, as seen in bug 7831. However, this doesn't usually occur until individual allocations hit half of the megablock size, 1M.


text:
Q: How to return property of all elements of array inside MongoDB document? I want to return the title and _id properties of each element in my trips array of a user's document. I am attempting to use the aggregate pipeline but its my first time and the docs are overwhelming. It seems like all the examples show how to find a single piece of data. I basically want to return something like this:

[
  {title: "one", _id: 123},
  {title: "two", _id: 456},
  {title: "three", _id: 789},
]

From my document that looks like this:

A: function ObjArray(array){
    let newArr = [];
    array.foreach(
    (obj) => {
        let newobj = {title: '', id:''}
        newobj.title = obj.title;
        newobj.id = obj.id;
        newArr.append(newobj);
    }
    );
    return newArr;
}

A: You can use find({}) for getting your expected result. In find query, you need to use a projection stage.
Here the demo
Expected query
db.collection.find({},{_id:1,"trips.title":1,"trips._id":1});


text:
Q: Getting JsonMappingException for JSON request Can anybody please clarify below query regarding JSON mapping.
We have a field userId as Long type and in the JSON request if we pass String type value to Long type then we are getting JsonMappingException.
"Caused by org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Long from String value 'safdsda': not a valid Long value\n at [Source: org.apache.catalina.connector.CoyoteInputStream@56ffc7; line: 4, column: 5] "
where as if it is XML request for the same scenario working fine means the the String type value binding to Long type and in the service side we are capturing the string value and throwing the relevant Error message.
We have below configuration in the web.xml file to convert Java Objects to JSON and back.
<init-param>
  <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
  <param-value>true</param-value>

Can you please let us know do we have to do any  more configuration and why this happening only incase of JSON request not for XML request?