text:
Q: Await Task hangs if creating a new form instance before running the task My await code hangs if I run a create a new form instance before running the await code.
If I comment the line Form frm = new Form(); the code will be run properly otherwise it will hang in the code await Task.Delay(2000);.
Another solution is to create a new form instance using Task.Run(the commented line in my example code). I have no idea why it does work and doesn't know if that's fine to create a new form instance in a subthread.
Here is a simple example code to replicate the problem. Is there anyone have the idea why does this happen?
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleApp1
{
    class Program
    {
        public async static Task Main(string[] args)
        {
            //Form frm = await Task.Run( () => new Form());
            Form frm = new Form();
            await Delay();
        }

        public static async Task Delay()
        {
            await Task.Delay(2000);
        }
    }
}

Sorry for the confusion. Added the real code I am writing which is actually the unit test code.
    public async Task TestFrmLoginGen1()
    {
        IFrmLogin frmLogin;
        frmLogin = await Task.Run(() => new FrmLogin());
        //frmLogin = new FrmLogin();

        FrmLoginPresenter loginPresenter = new FrmLoginPresenter(frmLogin);
        await  loginPresenter.LoginAsync();
    }

A: The other answers saying that you shouldn't be creating forms inside a console app or a unit test are absolutely correct.
From your updated code, it looks like someone has already gone to the trouble of making sure you can unit-test your presenter without having to instantiate your form: the FrmLoginPresenter constructor takes an IFrmLogin, which I'm assuming is an interface implemented by FrmLogin. This abstraction exists to allow you to unit-test FrmLoginPresenter without having to create an actual FrmLogin.
What you want to do is to create a mock implementation of IFrmLogin. This might be a normal class which you write yourself which implements IFrmLogin (it might already exist in your test suite), or it might use a mocking library like Moq or Rhino Mocks.
Then you pass your mock implementation to the FrmLoginPresenter constructor.
Ultimately, it looks like whoever architected your application has already thought about how it should be unit-tested. You should probably go and speak to them to get the full picture on their intentions.

A: Your code is never calling Application.Run() to start the message loop of the application.
When you use await, the continuation may be posted to the message loop depending on the context. Once you create a form, you are in such a context and you have to make sure that the message loop actually runs.
The bit of initialization code of a WinForms application where Application.Run() is normally called is not a good place to use async/await.

A:
My await code hangs if I run a create a new form instance before running the await code.

Well there are a number of reasons for that.

*

*Your app is actually a console app and not a WinForms app.  You are attempting to show a GUI in a console app which typically isn't possible

*Console apps default to a MTA rather than STA.  STA is required for all apps running a GUI

*Console apps don't process the Windows Message Pump unlike say native windows or a WinForms app
Sure you can add a message pump to a console app; force a STA thread but why would you when there is a perfectly good WinForms wizard in Visual Studio?

I comment the line Form frm = new Form(); the code will be run properly

I really doubt that.  You might have a window appear but it certainly won't be interactive.  Unless the message pump is processed the window won't paint (including painting after a window, that was in front of it, is moved away).  Clicking buttons and menus will be unresponsive.  Timers will be inoperative.
Finally, don't attempt to create a GUI via a thread and/or Task as you will have little control over STA.  It all must be done from the application's primary thread which must be STA as mentioned.  There is little reason for multiple STAs.
In conclusion there is little point for using async/await during construction of a window.

A: I'm a bit late to the party, but I found myself running into the same problem (Although my use case was an app that can be run as a windowless process or a GUI). I'm going to leave my solution for the next poor soul who wanders here.
Doing HTTP Async operations seem to be a big culprit (Task.Delay didn't cause deadlocks/hangs for me). The following triggered the same behaviour as OP
static async Task Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    var fooForm = new Form1();
    fooForm.RunLoginTest().Wait();
    Application.Run(new Form1());
}
public async Task RunLoginTest() {
    var tokenClient = new TokenClient("https://dev1idsrv.biz/connect/" + "token", "----", "----");
    var tokenResponse = await tokenClient.RequestClientCredentialsAsync("cloud_api_gateway");
}

As stated by others, running async code before Application.Run causes issues. The next attempt was triggering the async code inside the Application.Run() by sticking it inside the constructor method.
public Form1()
{
    InitializeComponent();
    RunLoginTest().Wait();
}

As you'd expect the above also failed, evidently the form actually has to be created before Application.Run does its magic.
Accordingly, sticking the code in the form_load event was what ended up working
private async void MyForm_Load(object sender, EventArgs e)
{
    this.Opacity = 0; //to hide the form
    this.ShowInTaskbar = false; //to hide the form
    await MyAsyncMethod();
    Application.Exit();//or Form.Close() or neither, depending on your use case
}

For my use case I wanted the code to run but not have the form show up. Any attempt to set .visible gets overriden, so instead I've set it invisible through other methods. The above code block successfully runs the async code without triggering deadlocks


text:
Q: SharpDX load a texture in Windows Phone 8 I'm creating a Windows Phone 8 app and I'm using SharpDX to load a texture.
I've tried to load PNG using Content.Load<Texture2D>("filename.png") but I've got errors and I've realized that SharpDX in Windows Phone 8 only accepts DDS textures and doesn't accept PNG/JPEG/BMP etc. I've converted my PNG to DDS using texconv filename.png and added the file to my solution just like other files that I'm using in my project (that I can load correctly). When I run my app, I'm getting an exception:
{SharpDX.Serialization.InvalidChunkException: Unexpected chunk [DDS /0x20534444] instead of [TKFX/0x58464B54]
   at SharpDX.Serialization.BinarySerializer.BeginChunk(FourCC chunkId)}
Well, I've converted my valid PNG to DDS using the texconv tool. From what I see, it's a file format error, and the fourCC code corresponds to DDS, which is as it should be. But SharpDX expects TKFX format (toolkit effect?) instead of DDS. Why? I am trying to load a texture with Content.Load<Texture2D> not Content.Load<Effect> (I also have it to load a shader and it works perfectly).
If anyone finds out how to load a PNG instead of DDS, that's even better!

A: In case you still want to load PNG images, I'll just leave this code snippet here:
public static Texture2D FromImage(BitmapImage image, GraphicsDevice device)
{
    WriteableBitmap bitmap = new WriteableBitmap(image);

    return FromImageData(bitmap.Pixels, bitmap.PixelWidth,
                            bitmap.PixelHeight, device);
}

public static Texture2D FromImageData(int[] data, int width, int height, GraphicsDevice device)
{
    Texture2D texture = Texture2D.New(device, width, height,
                                    PixelFormat.B8G8R8A8.UNorm);

    texture.SetData<int>(data);

    return texture;
}

A: I've figured the problem out. I've switched the order of the lines of loading my texture and loading my shader. This time, the texture loaded correctly, and my shader failed with this error:
{SharpDX.Serialization.InvalidChunkException: Unexpected chunk [TKFX/0x58464B54] instead of [TKTX/0x58544B54]
   at SharpDX.Serialization.BinarySerializer.BeginChunk(FourCC chunkId)}
It was expecting TKTX (possibly, toolkit texture) but got TKFX which is a shader. I don't currently have a solution for this misbehavior of ContentManager, but it wasn't about the DDS file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use autolayout to horizontally and vertically center an input and a button I'm initializing a text input and save button in my ViewController, but it's not displaying the way I want it to, as seen in the screenshot below.
I'm trying to fix this by using autolayout as recommended here, but it's giving me an error

use of undeclared identifier cn

How do I properly declare an autolayout, and is this the correct way to center the input and _saveButton?
- (void)viewDidLoad {
    [super viewDidLoad];

    //Dem Input
    input = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
    input.textColor = [UIColor blackColor];
    input.font = [UIFont fontWithName:@"Times-New-Roman" size:25];
    input.backgroundColor=[UIColor whiteColor];
    [input setBorderStyle:UITextBorderStyleLine];
    input.placeholder=@"Type words here...";

    //The Button
    _saveButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
    _saveButton.frame = CGRectMake(0, 0, 100, 18);
    [_saveButton setTitle:@"Save" forState:UIControlStateNormal];
    [_saveButton addTarget:self action:@selector(saveButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:input];
    [self.view addSubview:_saveButton];

    cn = [NSLayoutConstraint constraintWithItem:self.view
                                      attribute:NSLayoutAttributeHeight
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute
                                     multiplier:1
                                       constant:200];
    [self.view addConstraint:cn];

    cn = [NSLayoutConstraint constraintWithItem:self.view
                                      attribute:NSLayoutAttributeWidth
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute
                                     multiplier:1
                                       constant:200];
    [self.view addConstraint: cn];

}

A: cn is NSLayoutConstraint
cn is used only in viewDidLoad() scope. So declare it in here.
- (void)viewDidLoad {
  [super viewDidLoad];

  NSLayoutConstraint cn;

  cn = [NSLayoutConstraint constraintWithItem:self.view
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:nil
                                  attribute:NSLayoutAttributeNotAnAttribute
                                 multiplier:1
                                   constant:200];


text:
Q: Why we need Event Handler if we already have Event Listener in JS? I am learning JavaScript I have a question while I studied to Event.
As I know we have two ways to handle an event, Event Handler and Event Listener.
I can only have one event handler for a specific event type, but I can add multiple event listeners for it.
It seems like event listener is better than handler, and why or when do we need the Event Handler ?


text:
Q: What is the difference between JavaFx Task and creating a new Thread with Task I have a General class which has static methods and static variables with Hibernate configuration settings and methods which return List after hitting the database. I am working on JavaFx and i recently learned its better to use Task for time consuming operations like hitting the db for a long list of data etc.
So, here in my case, i created a Task object, wrote the code in anonymous inner class which contains the code for hitting the db for the LOGIN credential. The Task must return an instance of List.
I intialized a Thread object inside the static method, passed Task's object in its constructor, set the daemon to true and started the Thread. However i am getting NullPointerException after running the application..
private static SessionFactory sessionFactory = null;
private static Session session = null;
private static final Transaction transaction = null;
private static final Configuration configuration = null;
private static List list;
  public static List getSelectList(final String query)
  {
      //list = null;
      System.err.println("Inside getSelectList");
      try{
      final Task <List> task= new Task <List> ()
      {
          @Override
          public List call()
          {
              try
              {
                 System.err.println("Inside call");
                 session.beginTransaction();
                 list = session.createQuery(query).list();
                 System.err.println(list);

                 session.getTransaction().commit();
                 return list;
              }
                catch (Exception e)
                {
                     session.getTransaction().rollback();
                     e.printStackTrace();
                }
              System.err.println("Outta try block");
              return null;
          }
      };

      task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
          @Override
          public void handle(WorkerStateEvent t) {
              System.err.println("Inside handle");
             list = task.getValue();
            /* for (Iterator it = list.iterator();it.hasNext(); )
                 {
                  System.err.println("Inside Set on succeeded");
                  //System.err.println( ((Login)it.next()).getUsername());
                 } */
             }
            });

     Thread th = new Thread(task);
     th.setDaemon(true);
     th.start();

     //list=task.getValue();

      }
      catch (Exception e) {e.printStackTrace();}
      return list;

  }

However, after many combinations and random permutations, things worked for me with commenting the Thread code and instead substituting it with task.run();
 /*Thread th = new Thread(task);
     th.setDaemon(true);
     th.start();*/
task.run();

Also i had to change the local variable List list = session.createQuery(query).list(); by declaring static List list; and initializing this static list = session.createQuery(query).list(); since it was throwing me the exception too even if i removed Thread code and added task.run()
 try
              {

                 session.beginTransaction();
                 //List locallist = session.createSQLQuery(query).list();
                 list = session.createSQLQuery(query).list();
                 session.getTransaction().commit();
                 return list ;
              }
                catch (Exception e){
                     session.getTransaction().rollback();

I wish to know why this happened. Why task.run() along with using static List worked for me?
Converting List to static and removing the Thread instance and using task.run(); was merely a number to different tries from my side to make my code work. i dunno the reasons.
I will be greatly humbled for any explanations. Thanks in advance.


text:
Q: CCTransitionPageTurn not working after using opengl I'm using CCTansitionPageTurn to flip between scenes.  It works fine for most scenes, but I have a coloring scene that draws with gl.  After coloring begins, CCTransitionPageTurn does not work for any scene transition, even those that worked fine before. (I can still move to another scene just fine, but the page turn effect is broken).
I think it may have to do with altering the gl state before the transition is called, but restoring the default gl state didn't work.  There's potentially a lot of places in the code where the problem is, but here's some code where I'm playing with gl.
/* ColoringGameScene : CCScene, which handles drawing menus and other cool UI things */

// In init
CCLayerColor *layer = [CCLayerColor layerWithColor:ccc4(255, 255, 255, 255)];
[self addChild:layer];
TouchDraw *drawObj = [TouchDraw node];
[drawObj setDrawPoints:_drawPoints];
[layer addChild:drawObj z:999];

// In -(void)ccTouchMoved:(UITouch *) touch withEvent:(UIEvent *)event
// drawPoints, an array of points to draw is updated.  drawObj has a reference to this array

/* In TouchDraw : CCNode, which handles gl drawing */

// In init
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_POINT_SMOOTH_HINT);
glEnable(GL_LINE_SMOOTH_HINT);
glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_BLEND_COLOR);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLineWidth(8);
glPointSize(8);

// elsewhere

-(void)drawCircle:(CGPoint)center radius:(float)r arc:(float)a line:(NSUInteger)segs lineToCenter: (BOOL)drawLineToCenter
{
int additionalSegment = 1;
if (drawLineToCenter)
    additionalSegment++;

const float coef = 2.0f * (float)M_PI/segs;

GLfloat *vertices = calloc( sizeof(GLfloat)*2*(segs+2), 1);
if( ! vertices )
    return;

for(NSUInteger i=0;i<=segs;i++)
{
    float rads = i*coef;
    GLfloat j = r * cosf(rads + a) + center.x;
    GLfloat k = r * sinf(rads + a) + center.y;

    vertices[i*2] = j * CC_CONTENT_SCALE_FACTOR();
    vertices[i*2+1] =k * CC_CONTENT_SCALE_FACTOR();
}
vertices[(segs+1)*2] = center.x * CC_CONTENT_SCALE_FACTOR();
vertices[(segs+1)*2+1] = center.y * CC_CONTENT_SCALE_FACTOR();

glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);

glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) segs+additionalSegment);

// restore default state
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);

free( vertices );
}

-(void)draw
{
[super draw];

    if ([drawPoints count])
{
        for(int i = 0; i < [drawPoints count]; i += 4)
        {
            CGPoint point0 = CGPointFromString([drawPoints objectAtIndex:i]);
            CGPoint point1 = CGPointFromString([drawPoints objectAtIndex:i+1]);
            CGPoint point2 = CGPointFromString([drawPoints objectAtIndex:i+2]);
            CGPoint point3 = CGPointFromString([drawPoints objectAtIndex:i+3]);

            glColor4f(255.0f/255.0f, 0.0f/255.0f, 0.0f/255.0f, 1.0f); // Red
            glLineWidth(8);
            glPointSize(8);

            // various calls to drawCirle and ccDrawCubicBezier

            //default
            glColor4f(0.0f/255.0f, 0.0f/255.0f, 0.0f/255.0f, 0.0f);
        }
    }
}

Let me know if more code would be helpful.

A: I'm beginer in openGL, but as I know, OpenGL settings are same for all your program. Some code  of your own drawing should change something in this settings. This may be the reason of your eshue. I cant tell you more, but you should work on this question.


text:
Q: How can I compute the frequencies of itemsets using R? My input file contains a transaction on each line. The following example shows the structure of my input file:
a
a
a,b
b
a,b
a,c
c
c

The above input file has 11 items and 8 itemsets. This input file has 3 unique items and 5 unique itemsets. I would like to compute the frequencies of each unique itemset. For the above input file, I'd like to write an R script that generates an output similar to the following CSV file:
"a",0.25
"a,b",0.25
"c",0.25
"b",0.125
"a,c",0.125

The report presents the number of occurrences of each unique itemset in the input transactions file divided by the total number of item sets in the input. Note that the report has sorted the itemsets based on their frequencies. How can I use R to compute the frequencies of the itemsets in my input transactions file?
UPDATE: I've already computed the association rules using the read.transactions and apriori methods. Can I reuse the results of these methods to compute the frequencies of the input itemsets.

A: dat <- read.table(text="a
a
a,b
b
a,b
a,c
c
c")
prop.table(table(dat$V1))

#    a   a,b   a,c     b     c
#0.250 0.250 0.125 0.125 0.250
 dat.prop <- as.data.frame( prop.table(table(dat$V1)) )
 dat.prop <- dat.prop[order(dat.prop$Freq, decreasing=TRUE), ]
 dat.prop
#-------- Added the order step as a revision
  Var1  Freq
1    a 0.250
2  a,b 0.250
5    c 0.250
3  a,c 0.125
4    b 0.125
#---------

 write.table(dat.prop, file="dat.prop.csv", sep=",", header=FALSE)

A: As simple as this:
Data <- read.table(header=TRUE, text="
itemset
a
a
a,b
b
a,b
a,c
c
c")

cbind(table(Data), table(Data) / nrow(Data))

## EDIT: Include sorting by observed proportion
T <- table(Data)                        # observed freq.
T <- cbind(T, T/nrow(Data))             # combine freq. and prop.
T <- T[order(T[,2], decreasing=TRUE),]  # sort
colnames(T) <- c("freq", "prop")        # add column names

A: If the input data is in a file called 'dat.txt', then this code would work. The output would be in a file in the same directory called 'out.csv'.
Y=read.table('dat.txt')
Y=as.character(unlist(Y))
U=unique(Y)
n=length(U)
F=rep(0,n)
for(i in 1:n) F[i] = mean(Y==U[i])
D=cbind(U,F)
colnames(D)=c("Value","Frequency")
write.csv(D,'out.csv')

My apologies that this code is neither pretty nor commented.

A: Another solution using plyr
library(plyr)
ddply(dat, "V1", summarize, Freq = length(V1)/NROW(dat))

   V1  Freq
1   a 0.250
2 a,b 0.250
3 a,c 0.125
4   b 0.125
5   c 0.250


text:
Q: Dynamic property on JavaScript object getting null I'm trying to set the dynamic property on a javascript object using the ng-model. But I'm unable to create it as I always get null for that property. I have different ways to copy the value from the variable self.username to self.params javascript object in the below code.
Please see this plnkr
index.html
<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">

  Carriers

routes.js
myApp.config(function($routeProvider) {
  $routeProvider
    .when('/carriers', {
      templateUrl: 'carriers.html',
      controller: 'MainCtrl',
      controllerAs: 'mainCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
});

Carriers.html
<input type="text"  placeholder="username" ng-model="mainCtrl.username" />
<button  ng-click="mainCtrl.login()">Login</button>

app.js
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('MainCtrl', function() {
  var self = this;
  self.username = '';
  self.login = login;
  self.params = {
    username: self.username //doesnt work
  };
  //self.params.username=angular.copy(self.username);    //doesnt work
  //self.params['username']=self.username; //doesnt work
  function login() {
    //   alert(self.username);
    console.dir(self.username); // works
    console.dir(self.params); // username:'' getting empty string for username property
  }
});

A: The value does not update because you created a new object and set the value of self.params.username to the value of self.params. self.params.username does not reference self.params it was just set from the value when the object was created.
If you want to bind self.params.username to the input then you can change your input model to:
<input type="text"  placeholder="username" ng-model="mainCtrl.params.username" />

Another alternative is to watch self.username and set the value of self.params.username to the new value using $watch
// watch mainCtrl.username for any changes
$scope.$watch('mainCtrl.username', function(newValue, oldValue) {

    // set self.params.username from the new value
    self.params.username = newValue;

});


text:
Q: Need to find empty passage-uima ruta I need to annotate empty passage in a document.I used regex pattern to annotate.But it also covering the non-emptypassage
Sample Input file:

You can easily change the formatting

To change the overall look of your document

Ruta Script:
   "

"->EMPTYPASSAGE;
   "

"->EMPTYPASSAGE;
                         or
   "

"->EMPTYPASSAGE;
   "

"->EMPTYPASSAGE;

A: Your regex consumes several
 tags. Try something like:
"
]*?)>
"->EMPTYPASSAGE;
"
]*?)>
"->EMPTYPASSAGE;


text:
Q: How to use the same form for creating and editing in ruby on rails I am new to ruby. I have the same form but i need it to perform creation/updation as and when required. The problem i have now is that whenever i call edit instead of editing the details of an existing user, i am getting a new user with the edited details. To put it simply, i think whenever i perform edit, the create method is being called.
So is there any way to use single form for both new and edit instead of using separate forms.
The following code is for editing user details:
         <%= link_to 'Home', root_path %>

Edit user

        <%= form_for :user, url: user_index_path do |f| %>

            <%= f.label :name %>

            <%= f.text_field :name %>

            <%= f.label :address %>

            <%= f.text_area :address %>

            <%= f.label :email %>

            <%= f.text_field :email %>

            <%= f.label :phone %>

            <%= f.text_field :phone %>

            <%= f.label :state %>

            <%= f.text_field :state %>

            <%= f.label :country %>
            <%= f.collection_select(:country, Country.all, :name, :name) %>

            <%= f.submit %>

        <% end %>

The following code is for creating user:
        <%= link_to 'Home', root_path %>

Create new user

    <%= form_for :user, url: user_index_path do |f| %>

        <%= f.label :name %>

        <%= f.text_field :name %>

        <%= f.label :address %>

        <%= f.text_area :address %>

        <%= f.label :email %>

        <%= f.text_field :email %>

        <%= f.label :phone %>

        <%= f.text_field :phone %>

        <%= f.label :state %>

        <%= f.text_field :state %>

        <%= f.label :country %>
        <%= f.collection_select(:country, Country.all, :name, :name) %>

        <%= f.submit %>

    <% end %>

And this is my controller:
      class UserController < ApplicationController
    def index
        @users = User.all

    end

    def show
    @user = User.find(params[:id])
  end

    def new
        @user = User.new
    end

    def create
    @user = User.new(user_params)
        if @user.save
            redirect_to @user
        else
            render 'new'
        end
    end

  def edit

    @user = User.find(params[:id])

  end

    def update
    #@user = User.find(params[:id])
        if @user.update(user_params)
        redirect_to @user
    else
      render 'edit'
    end
    end

    def destroy
    @user = User.find(params[:id])
    @user.destroy
      redirect_to user_index_path
  end

    private
    def user_params
        params.require(:user).permit(:name, :address, :email, :phone, :state, :country)
    end

end

Since i am new to ruby, i did not get the exact details of how http requests function in ruby.

A: users/_form.html.erb
  <%= link_to 'Home', root_path %>
  <%= form_for @user do |f| %>

  <%= f.label :name %>

  <%= f.text_field :name %>

  <%= f.label :address %>

  <%= f.text_area :address %>

  <%= f.label :email %>

  <%= f.text_field :email %>

  <%= f.label :phone %>

  <%= f.text_field :phone %>

  <%= f.label :state %>

  <%= f.text_field :state %>

  <%= f.label :country %>
  <%= f.collection_select(:country, Country.all, :name, :name) %>

  <%= f.submit %>

  <% end %>

users/new.html.erb

Create new user

<%= render 'form' %>

users/edit.html.erb

Edit user

<%= render 'form' %>

users_controller.rb
class UsersController < ApplicationController
  before_filter :find_user, only: [:show, :edit, :update, :destroy]
  def index
    @users = User.all
  end

  def show
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    @user.destroy
    redirect_to user_index_path
  end

  private
  def user_params
    params.require(:user).permit(:name, :address, :email, :phone, :state, :country)
  end

  def find_user
    @user = User.find(params[:id])
  end

end

When you have same view code for two or more methods, you should create a partial of same view code and render it in those methods. This is called DRY principle in ruby on rails


text:
Q: MySQL Select query - remove unwanted rows I have a table with the following (I've sorted it by date):
ID        prodId    date
16      532     2015-08-17
19      535     2014-08-18
18      534     2011-08-17
27      48      2010-08-26
26      1541    2010-08-25
25      1541    2010-08-21
24      1540    2010-08-20
21      48      2010-08-19
20      48      2010-08-18
17      533     2010-08-17
14      532     2010-08-17
22      1540    1970-01-01

I want to select the most recent prodId whos date is in the past. My problem is I am getting multiple prodId with the same value (in this example, 48 and 1541).
My query is currently:
SELECT * FROM `prods` WHERE (date <= '2010-08-26')  order by date DESC

How do I change my query to remove the unwanted rows?

A: SELECT * FROM prods p1
WHERE (date <= '2010-08-26')
AND Date in (Select Max(Date) from prods p2 where p1.prodId = pr.ProdId
             and date <= '2010-08-26')
order by activeUntil DESC

A: add limit 1 to query

A: Are you looking for the LIMIT statement?
SELECT * FROM `prods` WHERE (date <= '2010-08-26')  order by activeUntil DESC LIMIT 1


text:
Q: Why is in MySQL every valid SELECT not a valid VIEW? I want to get a count, grouped by day. The following SELECT works fine:
  SELECT COUNT( time_end ),
         time_end
    FROM main
GROUP BY DAY( time_end )

I copy/pasted that into the VIEW creation form of phpmyadmin, and get this error:

"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'count(time_end)) AS SELECT count( time_end ) , time_end FROM main GROUP BY d' at line 4"

Here is the complete SQL generated from phpmyadmin's form:
CREATE ALGORITHM = UNDEFINED VIEW `count by day` (
  time_end,
  count( time_end )
) AS SELECT COUNT( time_end ),
            time_end
       FROM main
   GROUP BY DAY( time_end )

What's wrong? Why is a valid SELECT not automatically a valid VIEW creation? Thanks.

A: Don't know where phpMyAdmin is getting that syntax.  Use:
CREATE VIEW COUNT_BY_DAY AS
  SELECT COUNT( time_end ),
         time_end
    FROM main
GROUP BY DAY( time_end )

Be aware that you are relying on MySQL's hidden column functionality - the time_end value will be arbitrary (can't be relied on to always return the same value as the number of values to choose from increases).  It also can't be ported to most databases, you'll have to re-write it.
Also, you're counts are going to be skewed for days 28 - 31 if you aren't limiting by month.  Not all months have 31 days.

A: The only thing wrong with your query is that you have a column name that is not back-ticked.

CREATE ALGORITHM = UNDEFINED VIEW count by day (
    `count( time_end )`   # you needed to put this in backticks
    time_end,
  ) AS SELECT COUNT( time_end ),
              time_end
         FROM main
     GROUP BY DAY( time_end )

For what it's worth, you have the column names around the wrong way.
The syntax you are using is EXPLICIT NAMING of view column names. It allows you to give names to column that would otherwise be derived from the query columns, e.g.
CREATE VIEW X AS
SELECT time_end, other1
FROM main

:: X contains the columns `time_end` and `other1`

CREATE VIEW X ( TheStopTime, DataPoint ) AS
SELECT time_end, other1
FROM main

:: X contains the columns `TheStopTime` and `DataPoint`


text:
Q: A possible case of hacked email account. What kind of an attack is this? I own a Yahoo mail account. I am using this account for sending resumes and receive notifications from various job portals. But yesterday, I found that some 10-15 mails had been sent to random addresses from my account. Most of them had this format:
hr@<companyname>.com

I am pretty sure that I didn't send any mails to such addresses. Initially, I thought the job portals may be sending mails on my behalf and Yahoo is logging them, but then I saw the contents. The contents of all those mails were a URL, which I did not click. SCARED. Also, to top it off, my "Sending Name" has been changed to 'Nice Maria'!! o_0
I have taken the necessary measures and changed my password and the secret question. I cannot delete this account as this email is registered with all the job portals and other companies.
Is this a simple case of my account being compromised or was I a victim of some web vulnerability? All the mails seem to be bot generated, with only a URL as the message body. Please advice.

A: This is a SMTP faking, which basically means the user sent the email through another SMTP server that used any email address (you can send an email as i@am.com even though you don't even own the domain), however your email account is not compromised and by no means people could see your email inbox.
To prevent this from happening, my suggestion is to look into the SPF record creation, which if you are using Google Apps, it can be found here: http://support.google.com/a/bin/answer.py?hl=en&answer=33786, this can not prevent people from sending emails from fake email address, but it will automatically sent those ones to spam.

A: Nothing you have said suggests any sort of compromise. I can write a letter and mail it to you with the President's return address on the envelope -- does that mean I "hacked" the President?


text:
Q: Ergodicity of an image measure Let $X=(X_n)_{n \in \mathbb{Z}}$ and $Y=(Y_n)_{n \in \mathbb{Z}}$ be two sequences of i.i.d. random variables on the probability space $(\Omega, \mathcal{F}, \mathbb{P})$ such that $X$ is independent of $Y$. For $k \in \mathbb{Z}$ consider the shift operator $\theta_k$ which maps a sequence $(x_n)_{n \in \mathbb{Z}}$ in $\mathbb{R}^{\mathbb{Z}}$ to $(x_{n+k})_{n \in \mathbb{Z}}$.
Let the function
$$
f : \mathbb{R}^{\mathbb{Z}} \times \mathbb{R}^{\mathbb{Z}} \rightarrow \mathbb{R}^{\mathbb{Z}}
$$
be measurable and such that
$$
\theta_k f(X, Y) = f (\theta_k X, \theta_k Y) \quad \forall k \in \mathbb{Z}. \tag{1}
$$
Let $\mu_1$, $\mu_2$ denote the distributions of $X$ and $Y$ and let $\mu := \mu_1 \otimes \mu_2$ be the distribution of $(X, Y)$. $(1)$ means that
$$
\theta_k f(x, y) = f(\theta_k x, \theta_ky) \quad \mu \text{-a.s.} \ \forall k \in \mathbb{Z}.
$$
Using the fact that $\mu$ is stationary on $(\mathbb{R}^\mathbb{Z} \times \mathbb{R}^\mathbb{Z}, \mathcal{B}(\mathbb{R})^{\mathbb{Z}} \otimes \mathcal{B}(\mathbb{R})^{\mathbb{Z}})$ (with respect to $(\theta_k \times \theta_l)_{k, l \in \mathbb{Z}}$), one can show that the image measure $\mu \circ f^{-1}$ is also stationary on $(\mathbb{R}^\mathbb{Z}, \mathcal{B}(\mathbb{R})^{\mathbb{Z}})$ (with respect to $(\theta_k)_{k \in \mathbb{Z}}$). I am further interested in the following:

Question: Is the image measure $\mu \circ f^{-1}$ ergodic? We know that $\mu \circ f^{-1}$ is ergodic iff
$$
\lim_{n \rightarrow \infty} \frac{1}{(2n+1)} \sum_{k \in [ -n, n ] \cap \mathbb{Z}} \mu \left( f^{-1} (\theta_k^{-1} ( A ) \cap B) \right) = \mu(f^{-1}(A)) \mu(f^{-1}(B)) \quad \forall A, B \in \mathcal{B}(\mathbb{R})^{\mathbb{Z}}. \tag{2}
$$

To show this, we can write
\begin{align*}
\mu \left( f^{-1} (\theta_k^{-1} ( A ) \cap B) \right) &= \mu \left( f^{-1} (\theta_k^{-1} ( A ) ) \cap f^{-1}(B) \right) \\
&= \mu \left( \{ (x, y) : f(x, y) \in \theta_k^{-1}(A) \} \cap f^{-1}(B) \right) \\
&= \mu (\{ (x, y) : \theta_k f(x, y) \in A \} \cap f^{-1}(B)) \\
&= \mu (\{ (x, y) : f(\theta_k x, \theta_k y) \in A \} \cap f^{-1}(B)) \\
&= \mu \left( \{ (x, y) : (\theta_k x, \theta_k y) \in f^{-1}(A) \} \cap f^{-1}(B) \right) \\
&= \mu \left( (\theta_k \times \theta_k)^{-1} ( f^{-1}(A) ) \cap f^{-1}(B) \right). \tag{3}
\end{align*}
If $\mu$ is ergodic (is it?), then we also know that
$$
\lim_{n \rightarrow \infty} \frac{1}{(2n+1)^{\color{red}2}} \sum_{(k, l) \in [ -n, n ]^{\color{red}2} \cap \mathbb{Z}^{\color{red}2}} \mu \left( (\theta_k \times \theta_l)^{-1} ( E ) \cap F \right) = \mu(E) \mu(F) \quad \forall E, F \in \mathcal{B}(\mathbb{R})^{\mathbb{Z}} \otimes \mathcal{B}(\mathbb{R})^{\mathbb{Z}}. \tag{4}
$$
Now, is it possible to use $(3)$ and $(4)$ to obtain $(2)$?

A: This is simpler and more general. Suppose you have any  ergodic probability measure preserving system $(X, \mathcal F, \mu, T)$ and $F:X \to Y$ maps it to another system $(Y, \mathcal G, \nu, S)$, where
(1) $A \in \mathcal G$ implies that $F^{-1}(A) \in \mathcal F$, (2) the measures satisfy $\nu=\mu\circ F^{-1}$, and (3) the transformations satisfy $S \circ F=F \circ T$. Then the second system is ergodic as well. Just use the definition of ergodicity. Indeed, if $A \in \mathcal G$ is invariant, i.e., $S^{-1}(A)=A$, then $B=F^{-1}(A)$ satisfies $T^{-1}(B)=B$, so $\nu(A)=\mu(B) \in \{0,1\}$.


text:
Q: Grouping by similar lists in a column within a dataframe I have a dataframe which has a column of lists.
I want to group the rows which have similar lists, irrespective of the order of the items in the list. Each list can occur multiple times within the column. I want the grouped lists sorted according to number of occurences within the column.
data = [['a', ['tiger', 'cat', 'lion']], ['b', ['dolphin', 'goldfish', 'shark']], ['c', ['lion', 'cat', 'tiger']], ['d', ['bee', 'cat', 'tiger']],\
       ['e', ['cat', 'lion', 'tiger']],  ['f', ['cat', 'bee', 'tiger']], ['g', ['shark', 'goldfish', 'dolphin']]]
df = pd.DataFrame(data)
df.columns = ['ID', 'animals']

df
   ID   animals
0   a   [tiger, cat, lion]
1   b   [dolphin, goldfish, shark]
2   c   [lion, cat, tiger]
3   d   [bee, cat, tiger]
4   e   [cat, lion, tiger]
5   f   [cat, bee, tiger]
6   g   [shark, goldfish, dolphin]

I want to group the similar lists in the above dataframe. The order of the animals in the list, can be different.
I am currently using the below code to do this:
import collections as cs
animals_grouped = pd.DataFrame()
for q in range(len(df)):
    for r in range(len(df)):
        if (cs.Counter(df.iloc[q]['animals']) == cs.Counter(df.iloc[r]['animals'])):
            animals_grouped = animals_grouped.append(df.iloc[[r]], ignore_index = True)

animals_grouped.drop_duplicates('ID').reset_index(drop = True)

Result:
animals_grouped

    ID  animals
0   a   [tiger, cat, lion]
1   c   [lion, cat, tiger]
2   e   [cat, lion, tiger]
3   b   [dolphin, goldfish, shark]
4   g   [shark, goldfish, dolphin]
5   d   [bee, cat, tiger]
6   f   [cat, bee, tiger

Considering I have 100,000+ rows in my original dataframe, what is the alternative to this nested for loop.

A: data = [['a', ['tiger', 'cat', 'lion']], ['b', ['dolphin', 'goldfish', 'shark']], ['c', ['lion', 'cat', 'tiger']], ['d', ['bee', 'cat', 'tiger']],\
       ['e', ['cat', 'lion', 'tiger']],  ['f', ['cat', 'bee', 'tiger']], ['g', ['shark', 'goldfish', 'dolphin']]]
df = pd.DataFrame(data)
df.columns = ['ID', 'animals']
df1 = df.assign(temp=df.animals.apply(lambda x: ''.join(sorted(x))))
df = df1.assign(temp2 =df1.groupby(df1['temp'].values)['temp'].transform('count')).sort_values(['temp2','temp'], ascending=False).drop(['temp','temp2'], 1)

OUTPUT:
  ID                     animals
0  a          [tiger, cat, lion]
2  c          [lion, cat, tiger]
4  e          [cat, lion, tiger]
1  b  [dolphin, goldfish, shark]
6  g  [shark, goldfish, dolphin]
3  d           [bee, cat, tiger]
5  f           [cat, bee, tiger]

A: You can create a temp sort key by sorting the list, sort the df and then drop it.
(
    df.assign(sort_key = df.animals.apply(sorted))
    .sort_values('sort_key')
    .drop('sort_key', axis=1)
)

    ID  animals
0   a   [cat, lion, tiger]
2   c   [cat, lion, tiger]
1   b   [dolphin, goldfish, shark]


text:
Q: Difference between matplotlib's plot() and pandas plot()? What is the difference between matplotlib.pyplot.plot() and pandas.DataFrame.plot()?
We can plot using both but what is the measure difference between both?
How can i draw bar chart and group by some categorical variable?

A: Matplotlib's pyplot is the library that Pandas use in their plot function. Pandas' plot is only a convenient shortcut.
For the bar chart question: I would suggest using Seaborn's barplot, using the desired category as hue.
If you wish to only use Pandas, then maybe something like:
df = pd.DataFrame(np.random.rand(10, 1), columns=['col_name'])
df['category'] = df.col_name>0.5

print(df)

   col_name  category
0  0.053908     False
1  0.136295     False
2  0.325790     False
3  0.362942     False
4  0.919924      True
5  0.406884     False
6  0.433959     False
7  0.725699      True
8  0.582537      True
9  0.608040      True

df.groupby('category').count().plot(kind='bar', legend=False)


text:
Q: iOS detect tapped character Hello i gave a string that is:
[102,103] [207]

I have added TapGestureRecognizer to the string, and want to detect on which character user tapped, here is my code:
    - (void)handleTapFrom: (UITapGestureRecognizer *)recognizer {

if (recognizer.state == UIGestureRecognizerStateEnded) {
    CGPoint location = [recognizer locationInView:self];

    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self.attributedText];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    [textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.bounds.size];
    [layoutManager addTextContainer:textContainer];

    textContainer.maximumNumberOfLines = self.numberOfLines;
    textContainer.lineBreakMode = self.lineBreakMode;

    NSUInteger characterIndex = [layoutManager characterIndexForPoint:location
                                                      inTextContainer:textContainer
                             fractionOfDistanceBetweenInsertionPoints:NULL];
}

Always returns index of a last char ( in this situation = 14 ) - why?


text:
Q: Spring form field dataType conversion, error This is Achinta, a new bee in the world of Spring. I need a small help to understand and resolve a problem which I am facing. I hope will find my answer here.
I am working on a sample Spring Web project. Here I have a Controller, Bean class and a Jsp page for UI and the other artifacts. Here is my Bean class.
@Entity
@Table(name = "tblLoadCriteria")
public class Load implements Serializable {
    private Integer loadID;
    private String loadCountry;
    private String loadState;
    private String loadCity;
    private Integer totalAirVolume;

    public Load() {//Constructor}

   //And Getter & Setter methods for loadID, loadCountry, loadState, loadCity & totalAirVolume
}

And the Spring form in my Jsp page.
<form:form id="systemForm" commandName="load" action="${pageContext.request.contextPath}/doSothing" method="POST" >
  <spring:message code="loadCountry" />: <form:input path="loadCountry" />
  <spring:message code="loadState" />: <form:input path="loadState" />
  <spring:message code="loadCity" />: <form:input path="loadCity" />
  <spring:message code="totalAirVolume" />: <form:input path="totalAirVolume" />

  <spring:message code="save" text="Save" scope="page" var="save" />
  <input id="next" type="button" onClick="submitSave();" />
</form:form>

And here goes the controller code
@RequestMapping(value = "/doSothing", method = RequestMethod.POST)
public String doSothing(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("load") @Valid Load load ,
            BindingResult result, SessionStatus sessionStatus) {

    loadService.saveLoad(load);

    return "forward:getApplicationRequirements";
}

Here the problem I am facing is, The "totalAirVolume" in the Load bean class is of type Integer and is bind to the UI page using spring form tags. But in the UI if I enter float value (F.Ex 12.12), instead of an integer and submit the page it gives me  status:400 error.
I am not so keen on javascript for validation for "totalAirVolume" field and looking for Spring way to handle it. Please help.
Your responses are highly appreciated.
Regards
Achinta

A: Modify your controller like this to return back to your form in case of validation/conversion errors:
@RequestMapping(value = "/doSothing", method = RequestMethod.POST)
public String doSothing(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("load") @Valid Load load ,
            BindingResult result, SessionStatus sessionStatus) {
    // Return back to the form if the data is not valid
    if (bindingResult.hasErrors()) {
        return "yourFormViewName"; // Name of the view for your form
    }
    loadService.saveLoad(load);
    return "forward:getApplicationRequirements";
}

And put this in your JSP form:

The <form:errors> element will display server side validation/conversion error messages.

A: First of all, before saving anything into DB, better to check each field if valid or not. I see you add @Valid before the model object 'Load', that means you want to use JSR-303 to validate the bean object. However, in your bean class, you don't add annotation to check anything, for example @size.
Check this http://docs.spring.io/spring/docs/3.2.7.RELEASE/spring-framework-reference/htmlsingle/#validation-beanvalidation-overview, "7.8.1 Overview of the JSR-303 Bean Validation API".
Instead of using JSR-303 API, I suggest you create a validator that implements'org.springframework.validation.Validator', and make your rules.
And in your controller, before saving the object, call this validator to validate the object. If have  error, return error message to force input correct content.
@RequestMapping(value = "/doSothing", method = RequestMethod.POST)
public String doSothing(HttpServletRequest request, HttpServletResponse response,
LoadValidator lv=new LoadValidator ();
@ModelAttribute("load") @Valid Load load ,
            BindingResult result, SessionStatus sessionStatus) {

    LoadValidator.validate(load);
    if(result.hasErrors()){
       //do something
        return something;
    }else {
        loadService.saveLoad(load);
        return "forward:getApplicationRequirements";
   }
}

For your reference, check "7.2 Validation using Spring's Validator interface" of the above link.


text:
Q: Syncing time with Windows Server Dual Booting systems I am about to work on getting the workstations on my network here to be connected to the Active Directory on my Windows 2003 server using Likewise Identity Service. One of the security requirements is a good time sync, so I am trying to setup my Windows server time server on my CentOS machines.
These machines dual boot Windows 7 and CentOS 5.5. I am using the Windows server as a time server and it's getting its time from its CMOS. Following a microsoft Knowledge Base article, I removed all the time servers from the CentOS box I am experimenting with and added the IP of my Windows server. It seems to connect OK but the time never gets updated.
This network has no connection to the Internet, it's cut off from the world, so cannot get Internet time!
Any ideas?

A: Solved, I just had to check the box that says Syncronize before service is started inside the time settings and then unchecking the use local time source box.


text:
Q: Que hacer para que el resultado de un calculo con un loop se guarde en mi df? Mi intención con el siguiente código es dividir dos df en base al campo date, para luego aplicar un calculo y que se guarde el resultado de cada fecha en un único df. Esto es lo que he intentado:
for (i in unique(temp_maxmin$date))
     Tmaxmin_subset<- temp_maxmin[temp_maxmin$date==i,]
    radiosond_subset<-radiosond[radiosond$date==i,]
    basedata<-as.data.frame(seq(2500,10000,50))
    colnames(basedata)<-c("height")
    basedata$date<-Tmaxmin_subset$date
    basedata$Tmax<-(Tmaxmin_subset$max_val[[1]]-(9.8/1000*(basedata$height-radiosond_subset$height[[1]])))
    basedata$Classic<-(Tmaxmin_subset$classic[[1]]-(9.8/1000*(basedata$height-radiosond_subset$height[[1]])))
    basedata$ICU<-(Tmaxmin_subset$icubogota[[1]]-(9.8/1000*(basedata$height-radiosond_subset$height[[1]])))

Estoy teniendo algunos problemas, de primera mano y el mas importante es que no se están guardando todas los datos correspondientes a cada fecha si no la ultima fecha. Ademas, no he encontrado una linea en la cual pueda decir que solo se haga el calculo cuando los subsets coincidan en la fecha y de resto omita hacer el calculo.
Muestra de los df
        date  max_val  min_val  classic icubogota
      <date>    <dbl>    <dbl>    <dbl>     <dbl>
1 2006-04-17 290.4017 283.5183 288.5183  286.5183
2 2006-04-18 291.9247 283.2837 288.2837  286.2837
3 2006-04-19 292.3280 283.9537 288.9537  286.9537
4 2006-04-20 292.0320 284.1527 289.1527  287.1527
5 2006-04-21 290.8660 282.9913 287.9913  285.9913
6 2006-04-22 290.9757 282.6947 287.6947  285.6947

  press height   temp dwpt relh mixr drct sknt  thta  thte  thtv       date
1 753.0   2546 281.35  6.5   89 8.12    0    0 305.1 329.8 306.6 1999-03-11
2 740.0   2688 282.75  6.5   81 8.27   47    4 308.1 333.6 309.7 1999-03-11
3 735.1   2743 282.65  6.2   80 8.13   65    5 308.6 333.7 310.1 1999-03-11
4 708.2   3048 281.85  4.3   74 7.40  160   10 311.0 334.1 312.4 1999-03-11
5 700.0   3143 281.55  3.7   72 7.18  135    8 311.8 334.3 313.1 1999-03-11
6 682.4   3353 280.05  2.9   76 6.95  135    7 312.4 334.3 313.7 1999-03-11

Cualquier Ayuda es bien recibida

A: Tienes un problema de concepto. Dentro del ciclo for, por cada iteración estas haciendo:
basedata<-as.data.frame(seq(2500,10000,50))

Lo que te re-define cada vez de nuevo el data.frame, cada vuelta basedata vuelve a crearse en blanco y le completas los datos, por consiguiente al finalizar el ciclo basedata solo tendrá los valores de la última iteración.
Te aclaro que hay formas mucho mejores de resolver que usar un ciclo for, pero eso te lo dejo para que lo investigues. Tomando como base tu ejemplo, lo que puedes hacer es:
temp_maxmin <- read.table(text="date max_val min_val classic icubogota
2006-04-17 290.4017 283.5183 288.5183 286.5183
2006-04-18 291.9247 283.2837 288.2837 286.2837
2006-04-19 292.3280 283.9537 288.9537 286.9537
2006-04-20 292.0320 284.1527 289.1527 287.1527
2006-04-21 290.8660 282.9913 287.9913 285.9913
2006-04-22 290.9757 282.6947 287.6947 285.6947", sep=" ", header=TRUE)

radiosond <- read.table(text="press height temp dwpt relh mixr drct sknt thta thte thtv date
753.0 2546 281.35 6.5 89 8.12 0 0 305.1 329.8 306.6 1999-03-11
740.0 2688 282.75 6.5 81 8.27 47 4 308.1 333.6 309.7 2006-04-17
735.1 2743 282.65 6.2 80 8.13 65 5 308.6 333.7 310.1 2006-04-17
708.2 3048 281.85 4.3 74 7.40 160 10 311.0 334.1 312.4 1999-03-11
700.0 3143 281.55 3.7 72 7.18 135 8 311.8 334.3 313.1 1999-03-11
682.4 3353 280.05 2.9 76 6.95 135 7 312.4 334.3 313.7 2006-04-22", sep=" ", header=TRUE)

basedata<-data.frame()
for (i in unique(temp_maxmin$date)) {
    Tmaxmin_subset <- temp_maxmin[temp_maxmin$date==i,]
    radiosond_subset <- radiosond[radiosond$date==i,]

    if (nrow(Tmaxmin_subset)!= 0 & nrow(radiosond_subset)!=0) {
        tmp<-as.data.frame(seq(2500,10000,50))
        colnames(tmp)<-c("height")

        tmp$date <- Tmaxmin_subset$date
        tmp$Tmax <- (Tmaxmin_subset$max_val[[1]]-(9.8/1000*(tmp$height-radiosond_subset$height[[1]])))
        tmp$Classic <- (Tmaxmin_subset$classic[[1]]-(9.8/1000*(tmp$height-radiosond_subset$height[[1]])))
        tmp$ICU <- (Tmaxmin_subset$icubogota[[1]]-(9.8/1000*(tmp$height-radiosond_subset$height[[1]])))

        if (nrow(basedata)==0) {
            basedata <- tmp
        } else {
            basedata <- rbind(as.matrix(basedata), as.matrix(tmp))
        }
    }
}

Comentarios:

*

*basedata lo creamos fuera del ciclo como un data.frame vació

*Agregué un control para estar seguros que el proceso se ejecuta solo si tenemos datos de los dos data.farmes de entrada: if (nrow(Tmaxmin_subset)!= 0 & nrow(radiosond_subset)!=0)

*Luego creamos un data.frame temporal y lo completamos con tu lógica

*Si es el primer ciclo (nrow(basedata)==0) le asignamos a basedata el valor de tmp, caso contrario usamos rbind() para "agregar" tmp a basedata

A: Deberías echarle un vistazo al paquete Tidyverse o data.table, te permite trabajar con data frames con las mejores opciones. Además creo que también te vendría bien echarle un vistazo a Purrr, con las funciones "map" que te permiten aplicar funciones a través de listas y/o data frames. (Te contesto y no comento porque con la repu que tengo en español no me permite) Un saludo y espero que te ayude.


text:
Q: Why does fully qualified C# import fail? In my main method, I had a line of code -
WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);

I added an import - System.Net.WebRequest. This causes an error:

The type or namespace name 'YourProject' could not be found (are you
  missing a using directive or an assembly reference?).

The error goes away when I change the import to  System.Net Why does this happen ?
Actually, I am using this code inside a C# script task of SSIS, an ETL tool. I mention that in case you cannot replicate the problem in plain visual studio and want to declare SSIS as
a source of the problem.

A: using Directive (C# Reference)

The using directive has two uses:

*

*To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

  using System.Text;

*

*To create an alias for a namespace or a type. This is called a using alias directive.

  using Project = PC.MyCompany.Project;

You can't import a type, you have to import the entire namespace, and that's why  using System.New.WebRequest does no work, and your code does not compile.
You could create an alias to WebRequest, to prevent entire namespace to be imported, but I personally don't like that solution:
using WebRequest = System.Net.WebRequest;

And yes, the error could be a little more descriptive, but that's the problem here.


text:
Q: Why HttpConnection could be used even after the related HTTPResponse closed See the following code, written in Python 2.7
import httplib

HOST, PORT, PATH = '127.0.0.1', 8888, '/'  # mask

def test():
    conn = httplib.HTTPConnection(HOST, PORT)
    conn.request('GET', PATH, None, headers={})
    rsp = conn.getresponse()
    print rsp.status
    rsp.close()  # close response

    conn.request('GET', PATH, None, headers={})
    rsp2 = conn.getresponse()
    print rsp2.status

test()

The server will always return 403 for testing. But the result of test() is

403 200

It looks so wired! Two questions here

*

*Why the connection still could be used even after closing the
HTTPResponse, does the underlying socket closed?
It seemed that the underling socket does not shutdown.

*Why 200 is returned?
Here are the server code using Tornado
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_status(403)
        self.write('<html>\r\nhello world\r\n</html>')

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

A: Because you are closing a file on top of the socket and not the socket.
Quote from the documentation for socket.makefile

Return a file object associated with the socket. (File objects are
  described in File Objects.) The file object does not close the socket
  explicitly when its close() method is called, but only removes its
  reference to the socket object, so that the socket will be closed if
  it is not referenced from anywhere else.

Link: https://docs.python.org/2/library/socket.html
And the close in HTTPResponse closes self.fp which is the result of self.fp = sock.makefile(... in the __init__ method of HTTPResponse in httplib
The socket is still referenced in your conn object and hence it will not be automatically closed.
(some people would say: Use the source Luke )
As to why the server returns 200... you would need to let the world know against what you are testing and how the communication (HTTP Content) looks like.
Edit following the comment:
HTTPResponse.close does not consume anything. It simply removes a reference to to the socket, but you still have a reference in conn.
The data remains in the socket's buffer until the socket is really closed.
You are getting 200, because the 2nd getresponse tries to parse the data in the buffer. And because no proper HTTP Status line is found (it was consumed by the 1st getresponse), the result is that HTTPResponse believes it is an old HTTP 0.9 server and sets the default answer code to 200.
The code is in HTTPResponse._read_status


text:
Q: How to organize member field classes to use the base class in C#? I have a class called Gas which keeps basic information about the specific gas:
public class Gas {
    public float molarMass;
    public float heatCapacity;

    public float GetPartialPressure() {}
    public float GetMass() {}
    public float GetMassPercentage() {}
}

I also have a class called RoomAir which includes a list of Gas'es and a Dictionary<Gas, float>, which stores every gas in the air of that specific room and its volume percentage.
public class RoomAir {
    public float roomVolume;
    public float pressure;

    public List<Gas> gases;
    public Dictionary<Gas, float> gasVolPercentage;
}

Unfortunately all of the methods of Gas require information about other gases in a room and the room's volume.
public class Foo {
    public static void Main() {
        Gas nitrogen;
        nitrogen.molarMass = 0.028f;
        Gas oxygen;
        oxygen.molarMass = 0.032f;

        RoomAir earthAir;
        earthAir.roomVolume = 100f;
        earthAir.gases.Add(nitrogen);
        earthAir.gasVolPercentage.Add(nitrogen, 0.78f);
        earthAir.gases.Add(oxygen);
        earthAir.gasVolPercentage.Add(oxygen, 0.22f);

        earthAir.gases[0].GetMass(); // can't be done, as the nitrogen Gas would need
                                     // information about earthAir volume etc.
    }
}

Is there any proper workflow for the Gas class to use variables from the correct RoomAir object?
Additionaly: is it possible to tweak things up so that I could reach Gas members using gases.oxygeninstead of gases[0]?

A: Why dont you just add as a parameter of your GetMass method a volume?
public float GetMass(float roomVolume) {}

And then just pass the earth air volume
earthAir.gases[0].GetMass(earthAir.roomVolume);

A: I think when you create a new gas, you should require a reference to RoomAir to be passed into the constructor.
Your code is missing the construction of the Gas object, but do this:
Gas nitrogen;
nitrogen = new Gas(roomAir);
nitrogen.molarMass = 0.028f;

Store the reference to roomAir in your Gas object - obviously you'll have to construct the roomAir first. Since it's a reference any other changes you do to the room air will reflect in the gas object.
It's pretty standard to give objects a link to their parent (usually called Parent), and their parent is generally a container.
Your GetMass() method can then do Parent.gases to get other gases in the room.
This solution would work but I really don't think it's a nice one. I think a better solution would be to put GetMass onto the RoomAir class and keep the Gas classes totally dumb.
Since the mass of the nitrogen has nothing to do with the nitrogen itself, it is really something you have to examine the room to find, it makes more sense to put GetMass() on the RoomAir class, and give call it with a parameter such as GetMass("Nitrogen").


text:
Q: Cambiar colores del comando ls en Linux Quisiera cambiar los colores del comando ls en mi partición de datos, ya que los directorios son poco legibles desde la consola.

Es una partición NTFS que comparto con Windows y mi archivo /etc/fstab contiene lo siguiente para la partición:
/dev/sda4 /media/datos ntfs-3g rw,defaults 0 0

A: Para cambiar el color en la terminal, debes de modificar tu archivo .bashrc.
Entras a la terminal:
nano $HOME/.bashrc

Agregas al final del archivo:
export PS1="\[$(tput setaf 1)\]\u@\h:\w $ \[$(tput sgr0)\]"

Guardas (control + o) y luego cerras (control + x). Ahora cargas tu archivo que recién cambiaste.
source ~/.bashrc

Listado de opciones:

*

*tput bold – negrita

*tput rev – colores invertidos

*tput sgr0 – Restablecer todo

*tput setaf {CODE}– Establecer foreground color, ver color {CODE}

CODE de colores:
Color {code}    Color
0   Black
1   Red
2   Green
3   Yellow
4   Blue
5   Magenta
6   Cyan
7   White

Otra forma de cambiar colores es usando LS_COLORS:
Entras a la terminal:
wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O $HOME/.dircolors
echo 'eval $(dircolors -b $HOME/.dircolors)' >> $HOME/.bashrc
. $HOME/.bashrc

Link


text:
Q: Align flex inside another flex I'm trying to create a mobile layout with a logo on the left nav in the middle and a chevron to display and hide the items of a navbar(I'm not interested in doing this functionality right now).
But right now I'm trying to achieve something like this:
+------+---------+---------+
| logo |  lorem  | chevron |
+------+---------+---------+
       | ipsum   |
       +---------+
       | dolorem |
       +---------+

I've been trying to align the first item of the ul with the icons.
Any ideas on how can I achieve this while still maintaining the html syntax?

* {
  box-sizing: border-box;
}

body {
  font-family: "IBM Plex Mono", monospace;
  font-size: 18px;
}

.main-nav {
  font-size: 24px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid red;
  height: 50px;
}

.main-nav__list {
  display: flex;
  flex: 1;
  padding: 0;
  list-style-type: none;
  border: 1px solid greenyellow;
  flex-direction: column;
  align-self: flex-start;
  position: relative;
}

.main-nav__icon {
  height: 24px;
  width: auto;
  margin: auto;
}

.main-nav__links {
  text-decoration: none;
  color: white;
}

.main-nav__list-item {
  width: 100%;
  text-align: center;
}

/*.main-nav__list-item:not(:first-child){
  display: none;
}*/

.main-nav__list-item--blue {
  background-color: #1c77c3;
}

.main-nav__list-item--green {
  background-color: #00aa00;
}

.main-nav__list-item--orange {
  background: #dd2e02;
}

.main-nav__logo {
  flex: initial;
  width: 50px;
  background-color: black;
  display: flex;
  height: 100%;
  color: white;
}

Lorem

Ipsum

dolorem

A: To your .main-nav__list, add:
/* Add margin: 0; and height: 300%; */
margin: 0;
height: 300%;

To your .main-nav__list-item. add:
/* Add flex-grow: 1; and center items */
flex-grow: 1;
display: flex;
align-items: center;
justify-content: center;

* {
  box-sizing: border-box;
}

body {
  font-family: "IBM Plex Mono", monospace;
  font-size: 18px;
}

.main-nav {
  font-size: 24px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 1px solid red;
  height: 50px;
}

.main-nav__list {
  display: flex;
  flex: 1;
  padding: 0;
  list-style-type: none;
  border: 1px solid greenyellow;
  flex-direction: column;
  align-self: flex-start;
  position: relative;
  /* Add margin: 0; and height: 300%; */
  margin: 0;
  height: 300%;
}

.main-nav__icon {
  height: 24px;
  width: auto;
  margin: auto;
}

.main-nav__links {
  text-decoration: none;
  color: white;
}

.main-nav__list-item {
  width: 100%;
  text-align: center;
  /* Add flex-grow: 1; and center items */
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

/*.main-nav__list-item:not(:first-child){
  display: none;
}*/

.main-nav__list-item--blue {
  background-color: #1c77c3;
}

.main-nav__list-item--green {
  background-color: #00aa00;
}

.main-nav__list-item--orange {
  background: #dd2e02;
}

.main-nav__logo {
  flex: initial;
  width: 50px;
  background-color: black;
  display: flex;
  height: 100%;
  color: white;
}

Lorem

Ipsum

dolorem


text:
Q: Adding new tabs to TabControl What I want to do in this example is make the first tab of the tabcontrol disappear and add 2 new tabs dynamically. The new tabs appear but their 'Header' is not showing:
            ItemCollection ic = this.tabControl1.Items;
            TabItem firstTab = (TabItem)ic[0];
            firstTab.Visibility = Visibility.Collapsed;

            TabItem newTab = new TabItem();
            newTab.HeaderTemplate = firstTab.HeaderTemplate;
            newTab.Header = newTab.Name = "test1";
            ic.Add(new TabItem());

            newTab = new TabItem();
            newTab.HeaderTemplate = firstTab.HeaderTemplate;
            newTab.Template = firstTab.Template;
            newTab.ContentTemplate = firstTab.ContentTemplate;
            newTab.Header = newTab.Name = "test2";
            ic.Add(new TabItem());

A: Replace both ic.Add(new TabItem()); by ic.Add(newTab)
Like this:
TabItem newTab = new TabItem();
newTab.HeaderTemplate = firstTab.HeaderTemplate;
newTab.Header = newTab.Name = "test1";
ic.Add(newTab);

newTab = new TabItem();
newTab.HeaderTemplate = firstTab.HeaderTemplate;
newTab.Template = firstTab.Template;
newTab.ContentTemplate = firstTab.ContentTemplate;
newTab.Header = newTab.Name = "test2";
ic.Add(newTab);


text:
Q: Do Access Control rights remain after application closes? This may be a stupid question, but I'm struggling to find an answer to this on google or on here.
If I use .NET's Directory.SetAccessControl() function in my application to set or alter certain access rights for certain users, do these access rights then remain altered when the function in which I do this goes out of scope or my application is closed?
I'm still gaining experience in lots of areas in C# and .NET programming, so again pardon if this is a silly question. It just seems that this may leave huge security holes or risks if one is able to just alter access permissions willy-nilly from code, so my feeling is that this can't be permanent.
Any hints in the right direction would be appreciated.

A: Yes, rights remain because they are applied to file system and stored on disk

A: The changes made by this (and associated calls) are permanent - so be careful.
You have to remember though that your application will need to be running under an account that has the necessary permissions to make these changes though. So ordinary users, for example, won't be able break anything - unless you make efforts to have your program impersonate another user.

A: Yes, if you change the access right you will change the ACL, these are for the whole system:

Applies access control list (ACL) entries described by a
  DirectorySecurity object to the specified directory.


text:
Q: How can I get the date format from an initialized Bootstrap datepicker? I have the following bootstrap datepicker:
<input type="dtpicker" id="abc" name="abc" value="26-05-2022">

$('input[type="dtpicker"]').datepicker({
    format: "dd/mm/yyyy",
    clearBtn: true,
    autoclose: true,
    orientation: "bottom right",
    autoUpdateInput: true
});

How can I get "format" option by code (either Javascript or jQuery)?
Generally, how can I get datepicker options?

A: $(element).data().datepicker.o.format

See How to access properties and functions of a jQuery plugin.


text:
Q: ModuleNotFoundError: No module named 'fastai.nlp' I tried to import the following modules
from fastai.nlp import *
from fastai.model import Stepper

But, I get the following error
ModuleNotFoundError: No module named 'fastai.nlp'
ModuleNotFoundError: No module named 'fastai.model'

I have already install pip install fastai.
Thanks in advance for your help.

A: The fastai library does not contain modules called stepper or model. For NLP you use the fastai.text modules, not fastai.nlp. Here's a tutorial explaining how:
https://docs.fast.ai/tutorial.text.html
Where did you find code containing the two lines you're trying to run? It's not fastai v1 or v2 code. Perhaps it's from the part2 course where something like fastai was rewritten from scratch? https://course19.fast.ai/part2. If so, you'll need to use the notebooks from there.


text:
Q: Find range of the column where the active cell is I have 1000 columns each containing 30 rows of data in excel. I want to write a Macro that will find the average of each column. I want to use Range("A31:ALL31").Value = "=AVERAGE(current column's range)"  but i don't know how to get the range of the active column. Is there a way to do that?

A: Average for Columns of a Range
Sub AverageTest()

    Const rgAddress As String = "A1:ALL30"

    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim rg As Range: Set rg = ws.Range(rgAddress)
    Dim arg As Range: Set arg = rg.Resize(1).Offset(rg.Rows.Count)
    arg.Formula = "=AVERAGE(" & rg.Columns(1).Address(, 0) & ")"

End Sub

A: Not 100% sure exactly what  you want but this code will put a formula in row 31 from column A to column ALL (that is a column), that averages the rows above starting at row 2.
    Range("A31:ALL31").FormulaR1C1 = "=AVERAGE(R2C:R[-1]C)"

Here's an example of the formula(s) that code will produce.
=AVERAGE(A$1:A30)


text:
Q: Obtaining posterior outcome probabilities Multinomial Probit given posterior parameter estimates I'm trying to compute the individual posterior probabilities from my estimated multinomial probit model. I have obtained the latent utilities as well as the posterior parameters for beta and sigma for each individual, but now I am confused how to obtain the posterior probabilities.
For the binomial probit model it seems straightforward to obtain the posterior probabilities by calculating:

E[Φ(x'beta]

for each individual, where Φ represents the cumulative normal distribution . But I don't understand how to translate this to the multinomial scenario.

A: The Multinomial's equivalent of the prior Beta distribution is the prior Dirichlet distribution.
You can think of the concentration parameters of the posterior Dirichlet as essentially a vector of posterior 'Beta-ish' probabilities of each corresponding class, so you can apply the same procedure you're already familiar with.


text:
Q: PHP Action each function preforms I have the following situation.
I have a class with a lot of functions. Each function starts with executing the same method. Is there a way that I can like implement this method into the function so that it is executed automatically?
Here is an example:
class test
{
 static function_1($param) {some_method($param); other stuff....}
 static function_2($param) {some_method($param); other stuff then function 1....}
 static function_3($param) {some_method($param); other stuff then function 1 and function 2....}
}

So is there a way to execute some_method(); automaticly without declaring it in each function?
Thanks in advance!
Whole code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * The Assets Library
 *
 * This class let's you add assets (javascripts, stylesheets and images) way easier..
 */

class Assets {
    private $css_url;
    private $js_url;
    private $img_url;

    public function __construct()
    {
        $CI =& get_instance();
        $CI->config->load('assets');

        $asset_url = base_url() . $CI->config->item('assets_dir');
        $this->css_url = $asset_url . $CI->config->item('css_dir_name');
        $this->js_url = $asset_url . $CI->config->item('js_dir_name');
        $this->img_url = $asset_url . $CI->config->item('img_dir_name');
    }

    // Returns the css html link
    public function css_html_link($filename)
    {
        // Check whether or not a filetype was given
        $filename = $this->_add_filetype($filename, 'css');

        $link = '<link type="text/css" rel="stylesheet" href="' . $this->css_url . $filename . '" />';
        return $link;
    }

    // Returns the css link
    public function css_link($filename)
    {
        $filename = $this->_add_filetype($filename, 'css');

        return $this->css_url . $filename;
    }

    // Returns the js html link
    public function js_html_link($filename)
    {
        $filename = $this->_add_filetype($filename, 'js');

        $script = '<script type="text/javascript" src="' . $this->js_url . $filename . '"></script>';
        return $script;
    }

    // Return the js link
    public function js_link($filename)
    {
        $filename = $this->_add_filetype($filename, 'js');

        return $this->js_url . $filename;
    }

    // Returns the image html tag
    public function img_html_link($filename, $rel = NULL)
    {
        // Get the filename without the filetype
        $alt_text = substr($filename, 0, strpos($filename, '.')+1);
        $alt_text = 'alt="'.$alt_text.'"';

        // If relation is giving, use it
        $img_rel = ($rel !== FALSE) ? 'rel="' . $rel . '"' : '';

        $image = '<img src="' . $this->img_url . $filename . '" '.$rel.' ' . $alt_text . '/>';
        return $image;
    }

    // Return the image link
    public function img_link($filename)
    {
        return $this->img_url . $filename;
    }

    // Check whether or not a filetype was specified in $file, if not, it will be added
    private function _add_filetype($file, $type)
    {
        if(strpos($file, '.' . $type) === FALSE)
        {
            $file = $file . '.' . $type;
        }
        return $file;
    }
}

/* End of file assets.php */
/* Location: ./application/libraries/assets.php */

A: every time you initiate the class, it calls the __construct() function, or in PHP 4 (I hope you are not using php 4) it uses the function with the same name as the class
If you do this, it should work for every initiate of the class:
function __construct($param){
    some_method($param);
}

if you call multiple functions in the same initiation of the class, you could do this:
var $param;

function __construct($param){
    $this->param = $param;
}

function doMethod(){
    some_method($this->param);
}

function function_1()
{
    $this->doMethod();
}

Calling the class multiple times, with different params. Perhaps try this approach:
function __call($function, $param){
    some_method($param);
    switch ($function){
         case 'function1':
         $this->function1($param);
         break;
         /// etc..
    }
}

A: I'm afraid that in this case the answer is 'no'.
You're not 'declaring' some_method() each time, you are calling it. If you don't call it, it can't run, so you have to call it each time.
Cut & paste.....
Why not paste your actual code here, some refactoring may help.
Edit after seeing actual code
I can't see the problem with your existing code. It is clear and you will know what it does in a year's time. I would keep it as it is. The answer you accepted will work, but it is obfuscating your code. You will have problems working out what you did and why you did it in when you come back to maintain your code in the future.

A: You could create a class containing an instance of the class test (composition) and implement its __call magic method. Something akin to:
class testWrapper
{
    private $test;

    function __construct()
    {
        $this->test = new Test();
    }

    function __call($name, $args)
    {
        call_user_func_array(array($this->test, 'some_method'), $args);
        call_user_func_array(array($this->test, $name), $args);
    }
}

You then call methods from the test class on the instance object of testWrapper.
You can further refine the logic in the __call method to only call some_method() based on the passed-in method name, etc.


text:
Q: How to reference a struct instance method How can I reference a method from an instance instead of the full type.
It is easy that having any type that implements a function, you can access the method with MyStruct::the_method.
But how to do the same with an instance of it?
I got the following example (playground):
struct NumGen<N> {
    num: N
}

impl<N: Copy> NumGen<N> {
    fn new(n: N) -> Self {
        Self {
            num: n,
        }
    }

    fn get_num(&self) -> N {
        self.num
    }
}

fn print_num_from_other_func<F>(mut f: F) where F: FnMut() -> u32 {
    println!("{}", f());
}

fn main() {
    print_num_from_other_func(|| 10);
    let num_gen = NumGen::new(10);
    print_num_from_other_func(|| num_gen.get_num());
    // this part doesn't work
    // print_num_from_other_func(num_gen::get_num);
}


text:
Q: Handling data deletion in spring data jpa pagination? I have a method like the below.
  public List<ResponseDto> getChanges();

This service returns the result, but it is a stateful method because calling another service A, affects the result of getChangedAccounts() method. For example, I have 30 items in my list, in the normal situation (when the client does not call service A) this method works fine (page number 1 up to 3, with page size 10), but the problem is when the client call service A because it changes the status of entities and that changed record does not return in getChangedAccounts(). So in this scenario for example the first bunch (page no=1 page size=10) has been changed during service A and currently, I have 20 records, so when the client calls (page no=3 page size=10) there is no result, is there any way to keep the page no order but return previous data?
I know about hasPrevious(), but I don't exactly what should I do.
Page<Entity> changedEntities = repository.findChanges(paramA, paramB, pageable);
        if (ObjectUtils.isEmpty(changedEntities) || ObjectUtils.isEmpty(changedEntities.getContent())) {
            if (changedEntities.getTotalElements() == 0)
                throw new NotFoundException("Not found any changes!");
            else {
                while (changedEntities.hasPrevious()){
                    Pageable pageable1 = changedEntities.previousPageable();
                }
            }
        }

 PageImpl<ResponseDto> responseDtoPage = new PageImpl<>(changedEntities.getContent()
                .stream()
                .map(ce-> new ResponseDto(ce.getMessageId(), ce.getAccountNumber()))
                .collect(Collectors.toList())
        );


text:
Q: Create a href url with php variable + javascript variable I'm creating links with Mysql+PHP looping, but I need to add a javascript var into url href, like:
The javascript var is in a jquery cookie: $.cookie('limit')
urls.php:
1
2
3

Put the javascript var into a hidden input doesn't work on this case.
In my page.php I need to use both vars (id and limit) on a mysql query. So insert this javascript var in a hidden input in page.php won't work anyway.
I tried to remove limit var from href url and add this on my page.php but it didn't work:
if(!empty($_REQUEST['limit']){
    $_REQUEST['limit'] = "";
}

A: You did not put the variable correctly into php. With your code you just wrote limit inside a string. You need to connect variable to a string like this:
if(!empty($_REQUEST['limit']){
    $limit = "";
}

A: If the limit's being passed into the page that you're constructing links on, then you could grab that number through the $_REQUEST variable like you mentioned.  You could then write a for loop in the logic in that page to create the number of links that you want.  In that loop you could construct something like this to echo the url onto the page:
echo "{$i}"

A: Change links to this:
1
2
3

Add a javascript like this:
$(document).ready(function(){
    $('a[class="changeMe"]').each(function(){
        var newHref = $(this).attr("href") +"&limit="+ $.cookie('limit');
        $(this).attr("href", newHref);
    });
});


text:
Q: Stream not rebuilding the widget I'm trying to put a very simple project together. Aim here is to fetch some data from the HackerNews API and show it to the user. The code was working perfectly until I introduced the functionality to fetch each item from the top_ids list. I tried debugging it and I don't see any error whatsoever. However, I'm still not getting the required output (which is to fetch each item from the top_ids list)
news_list_screen
Widget buildList(StoriesBloc storiesBloc) {
    return StreamBuilder(
      stream: storiesBloc.topIds,
      builder: (context, AsyncSnapshot<List<int>> snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
        return ListView.builder(
          itemCount: snapshot.data!.length,
          itemBuilder: (context, int index) {
            storiesBloc.fetchItem(snapshot.data![index]);
            return NewsListTile(
              itemId: snapshot.data![index],
            );
          },
        );
      },
    );
  }
}

class NewsListTile extends StatelessWidget {
  final int itemId;
  NewsListTile({required this.itemId});
  Widget build(BuildContext context) {
    final bloc = StoriesBlocProvider.of(context);
    return StreamBuilder(
      stream: bloc.items,
      builder: (context, AsyncSnapshot<Map<int, Future<ItemModel>>> snapshot) {
        if (!snapshot.hasData) {
          return Text('Fetching item');
        }
        return FutureBuilder(
          future: snapshot.data![itemId],
          builder: (context, AsyncSnapshot<ItemModel> itemSnapshot) {
            if (!itemSnapshot.hasData) {
          //This gets populated with the correct ids
              return Text('Still loading item $itemId');
            }
            return Text(itemSnapshot.data!.title);
          },
        );
      },
    );
  }
}

stories_bloc
class StoriesBloc {
  final _newsRepository = NewsRepository();

  final _topIds = PublishSubject<List<int>>();
  final _itemsOutput = BehaviorSubject<Map<int, Future<ItemModel>>>();
  final _itemsFetcher = PublishSubject<int>();

  Stream<List<int>> get topIds => _topIds.stream;
  Stream<Map<int, Future<ItemModel>>> get items => _itemsOutput.stream;

  Function(int) get fetchItem => _itemsFetcher.sink.add;

  StoriesBloc() {
    _itemsFetcher.stream.transform(_itemsTransformer()).pipe(_itemsOutput);
  }

  fetchTopIds() async {
    final ids = await _newsRepository.fetchTopIds();
    _topIds.sink.add(ids);
  }

  _itemsTransformer() {
    return ScanStreamTransformer(
      (Map<int, Future<ItemModel>> cache, int id, index) {
        cache[id] = _newsRepository.fetchItem(id);
        return cache;
      },
      <int, Future<ItemModel>>{},
    );
  }

  dispose() {
    //code
  }
}

news_repository
class NewsRepository {
  List<Source> sources = <Source>[
    newsDbProvider,
    NewsApiProvider(),
  ];

  List<Cache> caches = <Cache>[
    newsDbProvider,
  ];

  Future<List<int>> fetchTopIds() async {
    late List<int> ids;
    Source source;

    for (source in sources) {
      ids = await source.fetchTopIds();
      if (ids.isNotEmpty) {
        break;
      }
    }

    return ids;
  }

  Future<ItemModel> fetchItem(int id) async {
    print('itemID to be fetched inside repo - $id');
    ItemModel? item;
    var source;
    Cache cache;

    for (source in sources) {
      item = await source.fetchItem(id);
      if (item != null) {
        break;
      }
    }

    for (cache in caches) {
      if (cache != source){
        cache.addItem(item!);
      }
    }
    return item;
  }
}

news_api_provider
class NewsApiProvider implements Source {
  Client client = Client();

  Future<List<int>> fetchTopIds() async {
    final response = await client.get(Uri.parse('$_root/topstories.json'));
    final parsedJsonIds = json.decode(response.body);
    return parsedJsonIds.cast<int>();
  }

  Future<ItemModel> fetchItem(int id) async {
    print('Inside API provider. Tryna fetch $id');
    final response = await client.get(Uri.parse('$_root/item/$id.json'));
    print('Status Code' + response.statusCode.toString());
    print(response.body);
    final parsedJsonItem = json.decode(response.body);
    final itemModel = ItemModel.fromJson(parsedJsonItem);
    return itemModel;
  }
}

Now, the interesting part is that I do see "Still loading the item - itemID" on the screen but It never resolves, as If my FutureBuilder never receives any data. However, during the debugging I was able to see that my api is indeed working and even the cache map in the streamTransformer is getting populated as well.
I'm still unable to understand why the data is not flowing from the streamTransformer to my itemsOutput stream which is actually responsible for showing this data.
I'm trying so hard to get this working and have checked my code millions of times. I would really appreciate if you could help me resolve this. Thanks in advance!

A: Okay. So it looks like - though the api is sending in some ids for the top posts but those ids do not exist when we fetch them through the api (using fetchItem method). Therefore the ItemModel was unable to work upon such requests which caused the error.
This is how I solved it ->
ItemModel.fromJson(Map<String, dynamic> parsedJson)
      : id = parsedJson['id'] ?? 0,
        deleted = parsedJson['deleted'] ?? false,
        type = parsedJson['type'] ?? '',
        by = parsedJson['by'] ?? '',
        time = parsedJson['time'] ?? 0,
        text = parsedJson['text'] ?? '',
        dead = parsedJson['dead'] ?? false,
        parent = parsedJson['parent'] ?? 0,
        kids = parsedJson['kids'] ?? [],
        url = parsedJson['url'] ?? '',
        score = parsedJson['score'] ?? 0,
        title = parsedJson['title'] ?? 'Did not find',
        descendants = parsedJson['descendants'] ?? 0;


text:
Q: JQUery Hide DIV clicking outside the DIV Let's assume i have the following control :

            <asp:Label ID="lblSL" CssClass="lblSL" runat="server">Clickable Label</asp:Label>

            This is the hidden content of my DIV Window

By default the wndSL has
style= " display:none;     background-color: blue;    height:500px;    width:590px;"
I am able to show the wndSL when I click either slControlLabel or slControlDropDown.
However I also need to hide it when I click either on the slControlLabel or slControlDropDown or anywhere outside the wndSL outside .
Can anyone help me how to figure out how to hide it, clicking anywhere outside my wndSL.
This is what I have so far... and I need to add the piece to hide it whenever i click outside the window
Thanks
 $('.slControlLabel, .slControlDropDown').bind('click',function(event){
       alert('This will open the wndSL');
       $('#wndSL').show();
 });

New Problem Revision 2
Here is the DIV i have now and as you will see I have more controls in there... so the origiinal answer does not work anymore because, when I click on the control within the DIV, it still closes the DIV.... So although my original request was to close when you click outside the DIV works , when i addded controls within the DIV, my condition to hide does not work... How can I tweak it so that anything within the DIV when clicked will not close the window (except the close button icoRedX.gif on the header )
This is my control

            Select a Saved Shopping List

            <input id="ctl00_phContent_DynamicUserControl_Step_1_btClose_ClientState" name="ctl00_phContent_DynamicUserControl_Step_1_btClose_ClientState" type="hidden" autocomplete="off">

            Select a saved Shopping List to open. The list you already have open will be automatically  saved

                                <colgroup>
                                <col>
                                <col>
                                <col>
                                <col>
                                </colgroup>

                                <input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl04$gbcSelectColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl04_gbcSelectColumn" src="../Images/btSelectCharcoal.gif" style="border-width:0px;">
                                Master Shopping List

                                 Updated August 10, 2011
                                	16 items	<input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl04$gbcDeleteColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl04_gbcDeleteColumn" src="../Images/icoDeleteRedX.gif" onclick="if(!confirm('Are you sure you want to delete this list ?'))return false;" style="border-width:0px;">

                                <input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl06$gbcSelectColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl06_gbcSelectColumn" src="../Images/btSelectCharcoal.gif" style="border-width:0px;">
                                Audrey's Birthday Party

                                Shopped August 2, 2011 for $49.11
                                	11 items	<input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl06$gbcDeleteColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl06_gbcDeleteColumn" src="../Images/icoDeleteRedX.gif" onclick="if(!confirm('Are you sure you want to delete this list ?'))return false;" style="border-width:0px;">

                                <input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl08$gbcSelectColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl08_gbcSelectColumn" src="../Images/btSelectCharcoal.gif" style="border-width:0px;">
                                Monthly Household Supplies

                                Updated February 22, 2011
                                	8 items	<input type="image" name="ctl00$phContent$DynamicUserControl_Step_1$grdTemplateShoppingList$ctl00$ctl08$gbcDeleteColumn" id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ctl00_ctl08_gbcDeleteColumn" src="../Images/icoDeleteRedX.gif" onclick="if(!confirm('Are you sure you want to delete this list ?'))return false;" style="border-width:0px;">

                                <input id="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ClientState" name="ctl00_phContent_DynamicUserControl_Step_1_grdTemplateShoppingList_ClientState" type="hidden" autocomplete="off">

This is the JS
function OnPageLoad(){
window.$ = $telerik.$;
var t;
$(document).ready(function () {
$('.slControlLabel, .slControlDropDown').bind('click',function(event){
    $('#wndShoppingList').show();
    event.stopPropagation();
});

// OnClick Event outside the wndShoppinglist.
// $('html').click(function(event){  Tried  this as well
if((event.target.id != 'wndShoppingList')){  // This used to work but after adding controls in the DIV, this returns the ID of the controls within the DIV
     alert('click on body '+ event.target.id)
     alert('about to hide')
     $('#wndShoppingList').hide();
});

});   //End $(document).ready()
}
Sys.Application.add_load(OnPageLoad);

A: Bind a click event to html to capture any click made, and make it hide the #wndSL
$("html").click(function() {
    $("#wndSL").hide();
});

Then override that on your #wndSL's click event using .stopPropagation();
$("#wndSL").click(function (event) {
  event.stopPropagation();
});

A: You need to use
event.stopPropagation();

Html

            <asp:Label ID="lblSL" CssClass="lblSL" runat="server">Clickable Label</asp:Label>

            This is the hidden content of my DIV Window

        I am for test click on me

CSS
#wndSL {

display:none;     background-color: blue;    height:500px;    width:590px;
}

Jquery
$('.slControlLabel, .slControlDropDown').bind('click',function(event){
       alert('This will open the wndSL');
       $('#wndSL').show();
     event.stopPropagation();
 });

$('html').click(function() {
   $('#wndSL').hide();
});

And here is Demo

A: $("body").click
(
  function(e)
  {
    if(e.target.id != "wndSL")
    {
      $("#wndSL").hide();
    }
  }
);


text:
Q: Dash dcc.DatePickerRange Colors I'm trying to style a Dash date picker and am having trouble identifying the appropriate classes.
So far I have
.CalendarDay__selected,
.CalendarDay__selected:active,
.CalendarDay__selected:hover {
  background: gold;
  border: 1px double black;
  color: #fff
}

.CalendarDay__selected_span {
  background: #a17f1a;
  border: 1px double #black;
  color: #fff
}

which modifies what I think are the default plotly classes.
However there are lots of hover, border, active, etc. properties which aren't affected by these, so the default blueish color remains.
Does anyone know how to change the overall color scheme with minimal css please? Or perhaps by some property on the dcc.DatePickerRange component itself?


text:
Q: Linear model/lmList with nested/multiple group categories? I am trying to build a model for monthly energy consumption based on weather, grouped by location (there are ~1100) AND year (I would like to do it from 2011-2014). The data is called factin and looks like this:
Store   Month      Days UPD     HD      CD      Year
1   August, 2013    31  6478.27 0.06    10.03   2013
1   September, 2013 30  6015.38 0.50    5.67    2013
1   October, 2013   31  5478.21 5.29    1.48    2013
1   November, 2013  30  5223.78 18.60   0.00    2013
1   December, 2013  31  5115.80 20.52   0.23    2013
6   January, 2011   31  4517.56 27.45   0.00    2011
6   February, 2011  28  4116.07 16.75   0.07    2011
6   March, 2011     31  3981.78 12.68   0.39    2011
6   April, 2011     30  4041.68 3.83    2.53    2011
6   May, 2011       31  4287.23 1.61    6.58    2011

And my model code, which just spits out 1 set of coefficients for all the years of each store, looks like this:
factout <- lmList(UPD ~ HD + CD | Store, factin)

My question is: is there any way I can get coefficients for each store AND year without creating a separate data frame for each year?

A:      dat <- read.table(header = T, stringsAsFactors = F, text = "Store   Month year     Days UPD     HD      CD      Year
                  1   August 2013    31  6478.27 0.06    10.03   2013
                  1   September 2013 30  6015.38 0.50    5.67    2013
                  1   October 2013   31  5478.21 5.29    1.48    2013
                  1   November 2013  30  5223.78 18.60   0.00    2013
                  1   December 2013  31  5115.80 20.52   0.23    2013
                  6   January 2011   31  4517.56 27.45   0.00    2011
                  6   February 2011  28  4116.07 16.75   0.07    2011
                  6   March 2011     31  3981.78 12.68   0.39    2011
                  6   April 2011     30  4041.68 3.83    2.53    2011
                  6   May 2011       31  4287.23 1.61    6.58    2011")

factout <- lmList(UPD ~ HD + CD | Store, dat)

data.frame(Store = unique(dat$Store), summary(factout)$coef[1:2,1,1:3])

  (Intercept)        HD       CD
1    5405.108 -12.90986 107.2061
6    3581.307  32.93137 102.9780