user relationships - add friend link in a content-profile node

Question: I have installed the User Relationships module, and I have questions about how it works.
When you install the module, a "relationships" link should be added in a user profile page (users/myname), but in my case it doesn't; I've modified user-profile.tpl.php, and cleared the cache, but still the link doesn't appear. What's wrong?
How can I add a link to "add/remove friend" on a content-profile node of user? And also how to output list of user's friends? I guess a view block would help me in this situation.
Comment: What version of Drupal?  Which version of User Relationships?
Comment: Can you see the links as the admin account? Are there any configuration options that need to be set first? Have you looked into your permissions? It may be that users need to be assigned permissions before they can view the links.
Comment: 1. i Can't see the links as the admin.
2. No
3. Yes, granted permissions to all users.
Comment: Could you possibly post a link to the site?
Comment: here: http://ruh.kz
Comment: Someone help please, have searched whole drupal.org - no results
Answer: I followed the instructions that I found in the documentation of the module, and everything worked absolutely perfect. The steps for your reference were:

Enabled the modules: UR-API, UR-Mailer, UR-UI, UR-Views
Created a new relationship (e.g. friend)
In Permissions make sure that you have enabled the can have relationships permission in the user_relationships_api module (this is what I forgot the first time)

The rest of the permissions are pretty straight-forward. If you follow the instructions to the letter, you will get the link in the user profile page.
P.S: The guide in the above-mentioned link has a screenshot for the required permissions: make sure that your permissions match this screenshot's EXACTLY.
As for the block that you want to create:
Enable the UR-blocks module. It creates sample useful blocks (including a block for each relationship that you created). You can insert this block directly in the profile node using the corresponding tpl.php file and a code like the one that you can find in this article:
Drupal - How To Display Block In Node?
Comment: ok, 1st question is solved. Deleted modifies user-profile.tpl.php and cleared the cache, then link  become a friend bla bla appeared on user-profile.
I can easily print this link in a user-profile.tpl.php with this code:

Now is the 2nd question:

How can i add a link to "add/remove friend" on a content-profile node of user? And also how to output list of user's friends? (I guess views block would help me in this situation).
Comment: Ok, now i've added the link add/remove friend in a profile node. Posted my solution here: http://webcoder.kz/user-relationships-addremove-friend-link-user-profile-node

So now is the only one question remains: How to output a block of user friends in a user profile with views?
Comment: Are you using the advanced profile kit? Are you using panels? How do you get the user profile as a node (i.e. which module are you using to do that)?
Comment: I'm not using nor APK, nor panels. I'm using content_profile module to do that.
Comment: Check the additions in the edit above.
Comment: @f1234k: thanks for the answer, but what if i want a views-block? I need to display there cck imagefield such as field_photo (I use this field as user avatar).
Comment: I suppose it will not be very hard to do that either. Since the profiles in your configuration are actually nodes, you will have to create a node type of view, in Arguments use the User:id, in the Fields the fields that you want to display (i.e. you can use the cck field with the avatar etc) and in the filter "User Relationships: Relationship type: Friend (or whatever). Then, all you have to do, is embed the view in your node with the user id as an argument.


Keras multi instance classification problem

Question: I'm trying to do a binary classification task on a dataset of 1D signals. Here are the input shapes of the training batch x and the groud truth batch y. In other words, I have 16 signals with 38400 time steps and 1 feature per time step for each batch. Each signal is classified into 150 time of one class (kind of multi instance learning problem).

x shape (16, 38400, 1)
y shape (16, 150, 1)

Here is the network I'm using so far:
model = Sequential()
model.add(LSTM(2, return_sequences=True, input_shape=params['input_shape'], dropout=0.5))
model.add(TimeDistributed(Dense(params["num_categories"])))
model.add(Activation('softmax' if params['num_categories'] != 1 else 'sigmoid'))

from keras.optimizers import Adam
optimizer = Adam(lr=params['learning_rate'], clipnorm=params.get("clipnorm", 1))
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])

return model

Please note that params['input_shape'] is equal to [:, :, None]. Here are the output shapes of the network layers when running the code:
Tensor("lstm_1/transpose_1:0", shape=(?, ?, 2), dtype=float32) : (1, 38400, 2)
Tensor("time_distributed_1/Reshape_1:0", shape=(?, ?, 1), dtype=float32) : (1, 38400, 1)
Tensor("activation_1/Sigmoid:0", shape=(?, ?, 1), dtype=float32) : (1, 38400, 1)

The problem is that we're getting this error:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [4,150,1] vs. [4,38400,1]
     [[{{node metrics/acc/Equal}} = Equal[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](_arg_activation_1_target_0_1/_65, metrics/acc/Round)]]
     [[{{node metrics/auroc/auc/assert_greater_equal/Assert/AssertGuard/Assert/Switch_2/_93}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_1152_...t/Switch_2", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

I know that this error is related to y that does not have the same shape of the output of the network. But, I'm not sure what kind of layer should I add to the network in order to get the required shape. Can you please help?
Thanks in advance.
Answer: You could add a fully-connected layer to your network. If the output of your network is size B, and you want it to be size A, you can define a fully connected layer to take input of size B and produce output of size A. Please see the documentation of tf.keras.layers.Dense: https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense


Why do Wikipedia and nLab seem to give completely incompatible definitions of the term "simplex"?

Question: nLab seems to define that a simplex is an inhabited finite totally-ordered set.
Wikipedia seems to define that simplex is a subset of real affine space satisfying certain conditions.

Q. What's going on here?
Comment: See definition 1 [here](https://ncatlab.org/nlab/show/simplex). It seems nLab defines *simplex* not really different from either Wikipedia or me.
Answer: That nLab article is not really defining a simplex; what it is defining is the simplex category $\Delta$. This is the diagram category used to define simplicial objects and cosimplicial objects. When you talk about "concrete simplices" as particular topological spaces, what you are really doing is describing a particular cosimplicial object, namely the functor $\Delta \to \text{Top}$ sending the "abstract $n$-simplex" as defined by the nLab to the "concrete $n$-simplex" as defined by Wikipedia.
(In general, the question to ask is not "what is an X?" but "what is the category of Xes?" It's possible to present the same category in many different ways, and in particular it's possible to define the simplex category by taking its objects to be "concrete $n$-simplices" provided that you define the morphisms appropriately.)
By abstract nonsense, this cosimplicial object determines an adjunction between the category $[\Delta^{op}, \text{Set}]$ of simplicial sets and $\text{Top}$, given in one direction by geometric realization and in the other direction by taking the singular simplicial set. This is the starting point of the simplicial (as in simplicial sets) approach to homotopy theory, and in fact was a major motivating example for the invention / discovery of adjoint functors.
Comment: I don't think Quillen invented adjoint functors, but rather Quillen adjunctions... According to Wikipedia the idea of adjoint functors was first formulated by Kan.
Comment: @Najib: ah yeah, I always mix the Daniels up.


How to add comment box and post form to django rest framework

Question: I created a site by following a django rest framework tutorial(http://126.96.36.199:8000)
and i finished hooking up login part and posts,
but i have no clue in what way how i can put a posting form and comment box for the individual post.
here is what i have tried though
html
<form id="post_form" method="post" action="">
<input type="text" name="title" placeholder="Username">
<input type="text" name="content" placeholder="content">
<button class="ladda-button button-primary login_button" ng-click="vm.submit()"/>submit</button>
</form>

jquery
  $('#post_form').on('submit', function(e) { e.preventDefault()

  $.ajax({
    type:"POST",
    url: '/api/posts/create/',
    data:$('#post_form').serialize(),
    error: function(response){
      alert('Not authorized.');  // Or something in a message DIV
    },
    success: function(response){
      console.log(response);
      $('.login_bar').html(response)
      $('.login_bar').html(response)
      $('#logout_form').toggleClass(show)
    // do something with response
 }
});

});

and here is my API.
http://184.108.40.206:8000/api/posts/create/
could anyone help me out here?
Comment: here are my rest APIs
Comment: http://22.214.171.124:8000/api/posts/
http://184.108.40.206:8000/api/comments/
http://18.104.22.168:8000/api/comments/create/
Comment: How do your models and REST views look like?
Comment: @Azimkhan this is the post serializers.py https://dpaste.de/Epfa
Comment: and the views.py https://dpaste.de/Ddo1#L5
Answer: Look at this exapmle:
models.py
class Post(models.Model):
    title = models.CharField(max_length=500)
    body = models.TextField()

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post)
    text = models.TextField()
    author = models.CharField(max_length=100)

    def __str__(self):
        return "[%s] %s" % (self.author, self.text)

serializers.py
from .models import Post, Comment
from rest_framework import serializers

class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = ('text', 'author', 'post')

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('title', 'body', 'comment_set')

views.py
from rest_framework import viewsets
from rest_framework.permissions import AllowAny
from .models import Post, Comment
from .serializers import CommentSerializer, PostSerializer

class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer
    permission_classes = [AllowAny]
    queryset = Post.objects.all()

class CommentViewSet(viewsets.ModelViewSet):
    serializer_class = CommentSerializer
    permission_classes = [AllowAny]
    queryset = Comment.objects.all()

urls.py
from django.conf.urls import url, include
from rest_framework import routers
from .views import PostViewSet, CommentViewSet

router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)
router.register(r'comments', CommentViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Sending a POST request in JSON format to http://127.0.0.1/comments/ with the following content:
{"author":"Jerry", "text": "Nice post!", "post": 1}

creates a new comment for post with id = 1 in this case
Comment: thanks for the example. but is there any way i can just put a comment without having to type in the 'post' number? for example, just like this stackoverflow comment system.
Comment: @MarkKang You could have nested resource design with the urls like `/posts/1/comments`. In this case you don't have to send post id cause id is determined in the url. But what's the problem with previous solution?
Comment: okay, but i already have create api for both post and comments. could you take a look at this page and why the post box doesn't work? http://220.127.116.11:8000/
Answer: This may work for you:
views.py :-
def adComment(request):
    print request
    if request.method == 'POST':
        form = CommentForm(request.POST) #Validate your data with form.
        if form.is_valid():
            instance = form.save(commit=False)
            instance.title = form.cleaned_data['username']
            instance.comments = form.cleaned_data['content']
            instance.save() #Will save your data if valid.
            data = {'success':True,'msg':"Store comment's data successfully"}
            return Response(data)

    else:
        data = {'success':False,'msg':'Error in storing comments'}
        return Response(data)

forms.py
from django.forms import ModelForm
from models import commentData

class CommentForm(ModelForm):
    class Meta:
        model = commentData #Your model name created to store comment's data
        fields = [
                  "username",
                  "content",

                  ]

Comment: sorry. but i am using plain DRF, which means there's no django template that renders what's inside the views.py. I use API.
Comment: You can use these function in urls with as_view().


Blazor: Failed to load resource: the server responded with a status of 404 ()

Question: I'm having a very difficult time trying to understand what the issue is with my blazor application. I have a client blazor which I'm updating from .net 3.1 to .net 6. I've read the instructions regarding migrating from 3.1 to 6 however my application never loads when I'm trying to debug it. It throws:
"Failed to load resource: the server responded with a status of 404 ()" error
I've read in other posts about blazor.webassembly.js not loading properly but I'm not sure what I'm doing wrong. I've checked the references for any errors. The Api reference is running properly on .NET 6 and the Shared library is using .net standard 2.0
Here is some code in case you need it.
Thanks for your time.
Index.html:
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.5" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.5" PrivateAssets="all" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
    <PackageReference Include="System.Net.Http.Json" Version="6.0.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\SkillMatrix.Api\SkillMatrix.Api.csproj" />
    <ProjectReference Include="..\SkillMatrix.Shared\SkillMatrix.Shared.csproj" />
  </ItemGroup>

</Project>

Index.html:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>SkillMatrix.Client</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/app.css" rel="stylesheet" />

    <app>Loading...</app>

        An unhandled error has occurred.
        Reload

Answer: Figured out the solution. I had to change the csproj from
<Project Sdk="Microsoft.NET.Sdk.Web">

to
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

based on this answer
Also make sure that the Microsoft.AspNetCore.Components.WebAssembly references on the item group are set to at least version 6.0.0
Answer: copy This or Replace to wwwroot index.html
to head tag
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link rel="icon" type="image/png" href="favicon.png" />
<link href="BlazorApp1.Client.styles.css" rel="stylesheet" />

<link href="_content/Syncfusion.Blazor/styles/bootstrap5.css" rel="stylesheet" />

Comment: Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach?
Answer: Only replacing <link href="BlazorServer.styles.css" rel="stylesheet" />
to <link href="AppName.styles.css" rel="stylesheet" /> fixed the issue.
Edit:
Sorry, I made some confusing about BlazorServer because I though it was related to the Blazor Server template, but it was related to the name of Blazor project I have with that name. I was migrating another Blazor project from netcore3.1 to net6.0 and I faced the issue in this post and replacing what I writes above, it fixed the issue. So, anyone who have this problem, need always do <link href="AppName.styles.css" rel="stylesheet" />.


Find out the title and artist of a song in Ruby

Question: I've found an interesting gem to discover from an unknown file which music it comes from returning the title and the artist : https://github.com/tenderlove/earworm
The fact is the last commit was 4 years ago and the website used is no longer working...
Does anyone know of another solution for this problem ? Another gem or another snippet ?
Answer: You could use taglib. I used it in my mylastfavourite script and it works really good and fast.
It reads mp3 tags. If you search for a gem which takes the stuff from a webservive, you could try rbrainz for example. I never worked with this before.


Why does this implementation of the Monty Hall give the probability to be 50%?

Question: I recently watched a video about the Monty Hall Problem and was interested in the fact that the contestant had a 2/3 chance of winning when switching. So, I decided to write a simulation for it to see it for myself. However, my simulation gave the answer to be 50%. Could somebody point out why? Note: the number of doors can be adjusted by changing num_of_doors.
from random import randint

num_of_doors = 3
num_of_simulations = 0
wins = 0

while True:
    num_of_simulations += 1
    doors = {k: "Donkey" for k in range(1, num_of_doors + 1)}
    car = randint(1, num_of_doors)
    doors[car] = "Car"
    choice = randint(1, num_of_doors)

    while len(doors) > 2:
        reveal = randint(1, num_of_doors)
        if reveal in doors:
            if reveal != choice and doors[reveal] != "Car":
                del doors[reveal]

    for k in doors:
        if k != choice:
            choice = k

    if doors[choice] == "Car":
        wins += 1
    print(100 * wins / num_of_simulations)

Comment: You probably want a `break` statement after `choice = k`
Answer: You've found the answer, but I thought I'd just post my shot at this:
from random import randint

def monty(n_doors):
    car = randint(0, n_doors - 1)
    first_choice = 0  # always pick 0 for convenience
    remaining_door = car if first_choice != car else 1  # 1 for convenience
    return remaining_door == car

total_runs = 10000
trials = [monty(3) for x in range(total_runs)]
print(sum(trials) / total_runs)

Gives:
0.6705


Understanding students t-test

Question: Suppose we have 4 groups of sample data with equal sizes and we want compare mean of group 1 with group 2 and group 3 with group 4. So we perform independent sample t-test on the pair of groups and their results are as follows
group 1, group 2
t_score = -5000, p_value = 0
mean(group 1) < mean(group 2)

group 3, group 4
t_score = -100, p_value = 0
mean(group 3) < mean(group 4)

What conclusion we can draw from this data. I am new to statistics, if the question seems very general then please forgive me.
Comment: It seems that your grouping variable (`group`) has four levels - namely `group 1`,  `group 2`,  `group 3`  and `group 4`. Is that so?
Comment: @AyalewA. I don't need to compare all 4 groups only pair wise analysis is needed
Answer: Assuming you have correctly coded the problem, you can conclude that there are statistically significant differences between a) Group 1 and 2 and b) Group 3 and 4 and that groups 2 and 4 have higher means than groups 1 and 3, respectively.
However, I am a bit worried that things were done correctly.
The output is very minimal.  A p value can never be 0, so there was some sort of rounding done there. And a t score of -5000 is very, very big. This is the sort of t you would get if you compared the heights of basketball players and jockeys.
Also, the t scores were rounded to integers, which is odd.
Comment: @Ayalew, I disagree because the OP explicitly states that he wants to compare group 1 to 2 and 3 to 4, so there is no benefit of testing additional hypotheses.
Comment: It is peculiar to have rounded t statics that are 5000 and 100.
Comment: I think if `group` is a variable with four levels, it seems better to go for `one-way ANOVA`. Subsequent to the `one-way ANOVA`, pair-wise comparison could be considered with adjustment for multiple testing.
Comment: @FransRodenburg yes you are right I just need to compare g1 with g2 and g3 with g4
Comment: @PeterFlom yes there is rounding p value were very small

Understanding students t-test


Why has India been refusing DRS (Decision review system) in Cricket?

Question: What is the reason behind the refusal of the Board Of Control For Cricket In India (BCCI) to accept DRS in cricket, while on the other hand most other major teams favour it?
Answer: The BCCI's position
The BCCI's opposition to the Decision Review System has been linked to three main factors.
1) The technology is not 100% accurate
BCCI president N Srinivasan said in December 2012:

We don't believe the technology is good enough [...] if you want to use technology it must be perfect. [...] I'm not against technology but one should be cautious and we should be clear what it is that we are trying to achieve. If you say my correct decision percentage has gone up from 94 to 95.6, is that all you are looking to achieve? It is relative.

Dave Richardson, the president of the ICC, suggested in March 2013 that unfavourable decisions against key India players may have contributed to the BCCI's opposition:

When they first trialled it [...] the technology wasn't very good. The players weren't used to it so every time the Indians asked for a review it went against them. I think it was Sehwag or one of their star batsmen who was given out by mistake by ball-tracking.

2) The umpire's decision is questioned
In his December 2012 interview, N Srinivasan commented:

In cricket the umpire's verdict is final [...] but now you're saying that I have two attempts to question [the umpire's] decision.

3) The system is expensive
N Srinivasan added:

There is a cost to DRS and there are only one or two people involved. It's a monopoly-area situation, which I am not going to go into here.

The ICC's position
1) DRS improves accuracy
Dave Richardson pointed out in February 2012:

If we use DRS, the percentage of correct decisions increases by approximately four to five percentage points, from 93% to 98%.

In the wake of the Trent Bridge Test of 2013, a match noted for a particularly high number of controversial umpiring decisions, the ICC observed that the number of correct decisions had increased from 90.3% to 95.8% through use of the DRS. Their press release declared:

Our confidence in technology is [...] strengthened by the fact that there was an increase in the number of correct decisions in the Trent Bridge Test through the use of the DRS. Technology was introduced with the objective of eradicating the obvious umpiring errors, and to get as many correct decisions as possible. If it can help increase the correct decisions by 5.5 percent, then it is a good outcome, but we must continue to strive to improve umpiring and the performance of the DRS.

2) DRS may improve the balance between bat and ball
Whilst urging caution in drawing conclusions too hastily, Richardson replied, in response to the suggestion that DRS should encourage batsman to use their bats more (because of the increase in LBW decisions):

Yes, it is going to bring about a change of technique. And that will improve things for everybody [...] A year ago, every Tom, Dick and Harry was averaging more than 50 in Test cricket. The balance between bat and ball had got out of kilter and experts were complaining. I think that using DRS may help redress that balance.

3) The cost is justified
Richardson stated:

It is expensive [...] In my view, cricket will pick up the cost [...]  because eventually the broadcasters will include it in their budgeting. [...] The percentage of correct decisions increases [...] I think it is worth it. Technology is here to stay.
Answer: Because BCCI does not feel the DRS system is foolproof. See this article for more information.

Dave Richardson, the International Cricket Council's (ICC) chief executive, has admitted that the technology that drives the Decision Review System (DRS) was not foolproof and that the Board of Control for Cricket in India (BCCI) does "have its own reasons" for opposing DRS.
Richardson's comments follow the first Ashes Test between England and Australia at Trent Bridge, where a number of umpiring howlers coincided with a controversy surrounding the efficacy and use of DRS.
Comment: Can you source your answer?
Comment: http://www.wisdenindia.com/cricket-news/india-good-reason-oppose-drs/69933
Comment: Good to have a reference; however, the quote only states that the BCCI has "its own reasons", without actually stating what those reasons are (although not being "foolproof" is implied).


UIView container disappears when I move it's Y origin down

Question: I have UIView which is container for button "send" and textView.
When I starting editing I have keyboard on the screen and I change Y origin of the container to move it higher and not be covered by keyboard.
When I finish editing I got keyboard hidden and my container(UIView with button and textView) just disappears! But if I turn simulator right or left this became visible again.
Here is the animation code that move my container up and down:
func textViewDidChange(textView: UITextView) {

    self.messagePromptLabel.hidden = messageTextView.hasText() ? true : false

}

func textViewDidEndEditing(textView: UITextView) {
    if !self.messageTextView.hasText()  {
        self.messagePromptLabel.hidden = false
    }
}

func didTapScrollView(){
    self.view.endEditing(true)
}

func keyboardWasShown(notification: NSNotification) {

    let dict: NSDictionary = notification.userInfo!
    let keyboardSize: NSValue = dict.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
    let frameKeyboardSize: CGRect = keyboardSize.CGRectValue()

    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.chatScrollView.frame.origin.y -= frameKeyboardSize.height
        self.messageView.frame.origin.y -= frameKeyboardSize.height

        }) { (finished: Bool) -> Void in

    }

}

func keyboardWillHide(notification: NSNotification) {

    UIView.animateWithDuration(0.3, animations: { () -> Void in
        self.chatScrollView.frame.origin.y = self.chatScrollViewOriginY!
        self.messageView.frame.origin.y = self.messageTextViewOriginY!

        }) { (finished: Bool) -> Void in
    }
}

Some additional code
This code may help find out something.
@IBOutlet weak var messageTextView: UITextView!
@IBOutlet weak var chatScrollView: UIScrollView!
@IBOutlet weak var messagePromptLabel: UILabel!
@IBOutlet weak var messageView: UIView!

var chatScrollViewOriginY: CGFloat?
var messageTextViewOriginY: CGFloat?

var messageArray = [String]()
var senderArray = [String]()

var currentUserImage: UIImage?
var recipientImage: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    messageTextView.addSubview(messagePromptLabel)
    self.title = recipientNickname

    chatScrollViewOriginY = self.chatScrollView.frame.origin.y
    messageTextViewOriginY = self.messageTextView.frame.origin.y
    print(" messageTextViewOriginY \(messageTextViewOriginY)")

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapScrollView")
    tapGestureRecognizer.numberOfTouchesRequired = 1
    chatScrollView.addGestureRecognizer(tapGestureRecognizer)
    chatScrollView.backgroundColor = UIColor.redColor()
}

func textViewDidChange(textView: UITextView) {

    self.messagePromptLabel.hidden = messageTextView.hasText() ? true : false

}

func textViewDidEndEditing(textView: UITextView) {
    if !self.messageTextView.hasText()  {
        self.messagePromptLabel.hidden = false
    }
}

func didTapScrollView(){
    self.view.endEditing(true)
}

Question:
What make my UIView container invisible all the time when I hidding keyboard and make it visible when I turn my phone left or right?
Answer: You need to add this code in your send button action:
self.view.endEditing(true)


Wait Until Website Internal Search Has Completed Using VBA

Question: I am really struggling to get my VBA code to wait until a website I am accessing, finishes an internal search it is performing.
So far I have tried:
Do While ie.Busy: DoEvents: Loop

Set doc = ie.document

Do While doc.readyState <> "complete": DoEvents: Loop

but it does not work. I could post the html 'refresh' function if that would help?
Any ideas would be greatly appreciated.
EDIT
It is using the following function which I have gathered from the source code:
var limit="5";
function beginrefresh()
{
if (!document.images) return;
if (limit==1)
    document.getElementsByTagName("Form")[0].submit();
else
   {
      limit-=1;
      window.status="Page will refresh in " + limit + " seconds.";
      setTimeout("beginrefresh()",1000);
   }
}

window.onload = function () { beginrefresh(); }

EDIT
I have cracked it and it was really simple in the end. I used the following to search for a known id on the page that was being loaded. So when it found this id it knew that the code could continue. A very useful technique IF you know an the name of an id on the page loading.
Do

Do While ie.Busy: DoEvents: Loop

    Set doc = ie.document

Do While doc.readyState <> "complete": DoEvents: Loop

Set testobject = ie.document.getElementById("changeFilterCriteria")

   If Not testobject Is Nothing Then Exit Do

Loop
EDIT
Or maybe not - it does work for about 5 or 6 times in a row but then crashes on
Set testobject = ie.document.getElementById("changeFilterCriteria")

IE comes up with 'internet explorer cannot display the webpage',
If I then click back and then refresh the page is still performing its internal search.
Any help would be gratefully received!
Jim
Comment: What's an "internal" search?  More code would be useful I think...
Comment: It is using the following function which I have gathered from the source code: var limit="5"

function beginrefresh(){
 if (!document.images)
  return
 if (limit==1)
  document.getElementsByTagName( 'Form' )[0].submit()
 else{
  limit-=1
  window.status="Page will refresh in " + limit + " seconds."
  setTimeout("beginrefresh()",1000)
 }
}

window.onload = function ()
{

beginrefresh()
Comment: How do I add a full comment and also use proper code tags?
Comment: @Jim77 you can't. You should update your original question to include the code snippet(s) instead of putting them in comments.
Comment: Try something like: `While IE.Busy Or IE.ReadyState <> 4: DoEvents: Wend`
Comment: @ David Zemens thanks for the code but does not wait until the internal search refresh is completed
Comment: What does this page actually do? It seems like it just refreshes itself at 5,4,3 and 2 second intervals and then submits a form.  Where does that form point to ? Another page?
Comment: From the users point of view it displays "Please wait while your document is being processed" and a yellow circle with increasing white segments taken out of it. I think this occurs for 5 seconds and then it checks (I assume) if all the data has been gathered and then shows the data else repeats the process. Does that help at all? What other code could I add to help?
Comment: The page is setup so that the left hand margin stays the same but the refresh part take place on the centre and right parts...
Comment: Are there any professional sites where you cqn pay to guarantee a solution?
Comment: A bit difficult to provide an answer without the full source of the page or a URL to look at.
Comment: Do you want the full source code for the page?
Comment: Yes, the full source would be useful (feel free to snip out parts you know aren't relevant).  A URL would be better though.
Answer: This is a tricky situation that I have come across numerous times as well. The traditional "Do...Until" loop with IE.ReadyState doesn't work after the first time the page is accessed, mostly because IE and Excel are out of synch at that point.  The best approach I've found is to use a Boolean flag in a "Do...If" loop, where the flag is triggered by a reference to an element in the page you're refreshing.  Until the page refreshes, the flag will be in one state. As long as the flag is in that state, the Do loop continues.  So, somewhere after you've instructed the page to refresh, insert the following code (be sure to adapt for your specific circumstance):
Dim flag as Boolean: flag = False
Dim lng_cnt as long: long_cnt = 0
Dim elem_temp as IHTMLElement: Set elem_temp = IE.document.getElementById("*element_name*")
Do Unitl flag = True or lng_cnt = 30
    If elem_temp Is Nothing Then
        flag = False
    Else
        flag = True
        Exit Do
    End If
    lng_cnt = lng_cnt +1
    Application.Wait (Now() + TimeValue("00:00:01"))
Loop

Note: I added the counter (lng_cnt) to prevent infinite looping. It instructs the program to wait 1 second before continuing if the page hasn't loaded yet, and will discontinue after 30 seconds; because you never know if the page's server is down or whatever. Hope this helps.


Force   between the last two words in nextjs app

Question: On all application I build I keep manually adding   in between the last two words of all paragraphs to avoid widows as they are not as aesthetically pleasing. I've tried multiple ways of setting up plugins  for nextjs that build my code with that feature on.
I know it's very easy to solve that on the client, but it would cause a layout shift on the first paragraphs and while you could add it manually that doesn't feel like the correct solution. I honestly think that should be a css option, but I know there is none.
So I still wonder is there a way to let your application manipulate your JSX code before it becomes the HTML page it becomes?.
I was thinking another option is to just store the text somewhere else and always push it with   but that would require setting up a db connection where it's not always necessary.
Answer: 1 . Create a custom Document component in your pages/_document.js file. This component is responsible for rendering the HTML document that Next.js generates.
2 . In the Document component, override the render method to modify the generated HTML. You can use the ReactDOMServer.renderToString method to render your app's JSX code to HTML, and then manipulate the HTML string before returning it.
Here's an example code:
<code>enter code here
 import Document, { Html, Head, Main, NextScript } from 'next/document'
 import ReactDOMServer from 'react-dom/server'

 class MyDocument extends Document {
 static async getInitialProps(ctx) {
 const initialProps = await Document.getInitialProps(ctx)
 return { ...initialProps }
 }

   render() {
   const { html } = ReactDOMServer.renderToString(<Main />)
   const modifiedHtml = html.replace(/(\s[\w'-]+)(\s[\w'-]+)(<\/p>)/gi, '
 $1 $2$3')

    return (
    <Html>
    <Head />
    <body dangerouslySetInnerHTML={{ __html: modifiedHtml }} />
    <NextScript />
  </Html>
   )
 }
}

export default MyDocument
</code>
This code uses a regular expression to find all occurrences of two words separated by a space in a paragraph () tag, and replaces the space with a non-breaking space character ( ).
Note that this approach modifies the generated HTML directly, so it won't work if you're using client-side rendering (CSR) or static site generation (SSG) in Next.js. Also, this solution assumes that all your paragraphs are wrapped in a  tag.
I hope this helps you add the non-breaking space character between the last two words of your paragraphs in Next.js!
Comment: That looks like a ChatGPT response. I only need a nbsp between the last two words of a paragraph.

I'm looking for a solution that works with SSG.


Object of type Cart is not JSON serializable

Question: I have a products model and a cart model. There is a ManyToMany relation that I put in cart model.
I am trying to return the object of cart model along with the context dictionary but it is giving this error "Object of type Cart is not JSON serializable".
I am using Django version '3.0.7'.
I am following Justing Michael's Tutorial,He is using lower Django version and its working on that.
Did Django change this thing?
class CartManager(models.Manager):
    def new_or_get(self,request):
        cart_id = request.session.get('cart_id')
        qs = self.get_queryset().filter(id = cart_id)
        if qs.count() == 1:
            new_obj  = False
            cart_obj = qs.first()
            if request.user.is_authenticated and cart_obj.user is None:
                cart_obj.user = request.user
                cart_obj.save()
        else:
            cart_obj  = Cart.objects.new_cart(user = request.user)
            new_obj   = True
            request.session['cart_id'] = cart_obj
        return cart_obj,new_obj

    def new_cart(self,user=None):
        user_obj = None
        if user is not None:
            if user.is_authenticated:
                user_obj = user
        return self.model.objects.create(user=user_obj)

and the model actually is:
class Cart(models.Model):
    user        = models.ForeignKey(User,on_delete = models.CASCADE,null=True,blank=True)
    products    = models.ManyToManyField(Product,blank=True)
    #more fields

and views.py is:
def cart_home(request):
    cart_obj,new_obj = Cart.objects.new_or_get(request)
    context={'cart':cart_obj}
    return render(request,'carts/cart_home.html',context)

Comment: `request.session` can only store simple data structure like list, dict, can not be used to store model instance object. change your code to `request.session['cart_id'] = cart_obj.id`, next time you get your `cart_obj` through `Cart.objects.get(id=request.session['cart_id'])`
Answer: You can't send a Python class instance (such as a Model class instance) as a render data, you must send a json like object (a dict in Python).
So what you need is to convert cart_obj to a dict so it can be sent to the frontend through a render. The easiest way to do it with Django is to use a serializer (In your case, the best option is a ModelSerializer).
def cart_home(request):
    cart_obj,new_obj = Cart.objects.new_or_get(request)
    cart_obj_dict = CartSerializer(cart_obj).data
    context={'cart':cart_obj_dict}
    return render(request,'carts/cart_home.html',context)

Comment: Sorry, I had made some mistake, I will compare the previous code with new code and update by tomorrow
Answer: I am sorry to disturb you guys,I had made an idiotic mistake:
request.session['cart_id'] = cart_obj

I was trying to assign cart object to session variable which was a typo ,instead in reality I should have done this:
request.session['cart_id'] = cart_obj.id

Credits:  minglyu


How to change the image size within a Drupal view

Question: Does anybody know the best way to change the image size of a field within a view using Drupal 8?
Answer: You can create an image style at admin interface and then use same style at your view settings.
Navigate to admin/config/media/image-styles and add new style. After that edit image field inside your view which will look like below image.
In image you can see Image style which you have created in earlier step. This way you can change the image sige at views.
Comment: perfect answer +1


Psychological variables: Right percentage of subjects to choose when comparing subjects depending on their level on Neuroticism (Eysenck's model)

Question: I am trying to analyze some data regarding the relationship between Neuroticism/Stability, from Eysenck's model of personality, and ease of use (one of the dimensions of the TAM model, by Davis) when applied to the intended use of software methods.
My intention is to check whether there are significant differences in the perceived ease of use reported by the subjects depending on whether Neuroticism is high or low with a t-test. My problem is where to establish the cut-off point for the high and low groups. Somewhere (and that's my problem, I do not remember in which article) I read that some researchers typically used the 27% top values and 27% lower values in order to define such groups (so that middle N values do not cloud such impact) but I am not sure if this is the right decision. The sample size (55) is rather low, and Pearson's correlation coefficient is not able to detect any meaningful relationship (nor was expected).
Can anybody help, please?
Comment: This seems to require expertise in psychology to answer well, but nothing in your title or tags is flagging that to attract attention from experts (not me). 27% seems utterly arbitrary as a cut-off. If you can't give a reference or an argument for that, it's hard to know what to say, except crucially why do you need to group here at all? If you have  measurements on some key variable, use it ungrouped as a predictor, even if there are some gaps in a sample.  Also, $N$ without explanation in  a statistical forum would usually be taken to be sample size, but I guess that you mean Neuroticism!
Comment: Thank you very much for the suggestions! I have edited the question to try to clarify it. The relationship between Neuroticism and Ease of Use is not linear, so Pearson's correlation coefficient does not work. My research question is rather whether people with high levels of Neuroticism find significantly more difficult to learn a new software development method.
Comment: It sounds as if you may  need to to use nonlinear transformations and/or a non-identity link. Your research question sounds malformed to me. If you identify what the relationship is, there may be a threshold although you shouldn't assume there to be one. Why not show your data: you have a small sample, so that's feasible?
Comment: Why not show the data to get better advice? If you think there is a threshold or stepped response, then Pearson correlation and how far the relationship is linear are irrelevant. I'd rather see the data and/or a scatter plot to judge.
Answer: Don't dichotomize the variable in the first place. It has many ordered values, so instead of splitting it into two groups and using a $t$-test, test the correlation between it and ease of use. You can use the Kendall correlation rather than the Pearson correlation to avoid issues regarding the nonlinearity of the neuroticism scale.


Is it safe to run Wireshark on a production IIS7 server? Is there a good alternative?

Question: We host a bunch of ASP.NET sites on an IIS7 server. Occasionally, we'd like to be able to log HTTP POST data to troubleshoot problems. IIS lets us log the query string, but not the POST data - at least, we haven't found a way.
Do you think it's safe to use Wireshark (or Netmon or another sniffer) on a production server? My gut feeling says "no" but I'd like to hear what others think.
It would be better to use port mirroring, and run the sniffer on a different box on the same switch. Unfortunately though, all the servers on that switch are production servers... so we'd have to affect one of them.
Thanks for your help,
Richard
Answer: Well over a decade later, disregard the original post from 2009 and consider that in 2020 Microsoft is referring people to use WireShark. Thanks to Justin in the comments below for the tip.

Microsoft Pro Support will often request that you install Netmon on a production server to help track down problems. If MSFT themselves want you to use a packet capture utility (in this case, Netmon) on a production server then that's a good indication that it's okay. (I suppose there's at least a few logical fallacies in that statement, but it sounded good to me. =) ) To my knowledge, there is nothing destabilizing about placing a packet capture utility on a production server.
Personally, I would use Netmon on a Windows server over Wireshark. The first reason is because in my experience Pro Support will not support Wireshark captures. The second reason is because... well... I like Netmon better, but that's subjective. =)
Comment: The question was whether there are any problems with having a network capture software on your production server... Choosing netmon over wireshare is purely subjective.  I use both and find that Microsoft can accept captures made from Wireshare just as easily as Netmon captures.
Comment: A few years later: Microsoft is now recommending Wireshark by name over Message Analyzer (which in turn was supposed to be successor to NetMon, I believe):
https://docs.microsoft.com/en-us/openspecs/blog/ms-winintbloglp/dd98b93c-0a75-4eb0-b92e-e760c502394f
Comment: +1 for NetMon. It happens to be my personal favorite as well.
Comment: Great minds... and all that implies. =)
Comment: Thanks - I'll definitely try it out. I'm used to Wireshark but I have to admit it has a pretty ugly UI :). And if MS says NetMon is safe for production use, I'll take their word for it...
Comment: Netmon rocks and if you really have to (for some odd reason) you can export the capture to wireshark (although I've not met anyone that's gone back to wireshark after using netmon)
Comment: I edited my post to rearrange my objective and subjective statements in a clearer fashion. Thanks.
Comment: @Justin Wow, blast from the past. Thanks for the tip. I updated the answer.
Answer: IMHO, there's no inherent risk or harm in running a packet capture program on a production server. In many cases, the problem is such that you need to run it on the "source" server to determine the cause of the problem.
Answer: If you consider staff running sniffs a risk - security, performance or outside their skill level you have a greater problem.
You WANT staff to know how to do things like this - it makes them think better and it raises the level of questions they bring to the table - unless of course you are afraid of job security by having server folks be able to read SRC/DST data.
Answer: It sounds like you want something like SmartSniff .
Wireshark will do the job since it also uses WinPcap, but I think Smart Sniff is a lot simpler and easier to use if your not doing advanced tracing.

(source: nirsoft.net)
Comment: I couldn't get anything that uses raw sockets to work on Server 2008. Does smartsniff use raw sockets? Have you used it on Server 08?
Comment: SmartSniff looks interesting - I'll check it out.
Comment: I'm almost certain I tried SmartSniff on a SBS 2008 machine and it wouldn't work for the above reason.
Comment: afaik, SmartSniff can use raw sockets, winpcap, or the microsoft monitor driver so you might as well use wireshark or netmon.
Comment: raw sockets is not required by SmartSniff.  it will also work with WinPCap.
Comment: SmartSniff uses WinPCap so, most likely, it will work.  Wireshark will work but its not required because you aren't looking for high detail.
Answer: Our environment prevents network capture solutions on production servers for the primary reason that you don't want it to be overly easy for tier'd admins to perform network captures.
The actual files necessary to run WireShark and/or NetMon don't themselves present much of a risk, rather the ability of admins to perform captures can be considered a risk.


Minesweeper mine generation algorithm

Question: I am making a minesweeper clone. My current algorithm for mine generation is just: pick a coordinate, if it has no mine, place a mine, else try again. I think this is not an efficient algorithm, especially in high density minefields. I am looking at some other options like: Fisher-Yates shuffle and the likes, but I think it has a long running time for much larger grids. I am thinking of using Linked Lists. Any suggestions?
Comment: put all possible locations in a list. shuffle the list and put bombs in the first x locations.
Comment: Just use the Fisher-Yates shuffle to randomize the indices and then pick the number of mines from 0 to that number
Comment: ohh. thanks! I will try those. But are there any other solutions that can reduce unnecessary work? For example, do I really need to shuffle the WHOLE list? Anyways, I think I'll stick with shuffling, it's simpler and more manageable
Comment: @userx01 you don't need to shuffle the whole list, you just need to pick a random index.
Answer: If you have a list/array where you can get size of list in constant time you may give a try to following:
<code>list = List of all fields
N = number of mines
N.times do
  index = random(list.size)
  pick list[index]
  list.remove(index)
end
</code>
This way:

you don't need to shuffle whole list
you avoid picking up same fields 2 times

In short it will be just drawing random field from list and removing it from list to avoid collision on next draw.
Comment: Yes! That's what I'm looking for. Great help, thanks! Btw, can this be achieved using only arrays? (for languages without data structures)
Comment: I think what you are searching for is rather Vector than list. By default pure list data structure has no constant time size() method and remove() method.
Comment: Let's say I have a 2d array for the minefield. Then I will make another list then pick X indices, right? So at the very least I'm copying the whole array?

Minesweeper mine generation algorithm


How to pick constants for Big Theta Notation.

Question: I'm having a problem solving these and understanding big theta notation in general.

i.) Show that if $a(n) = 5n^3 - 97n^2 + 6n - 3$, then $a(n) = \Theta\left(n^3\right)$.
ii.) Suppose that $a(n)$, $b(n)$, $c(n)$, $d(n)$ are positive sequences with $a(n) = \Theta\left(b(n)\right)$ and $c(n) = \Theta\left(d(n)\right)$. Show that if $b(n) \leq d(n)$ holds for all $n$, then $a(n) + c(n) = \Theta\left(d(n)\right)$.

For the first one, I was trying to find the best possible values for $c_1$ and $c_2$ but it always goes out of the rules as $n$ starts growing. For the second I guess I just really don't know where to start from. Any explanation or hint would be helpful really.
Comment: The "best" possible values for $c_1, c_2$ is really going to depend on what you mean by best. There is some $N$ such that for all $n>N$
$$4.999 n^3 \le a(n) \le 5.001n^3 $$ and these constants can get closer and closer to $5$ as we let $N$ get bigger.
Comment: Yes, I'm sorry my bad. I fixed it.
Comment: Does your text offer a rigorous definition of big theta?
Answer: Hint:

$f(n)\in\Theta\left(g(n)\right)$ if $$0 < \lim_{n\to\infty}\frac{f(n)}{g(n)} <\infty$$

Let $f(n) = 5n^3 - 97n^2 + 6n - 3$, and $g(n) = n^3$. Can you find $\displaystyle\lim_{n\to\infty}\frac{f(n)}{g(n)}$?


KIVY : Image + Label inside dynamic buttons

Question: I want to show Image+label inside dynamic buttons that created in a for loop. The problem is its showing the image+label layout only in the last button. How do I can display it in all buttons?
 main.py
class HomeScreen(Screen):
    grid_l = ObjectProperty(None)
    top_lbl = ObjectProperty(None)

    def search_btn_pressed(self):
        grid = self.grid_l
        grid.bind(minimum_height=grid.setter('height'),
                     minimum_width=grid.setter('width'))

        for i in range(3):
                layout = GridLayout(cols=1)
                print layout
                img = Image(source='kivy.png')
                print img
                lbl = Label(text='label')
                layout.add_widget(img)
                layout.add_widget(lbl)

                btn1 = Button(size_hint=(1, None))
                btn1.text = '%r' % i
                btn1.add_widget(layout)

                grid.add_widget(btn1)

 .kv
#:kivy 1.7.2

<HomeScreen>:
    scroll_view: scrollviewID
    top_lbl: lblID
    grid_l: gridlayoutID
    AnchorLayout:
        size_hint: 1, .1
        pos_hint: {'x': 0, 'y': .9}
        anchor_x: 'center'
        anchor_y: 'center'
        Label:
            id: lblID
            text: 'Button Tester'
    Button:
        size_hint: 1, .1
        pos_hint: {'x': 0, 'y': .8}
        text: 'Press me!'
        on_release: root.search_btn_pressed()
    ScrollView:
        id: scrollviewID
        orientation: 'vertical'
        pos_hint: {'x': 0, 'y': 0}
        size_hint: 1, .8
        bar_width: '8dp'
        GridLayout:
            id: gridlayoutID
            cols: 1
            size_hint: 1, None
            row_default_height: 40
            row_force_default: False

Answer: It's actually not displaying only for the last button - it's displaying for each button, but in the same position. The problem is that Button is not a layout, and as such, does not perform layout of its children. So the GridLayout for each button is rendered at 0, 0 with size 100, 100 relative to the origin of the nearest relative parent (in this case, the GridLayout grid_l because it is contained by the ScrollView).
When you add widgets to a non-layout widget, it's up to you to layout those widgets by setting position and size. Note that you must set the actual pos (or x and y) and size (or width and height) - you cannot use pos_hint or size_hint, as those are only handled by layouts.
This can be done easily using dynamic classes in kv language:
<CustomButton@Button>:
    image_source: ''
    subtext: ''
    GridLayout:
        height: self.parent.height  # match the button's height
        width: 100                  # set to whatever you would like
        pos: self.parent.pos        # match the button's position
        cols: 1
        Image:
            source: root.image_source
        Label:
            text: root.subtext

To use your dynamic class, you will need to import Factory:
from kivy.factory import Factory

Then, in your loop:
for i in range(3):
    btn = Factory.CustomButton(text=str(i), size_hint=(1, None),
                               image_source='kivy.png', subtext='label')
    grid.add_widget(btn)

Finally, a side note: you're creating new bindings on grid_l every time search_btn_pressed() is called. These bindings should only be created once. You could bind once in Python by moving those bindings to HomeScreen.__init__(), but again, this is easier in kv:
    GridLayout:
        id: gridlayoutID
        cols: 1
        size_hint: 1, None
        row_default_height: 40
        row_force_default: False
        height: self.minimum_height   # bind height to minimum_height
        width: self.minimum_width     # bind width to minimum_width


Meta-analysis of RR and OR calculated from 2x2 tables in R using metafor

Question: Background
My question concerns the calculation of risk ratios and odds ratios for meta-analysis using the metafor package. I know it looks long, but please bear with me, as it is a simple question. I've simply provided a lot of background information. First, copy/paste the below to make my example data.
# Load package
library(metafor)

# Create example_data
example_data <-
data.frame(
trial = c(1, 2, 3, 4, 5, 6),
author = c("Abers", "Baker", "Cook", "Dodds", "Eggers", "Fritz"),
year = c(2000, 2001, 2002, 2003, 2004, 2005),
tpos = c(437, NA, 51, 26, 468, 10),
tneg = c(49, NA, 1, 8, 83, 1),
cpos = c(50, 7, 6, 0, 36, 0),
cneg = c(33, 8, 0, 0, 19, 0)
)

# Show example_data
example_data
  trial author year tpos tneg cpos cneg
1     1  Abers 2000  437   49   50   33
2     2  Baker 2001   NA   NA    7    8
3     3   Cook 2002   51    1    6    0
4     4  Dodds 2003   26    8    0    0
5     5 Eggers 2004  468   83   36   19
6     6  Fritz 2005   10    1    0    0

More background
If I were to make a two-by-two table by hand for the first study, Abers, it would look as follows:
      pos  neg
 pos  437   49
 neg  50    33

The relative risk would be calculated by hand as follows:
RR = (437/(437 + 49)) / (50/(50 + 33)) = 1.49
log(RR) = 0.40

The odds ratio would be calculated by hand as follows:
OR = (437 * 33) / (50 * 49) = 5.89
log(OR) = 1.77

Here are the forest plots for log(RR) and log(OR). If you look at the first line in each plot, you can see that metafor produces the same values as I did by hand for the Abers study.

My question
Take a look at the line for Dodds on the plots. Where are these values for log(RR) and log(OR) coming from? As I see it, if I were to make a two-by-two table for the Dodds, it would look as follows:
      pos  neg
 pos   26    8
 neg    0    0

The relative risk would be calculated by hand as follows:
RR = (26/(26 + 8)) / (0/(0 + 0)) = Undefined! As you cannot divide by zero.
log(RR) = ?

The odds ratio would be calculated by hand as follows:
OR = (26 * 0) / (0 * 8) = Again, undefined!
log(OR) = ?

So how did the metafor package calculate a log(RR) of 0.41 and a log(OR) of 1.14 for the Dodds study? And more generally, for all of my studies with zero values (e.g., Cook, Dodds, and Fritz), can I even include any of them in my meta-analysis?
Answer: Quoting from the documentation (help(escalc)):

Cell entries with a zero count can be problematic, especially for the relative risk and the odds ratio. Adding a small constant to the cells of the 2x2 tables is a common solution to this problem. When to="only0" (the default), the value of add (the default is 1/2) is added to each cell of those 2x2 tables with at least one cell equal to 0. When to="all", the value of add is added to each cell of all 2x2 tables. When to="if0all", the value of add is added to each cell of all 2x2 tables, but only when there is at least one 2x2 table with a zero cell. Setting to="none" or add=0 has the same effect: No adjustment to the observed table frequencies is made. Depending on the outcome measure and the data, this may lead to division by zero inside of the function (when this occurs, the resulting value is recoded to NA). Also, studies where ai=ci=0 or bi=di=0 may be considered to be uninformative about the size of the effect and dropping such studies has sometimes been recommended (Higgins & Green, 2008). This can be done by setting drop00=TRUE. The counts for such studies will then be set to NA.

So, to make a long story short, escalc() added 1/2 to the cell counts before computing the log(RR) or the log(OR).
Comment: It's common practice to make this adjustment, so no, not necessarily. But I cannot give any more detailed recommendations without knowing much more about these data. And by the way, the two-by-two tables for Dodds and for Fritz are a bit strange, as both cells in the second row ('c' and 'd') are zeros. I suppose this could happen under multinominal (cross-sectional) sampling, but seems a bit odd for stratified sampling. Are these real data? And if yes, what are they supposed to reflect?
Comment: Then that sounds like cross-sectional sampling (both variables were simply observed). I would then suggest to only use the odds ratio as the outcome measure. And in that case, it would probably be okay to include those studies.
Comment: If you only want the visual reminder, you could also set ``to="none"``, but then use ``options(na.action="na.pass")`` before creating the forest plot. See [here](http://www.metafor-project.org/doku.php/tips:handling_missing_data) for further details.
Comment: Thanks @Wolfgang - Do you therefore think I should remove these studies from the meta-analysis/plot?
Comment: You are right, they are strange. They are from a case series report, and I know that it's illegal to include such a report in a meta-analysis so I don't plan to actually include them. These are surgical patients who either had (positive) or did not have (negative) an attribute noted during the surgery, and then their post-operative course was either complicated (positive) or non-complicated (negative). Another question - do you think it would be better to report the RR or the OR analysis for these data?
Comment: Ok, interesting. So you are saying that I could include the `to="only0"` and then plot all five studies? (I realize that the Cook, Dodds, and Fritz studies would contribute basically nothing to the effects estimate, but at least I could include them on the plot just as a visual reminder that the studies exist and did not contribute anything). Thanks a ton, I appreciate your advice


Hosting Nginx and Apache on same system with 2 IP

Question: My server holds two IP 192.168.1.90 and 192.168.1.99
I want nginx to listen on 192.168.1.99  and Apache on 192.168.1.90
I also need to host multiple virtual hosts on apache.
tried modifying ports.conf of apache to
NameVirtualHost 192.168.1.90:80
Listen 80

<IfModule mod_ssl.c>
    # If you add NameVirtualHost *:443 here, you will also have to change
    # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
    # to <VirtualHost *:443>
    # Server Name Indication for SSL named virtual hosts is currently not
    # supported by MSIE on Windows XP.
    Listen 443
</IfModule>

<IfModule mod_gnutls.c>
    Listen 443
</IfModule>

And then I hosted a Virtual host in apache
<VirtualHost 192.168.1.90:80>
DocumentRoot /home/webmaster/www/thefactor/
ServerName www.XYZ.com
ServerAlias XYZ.cu.com

# Other directives here

</VirtualHost>

The problem is all the traffic, all request that comes to 192.168.1.90 irrespective of the domain name loads XYZ.com. ie: If i point ABC.com to 192.168.1.90 then when I browse to it, It loads XYZ.com page but the address in the address bar will remain ABC.com, so it is not a redirect.
Any Idea why this is happening
Answer: You need to narrow the Listen directives to 192.168.1.90, like
Listen 192.168.1.90:80
  Listen 192.168.1.90:443
otherwise Apache will listen on all IP's (and incoming requests hit the default virtualhost).
Answer: The first virtual host you define will be the "default" host. Thus all requests for domains not configured elsewhere will go to this first host.
If you want requests for domains not configured on a server, but directed to it anyway to be ignored you need to create a separate, "catch all" dummy virtualhost that does just refuses all requests, and that is listed before the othosts.
<VirtualHost 192.168.1.90:80>
    #Dummy Host denies all accesses.
    Order Allow, Deny
    Deny from all
</VirtualHost>

<VirtualHost 192.168.1.90:80>
    DocumentRoot /home/webmaster/www/thefactor/
    ServerName www.XYZ.com
    ServerAlias XYZ.cu.com

    # Other directives here
</VirtualHost>


How to get HTTP status errors from cURL 8.0?

Question: When testing some REST API, I'm using a cURL command.
However when the request failed, it seems that cURL does not indicate that there was a non-success status code (HTTP/2 405 in my case); instead I just see the response (which is a JSON "messages" array).
As it would require "quite a lot of AI" to deduce from the contents of the message array that there was an error, I wonder how I can reliably detect the non-success status code when using cURL.
Maybe it could even be a bug in cURL (regarding use of HTTP/2).
Example session (I deliberately mad a request error to demonstrate):
> curl -u monitor  'https://redacted.server.name/api/status/get-token'
Enter host password for user 'monitor':

{
  "messages": [
    "The global command get-token requires to use PUT"
  ]
}
> echo $?
0

Comment: Dupe https://stackoverflow.com/questions/38906626/curl-to-return-http-status-code-along-with-the-response/
Comment: add `--verbose` to your command line.
Comment: The question was not "how to *see*", but "how to *get*", meaning how to test using a program. If I would have to "grep" the headers, wouldn't that make cURL rather useless? Finally how do you think I found out that there's a "HTTP/2 405" status? ;-)
Comment: Then I suggest you rephrase your question. CURL returns `string` output and not `boolean` or `int`, you need to parse its returned content for that. CURL is not really made for testing purposes in that way that your phrasing.
Comment: @Anuga As the HTTP status codes are well-defined, cURL *could* map them to exit status. HTTP does not require to send any more error details along with the status code, so relying on the response data only may be unreliable. For real use I won't use cURL or BASH.
Comment: Does this answer your question? [Curl to return http status code along with the response](https://stackoverflow.com/questions/38906626/curl-to-return-http-status-code-along-with-the-response)
Answer: curl --write-out '\nresponse_code=%{response_code}\n' 'https://redacted.server.name/api/status/get-token'

should end with
response_code=405

if you need it in a variable i suppose you could do
RESPONSE=$(curl --write-out '\n%{response_code}' 'https://redacted.server.name/api/status/get-token')
RESPONSE_CODE=$(tail -1 <<<$RESPONSE)
RESPONSE=$(echo "$RESPONSE" | head --lines=-1)

now echo "$RESPONSE_CODE" should give you 405 and echo "$RESPONSE" should give you the original http response body...
Btw seems you're approaching the complexity where using bash no longer makes sense, maybe try switching to a better scripting language like PHP, Python, or Perl? They all have good libcurl bindings.
Comment: HTTP body doesn't have to end with NL, and for JSON it often doesn't; safer to force \n _before_ RESPONSE_CODE as well. And can just write `\n%{response_code}\n` then do `RESPONSE_CODE=$(tail -1 <<<$RESPONSE)` instead of eval. Or use no newlines and take 3 _chars_: https://stackoverflow.com/questions/54038132/obtain-status-code-and-response-body-from-curl-request
Comment: @dave_thompson_085 seems curl hardcodes a newline between the HTTP Body and `--write-out` - great idea to use `RESPONSE_CODE=$(tail -1 <<<$RESPONSE)` tho
Comment: I agree that cURL with BASH has limits, but quite a lot of REST API docs refer to using cURL, and just to verify the principle, I used cURL and BASH. Once it's at parsing or creating JSON, it's better to leave BASH, however.
Comment: It doesn't add newline for me; please try [this test server I set up temporarily on AWS](http://18.104.22.168) (either approach, but especially yours)
Comment: @dave_thompson_085 dang you're right, it doesn't add a newline, and the code is vulnerable. thanks for pointing it out, code updated.
Comment: Actually I implemented a similar solution, however there are some pitfalls: First when using a proxy that returned a "503", I just got an empty response, so I needed an error code. First surprise was that `%{http_code` showed as `000`, so I had to examine `%{http_connect}` (that was `503`), too. And for completeness I wanted to capture `%{errormsg}` too.
Comment: @U.Windl neat. if you're feeling charitable, maybe post your solution as an answer here? might help someone else ^^
Comment: @hanshenrik See https://stackoverflow.com/a/76990503/6607497
Answer: As the response is JSON, I decided to format the extra status codes JSON-like, too (based on the suggestion in https://stackoverflow.com/a/76943672/6607497).
I use these extra options to curl:
-w \
'"_conn%{urlnum}": %{http_connect}\n'\
'"_code%{urlnum}": %{http_code}\n'\
'"_emsg%{urlnum}": "%{errormsg}"\n'

With curl's response in RESP I transform the result (all JSON values are assumed to be either numbers or strings on a single line). FILE is some temporary filename:
sed -n -e 's/^ *"\([^"]\+\)": *"\?\([^"]\+\)"\?,\?$/\1=\2/p' > "$FILE"

To lookup values I added this helper:
get_info()
{
    sed -n -e 's/^'"$1"'=\(.\+\)$/\1/p' "$FILE"
}

So finally the code to check the result (with a squid proxy present) looks like this:
STATUS=$(get_info _code0)
[ -z "$STATUS" -o "$STATUS" = 000 ] && STATUS=$(get_info _conn0)
if [ "$STATUS" = 200 ]; then
    # success...
    rm "$FILE"
else
    EMSG=$(get_info _emsg0)
    [ -n "$EMSG" ] && STATUS="$STATUS $EMSG"
    emsg "$0: failed with status \"$STATUS\":"
    emsg "$RESP"  # show the complete response for debugging purposes
    rm "$FILE"
fi

emsg just writes to STDERR:
emsg()
{
    echo "$@" >&2
}


Compute rolling skewness and kurtosis in sas quickly for a very large data set

Question: I have the following code to compute the skewness on a rolling window of returns:
<code>libname backup 'C:\Users\Anwender\Desktop\backup sas data';

data crsp_daily;
set backup.crsp_daily;
run;

proc sort data=crsp_daily;
by permno date;
run;

data crsp_daily1a;
set crsp_daily;
lastofmonth = last.month;
by permno year month;
run;

proc sql;
create table roll_ret as
select h2.permno, h2.Date, h1.retadj as lagret
from crsp_daily1a as h1,
crsp_daily1a as h2
where h1.permno = h2.permno
and intck("MONTH",h1.date,h2.date) between 0 and 11
group by h2.permno, h2.date
having count(h2.permno)>250 and h2.lastofmonth = 1
;

quit;

proc means data = roll_ret noprint;
by permno date;
var lagret;
output out=crsp_daily_final skew=skewRet kurt=KurtRet;
run;
</code>
The input data set has a daily date variable, from which I have already constructed a year and month variable. It also has an ID for the stock (permno) and daily returns (retadj).I want to compute rolling skewness from all observations from the last year, but only if there are at least 250 observations in this window. I am only interested in results for the last of the month.
The Input data set has more than 60 million!!! observations, the above code is simply too slow. I have already tried to work with a view instead of an data set for roll_view without improvement.
How can I quickly compute a rolling skewness in the above sense for this very large data set?
General comments on my code would be appreciated as well.
Thanks very much!
Comment: Have you tried to profile the code?
Comment: How would that work? Could this provide a solution how to speed things up? The main challenge comes from the proc sql, which creates a huge data set, is there a way around this step?
Comment: Simple profiling in SAS can be done using options fullstimer and examining the log (SAS also provides the script to extract this info http://support.sas.com/rnd/scalability/tools/fullstim/). I see, you already know the bottleneck :), will post some suggestion on optimization in an answer.
Answer: PROC SQL performs heuristic analysis of the potential join strategies, you can review it by using proc sql _method option. Potential user optimization strategies are outlined here (http://support.sas.com/techsup/technote/ts553.html). Probably, your case falls into the category of join of a small (h2) and large (h1) datasets - creating an index on the key usually helps in this case.
Comment: Thank you for this advice, so you would suggest creating an index on permno in both data sets? Would running the following code before the sql join do the job: proc sql; create unique index permno on crsp_daily1a; However, I am not really dealing with ohne small and one large data set, actually they are the same, thus having the same size. Would this still be a reasonable step?
Comment: @Kostya, there is some great stuff at that link that was new to me.  Thanks!
Comment: @user3575894 Apologies, couldn't come back earlier. Unfortunately, optimization depends on the structure of your data. But the main idea is simple: reduce the sizes of the datasets before forming the cartesian product. Maybe, if you can post a log of proc sql _method, we can suggest something more specific
Comment: Sorry for coming back late. Creating an index did not speed things up significantly. The following code works very well, but as mentioned before, speeding things up here might be data set specific. What helped in my case was to use a view instead of a data set and temporary arrays.
Comment: Here is the code I am now using:

data rwin /view=rwin;
array _Y {250} _temporary_ ;
set crsp_daily1;
by permno;
retain N 0;
N = ifn(first.permno,1,N+1);
I = mod(N-1,250)+1;
_Y{I} = retadj;
if (N >= 250 and lastofmonth) then do I = 1 to 250;
lagret = _Y{I};
output;
end;
run;

proc means data = rwin noprint;
by permno date;
var lagret;
output out=crsp_daily_skew_kurt skew=skewRet kurt=KurtRet;
run;


Commerce and Attribute Quantities

Question: Our Goal
We're creating a book product. It comes in a variety of sizes (ex. 5x5, 8x8, 10x10) with 20 pages included. We're using the size as an attribute field. Customers can order a standard book, or add additional pages up to 100 total pages. Additional pages are priced /page and /size; for example 5x5 = $1.00/page, 8x8 = $1.50/page etc. The "Add to Cart" section should look something like this:
===========================
BOOK

Size [5x5]
Pages [ enter amount ]

Total: $75.00
[Add to Cart]
===========================
The simplest solution would be to add a pricing option with its own quantity field, except that functionality doesn't seem to be available.
I've considered the following:

Commerce Option I: Creating a pricing attributes option (select list or radio button styles as a slider). The only caveat is the admin on adjusting pricing for 4000 options (50 books with 80 page options each) is a usability nightmare.
Commerce Option II: Creating a pricing attributes integer field (acting as a quantity field) and using Rules to do the math and adjust the pricing. Unfortunately the variables and math did not seem to be available to Rules.
Commerce Product Bundle: Creating a pages product variation and using page size as an attribute field. That would allow us to leverage the quantity field in the bundle's add to cart display. The problem in this case is two fold:

Having to create 3 product variations, then having to create at least 2 products (book and book/pages bundle; 3 if you have different papers or page pricing needs to vary) each time you add a new book to your collection. This very quickly creates something close to an administrative hell for the shop owner.
Commerce Product Bundle is still in Alpha, and has been for 2 years. No commits have been made in over a year. The module, even though it often works well, is buggy and doesn't play well with Commerce Option; which we leverage quite substantially.

Custom Line Item: Using Randy Fay's "custom line item custom discount technique" leveraging an integer field and rules. I added an integer field to the product variation for cost per page. Then created an integer field which needed to be exposed to the customer. Using the combination of both I attempted to create a rule which calculated the additional price based on the product of the those fields. It does not appear that this is possible using Rules.

Conclusion, and request for additional brain power
I've gone around multiple circles trying to figure this one out and am about to go completely bonkers. Perhaps I'm missing something completely simple, or I'm approaching this problem from the wrong angle. Has anyone been able to do something similar? How did you achieve it?
Answer: Commerce by default supports line item fields that can appear on the Add to Cart form. If you only sell this one type of product on the site and will always need that "additional pages" field, then you could just add the field to the default product line item type. If you have other needs, you'd use a custom line item type either defined in code or created via https://drupal.org/project/commerce_custom_product.
Once you have customers putting in their custom number of pages, it's up to you to adjust the price accordingly. Pricing rules receive the full line item object for price manipulation, including the values of any line item fields present on the Add to Cart form. You can construct a variety of rules that look at the referenced product to determine how much to charge for additional pages and work it out using the Rules actions to create data values.
Comment: Thanks Ryan. I attempted this using commerce_custom_product by adding quantity field to a custom line-item and a price field to the product variation type. Unfortunately when using a pricing rule I was only able to access the field in the line item, but could find no way of getting the field on the product variation to load.

"You can construct a variety of rules that look at the referenced product..." This was the part I couldn't get to work. Looking at Randy Fay's tutorials as well as itangelo's series on rules I still couldn't figure out how to expose those fields.
Comment: Is it because you haven't used the "Entity has field" condition yet to tell Rules the field existed on the entity?

Commerce and Attribute Quantities


How to make a class to be clicked when new page load?

Question: I have a class name "searchIcon", and i wrote a click function to that class.
In HTML

Icon

In Js file
  $(".searchIcon").click(function(){
   //class function
  });

I want this function should be clicked at time of page load.
maximum i need it in jquery
Answer: You could call .click() or .trigger('click') right after you bind the event.
$(function() {
    $(".searchIcon").click(function(){
        //class funstion
    }).click();
});

Answer: You can use JQuery trigger in document.ready function :-

$(".searchIcon").trigger('click');

$(function() {
    $(".searchIcon").click(function(){

    });
    $(".searchIcon").trigger('click');
});

Answer: You can have the click handler directly call a function and then on page load call that same function (jsFiddle example):
$(".searchIcon").click(function(){
   //class function
    clickFunction();
});

var clickFunction = function(){
      alert("clicked!");
};

clickFunction();

Answer: Your code requires a click trigger at page load:
$(function(){ // ready handler
    $(".searchIcon").click(function(){
       //class function
    });
    $(".searchIcon").click(); // this fires when doc gets ready
});


Body Class, Drupal 7, change language name programmatically

Question: I am trying to add a the language being displayed in the html body class. Drupal 7 for example, when i open firebug  it displays the body class  with these values
body class=html not-front logged-in no-sidebars page-node page-node- page-node-187 node-type-page toolbar toolbar-drawer i18n-el show-grid no-rgba
Is it possibe to add the language as lang-el instead of il8n-el?
Which file is it responsible for outputting these values?
Answer: <code>sites/all/modules/i18n/i18n.module

Line:267:  $variables['classes_array'][] = 'i18n-' . $language->language;
</code>
You can create your own small module mysmallmodule.module and put this in it:
<code>/**
 * Implements hook_preprocess_html().
 */
function mysmallmodule_preprocess_html(&$variables) {
  global $language;
  $variables['classes_array'][] = 'lang-' . $language->language;
}
</code>
Which wont get rid of the i18n class but will just add your own version :)
EDIT: Step by step to create a small custom module.

Create a new folder in the sites/all/modules folder called custom, in here you can keep any custom modules you may need.
Create another folder in the custom folder and call it something suitable like customclasses.
In the customclasses folder create two files, customclasses.module and customclasses.info.
In the customclasses.module file paste the code above but call it "function customclasses_preprocess_html" instead of "mysmallmodule".
In the customclasses.info file paste
name = Custom Classes
package = Custom Stuff
description = Custom class to get "lang-" in the body class.
core = 7.x
Finally, go to the modules page and enable your first custom module.
Comment: :) thank you so much for your quick reply. I just changed this line from Line:267:  $variables['classes_array'][] = 'i18n-' . $language->language;  to Line:267:  $variables['classes_array'][] = 'lang-' . $language->language;  and it worked. :)
Comment: Noooo, dont do that! But seriously, dont. Its really bad practice to mess with modules, and you will regret it in the future when you update that module. I will update my answer with what you need to do exactly to get the exact same effect and it will only take you 2 more minutes. Plus, if you think my answer is the right answer, you should click to accept that its the right answer.
Comment: ok you are right. This is bad practice. I have changed it back to il8n- and created the module as your edited comment. But insted of having the body class tag lang-en i have the code from inside my customclasses.module appeared on my screen along with the comment which is weird.
Comment: 0 down vote accept

Is working thank you very much for your help:) Ignore my last comment. Forgot to add the tags. Thank you once again.


How to create formula to calculate sum depend on group condition in crystal report

Question: I have crystal report that group by ticket type, journey type and process.
In group process I have type:

ticket sales
ticket cancel

Total for each group I can do it by insert summary.
But then, at the last grand total (net sales) I want only sum of ticket sales, excluded ticket cancel..so how to do that..?
my formula is:
<code>If ({Command.process})= "0") Then
(
    Sum ({Command.quantity}, {Command.process})
)
</code>
0 = ticket sales
2 = ticket cancel
Comment: according to me you should get canceled tickets in a separate field and just subtract it with the total sum of qty
Comment: ok..can you explain separate field? i bind crystal report with query.so my query has to select ticket sales and ticket cancel together as crystal report dont support 2 dataset.
Comment: what is the problem with formula?
Answer: Use running total fields:

create running total fields
give it a name
field to summarize: anyone, may be an id
type of summary: count
evaluate for each record
reset : use a formula  {Command.process})= "0"

This will count all the tickets of process "sales". The trick is the step 6 that says to count only when that is the process.


Problemas no SVN

Question: alguem ja passou por esse problema no svn
Uso o SVN no linux e o Tortoise no windows 10.
Commit falhou (detalhes a seguir):
<code>Não é possível mover 'J:\familia4\4r_sis\.svn\tmp\svn-4A465EB1' para
 'J:\familia4\4r_sis\.svn\pristine\2a\2a59232ae65ddb932d4109a4682d7cdfd933c6da.svn-base':
Acesso negado.
</code>
Comment: Algo que acontece em alguns programas no Windows é receber um erro de "Acesso negado" por não estar executando o mesmo como Administrador. Você pode se certificar que está fazendo isso?
Answer:
Pressione e segure ou clique com o botão direito do mouse na pasta
"J:\familia4" e clique em Propriedades.
Clique na aba Segurança.
Na aba Nomes de grupo ou de usuário, selecione seu usuário
para ver suas permissões, se caso não tiver altere e dê permissão.
Comment: Obrigado deu certo .

Problemas no SVN


Why is Eb to A# not a perfect 5th?

Question: I read a mock question that asked if Eb to A# was a perfect 5th.
I counted up 7 semitones, and concluded it was.
The answer says that it's not, but not why.
Is it simply because the enharmonic equivalent Bb should have been used, as that's in the Eb scale?
I find it an odd one if so, because if played you'd identify it as a perfect fifth.
Comment: Anyway - it makes sense to ask this question to test if a student has understood the theory of intervals and the principle of labeling them.
Comment: @AlbrechtHügli - asking the question as it was in the exam makes little sense. See my answer.
Comment: Did this "mock question" also mention a piece where this double augmented 4th appears? I know  Mikrokosmos Nr. by Bartok where he notates an augmented 3rd (that sounds like a 4th) but in context it makes sense to write it as a  >3rd. While I would be interested to see a progression of chords or voices where this double augmented 4th would make sense.
Comment: No it didn't have any context - it was simply a list of intervals I had to say were perfects fifths or not.
Answer: 'If played, you'd identify it as a perfect fifth'. Maybe, maybe not.
The sound of any interval is only half the story. Every interval has at least two different names but only one sound.
The other half of the story is what actual notes are being played. Their names, and where they live on the stave.
E♭ > A♯. Any E>A is going to be a 4th - of some sort. E-F-G-A - 4 letter names. Now, let's do some juggling. E♭ > A♭ is a P4. Count up the scale notes if you like, or state that P4 uses 5 semitones.
Keep the bottom note of E♭, but take that A♭ up to A ♮. Now the interval is an augmented 4th. Going up by another semitone to A♯ makes it a double augmented 4th.
Not a common interval at all, but an interval nevertheless! If intervals were recognisable purely by their sound, it would be a lot easier. But the problem then is how would we write them. Half the time (or more!) they'd be technically wrong, meaning a lot of the time they'd be harder to read. I understand that some would say that doesn't matter, but isn't it better to get things right? Like in key E, there's rarely a D♭m chord - should be C♯m...
And, as a question, that mock is flawed. 50:50 chance of getting it right. Doesn't reveal much. Better, perhaps, to ask why that isn't a P5..? Like you did?
Comment: Thank you - I was not familiar with double augmentation. In one way it's a bit easier than I expected. The question was presented as written on a stave - just counting there were four steps would immediately tell me it was not a fifth - regardless of key or the number of semitones.
Comment: Yes, but just *hearing* those two notes, most folk would automatically say P5, I guess.
Comment: Not only the most people. Everybody would. Or they wanted to give a mock answer ;)
Answer: Because it wasn't spell it with a Bb.
E to A is a fourth of some type. Lower the E with a flat and it becomes an augmented fourth. Add the sharp to the A and it is augmented (made larger by a half step) again and so it's called double augmented, a double augmented fourth.

...Is it simply because the enharmonic equivalent Bb should have been used, as that's in the Eb scale?

Which is it? Eb and A#or Eb and Bb?
Yes, they are enharmonically equal, but the whole point of asking about Eb and A# is to see if someone understands complex interval spelling in writting notation.

...I counted up 7 semitones...if played you'd identify it as a perfect fifth...

That's beside the point. The interval was spelled out with sharps and flats.
We need to take a step back and think about terminology.
Interval in the generic sense is just a distance of time or space, or some other measurable thing. If there are 7 steps between two things, it's just an interval of 7. (Not a musical seventh, I mean the distance is just 7 units, frets, piano keys, etc.) If the two things were frequencies you could describe the interval with a ratio like 3:2.
But, those are merely "physical" measurements. They are not musical notation.
7 half steps or 3:2 is not a perfect fifth. They are possibly a perfect fifth, double augmented fourth, diminished sixth, etc. You cannot use terms like perfect, augmented, diminished, etc. until the interval is notated or spelled with the letters and sharps and flats of notation.)
If someone played the two tones would they identify a perfect fifth? Yes. But that would be a kind of ear training test.
The question as asked is a test of notation reading.

Why is Eb to A# not a perfect 5th?


How to create nodes from shell script at server?

Question: I need to create nodes from shell script at my server (some server statistics).
As I know drush cannot add new node. (It was a discovery for me)
So I think make shell script which will create CSV file with node fields and make periodical import by Feeds.
Is there more smart solution?
Answer: If you are going to start scripting on the command line, you can always script a php script and run it via drush. That way, you have access to your Drupal system and data. For example, if you place the following code in a file, e.g. script_create_node.php:
<?php

// Expect title as $args[1] and body as $args[2]
if( !isset($args[1]) || trim($args[1]) == '' || !isset($args[2]) || trim($args[2]) == '') {
  print "Expecting two arguments on the command line, title and body, for the new article\n";
  exit;
}

$node = new stdClass();  // Create a new node object
$node->type = 'article';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = $args[1];
$node->body[$node->language][0]['value'] = $args[2];

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;

// Save the node
node_save($node);

you can always call this on the terminal like this:
drush scr script_create_node.php "Article Title" "Article Body"

You can extend such a script to include the logic you would use in your shell script, but instead of writing to a CSV file, you can write directly to the database. It's a great advantage having both PHP-CLI and a bootstrapped Drupal available at the same time.
Hope this helps some!
P.S: Lots of pages out there answering the question "programmatically creating nodes", one random pick would be http://www.group42.ca/creating_and_updating_nodes_programmatically_in_drupal_7
Comment: So `Drush` can add nodes (and much more) with `drush scr`! Thanks. It will take some time to test before I accept answer.
Answer: There are a lot of right answers here; using feeds would work fine. You might also be interested to try Drush Entity Commands.
Comment: Drush Entitiy Commands are not regarded as save and D7 only
Answer: Don't forget drush genc if you have the devel module installed.  Old school but effective, creates fully populated nodes with randomly generated images etc.  (You can also use it to delete nodes as well: drush genc --kill --types=NODE_TYPE 0 0)
> drush genc --help
Create content.

Arguments:
 number_nodes                              Number of nodes to generate.
 maximum_comments                          Maximum number of comments to generate.

Options:
 --feedback                                An integer representing interval for insertion rate logging. Defaults to 1000
 --kill                                    Delete all content before generating new content.
 --languages                               A comma-separated list of language codes
 --skip-fields                             A comma delimited list of fields to omit when generating random values
 --types                                   A comma delimited list of content types to create. Defaults to page,article.


How do I see the kick drum on a sampled track in Reaper?

Question: I edit many drum-fiddle duo samples to make loops in REAPER. The fiddle moves ahead and behind the beat and syncopates. The drummer plays a simple 8-beat pattern. The samples are on a single mono recording, but if I could see where the kick is landing, I could make clean edits with less trial and error.
How can I isolate the kick drum frequencies and overlay them on the track?
Answer: These instructions are for Reaper on Windows

Right-click on track | Spectral Edits | Always show spectrogram
Peaks Display Settings:

Drag the top color bar to the left to emphasize the lowest frequencies
Adjust "freq log," "curve," "contrast," "bright, and bottom color bar by dragging left and right.

On the spectrogram below, the first of each series of green peaks show the leading edge of the kick drum hits.

Zoomed in, the leading edge of this particular kick drum is the purple rectangle on the bottom.

Use scrubbing to find the leading edge of the kick quickly.

Options | Preferences | Audio | Playback

Looped-segment mode: -300 ms to 0 ms

At the edit point,  Ctl-Alt-drag the edit cursor handle back and forth over where you hear the kick

You also just do this with the "Spectrogram + Peaks" setting if you don't need the visual boost of the spectral peaks.


Let $\omega=e^{i2\pi/2015}$, evaluate $\sum_{k=1}^{2014}\frac{1}{1+\omega^k+\omega^{2k}}$

Question:
Let $\omega=e^{i2\pi/2015}$, evaluate:
  $$S=\sum_{k=1}^{2014}\frac{1}{1+\omega^k+\omega^{2k}}$$

My Attempt:
Clearly, $1,\omega,\omega^2,\omega^3,...,\omega^{2014}$ are the $2015$th roots of unity.
Thus, $\omega^{2014}=\bar\omega$, $\omega^{2013}=\bar\omega^2$, and so on.
Note that
$$\dfrac{1}{1+\omega^k+\omega^{2k}}+\dfrac{1}{1+\bar\omega^k+\bar\omega^{2k}}=\dfrac{1}{1+\omega^k+\omega^{2k}}+\dfrac{\omega^{2k}}{1+\omega^k+\omega^{2k}}=\dfrac{1+\omega^{2k}}{1+\omega^k+\omega^{2k}}$$
hence
$$S=\sum_{k=1}^{1007}\frac{\omega^k+\omega^{-k}}{1+\omega^k+\omega^{-k}}=\sum_{k=1}^{1007}\frac{2\cos\left(\frac{2k\pi}{2015}\right)}{2\cos\left(\frac{2k\pi}{2015}\right)+1}$$
How to proceed from here. Appears to be standard trigonometric expression but I am not able to recall.
Answer: For simplicity I will write $n=2015$. Since $X^n-1=\prod\limits_{k=0}^{n-1}(X-\omega^k)$ we conclude that
$$\frac{nX^{n-1}}{X^n-1}=\sum_{k=0}^{n-1}\frac{1}{X-\omega^k}$$
Substituting $X=j=e^{2i\pi/3}$ and  $X= \overline{j}$ and then subtracting    we get
$$\frac{nj^{n-1}}{j^n-1}-\frac{n\bar{j}^{n-1}}{\bar{j}^n-1}=\sum_{k=0}^{n-1}\left(\frac{1}{j-\omega^k}-\frac{1}{\bar{j}-\omega^k}\right)=(\bar{j}-j)\sum_{k=0}^{n-1}\frac{1}{1+\omega^k+\omega^{2k}}
$$
Finally, since $n=2015\equiv 2\mod 3$ we see that $j^{n-1}=j$ and $j^n=j^2=\bar{j}$, we get
$$\frac{1}{-i\sqrt{3}}\left(\frac{nj}{j^2-1}-\frac{n\bar{j}}{j-1}\right)=\frac{1}{3}+\sum_{k=1}^{n-1}\frac{1}{1+\omega^k+\omega^{2k}}$$
The final step is easy and we get
$$\sum_{k=1}^{n-1}\frac{1}{1+\omega^k+\omega^{2k}}=\frac{2n-1}{3}=1343$$
This conclusion is valid for every $n$ which is equal to $2\pmod3$.


How deserialize the same JSON object but with diferent values into a java class

Question: i have the following scenario:
some times i get this JSON Object
{"id": 1, "cp": "male", "money": 10.0, "startDate": "07:00", "endDate": "10:00"}

and others this one
{"id":1, "cp": "male", "money": 10.0, "startDate": 21600, "endDate": 32400}

as you can se the JSON has the same fields but some times the startDate and endDate are in diferent formats
in seconds in the second case.
y have simple java Class
public class Person {

    private Integer id;

    private String cp;

    private Double money;

    @JsonDeserialize(converter = StringToLocalTimeConverter.class)
    private LocalTime startDate;

    @JsonDeserialize(converter = StringToLocalTimeConverter.class)
    private LocalTime startDate;

    //Getter-Setter

Converter
public class StringToLocalTimeConverter extends StdConverter<String, LocalTime> {

    static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_TIME;

    @Override
    public LocalTime convert(String value) {

        Long number = Long.parseLong(value);

        return LocalTime.MIN.plusSeconds(number);

    }

}

Obviously I'm getting a parse exception because I can't map both data values into the same LocalTime due to format.
Is it possible to map both JSON objects to the same Class? how can I workaround this or do I have to create separate Classes
what solution can be applied.
Answer: Well , you can simply try parsing it with DateTimeFormatter.ISO_LOCAL_TIME first. If it fails , then you parse it as a long :
public class StringToLocalTimeConverter extends StdConverter<String, LocalTime> {

    static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_TIME;

    @Override
    public LocalTime convert(String value) {
        try {
            return LocalTime.parse(value, DATE_FORMATTER);
        } catch (DateTimeParseException e) {}

        Long number = Long.parseLong(value);
        return LocalTime.MIN.plusSeconds(number);
    }

}

Comment: i will give this a try
Comment: Worked fine,i had a similar aproach but was missing the  try {}catch()