text:
Q: How to get the QoS of a client in HiveMQ Client? I'm working with HiveMQ Client and I wanted to know if there was a way to get the quality of service (QoS) that a client is subscribing with (in terms of a specific topic or in general)? I would be looking for a method I could invoke on a client like so:
    Mqtt5BlockingClient subscriber = Mqtt5Client.builder()
            .identifier(UUID.randomUUID().toString()) // the unique identifier of the MQTT client
            .serverHost("localhost")
            .serverPort(1883)
            .buildBlocking();

subscriber.getQoS("topic") // returns the QoS of the subscriber is subscribing to the given topic

I would just want this information so I could print in to the console.

A: I think you have to read more about MQTT concepts.
The Quality of Service (QoS) level is an agreement between a sender and receiver of a message regarding the guarantees of delivering a message.
Therefore, the QoS is used in the publish() and subscribe() methods not the connect().
This is the scenario:
1. Connect: You have to connect your client to any broker with username/password. Every mqtt library has a connect() method. In this step, you have not specified qos yet.
After successful connection (every mqtt library has a callback for the connect method) and you can publish or subscribe to any desired (or allowed) topics.
Example:
Eclipse Paho library:
IMqttToken token = clientPhone.connect();

HiveMQ Library:
client.connect();
//or
client.connectWith().keepAlive(10).send();
//or
Mqtt5Connect connectMessage = Mqtt5Connect.builder().keepAlive(10).build();
client.connect(connectMessage);

2. Publish:
When you want to publish() a message, you have to specify a qos, so that the broker will respond to the client according with this qos:
Qos=0:
Client  ---- Publish method ----> broker
Qos=1:
Client  ---- Publish method  ----> broker
Client <---- PubAck callback ----  broker
Qos=2:
Client  ---- Publish method   ----> broker
Client <---- PubRec callback  ----  broker
Client  ---- PubRel method    ----> broker
Client <---- PubComp callback ----  broker

Example:
Eclipse Paho library:
IMqttDeliveryToken tokenPub = clientPhone.publish(topicPub, message);

HiveMQ Library:
client.publishWith()
        .topic("test/topic")
        .qos(MqttQos.AT_LEAST_ONCE)
        .payload("payload".getBytes())
        .send();
//or:
Mqtt5Publish publishMessage = Mqtt5Publish.builder()
        .topic("test/topic")
        .qos(MqttQos.AT_LEAST_ONCE)
        .payload("payload".getBytes())
        .build();
client.publish(publishMessage);

3. Subscribe:
A SUBSCRIBE message can contain an arbitrary number of subscriptions for a client. Each subscription is a pair of a topic and QoS level. The topic in the subscribe message can also contain wildcards, which makes it possible to subscribe to certain topic patterns. If there are overlapping subscriptions for one client, the highest QoS level for that topic wins and will be used by the broker for delivering the message.
Example:
Eclipse Paho library:
IMqttToken subToken = MqttAndroidClientInstance.subscribe(topics, qos);

HiveMQ Library:
client.subscribeWith().topicFilter("test/topic").qos(MqttQos.EXACTLY_ONCE).send();
//or:
Mqtt5Subscribe subscribeMessage = Mqtt5Subscribe.builder()
        .topicFilter("test/topic")
        .qos(MqttQos.EXACTLY_ONCE)
        .build();
client.subscribe(subscribeMessage);

Edit(1):
A mqtt client have to use the following parameters, if wants to receive the already subscribed topics after reconnecting:
A- connect with cleanSession false.
B- Subscribe with QOS>0.


text:
Q: Disk information Pane in Disk Utility is Black in LXDE When I open Disk Utility, and click on one of the drives, the information (right)pane is black.  Any ideas?
Thanks

A: Well, I found out its a bug See Here
Even in the bug description it suggests a solution, changing the widget style to .... but that did not work for me.  What I have done is change the widget to Ambiance, and that fixed it, although it changed the look. Hopefully this bug will be fixed soon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making a full page div with a navbar in TailwindCSS I'm using Tailwind CSS and I would like to achieve a layout which includes:

*

*A sticky navbar

*A full-page section with centered content

*Other sections with variable height

*A footer

Here's a quick representation:
+--------------------------+    -+
|  Navbar (sticky)         |     |
|--------------------------|     |
|                          |     |
|                          |     | --> this has viewport height
|    centered content      |     |
|                          |     |
|                          |     |
|--------------------------|    -+
|                          |
| Section 1                |
|                          |
+--------------------------+
| Section 2                |
+--------------------------+
| Footer                   |
+--------------------------+

I would like the centered content section to take up all the remaining space of the viewport after the navbar, but applying the h-screen class causes it to be as height as the viewport causing an overflow. Here's some reproducible code:
<!doctype html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

      Menu

      content

      content

      footer

Can someone help me to find a way to make the "centered content" section take up all the remaining space while letting the other, following, sections have an arbitrary height.
Thank you.

A: There is 2 solutions for your layout.
You can add negative margin bottom to sticky navbar -mb-20

  Menu

or you can change you navbar position to fixed

  Menu

Hope this helps.


text:
Q: Angular 2: 'ngFormModel' since it isn't a known native property
My error is

 EXCEPTION: Error: Uncaught (in promise): Template parse errors:
Can't bind to 'ngFormModel' since it isn't a known native property ("

MY PROFILE

<form  [ERROR ->][ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">

"): a@3:7
There is no directive with "exportAs" set to "ngForm" ("stname
        <input type="text" id="facebook" class="form-control"  ngControl="firstname" [ERROR ->]#firstname="ngForm" >

"): a@9:85
There is no directive with "exportAs" set to "ngForm" ("/label>
        <input type="text" id="facebook" class="form-control col-xs-3" ngControl="lastname" [ERROR ->]#lastname="ngForm" >

My template,

MY PROFILE

<form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">

            firstname
            <input type="text" id="facebook" class="form-control" ngControl="firstname" #firstname="ngForm">

                First name is required

            lastname
            <input type="text" id="facebook" class="form-control col-xs-3" ngControl="lastname" #lastname="ngForm">

                Last name is required

            Profilename
            <input type="text" id="facebook" class="form-control col-xs-3" ngControl="profilename" #profilename="ngForm">

            Phone
            <input type="text" id="facebook" class="form-control col-xs-3" ngControl="phone" #phone="ngForm">

                Phone number is required

        Image
        <input type="file" name="fileupload" ngControl="phone">

            <button type="submit" class="btn btn-primary  " [disabled]="!form.valid">Save</button>

</form>

My Component

import {Component} from '@angular/core';
import { Http, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {contentHeaders} from '../headers/headers';
import {FORM_DIRECTIVES} from '@angular/forms';
import {Router, ROUTER_DIRECTIVES} from '@angular/router';
import {Control, FormBuilder, ControlGroup, Validators} from '@angular/common';

@Component({
    templateUrl: './components/profile/profile.html',
    directives: [ROUTER_DIRECTIVES, FORM_DIRECTIVES],
})

export class Profile {

    http: Http;

    form: ControlGroup;

    constructor(fbld: FormBuilder, http: Http, public router: Router) {
        this.http = http;
        this.form = fbld.group({
            firstname: ['', Validators.required],
            lastname: ['', Validators.required],
            profilename: ['', Validators.required],
            image: [''],
            phone: [''],

        });

    }

    onSubmit(form: any) {

        console.log(form);
        let body = JSON.stringify(form);
        var headers = new Headers();
        this.http.post('http://localhost/angular/index.php/profile/addprofile', body, {
                headers: headers
            })
            .subscribe(
                response => {
                    if (response.json().error_code == 0) {
                        alert('added successfully');
                        this.router.navigate(['/demo/professional']);
                    } else {
                        alert('fail');

                    }

                });
    }

}

A: The problem is that you're still importing from common and especially using the instructions of the old forms.
Import correctly the components for new forms:
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

And correct the component:
@Component({
    ...
    directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES]
})
export class AppComponent {

    form: FormGroup;

    constructor(fbld: FormBuilder) {

        this.form = fbld.group({
            ...

        });

    }

    ...

}

Then correct the view: ngFormModel has been replaced by formGroup, and use formControl for your fields:
<form  [formGroup]="form" (ngSubmit)="onSubmit(form.value)">

            firstname
            <input type="text" id="facebook" class="form-control" [formControl]="form.controls['firstname']" >

            First name is required

        ...

            <button type="submit" class="btn btn-primary" [disabled]="!form.valid">Save</button>

</form>

Edit. From Angular 2.0.0-rc.5, is necessary to remove the directives from the component and import the form modules in AppModule:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    imports: [
        ...
        FormsModule,
        ReactiveFormsModule
    ],
    ...
    bootstrap: [AppComponent]
})

export class AppModule { }

If you use a shared module, do not forget to export them:
@NgModule({
    imports: [
        ...
        FormsModule,
        ReactiveFormsModule
    ],
    exports: [
        ...
        FormsModule,
        ReactiveFormsModule
    ]
})

export class SharedModule { }

A: I had the same issue. What I did to solve it:

*

*remove the  tag, and add (click)-function to the button

*checked my backend: there was an error in some special event... fixed it

Now it doesn't fire twice anymore.
So double check this! You never know...

A: Just import the following statement in ts,
import {FORM_DIRECTIVES, FormBuilder, Validators, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
directives: [CORE_DIRECTIVES, ROUTER_DIRECTIVES, FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES],

Make the following changes in templates,

MY PROFILE

 <form  [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">

     firstname
   <input type="text" id="facebook" class="form-control"   [formControl]="form.controls['firstname']">

       First name is required

lastname
<input type="text" id="facebook" class="form-control col-xs-3" [formControl]="form.controls['lastname']">

         Last name is required

   Profilename
    <input type="text" id="facebook" class="form-control col-xs-3" [formControl]="form.controls['profilename']" >

  Phone
   <input type="text" id="facebook" class="form-control col-xs-3" [formControl]="form.controls['phone']">

        Phone number is required

<button type="submit" class="btn btn-primary  "    [disabled]="!form.valid">Save</button>

Finally do this in your bootstrapping,
import {provideForms, disableDeprecatedForms} from '@angular/forms';
bootstrap(MyDemoApp, [
provideForms(),
disableDeprecatedForms()]);


text:
Q: Powershell's Start-Transcript cmdlet is not logging the console output of the executable ssh-keyscan from the Git family I am executing the ssh-keyscan command in a PowerShell script to update the SSH known hosts file on my Windows system.
Environment details:
PowerShell:5.1.18362.752
Operating system: Windows 10 x64 1903(OSBuild 18362.1082)
Language: English

My code is as follows:
Start-Transcript -Path C:\Windows\temp\abc.log
$sshKnownHostFile = "$Env:USERPROFILE\.ssh\known_hosts"
$cmd = "ssh-keyscan -p 7000 blah.net | Out-File -Encoding ASCII $sshKnownHostFile -Append"
Invoke-Expression $cmd -Verbose
Stop-Transcript

The problem I am experiencing is that, no matter what I try, the console output of ssh-keyscan is not captured in the transcript file. All that's captured in the transcript file is the following:
**********************
Windows PowerShell transcript start
Start time: 20201008201659
Username: DESKTOP-NIFKPBT\kiranh
RunAs User: DESKTOP-NIFKPBT\kiranh
Configuration Name:
Machine: DESKTOP-NIFKPBT (Microsoft Windows NT 10.0.18362.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 1280
PSVersion: 5.1.18362.752
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.18362.752
BuildVersion: 10.0.18362.752
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is C:\Windows\temp\abc.log
**********************
Windows PowerShell transcript end
End time: 20201008201707
**********************

I have attempted the following to resolve the issue:

*

*Invoke-Expression $cmd -Verbose | Out-Default
This was as per the suggestion at: https://github.com/PowerShell/PowerShell/issues/10994#issuecomment-550528523

*Invoke-Expression $cmd -Verbose | Out-Host
This was the suggestion at: https://github.com/PowerShell/PowerShell/issues/10994#issuecomment-596132121

*[System.Environment]::SetEnvironmentVariable("GIT_REDIRECT_STDERR", "2>&1", "User")
This was as per this response. The above answer was for Git. Since ssh-keyscan.exe is from the Git family of utilities, I tried using the same to see if my issue would be resolved.

*Use of Start-Process cmdlet to invoke ssh-keyscan.exe

*Directly invoking ssh-keyscan.exe in the PowerShell script, just like an external program is executed on the command prompt.
None of the above have really helped. The output captured in the transcript log is the same in all of the above cases.
How can I get this working?

A: As I commented, ssh-keyscan output shows up in the log just fine. Here are the commands I ran and the sanitized output.
Start-Transcript .\transcript.txt
ssh-keyscan linuxhost
$PSVersionTable

As you can see below, the transcript contains the output from ssh-keyscan as well as $PSVersionTable
Machine: DESKTOP-NEKK74J (Microsoft Windows NT 10.0.19041.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 8692
PSVersion: 5.1.19041.546
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.19041.546
BuildVersion: 10.0.19041.546
CLRVersion: 4.0.30319.42000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
Transcript started, output file is .\transcript.txt
PS C:\TEMP> ssh-keyscan.exe linuxhost
# linuxhost:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
linuxhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQ
# linuxhost:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
linuxhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItb
# linuxhost:22 SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
linuxhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOGy3M1
PS C:\TEMP> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.19041.546
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.546
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Running your commands, I see all the commands typed in the transcript as well.
Transcript started, output file is .\transcript.txt
PS C:\TEMP> $sshhostfile = "$env:USERPROFILE\.ssh\known_hosts"
PS C:\TEMP> $cmd = "ssh-keyscan linuxhost | Out-File -Encoding ASCII $sshhostfile -Append"
PS C:\TEMP> Invoke-Expression $cmd -Verbose
PS C:\TEMP> Stop-Transcript

I have no clue why your commands wouldn't be listed. I'd run them again just to be sure. If you're expecting to see the output that you're redirecting to the file, only what is shown in the console may be captured. If you're wanting the output to go to both a log file and the transcript, perhaps these changes to your commands will help
$cmd = {ssh-keyscan -p 7000 blah.net}
& $cmd | Tee-Object -FilePath $sshhostfile -Append

Now the transcript and the log have this output.
Transcript started, output file is .\transcript.txt
PS C:\TEMP> $cmd = {ssh-keyscan linuxhost}
PS C:\TEMP> & $cmd | Tee-Object -FilePath $sshhostfile
linuxhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCgoqTpOufcs
linuxhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyN
linuxhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOGy3M1StlLMI
PS C:\TEMP> Stop-Transcript


text:
Q: c# Invalid operation in several threads:Cross-thread operation not valid I want to change position of my coursor but it returns error. Please help me change my code. I read about Invoke but I don't know how to use as I am a beginner to c#.
Thank you!
namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        System.Timers.Timer myTimer = new System.Timers.Timer();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myTimer.Elapsed += new ElapsedEventHandler( DisplayTimeEvent );
            myTimer.Interval = 1000;
            myTimer.Start();
        }

       public  void DisplayTimeEvent( object source, ElapsedEventArgs e )
       {
            MoveCursor();
       }

       private void MoveCursor()
       {
            this.Cursor = new Cursor(Cursor.Current.Handle);
            Cursor.Position = new Point(Cursor.Position.X - 10, Cursor.Position.Y - 10);
       }
    }
}

A: This is a server timer which fires its timer events away from the UI thread. Which causes the problem you observe because you must interact with UI on the main UI thread.
You need a UI timer which will fire its timer events on the main UI thread. For instance: System.Windows.Forms.Timer.

A: for your case you may try this
namespace WindowsFormsApplication8
{
 public partial class Form1 : Form
 {
    System.Timers.Timer myTimer = new System.Timers.Timer();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        myTimer.Tick += myTimer_Tick;
        myTimer.Interval = 1000;
        myTimer.Start();
    }

    void myTimer_Tick(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(5000); // 5000 is 5 seconds. i.e. after 5 seconds i am changing the cursor position.
        MoveCursor();
    }

    private void MoveCursor()
    {
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = new Point(Cursor.Position.X - 10, Cursor.Position.Y - 10);
    }
 }
}

A: In WPF it is :
A) change your timer to : DispatcherTimer - with this Timer you can change in the tick event gui elements
B)
Call your "MoveMouse" in the GUI Thread
 this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    MoveMouse();
                }));

Heres a useful link FOR WINFORMS:
http://blog.altair-iv.com/2013/02/ui-access-from-background-thread-in.html


text:
Q: Navigationbar is positioned below the hidden statusbar coming from a TableView, I am creating an MKMapView. I want to have more screen real estate, so I hide the status bar und set the navigation bar to transluscent.
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.translucent = NO;

Unfortunaltely the navigation bar is positioned below the hidden status bar (see picture).

I already found out that this might help, since one can perform kind of a reload of the bar in the main event loop:
[self performSelector:@selector(setNavigationController:YES) withObject:nil afterDelay:0.1];

But this doesn't work so far. Any hint?
Thanks in advance.

A: Okay, I found out what to do:
[self performSelector:@selector(setNavigationController:NO) withObject:nil afterDelay:0.1];
[self performSelector:@selector(setNavigationController:YES) withObject:nil afterDelay:0.1];

This switches the navigation bar off and on again, which forces it to redraw in the correct position.

A: I use this in iOS 6:
self.navigationController.navigationBarHidden = YES;
self.navigationController.navigationBarHidden = NO;


text:
Q: Why isn't my UIButton responding to touches? I'm sure I'm overlooking the obvious as I've got countless working buttons...but...for whatever reason this one is not cooperating...
I've added a UIButton (Rounded Rect) to a UIView subclass (DialogView) which is a subview of my view controller's view. This subview is created almost entirely in IB. I've wired up the button to (IBAction)okButtonPressed:(id)sender in IB to Touch Up Inside and created a corresponding method in DialogView.  However when I "touch" this button it doesn't trigger the method. userInteractionEnabled is true for the VC's view, DialogView and the UIButton.
Thinking maybe initWithCoder had to do some frame manipulation or something I added the following which successfully logs to console.
- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        NSLog(@"DialogView initWithCoder called");
    }
    return self;
}

In further exploration I wired up an IBOutlet to the button and then if I try to change the titleLabel from the view controller I notice that it get's severely truncated. Default text of say "Press Me!" set in IB displays fine when view is first drawn. But if I change the text...
self.DialogView.okButton.titleLabel.text = @"Not Working";

...it gets truncated to "N..."
Dunno if this is related. Probably...
Anyone see what I've screwed up here?
Edit (adding code related to showing UIButton):
From the View Controller:
self.DialogView = [[[NSBundle mainBundle] loadNibNamed:@"DialogView" owner:self options:nil] objectAtIndex:0];;
self.DialogView.myVC = self;
self.DialogView.backgroundColor = [UIColor clearColor];
self.DialogView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
self.DialogView.nameLabel.text = loan.fullName;
self.DialogView.noteLabel.text = loan.summaryOfLoan;
self.DialogView.amountLabel.text = [currencyFormatter stringFromNumber:loan.originalAmount];
self.DialogView.alpha = 0.0;
[self.view addSubview:DialogView];

The UILabels all displaying as expected. As is the problem UIButton. I can see it I just can't interact with it!?!
DialogView's interface:
@class MyViewController;

@interface DialogView : UIView {
    IBOutlet UILabel *nameLabel, *noteLabel, *amountLabel;
    IBOutlet UIImageView *arrowView;
    IBOutlet UIButton *okButton;
    MyViewController *myVC;
}

@property (nonatomic, retain) UILabel *nameLabel, *noteLabel, *amountLabel;
@property (nonatomic, retain) UIImageView *arrowView;
@property (nonatomic, assign) MyViewController *myVC;
@property (nonatomic, retain) UIButton *okButton;

- (IBAction)okButtonPressed:(id)sender;

@end

And DialogView's implementation:
#import "DialogView.h"
#import "MyViewController.h"

@implementation DialogView

@synthesize nameLabel, noteLabel, amountLabel, arrowView, okButton;
@synthesize myVC;

- (void)dealloc {
    [nameLabel release];
    [noteLabel release];
    [amountLabel release];
    [arrowView release];
    [okButton release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super initWithCoder:decoder]) {
        NSLog(@"DialogView initWithCoder called");
    }
    return self;
}

- (IBAction)okButtonPressed:(id)sender {
    NSLog(@"pressed DialogView OK button");
    [self.myVC.navigationController popViewControllerAnimated:YES];
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
}

@end

A: I thought that we should use -setTitle:forState: in order to set button's title ?
An other thought, did you check that the button's frame is not CGRectZero ? And by the way, all the frames for the view in the hierarchy ? And check that one superview in the hierarchy is not user interaction disabled ?
And, I think imageView does not respond to touches, do you have one in your code ?

A: I was just having more or less the same problem and I found that my containing view did not have "User Interaction Enabled".
Hope this helps.

A: Do you maybe have two buttons on top of one another? Change the IB project window to the detail view and see if your view has more buttons than you are expecting. Maybe you've wired up a button that's not actually getting the press you're expecting.


text:
Q: Is it possible to force your PHP input variables to be strong typed When I started off with PHP, I was really happy with how PHP was loosely typed and how easy it was to learn. But as I grew into it, I realized that being loosely typed actually complicated my scripts rather then simplifying them. And now I am looking for ways I could strong type my PHP variables, specifically the input variables ($_POST, $_GET, $_COOKIE, $_REQUEST and some $_SERVER vars).
Also, I would like my validation and sanitizing to be hidden away in this process so that I can "forget" about SQL Injection and many of the other error prone validation processes. I have a rough sketch of how I want this to be.
First I declare the variable. Preferably in OOP
$varClass->post->variable_name->type('STR', 'SQL', 'EMAIL');

// or as an array
$_MY_POST['variable_name'] = array('STR', 'SQL', 'EMIAIL');

Now I could possibly just drop all undeclared variable from the predefined PHP GLOBALs and use the variable type to validate and sanitize them directly in the global arrays.
I could also set the values of unvalidated variables like an emaill to bool false and un-submitted to null and use them during data validation. However, before I went off and re-invented the wheel I was hoping:
some one might direct me to a library which already helps solve my issues?
if there were any reasons why I shouldn't pursue on this wild fantasy?
Better and more clear ways of achieving this?
and Other general thoughts you may have about this idea?

A: http://sourceforge.net/p/php7framework/wiki/input/
Wraps the superglobals per default, but you could also instantiate local objects with $postFilter = new input($_POST). It's supposed to be used manually like this:
 $_POST->email->sql["variable_name"]
 $_POST->array->int["order_list"]

And it complains if it sees any $_POST["raw"] access.
But you can also pre-define filter lists. I would do that centrally in the class-definition. This is supposed to be an add-on for old applications, where you don't want to manually go through the code and rewrite strings to enforce data formats or types:
 var $__rules = array(
      "variable_name" => "email,sql",
      "order_id" => "int,range:0:500",
      "order_list" => "array,int",
 );

But I would personally avoid ->sql escaping prematurely. If available PDO and parameterized SQL should be used. But of course a central escaping feature is anyway better than cautiosness.
Also you can define custom filters. It picks up global functions for example.

A:
PHP was loosely typed

No - its not loosely typed, it's dynamically typed - there's a subtle difference.

actually complicated my scripts rather then simplifying them

My experience is exactly the opposite.

I would like my validation and sanitizing...

Strong typing is not the way to deal with input validation, particularly over medium like HTTP (which is loosely typed). It's just not practical to have type validation for every possible input - sure you can store an email address in a string - but that does not mean the email address is formatted correctly, how do you ensure that a file is an image? How does strong typing ensure that the start date is before the end date?
While recent verions of PHP have filter functionality, I (and most people I know) have long been using my own input validation lib for atoms, and second-order validation (comparing the relative values of more than one input) needs custom code. The only time you should ever change the type of inputs is where there is no resulting data loss (e.g. string to number conversions - but you need to very that you've not lost data as a result). Declaring the expected type of the input var is no more difficult than declaring an actual type for a variable. If you can't create a valid representation of the input suitable for processing, then your code should never guess what the user meant - you need to reject the input and inform the user / calling procedure.
A lot of validation can be very contextual - e.g. 02/12/2010 in the UK is 10 months after the same date in the US.
If you really want PHP to behave as if its strongly typed, have a look at PHPLint

so that I can "forget" about SQL Injection

NO! You validate/sanitize inputs and you transform outputs according to where they are being output to! The right representation of a string for writing to HTML is different from writing it to a URL which is different from writing it to a database.

A: I have written a forms system for our app which does this to a large extent;

*

*I define all the fields I'm expecting and rules about them (data type, at minimum, but also mins, maximums, enumerations, etc)

*a nonce is used to secure the form and also to determine if it was submitted

*when the session is recovered, each serialised form checks to see if the appropriate nonce was sent and considers itself submitted if so

*

*it then checks each known field, gets the submitted data and validates it

*all fields can be reset to their default if they're invalid

This also handles the rendering of forms and generation of client side validation rules as well, so I can just write the rules once (server side) and both client and server side validation automatically occurs.  Data type rules are the minimum that must be defined for each field.
Unfortunately it's not open source and I don't have permission to open source it; I looked for a long time to find something like this, but I couldn't really find anything.  The Pear Quickforms library was the closest, but didn't seem to cover all of the validation and had terrible, terrible documentation.


text:
Q: Will durable function automatically create the storage shares, queues and containers it needs? I deployed an azure durable function to azure using visual studio.
It created a storage account that contains quite a few shares, queues and containers.
I am exporting the ARM templates to automate deployment via DevOps.
On exporting the ARM template for the storage account that was created, it contains definitions for all these shares, queues & containers.
If I remove these, will the function, or the zip deployment step of the deployment pipeline create what it needs in the storage when its run?

A: AFAIK, Whenever we are exporting template from Azure portal we need to customize the required things as the resource is already exist in our resource group and portal itself.
So When we are using zip deployment for durable function or directly deploy them from local in storage account there will be shares, blobs and table will create automatically for storing the data into them.
Once we export and re-deploy according to our requirement the deployment will be succeed then we need to zip deploy our function to it (e.g: Durable function, http trigger etc.) .
SCREENSHOT FOR REFERENCE:-

For more information regarding exporting templates please refer the below links:-

*

*MICROSOFT DOCUMENTATION| Use exported template from the Azure portal & Integrate ARM templates with Azure Pipelines

*GitHub| Issue with deploying Durable function to Azure using ARM Template .


text:
Q: Elementary matrix proof I am supposing that $E$ is the elementary matrix obtained from $I$ (the identity matrix), by adding $\mu$ times the $m$-th row to the $l$-th row for some $\mu \in \mathbb{R}$ and $1\leq l,m\leq n$ and $l\neq m$.
I need to prove that for any $n\times n$ the matrix $B=EA$ can be obtained from $A$ by applying the same row operations.
I think I need to start by stating $E=e_{ik}$, so $e_{ik}= \left\{
  \begin{array}{2 2}
    1 \quad \text{if} \space i=k & \quad \\ \mu \quad \text{if} \space i=l \space \text{and} \space k=m & \quad \\0 \quad \text{otherwise}
  \end{array} \right.$
But I'm not sure where to go from there. I'm not very good at matrices so a bit more in depth explanation would be appreciated.

A: Let's do it formally. I'll use the notation $E_{lm}(d)$ for the matrix obtained from the identity by adding to the $l$-th row the $m$-th row multiplied by $d$, with $l\ne m$. If $e_{ij}$ are its coefficients, then
$$
e_{ij}=\begin{cases}
1 & \text{if $i=j$}\\
d & \text{if $i=l$ and $j=m$}\\
0 & \text{otherwise}
\end{cases}
$$
Denote by $a_{ij}$ the coefficients of $A$. Then the coefficient at position $(i,j)$ in $E_{lm}(d)A$ is:

*

*for $i\ne l$,
$$
\sum_{k} e_{ik}a_{kj}=e_{ii}a_{ij}=a_{ij}
$$
because $e_{ik}=0$ for $k\ne i$ and $e_{ii}=1$.

*for $i=l$,
$$
\sum_{k} e_{lk}a_{kj}=e_{ll}a_{lj}+e_{lm}a_{mj}=a_{lj}+da_{mj}
$$
because $e_{lk}=0$ for $k\notin\{l, m\}$, while $e_{ll}=1$ and $e_{lm}=d$.

A: You can easily see that the $l^{th}$ row of $E$ will have $\mu$ at position $m$. So $b_{lj}$ (the $(l, j)$ position in $B$) is the scalar multiplication of the $l^{th}$ row of $E$ and $j^{th}$ column of $A$. But in this row everything is $0$ except position $m$ (where resides $\mu$) and position $l$ (where resides $1$), so the result will be $\mu a_{mj} + a_{lj}$. And you get just what you need : $$(b_{l1}, b_{l2}, ... b_{ln}) = \mu (a_{m1}, a_{m2}, ... a_{mn}) + (a_{l1}, a_{l2}, ... a_{ln})$$

A: $E$ is constructed by adding a single element, $\mu$, at some off-diagonal position in the identity matrix, $I$.
Let $H$ be a matrix of all zeros except for a single $\mu$ at the $(l,m)$ position: $h_{lm} = \mu$.
Then, $$E = I+H$$
so $$EA = (I+H)A = A+HA.$$
Now, it should be obvious that $HA$ is a matrix of zeros except for a single row, which is $\mu$ times some other row of $A$. Therefore, adding $HA$ to $A$ yields the result we demand.


text: Q: Review manager/reviews manager I work for a transcription company where my job is to both review files for accuracy and oversee and coordinate with other people who also will review files.  Is it more accurate to say that I am the Reviews Manager (Because I am overseeing all incoming reviews), or Review Manager (because I manage the review process)?  Or is there another title that would be more appropriate?


text:
Q: How can I introduce a partition between the categories of a stacked bar chart in ggplot2? Current:

Needed: A white space between red and blue categories

Data:

A: In addition to the great comments of @AllanCameron and @eipi10 here is the code for what you want:
#Data
df <- data.frame(class=c('1st class','1st class','2nd class','2nd class','3rd class','3rd class'),
                 sex=rep(c('male','female'),3),
                 n=c(179,143,172,107,499,212))
#Code
ggplot(df,aes(x=class,y=n,fill=sex,label=n))+
  geom_bar(stat='identity',color='white',size=1)+
geom_text(color='white',position=position_stack(vjust=0.5),fontface='bold')+
  scale_fill_manual(values=c("#cb5e5f", "#0072b1")) +
  theme_classic() + theme(legend.position = "b")


text:
Q: Locally Store Variables js When I write code, I do so for my own amusement. I don't upload to a server or have my own website. I recently wrote a code which has quite a long run time (on average) and was just wondering if there's any way I can locally store a variable or two, without the use of cookies or other methods for storing info on a server.
For example:
// On first run, declare variable
var rise=0;
// Do something with it when the page is open
setInterval('rise++;',10);
// And then store the value somehow when I close the browser
browser.onClose(locallyStore('keyname',rise));

So that when I refresh the page or come back to it another day, the old value will be plugged back in and it will continue running from where I left off...
Thnx!

A: If you are working under Windows, you may want to consider an HTA file.
These are basicly web-pages that run with application level access and can do some amazing things.
In this answer I cover how to read and write local files.

A: localStorage.keyname = rise;
Later...
var rise = localStorage.keyname;
In any modern browser. (IE9+ if I recall correctly).

A: Try
localStorage.setItem("key", "value");

$var myItem = localStorage.getItem("key", "value");


text:
Q: Datagridview multiple columns search I'm new in dev and in vb.net I made a little application that stores names and phone numbers like that
Name  Phone

mike  123

Tom   125

Jhon  345

I want to make a search textbox and I tried this code
BindingSource1.Filter = "[name] LIKE '" & Search.Text & "%'"

That WORKS BUT doesn't work on both columns. I tried also to change the [name] with [phone] and works but i need a combined filter like
BindingSource1.Filter = "[name] LIKE '" & Search.Text & "%'" OR
BindingSource1.Filter = "[phone] LIKE '" & Search.Text & "%'"

so I can search better, is this possible?

A: This should work:
BindingSource1.Filter = "[name] LIKE '" & Search.Text & "%' OR [phone] LIKE '" & Search.Text & "%'"


text:
Q: getSheet(sheetName) causes OutofMemory Problems I'm using workbook.getSheet(sheetName)  to get a specific sheet in an excel file and keep getting an OutOfMemory exception. The sheet has ~52000 rows.
Is there a way to read small chunks of the sheet or something to fix this? Note that increasing JVM memory is not really an option right now.

A: You can try using:
setPropertySets(false);

Sets whether or not to enable any
  property sets (such as macros) to be
  copied along with the workbook Leaving
  this feature enabled will result in
  the JXL process using more memory

Aside from that if you're operating on a single sheet, there isn't much else you can do besides giving your Java process more memory.


text: Q: Use both Jade and html in the same Node and express Project I'm working on Email Html template. I want to use jade and html in the same node project. Is there any package available where I can convert my jade file into html?


text:
Q: Why do I get "Notice: Undefined offset" from arrays passed as arguments? What am I doing wrong here that is causing me to get this message?
function numbered_array( $array ) {
    for ( $i = 0; $i < count( $array ); $i++ ) {
        echo $i . ": ";
        echo $array[$i] . "
\n";
    }
}

I only have this problem from inside a function. When I use the same code on its own, e.g.
for ( $i = 0; $i < count( $my_array ); $i++ ) {
    echo $i . ": ";
    echo $my_array[$i] . "
\n";
}

it works just fine.
I seem to be having this issue with ANY function to which arrays are passed as arguments.
(For reference, I am working with a 1 dimensional array of string values)

A: Here is a solution for your problem.
function numbered_array(array $array)
{
    foreach ($array as $key => $value) {
        echo $key . ": ";
        echo $value . "
\n";
    }
}

$array = array("test","test","test","test",);

numbered_array($array);

Output
0: test

1: test

2: test

3: test


text:
Q: how to access zoomed pdf page in php or html I am converting pdf to image using imagmagik n php. but having with 100% resolution image quailty is poor. so that i want to access pdf in 200% resolution. please help me out..

A: Would this help you? Just Googled it - using the -density option
http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=10928#p34799


text:
Q: How does sudo decide whether to ask for a password, when given a command which doesn't actually need `sudo`? When applying sudo to a command which doesn't actually need sudo,

*

*sometimes it doesn't ask me for my password. For example under my $HOME, sudo ls.

*But I remember that it does for some other command, though I forget which one.
So I was wondering how sudo decides whether to ask for a password, when given a command which doesn't actually need sudo? Is there some rule in /etc/sudoers specifying that?
My real problem is that when I use du, it sometimes shows "permission denied" for some directories, and sometimes not, probably because I don't have permission on some directories? I apply sudo to du regardless, and thought I would be asked for a password regardless, but actually not on my own directories.

A:
to a command which doesn't actually need sudo

It's not that a command needs or needs not sudo. When you run
sudo -u user command

the system executes command as the user.
Whether the invocation is successful or not, and whether a password is asked or not, depends on the security policy sudoers (usually configured in /etc/sudoers).

A: sudo doesn't know whether the command it's asked to run needs to run as some other user (typically root), all it knows is its configuration. That determines which users are allowed to run sudo, with what users as "targets", and for what commands; it also determines whether a password is needed, which one, and whether to keep an authentication token around.
If you're using the default Debian configuration, the latter is most likely what's involved here: sudo will ask you for your password the first time you use it in any given terminal, then it will keep an authentication token for a certain amount of time. If you re-use sudo in the same terminal within that timeframe, it won't prompt you for a password.

A: In a typical configuration, the command is irrelevant. You need to enter your password the first time you use sudo, and you don't need your password in that particular shell for the next 15 minutes.
From the computer's perspective, there is no such thing as a "command that needs sudo". Any user can attempt to run any command. The outcome may be nothing but an error message such as "Permission denied" or "No such file or directory", but it's always possible to run the command.
For example, if you run du on a directory tree that has contents that you don't have permission to access, you'll get permission errors. That's what "permission denied" means. If you run sudo du, sudo runs du as root, so you don't get permission errors (that's the point of the root account: root¹ always has permission). When you run sudo du, du runs as root, and sudo is not involved at all after du has started. Whether du encounters permission errors is completely irrelevant to how sudo operates.
There are commands that need sudo to do something useful. Usefulness is a human concept. You need to use sudo (or some other methods to run the command as root) if the command does something useful when run as root but not when run under your account.
Whether sudo asks for your password depends on two things.

*

*Based on the configuration, sudo decides whether you need to be authenticated. By default, sudo requires a password. This can be turned off in several ways, including setting the authenticate option to false and having an applicable rule with the NOPASSWD tag.

*If sudo requires your password, it may be content to use a cached value. That's ok because the reason sudo needs your password is not to authenticate who's calling it (sudo knows what user invoked it), but to confirm that it's still you at the commands and not somebody who took control over your keyboard. By default, sudo is willing to believe that you're still at the commands if you entered your password less than 15 minutes ago (this can be changed with the timeout option). You need to have entered the password in the same terminal (so that if you remain logged in on one terminal then leave that terminal unattended and then use another terminal, someone can't take advantage of this to use sudo on the other terminal — but this is a very weak advantage and it can be turned off by setting the tty_tickets option to false).

¹  nearly, but that's beyond the scope of this thread.


text:
Q: Formatting a Pandas dataframe (flattening multindexes) I have data like this:
region  status  value
north   success 1
north   success 2
east    fail    2
east    open    3

I want to group by region and status, sum, and put together in a dataframe like so:
region  success fail    open
north   3       NaN     NaN
east    NaN     2       3

I can group and sum the data, but I don't understand how to flatten/remove/simplify the resulting MultiIndex in the code below:
d = {'region':['north','north','east','east'],
     'status':['success','success','fail','open'],
     'value':[1,2,2,3]}

df = pd.DataFrame(data = d)

df2 = df.groupby(by = ['region','status']).sum().unstack()

df2

That yields a MultiIndex dataframe. How can I simplify it?
    value
status  fail    open    success
region
east    2.0     3.0     NaN
north   NaN     NaN     3.0

A: You're probably looking for:
                           # Note how I select the one column.
df2 = df.groupby(['region','status'])['value'].sum().unstack()
print(df2)

# Output:

status  fail  open  success
region
east     2.0   3.0      NaN
north    NaN   NaN      3.0

Another method:
df2 = df.pivot_table(index='region', columns='status', values='value', aggfunc='sum', fill_value=0)
print(df2)

# Output:

status  fail  open  success
region
east       2     3        0
north      0     0        3


text:
Q: Using the open cover definition of compactness to show that the set of nilpotent $m \times m$ real matrices is noncompact
Is the set of nilpotent $m \times m$ real matrices compact?

I found the proof of this statement, using Heine-Borel theorem on $\mathbb R^n$. Tha'ts quite good.
But, is it possible to prove this statement via the following definition of compactness?

A set is said to be compact if every open cover admits a finite subcover.

Assume the usual topology.

A: The set $N$ of $m \times m$ real nilpotent matrices is compact iff $m = 1$, in which case $N$ is the singleton containing the zero matrix (in particular it is finite, hence compact).
For $m > 1$, consider the norm covering of $M(m, \mathbb{R})$ by open balls, namely the covering $\mathcal{B} := \{B_r : r \in \mathbb{Z}_+\}$, where
$$B_r := \{A \in M(m, \mathbb{R} : ||A|| < r \},$$
and $||A||$ is (for example) $\sqrt{\sum_{i, j = 1}^m A_{ij}^2}$.
Now, by construction, $\{B_r \cap N : i \in \mathbb{Z}_+\}$ is an open cover of $N$, and we will show it admits no finite subcover: The sets $B_r$ are nested, that is, $B_1 \subseteq B_2 \subseteq B_3 \subseteq \cdots$, and hence so are the sets $B_r \cap N$; thus, the union of the sets in any finite subcollection $\{B_{r_1} \cap N, \ldots, B_{r_k} \cap N\} \subset \mathcal{B}$ is just $B_R$, where $R := \max\{r_1, \ldots, r_k\}$. On the other hand, the matrix $R_0$ with $(1, 2)$ entry $R$ and all other entries zero is in $N$ (its square is the zero matrix), but $||R_0|| = R$, so $R_0$ is not in $B_R$, so hence arbitrary finite subcollection is not a cover of $N$, that is, $N$ is not compact.


text:
Q: Trying to find alternative way to express LINQ expression Further to a previous question I hadI've been able to simplify my query but am still having an issue with the MySQL provider.
I've got a membership table that records whether a user is a member of a list. When an update to a user's membership occurs a new record is written and the previous records are left as is which allows a history of their memberships to be maintained. To get a user's membership status involves selecting their most recent entry.
An example of some user list membership data is below. The aim is to find a LINQ expression that groups by list and user but only returns the row with most recently inserted record.
List Name, Username, Comment, ExpiresOn, Inserted
Test List, joeb, second update, 2012-03-13 16:55:03, 2012-01-31 22:28:40
Test List, joeb, first update, 2012-02-13 16:55:01, 2012-01-31 22:28:39
Test List, joeb, initial, 2012-01-13 16:55:02, 2012-01-31 22:28:38

My LINQ expression is as below.
var query = from mem in db.UserListMemberships
            where
             mem.Inserted >= (from mem2 in db.UserListMemberships where mem.UserID == mem2.UserID && mem.UserListID == mem2.UserListID orderby mem2.Inserted descending select mem2.Inserted).FirstOrDefault()
             select mem;

The issue is I'm getting an exception from the MySQL entity provider of "MySql.Data.MySqlClient.MySqlException: Unknown column 'Extent1.UserID' in 'where clause'". Is there any other way I could write e expression that might get around the MySQL exception?

A: Try this and see if it works for you:
var query =
    from mem in db.UserListMemberships
    group mem by mem.UserID into mems
    select mems.OrderByDescending(m => m.Inserted).First();


text:
Q: Dynamically add new lambda expressions to create a filter I need to do some filtering on an ObjectSet to obtain the entities I need by doing this :
query = this.ObjectSet.Where(x => x.TypeId == 3); // this is just an example;

Later in the code (and before launching the deferred execution) I filter the query again like this :
query = query.Where(<another lambda here ...>);

That works quite well so far.
Here is my problem :
The entities contains a DateFrom property and a DateTo property, which are both DataTime types. They represent a period of time.
I need to filter the entities to get only those that are part of a collection of periods of time. The periods in the collection are not necessarily contiguous, so, the logic to retreive the entities looks like that :
entities.Where(x => x.DateFrom >= Period1.DateFrom and x.DateTo <= Period1.DateTo)
||
entities.Where(x => x.DateFrom >= Period2.DateFrom and x.DateTo <= Period2.DateTo)
||

... and on and on for all the periods in the collection.
I have tried doing that :
foreach (var ratePeriod in ratePeriods)
{
    var period = ratePeriod;

    query = query.Where(de =>
        de.Date >= period.DateFrom && de.Date <= period.DateTo);
}

But once I launch the deferred execution, it translates this into SQL just like I want it (one filter for each of the periods of time for as many periods there is in the collection), BUT, it translates to AND comparisons instead of OR comparisons, which returns no entities at all, since an entity cannot be part of more than one period of time, obviously.
I need to build some sort of dynamic linq here to aggregate the period filters.

Update
Based on hatten's answer, I've added the following member :
private Expression<Func<T, bool>> CombineWithOr<T>(Expression<Func<T, bool>> firstExpression, Expression<Func<T, bool>> secondExpression)
{
    // Create a parameter to use for both of the expression bodies.
    var parameter = Expression.Parameter(typeof(T), "x");
    // Invoke each expression with the new parameter, and combine the expression bodies with OR.
    var resultBody = Expression.Or(Expression.Invoke(firstExpression, parameter), Expression.Invoke(secondExpression, parameter));
    // Combine the parameter with the resulting expression body to create a new lambda expression.
    return Expression.Lambda<Func<T, bool>>(resultBody, parameter);
}

Declared a new CombineWithOr Expression :
Expression<Func<DocumentEntry, bool>> resultExpression = n => false;

And used it in my period collection iteration like this :
foreach (var ratePeriod in ratePeriods)
{
    var period = ratePeriod;
    Expression<Func<DocumentEntry, bool>> expression = de => de.Date >= period.DateFrom && de.Date <= period.DateTo;
    resultExpression = this.CombineWithOr(resultExpression, expression);
}

var documentEntries = query.Where(resultExpression.Compile()).ToList();

I looked at the resulting SQL and it's like the Expression has no effect at all. The resulting SQL returns the previously programmed filters but not the combined filters. Why ?

Update 2
I wanted to give feO2x's suggestion a try, so I have rewritten my filter query like this :
query = query.AsEnumerable()
    .Where(de => ratePeriods
        .Any(rp => rp.DateFrom <= de.Date && rp.DateTo >= de.Date))

As you can see, I added AsEnumerable() but the compiler gave me an error that it cannot convert the IEnumerable back to IQueryable, so I have added ToQueryable() at the end of my query :
query = query.AsEnumerable()
    .Where(de => ratePeriods
        .Any(rp => rp.DateFrom <= de.Date && rp.DateTo >= de.Date))
            .ToQueryable();

Everything works fine. I can compile the code and launch this query. However, it doesn't fit my needs.
While profiling the resulting SQL, I can see that the filtering is not part of the SQL query because it filters the dates in-memory during the process. I guess that you already know about that and that is what you intended to suggest.
Your suggestion works, BUT, since it fetches all the entities from the database (and there are thousands and thousands of them) before filtering them in-memory, it's really slow to get back that huge amount from the database.
What I really want is to send the period filtering as part of the resulting SQL query, so it won't return a huge amount of entities before finishing up with the filtering process.

A: Despite the good suggestions, I had to go with the LinqKit one. One of the reasons is that I will have to repeat the same kind of predicate aggregation in many other places in the code. Using LinqKit is the easiest one, not to mention I can get it done by writing only a few lines of code.
Here is how I solved my problem using LinqKit :
var predicate = PredicateBuilder.False<Document>();
foreach (var submittedPeriod in submittedPeriods)
{
    var period = period;
    predicate = predicate.Or(d =>
        d.Date >= period.DateFrom && d.Date <= period.DateTo);
}

And I launch deferred execution (note that I call AsExpandable() just before) :
var documents = this.ObjectSet.AsExpandable().Where(predicate).ToList();

I looked at the resulting SQL and it does a good job at translating my predicates into SQL.

A: You can use a method like the following:
Expression<Func<T, bool>> CombineWithOr<T>(Expression<Func<T, bool>> firstExpression, Expression<Func<T, bool>> secondExpression)
{
    // Create a parameter to use for both of the expression bodies.
    var parameter = Expression.Parameter(typeof(T), "x");
    // Invoke each expression with the new parameter, and combine the expression bodies with OR.
    var resultBody = Expression.Or(Expression.Invoke(firstExpression, parameter), Expression.Invoke(secondExpression, parameter));
    // Combine the parameter with the resulting expression body to create a new lambda expression.
    return Expression.Lambda<Func<T, bool>>(resultBody, parameter);
}

And then:
Expression<Func<T, bool>> resultExpression = n => false; // Always false, so that it won't affect the OR.
foreach (var ratePeriod in ratePeriods)
{
    var period = ratePeriod;
    Expression<Func<T, bool>> expression = (de => de.Date >= period.DateFrom && de.Date <= period.DateTo);
    resultExpression = CombineWithOr(resultExpression, expression);
}

// Don't forget to compile the expression in the end.
query = query.Where(resultExpression.Compile());

For more information, you may want to check out the following:
Combining two expressions (Expression<Func<T, bool>>)
http://www.albahari.com/nutshell/predicatebuilder.aspx
Edit: The line Expression<Func<DocumentEntry, bool>> resultExpression = n => false; is just a placeholder. CombineWithOr method needs two methods to combine, if you write Expression<Func<DocumentEntry, bool>> resultExpression;', you can't use it in the call toCombineWithOrfor the first time in yourforeach` loop. It's just like the following code:
int resultOfMultiplications = 1;
for (int i = 0; i < 10; i++)
    resultOfMultiplications = resultOfMultiplications * i;

If there's nothing in resultOfMultiplications to begin with, you cannot use it in your loop.
As to why the lambda is n => false. Because it doesn't have any effect in an OR statement. For example, false OR someExpression OR someExpression is equal to someExpression OR someExpression. That false doesn't have any effect.

A: How about this code:
var targets = query.Where(de =>
    ratePeriods.Any(period =>
        de.Date >= period.DateFrom && de.Date <= period.DateTo));

I use the LINQ Any operator to determine if there is any rate period that conforms to de.Date. Although I'm not quite sure how this is translated into efficient SQL statements by entity. If you could post the resulting SQL, that would be quite interesting for me.
Hope this helps.
UPDATE after hattenn's answer:
I don't think that hattenn's solution would work, because Entity Framework uses LINQ expressions to produce the SQL or DML that is executed against the database. Therefore,  Entity Framework relies on the IQueryable<T> interface rather than IEnumerable<T>. Now the default LINQ operators (like Where, Any, OrderBy, FirstOrDefault and so on) are implemented on both interfaces, thus the difference is sometimes hard to see. The main difference of these interfaces is that in case of the IEnumerable<T> extension methods, the returned enumerables are continuously updated without side effects, while in the case of IQueryable<T> the actual expression is recomposed, which is not free of side effects (i.e. you are altering the expression tree that is finally used to create the SQL query).
Now Entity Framework supports the ca. 50 standard query operators of LINQ, but if you write your own methods that manipulate an IQueryable<T> (like hatenn's method), this would result in an expression tree that Entity Framework might not be able to parse because it simply doesn't know the new extension method. This might be the cause why you cannot see the combined filters after you composed them (although I would expect an exception).
When does the solution with the Any operator work:
In the comments, you told that you encountered a System.NotSupportedException: Unable to create a constant value of type 'RatePeriod'. Only primitive types or enumeration types are supported in this context. This is the case when the RatePeriod objects are in-memory objects and not tracked by the Entity Framework ObjectContext or DbContext. I made a small test solution that can be downloaded from here: https://dl.dropboxusercontent.com/u/14810011/LinqToEntitiesOrOperator.zip
I used Visual Studio 2012 with LocalDB and Entity Framework 5. To see the results, open the class LinqToEntitiesOrOperatorTest, then open Test Explorer, build the solution and run all tests. You will recognize that ComplexOrOperatorTestWithInMemoryObjects will fail, all the others should pass.
The context I used looks like this:
public class DatabaseContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<RatePeriod> RatePeriods { get; set; }
}
public class Post
{
    public int ID { get; set; }
    public DateTime PostDate { get; set; }
}
public class RatePeriod
{
    public int ID { get; set; }
    public DateTime From { get; set; }
    public DateTime To { get; set; }
}

Well, it is as simple as it gets :-). In the test project, there are two important unit test methods:
    [TestMethod]
    public void ComplexOrOperatorDBTest()
    {
        var allAffectedPosts =
            DatabaseContext.Posts.Where(
                post =>
                DatabaseContext.RatePeriods.Any(period => period.From < post.PostDate && period.To > post.PostDate));

        Assert.AreEqual(3, allAffectedPosts.Count());
    }

    [TestMethod]
    public void ComplexOrOperatorTestWithInMemoryObjects()
    {
        var inMemoryRatePeriods = new List<RatePeriod>
            {
                new RatePeriod {ID = 1000, From = new DateTime(2002, 01, 01), To = new DateTime(2006, 01, 01)},
                new RatePeriod {ID = 1001, From = new DateTime(1963, 01, 01), To = new DateTime(1967, 01, 01)}
            };

        var allAffectedPosts =
            DatabaseContext.Posts.Where(
                post => inMemoryRatePeriods.Any(period => period.From < post.PostDate && period.To > post.PostDate));
        Assert.AreEqual(3, allAffectedPosts.Count());
    }

Notice that the first method passes while the second one fails with the exception mentioned above, although both methods do exactly the same thing, except that in the second case I created rate period objects in memory the DatabaseContext does not know about.
What can you do to solve this problem?

*

*Do your RatePeriod objects reside in the same ObjectContext or DbContext, respectively? Then use them right from it like I did in the first unit test mentioned above.

*If not, can you load all your posts at once or would this result in an OutOfMemoryException? If not, you could use the following code. Notice the AsEnumerable() call that results in the Where operator being used against the IEnumerable<T> interface instead of IQueryable<T>. Effectively, this results in all posts being loaded into memory and then filtered:
[TestMethod]
public void CorrectComplexOrOperatorTestWithInMemoryObjects()
{
    var inMemoryRatePeriods = new List<RatePeriod>
        {
            new RatePeriod {ID = 1000, From = new DateTime(2002, 01, 01), To = new DateTime(2006, 01, 01)},
            new RatePeriod {ID = 1001, From = new DateTime(1963, 01, 01), To = new DateTime(1967, 01, 01)}
        };

    var allAffectedPosts =
        DatabaseContext.Posts.AsEnumerable()
                       .Where(
                           post =>
                           inMemoryRatePeriods.Any(
                               period => period.From < post.PostDate && period.To > post.PostDate));
    Assert.AreEqual(3, allAffectedPosts.Count());
}

*If the second solution is not possible, then I would recommend to write a TSQL stored procedure where you pass in your rate periods and that forms the correct SQL statement. This solution is also the most performant one.

A: Anyways, I think dynamic LINQ query creation was not as simple as I thought. Try using Entity SQL, similar to the way below:
var filters = new List<string>();
foreach (var ratePeriod in ratePeriods)
{
    filters.Add(string.Format("(it.Date >= {0} AND it.Date <= {1})", ratePeriod.DateFrom, ratePeriod.DateTo));
}

var filter = string.Join(" OR ", filters);
var result = query.Where(filter);

This may not be exactly correct (I haven't tried it), but it should be something similar to this.


text:
Q: jPaginate obtains incorrect child count In the jQuery plugin, jPaginate, the number of child objects is always returning the value of 1 determined by this code (lines 45-48 in jPaginate.js):
//getting the amount of elements inside parent element
var number_of_items = obj.children().size();
//calculate the number of pages we are going to have
var number_of_pages = Math.ceil(number_of_items/show_per_page);

I call the script in the header in the document.ready function:
$("#content").jPaginate({
items: 4,
pagination_class: "pagination",
minimize: true
});

and I wrapped a div with id="content" around the table rows I want paginated like this:

            <?php foreach ($invoices as $invoice) { ?>

                        <a href='<?php echo $_SERVER['PHP_SELF']; ?>/retrieve?class=InvoiceLineItems&id=<?php echo $invoice['invoice_id']; ?>'><?php echo $invoice['invoice_number']; ?> <?php echo $invoice['customer_name'] ?> <?php echo $invoice['invoice_date'] ?>

            <?php } ?>

What I get is one long page of records, with the pagination selector set to 'previous' 1 'next'. I tripled check, removed & replaced, and debugged the code as best I could. I still cannot determine why number_of_items gets set to 1.
Any help is appreciated.
Thanks.

A: The answer is due to the selector.
var number_of_items = obj.children().size();

The obj is #content which your are passing to the plugin. So obj.children() is only returning the first child, table, within the obj. Since there is only one item in the array it has a size of 1.


text:
Q: Does Bluebird "map" return early? Let's imagine that I have 10 promises running that will be passed to Promise.map() with its default concurrency setting of 3.
If any of the first 3 promises are rejected, will the other 7 be even started?
Bluebird's docs for map() states the following:

Promises returned by the mapper function are awaited for and the returned promise doesn't fulfill until all mapped promises have fulfilled as well. If any promise in the array is rejected, or any promise returned by the mapper function is rejected, the returned promise is rejected as well.

It only states that if all fulfill, then the inner promises are awaited, but it's not clear to me what happens if any of them is rejected.
Edit
I'm aware that the canonical definition of the map function is that the output's length is the same as the size of the input, but I'm not sure if Bluebird honors this.

A: Taken literally, Bluebird's Promise.prototype.map returns immediately.
When doing so, it returns a Promise that may not resolve immediately. I imagine you really want to know how that promise behaves and there are a few things to break down here:

If any of the first 3 promises are rejected, will the other 7 be even started?

Yes. Promises are "started" (that is, scheduled) when you create them. The other 7 will attempt to resolve or are likely enough to do so that you need to assume they will.
Imagine if the browser only allows 4 HTTP connections to a server and you make 10 requests. Those first (failing) 3 will be sent, along with a friend, who may not fail but will certainly run.
You should assume that all promises will invoke their bodies.

It only states that if all fulfill, then the inner promises are awaited, but it's not clear to me what happens if any of them is rejected.

That's easy enough to test:
const Promise = require('bluebird');

function delayReject(delay, err) {
  return new Promise((res, rej) => {
    console.log('waiting to reject', err);
    setTimeout(() => rej(err), delay);
  });
}

function delayValue(delay, val) {
  return new Promise((res, rej) => {
    console.log('waiting to resolve', val);
    setTimeout(() => res(val), delay);
  });
}

const promises = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(it => {
  if (it % 3 === 0) {
    return delayReject(50, it);
  } else {
    return delayValue(50, it);
  }
});

Promise.map(promises, v => {
  console.log('mapping', v);
  return -v;
}).then(it => {
  console.log('mapped', it);
}).catch(err => {
  console.log('error', err);
});

My output, with node v6.8.1, is:
ssube@localhost ~/questions/40619451 $  > node early-exit.js
waiting to resolve 1
waiting to resolve 2
waiting to reject 3
waiting to resolve 4
waiting to resolve 5
waiting to reject 6
waiting to resolve 7
waiting to resolve 8
waiting to reject 9
mapping 1
mapping 2
error 3

As you may expect, all the promises are scheduled and run, but the map does stop running against them after the first failure.
The Bluebird docs mention that:

The mapper function for a given item is called as soon as possible, that is, when the promise for that item's index in the input array is fulfilled. This doesn't mean that the result array has items in random order, it means that .map can be used for concurrency coordination unlike .all.

That suggests that the order of mapped items may not be persisted, like it is in the above example. We can test that by adding some noise to the delay:
const Promise = require('bluebird');

function delayNoise(n) {
  return n + Math.floor(Math.random() * 50);
}

function delayReject(delay, err) {
  return new Promise((res, rej) => {
    console.log('waiting to reject', err);
    setTimeout(() => rej(err), delayNoise(delay));
  });
}

function delayValue(delay, val) {
  return new Promise((res, rej) => {
    console.log('waiting to resolve', val);
    setTimeout(() => res(val), delayNoise(delay));
  });
}

const promises = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(it => {
  if (it % 3 === 0) {
    return delayReject(50, it);
  } else {
    return delayValue(50, it);
  }
});

Promise.map(promises, v => {
  console.log('mapping', v);
  return -v;
}).then(it => {
  console.log('mapped', it);
}).catch(err => {
  console.log('error', err);
});

Running that yields far more interesting results: if the first promise rejects, then the map ends and does not attempt to map the others. It does short-circuit, as you guessed.

A: I have achieved very similar results to @ssube's answer.
I got 10 promises, that will be resolved or rejected after a increasing timeout. The 4th one (because the array is 0-based) is rejected.
const Promise = require('bluebird')

function delay(timeout, err, i) {
  return new Promise(function (resolve, reject) {
    if (err) {
      setTimeout(function () {
        console.log('Rejected', err.message)
        reject(err)
      }, timeout)
    } else {
      setTimeout(function () {
        console.log('Resolved', i)
        resolve(i)
      }, timeout)
    }
  })
}

const promises = Array.apply(null, {length: 10})
  .map(Function.call, Number)
  .map(function (it) {
    if (it === 3) {
      return delay(500 * it, new Error(it))
    } else {
      return delay(500 * it, null, it)
    }
  })

Promise.map(promises, function (p) {
  console.log('Mapping', p)
  return p.toString()
})
  .then(function (it) {
    console.log('All resolved', it)
  })
  .catch(function (err) {
    console.log('Error', err.message)
  })

This will yield:
> Resolved 0
> Mapping 0
> Resolved 1
> Mapping 1
> Resolved 2
> Mapping 2
> Rejected 3
> Error 3
> Resolved 4
> Resolved 5
> Resolved 6
> Resolved 7
> Resolved 8
> Resolved 9

So, the behaviour is the following:

*

*Promise.map is short-circuited whenever one of the promises being mapped is rejected.

*The callback in map is never executed for any of the subsequent promises.

*Notice that Error 3 comes before the deliberately slower promises.

*However, all of the promises are "executed" until they are settled.


text:
Q: Joint PMF of $max\{X,Y\}$ and $X$ where $X,Y$ iid geometric I am interested in finding the joint PFM of $X$, $max\{X,Y\} $ where $X,Y $ are i.i.d geometric random variables with parameter $p$.
My attempt:
$P(X=x,M=m) = P(X=x,M=m,X\geq Y) + P(X=x,M=m, X\lt Y)$
$ = P(X=x=m, X \geq Y) + P(X=x,Y=m,X \lt Y)$
$=P(X=x=m, x  \geq Y) + P(X=x, Y=m, x\lt m)$
=$P(X=x)P(Y \leq x)$ if $x=m$
and $=P(X=x)P(Y=m)$ if $x \lt m$
Is this reasoning correct?

A: Let $\mathbb P(X=k)=(1-p)^{k-1}p = \mathbb P(Y=k)$ for positive integers $k$. Denote by $M=X\vee Y$ the maximum of $X$ and $Y$. Then for any positive integer $m$, we have
$$
\{M=m\} = \{X=m,Y=m\} \cup \{X=m,Y<m\} \cup \{X<m,Y=m\},
$$
and so
\begin{align}
\mathbb P(M=m) &= \mathbb P(X=m,Y=m) + \mathbb P(X=m,Y<m) + \mathbb P(X<m,Y=m)\\
&= \mathbb P(X=m)\mathbb P(Y=m) + \mathbb P(X=m)\mathbb P(Y<m) + \mathbb P(X<m,Y=m)\\
&=(1-p)^{2(m-1)}p^2 + (1-p)^{m-1}p(1 - (1-p)^{m-1}p) + (1 - (1-p)^{m-1}p)(1-p)^{m-1}p\\
&=(p(1-p)^{m-1})^2 + 2 (1-p)^{m-1}p(1 - (1-p)^{m-1}p).
\end{align}


text:
Q: JAVAC Error with Path Change to jdk\bin Problem still exists with Path Change to jdk67/bin.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
C:\Users\Dell>java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) Client VM (build 24.65-b04, mixed mode, sharing)
C:\Users\Dell>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\Dell>echo %path%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\ant194\bin;C:\maven323\bin;C:\Java\jdk67\bin;C:\Ruby200\b
in
C:\Users\Dell>javac
'javac' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\Dell>
Please let me know.

A: This may help you,
1.copy the  path upto 'bin' (Eg:-C:\Program Files\Java\jdk1.7.0_07\bin)
2.Go to properties of 'MY COMPUTER'
3.Select 'Advanced System Settings'

*Select 'Environment Variables'

5.Find 'Path' in 'System variables'
6.Click 'Edit'
7.Paste your above path into 'Variable value' By putting a semi-column(;)at the end of current
values(Do not clear the value that already set)
8.click ok...ok
9.Go to Command Prompt and type 'javac' , if pathe setting is correct,it will show some information, if not correct it will show "javac' is not recognized as an internal or external command, operable program or batch file."

A: Probable JAVA Version 7 Update 67 Installation Problem - javac.exe not found
I think that there is no problem in giving contact numbers and this is not a same query
as it is on Windows 7.
After installing I tried to check javac.exe in this dir C:\Java\jdk67\bin and it was not
present there. Then I searched C:\ and culd not find there.
I installed JDK from the site:
https://java.com/en/download/index.jsp
I think that the installer has some problem.
Regards
Rohan Sarker
www.rohansarker.com
+913324288069 / +917278539338


text:
Q: How to initialize local variable to unkown value C++ trying to make my first post right so here goes.
I ran into this question and have not been able to figure it out. I keep receiving the error:
error C4700: uninitialized local variable 'miles' used

I have scavenged over all of StackOverflow and keep running into the same answer: I have to initialize my local variable, but when I do that I am creating a set value. I want to set my local variable 'miles' to an unknown value because I want the user to be able to set the value when the program runs.
Everything ran great until I tried to cast the end value 'miles'so that it would truncate.
Please correct me if I'm using incorrect terminology. Fresh-out-of-the-womb-to-programming. And thank you to everyone in advance.
Question:
Write a program that prompts the capacity, in gallons, of an automobile fuel tank and the miles per gallon the automobile can be driven. The program outputs the number of miles the automobile can be driven without refueling. Numbers entered for capacity must allow entry of capacity being an integer and the miles per gallon in decimals. The number of miles must be output to the next lowest integer (without decimals).
#include "stdafx.h"

//include statement
#include<iostream>

//include namespace statement
using namespace std;

//main function
int main()
{
    //variable declaration
    double capacity_Gallons;
    double miles_Gallon;
    double miles = static_cast<int>(miles < 0 ? miles - 0.5 : miles + 0.5);

    //inputting capacity of automobile
    cout << "Enter the capacity of the automobile fuel in gallons: ";
    cin >> capacity_Gallons;
    cout << endl;

    //inputting the miles per Gallons
    cout << "Enter the miles per gallons the automobile can be driven: ";
    cin >> miles_Gallon;
    cout << endl;

    //calculating miles
    miles = capacity_Gallons * miles_Gallon;

    //display output data
    cout << "Number of miles driven wihtout refueling: " << miles << endl;

    //pause system for some time for user continuation
    system("pause");

}   //end main

A: You should take out that line entirely, and change the later line to double miles = capacity_Gallons * miles_Gallon;.
Instead of your handcrafted rounding code it would be better to use the standard rounding function in the display statement, ... << std::lround(miles) << ... although your assignment stipulation says you should round down , not round to nearest as you are currently doing. (So you can just cast to int there).

A: You don't need to declare miles there, you can declare it at the point it has a value.
#include<iostream>

int main()
{
    //inputting capacity of automobile
    double capacity_Gallons;
    std::cout << "Enter the capacity of the automobile fuel in gallons: ";
    std::cin >> capacity_Gallons;
    std::cout << endl;

    //inputting the miles per Gallons
    double miles_Gallon;
    std::cout << "Enter the miles per gallons the automobile can be driven: ";
    std::cin >> miles_Gallon;
    std::cout << endl;

    //calculating miles
    double miles = capacity_Gallons * miles_Gallon;

    //display output data
    std::cout << "Number of miles driven wihtout refueling: " << miles << std::endl;

    //pause system for some time for user continuation
    system("pause");
}

As an aside, using namespace std is a bad habit.


text:
Q: Ergonomics issues with fixed size byte arrays in Rust Rust sadly cannot produce a fixed size array [u8; 16] with a fixed size slicing operator s[0..16].  It'll throw errors like "expected array of 16 elements, found slice".
I've some KDFs that output several keys in wrapper structs like
pub struct LeafKey([u8; 16]);
pub struct MessageKey([u8; 32]);

fn kdfLeaf(...) -> (MessageKey,LeafKey) {
    // let mut r: [u8; 32+16];
    let mut r: (MessageKey, LeafKey);
    debug_assert_eq!(mem::size_of_val(&r), 384/8);
    let mut sha = Sha3::sha3_384();
    sha.input(...);

    // sha.result(r);
    sha.result(
      unsafe { mem::transmute::<&mut (MessageKey, LeafKey),&mut [u8;32+16]>(&r) }
    );
    sha.reset();

    // (MessageKey(r[0..31]), LeafKey(r[32..47]))
    r
}

Is there a safer way to do this?  We know mem::transmute will refuse to compile if the types do not have the same size, but that only checks that pointers have the same size here, so I added that debug_assert.
In fact, I'm not terribly worried about extra copies though since I'm running SHA3 here, but afaik rust offers no ergonomic way to copy amongst byte arrays.
Can I avoid writing (MessageKey, LeafKey) three times here?  Is there a type alias for the return type of the current function?  Is it safe to use _ in the mem::transmute given that I want the code to refuse to compile if the sizes do not match?  Yes, I know I could make a type alias, but that seems silly.
As an aside, there is a longer discussion of s[0..16] not having type [u8; 16] here

A: There's the copy_from_slice method.
fn main() {
    use std::default::Default;

    // Using 16+8 because Default isn't implemented
    // for [u8; 32+16] due to type explosion unfortunateness
    let b: [u8; 24] = Default::default();
    let mut c: [u8; 16] = Default::default();
    let mut d: [u8; 8] = Default::default();

    c.copy_from_slice(&b[..16])
    d.copy_from_slice(&b[16..16+8]);
}

Note, unfortunately copy_from_slice throws a runtime error if the slices are not the same length, so make sure you thoroughly test this yourself, or use the lengths of the other arrays to guard.
Unfortunately, c.copy_from_slice(&b[..c.len()]) doesn't work because Rust thinks c is borrowed both immutably and mutably at the same time.

A: I marked the accepted answer as best since it's safe, and led me to the clone_into_array answer here, but..
Another idea that improves the safety is to make a version of mem::transmute for references that checks the sizes of the referenced types, as opposed to just the pointers.  It might look like :
#[inline]
unsafe fn transmute_ptr_mut<A,B>(v: &mut A) -> &mut B {
    debug_assert_eq!(core::mem::size_of(A),core::mem::size_of(B));
    core::mem::transmute::<&mut A,&mut B>(v)
}

I have raised an issue on the arrayref crate to discuss this, as arrayref might be a reasonable crate for it to live in.
Update : We've a new "best answer" by the arrayref crate developer :
let (a,b) = array_refs![&r,32,16];
(MessageKey(*a), LeafKey(*b))


text:
Q: php set permissions file to make it writable After ages of programming in php this question seems really weird still to me.
I want to make a file writable dinamically to not have problem with permissions in production / development  .... but it still gives me trouble.
Can someone gives me explanation on what am I wrong?
// permissions    -- the folder writable by www-data
//drwxrwxrwx 2 www-data www-data  4096 mag 24 12:19 Details

// then the file not writable by the owner
-r----x--t 1 www-data www-data 0 giu  8 12:48 /home/giuseppe/homeProj//Ariprova/trunk/PhpCsv/phpcsv/ConfigClasses/Helpers/Virtuemart2/Details/324-PartsToAdd.json

// then the code

if (!file_exists($fileRequest)) {   // it's found
                throw new Exception ('File non trovato. Nome File completo: '.$fileRequest. ' con cartella '.  getcwd());
                }

if (!is_writable($fileRequest)) {
                $results = @chmod($fileRequest, '0777');  //this gives true

            }

            $fileReq = fopen($fileRequest, 'w');
            fwrite($fileReq, 'a string' );   // this writes nothing on file

            fclose($fileReq);

A: Change chmod($fileRequest, '0777') to chmod($fileRequest, 0777). The string '0777' will be converted to a numeric value, which will be 777 decimal, which is not what you expect; what you really want is 0777 octal.

A: Here is the man page for chmod: http://php.net/chmod
You can see that the function "Attempts to change the mode of the specified file"
This is because the user that runs the script (eg apache) might not be allowed to overwrite permissions set by the owner of that directory (at least that can be one of the reasons)
Update: you can try to go to the parent directory with the owner (or root just to be sure) and change the ownership to the user that you need to be able to do this (chown apache:apache dirname or something like that)


text:
Q: Does differentiating an integro-differential equation results in equivalent stability of the solution? I have a dynamical system in the form of an integro-differential equation which I want to analyze in terms of stability. To demonstrate my problem consider the following integro-differential equation:
$$\dot{x}(t)=ax(t)+b\int_0^tx(\tau)\text{d}\tau,$$
where $\dot{x}(t)$ denotes the time derivative of $x(t)$. If we derive the above equation and try $x(t)=\text{e}^{\lambda t}$ we get:
$$\ddot{x}(t)-a\dot{x}(t)-bx(t)=\text{e}^{\lambda t}\left(\lambda^2-a\lambda-b\right) = 0$$ which we can solve for $\lambda$. However if we first use the substitution $x(t)=\text{e}^{\lambda t}$ to the original equation we get:
$$\lambda\text{e}^{\lambda t}=a\text{e}^{\lambda t}+b\left[\frac{1}{\lambda}\text{e}^{\lambda \tau}\right]^t_0=a\text{e}^{\lambda t}+\left[\frac{b}{\lambda}\text{e}^{\lambda t}-\frac{b}{\lambda}\right]$$ in which case we end up with:
$$\text{e}^{\lambda t}\left(\lambda-\frac{b}{\lambda}-a\right) = \frac{b}{\lambda}.$$
For me it seams like differentiating an integro-differential equation modifies it's stability properties. Does this mean that in case of stability analysis one cannot differentiate? Or these are equivalent in terms of stability and I am just missing an obvious point? Thank you for any comments, ideas!

A: What you are missing is that your system secretly has two degrees of freedom. Your integro-differential equation is equivalent to the first order linear differential system
$$ \begin{cases}  \dot{p}(t) = bx(t) ,& p(0) = 0 \\
\dot{x}(t) = a x(t) + p (t),& x(0) = ? \end{cases} $$
The initial condition that $p(0)$ comes from the requirement that $p(t) = b\int_0^t x(s) ds$.
Ignoring the prescribed initial data, to do stability analysis of such a system with two unknowns, your hypothesized exponential solution should look like  $(p(t),x(t)) = (p(0),x(0)) e^{\lambda t}$, where both $\lambda$ and the eigenvector need to be solved for.
A priori there is no reason that an eigenvector can be chosen so that $p(0) = 0$, matching your initial conditions. In fact, as pointed out by Dirk Werner, an eigenvector with $p(0) = 0$ is only possible for this equation when $b = 0$.
However, you can still use the information from the stability analysis of the system (or equivalently, the linear second order equation you derived). You just need to solve first and impose the initial condition $p(0)$ later. Denoting by $\lambda_\pm$ the roots of $\lambda^2 - a \lambda - b$, you have that solutions to your integral-differential equation can always take the form
$$ x(t) = x_+ e^{\lambda_+ t} + x_- e^{\lambda_- t} $$
By Dirk Werner's analysis, when $b\neq 0$ the eigenvectors must have a $p$ component, implying that a $p(0) = 0$ solution necessarily has a non-trivial projection into both eigenspaces. This means that as long as one of the roots $\lambda_{\pm}$ is positive, your equation is unstable.


text:
Q: I'm unable to get the selected data from spinner when I'm using arraylist tospinner I'm unable to get the selected data from spinner when I'm using arraylist to spinner.
Here when I'm using array of fixed length then it sets the spinner's selected data to textview but when I'm using arraylist then it's not getting set.
public class GetData extends AsyncTask<String,String,String> {
    int i=0;
    String data;
    String[] array;

    @Override
    protected String doInBackground(String... strings) {
        // data = strings[0];
        arrayList.clear();
        Query query = FirebaseDatabase.getInstance().getReference().child(strings[0]);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long c=dataSnapshot.getChildrenCount();
                int count = (int)c;
                array= new String[count];

                Iterator iterator = dataSnapshot.getChildren().iterator();
                while (iterator.hasNext()) {
                    DataSnapshot dataSnapshot1 = (DataSnapshot) iterator.next();
                    // array[i] = dataSnapshot1.getValue().toString();
                    // i++;
                    arrayList.add(dataSnapshot1.getValue().toString());
                }
                Toast.makeText(Register_Activity.this,"Now Select : "/*+array[0]*/, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        // super.onPostExecute(s);

        switch(n){
            case 0:
                adapter[0] = new ArrayAdapter(Register_Activity.this, android.R.layout.simple_spinner_item, array);
                spinner[0].setAdapter(adapter[0]);
                break;
            case 1:
                adapter[1] = new ArrayAdapter(Register_Activity.this, android.R.layout.simple_spinner_item, array);
                spinner[1].setAdapter(adapter[1]);
                break;
            case 2:
                adapter[2] = new ArrayAdapter(Register_Activity.this, android.R.layout.simple_spinner_item, array);
                spinner[2].setAdapter(adapter[2]);
                break;
            case 3:
                adapter[3] = new ArrayAdapter(Register_Activity.this, android.R.layout.simple_spinner_item, array);
                spinner[3].setAdapter(adapter[3]);
                break;
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                spinner[n].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        // data = spinner[n].getSelectedItem().toString();
                        data = spinner[n].getItemAtPosition(i).toString();
                        Toast.makeText(Register_Activity.this, "hey"+data, Toast.LENGTH_SHORT).show();
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Register_Activity.this);
                        alertDialogBuilder.setMessage("Are you sure: "+data);
                        alertDialogBuilder.setPositiveButton("yes",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                **textViews[n].setText(data);
                                spinner[n].setEnabled(false);**
                                n++;
                                if (n < 4) {
                                    new GetData().execute(data);
                                }
                            }
                        });

                        alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });

                        AlertDialog alertDialog = alertDialogBuilder.create();
                        alertDialog.show();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
            }
        }, 300);
    }
}


text:
Q: Rails submit create action succeeding I am learning ruby rails and i have a #create problem (i think)
when i am creating a new "stat" with form_for, once i press submit i get redirect to index.html.erb (as written in my controller) but there is no data apart from the id (even if i chose my self an id, it get generated by rails)
the weird part is, if i edit the new entry (where everything is blank but :ID) data are saved.
I hope i am clear enough it's my first question on stackoverflow
Thx a lot !
My controller : stats
def new
    @stat = Stat.new
end

def create
    @stat = Stat.new
    if @stat.save
      redirect_to "/stats"
      flash[:notice] = "work"
    else
      render "new"
      flash[:notice] = "didn't work"
    end
end

the log for create action
tarted POST "/stats" for 92.133.16.18 at 2015-06-09 12:09:11 +0000
Processing by StatsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"bCV+ymN4NxuMM6441OLaRyu/cuLXIcX5fu1g/rG+gqg=", "stat"=>{"id"=>"", "cc"=>"ok", "ct"=>"ok", "force"=>"ok", "endurance"=>"ok", "blessure"=>"ok", "init"=>"ok", "attaque"=>"ok", "ld"=>"ok", "sv"=>"ok"}, "commit"=>"Save"}
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "stats" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2015-06-09 12:09:11.561787"], ["updated_at", "2015-06-09 12:09:11.561787"]]
   (10.8ms)  commit transaction
Redirected to https://codex-bobix.c9.io/stats
Completed 302 Found in 16ms (ActiveRecord: 11.2ms)

the log for the update action
Started PATCH "/stats/11" for 92.133.16.18 at 2015-06-09 12:04:09 +0000
Processing by StatsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"bCV+ymN4NxuMM6441OLaRyu/cuLXIcX5fu1g/rG+gqg=", "stat"=>{"id"=>"11", "statname"=>"tt", "cc"=>"tt", "ct"=>"t", "force"=>"ttt", "endurance"=>"tt", "blessure"=>"t", "init"=>"ttt", "attaque"=>"tt", "ld"=>"ttt", "sv"=>"tt"}, "commit"=>"save", "id"=>"11"}
  Stat Load (0.2ms)  SELECT  "stats".* FROM "stats"  WHERE "stats"."id" = ? LIMIT 1  [["id", 11]]
   (0.1ms)  begin transaction
  SQL (0.5ms)  UPDATE "stats" SET "attaque" = ?, "blessure" = ?, "cc" = ?, "ct" = ?, "endurance" = ?, "force" = ?, "init" = ?, "ld" = ?, "statname" = ?, "sv" = ?, "updated_at" = ? WHERE "stats"."id" = 11  [["attaque", "tt"], ["blessure", "t"], ["cc", "tt"], ["ct", "t"], ["endurance", "tt"], ["force", "ttt"], ["init", "ttt"], ["ld", "ttt"], ["statname", "tt"], ["sv", "tt"], ["updated_at", "2015-06-09 12:04:09.051306"]]
   (15.9ms)  commit transaction
Redirected to https://codex-bobix.c9.io/stats
Completed 302 Found in 25ms (ActiveRecord: 16.8ms)

.
class StatsController < ApplicationController
  def index
    @stats = Stat.all
  end

  def show
    @stat = Stat.find(params[:id])
    @units = @stat.units
  end

  def new
    @stat = Stat.new
  end

  def edit
    @stat = Stat.find(params[:id])
  end

  def update
    @stat = Stat.find(params[:id])
    @stat.update(stat_params)
    redirect_to "/stats"
    flash[:notice] = "work"
  end

  def new
    @stat = Stat.new
  end

  def create
    @stat = Stat.new
    if @stat.save
      redirect_to "/stats"
      flash[:notice] = "work"
    else
      render "new"
      flash[:notice] = "didn't work"
    end
  end

    private

    def stat_params
        params.require(:stat).permit(:cc, :ct, :force, :endurance, :blessure, :init, :attaque, :ld, :sv, :id, :statname)
    end

end

A: In your create action you are not passing any arguments for your Stat, it should be something like:
class StatsController < ApplicationController
  def create
    @stat = Stat.new stat_params
    # ...
  end

  private

  def stat_params
    params.require(:stat).permit(:id, :cc, :ct, :force, :endurance, :blessure, :init, :attaque, :ld, :sv)
  end
end

Hope that helps!

A: When you say @stat = Stat.new, you're instantiating a new Stat object with no assigned attributes, and then saving that. As such, no matter what parameters you pass to the controller, you will only have the fields which are automatically generated (in this case ID). What you need to do is take the parameters and create a new object from them (i.e. @stat = Stat.new( stat_params )).
Since you have a stat_params method defined at the bottom of your controller (as is generally the case by default when you generate a scaffold), then that line of code alone will fix it. Essentially all you need to do is grab the params for the stat (submitted from new), turn them into a hash, and put them into the Stat.new( ... ) statement.


text:
Q: Join on a cursor I have the following pl sql proc, I'm trying to join a table on a CUR
FETCH CUR INTO V_CTR_ID,V_TRXN_INTRL_REF_ID,V_TRXN_DT,V_ACCT_INTRL_ID,V_TRXN_BASE_AM;
        EXIT WHEN CUR%NOTFOUND;
        --dbms_output.put_line('Enter CUR');
        OPEN CUR1 FOR  SELECT distinct CTR.OCCUPATION,CTR.TAX_ID
                         FROM
                            BR_CTR_TRANS BR join CUR on
                            CUR.V_TRXN_INTRL_REF_ID=BR.TRANS_REF_ID AND CUR.V_ACCT_INTRL_ID=BR.ACCT_IDENTIFIER AND CUR.V_TRXN_BASE_AM=BR.TRANS_AMT_BASE AND CUR.V_TRXN_DT=BR.TRANS_DT
                            join CTR_XML_BR_COND CTR
                            on
                            BR.BR_CTR_SUM_REF_ID=CTR.CTR_ID;

The error I'm getting is, the CUR is considered as table, and it's giving table or view doesn't exist. Can someone help?

A: You cannot JOIN to a cursor, but you can use the use the fetched  values in a subsequent SQL statement. In this case remove the 'join cur' and move the on clause conditions to a 'where' clause.
fetch cur into v_ctr_id,v_trxn_intrl_ref_id,v_trxn_dt,v_acct_intrl_id,v_trxn_base_am;
        exit when cur%notfound;
        --dbms_output.put_line('Enter CUR');
        open cur1 for  select distinct ctr.occupation,ctr.tax_id
                         from br_ctr_trans br
                         join ctr_xml_br_cond ctr onbr.br_ctr_sum_ref_id=ctr.ctr_id
                        where 1=1
                          and cur.v_trxn_intrl_ref_id=br.trans_ref_id
                          and cur.v_acct_intrl_id=br.acct_identifier
                          and cur.v_trxn_base_am=br.trans_amt_base
                          and cur.v_trxn_dt=br.trans_dt;


text:
Q: How to access byte array from String which is made up of bytes array? I want to save data in byte code format to my MySql db and retrieve it.
Example
String s = "String To Byte Array";

I am converting it to byte code using base64 library, so it becomes -
"U3RyaW5nIFRvIEJ5dGUgQXJyYXk="
Now I am saving this value in my MySql database in column with data type longtext
After fetching this value from DB I want to convert it in to original format.

A: You can decode the base64 back to string. This might help you.
https://examples.javacodegeeks.com/core-java/apache/commons/codec/decode-base64/

A: Once you obtained the encoded string from the database, you can obtain an instance of class Decoder and decode the string in this way:
Decoder decoder = Base64.getDecoder();
byte[] bytes = decoder.decode(encoded.getBytes());
String decoded = new String(bytes);


text:
Q: Python - validate if the process filtered by PID is still running Using subprocess library I do spawn new processes.
import subprocess
pid = subprocess.Popen(["sleep", "1"]).pid
is_process_running(pid)

The whole point of that is to invoke a script in an async wait and continue work of the program.
I do not want to spawn multiple subprocesses with the same script invoked, that is why I am trying to detect if the process with a given PID number still exists in the system.
The function that I use looks in the following way:
import os
def is_process_running(process_id):
    try:
        os.kill(process_id, 0)
        return True
    except OSError:
        return False

Unfortunately, processes created with subprocess library are accessible forever. The status that these have is: defunct. Due to that, the function that I have written above always returns True. Is there any way to detect if the process is marked with defunct?

A: It's much simpler to keep and operate on the Popen instance returned by the subprocess.Popen call. This does what you want:
import subprocess as sp
import time

def is_process_running(proc):
    return proc.poll() is None

proc = sp.Popen(['sleep', '10'])
is_process_running(proc) # will return True
time.sleep(6)
is_process_running(proc) # still True
time.sleep(6)
is_process_running(proc) # will now return False