text:
Q: Good references for Elastodynamics I'm looking for a graduate-level reference about Elastodynamics.
If possible i would prefer it mainly rooted in vector notation better than Einstein notation (although i understand some proofs will be inevitabily carried out with this latter notation i guess).
Rigorous approach is best, with little intuitive notes is super.

A: For general reference, I would suggest:

*

*Graff, K. F. (2012). Wave motion in elastic solids. Courier Corporation. This book it's a good starting point since it first presents the wave motion in simpler setups such as strings and rods and moves towards three-dimensional solids.

*Achenbach, J. (1975). Wave propagation in elastic solids. Elsevier. This book starts from the elasticity equations and moves from there. This is a "must-read" reference for some people.
On more advanced topics, I suggest:

*

*Auld, B. A. (1973). Acoustic fields and waves in solids. Рипол Классик. This is one of the best references that I have found when studying elastodynamics in anisotropic solids.

*Carcione, J. M. (2007). Wave fields in real media: Wave propagation in anisotropic, anelastic, porous and electromagnetic media. Elsevier. Besides anisotropic solids, this book considers anelastic media. Auld's book might be difficult to find, this is a good replacement.


text:
Q: Tackling bandwidth optimization (possibly) through R-Sync I am currently looking for solutions that can optimize network bandwidth usage.
Scenario: Server has a file. Client downloads it through a REST API. Client makes some changes and uploads the changed file back to server through REST. Server will replace the original file with the uploaded file.
Possible approaches
I have two possible approaches in mind.
1- Local Diff Before making any changes client will make a copy of original file. After making the changes client will use algorithms like BSDiff or XDelta to extract changes by comparing original and changed files. These changes will be then sent to the server. Server will apply the diff on original file.
2- Use R-Sync Make a REST call to server and ask for initial Rolling Checksum and MD5 Hash. Then based on response generate the diff and POST it to the server. Server will the merge the changes.
I did some rough testing and found out that BSDiff is the most efficient solution (diff size wise - which is the primary optimization target). It generates the smallest possible diff BUT it takes huge memory which makes it impossible to use at client side for large file sizes. On the other hand results of X-Delta and rest of the binary diff tools I tried aren't that great in terms of generated diff size. Local diff also has disadvantage of using extra disk space because of keeping the copy of original file. This can be a problem in case of large files.
Memory issue of BSDiff makes R-Sync the most suitable choice (because rest of the tools are not that efficient in finding the diff). So I have decided to go for R-Sync.
R-Sync works in two steps. First it gets the signatures based on file and then data is sent back based on the signatures sent earlier. I am planning to further optimize the R-Sync by keeping the signatures of original file at client side before making any changes in it. This will remove the need of client requesting server to compute and send signatures at time of upload. Client can just send data based on already computed signatures to server whenever client wants to upload the file.
Question I know this is a bit of odd question that's why I asked a question before actually asking it here. I just would like to know if there are any better alternatives out there to solve this kind of problem? I want to confirm my approach just to make sure that I am on the right path and not missing anything major.

A: I think your decision to go with rsync is the best one. It is cost effective, accurate and well thought of. Please keep in mind to use --strict option for md5sum as otherwise you may run into troubles. You may want to consider skipping some checks on large files, as it just will eat resources and yield the same result. Imagine you compare two 2GB files - it is much easier to just delete the old one, copy the new one and update the hash and the checksum than to create new hash, compare it against the old one, and then merge the changes. For small files makes no difference.
Another idea is to just run diff on hashes and then transfer files partially - rsync's --checksum, --update and --inplace are your friends.
To further optimize the network bandwidth usage you may consider --compress and --bwlimit= options.
I don't know how often you need to transfer this files, how often the sync shall occur. If too often it may be better to setup Unison. More about it in Linux Journal.
Good luck!

A: This is mostly over my head - especially with binary files, but doesn't plain old rsync transfer only the changes to a non-local destination by default?  (If not, it has a --nowhole-files option.)
If so, it will do all the work for you.
If you need more details, post at rsync@lists.samba.org where very helpful rsync experts hang out.  You can subscribe at https://lists.samba.org/mailman/listinfo/rsync  .
For questions like this, it would help a lot if you would specify what operating system and version you are using and the version of the programs in question.  I have never heard of R-Sync, but I use rsync on Linux all the time.
I'm not sure, but I believe I've seen references to running rsync under cygwin on Windows if that's your environment.
This forum in particular handles questions about Windows and Linux, so it's even more important to specify your environment here.
See also https://en.wikipedia.org/wiki/Rsync
It covers rsync itself as well as other utilities such as rdiff that you may find useful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to delete show diff on github I recently pushed a commit to GitHub that I shouldn't have, which could have contained sensitive information. Thankfully it didn't. I immediately deleted the file in question and quickly noticed that I and anyone with access to this repo can see the contents of the uploaded file if they click on the commit history and load diff. Is there any way to delete the contents of that commit so that it no longer shows up in my repository commit history?

A: GitHub documents the process quite clearly.
Basic steps:

*

*Rebase your changes and remove the offending commit from your local history.

*Force push the rebased changes to GitHub.

*Contact support to have the offending commit purged from pull requests, caches and issues it might be linked to.


text:
Q: Add a class depending on number of elements What would be a good way to add a class to a series of elements depending on how many of them existed?
so in this case if there are two or less items the class is "half"
- if there are less than 8 it should be the "quarter" class applied to them.
Is there a way to add/remove a class depending on how many "item" (s) there are in a section?

 1

 2

 1

 2

 3

 4

 5

A: You can always get the count of your elements like
var elems = document.querySelectorAll(".item");
var count = elems.length;

if(count < 2) {
// add class half
} else if (count < 8) {
// add class quarter
}

A: You could try this:

$(document).ready(function(){
  $('section').each(function(i, sect){
    var itemsInSection = $(sect).children('.item');
    var count = itemsInSection.length;
    if(count < 3){
      itemsInSection.addClass('half');
    }else if(count < 8){
      itemsInSection.addClass('quarter');
    }
  });
});

 1

 2

 1

 2

 3

 4

 5


text:
Q: constructor with virtual function call in c++ first of all below code is not working visual c++ , but workin with bloodshed
output is 0 , but acc. to me it shud be 1 ; can anyone explain this
#include<iostream>
using namespace std;
class shape
{
public:
    virtual void print() const =0;
    virtual double area() { return 0.0;}
};
class point : public shape
{
    int x;
    int y;
public :
    point(int a=11, int b=11)
    {
        x=a;
        shape *s;
        s=this;
        cout<<s->area();
        y=b;
    }
    double area()const {return 1.0;}
    void print() const
    {
        cout<<"\nPoint\n";
        cout<<x<<"\t"<<y;
    }
};

int main()
{
    point p(1,2);
    return 0;
}

A: There's a subtle flaw in your code:
double area()const {return 1.0;}

The base class' area() method is not declared const.  point::area is therefore not a virtual method.   Either declare shape::area const as well or remove const from point::area and it will work as expected.

A: Calling virtual functions from the constructor is a really bad idea. See this Calling virtual functions from constructor (see 3rd para) for details.

A: Calling a virtual function in the constructor of a function acts as if the function is not virtual. It can be confusing, but it's standard behavour in c++
If you want to achieve your aim then you should probably have an "initialise" function that you call after the constructor in which virtual function calls will work as you expect.

A: You got the correct output. It should be 0. When you call area() in the constructor of your derived class, actually the base version of area() is called instead of the derived version. Calling a virtual function inside a constructor won't call the overriding functions in the derived classes.
Read this.


text:
Q: asp.net cookies not set into browser I am trying receive cookies in ASP.NET core API. When I am testing it in postman everything is working, but browser does not sends cookies back.
This is c# code which sets cookie in response.
 HttpContext.Response.Cookies.Append("Test", "test value", new CookieOptions()
        {
            HttpOnly = false,
            Domain = "localhost",
            Expires = DateTimeOffset.Now.AddDays(10),
            IsEssential = true,
            Path = "/",
            Secure = false,
            SameSite = SameSiteMode.Strict,
            MaxAge = TimeSpan.MaxValue
        });

Here is js code
  var myHeaders = new Headers();
  myHeaders.append("Accept", "application/json");
  myHeaders.append("credentials", "include");

  var requestOptions = {
    method: 'GET',
    headers: myHeaders
  };

  fetch("https://localhost:5001/api/user/get-authed-user", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

During debugging asp.net, there is not "Test" cookie in it when sending request from
browser.
Postman does it well and the "Test" cookie is visible during debugging.
Also I can not see cookies in browser (F12 -> Application -> cookies).
enter image description here


text:
Q: Two HTTP Methods for one AWS API Gateway Resource There is this wicked post about configuring an API Gateway method for CORS through CloudFormation, and I'm giving it a go. I want to create the following endpoint with two methods, "options" and "post":
/image/submit

Here is my CF template snippet:
ApiDefault:
    Type: "AWS::ApiGateway::RestApi"
    Properties:
      Name: "Stash-Default"
      FailOnWarnings: true
  ApiDefaultDeployment:
    Type: AWS::ApiGateway::Deployment
    DependsOn:
      - "ApiMethodImageSubmitPost"
      - "ApiMethodImageSubmitOption"
    Properties:
      RestApiId: !Ref "ApiDefault"
      StageName: "v1"
  ApiResourceImage:
    Type: "AWS::ApiGateway::Resource"
    Properties:
      ParentId: !GetAtt ["ApiDefault", "RootResourceId"]
      PathPart: "image"
      RestApiId: !Ref "ApiDefault"
  ApiResourceImageSubmit:
    Type: "AWS::ApiGateway::Resource"
    Properties:
      ParentId: !Ref "ApiResourceImage"
      PathPart: "submit"
      RestApiId: !Ref "ApiDefault"
  ApiMethodImageSubmitPost:
    Type: "AWS::ApiGateway::Method"
    Properties:
      HttpMethod: "POST"
      AuthorizationType: "NONE"
      MethodResponses:
        - StatusCode: "200"
      Integration:
        IntegrationHttpMethod: "POST"
        Type: "AWS_PROXY"
        IntegrationResponses:
          - StatusCode: "200"
        Credentials: !GetAtt [ "ExecuteApiMethodImageSubmit", "Arn" ]
        Uri: !Sub
          - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
          - lambdaArn: !GetAtt [ "ImageReceive", "Arn" ]
      RestApiId: !Ref "ApiDefault"
      ResourceId: !Ref "ApiResourceImageSubmit"
  ApiMethodImageSubmitOption:
    Type: "AWS::ApiGateway::Method"
    Properties:
      HttpMethod: "OPTIONS"
      AuthorizationType: "NONE"
      Integration:
        Type: "MOCK"
        IntegrationResponses:
          - StatusCode: "200"
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
      MethodResponses:
        - StatusCode: "200"
          ResponseModels:
            application/json: "Empty"
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: false
            method.response.header.Access-Control-Allow-Methods: false
            method.response.header.Access-Control-Allow-Origin: false
      RestApiId: !Ref "ApiDefault"
      ResourceId: !Ref "ApiResourceImageSubmit"

It bombs saying ApiMethodImageSubmitPost:

Method already exists for this resource (Service: AmazonApiGateway;
  Status Code: 409; Error Code: ConflictException; Request ID:
  454cf46a-b434-4626-bd4b-b6d4fe21142c)

Can you create two http-methods for a single API resource in this fashion? I'm not having a ton of luck with AWS' docs on this one.


text:
Q: Lightweight / Fast jQuery Modal Window Looking for a lightweight and fast jQuery modal window - i.e. the jQuery UI modal seems to be large and looking for something light weight ?
Does anyone know of a light-weight jQuery Modal window that's given good / fast performance with ajax etc ?

A: this is the simplest yet configurable one I've come across: jQModal.
If you're willing to write you're own AJAX stuff and want a really simple Modal implementation only see: Soh Tanaka's Simple Modal

A: SimpleModal /
I think this one is suitable for you.

A: Let's dig up this topic... Some people might be still looking for a lightweight & fast modal jQuery plugin in 2013.
My favorite lightweight modal plugin for 2013 is easyModal.js. It's only 1.87 KB minified. It's inspired by leanModal.js, which is also brilliant.


text:
Q: Dapper exige escrever código SQL, por que? Estou olhando o seguinte link que usa Dapper: Getting Started With PostgreSQL Using Dapper In .NET Core e a minha duvida é, quando faço pelo Java não preciso escrever o código SQL como esse exemplo aqui:
//1. Insert
using (var conn = OpenConnection(_connStr))
{
    var insertSQL = string.Format(@"INSERT INTO public.customer(firstname, lastname, email,createtime)
    VALUES('{0}', '{1}', '{2}','{3}');", "Catcher", "Wong", "catcher_hwq@outlook.com", DateTime.Now);
    var res = conn.Execute(insertSQL);
    Console.WriteLine(res > 0 ? "insert successfully!" : "insert failure");
    PrintData();
}

Por esse exemplo eu realmente preciso fazer isso? se precisar qual a vantagem de usar ele?

A: Por que o Dapper foi criado assim, as tecnologias tem suas características próprias, seja para atender uma demanda que exige que seja assim, seja por vontade de quem a criou, seja por deficiência.
O Dapper tem como objetivo acessar o banco de dados e gerar um objeto para consumo na sua aplicação e praticamente mais nada. Comparar com outra tecnologia não faz sentido porque outra provavelmente tem outro objetivo. Por exemplo o Entity Framework permite fazer de outra forma.
Note que o código usado é bem ruim e inseguro. Eu não seguiria esse tutorial. Tem um próximo do que pode se chamar de oficial muito melhor. Veja o Execute(). Elias eu não sugeriria tutorial algum, eu procuraria entender como tudo funciona e porquê das coisas, assim pode tomar decisões mais apropriadas.
Como pode ser visto no mesmo site é possível usar um extensão que evita escrever o SQL para o INSERT (com vantagens e desvantagens).

A: Complementando a resposta do Maniero, o seu código é perigoso porque você está concatenando os valores na string e fica sujeito a um SQL Injection.
Segue um exemplo simples de insert com o Dapper
// Insert
using (var db = new SqlConnection(connstring))
{
    const string sql = @"INSERT INTO [Region] (Name) VALUES (@Name)";

    db.Execute(sql, new { Name = region.Name }, commandType: CommandType.Text);
}

Tem uma extensão para o VisualStudio que eu criei para facilitar a vida em alguns projetos:
https://marketplace.visualstudio.com/items?itemName=thiagoguaru.DapperCrudGenerator
Porém para o uso dessa extensão você tem que criar os seus Models, se quiser saber um pouco mais sobre o que é Model já que está iniciando:
https://docs.microsoft.com/pt-br/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-a-model


text:
Q: Angular2 with Auth0, do I need to hide my ClientID and domain? I've been using Auth0 to build the front-end user authentication part of my site, but am unsure if I should be following the documentation exactly.
If I want to build a commercial product, should I be hiding the client ID and domain? Is this something that would lead to a security breach?
Currently anyone can view my Angular2 source code and look at the client ID and domain.

A: The client identifier and your domain (which I'm assuming you're referring to the assigned Auth0 domain similar to [account].auth0.com) are both considered information that does not need to be kept secret.
The domain represents the entity handling the authentication; the equivalent of accounts.google.com for your application.
The client identifier is defined within the OAuth 2.0 specification which clearly indicates that is not confidential information:

The client identifier is not a secret; it is exposed to the resource owner and MUST NOT be used alone for client authentication.

In browser-based or other application where the actual code is located in a client environment it's unavoidable to have information stored there for authentication purposes. You just need to be sure that the information stored is okay to be disclosed like it is with the two examples you gave.
On the other hand these types of application could not securely use a client secret as it is defined by OAuth 2.0, because like you said, anyone could see it by inspecting the code.


text:
Q: At a loss as to why this simple jQuery AJAX script causes an error in IE7 <script type="text/javascript">
$(function(){
 $('.update').click(function(){
  $.ajax({
     type: "POST",
     url: "/reporting_results/mark_result",
     data: "id="+$(this).attr("id")+"&check="+$(this).val()+"&user_id=<?=$user_id?>&product=<?=$this->uri->segment(3)?>",
  });
 return true
 });
});
</script>

A: Because of a trailing comma, right before the end of your $.ajax options:
 data: "id="+$(this).attr("id")+"&check="+$(this).val()+"&user_id=<?=$user_id?>&product=<?=$this->uri->segment(3)?>", <-- trailing comma, is why

A: Inside the $.ajax brackets, the this context changes to the ajax action. Can you verify that this is pointing to the original element that initiated the click event? I've done stuff like this before, and I remember needing to prefetch variables before entering the $.ajax block.
$('.update').click(function() {
    var id = $(this).attr('id');
    var value = $(this).val();
    var product = '<?=$this->uri->segment(3)?>';
    $.ajax({
        type: "POST",
        url: "/reporting_results/mark_result",
        data: "id="+id+"&check="+value+"&user_id=<?=$user_id?>&product="+product
    });
});

In javascript, the this reference can be very tricky at times, since it refers to the current javascript contextual object.


text:
Q: how to get input size with fgets? I have a problem with checking the size of input string with fgets. what I wanted to do is
If the input size is bigger then the buf_len then set "more" to 1 else 0 .
but I am not sure what is the right way to check the input size.
int read_stdin(char *buf, int buf_len, int *more)
{    // buf = malloc(10), buf_len = 10 , more = 1,

    fgets(buf, buf_len, stdin) ;
    size_t input_buf_len = strlen(buf);
    printf("size of input: %zu \n",sizeof(input_buf_len)); // prints 8
    printf("buf: %lu \n",sizeof(buf)); // prints 8
    printf("buf_len:%lu \n",sizeof(buf_len)); // prints 4
    printf("stdin:%lu \n",sizeof(stdin));// prints 8
        if (input_buf_len > buf_len)
        {
            *more = 1;
            printf("buf > buf_len\n");
        }
        *more = 0;
         printf("buf < buf_len \n");
     return sizeof(buf);
}

it does not matter how big the input length is , could be 1 or 20 , still prints the same number as the comment in the code.

A: The fgets call reads text up to a newline and includes the newline in the read text.  If what was read by fgets does not end in a newline character, that means that there's more text to be read on that line.
If fgets returns NULL, that means it reached EOF and that no characters have been read.

A: fgets() reads user input and stops when it reads a newline character. It returns:

*

*A pointer to the string read if it succeeds

*NULL if it fails or if it encounters an EOF
To get input size, first you have to replace \n by a null-terminator, then call strlen(). This is because strlen() stops when it encouters a null-terminator, but doesn't when it encounters a newline:
if (!fgets(buf, buf_len, stdin)) {
    // fgets failed...
} else {
    buf[strcspn(buf, "\n")] = '\0';
    size_t input_buf_len = strlen(buf);
    printf("Input length: %ld", input_buf_len);
}


text:
Q: COUNTIF() equivalent and discharge 'status typing' equivalent in SSMS or ADF I am currently trying to create a table in SSMS that holds patient record information. Ideally, I can achieve my goals in SSMS alone, but I can also utilize ADF should that be a better tool.
The ultimate goal is outlined in part two, however, to achieve this I have had to do step one first:

*

*The number of admissions prior and admissions ahead to any given row for an individual

*Discharge 'status typing': the type of discharge from a facility

An example table is provided below. Here is a breakdown of each column/variable:

*

*Patient ID: ID attached to a patient when they admit to a facility

*Patient Master ID: ID attached to an individual that stays with them, even if they admit to more than one facility

*Admission: The date when a patient admits to a facility

*Discharge: The date when a patient discharges from a facility

*Level of Care (LOC): Term referring to the level of care required to adequately address the patient's needs; Higher numbers indicate greater levels of care and more severe symptom severity

*Discharge Date

Patient ID
Patient Master ID
Admission
Discharge
Level of Care (LOC)
Discharge Date

1234-5
aBcDD-Ecnad9-09as
2022-09-01
2022-10-01
3
2022-10-01

123-6
aBcDD-Ecnad9-09as
2022-10-01
2022-10-31
2
2022-10-31

Below is an outline of what I've done in separate programs (excel for step one, and R for step two):

*

*Admissions prior and admissions ahead:
I originally did this in excel with a COUNTIF() function in excel, where each row counted the number of Patient Master ID before a given observation/row (admissions prior) and after a given observation/row (admissions ahead)

Therefore, the example table would look something like this:

Patient ID
Patient Master ID
Admission
Discharge
(LOC)
Admissions Ahead
Admissions Prior

1234-5
aBcDD-Ecnad9-09as
2022-09-01
2022-10-01
3
1
0

123-6
aBcDD-Ecnad9-09as
2022-10-01
2022-10-31
2
0
1

*I would then load this table into R and create custom functions to accomplish the 2nd goal: The type of discharge from a facility. (Please note that although I am looking to add an Admission Type column in my work, I will leave it out, as it involves similar logic as Discharge Type)

A brief description of discharge types:

*

*True discharge: When a patient discharges, but does not readmit at another facility (i.e., Admissions Ahead == 0)

*Stepdown: When a patient discharges, but admits to a lower level of care (LOC) (i.e., Admissions Ahead == 1 & LOC_new < LOC_old

*Lateral Transfer: When a patient discharges, but admits to the same level of care (LOC) (i.e., Admissions Ahead == 1 & LOC_new == LOC_old

*Step-Up: When a patient discharges, but admits to a higher level of care (LOC) (i.e., Admissions Ahead == 1 & LOC_new > LOC_old
At the end the table would look something like this (note that I have truncated the table by removing Admissions Prior):

Patient ID
Patient Master ID
Admission
Discharge
(LOC)
Admissions Ahead
Discharge Type

1234-5
aBcDD-Ecnad9-09as
2022-09-01
2022-10-01
3
1
Stepdown

123-6
aBcDD-Ecnad9-09as
2022-10-01
2022-10-31
2
0
True Discharge

In practice there will be many rows, and I know I will have to have the table sorted by Admission in order to have these functions work properly. What I'm hoping to get out of this post is to determine if I can do something similar in SSMS (or ADF if needed) to achieve this result in an efficient manner.
One post that's close to achieving my first step is here. However, if I understand the suggested queries using partition by wouldn't work for counting Admissions Prior.
Thank you for your time.

A: To count the prior and following admission counts per patient, you can use a windowed COUNT() function constrained with OVER( PARTITION BY ... ORDER BY ... ROWS ... ), where ROWS limits the window to either all preceding or all following admissions.
COUNT(*) OVER(
    PARTITION BY PatientMasterID
    ORDER BY Admission
    ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
    ) AS AdmissionsBefore,
COUNT(*) OVER(
    PARTITION BY PatientMasterID
    ORDER BY Admission
    ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
    ) AS AdmissionsAfter,

Note that this will count all preceding or following admissions for a patient, not just those with consecutive date ranges (transfers). Achieving the latter gets way more complicated and would involve preprocessing and assigning admission-group numbers that can later be used to limit calculations.
In order to calculate Discharge Type you will need to first extract the Level of Care from the next admission to compare with the current. Although I didn't see it outlined in your requirements, I expect you really only want to consider immediate following admissions, not those weeks, months, or years down the road. To determine that, you will also need to capture the next admission date for comparison with the current discharge date.
Both can be done using the LEAD() function with similar OVER PARTITION BY ... ORDER BY ...) constraints.
LEAD(Admission) OVER(PARTITION BY PatientMasterID ORDER BY Admission) AS NextAdmission,
LEAD(LevelOfCare) OVER(PARTITION BY PatientMasterID ORDER BY Admission) AS NextLevelOfCare

If you then wrap all that up in a subselect, the outer select can reference the available information in a CASE expression to select the appropriate discharge type.
I've pulled all this together with a few more rows of sample data in this db<>fiddle.
I'm not sure what the difference between Discharge and Discharge Date was in your sample data, so I ignored the latter.
And as for calculating the Admission Type, I expect you will need to access the prior LOC and perhaps Discharge date, which can be done using the LAG() function in a manner similar to LEAD(). (Left as an exercise.)


text:
Q: How do I define all inputs in rails to be read in one timezone? I need some help with Timezones. I want all of my inputs for Clock.new to CREATE/POST as PST rather than UTC, but I'm not have any success with my attempts. I have two database fields one for time_start, and time_end.
In my application.rb file I have tried setting a local timezone, based on what I found in other SO questions, but that doesn't seem to be working for me.
module Timer
  class Application < Rails::Application
    config.time_zone = 'Pacific Time (US & Canada)'
    config.active_record.default_timezone = :local
  end
end

Thanks in advance!

A: Iin your application.rb
#application.rb
config.time_zone = 'London'
config.active_record.default_timezone = :local

Here set the value_of time_zone based on your country.
in your rails console run below command to get list of available timezones.
ActiveSupport::TimeZone.all.map(&:name)

Dont forget to restart your server after above changes!


text:
Q: Ocassional error 400 when sending requests in golang Here's what I have right now:
func (client Client) PressButton(i int, k int, msg Message) error {
    if client.Token == "" {
        return fmt.Errorf("no token")
    }
    i--
    k--

    url := "https://discord.com/api/v9/interactions"
    time.Sleep(2 * time.Second)

    data := map[string]interface{}{"component_type": msg.Components[i].Buttons[k].Type, "custom_id": msg.Components[i].Buttons[k].CustomID, "hash": msg.Components[i].Buttons[k].Hash}
    values := map[string]interface{}{"application_id": "270904126974590976", "channel_id": msg.ChannelID, "type": "3", "data": data, "guild_id": msg.GuildID, "message_flags": 0, "message_id": msg.ID,}
    json_data, err := json.Marshal(values)

    if err != nil {
        return fmt.Errorf("error while encoding button click as json: %v", err)
    }
    req, err := http.NewRequest("POST", url, strings.NewReader(string(json_data)))
    if err != nil {
        return fmt.Errorf("error while creating http request: %v", err)
    }
    req.Header.Set("authorization", client.Token)
    req.Header.Set("Content-Type", "application/json")

    httpClient := &http.Client{}
    resp, err := httpClient.Do(req)
    if err != nil {
        return fmt.Errorf("error while sending http request: %v", err)
    }

    if resp.StatusCode != 204 {
        switch resp.StatusCode {
        case http.StatusUnauthorized:
            return ErrUnauthorized
        case http.StatusForbidden:
            return ErrForbidden
        case http.StatusNotFound:
            return ErrNotFound
        case http.StatusTooManyRequests:
            return ErrTooManyRequests
        case http.StatusInternalServerError:
            return ErrIntervalServer
        default:
            return fmt.Errorf("unexpected status code while clicking button: %v", resp.StatusCode)
        }
    }
    return nil
}

This works perfectly 90% of the times. But sometimes I get an error 400. I looked it up, I tried every recommended solution, I have confirmed that the payload and the URL are absolutely right moreover it wouldn't work most of the times if they weren't. I've also tried changing the headers among other things.
Here's an example payload that was sent (Before Marshaling) :
map[application_id:12345 channel_id:872747211551801384 data:map[component_type:2 custom_id:c34117ee-a332-4d7c-888f-47081e40092f:0 hash:]

(Changed the application id)
Response status is 400, here's the response body:
{"code": 50035, "errors": {"data": {"_errors": [{"code": "COMPONENT_VALIDATION_FAILED", "message": "Component validation failed"}]}}, "message": "Invalid Form Body"}

I've absolutely scavanged the internet and coding servers on discord to understand why this is happening.
The hash is always an empty field now, earlier it used to have a value for my use-case. I just left it in so it's more generalized.


text:
Q: Convergence in $L_2$ implies convergence in $L_1$. I have some doubts if this problem is right. Show that if $X,Y,X_n$ are r.v. in $L_2(\Omega,\mathcal{F},P)$ such that $X_n \xrightarrow{L_2} X$, then
$$X_nY \xrightarrow{L_1} XY$$
First of all, I need to prove that $E|X_nY-XY| \to 0$. Then,
$$E|X_nY-XY|=E|(Y)(X_n-X)| \leq \sqrt{E|Y|^2 E|X_n-X|^2},$$
since $X,Y,X_n$ r.v. in $L_2(\Omega,\mathcal{F},P)$ and Schwarz inequality. But $X_n \xrightarrow{L_2} X$ and hence my proof is done. Is it correct? I think it is too easy. If is not correct any help?


text:
Q: Parsing through HTML in a dictionary I'm trying to pull table data from the following website: https://msih.bgu.ac.il/md-program/residency-placements/
While there are no table tags I found the common tag to pull individual segments of the table to be div class=accord-con
I made a dictionary where the keys are the graduation year (ie, 2019, 2018, etc), and the values is the html from each div class-accord con.
I'm stuck and don't know how to parse the html within the dictionary. My goal is to have separate lists of the specialty, hospital, and location for each year. I don't know how to move forward.
Below is my working code:
import numpy as np
import bs4 as bs
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd

sauce = urllib.request.urlopen('https://msih.bgu.ac.il/md-program/residency-placements/').read()
soup = bs.BeautifulSoup(sauce, 'lxml')

headers = soup.find_all('div', class_={'accord-head'})
grad_yr_list = []
for header in headers:
    grad_yr_list.append(header.h2.text[-4:])

rez_classes = soup.find_all('div', class_={'accord-con'})

data_dict = dict(zip(grad_yr_list, rez_classes))

Here is a sample of what my dictionary looks like:
{'2019':

Anesthesiology

University at Buffalo School of Medicine, Buffalo, NY

Emergency Medicine

Aventura Hospital, Aventura, Fl

Family Medicine

Louisiana State University School of Medicine, New Orleans, LA

UT St Thomas Hospitals, Murfreesboro, TN

Sea Mar Community Health Center, Seattle, WA

Internal Medicine

Oregon Health and Science University, Portland, OR

St Joseph Hospital, Denver, CO

Obstetrics-Gynecology

Jersey City Medical Center, Jersey City, NJ

New York Presbyterian Brooklyn Methodist Hospital, Brooklyn, NY

Pediatrics

St Louis Children's Hospital, St Louis, MO

University of Maryland Medical Center, Baltimore, MD

St Christopher's Hospital, Philadelphia, PA

Surgery

Mountain Area Health Education Center, Asheville, NC

,
 '2018':

Anesthesiology

NYU School of Medicine, New York, NY

Emergency Medicine

Kent Hospital, Warwick, Rhode Island

University of Connecticut School of Medicine, Farmington, CT

University of Texas Health Science Center at San Antonio, San Antonio, TX

Vidant Medical Center East Carolina University, Greenville, NC

Family Medicine

University of Kansas Medical Center, Wichita, KS

Ellis Hospital, Schenectady, NY

Harrison Medical Center, Seattle, WA

St Francis Hospital, Wilmington, DE

University of Virginia, Charlottesville, VA

Valley Medical Center, Renton, WA

Internal Medicine

Oregon Health and Science University, Portland, OR

Virginia Commonwealth University Health Systems, Richmond, VA

University of Chicago Medical Center, Chicago, IL

Obstetrics-Gynecology

St Francis Hospital, Hartford, CT

Pediatrics

Case Western University Hospitals Cleveland Medical Center, Cleveland, OH

Jersey Shore University Medical Center, Neptune City, NJ

University of Maryland Medical Center, Baltimore, MD

University of Virginia, Charlottesville, VA

Vidant Medical Center East Carolina University, Greenville, NC

Preliminary Medicine Neurology

Howard University Hospital, Washington, DC

Preliminary Medicine Radiology

Maimonides Medical Center, Bronx, NY

Preliminary Medicine Surgery

Providence Park Hospital, Southfield, MI

Psychiatry

University of Maryland Medical Center, Baltimore, MI

,

My ultimate goal is to pull this data into a pandas dataframe with the following columns: grad year, specialty, hospital, location

A: You have dictionary with BS elements ('bs4.element.Tag') and you don't have to parse them.
You can directly uses find(), find_all(), etc.
for key, value in data_dict.items():
    print(type(value), key, value.find('h4').text)

Result
<class 'bs4.element.Tag'> 2019 Anesthesiology
<class 'bs4.element.Tag'> 2018 Anesthesiology
<class 'bs4.element.Tag'> 2017 Anesthesiology
<class 'bs4.element.Tag'> 2016 Emergency Medicine
<class 'bs4.element.Tag'> 2015 Emergency Medicine
<class 'bs4.element.Tag'> 2014 Anesthesiology
<class 'bs4.element.Tag'> 2013 Anesthesiology
<class 'bs4.element.Tag'> 2012 Emergency Medicine
<class 'bs4.element.Tag'> 2011 Emergency Medicine
<class 'bs4.element.Tag'> 2010 Dermatology
<class 'bs4.element.Tag'> 2009 Emergency Medicine
<class 'bs4.element.Tag'> 2008 Family Medicine
<class 'bs4.element.Tag'> 2007 Anesthesiology
<class 'bs4.element.Tag'> 2006 Triple Board (Pediatrics/Adult Psychiatry/Child Psychiatry)
<class 'bs4.element.Tag'> 2005 Family Medicine
<class 'bs4.element.Tag'> 2004 Anesthesiology
<class 'bs4.element.Tag'> 2003 Emergency Medicine
<class 'bs4.element.Tag'> 2002 Family Medicine

Full code:
import urllib.request
import bs4 as bs

sauce = urllib.request.urlopen('https://msih.bgu.ac.il/md-program/residency-placements/').read()
soup = bs.BeautifulSoup(sauce, 'lxml')

headers = soup.find_all('div', class_={'accord-head'})
grad_yr_list = []
for header in headers:
    grad_yr_list.append(header.h2.text[-4:])

rez_classes = soup.find_all('div', class_={'accord-con'})

data_dict = dict(zip(grad_yr_list, rez_classes))

for key, value in data_dict.items():
    print(type(value), key, value.find('h4').text)

A: Your code is quite close to finding the end result. Once you have paired the years with the student placement data, simply apply an extraction function to the latter.:
from bs4 import BeautifulSoup as soup
import re
from selenium import webdriver
_d = webdriver.Chrome('/path/to/chromedriver')
_d.get('https://msih.bgu.ac.il/md-program/residency-placements/')
d = soup(_d.page_source, 'html.parser')
def placement(block):
   r = block.find_all(re.compile('ul|h4'))
   return {r[i].text:[b.text for b in r[i+1].find_all('li')] for i in range(0, len(r)-1, 2)}

result = {i.h2.text:placement(i) for i in d.find_all('div', {'class':'accord-head'})}
print(result['Class of 2019'])

Output:
{'Anesthesiology': ['University at Buffalo School of Medicine, Buffalo, NY'], 'Emergency Medicine': ['Aventura Hospital, Aventura, Fl'], 'Family Medicine': ['Louisiana State University School of Medicine, New Orleans, LA', 'UT St Thomas Hospitals, Murfreesboro, TN', 'Sea Mar Community Health Center, Seattle, WA'], 'Internal Medicine': ['Oregon Health and Science University, Portland, OR', 'St Joseph Hospital, Denver, CO\xa0'], 'Obstetrics-Gynecology': ['Jersey City Medical Center, Jersey City, NJ', 'New York Presbyterian Brooklyn Methodist Hospital, Brooklyn, NY'], 'Pediatrics': ['St Louis Children's Hospital, St Louis, MO', 'University of Maryland Medical Center, Baltimore, MD', 'St Christopher's Hospital, Philadelphia, PA'], 'Surgery': ['Mountain Area Health Education Center, Asheville, NC']}

Note: I ended up using selenium because for me, the returned HTML response from requests.get did not included the rendered student placement data.

A: You can go to pandas once you get the soup, then parse the necessary information
df = pd.DataFrame(soup)
df['grad_year'] = df[0].map(lambda x: x.text[-4:])
df['specialty'] = df[1].map(lambda x: [i.text for i in x.find_all('h4')])
df['hospital'] = df[1].map(lambda x: [i.text for i in x.find_all('li')])
df['location'] = df[1].map(lambda x: [''.join(i.text.split(',')[1:]) for i in x.find_all('li')])

You will have to do some pandas magic after that

A: I don't know pandas. The following code can get the data in the table. I don't know if this will meet your needs.
import requests
from simplified_scrapy.simplified_doc import SimplifiedDoc
url = 'https://msih.bgu.ac.il/md-program/residency-placements/'
response = requests.get(url)
doc = SimplifiedDoc(response.text)
divs = doc.getElementsByClass('accord-head')
datas={}
for div in divs:
  grad_year = div.h2.text[-4:]
  rez_classe = div.getElementByClass('accord-con')
  h4s = rez_classe.h4s # get h4
  for h4 in h4s:
    if not h4.next:
      continue
    lis = h4.next.lis
    specialty = h4.text
    hospital = [li.text for li in lis]
    datas[grad_year]={'specialty':specialty,'hospital':hospital}
for data in datas:
  print (data,datas[data])


text:
Q: Degree of differential equation $\sqrt{1+\frac{d^2y}{dx^2}}=x+\frac{dy}{dx}$
Degree of the differential equation $\sqrt{1+\frac{d^2y}{dx^2}}=x+\frac{dy}{dx}$

Degree of the differential equation $\sqrt{1+\frac{d^2y}{dx^2}}=x+\frac{dy}{dx}$ is said to be "not defined" in my reference.
Doubt 1
What if I do:
$$
\color{blue}{\sqrt{1+\frac{d^2y}{dx^2}}=x+\frac{dy}{dx}}\implies 1+\frac{d^2y}{dx^2}=\bigg[x+\frac{dy}{dx}\bigg]^2
$$
Now can I say the degree is $1$. If not, is it because squaring both sides add more information into the equation that both the differential equations are not exactly the same ?
Doubt 2
Thanx @farruhota for the link: How to find degree of a differential equation or check page 4 of ordinary differential equations by E. L. Ince
If I'm allowed to square both sides and say that the degree is $1$, as in the link, can I also square again and say the degree is $2$ right ?

A: The order is the greatest $n$ for which an $n$th derivative is present, while the degree is the highest power of such maximal-order derivatives, after the equation is written in rational form with all exponents integers. The equation $1+y''=x^2+2xy'+y'^2$ has order $2$, degree $1$.


text:
Q: mysql deletion efficiency I have a table with large amount of data. The data need to be updated frequently: delete old data and add new data. I have two options

*

*whenever there is an deletion event, I delete the entry immediately

*I marked delete the entries and use an cron job to delete at unpeak time.

any efficiency difference between the two options?  or any better solution?

A: *

*Both delete and update can have triggers, this may affect performance (check if that's your case).

*Updating a row is usually faster than deleting (due to indexes etc.)

However, in deleting a single row in an operation, the performance impact shouldn't be that big. If your measurements show that the database spends significant time deleting rows, then your mark-and-sweep approach might help. The key word here is probably measured - unless the single deletes are significantly slower than updates, I wouldn't bother.

A: You should use low_priority_updates - http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_low_priority_updates. This will give higher priority to your selects than insert/delete/update operations. I used this in production and got a pretty decent speed improvement. The only problem I see with it is that you will lose more data in case of a crashing server.

A: With MySQL, deletes are simply marked for deletion internally, and when the CPU is (nearly) idle, MySQL then updates the indexes.
Still, if this is a problem, and you are deleting many rows, consider using DELETE QUICK. This tells InnoDB to not update the index, just leave it marked as deleted, so it can be reused.
To recover the unused index space, simply OPTIMIZE TABLE nightly.
In this case, there's no need to implement the functionality in your application that MySQL will do internally.


text:
Q: Need Pentaho JSON without array I wanted to output json data not as array object and I did the changes mentioned in the pentaho document, but the output is always array even for the single set of values. I am using PDI 9.1 and I tested using the ktr from the below link
https://wiki.pentaho.com/download/attachments/25043814/json_output.ktr?version=1&modificationDate=1389259055000&api=v2
below statement is from https://wiki.pentaho.com/display/EAI/JSON+output
Another special case is when 'Nr. rows in a block' = 1.
If used with empty json block name output will looks like:
{
"name" : "item",
"value" : 25
}
My output comes like below

{ "": [ {"name":"item","value":25} ] }

A: I have resolved myself. I have added another JSON input step and defined as below
$.wellDesign[0] to get the array as string object


text:
Q: Android Spannable Line Height I have been trying to figure this one out for the last couple of days now, and have had no success...
I'm learning android right now, and am currently creating a calculator with history as my learning project. I have a TextView that is responsible for displaying all history... I'm using a digital font that looks like a calculator font, but this only looks good for digits and decimals and comma's. I want all operators to be highlighted and in a different font (Arial Narrow at the moment). I have been able to get this to work beautifully using a spannable string where I'm specifying a font color as well as a font using a CustomTypeFaceSpan class to apply my custom fonts.
The problem... When I mix the Typefaces, there seems to be an issue with the line height, so I found this post which demonstrates using another custom defined class to apply a line height to each added line of spannable text:
public class CustomLineHeightSpan implements LineHeightSpan{
    private final int height;

    public CustomLineHeightSpan(int height){
        this.height = height;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, FontMetricsInt fm) {
        fm.bottom += height;
        fm.descent += height;
    }

}

This does not seem to work, and I can not figure out why. If I don't apply the different typefaces, then it displays as expected with no space above the first line, and about 5px spacing between lines. When I apply the alternate typefaces, there is a space of about 10 to 15px above the first line of text and the line spacing is about the same 10 to 15px.
There is no difference in the font size, only the typeface. What am I missing. I implemented the CustomLineHeightSpan which implements LineHeightSpan and overrides the chooseHeight method. I call it like so:
WordtoSpan.setSpan(new CustomLineHeightSpan(10), operatorPositions.get(ii), operatorPositions.get(ii) + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
It does not seem to matter what I put in the call to CustomLineHeightSpan. Nothing changes...
Anybody have any idea what I'm missing... I'm sure it's an "I can't believe I missed that" answer, but can't seem to figure it out at the moment.
Thanks for the help guys :-)

A: I finally found a more in depth example of the use of LineHeightSpan... Actually LineHeightSpan.WithDensity to be more precise... The following is the excerpt that helped me to resolve my issue:
private static class Height implements LineHeightSpan.WithDensity {
    private int mSize;
    private static float sProportion = 0;

    public Height(int size) {
        mSize = size;
    }

    public void chooseHeight(CharSequence text, int start, int end,
                             int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        // Should not get called, at least not by StaticLayout.
        chooseHeight(text, start, end, spanstartv, v, fm, null);
    }

    public void chooseHeight(CharSequence text, int start, int end,
                             int spanstartv, int v,
                             Paint.FontMetricsInt fm, TextPaint paint) {
        int size = mSize;
        if (paint != null) {
            size *= paint.density;
        }

        if (fm.bottom - fm.top < size) {
            fm.top = fm.bottom - size;
            fm.ascent = fm.ascent - size;
        } else {
            if (sProportion == 0) {
                /*
                 * Calculate what fraction of the nominal ascent
                 * the height of a capital letter actually is,
                 * so that we won't reduce the ascent to less than
                 * that unless we absolutely have to.
                 */

                Paint p = new Paint();
                p.setTextSize(100);
                Rect r = new Rect();
                p.getTextBounds("ABCDEFG", 0, 7, r);

                sProportion = (r.top) / p.ascent();
            }

            int need = (int) Math.ceil(-fm.top * sProportion);

            if (size - fm.descent >= need) {
                /*
                 * It is safe to shrink the ascent this much.
                 */

                fm.top = fm.bottom - size;
                fm.ascent = fm.descent - size;
            } else if (size >= need) {
                /*
                 * We can't show all the descent, but we can at least
                 * show all the ascent.
                 */

                fm.top = fm.ascent = -need;
                fm.bottom = fm.descent = fm.top + size;
            } else {
                /*
                 * Show as much of the ascent as we can, and no descent.
                 */

                fm.top = fm.ascent = -size;
                fm.bottom = fm.descent = 0;
            }
        }
    }
}

This was taken from this example.
What it does is as quoted below:

Forces the text line to be the specified height, shrinking/stretching
  the ascent if possible, or the descent if shrinking the ascent further
  will make the text unreadable.

I hope this helps the next person :-)


text:
Q: Logout icon avec DrawerNavigation (react native) how i add icon to drawer navigation item using react native ?
const AppDrawerNavigator = createDrawerNavigator({
    'Rendez Vous' : RendezVous,
    'Parcours de soin': ParcoursDeSoin,
    'Ordonnances' : Ordonnances,
    'Analyses' : Analyses,
    'Profil' : Profil,
    'A Propos': APropos,
    'Logout ': Login

A: Under your login screen route config, use drawerIcon under navigationOptions to add your icon
Login: {
  screen: Login,
  navigationOptions: {
    drawerIcon: ({ tintColor }) => (
      <Icon name="ios-home" size={20} color={tintColor} />
    ),
  },
},

demo


text:
Q: Separate string I have complete addresses (street address, state, country) and want to separate it in
address.address
address.state
address.country

for example
var addressString = 'Calle del Padre Jesús Ordóñez, 18. 1, Madrid, España'

the outcome should be:
address.address: Calle del Padre Jesús Ordóñez, 18. 1,
address.state: Madrid
address.country: España

A: You can get the fields by using String#match with a regular expression (regex101). Then you can destructure (or manually assign), the 2nd, 3rd, and 4th parts of the string to the variables, and create an object:

const addressString = 'Calle del Padre Jesús Ordóñez, 18. 1, Madrid, España';

const [,addr, state, country] = addressString.match(/(.+),\s+([^,]+),\s+([^,]+)$/);

const address = {
  address: addr,
  state,
  country
};

console.log(address);

A: ES6 offers us destructuring, template strings and porperty shortcuts, making this whole process almost trivial for addresses that use a consistent seperator.

const address_string = 'Calle del Padre Jesús Ordóñez, 18. 1, Madrid, España';
const [ street, number, state, country ] = address_string.split( ',' );
const address = { "address" : `${street}, ${number}`, state, country };
console.dir( address );

A: I don't know your project, but it would be preferable to get the address already splitted, and join it when needed.
You could use split function to split your string at commas. If needed, you could join back the entire array in one string but without the two last index of the array, in order to get address, state, and country as needed (assuming state and country don't contain a comma).


text:
Q: Converting HTML Canvas to Image. Javascript I am trying to export my HTML Canvas to an Image. But when I export the image, I keep getting the img src = "undefined".  I printed the canvas to the page directly and confirmed I am getting the correct canvas.  Here's the code that I'm using.  Please let me know what you see is wrong. May be a problem with CORS (This is HTML5)?
scope.getShuttleImage = function () {
            var tmpPng
            var imageElement
            html2canvas(document.body.getElementsByClassName("shuttle-truck"), {
                useCORS: true,
                onrendered: function (canvas) {
                    tmpPng = canvas.toDataURL("image/png");

                }
            });
            document.write('"') // Just for testings sake
        };

A: I believe the problem is with html2canvas being asynchronous. Try changing your code to the following. Like @Archer said
scope.getShuttleImage = function () {
        var tmpPng
        var imageElement
        html2canvas(document.body.getElementsByClassName("shuttle-truck"), {
            useCORS: true,
            onrendered: function (canvas) {
                tmpPng = canvas.toDataURL("image/png");
                document.write('"') // Just for testings sake

            }
        });
    };


text:
Q: Plotting color graph setting array element with a sequence I'm trying to produce a colored graph using the below code
x = range(0,170)
y = range(0,60)
X,Y = meshgrid(x, y) # grid of point
Z = ATFS.ATFS(state, T, dt, Y, tm, td, sigma, D, X, f, A, measurement)

Where ATFS uses X in a matrix. This produces the error

arr = N.array(data, dtype=dtype, copy=copy)
ValueError: setting an array element with a sequence.

I know if I use Z = X*Y it works and it doesn't matter that they are a sequence so what wrong here?


text:
Q: wrong borders' width in android browser On android devices with high density screens (devicePixelRatio of 1.5) the borders of html elements have wrong border width.
The two boxes here: jsbin sample, appear correctly on the desktop
but on the android - both in chrome and the stack browser - they look like this:

now i understand why they look like this, but i cannot find any CSS solution - only js.
the js solution would be to change the width and height of the elements to be odd as well as the top/left properties.

A: There is no standard solution, too bad. You can make the next tricks to avoid an inconsistent displaying of borders with 1px width.

*

*make colour of borders slightly transparent, i.e. with alpha <= 0.5. For example border-color: rgba(169, 0, 52, 0.5) I tested this on Android 4.4.2 Chrome & Yabrowser browsers. Works fine!;

*make width/height of bordered element odd, and shift element position. Here you need to experiment and use JS, saying like:
$('div.elemWithBadBorders').each(function(){
    var $el = $(this);
    var width = $el.width();
    if(width % 2 == 0){
        $el.css('width', (width+1)+'px');
    }
});

*

*Disable borders if showed on Retina displays or other hires screens. You need to use media query in css like this:
 @media (-webkit-min-device-pixel-ratio: 1.5) {
    div.elemWithBadBorders {
        border: none;
    }
 }

where 1.5 is pixel density. On Retina displays it appears as 2

A: It looks like you want to apply a media query based on pixel ratio. Try the following pure CSS solution:
@media only screen and (min--moz-device-pixel-ratio: 1.5),
       only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (min-device-pixel-ratio: 1.5),
       only screen and (min-resolution: 1.5dppx),
       only screen and (min-resolution: 240dpi) {
          /* High density screen fixes go here */
       }

The first line is not a typo (I know, it's weird). As written, the query above will also apply the associated rules to higher-density Retina displays, so change it if you want something more targeted.
Hope this helps!

A: The answer is near width=device-width string. Remove it and I think all will be alright.
In theory:
For example, you use Samsung Galaxy S or S2 with viewport 480px to 800px (css pixels) and devicePixelRatio of 1.5. But device-width is 480/1.5 = 320 (height 800/1.5 = 533).
So then you say to browser of Samsung Galaxy S "Draw me 1px in css pixels line", then width=device-width string is enabled - you say to it "Draw me 1px in device pixels". And with width=device-width string device pixel is equal 1.5px css pixels. And then you draw 1.5px height(for example) lines browser use anti-aliasing for not integer values then the started from not integer coords. It means line with height 1.5px from 1.5px to 3px by vertical can be drawn like 2px height (or 1px height)

A: Use <meta name="viewport" content="initial-scale=1.0,width=device-width"> instead of <meta name="viewport" content="width=device-width">


text:
Q: QnA maker get answer from multiple kb Currently i am getting response from single kb in QnA maker.
Current code.
  QnAMaker _qnaservice = new QnAMaker(new QnAMakerEndpoint
        {
            EndpointKey = _qnaconfig.AuthKey,
            Host = _qnaconfig.EndPoint,
            KnowledgeBaseId = "{KBID}"
        }, new QnAMakerOptions { Top = 3, StrictFilters = channelData.Filters?.ToArray() });
        var response = await _qnaservice.GetAnswersAsync(stepContext.Context);

Is there any option to get results from multiple KBs?

A: The code you have there pulls the top three answers from just the one kb you have from KBID. You have to code to show three answers, and if you're scorethreshold isn't set, its going to return the answer that's something around 0.3 or higher. Then to display them in chat you're going to have to basically iterate through them. For example:
var options = new QnAMakerOptions { Top = 3, ScoreThreshold=0.0F };

var httpClient = _httpClientFactory.CreateClient();

var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
    EndpointKey = _configuration["QnAEndpointKey"],
    Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);

_logger.LogInformation("Calling QnA Maker");

// The actual call to the QnA Maker service.
var response = await qnaMaker.GetAnswersAsync(turnContext);
if (response != null && response.Length > 0)
{

    for (int i = 0; i < response.Length; i++)
    {
        await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
    }
}

For my KB, this shows:

Now, if you want to show top three answers from multiple KBs, you're going to have to construct multiple QnAMakers
var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
    KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
    EndpointKey = _configuration["QnAEndpointKey"],
    Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);

var qnaMaker2 = new QnAMaker(new QnAMakerEndpoint
{
    KnowledgeBaseId = _configuration["QnAKnowledgebaseId2"],
    EndpointKey = _configuration["QnAEndpointKey"],
    Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);

//LATER IN CODE:
var response = await qnaMaker.GetAnswersAsync(turnContext);
var response2 = await qnaMaker2.GetAnswersAsync(turnContext);

if ((response != null && response.Length > 0) && (response2 != null && response2.Length > 0))
{
    await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB1:"), cancellationToken);
    for (int i = 0; i < response.Length; i++)
    {
        await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
    }
    await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB2:"), cancellationToken);
    for (int i = 0; i < response2.Length; i++)
    {
        await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
    }
}
else if (response != null && response.Length > 0)
{
    await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB1:"), cancellationToken);
    for (int i = 0; i < response.Length; i++)
    {
        await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
    }
}
else if (response2 != null && response2.Length > 0)
{
    await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB2:"), cancellationToken);
    for (int i = 0; i < response2.Length; i++)
    {
        await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
    }
}
else
{
    await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
}

Then just do the same length check, and SendActivities for each:


text:
Q: How to create log.txt using log4net? I'm able to create logs but unable to write exception string to it...the logs.txt remains empty...
This is the catch block :
 catch (Exception ex)
            {
                Logging.LogError(ex.ToString());
                return new DataTable();
            }

Logging.cs :
public class Logging
{
    public readonly ILog log = LogManager.GetLogger(typeof(Logging));
    public static void LogError(string exception)
    {
        log4net.Config.XmlConfigurator.Configure();
    }
}

web config :
<log4net>
    <appender name="file" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="Logs\Log_%date{dd-MM-yyyy_HH-mm-ss}.txt"/>
      <appendToFile value="true"/>
      <maxSizeRollBackups value="-1"/>
      <!--infinite-->
      <staticLogFileName value="true"/>
      <rollingStyle value="Once"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="file"/>
    </root>
  </log4net>

A: public static class Logging
{
    private static ILog _logger = null;
    private static log4net.ILog Logger
    {
        get
        {
            if(_logger == null)
            {
                _logger = LogManager.GetLogger(typeof(Logging));
                log4net.Config.XmlConfigurator.Configure();
            }
            return _logger;
        }
    }

    // Better to use Exception object. This gives you more details
    public static void LogError(string msg, Exception ex)
    {
         Logger.Error(msg, ex);
    }

Check permissions on your web server and use full path to log file. Also use debug="true" for log4net. Here is example of working log4net configuration, which rolls files on size. You could change it later.
  <log4net debug="true">
    <root>
      <level value="ALL" />
      <appender-ref ref="file" />
    </root>
    <appender name="file" type="log4net.Appender.RollingFileAppender, log4net">
      <file value="wwwroot\logs\Log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maximumFileSize value="1MB" />
      <maxSizeRollBackups value="5" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%-5level] (%thread) %logger - %message%newline" />
      </layout>
    </appender>

A: Change your class to
public class Logging
{
    public static readonly ILog log = LogManager.GetLogger(typeof(Logging));
    public static Logging()
    {
        log4net.Config.XmlConfigurator.Configure();
    }
    public static void LogError(string exception)
    {
        log.Error(exception);
    }
}

A: To use log4net you need to:

*

*configure log4net: take a look at the samples that are available on the site to see how to configure it in a configuration file

*initialize log4net: you need to do it at the start of your application, for example using log4net.Config.XmlConfigurator.Configure();

*instantiate a logger in the class you want to log data from:
private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

*use the logger to log: log.Info("Exiting application.");
In your example you need to declare the logger in the class where the catch block is, initialize log4net at the start of your app, and use the instance to log the exception


text:
Q: R: Convert a caret train object to glmnet object I'd like to ask how can I convert the final model that I get from a grid search with caret's 'train' function into an object of the class that is created with the glmnet function, assuming that I specified method='glmnet'.

A: I'll answer myself (found it looking with different terms): the final model is saved in the train object as attribute 'finalModel', so if the train object is called 'fit', it can be accessed by fit$finalModel


text:
Q: Format code inside jquery append just wondering if its possible to format code whilst using the append() function.
Im creating a form with JSON and jQuery but this form will be quite large and Its going to be annoying to work on one long line of code... so instead of:
$('

<form class="editUserDetails-form" action="admin/process/saveUserDetails.php">Editing Details for User:'+response.username+' , User ID:'+response.userID+'</form>').appendTo('body');

Is it possible to somehow do similiar to:
$('

  <form class="editUserDetails-form" action="admin/process/saveUserDetails.php">
    Editing Details for User:'+response.username+' , User ID:'+response.userID+'
  </form>').appendTo('body');

I know the above will break the code and wont work. But surely theres a way to do what im asking? Unless HOW im doing it is correct / frowned upon :)
Craig.

A: You can say like bellow
$('

\
  <form class="editUserDetails-form" action="admin/process/saveUserDetails.php">\
    Editing Details for User:'+response.username+' , User ID:'+response.userID+'\
  </form>').appendTo('body');


text:
Q: Single XML attribute per line in Android Studio Is there any option in Android Studio to enable / disable to have only one XML file attribute in one line?
By default, I have (for instance) 2 or 3 attributes on the same line.
I would like to have only one attribute per line.
How can I achieve that?
My code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">

<TextView android:text="Hello World!" android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</RelativeLayout>

But instead I would like to have by default this :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main"
tools:context=".MainActivity">

<TextView
    android:text="Hello World!"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</RelativeLayout>

Definitely more readable for me.

A: *

*Ctrl+A (Select All) in your XML file.

*Ctrl+Alt+L (Reformat Code)
that's it.

A: If Ctrl+Alt+L doesn't work, check your Settings->Editor->Code Style->XML->Android->Layout Files->Wrap Attributes

A: Go to File on the top left corner → Settings → Editor → Code Style → XML → Other tab → Wrap Attributes into "Wrap Always" and click OK.
For Windows. Press CTRL + ALT + L to reformat the code.
For Mac. Press Command + Option + L to reformat the code.


text:
Q: Progress Update in AsyncTask , Android I am new to android. I am trying to use asyncTask. I understand there is something called as onProgressUpdate.
I am downloading data from online server and total data is about 2000.
in Background Async I have done the following inside the for loop I keep publishing the value of I. something like this:
@Override
protected String doInBackground(JSONArray... params)
{
  for (int i = 0; i < params[0].length(); i++)
  {
     //I DO MY BACKGROUND PROCESS

     publishProgress(i);
  }
return null;

}
protected void onProgressUpdate(Integer... values) {
            Log.e("Value", "onProgressUpdate - " + values[0]);
        }

This actually prints count one by one until 2000. Now how would I make to show when the count in percentage. Like 1%, 2% till 100%.
Thanks

A: try this:
Use double value instead of Integer
protected void onProgressUpdate(Double... values) {
double percentage = (values[0]/2000)*100;
            Log.e("Value", "onProgressUpdate - " + percentage+"%");
}

A: The formula is stated in the comments, but it is safer to calculate dynamically, rather than hardcoded to 2000.
AsyncTask<JSONArray, Integer, String> task = new AsyncTask<JSONArray, Integer, String>() {
            private int maxProgress;

            @Override
            protected String doInBackground(JSONArray... params) {

                maxProgress = params[0].length();
                for (int i = 0; i < maxProgress; i++) {
                    //I DO MY BACKGROUND PROCESS

                    publishProgress(i);
                }

                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                Log.e("Value", "onProgressUpdate - " + (values[0] * 100 / maxProgress) + "%");
            }
        };


text:
Q: How to extract every second row into seperate column in dataframe? I have a df that looks like this:
col1
aaa
1
bbb
2
ccc
3

How do I pull at every second row out of the dataframe and make it, its own column like so:
col1    col2
aaa     1
bbb     2
ccc     3

I tried this:
df[::1]

since the second row has an index of 1, but I am not returned the data I am looking for.

A: Using reshape
pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])

Full example:
import pandas as pd

df = pd.DataFrame({
    'col1': ['aaa','1','bbb','2','ccc','3']
})

df = pd.DataFrame(df.col1.values.reshape(-1,2),columns=['c1','c2'])
df.c2 = df.c2.astype(int) # optional to convert col to int

print(df)

Returns
    c1  c2
0   aaa 1
1   bbb 2
2   ccc 3

A: Although not as elegant (and as fast!) as reshape I think a readable alternative would be:
df = pd.DataFrame({
    'col1': df.col1[::2].values,
    'col2': df.col1[1::2].astype(int)
})

A: Try:
df['col1'] = df['col1'][0:][::2]
df['col2'] = df['col1'][1:][::2]

A: Another way is with concat
pd.concat([df.col1[::2].reset_index(drop=True), df.col1[1::2].reset_index(drop=True)], axis=1)

A: The Pandas answers are certainly compact.
If you don't need Pandas, or are just curious how this might be done without Pandas, consider:
import csv
import pprint

# configure the shape of your data
reshaped = [['col1', 'col2']]
row_tmpl = [None, None]

with open('sample.csv', newline='') as f:
    reader = csv.reader(f)
    next(reader)  # discard input header

    new_row = row_tmpl[:]  # create "empty" row

    for row in reader:
        data_val = row[0]

        # index will "move over" as columns are filled
        col_idx = new_row.index(None)
        new_row[col_idx] = data_val

        if None not in new_row:    # all columns are filled
            reshaped.append(new_row)
            new_row = row_tmpl[:]  # make empty for next set

pprint.pprint(reshaped, indent=2, width=20)

With sample.csv filled with OP's sample data, I get:
[ ['col1', 'col2'],
  ['aaa', '1'],
  ['bbb', '2'],
  ['ccc', '3'],
  ['ddd', '4']]

This scheme allows us to change the number of rows to interpret as columns simply by changing the size of row_tmpl:
row_tmpl = [None, None, None, None, None]  # or, `[None] * 5`

and we should grow reshaped's headers to match:
reshaped = [['col1', 'col2', 'col3', 'col4', 'col5']]

Now with sample.csv:
col1
aaa
AAA
1
uno
foo
bbb
BBB
2
dos
bar
ccc
CCC
3
tres
baz
ddd
DDD
4
cuatro
foobarbaz

I get:
[ ['col1', 'col2', 'col3', 'col4', 'col5'],
  ['aaa', 'AAA', '1', 'uno', 'foo'],
  ['bbb', 'BBB', '2', 'dos', 'bar'],
  ['ccc', 'CCC', '3', 'tres', 'baz'],
  ['ddd', 'DDD', '4', 'cuatro', 'foobarbaz']]


text:
Q: How to have a function in an abstract class return instances of a child classes in typescript Is it possible to have something like this pseudocode:
abstract class AbstractParent {
    protected value: number;
    constructor(value: number) {
        this.value = value;
    }
    ...
    public times(multiplicator: number) {
        return new ???(value * multiplicator);
    }
}

Which returns a new Foo for class Foo extends AbstractParent and a new Bar for class Bar extends AbstractParent?

A: A maintainable way is to keep the times calculation in the base class, and implement separate create factory methods inside Foo and Bar. This way, the base class is not  aware of its extending child classes.
You declare create as abstract in AbstractParent to make sure it will be implemented in all sub classes. The polymorphic this return type ensures for the caller of times, that the returned instance has the same sub class type (Playground).
abstract class AbstractParent {
    protected value: number;

    constructor(value: number) {
        this.value = value;
    }

    times(multiplicator: number) {
        return this.create(this.value * multiplicator);
    }

    // factory method creates instances of same polymorphic type (Foo / Bar)
    protected abstract create(value: number): this
}

class Foo extends AbstractParent {

    create(value: number) {
        // Polymorphic this type is Foo here, so it's OK to return a Foo.
        // Compiler is not aware of the class context, so we cast.
        return new Foo(value) as this
    }
}

class Bar extends AbstractParent {
    // same as Foo
    create(value: number) {
        return new Bar(value) as this
    }
}

const foo = new Foo(42).times(2) // Foo
const bar = new Bar(42).times(3) // Bar

A: You could pass the child type into the parent constructor and save a reference. This prevents the parent having to know about all the possible child types (though I agree with the other answer that there may be a better way to achieve your overall goal). Something like this (playground link):
type ChildConstructor<Child> = new (value: number, childConstructor: ChildConstructor<Child>) => Child;

abstract class AbstractParent<Child extends AbstractParent<Child>> {
    protected value: number;
    protected childConstructor: ChildConstructor<Child>;

    constructor(value: number, childConstructor: ChildConstructor<Child>) {
        this.value = value;
        this.childConstructor = childConstructor;
    }

    public times(multiplicator: number): Child {
        return new this.childConstructor(this.value * multiplicator, this.childConstructor);
    }
}

class Foo extends AbstractParent<Foo> {
    constructor(value: number) {
        super(value, Foo);
    }
}

class Bar extends AbstractParent<Bar> {
    constructor(value: number) {
        super(value, Bar);
    }
}

Note that to get 100% type safety, each child class would need to have at least one additional private property or method to keep TypeScript's "duck typing" from considering the classes to be interchangeable (since they share the same properties and methods).


text:
Q: Scraping webdata returning no result I am trying to extract data (59,805) from the mentioned URL. And I am using BeautifulSoup and requests package of Python.
Below is the code I am trying, however its giving me no result. Down below is the HTML code, where from I am trying to extract. The result should be 'Confirmed', 59,805
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

case_type = []
count = []

url = requests.get('https://www.covid19india.org/')
soup = bs(url.content,'html.parser')

for a in soup.findAll('div',  attrs={'class':'level-item is-cherry fadeInUp'}):
    b = a.find('h1')
    c = a.find('h5')
    case_type.append(c.text)
    count.append(b.text)

df = pd.DataFrame({'Case Type':case_type, 'Count':count})
print(df)

HTML code snippet from the said page

Confirmed

[+115]

59,805

Active

39,914

Recovered

[+14]

17,901

A: This site has been created in React so the content you're pulling in via requests won't include all of the site content as this is loaded dynamically
If you look at the network requests the site makes when it loads you'll see that the information is coming from:
https://api.covid19india.org/data.json

So you could (assuming you don't affect the site performance / have permission) do:
r = requests.get('https://api.covid19india.org/data.json')
j = r.json()
confirmed = j['statewise'][0]['confirmed']
print(confirmed)


text:
Q: Find a matrix $X$ such that $\exp(X) = M$ Let $M=\begin{bmatrix}
4 & -2 \\
-1 & 5
\end{bmatrix}$.
Find a matrix $X$ such that $e^X = M$, or show this is impossible.
Attempt. I think that this is not possible because of the convergence problem of the logarithm function. But I couldn't prove it. I've computed that $M=PDP^{-1}$ where $P=\begin{bmatrix}
2 & -1 \\
1 & 1
\end{bmatrix}$ and $D=\begin{bmatrix}
3 & 0 \\
0 & 6
\end{bmatrix}$. Thanks!

A: Notice that $P^{-1} M P= D(3,6)$ and $\exp X=M \implies X=\ln M,$
We have $$M=P D P^{-1} \implies X=\ln M= P~ \ln D ~P^{-1},$$ $\ln D = \begin{bmatrix} \ln 3 & 0 \\ 0 & \ln 6 \end{bmatrix}.$ Here we have used the result that$$f(M)=P ~f(D) P^{-1}$$ and
$$f(D)=D(\ln \lambda_1, \ln \lambda_2).$$

A: Hint: Consider $e^{PXP^{-1}}$.


text:
Q: Android Maps v2 API...How to calculate distance between two locations (Lat, long) In my "native" Android app I'm trying to calculate the distance in feet and/or meters (as the crow flies) between two locations on a map. Ideally there would be a method that would take two LatLng values (as that is what I have readily available) as input and return the distance in meters and/or yards. As noted above I'm using Android Maps v2 API.
I've looked at MANY postings (20-30) regarding calculating distances and haven't found any that have helped me resolve my issue. Again this is a native Android application and I'm using Maps v2 API.
Not sure if this is the best approach but I'm currently trying to use the Location method:
distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

But unfortunately the app crashes every time because I get a null value for results. I have verified via the debugger that the latitude and longitude dummy values that I'm passing in are valid and that the value of results is null (hence the problem). Here is the LogCat:
04-04 23:48:04.770: D/onMapClick(17970): lat/lng: (32.90843038503306,-117.22537234425546)
04-04 23:48:08.710: D/dalvikvm(17970): threadid=1: still suspended after undo (sc=1 dc=1 s=Y)
04-04 23:48:08.710: D/dalvikvm(17970): GC_FOR_MALLOC freed 7010 objects / 641712 bytes in 121ms
04-04 23:48:24.980: D/AndroidRuntime(17970): Shutting down VM
04-04 23:48:24.980: W/dalvikvm(17970): threadid=1: thread exiting with uncaught exception (group=0x40020950)
04-04 23:48:25.100: E/AndroidRuntime(17970): FATAL EXCEPTION: main
04-04 23:48:25.100: E/AndroidRuntime(17970): java.lang.IllegalArgumentException: results is null or has length < 1
04-04 23:48:25.100: E/AndroidRuntime(17970):    at android.location.Location.distanceBetween(Location.java:394)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.example.googleplacesandmaps.PlacesMapActivity$1.onMapClick(PlacesMapActivity.java:259)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.google.android.gms.maps.GoogleMap$6.onMapClick(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.google.android.gms.internal.t$a.onTransact(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at android.os.Binder.transact(Binder.java:249)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.google.android.gms.maps.internal.IOnMapClickListener$Stub$Proxy.onMapClick(IOnMapClickListener.java:93)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at maps.i.s.b(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at maps.y.v.c(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at maps.y.bf.onSingleTapConfirmed(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at maps.d.v.onSingleTapConfirmed(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at maps.d.j.handleMessage(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at android.os.Looper.loop(Looper.java:123)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at android.app.ActivityThread.main(ActivityThread.java:4627)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at java.lang.reflect.Method.invokeNative(Native Method)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at java.lang.reflect.Method.invoke(Method.java:521)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)
04-04 23:48:25.100: E/AndroidRuntime(17970):    at dalvik.system.NativeStart.main(Native Method)

Here is the method I'm currently using to try and calculate the distance:
            Location.distanceBetween(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude),
                fxdLatitude, fxdLongitude, results);

The results was defined as a Class variable:  private float[] results = null;
Not sure what i'm doing wrong here.
Again I'd rather have a method that would take two LatLng's as input parameters because they are both readily available...but perhaps more importantly I only have one of the locations available as separate Longitude, Latitude values...the second location is only available as a LatLng value because I get it via onMapClick (when user taps screen). So to use the method distanceBetween I'd need someway to convert this LatLng value into a Latitude/Longitude pair to be able to use it. Anybody know how to do that?
Hopefully there is a simple way of calculating the distances and a simple way to "extract" the latitude/longitude from a LatLng value.

A: You can use following function that accepts two LatLng for calculating distance between them. But before you use this make sure your LatLng variables are not null.

public static double distance(LatLng StartP, LatLng EndP) {
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    double dLat = Math.toRadians(lat2-lat1);
    double dLon = Math.toRadians(lon2-lon1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2 * Math.asin(Math.sqrt(a));
    return 6366000 * c;
}

A: What about making Location object from the two ?
private float distanceBetween(LatLng latLng1, LatLng latLng2) {

        Location loc1 = new Location(LocationManager.GPS_PROVIDER);
        Location loc2 = new Location(LocationManager.GPS_PROVIDER);

        loc1.setLatitude(latLng1.latitude);
        loc1.setLongitude(latLng1.longitude);

        loc2.setLatitude(latLng2.latitude);
        loc2.setLongitude(latLng2.longitude);

        return loc1.distanceTo(loc2);
    }

A: private float[] results = null; is wrong.
You need to use private float[] results = new float[1]; and read the distance with results[0].

A: In Kotlin, you can:
Define a method to convert LatLng to Location:
fun LatLng.toLocation() = Location(LocationManager.GPS_PROVIDER).also {
    it.latitude = latitude
    it.longitude = longitude
}

Call it on each LatLng and use Location#distanceTo(...) method:
val distance = coords1.toLocation().distanceTo(coords2.toLocation())

Define an extension method for LatLngBounds:
fun LatLngBounds.computeDistance(): Float {
    return northeast.toLocation().distanceTo(southwest.toLocation())
}

A: Yes, I think MaciejGórski is right.
The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2].


text:
Q: Play only VAST Video without primary video using JW player I am using JW player to play video. I set up vast Tag following Manner
var playerInstance = jwplayer("player1");
playerInstance.setup({
    file: "sample.mp4",
    width: "100%",
    displaytitle: false,
    controls: true,
    primary: 'html5',
    mute:'false',
    autostart: false,
    advertising: {
          client: "vast",
          tag: 'http://ad4.liverail.com/?LR_PUBLISHER_ID=1331&LR_CAMPAIGN_ID=229&LR_SCHEMA=vast2-vpaid'
        }

The vast video plays infront of the primary video (sample.mp4). Now i need to play only VAST video without primary video. and also need to capture all events for Ad Video. is this possible?? please Help.
Fiddle Link

A: JW Player doesn't offer an ads-only player, so you'll have to load blank.mp4 in order to play the preroll ad.

A: @ Josie Keller
I am able to play just the Ad by targeting a "blank.mp4" (which may be an actual file or a false reference) Either way, it works fine on desktop systems, including OSX and Windows.
I simply use listeners to do something else, like so...
    jwplayer("advertisement").on('adSkipped',function(){next()})
    jwplayer("advertisement").on('adComplete',function(){next()})
    jwplayer("advertisement").on('adError',function(){next()})
    jwplayer("advertisement").on('error',function(){next()})
    jwplayer("advertisement").on('play',function(){next()})
However!...
The ads do not play on either iOS or Android, regardless of whether the blank.mp4 points to an actual file or not. The ad is skipped entirely. Is there something I need to do to get this operational on mobile? I am using  primary: 'html5' as well so I don't see what's causing the ad not to show on mobile...


text:
Q: ALSA - snd_pcm_writei - not using all frames My playback stops after about 20 seconds, when I set non-blocking mode. I first read a file complete to RAM, the buffer is called "buffer_alsa", there are bframes frames in it (here 6894888). Played in blocking mode it works. Played with non-blocking mode it stops after 1048576 frames. I looped it, but no change. Any idea?
snd_pcm_open(&handle, carddevice, SND_PCM_STREAM_PLAYBACK,SND_PCM_NONBLOCK)
//...
pcm = snd_pcm_writei(handle, buffer_alsa, bframes);
if (pcm < 0)
pcm = snd_pcm_recover(handle, pcm, 0);
if (pcm < 0)
{
std::cout << "              snd_pcm_writei failed:  " <<   snd_strerror(pcm) << std::endl;
return;
}
if (pcm > 0 && pcm < bframes)
{
std::cout << "                   expected / wrote:  " << bframes << " / " << pcm << std::endl;
//return;
}

output:
expected / wrote:  6894888 / 1048576


text:
Q: PHP login, getting wrong count value from query / fetch array EDITThanks to the comments below it has been figured out that the problem lies with the md5, without everything works as it should.
But how do i implent the md5 then?
I am having some troubles with the following code below to login.
The database and register system are already working.
The problem lies that it does not find any result at all in the query.
IF the count is > 0 it should redirect the user to a secured page.
But this only works if i write count >= 0, but this should be > 0 , only if the user name and password is found he should be directed to the secure (startpage) of the site after login.
For example root (username) root (password) already exists but i cannot seem to properly login with it.
<?php
session_start();

if (!empty($_POST["send"]))
{
$username = ($_POST["username"]);
$password = (md5($_POST["password"]));
$count = 0;

$con = mysql_connect("localhost" , "root", "");

mysql_select_db("testdb", $con);

$result = mysql_query("SELECT name, password FROM user WHERE name = '".$username."' AND password = '".$password."' ")
    or die("Error select statement");

$count = mysql_num_rows($result);

if($count > 0) // always goes the to else, only works with >=0 but then the data is not found in the database, hence incorrect
{
    $row = mysql_fetch_array($result);

    $_SESSION["username"] = $row["name"];
    header("Location: StartPage.php");
}
else
{
    echo "Wrong login data, please try again";
}

mysql_close($con);
}

?>

A: The best thing you can do in such situations is trying to find out where the problem lies.
So, you could proceed by steps and do the following:
1) start your script with a print_r($_POST), to see what variables are passed by post (by absurd, the problem might even be related to the 'send' guard parameter you have ..IE a form being sent through get)
2) Assign your query to a variable (...and don't forget to escape parameters!) and print it to screen; and then exec it on mysql (or phpmyadmin) to see what results they give.
As a side note, as someone already pointed out, this code might be subject to SQL-injection, so you might consider using prepared statements; see here: quick intro

A: Your login code is good.
But you also need to use md5() function BEFORE storing the password in the database. So when you are inserting the user record in the DB , apply the md5() to the password , save in the DB. Now when you will try to find the record on login, it will match correctly.

A: You should rewrite this with mysqli or PDO and using a newer hash function as well as a salt. MD5 is very widely used and is a target for crackers.


text:
Q: Align equal sign inside case with equal sign outside I want to align the equal sign inside the case with the equal sign outside. How to do that? I have read answers to these questions 1 2 3, but I'm still very clueless. Could anyone please help? Thanks!
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
    v&=s\\
    \begin{cases}
    v'_x&=1\\
    v'_y&=2\\
    \end{cases}
\end{align*}
\end{document}

A: One way is drawing this set of equations:
\documentclass[border=5mm, preview]{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing,
                matrix}

\begin{document}
\[
\begin{tikzpicture}
\matrix (a) [matrix of math nodes,
             nodes = {inner ysep=2pt},
             column sep=-4pt
             ]
{
v       & = s   \\
v'_x    & = 1   \\
v'_y    & = 2   \\
};
\draw[decorate,decoration={brace, mirror}]
    (a-2-1.north -| a-3-1.west) -- (a-3-1.south west);
\end{tikzpicture}
\]
\end{document}

A: Just adapt the code in https://tex.stackexchange.com/a/621802/4427
\documentclass{article}
\usepackage{amsmath}
\usepackage{nicematrix}

\begin{document}

\[
\setlength{\arraycolsep}{0pt}
\begin{NiceArray}{r >{{}}c<{{}} l}
    v&=&s\\[1ex]
    v'_x&=&1\\[1ex]
    v'_y&=&2
\CodeAfter\SubMatrix\{{2-1}{3-3}.
\end{NiceArray}
\]

\end{document}

A: A possibility with the blkarray package:
    \documentclass{article}
    \usepackage{blkarray}
    \usepackage{amsmath}

    \begin{document}

    \[ \begin{blockarray}{r@{}l}
        v&{}=s\\
        \begin{block}{\{r@{}l}
        v'_x &{}=1\\
        v'_y&{}=2\\
        \end{block}
    \end{blockarray} \]

    \end{document}


text:
Q: rails find(params[:id]) always returns id of the first element I am trying to get the id of the user of the entry and return it in the documents show view
documents_controller.rb
def show
    @document = Document.find(params[:id])
    @entries = @document.entries  # to show all entries of a document
    @user = Entry.find(params[:id]).user_id # trying to get id of the user that was selected in the entry (always returns id of the first entry of a document)
end

documents/show.html.erb
<% @entries.each do |document| %>

        <% userName = @user%>
        <%= userName %>	 //always gets same id
        <% #end %>

<% end %>

A: If Entry has a user_id column, then just print it in the loop:
<% @entries.each do |document| %>

    User id: <%= document.user_id %>

    User name: <%= User.find(document.user_id).name %>

<% end %>

With Entry.find(params[:id]).user_id you were only finding that one user_id because you were find it by params[:id], which was always the same in the loop.


text:
Q: Woocommerce order empty items array I call $order = new WC_Order(52); and I get a correct order object but the Items array is empty.
I 've tried select * from wp_woocommerce_order_items where order_id=52; and I got the line item.
Any ideas whats going wrong ?
I am using WooCommerce 3.4.3.

A: To fetch the order items you can use the method
get_items()

I am doing something similar to you and i am doing it like this
$order = wc_get_order($order_id);
$line_items = $order->get_items();

In WooCommerce 3.0, CRUD objects were added so all the data can be accessed using getters and set using setters. Line items are the same so when you have your line items you should loop them and access the data using getters.
For more information about the available getters and setters for these objects you can use this for reference https://docs.woocommerce.com/wp-content/images/wc-apidocs/class-WC_Order.html for the order object and for the product line items you can check https://docs.woocommerce.com/wc-apidocs/class-WC_Order_Item_Product.html
Hope this helps!


text:
Q: XML String Android - Unknown ParentNode I have the following xml:
<THISVALUECHANGESANDISUNKNOWN>
<TEST></TEST>
</THISVALUECHANGESANDISUNKNOWN>

In PHP I can do something like
preg_match('~<TEST>([^<]+)</TEST>~i', $xml, $test);

But how do I get the value of TEST in android, if the parentnode is unknown?`

A: You could use jsoup.
String xml = "<THISVALUECHANGESANDISUNKNOWN><TEST></TEST></THISVALUECHANGESANDISUNKNOWN>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
String testValue = doc.select("TEST").text();

A: This is actually pretty easy to do and is described in good detail in the platform docs: http://developer.android.com/training/basics/network-ops/xml.html


text:
Q: How to get multi-variable facets using tmap for raster maps (tm_raster() +tm_facets()) I would like to create a faceted map using my raster data using the tmap package.
The end result will be multiple raster maps showing "values", with rows showing "class1" maps and columns showing "class2" maps as shown in the example figure below:

I have tried multiple approaches without success. I think the issue is building the raster brick layer in the correct format. Would appreciate any advice.
library(tmap)
library(dplyr)
library(magrittr)
library(raster)

r<-data.frame(lat=c(rep(12.25,5),rep(12.5,5)),
          lon=c(rep(c(-72.25,-71.75,-71.25,-70.25,-69.25),2)),
          value=runif(10));r
rx<-sp::SpatialPointsDataFrame(sp::SpatialPoints(coords=
(cbind(r$lon,r$lat))),data=r%>%dplyr::select(value))
rx@data
sp::gridded(rx)<-T
rx<-raster(rx);rx
r
tm_shape(rx)+tm_raster()
# This works and shows one of the raster maps I would like.

m1<-r%>%dplyr::mutate(class1="class1_A",class2="class2_A",value=value*0.5)
m2<-r%>%dplyr::mutate(class1="class1_A",class2="class2_B",value=value*3)
m3<-r%>%dplyr::mutate(class1="class1_B",class2="class2_B",value=value*10)
m<-bind_rows(m1,m2,m3);m

mx<-sp::SpatialPointsDataFrame(sp::SpatialPoints(coords=
(cbind(m$lon,m$lat))),data=m)
sp::gridded(mx)<-T
mx@data
# mx@data shows the data.frame with the lat/lon and the classes.
# I would like to plot this as facets
mxr<-brick(mx)
tm_shape(mxr)+tm_raster(col="value")+tm_facets(by="class1","class2")

A: An answer using ggplot2 instead of tmap:
library(dplyr)
library(ggplot2)

r <- data.frame(lat = c(rep(12.25, 5), rep(12.5, 5)),
                lon = c(rep(c(-72.25, -71.75, -71.25, -70.25, -69.25), 2)),
                value = runif(10))

m1 <- r %>% dplyr::mutate(class1 = "class1_A",
                      class2 = "class2_A",
                      value = value * 0.5)
m2 <- r %>% dplyr::mutate(class1 = "class1_A",
                      class2 = "class2_B",
                      value = value * 3)
m3 <- r %>% dplyr::mutate(class1 = "class1_B",
                      class2 = "class2_B",
                      value = value * 10)
m4 <- r %>% dplyr::mutate(class1 = "class1_B",
                          class2 = "class2_A",
                          value = value * 6)
m <- bind_rows(m1, m2, m3, m4)
head(m)
#>     lat    lon      value   class1   class2
#> 1 12.25 -72.25 0.07352787 class1_A class2_A
#> 2 12.25 -71.75 0.44638923 class1_A class2_A
#> 3 12.25 -71.25 0.20745736 class1_A class2_A
#> 4 12.25 -70.25 0.48200665 class1_A class2_A
#> 5 12.25 -69.25 0.06922203 class1_A class2_A
#> 6 12.50 -72.25 0.12036249 class1_A class2_A

# probably you should also add + coord_map()
ggplot(m, aes(x = lat, y = lon, fill = value)) +
  geom_tile() +
  facet_grid(class1~class2)

Created on 2019-01-31 by the reprex package (v0.2.1)