问:
Creating path-names with variables in Python 2.7
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

```<code>a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')
</code>```

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

```<code>os.path.join('./results/', test, '/outputs/'))
</code>```

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

答:
To create a string including variables values (well, the string representation of variables values), you want str.format():

```<code>a = 'test'
b = 2
c = 3
d = 4

dirname = "{}_{}_{}_{}".format(a, b, c d)
</code>```

Then you use os.path.join() to create the full path in a portable way (so your code works on any supported OS). Also it's better to use absolute path (this make the code more predictable) instead of relying on either os-specific stuff ("./xxx") and/or os.chdir(). Here I'm using o.getcwd() to use the current working directory as root but it's better to use something more reliable, based either on the current user's homedir, the application's directory or some command line arg or environment variable:

```<code>root = os.getcwd() # or whatever root folder you want
dirpath = os.path.join(root, "results", dirname, "outputs")
</code>```

And finally, you use os.makedirs to create the whole directory tree in one single call:

```<code>if not os.path.exists(dirpath):
    os.makedirs(dirpath)
</code>```

NB :

I've seen I can do os.path.join('./results/', test, '/outputs/')

The point of os.path.join() is to use the appropriate path separators for the current OS, so do not hardcode path separators in your arguments - this should have been os.path.join('results', test, 'outputs')

Body:
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

os.path.join('./results/', test, '/outputs/'))

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

Body:
To create a string including variables values (well, the string representation of variables values), you want str.format():

a = 'test'
b = 2
c = 3
d = 4

dirname = "{}_{}_{}_{}".format(a, b, c d)

Then you use os.path.join() to create the full path in a portable way (so your code works on any supported OS). Also it's better to use absolute path (this make the code more predictable) instead of relying on either os-specific stuff ("./xxx") and/or os.chdir(). Here I'm using o.getcwd() to use the current working directory as root but it's better to use something more reliable, based either on the current user's homedir, the application's directory or some command line arg or environment variable:

root = os.getcwd() # or whatever root folder you want
dirpath = os.path.join(root, "results", dirname, "outputs")

And finally, you use os.makedirs to create the whole directory tree in one single call:

if not os.path.exists(dirpath):
    os.makedirs(dirpath)

NB :

I've seen I can do os.path.join('./results/', test, '/outputs/')

The point of os.path.join() is to use the appropriate path separators for the current OS, so do not hardcode path separators in your arguments - this should have been os.path.join('results', test, 'outputs')


来源: stackexchange

问:
Regular expression for GST Identification Number (GSTIN)
What is the regex for the GST number in India?

You can read more about the GST numbers in What is GST Number? – Know your 15 Digits GSTIN. On a summary level, the number is represented as

List item. The first two digits of this number will represent the state code as per 2011 Census of India

The next ten digits will be the PAN number of the taxpayer

The thirteenth digit will be assigned based on the number of registration within a state

The fourteenth digit will be Z by default

The last digit will be for a check code

ContentLicense: CC BY-SA 4.0

Body:
The regex should be:

/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9]{1}Z[0-9]{1}$/


问:
How to set ip, jumbo frame, receive buffers properties to Intel(R) Ethernet Server Adapter I350-T2 cards on Windows?
We have to set ip, jumbo frame, receive buffers properties to Intel(R) Ethernet Server Adapter I350-T2 network cards (lot of them) on Windows7.
 Unfortunately when we do a disk image, these values are lost and we have to input all of them manually on the cloned PC for each network adapter.
 Is there any sdk/api to set them programmatically?

答: I am able to change all the advanced adapter properties using Intel® PROSet for Windows PowerShell* Software . </p>

ContentLicense: CC BY-SA 3.0


问:
Check if the current time has just passed 12 o'clock in BACKGROUND
I want to check if the current time (24 hours or 12 hours am/pm) has just passed 12 o'clock.

I did something like that in a view, but in this case I checked if it was not yet 12 in the morning:

```<code>let date = Date()
let calendar = Calendar.current
let hora = calendar.component(.hour, from: date)
let minutos = calendar.component(.minute, from: date)
if hora < 12 && minutos <= 59 { ... }
</code>```

I don't know if I explained it well... I was wondering if I can check if the time has passed in AppDelegate, always in background, and execute a function when 12 am has passed. It is possible?

答:
I don't think you will achieve at least in iOS framework.

Apple won't allow you to execute code at a certain time interval in background. Because it's almost similar what some malwares do.

Additional: But if you don't want to execute code in background rather when in your app's foreground then it's possible using timer.

Body:
I want to check if the current time (24 hours or 12 hours am/pm) has just passed 12 o'clock.

I did something like that in a view, but in this case I checked if it was not yet 12 in the morning:

let date = Date()
let calendar = Calendar.current
let hora = calendar.component(.hour, from: date)
let minutos = calendar.component(.minute, from: date)
if hora < 12 && minutos <= 59 { ... }

I don't know if I explained it well... I was wondering if I can check if the time has passed in AppDelegate, always in background, and execute a function when 12 am has passed. It is possible?


问:
Android - fragment back stack resulting into white screen
I have five different fragments in my project, let's call them A...E. A and B are only visible for the user when he opens the app. Those are responsible for showing the loading screen (checking current login session) and the login screen itself. Fragment C ist the main screen of that application which the user can use to reach the other areas of the app. Because of that this, the fragments D and E got the "addToBackStack(String)" extra when the transaction have been created/commited.

My problem which is resulting into a blank screen, is when the user is opening D or E and goes back to C again. This action can lead to the blank screen for C the first time or redoing that step several times.

The relevant fragments C,D,E are using a view holder, databinding and recycler views. Each recycler view has multiple view types.

It seems like that onBackPressed to C is executing correctly but that C has been deleted from the cache or something similar.

Hope anyone can help me with that issue.

答:
I found a possible solution for my problem. Still need to test this further but so far it seems to work:</p>

```<code>private void showFragment(Fragment fragment, String tag, String backStackTag) {
    FragmentTransaction ft = fragmentManager.beginTransaction();

    if (backStackTag != null) {
        ft.addToBackStack(backStackTag);
    }

    switch (tag) {
        case "A":
        case "B":
            ft.replace(containerId, fragment, tag);
            break;
        case "C": {
            Fragment main = fragmentManager.findFragmentByTag("C");
            if (main != null) {
                ft.show(main);
            } else {
                ft.replace(containerId, fragment, tag);
            }
            break;
        }
        case "D":
        case "E": {
            Fragment main = fragmentManager.findFragmentByTag("C");
            ft.hide(main);
            ft.add(containerId, fragment, tag);
            break;
        }
        default:
            ft.add(containerId, fragment, tag);
            break;
    }

    ft.commit();
}
</code>```

Body:
I found a possible solution for my problem. Still need to test this further but so far it seems to work:

private void showFragment(Fragment fragment, String tag, String backStackTag) {
    FragmentTransaction ft = fragmentManager.beginTransaction();

    if (backStackTag != null) {
        ft.addToBackStack(backStackTag);
    }

    switch (tag) {
        case "A":
        case "B":
            ft.replace(containerId, fragment, tag);
            break;
        case "C": {
            Fragment main = fragmentManager.findFragmentByTag("C");
            if (main != null) {
                ft.show(main);
            } else {
                ft.replace(containerId, fragment, tag);
            }
            break;
        }
        case "D":
        case "E": {
            Fragment main = fragmentManager.findFragmentByTag("C");
            ft.hide(main);
            ft.add(containerId, fragment, tag);
            break;
        }
        default:
            ft.add(containerId, fragment, tag);
            break;
    }

    ft.commit();
}


问:
Is RedGate SQL Source Control for me?
I've just inherited an SQL Server database. One of the things I will need to sort out is versioning and automated builds.

It has been suggested that I should think seriously about recommending RedGate SQL Compare, but I have to admit I am a little uneasy about it.

My reservations are...

it appears to promote use of the gui tools for db work?

for live apps, I prefer to work with change scripts, this avoids the last minute panic to create migration scripts at the end of each scrum cycle, and it means your update scripts can be tested by the CI. I can't see how the RedGate tool addresses this.

My gut instinct tells me to stick with the tried and tested approach of an MSBuild file and a stack of .SQL files.

I would be interested to hear if anyone has any experience on using this tool.

答:
SQL Compare can either generate a SQL migration script that can be independently reviewed before applying it, but also gives the option to execute the script within the tool. Red Gate recommends using the former method when deploying to production databases.

For database versioning, SQL Source Control support most source control systems (eg, SVN, TFS, etc, although VSS support has been deprecated). There is, in v3, an option to link to a working folder, allowing you to use your own version control client if desirable.

Title: Is RedGate SQL Source Control for me?


问:
Create Non duplicate view in SQL
I have two tables

Developers

Developer_Id

Full Name

Cellphone number

Email address

Team

Role

Assigned To

JobList

Job_Id

Assignment Name

Assignment Description

Created By

Date Created

Due Date

Status

I want to view the JobList table but it should include:

Developers.Full Name

Developers.Team

Developers.Role

Developers.Assigned To

I created a view but it return duplicate values like this:

is there any way I can view the JobList table in a single row but include the muliple rows from the Developers table, something like this

Here is the code I use

Create Tables:

```<code>CREATE TABLE [dbo].[Developers] (
[Developer_Id]     INT          NOT NULL,
[Full Name]        VARCHAR (50) NULL,
[Cellphone number] VARCHAR (50) NULL,
[Email address]    VARCHAR (50) NULL,
[Team]             VARCHAR (50) NULL,
[Role]             VARCHAR (50) NULL,
[Assigned To] INT NULL,
CONSTRAINT [PK_Developers] PRIMARY KEY ([Developer_Id])
);

CREATE TABLE [dbo].[JobList] (
[Job_Id]                 INT           NOT NULL,
[Assignment Name]        VARCHAR (50)  NULL,
[Assignment Description] VARCHAR (MAX) NULL,
[Created By]             VARCHAR (50)  NULL,
[Date Created]           DATE          NULL,
[Due Date]               DATE          NULL,
[Status] VARCHAR(50) NULL,
CONSTRAINT [PK_JobList] PRIMARY KEY ([Job_Id])
);
</code>```

Create view

```<code>CREATE VIEW [dbo].AssignedJobs
AS SELECT JobList.[Assignment Name], JobList.[Assignment Description], JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
from JobList
inner join Developers
on JobList.Job_Id = Developers.[Assigned To]
</code>```

答:
```<code>CREATE VIEW [dbo].AssignedJobs
AS SELECT JobList.[Assignment Name], JobList.[Assignment Description],
JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
from JobList
inner join Developers
on JobList.Job_Id = Developers.[Assigned To]
group by JobList.[Assigment Name], JobList.[Assignment Description], JobList.[Due Date], JobList[Status], string_agg(Developers.[Full Name], ' ') as [Full Name], string_agg (Developers.Role, ' ') as Role
</code>```

If you are not on SQL Server 2017/Azure then use something like this: Agg with Stuff and XML FOR PATH

Title: Create Non duplicate view in SQL

Body:
I have two tables

Developers

Developer_Id

Full Name

Cellphone number

Email address

Team

Role

Assigned To

JobList

Job_Id

Assignment Name

Assignment Description

Created By

Date Created

Due Date

Status

I want to view the JobList table but it should include:

Developers.Full Name

Developers.Team

Developers.Role

Developers.Assigned To

I created a view but it return duplicate values like this:

is there any way I can view the JobList table in a single row but include the muliple rows from the Developers table, something like this

Here is the code I use

Create Tables:

CREATE TABLE [dbo].[Developers] (
[Developer_Id]     INT          NOT NULL,
[Full Name]        VARCHAR (50) NULL,
[Cellphone number] VARCHAR (50) NULL,
[Email address]    VARCHAR (50) NULL,
[Team]             VARCHAR (50) NULL,
[Role]             VARCHAR (50) NULL,
[Assigned To] INT NULL,
CONSTRAINT [PK_Developers] PRIMARY KEY ([Developer_Id])
);

CREATE TABLE [dbo].[JobList] (
[Job_Id]                 INT           NOT NULL,
[Assignment Name]        VARCHAR (50)  NULL,
[Assignment Description] VARCHAR (MAX) NULL,
[Created By]             VARCHAR (50)  NULL,
[Date Created]           DATE          NULL,
[Due Date]               DATE          NULL,
[Status] VARCHAR(50) NULL,
CONSTRAINT [PK_JobList] PRIMARY KEY ([Job_Id])
);

Create view

CREATE VIEW [dbo].AssignedJobs
AS SELECT JobList.[Assignment Name], JobList.[Assignment Description], JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
from JobList
inner join Developers
on JobList.Job_Id = Developers.[Assigned To]

Body:
CREATE VIEW [dbo].AssignedJobs
AS SELECT JobList.[Assignment Name], JobList.[Assignment Description],
JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
from JobList
inner join Developers
on JobList.Job_Id = Developers.[Assigned To]
group by JobList.[Assigment Name], JobList.[Assignment Description], JobList.[Due Date], JobList[Status], string_agg(Developers.[Full Name], ' ') as [Full Name], string_agg (Developers.Role, ' ') as Role

If you are not on SQL Server 2017/Azure then use something like this: Agg with Stuff and XML FOR PATH


问:
How can get data complicated json response in angular 2?
I have a booking listing page. I tried to get data from json file. In first format result is getting but second format data is not getting. I have explained two format below. Please help me to solve this problem. I have added my code in plunker.

Plunker Link

First

```<code>    [
       {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
       },
       {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
       },
       { "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
       },
      {
       "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
       }
   ]
</code>```

Second

```<code>{
  "bookingDetails": {
    "data": [
      {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
      }
    ]
  }
}
</code>```

Json file is oncluded in apidata -> testData.json

app -> booking -> booking.service.ts

```<code>getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .toPromise()
            .then(response => response.json() as Bookings[])
            .catch(this.handleError);
    }
</code>```

app -> booking -> booking.component.ts

```<code>export class BookingComponent implements OnInit {
    bookings: Bookings[];
    constructor(private employeeService: BookingService) {}
    getBooking(): void {
        /*this.employeeService.getEmployee().then(employees => this.employees = employees);*/
        this.employeeService.getBooking().then(bookings => this.bookings = bookings);
    }
    ngOnInit(): void {
        this.getBooking();
    }
}
</code>```

答:
your plunker has errors, but you need to correct your service implementation and the way you consume it in angular2.

Change the booking.service.ts code, like:

```<code>getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .catch(this.handleError);
    }
</code>```

and code in booking.component.ts , like:

```<code>this.employeeService.getBooking().subscribe(bookings => this.bookings = bookings );
</code>```

Body:
I have a booking listing page. I tried to get data from json file. In first format result is getting but second format data is not getting. I have explained two format below. Please help me to solve this problem. I have added my code in plunker.

Plunker Link

First

    [
       {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
       },
       {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
       },
       { "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
       },
      {
       "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
       }
   ]

Second

{
  "bookingDetails": {
    "data": [
      {"_id": "57ee4e32f8f888dc11000029", "cabinname": "Foo", "user": "5818355ad2ae67e505431d5b"
      },
      {"_id": "57f22cf3f8f888800c000030", "cabinname": "Joo", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000031", "cabinname": "Maria", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000032", "cabinname": "Peter", "user": "5818355ad2ae67e505431d5b"
      },
      {
        "_id": "57f22cf3f8f888800c000033", "cabinname": "Declan", "user": "5818355ad2ae67e505431d5b"
      }
    ]
  }
}

Json file is oncluded in apidata -> testData.json

app -> booking -> booking.service.ts

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .toPromise()
            .then(response => response.json() as Bookings[])
            .catch(this.handleError);
    }

app -> booking -> booking.component.ts

export class BookingComponent implements OnInit {
    bookings: Bookings[];
    constructor(private employeeService: BookingService) {}
    getBooking(): void {
        /*this.employeeService.getEmployee().then(employees => this.employees = employees);*/
        this.employeeService.getBooking().then(bookings => this.bookings = bookings);
    }
    ngOnInit(): void {
        this.getBooking();
    }
}

Body:
your plunker has errors, but you need to correct your service implementation and the way you consume it in angular2.

Change the booking.service.ts code, like:

getBooking(): Promise<Bookings[]> {
        return this.http.get(this._url)
            .map(response => response.json().bookingDetails.data as Bookings[])
            .catch(this.handleError);
    }

and code in booking.component.ts , like:

this.employeeService.getBooking().subscribe(bookings => this.bookings = bookings );


问:
Vue and Vue Resource
I'm trying to send a post request via vue-resource and I can't quite seem to figure out what I'm doing incorrectly.

I'm using Laravel 5.1 to process the request.

The following jquery code works fine from within my Vue method.

```<code> $.ajax({
        type: 'POST',
        url: '/purchase/save-cart-items',
        data: { 'purchaseItems' : purchaseItems},
        success: function (response) {
            if(response == "ok") {
                alert("Cart saved successfully.");
            } else {
                alert('There was a problem saving this cart. Please try again.');
            }
        }
    });
</code>```

However, the replacing the jquery above with the following vue-resource post request doesn't work for some reason.  I'm sure it's something simple, but I can't seem to figure it out.  Vue-resource is properly included in the project as I'm using it for get requests without issue.

```<code>this.$http.post('/purchase/save-cart-items', {purchaseItems:purchaseItems}, function (data, status, request) {
    alert("Cart saved successfully.");
}).error(function (data, status, request) {
    alert('There was a problem saving this cart. Please try again.');
});
</code>```

答:
Vue's author has stopped updating and maintaining vue-resource. He himself also suggested using axios, axios more easy to use and easy to maintain.
axios introduction

If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!

Github Demo

Title: Vue and Vue Resource

Body:
I'm trying to send a post request via vue-resource and I can't quite seem to figure out what I'm doing incorrectly.

I'm using Laravel 5.1 to process the request.

The following jquery code works fine from within my Vue method.

 $.ajax({
        type: 'POST',
        url: '/purchase/save-cart-items',
        data: { 'purchaseItems' : purchaseItems},
        success: function (response) {
            if(response == "ok") {
                alert("Cart saved successfully.");
            } else {
                alert('There was a problem saving this cart. Please try again.');
            }
        }
    });

However, the replacing the jquery above with the following vue-resource post request doesn't work for some reason.  I'm sure it's something simple, but I can't seem to figure it out.  Vue-resource is properly included in the project as I'm using it for get requests without issue.

this.$http.post('/purchase/save-cart-items', {purchaseItems:purchaseItems}, function (data, status, request) {
    alert("Cart saved successfully.");
}).error(function (data, status, request) {
    alert('There was a problem saving this cart. Please try again.');
});


问:
React Redux onBlur event not firing in Safari and Firefox
This seems to work perfectly in Chrome and Edge. I have a tooltip that needs to pop up onClick of the button, and then disappear onBlur. For some reason the onBlur event does not fire at all on Safari or Firefox.

I've tried logging to the console in handleBlur and it does not get that far, it is as if onBlur does not exist in this context.

```<code>class Tooltip extends Component {
  componentWillUnmount() {
    this.closeActiveTooltip();
  }

  handleKeyPress = (event) => {
    if (event.keyCode === 27) { // Esc key
      this.closeActiveTooltip();
    }
  }

  handleBlur = () => {
    if (this.props.activeTooltip === this.props.name) {
      // setTimeout is for link click
      setTimeout(this.closeActiveTooltip, 100);
    }
  }

  closeActiveTooltip = () => {
    const { activeTooltip, closeTooltip } = this.props;

    if (activeTooltip) {
      closeTooltip(activeTooltip);
    }
  }

  render() {
    const {
      isOpen,
      text,
      link,
      position,
    } = this.props;
    const popupClassName = getClassNameFor(s, 'popup', `${isOpen && 'open'} ${position}`);
    const linkElement = (
      <div className={s.link}>
        <a
          href={link}
          target="_blank"
          rel="noopener noreferrer"
        >
          More info here
        </a>
      </div>
    );

    return (
      <button
        type="button"
        className={s.root}
        onClick={this.props.toggleTooltip}
        onBlur={this.handleBlur}
        onKeyDown={this.handleKeyPress}
      >
        <svg className={s.icon}>
          <use xlinkHref="#more-info" />
        </svg>
        <div className={popupClassName}>
          {text}
          {link && linkElement}
        </div>
      </button>
    );
  }
}
</code>```

答:
All I know is that I could never get an element (most likely an <input />) focused on mount with React, probably because of render()s, so I use setTimeout(() => input.focus(), 0) to make it async. So, it seems there are issues with focus handling...

A simple workaround would be:

```<code><button
    onClick={this.handleAction}
    onMouseDown={this.handleFocus}
    onMouseUp={this.handleBlur} />
</code>```

But when user release the mouse button out of the button, you'll never trigger the onMouseUp.

A better workaround consists in simulating a click out:

```<code>class Tooltip extends Component {
    componentDidMount() {
        document.body.addEventListener('click', this.handleClickOut, false);
    }

    componentWillUnmount() {
        document.body.removeEventListener('click', this.handleClickOut, false);
    }

    handleClickOut = event => {
        if(event.target != this.refs.btn) { // Actually more complicated, event.target can be a child of button (icon, span, etc)
            this.handleBlur();
        }
    }

    handleBlur() {}

    render() {
        return (
            <button
                ref='btn'
                type="button"
            >
                {text}
            </button>
        );
    }
}
</code>```

possibly with a component that wraps your button

```<code><ClickOut onClickOut={this.handleBlur}>
    <button
        onClick={this.handleAction}
        onMouseDown={this.handleFocus} />
</ClickOut>
</code>```

Any time you click on your document, if target is not <button /> or one of its child nodes, trigger the click out pseudo event

Body:
This seems to work perfectly in Chrome and Edge. I have a tooltip that needs to pop up onClick of the button, and then disappear onBlur. For some reason the onBlur event does not fire at all on Safari or Firefox.

I've tried logging to the console in handleBlur and it does not get that far, it is as if onBlur does not exist in this context.

class Tooltip extends Component {
  componentWillUnmount() {
    this.closeActiveTooltip();
  }

  handleKeyPress = (event) => {
    if (event.keyCode === 27) { // Esc key
      this.closeActiveTooltip();
    }
  }

  handleBlur = () => {
    if (this.props.activeTooltip === this.props.name) {
      // setTimeout is for link click
      setTimeout(this.closeActiveTooltip, 100);
    }
  }

  closeActiveTooltip = () => {
    const { activeTooltip, closeTooltip } = this.props;

    if (activeTooltip) {
      closeTooltip(activeTooltip);
    }
  }

  render() {
    const {
      isOpen,
      text,
      link,
      position,
    } = this.props;
    const popupClassName = getClassNameFor(s, 'popup', `${isOpen && 'open'} ${position}`);
    const linkElement = (

          More info here

    );

    return (
      <button
        type="button"
        className={s.root}
        onClick={this.props.toggleTooltip}
        onBlur={this.handleBlur}
        onKeyDown={this.handleKeyPress}
      >
        <svg className={s.icon}>
          <use xlinkHref="#more-info" />
        </svg>

          {text}
          {link && linkElement}

      </button>
    );
  }
}

Body:
All I know is that I could never get an element (most likely an <input />) focused on mount with React, probably because of render()s, so I use setTimeout(() => input.focus(), 0) to make it async. So, it seems there are issues with focus handling...

A simple workaround would be:

<button
    onClick={this.handleAction}
    onMouseDown={this.handleFocus}
    onMouseUp={this.handleBlur} />

But when user release the mouse button out of the button, you'll never trigger the onMouseUp.

A better workaround consists in simulating a click out:

class Tooltip extends Component {
    componentDidMount() {
        document.body.addEventListener('click', this.handleClickOut, false);
    }

    componentWillUnmount() {
        document.body.removeEventListener('click', this.handleClickOut, false);
    }

    handleClickOut = event => {
        if(event.target != this.refs.btn) { // Actually more complicated, event.target can be a child of button (icon, span, etc)
            this.handleBlur();
        }
    }

    handleBlur() {}

    render() {
        return (
            <button
                ref='btn'
                type="button"
            >
                {text}
            </button>
        );
    }
}

possibly with a component that wraps your button

<ClickOut onClickOut={this.handleBlur}>
    <button
        onClick={this.handleAction}
        onMouseDown={this.handleFocus} />
</ClickOut>

Any time you click on your document, if target is not <button /> or one of its child nodes, trigger the click out pseudo event


问:
Loading Module on an Air/Android application
I'm building an Air for Android App and I'm having problems loading a flex module. Does anyone know if loading modules is possible???

I built a simple app with just a ModuleLoader in it, which loads a mx:module. The module has only a simple mx:Label with a "Hello World" text.

I build a .air with this. Then I build a .apk with the followin adt command.

adt -package -target apk-emulator -storetype pkcs12 -keystore certificate.p12 hello.apk hello.air

The application works just fine when running it on the PC, but when I do it on the apk-emulator it just goes blank and throws error #2032.

答:
I've just solved it. You can't generate the apk using the air file, at least not the way I did it.

I've just generated the apk using the following:

adt -package -target apk -storetype pkcs12 -keystore certificate.p12 AndroidApp.apk AndroidApp-app.xml AndroidApp.swf module.swf

AndroidApp.swf was my main application and module.swf was my module. It worked like a charm :D

Bye!

Gabriel.-

ContentLicense: CC BY-SA 2.5


问:
How would I test for a Application with a certain title being the active window and return the value?
I'm not super experienced in coding. I'll admit I know that the bare basic of the concept should be possible considering I've seen these particular strings while searching for this very thing on other sources:

```<code>if (title === "") {
sh.SendKeys(keys);
WScript.Quit(0);
}
if (sh.AppActivate(title)){
sh.SendKeys(keys);
WScript.Quit(0);
} else {
</code>```

However, I'm not sure how to set up a JavaScript excerpt or how to test to see if a specific title is the active window and return the value back to the batch-file if true or false how would I do so? I'm currently using this:

```<code>:loop
@echo off
tasklist /V /FI "IMAGENAME eq Test.exe" 2>NUL | find /I /N "Test.exe">NUL
if "%ERRORLEVEL%"=="0" echo Working
goto loop
</code>```

However, it's not able to detect the active window or anything like that so I began searching for JavaScript and figured out that it should be possible. However, the code I found was for sending keys and not particularly what I needed.

Of course, I don't intend to take credit for others work but I'm just trying to piece something semi-functional together. I want to have a program run only while another program is active and close when it isn't the active window.

答:
May be I misunderstand you, but if your actual question is how to retrieve the active window title from batch, you must use an hybrid script containing both batch code and another language code that can call the windows api.

There are lot of examples about hybrid batch scripts, here is c# which does the proper API calls.

```<code>//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal
set "theExeFile=getForeWinData.exe"
if not exist "%theExeFile%" call :build_the_exe || exit/B

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  echo/Foreground window title is [%%a]
  echo/Created by process [%%b] thread [%%c]
  echo/
  echo/Now do whatever you wanna do with this info
)
endlocal
exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"%theExeFile%" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
using System;
using System.Text;
using System.Runtime.InteropServices;
public class GetWindow {
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern IntPtr GetForegroundWindow();
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowTextLength(IntPtr hWnd);
  [DllImport("user32.dll", SetLastError=true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

  public static void Main()
  {
    string strTitle = string.Empty;
    IntPtr handle = GetForegroundWindow();
    int intLength = GetWindowTextLength(handle) + 1;
    StringBuilder stringBuilder = new StringBuilder(intLength);
    uint procId=0;
    uint thrdId = GetWindowThreadProcessId(handle, out procId);
    if (GetWindowText(handle, stringBuilder, intLength) > 0)
      strTitle = stringBuilder.ToString();
    strTitle = string.Format("{0}^{1}^{2}", strTitle, procId.ToString(), thrdId.ToString());
    Console.WriteLine(strTitle);
  }
}
</code>```

Save this as i.e test.bat and run it. The first time, it will create the getForeWinData.exe as it doesn't exist, and then call it in a for loop to grab its output. Once the exe is created, you may remove the hybrid part and simply call the newly created exe.

```<code>@echo off
setlocal
set "theExeFile=getForeWinData.exe"

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  echo/Foreground window title is [%%a]
  echo/Created by process [%%b] thread [%%c]
  echo/
  echo/Now do whatever you wanna do with this info
)

endlocal
exit /b 0
</code>```

Another example of hybrid batch, now using cscript to minimize the calculator if it is open.

```<code>@echo off

set "lookFor=Calculator"

for /f "tokens=2 delims=," %%A in ('tasklist /nh /fo csv /fi "WINDOWTITLE eq %lookfor%"') do set "pid=%%~A"

>"%TEMP%\close.vbs" (
  echo/Set oShell = CreateObject("WScript.Shell"^)
  echo/oShell.AppActivate %pid%
  echo/WScript.Sleep 500
  echo/oShell.SendKeys "%% (n)" ' minimize (Alt+SpaceBar,n^)
)

start /B cmd /C "CScript //nologo //E:vbs "%TEMP%\close.vbs" & del /F /Q "%TEMP%\close.vbs" >NUL 2>NUL"

exit/B
</code>```

EDIT: to check for a certain window title

```<code>@echo off
setlocal
set "theExeFile=getForeWinData.exe"

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  if /i "%%a" == "my window title text" (
    echo let's do some action here
  )
)

endlocal
exit /b 0
</code>```

Body:
I'm not super experienced in coding. I'll admit I know that the bare basic of the concept should be possible considering I've seen these particular strings while searching for this very thing on other sources:

if (title === "") {
sh.SendKeys(keys);
WScript.Quit(0);
}
if (sh.AppActivate(title)){
sh.SendKeys(keys);
WScript.Quit(0);
} else {

However, I'm not sure how to set up a JavaScript excerpt or how to test to see if a specific title is the active window and return the value back to the batch-file if true or false how would I do so? I'm currently using this:

:loop
@echo off
tasklist /V /FI "IMAGENAME eq Test.exe" 2>NUL | find /I /N "Test.exe">NUL
if "%ERRORLEVEL%"=="0" echo Working
goto loop

However, it's not able to detect the active window or anything like that so I began searching for JavaScript and figured out that it should be possible. However, the code I found was for sending keys and not particularly what I needed.

Of course, I don't intend to take credit for others work but I'm just trying to piece something semi-functional together. I want to have a program run only while another program is active and close when it isn't the active window.

Body:
May be I misunderstand you, but if your actual question is how to retrieve the active window title from batch, you must use an hybrid script containing both batch code and another language code that can call the windows api.

There are lot of examples about hybrid batch scripts, here is c# which does the proper API calls.

//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal
set "theExeFile=getForeWinData.exe"
if not exist "%theExeFile%" call :build_the_exe || exit/B

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  echo/Foreground window title is [%%a]
  echo/Created by process [%%b] thread [%%c]
  echo/
  echo/Now do whatever you wanna do with this info
)
endlocal
exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"%theExeFile%" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
using System;
using System.Text;
using System.Runtime.InteropServices;
public class GetWindow {
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern IntPtr GetForegroundWindow();
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
  [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowTextLength(IntPtr hWnd);
  [DllImport("user32.dll", SetLastError=true)] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

  public static void Main()
  {
    string strTitle = string.Empty;
    IntPtr handle = GetForegroundWindow();
    int intLength = GetWindowTextLength(handle) + 1;
    StringBuilder stringBuilder = new StringBuilder(intLength);
    uint procId=0;
    uint thrdId = GetWindowThreadProcessId(handle, out procId);
    if (GetWindowText(handle, stringBuilder, intLength) > 0)
      strTitle = stringBuilder.ToString();
    strTitle = string.Format("{0}^{1}^{2}", strTitle, procId.ToString(), thrdId.ToString());
    Console.WriteLine(strTitle);
  }
}

Save this as i.e test.bat and run it. The first time, it will create the getForeWinData.exe as it doesn't exist, and then call it in a for loop to grab its output. Once the exe is created, you may remove the hybrid part and simply call the newly created exe.

@echo off
setlocal
set "theExeFile=getForeWinData.exe"

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  echo/Foreground window title is [%%a]
  echo/Created by process [%%b] thread [%%c]
  echo/
  echo/Now do whatever you wanna do with this info
)

endlocal
exit /b 0

Another example of hybrid batch, now using cscript to minimize the calculator if it is open.

@echo off

set "lookFor=Calculator"

for /f "tokens=2 delims=," %%A in ('tasklist /nh /fo csv /fi "WINDOWTITLE eq %lookfor%"') do set "pid=%%~A"

>"%TEMP%\close.vbs" (
  echo/Set oShell = CreateObject("WScript.Shell"^)
  echo/oShell.AppActivate %pid%
  echo/WScript.Sleep 500
  echo/oShell.SendKeys "%% (n)" ' minimize (Alt+SpaceBar,n^)
)

start /B cmd /C "CScript //nologo //E:vbs "%TEMP%\close.vbs" & del /F /Q "%TEMP%\close.vbs" >NUL 2>NUL"

exit/B

EDIT: to check for a certain window title

@echo off
setlocal
set "theExeFile=getForeWinData.exe"

for /F "tokens=1,2* delims=^^" %%a in ('%theExeFile%') do (
  if /i "%%a" == "my window title text" (
    echo let's do some action here
  )
)

endlocal
exit /b 0


问:
Docker login working only with daemon but not with Docker active service
I have been trying to set up nexus3 as private registry for the Docker images with nginx serving as a reverse proxy for nexus3.

I have been encountering all types of error ranging from Forbidden to Connection Refused and have tried all reference steps.

Below are my configurations.

I have set up a self-signed certificate (orgnexus.crt) with key (orgnexus.key) and  used the same as reverse proxy with nginx.

Nexus is configured with port 4444 and the docker hosted repo configured with https port 6666. Nexus is configured to run on "server908" while docker is running on "server446"

Below is the configuration for nginx.

```<code>server {

    listen 6666;
    server_name server908.int.org.com;
    keepalive_timeout 60;

    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

    client_max_body_size 1G;
    chunked_transfer_encoding on;

    location /v2/ {

            access_log              /var/log/nginx/docker.log;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto "https";
            proxy_pass              http://server908.int.org.com:4444/;
            proxy_read_timeout      90;
}

    location / {

            access_log              /var/log/nginx/docker.log;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto "https";
            proxy_pass              http://server908.int.org.com:4444/;
            proxy_read_timeout      90;
    }
}
</code>```

The same cert (orgnexus.crt) has been imported to the docker server at location /etc/docker/certs.d/server.int.org.com:6666.

```<code>[root@server446 server908.int.org.com:6666]# ls -ltr
-rwxr-xr-x. 1 root root 2139 May 31 12:07 ca.crt
</code>```

Copied the nexus cert file (orgnexus.crt) to "server446" at location /etc/pki/ca-trust/source/anchors/server.int.org.com.crt

We are running docker version 1.12.6 and nexus 3.2.1-01.

The issue here comes when the docker service is active.

```<code>Active: active (running) since Thu 2017-06-01 20:20:36 HKT; 15h ago
[root@server446 ~]# docker login server908.int.org.com:6666
Username (admin): admin
Password:
Error response from daemon: Get https://server908.int.org.com/v2/: Forbidden
</code>```

But when we run docker daemon manually with the docker service down, the same command goes through successfully.

```<code>[root@server446 ~]# docker login server908.int.org.com:6666
Username (admin): admin
Password:
Login Succeeded
</code>```

"dockertest" is the username at "server446" .

Below is the docker info logs.

When Daemon run manually with Docker client service down

```<code>Containers: 2
 Running: 0
 Paused: 0
 Stopped: 2
Images: 2
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-253:8-131425-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 24.77 MB
 Data Space Total: 107.4 GB
 Data Space Available: 8.877 GB
 Metadata Space Used: 602.1 kB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.147 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: null overlay host bridge
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 3.10.0-514.10.2.el7.x86_64
Operating System: Red Hat Enterprise Linux Server 7.3 (Maipo)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 4
Total Memory: 7.64 GiB
Name: server446.int.org.com
ID: 3EMU:FC6L:454V:5WN4:BUXQ:AUVM:3E7D:T2TD:7G4M:AHS4:NAJ6:42OS
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 16
 Goroutines: 23
 System Time: 2017-06-05T12:04:47.223159468+08:00
 EventsListeners: 0
Registry: https://index.docker.io/v1/
WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
Insecure Registries:
 server908.int.org.com:6666,x.y.z.232:6666
 127.0.0.0/8
Registries: docker.io (secure)
</code>```

With Docker client service up.

```<code>Containers: 26
 Running: 1
 Paused: 0
 Stopped: 25
Images: 12
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: vg00-docker--pool
 Pool Blocksize: 524.3 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file:
 Metadata file:
 Data Space Used: 4.749 GB
 Data Space Total: 8.623 GB
 Data Space Available: 3.874 GB
 Metadata Space Used: 2.019 MB
 Metadata Space Total: 134.2 MB
 Metadata Space Available: 132.2 MB
 Thin Pool Minimum Free Space: 861.9 MB
 Udev Sync Supported: true
 Deferred Removal Enabled: true
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: bridge overlay null host
 Authorization: rhel-push-plugin
Swarm: inactive
Runtimes: docker-runc runc
Default Runtime: docker-runc
Security Options: seccomp selinux
Kernel Version: 3.10.0-514.10.2.el7.x86_64
Operating System: Red Hat Enterprise Linux Server 7.3 (Maipo)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 4
Total Memory: 7.64 GiB
Name: server446.int.org.com
ID: 3EMU:FC6L:454V:5WN4:BUXQ:AUVM:3E7D:T2TD:7G4M:AHS4:NAJ6:42OS
Docker Root Dir: /app/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 24
 Goroutines: 33
 System Time: 2017-06-05T12:02:26.153754978+08:00
 EventsListeners: 0
Http Proxy: http://10.10.120.98:3128
Https Proxy: http://10.10.120.98:3128
Registry: https://index.docker.io/v1/
WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
Insecure Registries:
 server908.int.org.com:6666,x.y.z.232:6666
 127.0.0.0/8
Registries: docker.io (secure)
</code>```

Within daemon logs(/var/log/daemon.log) I notice this .

```<code>Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.837496046+08:00" level=debug msg="Calling POST /v1.24/auth"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.838840542+08:00" level=debug msg="form data: {\"password\":\"*****\",\"serveraddress\":\"server908.int.org.com:6666\",\"username\":\"admin\"}"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.842033018+08:00" level=info msg="{Action=auth, Username=dockertest, LoginUID=1960, PID=31397}"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.843339118+08:00" level=debug msg="AuthZ request using plugin rhel-push-plugin"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.845046779+08:00" level=debug msg="hostDir: /etc/docker/certs.d/server908.int.org.com:6666"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.875205677+08:00" level=debug msg="crt: /etc/docker/certs.d/server908.int.org.com:6666/ca.crt"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.875890502+08:00" level=debug msg="attempting v2 login to registry endpoint https://server908.int.org.com:6666/v2/"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879260054+08:00" level=info msg="Error logging in to v2 endpoint, trying next endpoint: Get https://server908.int.org.com:6666/v2/: Forbidden"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879318527+08:00" level=error msg="Handler for POST /v1.24/auth returned error: Get https://server908.int.org.com:6666/v2/: Forbidden"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879342144+08:00" level=error msg="Handler for POST /v1.24/auth returned error: Get https://server908.int.org.com:6666/v2/: Forbidden"
</code>```

Where I am going wrong? Is it something related to docker group permissions or nginx or the configurations? I suspect the request (from docker client machine) is not reaching to nginx (server908) and is revolving between docker client and daemon.

答:
I was able to solve the issue and was able to login after configuring nginx correctly referring docker login not working with nexus 3 private registry

Nexus HTTP Port : 8082

Docker Hosted Repo HTTP Port : 4444

Below is my nginx configuration .

```<code>    server {

    proxy_send_timeout 120;
    proxy_read_timeout 300;
    proxy_buffering    off;
    tcp_nodelay        on;

    server_tokens off;
    client_max_body_size 1G;

    listen 80;
    server_name server908.int.org.com;
    location / {
          rewrite ^(.*) https://server908.int.org.com$1 permanent;
    }
}

server {

    listen 443;
    server_name server908.int.org.com;
    keepalive_timeout 60;
    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

    location / {

      proxy_set_header        Host $http_host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto "https";
      proxy_pass              http://server908.int.org.com:8082;
      proxy_read_timeout      90;

    }
}

# correlates to your nexus http connector
server {

    listen 6666;
    server_name server908.int.org.com;
    keepalive_timeout 60;
    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;
    client_max_body_size 1G;
    chunked_transfer_encoding on;

    location / {

      access_log              /var/log/nginx/docker.log;
      proxy_set_header        Host $http_host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto "https";
      proxy_pass              http://server908.int.org.com:4444;
      proxy_read_timeout      90;

    }
}
</code>```

Body:
I have been trying to set up nexus3 as private registry for the Docker images with nginx serving as a reverse proxy for nexus3.

I have been encountering all types of error ranging from Forbidden to Connection Refused and have tried all reference steps.

Below are my configurations.

I have set up a self-signed certificate (orgnexus.crt) with key (orgnexus.key) and  used the same as reverse proxy with nginx.

Nexus is configured with port 4444 and the docker hosted repo configured with https port 6666. Nexus is configured to run on "server908" while docker is running on "server446"

Below is the configuration for nginx.

server {

    listen 6666;
    server_name server908.int.org.com;
    keepalive_timeout 60;

    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

    client_max_body_size 1G;
    chunked_transfer_encoding on;

    location /v2/ {

            access_log              /var/log/nginx/docker.log;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto "https";
            proxy_pass              http://server908.int.org.com:4444/;
            proxy_read_timeout      90;
}

    location / {

            access_log              /var/log/nginx/docker.log;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto "https";
            proxy_pass              http://server908.int.org.com:4444/;
            proxy_read_timeout      90;
    }
}

The same cert (orgnexus.crt) has been imported to the docker server at location /etc/docker/certs.d/server.int.org.com:6666.

[root@server446 server908.int.org.com:6666]# ls -ltr
-rwxr-xr-x. 1 root root 2139 May 31 12:07 ca.crt

Copied the nexus cert file (orgnexus.crt) to "server446" at location /etc/pki/ca-trust/source/anchors/server.int.org.com.crt

We are running docker version 1.12.6 and nexus 3.2.1-01.

The issue here comes when the docker service is active.

Active: active (running) since Thu 2017-06-01 20:20:36 HKT; 15h ago
[root@server446 ~]# docker login server908.int.org.com:6666
Username (admin): admin
Password:
Error response from daemon: Get https://server908.int.org.com/v2/: Forbidden

But when we run docker daemon manually with the docker service down, the same command goes through successfully.

[root@server446 ~]# docker login server908.int.org.com:6666
Username (admin): admin
Password:
Login Succeeded

"dockertest" is the username at "server446" .

Below is the docker info logs.

When Daemon run manually with Docker client service down

Containers: 2
 Running: 0
 Paused: 0
 Stopped: 2
Images: 2
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-253:8-131425-pool
 Pool Blocksize: 65.54 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 24.77 MB
 Data Space Total: 107.4 GB
 Data Space Available: 8.877 GB
 Metadata Space Used: 602.1 kB
 Metadata Space Total: 2.147 GB
 Metadata Space Available: 2.147 GB
 Thin Pool Minimum Free Space: 10.74 GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 WARNING: Usage of loopback devices is strongly discouraged for production use. Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: null overlay host bridge
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 3.10.0-514.10.2.el7.x86_64
Operating System: Red Hat Enterprise Linux Server 7.3 (Maipo)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 4
Total Memory: 7.64 GiB
Name: server446.int.org.com
ID: 3EMU:FC6L:454V:5WN4:BUXQ:AUVM:3E7D:T2TD:7G4M:AHS4:NAJ6:42OS
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 16
 Goroutines: 23
 System Time: 2017-06-05T12:04:47.223159468+08:00
 EventsListeners: 0
Registry: https://index.docker.io/v1/
WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
Insecure Registries:
 server908.int.org.com:6666,x.y.z.232:6666
 127.0.0.0/8
Registries: docker.io (secure)

With Docker client service up.

Containers: 26
 Running: 1
 Paused: 0
 Stopped: 25
Images: 12
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: vg00-docker--pool
 Pool Blocksize: 524.3 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file:
 Metadata file:
 Data Space Used: 4.749 GB
 Data Space Total: 8.623 GB
 Data Space Available: 3.874 GB
 Metadata Space Used: 2.019 MB
 Metadata Space Total: 134.2 MB
 Metadata Space Available: 132.2 MB
 Thin Pool Minimum Free Space: 861.9 MB
 Udev Sync Supported: true
 Deferred Removal Enabled: true
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: journald
Cgroup Driver: systemd
Plugins:
 Volume: local
 Network: bridge overlay null host
 Authorization: rhel-push-plugin
Swarm: inactive
Runtimes: docker-runc runc
Default Runtime: docker-runc
Security Options: seccomp selinux
Kernel Version: 3.10.0-514.10.2.el7.x86_64
Operating System: Red Hat Enterprise Linux Server 7.3 (Maipo)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 4
Total Memory: 7.64 GiB
Name: server446.int.org.com
ID: 3EMU:FC6L:454V:5WN4:BUXQ:AUVM:3E7D:T2TD:7G4M:AHS4:NAJ6:42OS
Docker Root Dir: /app/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 24
 Goroutines: 33
 System Time: 2017-06-05T12:02:26.153754978+08:00
 EventsListeners: 0
Http Proxy: http://10.10.120.98:3128
Https Proxy: http://10.10.120.98:3128
Registry: https://index.docker.io/v1/
WARNING: bridge-nf-call-iptables is disabled
WARNING: bridge-nf-call-ip6tables is disabled
Insecure Registries:
 server908.int.org.com:6666,x.y.z.232:6666
 127.0.0.0/8
Registries: docker.io (secure)

Within daemon logs(/var/log/daemon.log) I notice this .

Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.837496046+08:00" level=debug msg="Calling POST /v1.24/auth"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.838840542+08:00" level=debug msg="form data: {\"password\":\"*****\",\"serveraddress\":\"server908.int.org.com:6666\",\"username\":\"admin\"}"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.842033018+08:00" level=info msg="{Action=auth, Username=dockertest, LoginUID=1960, PID=31397}"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.843339118+08:00" level=debug msg="AuthZ request using plugin rhel-push-plugin"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.845046779+08:00" level=debug msg="hostDir: /etc/docker/certs.d/server908.int.org.com:6666"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.875205677+08:00" level=debug msg="crt: /etc/docker/certs.d/server908.int.org.com:6666/ca.crt"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.875890502+08:00" level=debug msg="attempting v2 login to registry endpoint https://server908.int.org.com:6666/v2/"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879260054+08:00" level=info msg="Error logging in to v2 endpoint, trying next endpoint: Get https://server908.int.org.com:6666/v2/: Forbidden"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879318527+08:00" level=error msg="Handler for POST /v1.24/auth returned error: Get https://server908.int.org.com:6666/v2/: Forbidden"
Jun  5 13:37:41 server446 dockerd-current[31151]: time="2017-06-05T13:37:41.879342144+08:00" level=error msg="Handler for POST /v1.24/auth returned error: Get https://server908.int.org.com:6666/v2/: Forbidden"

Where I am going wrong? Is it something related to docker group permissions or nginx or the configurations? I suspect the request (from docker client machine) is not reaching to nginx (server908) and is revolving between docker client and daemon.

Body:
I was able to solve the issue and was able to login after configuring nginx correctly referring docker login not working with nexus 3 private registry

Nexus HTTP Port : 8082

Docker Hosted Repo HTTP Port : 4444

Below is my nginx configuration .

    server {

    proxy_send_timeout 120;
    proxy_read_timeout 300;
    proxy_buffering    off;
    tcp_nodelay        on;

    server_tokens off;
    client_max_body_size 1G;

    listen 80;
    server_name server908.int.org.com;
    location / {
          rewrite ^(.*) https://server908.int.org.com$1 permanent;
    }
}

server {

    listen 443;
    server_name server908.int.org.com;
    keepalive_timeout 60;
    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;

    location / {

      proxy_set_header        Host $http_host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto "https";
      proxy_pass              http://server908.int.org.com:8082;
      proxy_read_timeout      90;

    }
}

# correlates to your nexus http connector
server {

    listen 6666;
    server_name server908.int.org.com;
    keepalive_timeout 60;
    ssl on;
    ssl_certificate /etc/ssl/certs/orgnexus.crt;
    ssl_certificate_key /etc/ssl/certs/orgnexus.key;
    ssl_ciphers HIGH:!kEDH:!ADH:!MD5:@STRENGTH;
    ssl_session_cache shared:TLSSSL:16m;
    ssl_session_timeout 10m;
    ssl_prefer_server_ciphers on;
    client_max_body_size 1G;
    chunked_transfer_encoding on;

    location / {

      access_log              /var/log/nginx/docker.log;
      proxy_set_header        Host $http_host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto "https";
      proxy_pass              http://server908.int.org.com:4444;
      proxy_read_timeout      90;

    }
}


问:
LinQ Query Where Condition
I am trying to import data into a new database, but some of the columns in the old database are null.

In one of my methods, I am using the query below to get the records, like I said already there is a column in the rows which has a null value for some records.

```<code>Guid nameGuid= new guid('CCECE54B-EE14-4463-8A0B-02C72679334A')

MySubQuery = from a in MainQuery
              where a.Table1.Id.Equals(nameGuid)
        Select a;
</code>```

I want to check for a.Table1.Id value, if it is equal to null, then I still want the row but ignore the where condition.

Any suggestion for using the ternary operator in Linq query or any other approaches for my task.

答:
```<code> var datarows = (from row in dt.AsEnumerable()
                            where row.Field<Guid>("Id") == new
                 Guid(ddlCode.SelectedValue.ToString())
                            select row);
</code>```

<p>After that </p>

```<code>     DataTable newDt=datarows.CopyToDataTable();
     var sampleName=newDt.Rows[0]["SampleName"].ToString();
</code>```

Title: LinQ Query Where Condition

Body:
I am trying to import data into a new database, but some of the columns in the old database are null.

In one of my methods, I am using the query below to get the records, like I said already there is a column in the rows which has a null value for some records.

Guid nameGuid= new guid('CCECE54B-EE14-4463-8A0B-02C72679334A')

MySubQuery = from a in MainQuery
              where a.Table1.Id.Equals(nameGuid)
        Select a;

I want to check for a.Table1.Id value, if it is equal to null, then I still want the row but ignore the where condition.

Any suggestion for using the ternary operator in Linq query or any other approaches for my task.

Body:
 var datarows = (from row in dt.AsEnumerable()
                            where row.Field<Guid>("Id") == new
                 Guid(ddlCode.SelectedValue.ToString())
                            select row);

After that

     DataTable newDt=datarows.CopyToDataTable();
     var sampleName=newDt.Rows[0]["SampleName"].ToString();


问:
Concat javascript arrays as array of arrays
I have these arrays:

```<code>arr1 = ['29.5',  32035];
arr2 = ['30.5',  32288];
arr3 = ['31.5',  31982];
arr4 = ['1.6',  31768];
</code>```

As a result I want to have something like this:

```<code>result = [['29.5',  32035], ['30.5',  32288], ['31.5',  31982], ['1.6',  31768]];
</code>```

I means the result is array created by another arrays. The question is, how I can concat the arrays. result.push.apply(result, arr1); etc. give me array made by final values.

Thank you for any advice.

答:
You can do this using push .  </p>

```<code>var result = [];

result.push(arr1);
result.push(arr2);
result.push(arr3);
result.push(arr4);

console.log(result);
</code>```

Body:
I have these arrays:

arr1 = ['29.5',  32035];
arr2 = ['30.5',  32288];
arr3 = ['31.5',  31982];
arr4 = ['1.6',  31768];

As a result I want to have something like this:

result = [['29.5',  32035], ['30.5',  32288], ['31.5',  31982], ['1.6',  31768]];

I means the result is array created by another arrays. The question is, how I can concat the arrays. result.push.apply(result, arr1); etc. give me array made by final values.

Thank you for any advice.

Body:
You can do this using push .

var result = [];

result.push(arr1);
result.push(arr2);
result.push(arr3);
result.push(arr4);

console.log(result);


问:
Parse plain email address into 2 parts
How do I get the username and the domain from an email address of:

```<code>string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";
</code>```

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

答:
```<code>int i = email.IndexOf('@');
if (i >= 0)
{
    username = email.Substring(0, i);
    domain = email.Substring(i + 1);
}
</code>```

Title: Parse plain email address into 2 parts

Body:
How do I get the username and the domain from an email address of:

string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.


问:
Can Google Apps Script read txt line by line?
First, I want parse a html and fetch some line

with Google Apps Script, and it's showed

" The element type "link" must be terminated by the matching end-tag "/link " "

and code here

```<code>var response = UrlFetchApp.fetch(url)
var downloadContent = response.getContentText();
var doc = XmlService.parse(downloadContent);
</code>```

I think because the html use html5, that GAS can't parsing,

so I try otherwise method to parsing string,
(read line by line and keep lines which I need)

```<code>var xml = UrlFetchApp.fetch(url).getContentText();
</code>```

but GAS hasn't Scanner, and how can I do?

In fact, I want to go this url "https://www.ptt.cc/bbs/gossiping/index.html"

and fetch information in

```<code><div class="r-ent">
...
</div>
</code>```

答:
Google Apps Script is JavaScript so you can use the split() method to split the text content into multiple lines by the newline character.</p>

```<code>var text = UrlFetchApp.fetch(url).getContentText();
var lines = text.split(/\r?\n/);
Logger.log(lines);
</code>```

Body:
First, I want parse a html and fetch some line

with Google Apps Script, and it's showed

" The element type "link" must be terminated by the matching end-tag "/link " "

and code here

var response = UrlFetchApp.fetch(url)
var downloadContent = response.getContentText();
var doc = XmlService.parse(downloadContent);

I think because the html use html5, that GAS can't parsing,

so I try otherwise method to parsing string,
(read line by line and keep lines which I need)

var xml = UrlFetchApp.fetch(url).getContentText();

but GAS hasn't Scanner, and how can I do?

In fact, I want to go this url "https://www.ptt.cc/bbs/gossiping/index.html"

and fetch information in

...

Body:
Google Apps Script is JavaScript so you can use the split() method to split the text content into multiple lines by the newline character.

var text = UrlFetchApp.fetch(url).getContentText();
var lines = text.split(/\r?\n/);
Logger.log(lines);


问:
App installation tracking using AppsFlyer
I want to track how my android app was installed by user, either by google play store or anything else. I've choosed AppsFlyer for tracking and referenced some sites and just coded to track app events alone and got it on AppsFlyer site too. But couldn't get that much clear about how to track whether its installed from Google PlayStore or any other media source like TapJoy or something else. Could u please suggest me any idea to proceed as soon as possible. Thanks in advance.</p>

答:
Appsflyer provide 2 type of installation tracking

1.Organic install-installation through google play store.
  2.Inorganic install -installation through other media like an external link,advertising api.

hope it helps.


问:
Getting a 503 error but the Apache log doesn't seem to give any clues
I'm getting a 503 error whenever I try to request any page. I really don't know how to go about fixing this problem. I've checked the error.log and this is what it contains:

```<code>[Fri Jan 13 19:03:41 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:03:51 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with     Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:08:59 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:09:41 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:11:59 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:12:45 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:13:03 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:13:14 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Sat Jan 14 11:25:28 2012] [notice] caught SIGWINCH, shutting down gracefully
[Sat Jan 14 11:26:10 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Sat Jan 14 11:34:34 2012] [notice] caught SIGWINCH, shutting down gracefully
</code>```

I assume this is just reporting that I've rebooted the server from the AWS console.

答: Phew, fixed! For the benefit of others, the 503 error seems to have been caused by my elastic load balancer not having any healthy instances to route requests to. This was because the URL I'd been using to check for health was throwing some database errors. I simply changed the health check ping target to a path that was working and everything started working again.</p>

Body:
I'm getting a 503 error whenever I try to request any page. I really don't know how to go about fixing this problem. I've checked the error.log and this is what it contains:

[Fri Jan 13 19:03:41 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:03:51 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with     Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:08:59 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:09:41 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:11:59 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:12:45 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Fri Jan 13 19:13:03 2012] [notice] caught SIGWINCH, shutting down gracefully
[Fri Jan 13 19:13:14 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Sat Jan 14 11:25:28 2012] [notice] caught SIGWINCH, shutting down gracefully
[Sat Jan 14 11:26:10 2012] [notice] Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.17 with Suhosin-Patch configured -- resuming normal operations
[Sat Jan 14 11:34:34 2012] [notice] caught SIGWINCH, shutting down gracefully

I assume this is just reporting that I've rebooted the server from the AWS console.


问:
How to get String[] outside OnCreate()
Here I'm using the following code to create a string current[] using for loop:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imageactivity);

    Intent intent = getIntent();
    String jsonArray = intent.getStringExtra("jsonArray");
   try {
        JSONArray array = new JSONArray(jsonArray);
        for (int i = 0; i < array.length(); i++) {
           JSONObject obj = array.getJSONObject(i);
            String current_name[] = { obj.getString("current_name") }; // array
       }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

// Log.e(TAG,"VALUES" + Arrays.toString(current_name));
</code>```

Now I want to call this current_name[] outside OnCreate or some other method. By using this code I can't Log outside OnCreate. So please help me to solve this issue. Answers will be appreciated.

答:
try this one.

```<code>String current_name[] = {};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageactivity);

Intent intent = getIntent();
String jsonArray = intent.getStringExtra("jsonArray");
try {
    JSONArray array = new JSONArray(jsonArray);
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        current_name[i] =obj.getString("current_name"); // array
   }
} catch (JSONException e) {
    e.printStackTrace();
}
}
</code>```

Now you can access String out of oncreate.

Title: How to get String[] outside OnCreate()

Body:
Here I'm using the following code to create a string current[] using for loop:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imageactivity);

    Intent intent = getIntent();
    String jsonArray = intent.getStringExtra("jsonArray");
   try {
        JSONArray array = new JSONArray(jsonArray);
        for (int i = 0; i < array.length(); i++) {
           JSONObject obj = array.getJSONObject(i);
            String current_name[] = { obj.getString("current_name") }; // array
       }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

// Log.e(TAG,"VALUES" + Arrays.toString(current_name));

Now I want to call this current_name[] outside OnCreate or some other method. By using this code I can't Log outside OnCreate. So please help me to solve this issue. Answers will be appreciated.

Body:
try this one.

String current_name[] = {};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageactivity);

Intent intent = getIntent();
String jsonArray = intent.getStringExtra("jsonArray");
try {
    JSONArray array = new JSONArray(jsonArray);
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        current_name[i] =obj.getString("current_name"); // array
   }
} catch (JSONException e) {
    e.printStackTrace();
}
}

Now you can access String out of oncreate.


问:
Getting an 'invalid File Extension' error on uploading an image file
This is my php code to upload a file. The code is showing a Notice for udentified index in the lines where the variables are initiated. Also the output that is displayed is "Invalid File Extension" while I am uploading a jpeg file. </p>

```<code><?php

    if (isset($_POST["submit"])) {

        $name     = $_FILES['file']['name'];
        $tmpName  = $_FILES['file']['tmp_name'];
        $error    = $_FILES['file']['error'];
        $size     = $_FILES['file']['size'];
        $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        switch ($error) {
            case UPLOAD_ERR_OK:
                $valid = true;
                //validate file extensions
                if ( !in_array($ext, array('jpg','jpeg','png','gif')) ) {
                    echo $ext;
                    $valid = false;
                    $response = 'Invalid file extension.';
                }
                //validate file size
                if ( $size/1024/1024 > 2 ) {
                    $valid = false;
                    $response = 'File size is exceeding maximum allowed size.';
                }
                //upload file
                if ($valid) {
                    $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR. $name;
                    move_uploaded_file($tmpName,$targetPath);
                    header( 'Location: index.php' ) ;
                    exit;
                }
                break;
            case UPLOAD_ERR_INI_SIZE:
                $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;
            case UPLOAD_ERR_PARTIAL:
                $response = 'The uploaded file was only partially uploaded.';
                break;
            case UPLOAD_ERR_NO_FILE:
                $response = 'No file was uploaded.';
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
                break;
            case UPLOAD_ERR_EXTENSION:
                $response = 'File upload stopped by extension. Introduced in PHP 5.2.0.';
                break;
            default:
                $response = 'Unknown error';
            break;
        }

        echo $response;
    }
    ?>
</code>```

<p>The html file is as follows: </p>

```<code><html>
   <body>
     <form method = "post" action = "upload.php">
        <input type="file" name="file">
        <input type="submit" value="Upload Image" name="submit">
     </form>
   </body>
 </html>
</code>```

答: Add the attribute enctype="multipart/form-data" in form tag to send files with the form

Body:
This is my php code to upload a file. The code is showing a Notice for udentified index in the lines where the variables are initiated. Also the output that is displayed is "Invalid File Extension" while I am uploading a jpeg file.

<?php

    if (isset($_POST["submit"])) {

        $name     = $_FILES['file']['name'];
        $tmpName  = $_FILES['file']['tmp_name'];
        $error    = $_FILES['file']['error'];
        $size     = $_FILES['file']['size'];
        $ext      = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        switch ($error) {
            case UPLOAD_ERR_OK:
                $valid = true;
                //validate file extensions
                if ( !in_array($ext, array('jpg','jpeg','png','gif')) ) {
                    echo $ext;
                    $valid = false;
                    $response = 'Invalid file extension.';
                }
                //validate file size
                if ( $size/1024/1024 > 2 ) {
                    $valid = false;
                    $response = 'File size is exceeding maximum allowed size.';
                }
                //upload file
                if ($valid) {
                    $targetPath =  dirname( __FILE__ ) . DIRECTORY_SEPARATOR. 'uploads' . DIRECTORY_SEPARATOR. $name;
                    move_uploaded_file($tmpName,$targetPath);
                    header( 'Location: index.php' ) ;
                    exit;
                }
                break;
            case UPLOAD_ERR_INI_SIZE:
                $response = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $response = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
                break;
            case UPLOAD_ERR_PARTIAL:
                $response = 'The uploaded file was only partially uploaded.';
                break;
            case UPLOAD_ERR_NO_FILE:
                $response = 'No file was uploaded.';
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $response = 'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.';
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $response = 'Failed to write file to disk. Introduced in PHP 5.1.0.';
                break;
            case UPLOAD_ERR_EXTENSION:
                $response = 'File upload stopped by extension. Introduced in PHP 5.2.0.';
                break;
            default:
                $response = 'Unknown error';
            break;
        }

        echo $response;
    }
    ?>

The html file is as follows:

     <form method = "post" action = "upload.php">
        <input type="file" name="file">
        <input type="submit" value="Upload Image" name="submit">
     </form>


问:
BLE only getting Battery Level characteristic Value IOS
I am trying to read all the services available and their characteristics value using CoreBluetooth framework from a device.

```<code>- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral
        advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
        NSLog(@"Received peripheral : \n%@", peripheral);
        NSLog(@"Adv data : %@", advertisementData);

    self.activeperipheral=peripheral;

    [self.myCentralManager connectPeripheral:peripheral options:nil];

    if(peripheral.state==CBPeripheralStateConnected){
        peripheral.delegate=self;
        NSLog(@"Connected");

    }
    else
        NSLog(@"Not Connected");

    NSArray *serviceUUIDs=[advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey];
    for(CBUUID *foundserviceUUIDs in serviceUUIDs){

        if([serviceUUIDs containsObject:foundserviceUUIDs]){
            NSLog(@"%@",serviceUUIDs);
        }
    }

}

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

    for(CBService *service in peripheral.services){
    [peripheral discoverCharacteristics:nil forService:service];
        NSLog(@"Discover Service:%@",service);
    }
}

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

    for(CBCharacteristic *characteristic in service.characteristics){
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        self.myCharacteristic=characteristic;
        NSLog(@"NotifyValue set on %@",characteristic);
        //[peripheral readValueForCharacteristic:myCharacteristic];

    }
}

-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if(characteristic.isNotifying)
    NSLog(@"Notification began on %@",characteristic);
}

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error  {

    NSLog(@"%@",characteristic);
   // NSLog(@"Characteristic Value Updated");
}

- (int)scanForPeripherals {
    NSLog(@"Scanning");

    if(self.myCentralManager.state!=CBCentralManagerStatePoweredOn)
        NSLog(@"Turn on Bluetooth");
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey,
                             nil];
    NSLog(@"Scanning");
    [myCentralManager scanForPeripheralsWithServices:nil options:options];
    return 0;
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"Peripheral Connected");
    peripheral.delegate=self;
    //CBUUID *serviceUUID=[CBUUID UUIDWithString:@"1804"];
    [peripheral discoverServices:nil];
    //[myCentralManager stopScan];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"didDisconnectPeripheral");
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"failed to connect");
}

- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
    NSLog(@"didReadRSSI");
}

@end
</code>```

The problem is I cannot setNotifyValue : Yes for other characteristics except the BatteryLevel characteristic and I am also getting the notification for the same only.

Here is my output.
Any idea what am I doing wrong here?
Thanks

答:
That because your characteristic settings in gatt file (your bluetooth project) is not properly setup. See for example another characteristic settings and update your gatt file.
Another way to get characteristic value use a timer in which read your charackteristic:

```<code>   -(void)TimerFunction
    {
      [talking_peripher readValueForCharacteristic:_talk_charack];
      NSlog("VALUE: %@" _talk_charack);
    }
</code>```

And that is all. But actually best to do -  modify your characteristic settings in gatt file (bluetooth project).

Body:
I am trying to read all the services available and their characteristics value using CoreBluetooth framework from a device.

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral
        advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
        NSLog(@"Received peripheral : \n%@", peripheral);
        NSLog(@"Adv data : %@", advertisementData);

    self.activeperipheral=peripheral;

    [self.myCentralManager connectPeripheral:peripheral options:nil];

    if(peripheral.state==CBPeripheralStateConnected){
        peripheral.delegate=self;
        NSLog(@"Connected");

    }
    else
        NSLog(@"Not Connected");

    NSArray *serviceUUIDs=[advertisementData objectForKey:CBAdvertisementDataServiceUUIDsKey];
    for(CBUUID *foundserviceUUIDs in serviceUUIDs){

        if([serviceUUIDs containsObject:foundserviceUUIDs]){
            NSLog(@"%@",serviceUUIDs);
        }
    }

}

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

    for(CBService *service in peripheral.services){
    [peripheral discoverCharacteristics:nil forService:service];
        NSLog(@"Discover Service:%@",service);
    }
}

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

    for(CBCharacteristic *characteristic in service.characteristics){
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
        self.myCharacteristic=characteristic;
        NSLog(@"NotifyValue set on %@",characteristic);
        //[peripheral readValueForCharacteristic:myCharacteristic];

    }
}

-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
if(characteristic.isNotifying)
    NSLog(@"Notification began on %@",characteristic);
}

-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error  {

    NSLog(@"%@",characteristic);
   // NSLog(@"Characteristic Value Updated");
}

- (int)scanForPeripherals {
    NSLog(@"Scanning");

    if(self.myCentralManager.state!=CBCentralManagerStatePoweredOn)
        NSLog(@"Turn on Bluetooth");
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey,
                             nil];
    NSLog(@"Scanning");
    [myCentralManager scanForPeripheralsWithServices:nil options:options];
    return 0;
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"Peripheral Connected");
    peripheral.delegate=self;
    //CBUUID *serviceUUID=[CBUUID UUIDWithString:@"1804"];
    [peripheral discoverServices:nil];
    //[myCentralManager stopScan];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"didDisconnectPeripheral");
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"failed to connect");
}

- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
    NSLog(@"didReadRSSI");
}

@end

The problem is I cannot setNotifyValue : Yes for other characteristics except the BatteryLevel characteristic and I am also getting the notification for the same only.

Here is my output.
Any idea what am I doing wrong here?
Thanks

Body:
That because your characteristic settings in gatt file (your bluetooth project) is not properly setup. See for example another characteristic settings and update your gatt file.
Another way to get characteristic value use a timer in which read your charackteristic:

   -(void)TimerFunction
    {
      [talking_peripher readValueForCharacteristic:_talk_charack];
      NSlog("VALUE: %@" _talk_charack);
    }

And that is all. But actually best to do -  modify your characteristic settings in gatt file (bluetooth project).


问:
Restore only changed files with duplicity
I've a problem. Duplicity is perfect for backups, I love so much that can be able to do incremental diff tars, but ... when restoring duplicity seems don't apply same concept.

Basically I need to restore only changed files (obviously after a full backup) but I can't figure how do that.

When I try to restore a directory I get:

```Restore destination directory /Volumes/Data/Backups/Srv1 already exists.```

I need to backup a directory (and I don't have any problems in doing that) and setup a mirror on another machine.

Thanks!

答:
First of all, duplicity doesn't overwrite anything when restoring. So your <target_folder> must not exist.

To your actual question: This sounds like a job for rsync and not for duplicity. Is there an actual reason the mirror needs to be generated from the backup and not from the source?

I guess it should be possible to write a shell script which compiles a list of changed files from the duplicity manifest file (duplicity-inc.<timestamp>.to.<timestamp>.manifest, can also be found in ~/.cache/duplicity/) and feeds it to the --files-to-restore option. But it can quickly lead to other problems, like hitting your shell's line length limit and having to accommodate for special characters in file names and so on.

Restore syntax for reference:

duplicity restore [--file-to-restore <relpath>] [--time <time>] <url> <target_folder>

Edit:

Oh my, just seen how old the question is ;-)

Body:
I've a problem. Duplicity is perfect for backups, I love so much that can be able to do incremental diff tars, but ... when restoring duplicity seems don't apply same concept.

Basically I need to restore only changed files (obviously after a full backup) but I can't figure how do that.

When I try to restore a directory I get:

Restore destination directory /Volumes/Data/Backups/Srv1 already exists.

I need to backup a directory (and I don't have any problems in doing that) and setup a mirror on another machine.

Thanks!


问:
Angular2 IE11 caching issue
I have an caching problem every time I do simple CORS get request on IE. This is not happening on Chrome. So i had to add options on get request:

```<code>            let options = new RequestOptions({
                url: this.elementsUrl,
                method: RequestMethod.Get,
                headers: this.getHeaders
            });
            return this.http.get(this.elementsUrl, options)
                .map(response => response.json())
                .catch(error => {
                        console.error('Error', error);
                        return Promise.reject(error.message || error);
                    }
                );
</code>```

And I set headers to disable cache.

```<code>    private _getHeaders = new Headers({
    'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache'
});
</code>```

And now I am getting info required CORS preflight and XMLHttpRequest: Network Error 0x80070005, Access is denied. Can I avoid triggering preflight options? Am I setting options correctly?

It's only related to IE that do caching of GET request. CORS is working OK on chrome. On server side is set: Access-Control-Allow-Origin: *

答:
On server side in case of JAVA I have created a filter as below

@PreMatching
@Provider
public class GwsApiCorsFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", getAllowedHeaders());
        responseContext.getHeaders().add("Access-Control-Expose-Headers", getAllowedHeaders());

    }

    private String getAllowedHeaders() {
        StringBuilder sb = new StringBuilder();
        sb.append(HttpHeaders.ACCEPT).append(", ")
        .append(HttpHeaders.CONTENT_TYPE).append(", ")
        .append(HttpHeaders.AUTHORIZATION).append(", ")
        .append(HEADER_IF_MODIFIED_SINCE).append(", ")
        .append(HEADER_CACHE_CONTROL).append(", ")
        .append(HEADER_PRAGMA).append(", ")
        .append(HEADER_CONTENT_DISPOSITION).append(", ");
        return sb.toString();
    }
}
```

And on client in angular implement http interceptor using following tutorial

https://scotch.io/@kashyapmukkamala/using-http-interceptor-with-angular2

Add all the headers in request in the private getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {} function

Title: Angular2 IE11 caching issue

Body:
I have an caching problem every time I do simple CORS get request on IE. This is not happening on Chrome. So i had to add options on get request:

            let options = new RequestOptions({
                url: this.elementsUrl,
                method: RequestMethod.Get,
                headers: this.getHeaders
            });
            return this.http.get(this.elementsUrl, options)
                .map(response => response.json())
                .catch(error => {
                        console.error('Error', error);
                        return Promise.reject(error.message || error);
                    }
                );

And I set headers to disable cache.

    private _getHeaders = new Headers({
    'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache'
});

And now I am getting info required CORS preflight and XMLHttpRequest: Network Error 0x80070005, Access is denied. Can I avoid triggering preflight options? Am I setting options correctly?

It's only related to IE that do caching of GET request. CORS is working OK on chrome. On server side is set: Access-Control-Allow-Origin: *

Body:
On server side in case of JAVA I have created a filter as below

@PreMatching
@Provider
public class GwsApiCorsFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", getAllowedHeaders());
        responseContext.getHeaders().add("Access-Control-Expose-Headers", getAllowedHeaders());

    }

    private String getAllowedHeaders() {
        StringBuilder sb = new StringBuilder();
        sb.append(HttpHeaders.ACCEPT).append(", ")
        .append(HttpHeaders.CONTENT_TYPE).append(", ")
        .append(HttpHeaders.AUTHORIZATION).append(", ")
        .append(HEADER_IF_MODIFIED_SINCE).append(", ")
        .append(HEADER_CACHE_CONTROL).append(", ")
        .append(HEADER_PRAGMA).append(", ")
        .append(HEADER_CONTENT_DISPOSITION).append(", ");
        return sb.toString();
    }
}

And on client in angular implement http interceptor using following tutorial

https://scotch.io/@kashyapmukkamala/using-http-interceptor-with-angular2

Add all the headers in request in the private getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {} function