问:
How to Observe a Custom Event using RXJS in Angular 2?
I have a third party library that I am intending to integrate with RxJS. This is a messaging library called Tiger Text. According to them I can listen to an event called messages and when the stream has a message I can use it to further utilize it. The code snippet for the same is as follows:-

```<code>var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' })

client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session)
})

function onSignedIn(session) {
  console.log('Signed in as', session.user.displayName)

  client.messages.sendToUser(
    'someone@mail.com',
    'hello!'
  ).then(function (message) {
    console.log('sent', message.body, 'to', message.recipient.displayName)
  })

  client.events.connect()

  client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
}
</code>```

Now please have a look at the place where you have the below mentioned piece of code.

```<code>client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
</code>```

I wanted to know how to use RxJS so as to create an observable out of this piece of code so as to subscribe to the stream and whenever we have a change I take the new data and process it as I wish.

Please Advice.

答:
For this use-cases you typically don't need to write a custom Observable and you can use just Observable.create(). Then it depends on whether you want to write a cold or a hot observable.

For cold Observables you create the producer of values when subscribing and close it when unsubscribing:

```<code>Observable.create(obs => {
  var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' });
  client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
    onSignedIn(session);
  });

  client.on('message', function (message) {
    obs.next(...);
  });

  return () => {
    client.close(); // or whatever...
  };
});
</code>```

Or if you want to write a hot Observable the producer will exist independently on any subscriptions and just add/remove the listener:

```<code>var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' });
client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session);
});

Observable.create(obs => {
  let listener = client.on('message', function (message) {
    obs.next(...);
  });

  () => {
    // remove the event listener somehow
    listener.remove();
  };
});
</code>```

Sometimes you can see this solved by using a Subject but this is usually more complicated than using Observable.create() because then you need to handle the creation and tear down logic yourself and also Subjects have internal state.

Here's a very similar question as yours:

Subscribe to a stream with RxJS and twitter-stream-api module

Articles on the topics related to your question by the lead developer of RxJS:

https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339

https://medium.com/@benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93

https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87

Body:
I have a third party library that I am intending to integrate with RxJS. This is a messaging library called Tiger Text. According to them I can listen to an event called messages and when the stream has a message I can use it to further utilize it. The code snippet for the same is as follows:-

var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' })

client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session)
})

function onSignedIn(session) {
  console.log('Signed in as', session.user.displayName)

  client.messages.sendToUser(
    'someone@mail.com',
    'hello!'
  ).then(function (message) {
    console.log('sent', message.body, 'to', message.recipient.displayName)
  })

  client.events.connect()

  client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })
}

Now please have a look at the place where you have the below mentioned piece of code.

client.on('message', function (message) {
    console.log(
      'message event',
      message.sender.displayName,
      'to',
      message.recipient.displayName,
      ':',
      message.body
    )
  })

I wanted to know how to use RxJS so as to create an observable out of this piece of code so as to subscribe to the stream and whenever we have a change I take the new data and process it as I wish.

Please Advice.

Body:
For this use-cases you typically don't need to write a custom Observable and you can use just Observable.create(). Then it depends on whether you want to write a cold or a hot observable.

For cold Observables you create the producer of values when subscribing and close it when unsubscribing:

Observable.create(obs => {
  var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' });
  client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
    onSignedIn(session);
  });

  client.on('message', function (message) {
    obs.next(...);
  });

  return () => {
    client.close(); // or whatever...
  };
});

Or if you want to write a hot Observable the producer will exist independently on any subscriptions and just add/remove the listener:

var client = new TigerConnect.Client({ defaultOrganizationId: 'some-org-id' });
client.signIn('user@mail.com', 's3cr3t', { udid: 'unique-device-id' }).then(function (session) {
  onSignedIn(session);
});

Observable.create(obs => {
  let listener = client.on('message', function (message) {
    obs.next(...);
  });

  () => {
    // remove the event listener somehow
    listener.remove();
  };
});

Sometimes you can see this solved by using a Subject but this is usually more complicated than using Observable.create() because then you need to handle the creation and tear down logic yourself and also Subjects have internal state.

Here's a very similar question as yours:

Subscribe to a stream with RxJS and twitter-stream-api module

Articles on the topics related to your question by the lead developer of RxJS:

https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339

https://medium.com/@benlesh/on-the-subject-of-subjects-in-rxjs-2b08b7198b93

https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

https://medium.com/@benlesh/learning-observable-by-building-observable-d5da57405d87


来源: stackexchange

问:
Python in Visual Studio 2015 for Micsrosoft Windows CE 7.0
Questions:
(Q1) How can I write a GUI Python code in Visual Studio 2015 for a hand held scanner which runs Microsoft Windows CE 7.0 - (Q2) how can I upload the python code from VS'15 onto the scanner's Windows CE 7.0.

Background/Research: I have a hand held scanner where we want to create our own GUI so that the user interface is dead simple. Some reading led that Visual Studio 2015 will be required as it supports Python. I installed it and wrote a "hello world!' code in Python within VS'15. Moving on to a GUI I will be using TKinter or a similar library that will create a GUI. But I just want to ask (Q3) if there is also another alternative method that I might have missed?

答:
As far as I know there is no official python implementation supporting Windows CE and the existing one http://pythonce.sourceforge.net/ was no longer updated since 2013.
VS2015 supports Python tools and you may even be able to do remote debugging if the python runtime supports it, but I never tried that on Windows CE.
If you need to implement a simple GUI application and your device supports it, you may use the .NET Compact Framework and develop your application in C# or VB.NET, I know they are not as nice as Python :) but it is probably the simplest solution.
That would also mean using VS2008 (developing for CE nowadays is like travelling back in time).</p>

ContentLicense: CC BY-SA 3.0


问:
what does the code mean?
pleas help me understand that's the meaning of following code. the functions after the route are executed continuously one by one, or depending on the http request type, only execute one at a time? Thanks</p>

```<code>app.route('/api/articles/:articleId')
   .get(articles.read)
   .put(users.requiresLogin, articles.hasAuthorization, articles.update)
   .delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
</code>```

答:
What is not clear here?

You call an API endpoint (route).
For get() request you don't need authorisation, whilst for put() and delete() you need.

You have 3 chained methods, instead calling each one separately.

And it won't call all 3 methods at once, but rather call the right one based on request sent to the endpoint. You can have one request, and based on that it will iterate through a method calls, and see the method that corresponds to a request.
If the request type doesn't exist it will discard it and present you with error.

That means if you want to fetch data get() will hapilly return data if it exists, and for other two will ask you to Log in(authorize) the changes.

Hopefully this answers your question.

Title: what does the code mean?

Body:
pleas help me understand that's the meaning of following code. the functions after the route are executed continuously one by one, or depending on the http request type, only execute one at a time? Thanks

app.route('/api/articles/:articleId')
   .get(articles.read)
   .put(users.requiresLogin, articles.hasAuthorization, articles.update)
   .delete(users.requiresLogin, articles.hasAuthorization, articles.delete);


问:
Elegantly selecting attributes from has_many :through join models in Rails
I'm wondering what the easiest/most elegant way of selecting attributes from join models in has_many :through associations is.

Lets say we have Items, Catalogs, and CatalogItems with the following Item class:

```<code>class Item < ActiveRecord::Base
      has_many :catalog_items
      has_many :catalogs, :through => :catalog_items
end
</code>```

Additionally, lets say that CatalogueItems has a position attribute and that there is only one CatalogueItem between any catalog and any item.

The most obvious but slightly frustrating way to retrieve the position attribute is:

```<code>@item         = Item.find(4)
@catalog      = @item.catalogs.first
@cat_item     = @item.catalog_items.first(:conditions => {:catalog_id => @catalog.id})
position      = @cat_item.position
</code>```

This is annoying because it seems that we should be able to do @item.catalogs.first.position since we have completely specified which position we want: the one that corresponds to the first of @item's catalogs.

The only way I've found to get this is:

```<code>class Item < ActiveRecord::Base
      has_many :catalog_items
      has_many :catalogs, :through => :catalog_items, :select => "catalogue_items.position, catalogs.*"
end
</code>```

Now I can do Item.catalogs.first.position. However, this seems like a bit of a hack - I'm adding an extra attribute onto a Catalog instance. It also opens up the possibility of trying to use a view in two different situations where I populate @catalogs with a Catalog.find or with a @item.catalogs. In one case, the position will be there, and in the other, it won't.

Does anyone have a good solution to this?

Thanks.

答:
Why don't You just

```<code>@item = Item.find(4)
position = @item.catalog_items.first.position
</code>```

why do you go through catalogs? It doesn't make any sense to me since you are looking for first ANY catalog!?

OwnerDisplayName: arjun

ContentLicense: CC BY-SA 2.5

Body:
I'm wondering what the easiest/most elegant way of selecting attributes from join models in has_many :through associations is.

Lets say we have Items, Catalogs, and CatalogItems with the following Item class:

class Item < ActiveRecord::Base
      has_many :catalog_items
      has_many :catalogs, :through => :catalog_items
end

Additionally, lets say that CatalogueItems has a position attribute and that there is only one CatalogueItem between any catalog and any item.

The most obvious but slightly frustrating way to retrieve the position attribute is:

@item         = Item.find(4)
@catalog      = @item.catalogs.first
@cat_item     = @item.catalog_items.first(:conditions => {:catalog_id => @catalog.id})
position      = @cat_item.position

This is annoying because it seems that we should be able to do @item.catalogs.first.position since we have completely specified which position we want: the one that corresponds to the first of @item's catalogs.

The only way I've found to get this is:

class Item < ActiveRecord::Base
      has_many :catalog_items
      has_many :catalogs, :through => :catalog_items, :select => "catalogue_items.position, catalogs.*"
end

Now I can do Item.catalogs.first.position. However, this seems like a bit of a hack - I'm adding an extra attribute onto a Catalog instance. It also opens up the possibility of trying to use a view in two different situations where I populate @catalogs with a Catalog.find or with a @item.catalogs. In one case, the position will be there, and in the other, it won't.

Does anyone have a good solution to this?

Thanks.

Body:
Why don't You just

@item = Item.find(4)
position = @item.catalog_items.first.position

why do you go through catalogs? It doesn't make any sense to me since you are looking for first ANY catalog!?

OwnerDisplayName: aivarsak


问:
What is the minimum file size of a PE file (exe) on Windows? And the minimal memory allocation?
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

```<code>; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start
</code>```

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)

答:
ntdll.dll is mapped into every single process and does a lot of basic initialization before your code starts running. This will always cause a small amount of private memory to be allocated. Take a look at LdrpInitializeProcess; here's a small list of things:

It creates the process heap.

It sets up the activation context stack for the current thread.

It initializes several critical sections. This will almost always cause memory to be allocated.

Also, other DLLs that get loaded into your process (e.g. kernel32.dll, user32.dll) will probably allocate memory themselves, in their DllMain functions.

EDIT: Take a look at this simple test program I created:

It's a completely native program (no Win32), and imports just two functions from ntdll.dll: NtDelayExecution and NtTerminateProcess. It's very similar to your program, and even though it doesn't do anything except sleep, it still uses 100 kB of private memory. The file is 2.5 kB in size, just like your program.

Body:
What is the minimum file size of a PE file (exe) on Windows?
And the minimum memory allocation?

I assembled (using MASM (ml.exe) and link.exe that come with VS 10) the following code:
I can not leave out kernel32.lib and ExitProcess, if I do, the program crashes.

; Assmebly options
.386
.MODEL FLAT, STDCALL
option casemap:none

; Include Libs
includelib kernel32.lib

; Imported symbols
ExitProcess PROTO :Dword
Sleep PROTO :Dword

; Code
.CODE

start:
    invoke Sleep, 10000
    invoke ExitProcess, 0
END start

The Sleep command is included only to be able to read the memory usage before the program ends.

Now I measure the following: The .exe file is exactly 2.5 KB in size (if I include user32.lib and MessageBoxA, it becomes 3 KB in size --> blocks?) and the application uses 136 KB RAM when it's run (Vista 32bit).

Isn't that somewhat much memory for such a simple program? Why is the exe file so large, and the RAM requirement much larger than the exe file?

Are there some minimal memory sizes? What about the file? It looks like it's organized in blocks of 0.5 KB in size, but isn't it 0.5 KB then for this shortest possible program?

Where can I read about this (except http://msdn.microsoft.com/en-us/magazine/cc301805.aspx which I will check out)?

Thanks (my first question here)


问:
Item is not recorded to CoreData from Share Extension
I did create Share Extension. Using this extension I am trying to insert new item to CoreData. The code is below. Variables context and document is created. context.save() not failing. Insertion to the CoreData using main/host app works fine and presented to UI.

Another thing what I noticed that all insertions from Share Extension are stored somewhere else, but not in the main app. It looks that these items are not merged to the main CoreData.

Why my items insertion to CoreData throw Share Extension is not merged to main CoreData?

```<code>let context = CoreDataStackManager.sharedManager.persistentContainer.viewContext
let document = SGDocument(context: context)
document.name = "Document Name"
do {
    try context.save()
} catch {
    fatalError("Unresolved error \(error)")
}
</code>```

PS: Here is similar question, but without answer.

答:
I found solution for it.</p>

```<code>// In the extension I am setting that VC needs to be updated/refreshed.
UserDefaults.group.set(true, forKey: .udRefreshDocumentsVC)

// In the view controller adding listener for application will enter foreground.
NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: nil, using: applicationWillEnterForeground)

// In the applicationWillEnterForeground method do reload.
    func applicationWillEnterForeground(notification: Notification) {
        if UserDefaults.group.bool(forKey: .udRefreshDocumentsVC) {
            _fetchedResultsController = nil
            tableView.reloadData()
            UserDefaults.group.set(false, forKey: .udRefreshDocumentsVC)
        }
    }
</code>```

Body:
I did create Share Extension. Using this extension I am trying to insert new item to CoreData. The code is below. Variables context and document is created. context.save() not failing. Insertion to the CoreData using main/host app works fine and presented to UI.

Another thing what I noticed that all insertions from Share Extension are stored somewhere else, but not in the main app. It looks that these items are not merged to the main CoreData.

Why my items insertion to CoreData throw Share Extension is not merged to main CoreData?

let context = CoreDataStackManager.sharedManager.persistentContainer.viewContext
let document = SGDocument(context: context)
document.name = "Document Name"
do {
    try context.save()
} catch {
    fatalError("Unresolved error \(error)")
}

PS: Here is similar question, but without answer.

Body:
I found solution for it.

// In the extension I am setting that VC needs to be updated/refreshed.
UserDefaults.group.set(true, forKey: .udRefreshDocumentsVC)

// In the view controller adding listener for application will enter foreground.
NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: nil, using: applicationWillEnterForeground)

// In the applicationWillEnterForeground method do reload.
    func applicationWillEnterForeground(notification: Notification) {
        if UserDefaults.group.bool(forKey: .udRefreshDocumentsVC) {
            _fetchedResultsController = nil
            tableView.reloadData()
            UserDefaults.group.set(false, forKey: .udRefreshDocumentsVC)
        }
    }


问:
Apply borders to all cells in a range with openpyxl
I have a script that takes a pandas dataframe and chops it up into several hundred chunks and saves each chunk as a separate excel file. Each chunk will have the same number of columns but the number of rows varies. I've figured out how to apply all the other necessary formatting to these files with openpyxl, but I haven't yet determined the fastest way to apply borders. Also, I think I'm just not applying borders correctly, because the code below (which I suspect shouldn't need to loop over each cell individually) doesn't apply any borders.

```<code>from openpyxl.style import Border

wb = load_workbook(filename = _fname)
ws = wb.worksheets[0]
for _row in ws.range('A1:L'+str(ws.get_highest_row() ) ):
    for _cell in _row:
            _cell.style.borders.left.border_style = Border.BORDER_THIN
            _cell.style.borders.right.border_style = Border.BORDER_THIN
            _cell.style.borders.top.border_style = Border.BORDER_THIN
            _cell.style.borders.bottom.border_style = Border.BORDER_THIN
wb.save(_fname)
</code>```

So this code works, but it doesn't apply the border I expect (the default border in excel) and it takes a lot more steps than I'd prefer. My expectation is that I should be able to do something like this:

```<code>from openpyxl.style import Border

wb = load_workbook(filename = _fname)
ws = wb.worksheets[0]

_range = ws.some_range_func('A1:L'+str(ws.get_highest_row() ) ):
    _range.style.borders.all_borders = Borders.BORDER_THIN
</code>```

Does this functionality exist? If not, can someone please be so kind as to at least explain how to apply the default border style and not this slightly thicker border? None of Border.BORDER_THICK, Border.BORDER_MEDIUM, Border.BORDER_THIN, or Border.BORDER_HAIR seem correct.

Thanks!

答:
Decision that works on openpyxl 2.3.5</p>

```<code>from openpyxl.styles import Border, Side

def set_border(ws, cell_range):
    border = Border(left=Side(border_style='thin', color='000000'),
                right=Side(border_style='thin', color='000000'),
                top=Side(border_style='thin', color='000000'),
                bottom=Side(border_style='thin', color='000000'))

    rows = ws.iter_rows(cell_range)
    for row in rows:
        for cell in row:
            cell.border = border

set_border(worksheet, 'A5:C10')
</code>```

Body:
I have a script that takes a pandas dataframe and chops it up into several hundred chunks and saves each chunk as a separate excel file. Each chunk will have the same number of columns but the number of rows varies. I've figured out how to apply all the other necessary formatting to these files with openpyxl, but I haven't yet determined the fastest way to apply borders. Also, I think I'm just not applying borders correctly, because the code below (which I suspect shouldn't need to loop over each cell individually) doesn't apply any borders.

from openpyxl.style import Border

wb = load_workbook(filename = _fname)
ws = wb.worksheets[0]
for _row in ws.range('A1:L'+str(ws.get_highest_row() ) ):
    for _cell in _row:
            _cell.style.borders.left.border_style = Border.BORDER_THIN
            _cell.style.borders.right.border_style = Border.BORDER_THIN
            _cell.style.borders.top.border_style = Border.BORDER_THIN
            _cell.style.borders.bottom.border_style = Border.BORDER_THIN
wb.save(_fname)

So this code works, but it doesn't apply the border I expect (the default border in excel) and it takes a lot more steps than I'd prefer. My expectation is that I should be able to do something like this:

from openpyxl.style import Border

wb = load_workbook(filename = _fname)
ws = wb.worksheets[0]

_range = ws.some_range_func('A1:L'+str(ws.get_highest_row() ) ):
    _range.style.borders.all_borders = Borders.BORDER_THIN

Does this functionality exist? If not, can someone please be so kind as to at least explain how to apply the default border style and not this slightly thicker border? None of Border.BORDER_THICK, Border.BORDER_MEDIUM, Border.BORDER_THIN, or Border.BORDER_HAIR seem correct.

Thanks!

Body:
Decision that works on openpyxl 2.3.5

from openpyxl.styles import Border, Side

def set_border(ws, cell_range):
    border = Border(left=Side(border_style='thin', color='000000'),
                right=Side(border_style='thin', color='000000'),
                top=Side(border_style='thin', color='000000'),
                bottom=Side(border_style='thin', color='000000'))

    rows = ws.iter_rows(cell_range)
    for row in rows:
        for cell in row:
            cell.border = border

set_border(worksheet, 'A5:C10')

ContentLicense: CC BY-SA 4.0


问:
Sql Server 2005 Copy Multiple Result Sets
How Can i copy multiple result sets at the same time?

for example if i were to execute the below code:

```<code>select 'a'
select 'b'
select 'c'
</code>```

how can i copy all 3 results so i can then paste them into excel? I tried holding down shift and selecting all 3 result sets but it only copies the last one i select.

答:
You can select

Query'>'Results to'> 'Results to text' or

Query'>'Results to'> 'Results to file'

Body:
How Can i copy multiple result sets at the same time?

for example if i were to execute the below code:

select 'a'
select 'b'
select 'c'

how can i copy all 3 results so i can then paste them into excel? I tried holding down shift and selecting all 3 result sets but it only copies the last one i select.


问:
Create groupings using GroupBY
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

```<code>class A {
   string X {get; set;}
}

var list = listOfAs;
List<A> listOfAWithXEqualAA;
List<A> listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.
</code>```

Please suggest me such a query.

答:
```<code>List<A> FirstList = listofAs.Where(a => a.x == "matchvalue").ToList();
List<A> SecondList = listofAs.Where(a => a.x != "matchvalue").ToList();
</code>```

Title: Create groupings using GroupBY

Body:
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

class A {
   string X {get; set;}
}

var list = listOfAs;
List listOfAWithXEqualAA;
List listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.

Please suggest me such a query.


问:
angular 2 IE9 getting 404's when loading script files
When I load https://me.com:80/p/manage;Id=1234

in ie10: https://me.com:80/styles.bundle.js
ie ie9: https://me.com:80/p/styles.bundle.js

in my index.html I have <base href="/" />

the scripts are added to index.html on build autogeneration:

```<code><script src="styles.bundle.js" type="text/javascript"></script>
</code>```

This is happening with all auto added scripts that angular2 relies on.

Why is the url in ie9 generated like this, is this fixable?

答:
add to your index.html:

```<code><script src="https://raw.githubusercontent.com/angular/angular/66df335998d097fa8fe46dec41f1183737332021/shims_for_IE.js" type="text/plain"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-sham.js" type="text/plain"></script>
</code>```

in head section :

```<code><meta http-equiv="X-UA-Compatible" content="IE=9;IE=edge;IE=10" />
</code>```

Body:
When I load https://me.com:80/p/manage;Id=1234

in ie10: https://me.com:80/styles.bundle.js
ie ie9: https://me.com:80/p/styles.bundle.js

in my index.html I have <base href="/" />

the scripts are added to index.html on build autogeneration:

This is happening with all auto added scripts that angular2 relies on.

Why is the url in ie9 generated like this, is this fixable?

Body:
add to your index.html:

<script src="https://raw.githubusercontent.com/angular/angular/66df335998d097fa8fe46dec41f1183737332021/shims_for_IE.js" type="text/plain"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.5.9/es5-sham.js" type="text/plain"></script>

in head section :

<meta http-equiv="X-UA-Compatible" content="IE=9;IE=edge;IE=10" />


问:
Converting XML to C# object
I need to get the OrderID from these xml data:

```<code><?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>
</code>```

I have tried this one but does not work.

```<code>var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}
</code>```

Please advice.

答:
You can follow this:</p>

```<code>XDocument xdoc = XDocument.Load("YourXMLFile");
var orderId = xdoc.Descendants("OrderID").FirstOrDefault().Value;
</code>```

Title: Converting XML to C# object

Body:
I need to get the OrderID from these xml data:

<?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>

I have tried this one but does not work.

var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}

Please advice.

Body:
You can follow this:

XDocument xdoc = XDocument.Load("YourXMLFile");
var orderId = xdoc.Descendants("OrderID").FirstOrDefault().Value;


答:
You should be use this sample code

Importent Note

Serialized class mark as [Serializable] attirbute

If the class name   is not same as the xml root tag, class will be
mark as    [XmlRoot(ElementName = "XmlTagName")] attribute

If serialized class    have property type as another class, this
property mark as    [XmlElement("XmlTagName")] attribute

Sample Code

Model

```<code>      [Serializable]
        [XmlRoot(ElementName = "HardwareInfo")]
        public class Hardware
        {
            [XmlElement]
            public string cpu_name { get; set; }
            [XmlElement]
            public int ram_size { get; set; }

            [XmlElement("hard_disk")]
            public List<HardDisk> hd { get; set; }
        }

        [Serializable]
        [XmlRoot(ElementName = "hard_disk")]
        public class HardDisk
        {
            [XmlElement]
            public string model { get; set; }
            [XmlElement]
            public string size { get; set; }
        }

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlString = @"<HardwareInfo>
                                  <cpu_name> ABC Pentium xyz</cpu_name>
                                  <ram_size> 123 </ram_size>
                                  <hard_disk>
                                    <model>Toshiba XYZ</model>
                                    <size> 123 GB </size>
                                  </hard_disk>
                                  <hard_disk>
                                    <model>Logitech XYZ</model>
                                    <size> 99 GB </size>
                                  </hard_disk>
                                </HardwareInfo>";

            var result = DeSerialization<Hardware>(xmlString);
        }

        static T DeSerialization<T>(string xmlStrig) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (StringReader sReader = new StringReader(xmlStrig))
            {
                return (T)xmlSerializer.Deserialize(sReader);
            }
        }
    }
}
</code>```

Title: Converting XML to C# object

Body:
You should be use this sample code

Importent Note

Serialized class mark as [Serializable] attirbute

If the class name   is not same as the xml root tag, class will be
mark as    [XmlRoot(ElementName = "XmlTagName")] attribute

If serialized class    have property type as another class, this
property mark as    [XmlElement("XmlTagName")] attribute

Sample Code

Model

      [Serializable]
        [XmlRoot(ElementName = "HardwareInfo")]
        public class Hardware
        {
            [XmlElement]
            public string cpu_name { get; set; }
            [XmlElement]
            public int ram_size { get; set; }

            [XmlElement("hard_disk")]
            public List<HardDisk> hd { get; set; }
        }

        [Serializable]
        [XmlRoot(ElementName = "hard_disk")]
        public class HardDisk
        {
            [XmlElement]
            public string model { get; set; }
            [XmlElement]
            public string size { get; set; }
        }

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlString = @"<HardwareInfo>
                                  <cpu_name> ABC Pentium xyz</cpu_name>
                                  <ram_size> 123 </ram_size>
                                  <hard_disk>
                                    <model>Toshiba XYZ</model>
                                    <size> 123 GB </size>
                                  </hard_disk>
                                  <hard_disk>
                                    <model>Logitech XYZ</model>
                                    <size> 99 GB </size>
                                  </hard_disk>
                                </HardwareInfo>";

            var result = DeSerialization<Hardware>(xmlString);
        }

        static T DeSerialization<T>(string xmlStrig) where T : class
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (StringReader sReader = new StringReader(xmlStrig))
            {
                return (T)xmlSerializer.Deserialize(sReader);
            }
        }
    }
}


问:
Make postgres database production on rails 5 for deploy app to heroku
My app is not working on heroku but its working properly on my local

My app is deployed successfully on heroku without any error, but when I visit url of my app its showing We're sorry, but something went wrong., and when I check heroku log using heroku logs -t its showing error, I dont know whats going wrong, Any suggestion will be appreciated

I am using MySql as a database

UPD: Solve, just need update gem file, because heroku using Postgres databse.

```<code>gem 'pg', group: :production
gem 'mysql', group: :development
</code>```

答:
Rails default database is SQL Lite, unless you have changed database.yml this is the database you are using.

Regardless of any configuration changes you make Heroku only runs on Postgres database. You cannot run any other database on Heroku.

If you want to use Mysql in development and PG in production development then you can define group in gemfile like

```<code>Gemfile
gem 'pg', group: :production
gem 'mysql', group: :development
</code>```

Body:
My app is not working on heroku but its working properly on my local

My app is deployed successfully on heroku without any error, but when I visit url of my app its showing We're sorry, but something went wrong., and when I check heroku log using heroku logs -t its showing error, I dont know whats going wrong, Any suggestion will be appreciated

I am using MySql as a database

UPD: Solve, just need update gem file, because heroku using Postgres databse.

gem 'pg', group: :production
gem 'mysql', group: :development

Body:
Rails default database is SQL Lite, unless you have changed database.yml this is the database you are using.

Regardless of any configuration changes you make Heroku only runs on Postgres database. You cannot run any other database on Heroku.

If you want to use Mysql in development and PG in production development then you can define group in gemfile like

Gemfile
gem 'pg', group: :production
gem 'mysql', group: :development


问:
cakephp use record values in afterDelete
I am using the soft delete plugin for my EmployeesTable.php in CakePHP 3.0.

When I soft delete an employee I wish to update their associated user table with $user->set('active', false); within the afterDelete()

My problem is getting the user_id used in the employees table into the afterDelete()

I have even tried to just the id of the employee deleted and do a find on that but the examples I have seen using the $this->id return and error Table "App\Model\Table\EmployeesTable" is not associated with "id" from the beforeDelete.

EmployeesTable.php

```<code>public function afterDelete( ) {
    $user = $this->Users->get($this->user_id);
    $user->set('active', false);
    $this->Users->save($user);
}
</code>```

I have also tried catching $this->id in beforeDelete() and passing it to the afterDelete() but again get the error Table "App\Model\Table\EmployeesTable" is not associated with "id"

答:
I'm not sure but I think you can use the Event object with entities like: </p>

```<code>  public function afterDelete(Event $event) {
     $entity = $event->data["entity"];
     Log::debug("all data: " . $entity);
  }
</code>```

<p>This will log a array inside the debug.log file, with all the data of the deleted user. </p>

Body:
I am using the soft delete plugin for my EmployeesTable.php in CakePHP 3.0.

When I soft delete an employee I wish to update their associated user table with $user->set('active', false); within the afterDelete()

My problem is getting the user_id used in the employees table into the afterDelete()

I have even tried to just the id of the employee deleted and do a find on that but the examples I have seen using the $this->id return and error Table "App\Model\Table\EmployeesTable" is not associated with "id" from the beforeDelete.

EmployeesTable.php

public function afterDelete( ) {
    $user = $this->Users->get($this->user_id);
    $user->set('active', false);
    $this->Users->save($user);
}

I have also tried catching $this->id in beforeDelete() and passing it to the afterDelete() but again get the error Table "App\Model\Table\EmployeesTable" is not associated with "id"

Body:
I'm not sure but I think you can use the Event object with entities like:

  public function afterDelete(Event $event) {
     $entity = $event->data["entity"];
     Log::debug("all data: " . $entity);
  }

This will log a array inside the debug.log file, with all the data of the deleted user.


问:
TableViewCell is not clickable with one finger tap, but it is with two fingers
I created a table view and the tableViewCell is not clickable with one finger, but when I try to click the tableViewCell with two fingers the click event takes place. I don't know why this occurres. I created a custom cell in tableView.

InviteVC

```<code>import UIKit

class InvitePeopleVC: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    var nameArray = ["Alwin Lazar", "Ajith Ramesh CR", "Ebrahim KK", "Vishnu Prakash"]
    var emailArray = ["alwin@xeoscript.com", "ajith@xeoscript.com", "ebrahim@xeoscript.com", "vishnu@xeoscript.com"]

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var doneImg: UIImageView!
    @IBOutlet weak var nameTextFld: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        delegates()
        uiModifications()
        gestureRecognizers()
    }

    func delegates() {
        tableView.dataSource = self
        tableView.delegate = self
        nameTextFld.delegate = self
    }

    func uiModifications() {
        nameTextFld.attributedPlaceholder = NSAttributedString(string: "Name or email address", attributes: [NSForegroundColorAttributeName: UIColor.white])
    }

    func gestureRecognizers() {
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
        self.doneImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.doneImgPressed)))
    }

    func dismissKeyboard() {
        nameTextFld.resignFirstResponder()
    }

    func doneImgPressed() {
        print("done Image tapped")

    }

    func inviteBtnPressed() {
        print("invite button pressed")
    }

    // UITextFieldDelegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == self.nameTextFld {

            self.nameTextFld.resignFirstResponder()

        }
        return true

    }

    // TableView DataSource methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "InviteCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! InviteCell

        cell.nameLbl.text = nameArray[indexPath.row]
        cell.emailLbl.text = emailArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    // TableView Delegate methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected row is \(indexPath.row)")
    }

    @IBAction func backBtnPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}
</code>```

#InviteCell

```<code>import UIKit

class InviteCell: UITableViewCell {

    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var emailLbl: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

}
</code>```

UIViewController Images

TableView Attributes Inspector

InviteCell Atribute Inspector

In the code above, I'm trying to select a cell with one finger, but the selection does not happen.

Thanks in advance...

答:
You have the following line in your set up code:

```<code>self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
</code>```

That sets up a gesture recognizer for your whole view and that would swallow any touches on the main view. If you remove that, you should get the table cell selection working correctly :)

Body:
I created a table view and the tableViewCell is not clickable with one finger, but when I try to click the tableViewCell with two fingers the click event takes place. I don't know why this occurres. I created a custom cell in tableView.

InviteVC

import UIKit

class InvitePeopleVC: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    var nameArray = ["Alwin Lazar", "Ajith Ramesh CR", "Ebrahim KK", "Vishnu Prakash"]
    var emailArray = ["alwin@xeoscript.com", "ajith@xeoscript.com", "ebrahim@xeoscript.com", "vishnu@xeoscript.com"]

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var doneImg: UIImageView!
    @IBOutlet weak var nameTextFld: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        delegates()
        uiModifications()
        gestureRecognizers()
    }

    func delegates() {
        tableView.dataSource = self
        tableView.delegate = self
        nameTextFld.delegate = self
    }

    func uiModifications() {
        nameTextFld.attributedPlaceholder = NSAttributedString(string: "Name or email address", attributes: [NSForegroundColorAttributeName: UIColor.white])
    }

    func gestureRecognizers() {
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
        self.doneImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.doneImgPressed)))
    }

    func dismissKeyboard() {
        nameTextFld.resignFirstResponder()
    }

    func doneImgPressed() {
        print("done Image tapped")

    }

    func inviteBtnPressed() {
        print("invite button pressed")
    }

    // UITextFieldDelegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == self.nameTextFld {

            self.nameTextFld.resignFirstResponder()

        }
        return true

    }

    // TableView DataSource methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "InviteCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! InviteCell

        cell.nameLbl.text = nameArray[indexPath.row]
        cell.emailLbl.text = emailArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    // TableView Delegate methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected row is \(indexPath.row)")
    }

    @IBAction func backBtnPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

#InviteCell

import UIKit

class InviteCell: UITableViewCell {

    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var emailLbl: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

}

UIViewController Images

TableView Attributes Inspector

InviteCell Atribute Inspector

In the code above, I'm trying to select a cell with one finger, but the selection does not happen.

Thanks in advance...

Body:
You have the following line in your set up code:

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))

That sets up a gesture recognizer for your whole view and that would swallow any touches on the main view. If you remove that, you should get the table cell selection working correctly :)


答:
This should populate your lists with the required values

```<code>List<A> listOfAs = new List<A>() ;
string AA = "foo";
List<A> listOfAWithXEqualAA = listOfAs.Where(x => x.X == AA).ToList();
List<A> listOfAWithXNotEqualAA = listOfAs.Where(x => x.X != AA).ToList();
</code>```

class:

```<code>class A
{
    public  string X { get; set; }
}
</code>```

Title: Create groupings using GroupBY

Body:
This should populate your lists with the required values

List<A> listOfAs = new List<A>() ;
string AA = "foo";
List<A> listOfAWithXEqualAA = listOfAs.Where(x => x.X == AA).ToList();
List<A> listOfAWithXNotEqualAA = listOfAs.Where(x => x.X != AA).ToList();

class:

class A
{
    public  string X { get; set; }
}


问:
Python: method invoke by read a file
I have a excel having data like below:

Data.xlsx

```<code>Method_Name | Argument_01 | Argument _02
Func1       | val1        | val2
Func2       | val3        | val4
</code>```

Now my question is:

How to read the function name and arguments from Data.xlsx file and invoke the method Func1 and pass the arguments (val1,val2) using python?

If provide me a code on that using python it would be very very helpful for me.

Thanks.

答:
To read a file is trivial. Just google it. Next, you can use eval(). Something like this.

```<code>def method1(val1):
    print(val1 + 1)

s1 = 'method1'
s2 = '99'
eval(s1 + '(' + s2 + ')')
# 100
</code>```

Title: Python: method invoke by read a file

Body:
I have a excel having data like below:

Data.xlsx

Method_Name | Argument_01 | Argument _02
Func1       | val1        | val2
Func2       | val3        | val4

Now my question is:

How to read the function name and arguments from Data.xlsx file and invoke the method Func1 and pass the arguments (val1,val2) using python?

If provide me a code on that using python it would be very very helpful for me.

Thanks.

Body:
To read a file is trivial. Just google it. Next, you can use eval(). Something like this.

def method1(val1):
    print(val1 + 1)

s1 = 'method1'
s2 = '99'
eval(s1 + '(' + s2 + ')')
# 100


问:
Dispatching action on Route change
I have a smart User component that renders user information from Redux state.

Here is a route I defined:

```<code><Route path="/users/:id" component={User}/>
</code>```

Whenever I click on a specific user, route changes and it forces component to update. However when route changes I wish to dispatch a Redux action to fetch user details by :id from an external API.

What is the correct approach of fetching new set of data for User component after changing Route path?

I have tried to dispatch Redux action on componentWillReceiveProps() but this causes infinite loop since the action causes component to update again... repeat.

答:
You can do that in componentWillReceiveProps but there you can provide a condition on present and nextProps like

```<code>componentWillReceiveProps(nextProps) {

    if(this.props.params.id !== nextProps.params.id) {
        //...action here
    }
}
</code>```

Title: Dispatching action on Route change

Body:
I have a smart User component that renders user information from Redux state.

Here is a route I defined:

<Route path="/users/:id" component={User}/>

Whenever I click on a specific user, route changes and it forces component to update. However when route changes I wish to dispatch a Redux action to fetch user details by :id from an external API.

What is the correct approach of fetching new set of data for User component after changing Route path?

I have tried to dispatch Redux action on componentWillReceiveProps() but this causes infinite loop since the action causes component to update again... repeat.

Body:
You can do that in componentWillReceiveProps but there you can provide a condition on present and nextProps like

componentWillReceiveProps(nextProps) {

    if(this.props.params.id !== nextProps.params.id) {
        //...action here
    }
}


问:
How the manager can get the data (or any update done in the container ) from the worker nodes in a docker swarm
I am creating a docker swarm with one manager , and 3 worker nodes and the service that is running is bash terminal .How the manager can get the output of commands which are run on bash(terminal) containers on worker nodes
Ex: If i run run ls on terminal of worker node, how the manager can get the output of ls </p>

答:
To get the logs of one service use docker-cloud service logs https://docs.docker.com/docker-cloud/getting-started/deploy-app/8_view_logs/

What are you trying to accomplish?
If you want to be able to control the output of the workers from a centralized point there is tools like portainer, universal comtrol plane which have nice uis and let you access logs of containers on the workers.

If you actually need data to be pressnt in the manager use a shared storage (like a mounted nfs drive) or scp the data you want.

Just remember a worker node can have multiple containers with each having their own stdout.


问:
PHP: Standards of class constructors preventing instantiation
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

```<code>    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }
</code>```

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?

答:
Singletons are generally considered "bad"; see this section here for a flame war on the topic.

That said, using factory methods or factory classes to create objects is generally considered good, so you're fine there :)

I personally use the symfony dependency injection component (can be installed in any project without using the symfony framework) to simplify dependency injection and avoid singletons where it seems appropriate.

I do still use some singletons, where it makes sense to me; loggers and factory objects, for example, seem to naturally be single to me, so I make them that way.  The idea is that global functionality (e.g. a factory) is fine, but global state is bad, I believe.

With regards to your amended question on whether to throw an Exception or whether to return false from your create() call; it depends on whether your application can continue successfully without the created object if not.  If, for example, you were creating a database connection that is necessary to create a page, then throw an Exception.  If you're doing something less essential, return false and continue on your merry way :)

Body:
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?


问:
Insert comma delimited string to table in SQL
I found a similar questions are regarding this but I couldn't get it to for for my issue..

Lets say I have the string compiled of many many lines:

```<code>1,Users,2015-01-20\n
1,System,2015-01-18\n
....
....
</code>```

I need to put it into existing table:

```<code>╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣

enter code here
</code>```

So it would look like:

```<code>╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣
║ 1        ║     Users ║2015-01-20║
║ 1        ║    System ║2015-01-18║
</code>```

How do I do that? I must say I know little to nothing about SQL so forgive me for any stupid Q that will follow, thank you :)

答:
Please try this:</p>

```<code>insert into table_name values ( '1' ,'Users' , '2015-01-20')
</code>```

Body:
I found a similar questions are regarding this but I couldn't get it to for for my issue..

Lets say I have the string compiled of many many lines:

1,Users,2015-01-20\n
1,System,2015-01-18\n
....
....

I need to put it into existing table:

╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣

enter code here

So it would look like:

╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣
║ 1        ║     Users ║2015-01-20║
║ 1        ║    System ║2015-01-18║

How do I do that? I must say I know little to nothing about SQL so forgive me for any stupid Q that will follow, thank you :)

Body:
Please try this:

insert into table_name values ( '1' ,'Users' , '2015-01-20')


问:
Add each character from each line of a text file, to a list in Python
So I want to read each character (separated by spaces) of each line of a text file and add them to a seperate index of a list for each line.

```<code>file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)
</code>```

The text file has a single character separated by a space for each line.
The editor wouldn't allow for my punctuation from the text file, but below is an example of what it looks like.

r o t o r

r a c e c

答:
This is what I did to solve my issue:</p>

```<code>lines = open('theTextFile.txt','r')

secondList = []
for line in lines:
    line = line.split()
    secondList.append(line)
</code>```

Body:
So I want to read each character (separated by spaces) of each line of a text file and add them to a seperate index of a list for each line.

file = open("theTextFile.txt", 'r+')
pal = []

words = file.split(' ')
pal.append(words)

print(pal)
split_line(file)

The text file has a single character separated by a space for each line.
The editor wouldn't allow for my punctuation from the text file, but below is an example of what it looks like.

r o t o r

r a c e c

Body:
This is what I did to solve my issue:

lines = open('theTextFile.txt','r')

secondList = []
for line in lines:
    line = line.split()
    secondList.append(line)


问:
How can I get the images from the subdirectory just created and assigned to the dropdown list in asp.net c#
```<code>DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/Images/") + txtFolder.Text
</code>```

After I create new folder with some images, How can I retreive them and assign to a ddlist
Thanks

答:
Try below code to get list of files in directory that you have created and also bind dropdown list.</p>

```<code>string DirecotryPath = Server.MapPath(string.Format("~/Images/") + txtFolder.Text);
            if (Directory.Exists(DirecotryPath))
            {
                string[] files = System.IO.Directory.GetFiles(DirecotryPath);
                int counter = 1;
                foreach (string file in files)
                {
                    string filename = file.Substring(file.LastIndexOf("\\"), file.Length);
                    ListItem li = new ListItem(counter.ToString(), counter.ToString());
                    li.Attributes.Add("data-image", "~/images/" + filename);
                    ddlList.Items.Add(li);
                }
            }
</code>```

Body:
DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/Images/") + txtFolder.Text

After I create new folder with some images, How can I retreive them and assign to a ddlist
Thanks

Body:
Try below code to get list of files in directory that you have created and also bind dropdown list.

string DirecotryPath = Server.MapPath(string.Format("~/Images/") + txtFolder.Text);
            if (Directory.Exists(DirecotryPath))
            {
                string[] files = System.IO.Directory.GetFiles(DirecotryPath);
                int counter = 1;
                foreach (string file in files)
                {
                    string filename = file.Substring(file.LastIndexOf("\\"), file.Length);
                    ListItem li = new ListItem(counter.ToString(), counter.ToString());
                    li.Attributes.Add("data-image", "~/images/" + filename);
                    ddlList.Items.Add(li);
                }
            }


问:
call function in postgresql
I made a simple function as part of my homework but for the life of me I can't figure out how to call it and test it. Can anyone tell me how?</p>

```<code>    -- Procedure
CREATE OR REPLACE FUNCTION addDoctor (
    a INT,
    b VARCHAR (20),
    c VARCHAR (20)
) RETURNS VOID
LANGUAGE plpsql
AS $BODY$
BEGIN
    INSERT INTO doctor
    VALUES (a,b,c);
END;
$BODY$
</code>```

答:
Use SELECT:</p>

```<code>SELECT function_name();
</code>```

Title: call function in postgresql

Body:
I made a simple function as part of my homework but for the life of me I can't figure out how to call it and test it. Can anyone tell me how?

    -- Procedure
CREATE OR REPLACE FUNCTION addDoctor (
    a INT,
    b VARCHAR (20),
    c VARCHAR (20)
) RETURNS VOID
LANGUAGE plpsql
AS $BODY$
BEGIN
    INSERT INTO doctor
    VALUES (a,b,c);
END;
$BODY$

Body:
Use SELECT:

SELECT function_name();


问:
Iterating Array of Objects in javascript
I am having an array that consists the objects with a key, value how can we iterate each object for caste and id.

```<code>[
    Object {
        caste = "Banda",
        id = 4
    },
    Object {
        caste = "Bestha",
        id = 6
    }
]
</code>```

答:
The forEach loop accepts an iterator function and, optionally, a value to use as "this" when calling that iterator function.

```<code> var donuts = [
    { type: "Jelly", cost: 1.22 },
    { type: "Chocolate", cost: 2.45 },
    { type: "Cider", cost: 1.59 },
    { type: "Boston Cream", cost: 5.99 }
];

donuts.forEach(function(theDonut, index) {
    console.log(theDonut.type + " donuts cost $"+ theDonut.cost+ " each");
});
</code>```

Subsequently it can also be broken down to this

```<code>var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];

function ShowResults(donuts) {
    console.log(donuts.type + " donuts cost $"+ donuts.cost+ " each");
}

donuts.forEach(ShowResults);
</code>```

Body:
I am having an array that consists the objects with a key, value how can we iterate each object for caste and id.

[
    Object {
        caste = "Banda",
        id = 4
    },
    Object {
        caste = "Bestha",
        id = 6
    }
]

Body:
The forEach loop accepts an iterator function and, optionally, a value to use as "this" when calling that iterator function.

 var donuts = [
    { type: "Jelly", cost: 1.22 },
    { type: "Chocolate", cost: 2.45 },
    { type: "Cider", cost: 1.59 },
    { type: "Boston Cream", cost: 5.99 }
];

donuts.forEach(function(theDonut, index) {
    console.log(theDonut.type + " donuts cost $"+ theDonut.cost+ " each");
});

Subsequently it can also be broken down to this

var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];

function ShowResults(donuts) {
    console.log(donuts.type + " donuts cost $"+ donuts.cost+ " each");
}

donuts.forEach(ShowResults);


答:
Heroku used postgres database only.

Change Gemfile from

```<code>gem 'mysql'
</code>```

to

```<code>gem 'pg'
</code>```

Title: Make postgres database production on rails 5 for deploy app to heroku

Body:
My app is not working on heroku but its working properly on my local

My app is deployed successfully on heroku without any error, but when I visit url of my app its showing We're sorry, but something went wrong., and when I check heroku log using heroku logs -t its showing error, I dont know whats going wrong, Any suggestion will be appreciated

I am using MySql as a database

UPD: Solve, just need update gem file, because heroku using Postgres databse.

gem 'pg', group: :production
gem 'mysql', group: :development

Body:
Heroku used postgres database only.

Change Gemfile from

gem 'mysql'

to

gem 'pg'


问:
Customer emails not sending any more in Magento 1.9.3.2 via cronjob
Magento customer e-mails are not sending any more after update. It shows following message in the cron_schedule table. Our hoster is mittwald and they use a special cron.sh which not uses "ps".</p>

```<code>exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (message_id='33')' at line 1' in /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /html/update_1.9.3/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /html/update_1.9.3/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#4 /html/update_1.9.3/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `v1_core...', Array)
#5 /html/update_1.9.3/lib/Varien/Db/Adapter/Pdo/Mysql.php(504): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `v1_core...', Array)
#6 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(635): Varien_Db_Adapter_Pdo_Mysql->query('UPDATE `v1_core...', Array)
#7 /html/update_1.9.3/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(433): Zend_Db_Adapter_Abstract->update('v1_core_email_q...', Array, 'message_id='33'')
#8 /html/update_1.9.3/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Core_Model_Resource_Db_Abstract->save(Object(Mage_Core_Model_Email_Queue))
#9 /html/update_1.9.3/app/code/core/Mage/Core/Model/Email/Queue.php(246): Mage_Core_Model_Abstract->save()
#10 [internal function]: Mage_Core_Model_Email_Queue->send(Object(Mage_Cron_Model_Schedule))
#11 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(326): call_user_func_array(Array, Array)
#12 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
#13 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1358): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
#14 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
#15 /html/update_1.9.3/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
#16 /html/update_1.9.3/cron.php(78): Mage::dispatchEvent('default')
#17 {main}

Next exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (message_id='33')' at line 1, query was: UPDATE `v1_core_email_queue` SET  WHERE (message_id='33')' in /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php:235
Stack trace:
#0 /html/update_1.9.3/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /html/update_1.9.3/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /html/update_1.9.3/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `v1_core...', Array)
#4 /html/update_1.9.3/lib/Varien/Db/Adapter/Pdo/Mysql.php(504): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `v1_core...', Array)
#5 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(635): Varien_Db_Adapter_Pdo_Mysql->query('UPDATE `v1_core...', Array)
#6 /html/update_1.9.3/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(433): Zend_Db_Adapter_Abstract->update('v1_core_email_q...', Array, 'message_id='33'')
#7 /html/update_1.9.3/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Core_Model_Resource_Db_Abstract->save(Object(Mage_Core_Model_Email_Queue))
#8 /html/update_1.9.3/app/code/core/Mage/Core/Model/Email/Queue.php(246): Mage_Core_Model_Abstract->save()
#9 [internal function]: Mage_Core_Model_Email_Queue->send(Object(Mage_Cron_Model_Schedule))
#10 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(326): call_user_func_array(Array, Array)
#11 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
#12 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1358): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
#13 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
#14 /html/update_1.9.3/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
#15 /html/update_1.9.3/cron.php(78): Mage::dispatchEvent('default')
#16 {main}
</code>```

答:
There was an error in v1_core_email_queue WHERE (message_id='33').

The order with the id 33 was already deleted. The solution was just to delete the entry with the id 33.

Body:
Magento customer e-mails are not sending any more after update. It shows following message in the cron_schedule table. Our hoster is mittwald and they use a special cron.sh which not uses "ps".

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (message_id='33')' at line 1' in /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php:228
Stack trace:
#0 /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /html/update_1.9.3/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /html/update_1.9.3/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#4 /html/update_1.9.3/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `v1_core...', Array)
#5 /html/update_1.9.3/lib/Varien/Db/Adapter/Pdo/Mysql.php(504): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `v1_core...', Array)
#6 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(635): Varien_Db_Adapter_Pdo_Mysql->query('UPDATE `v1_core...', Array)
#7 /html/update_1.9.3/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(433): Zend_Db_Adapter_Abstract->update('v1_core_email_q...', Array, 'message_id='33'')
#8 /html/update_1.9.3/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Core_Model_Resource_Db_Abstract->save(Object(Mage_Core_Model_Email_Queue))
#9 /html/update_1.9.3/app/code/core/Mage/Core/Model/Email/Queue.php(246): Mage_Core_Model_Abstract->save()
#10 [internal function]: Mage_Core_Model_Email_Queue->send(Object(Mage_Cron_Model_Schedule))
#11 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(326): call_user_func_array(Array, Array)
#12 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
#13 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1358): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
#14 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
#15 /html/update_1.9.3/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
#16 /html/update_1.9.3/cron.php(78): Mage::dispatchEvent('default')
#17 {main}

Next exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (message_id='33')' at line 1, query was: UPDATE `v1_core_email_queue` SET  WHERE (message_id='33')' in /html/update_1.9.3/lib/Zend/Db/Statement/Pdo.php:235
Stack trace:
#0 /html/update_1.9.3/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /html/update_1.9.3/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /html/update_1.9.3/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `v1_core...', Array)
#4 /html/update_1.9.3/lib/Varien/Db/Adapter/Pdo/Mysql.php(504): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `v1_core...', Array)
#5 /html/update_1.9.3/lib/Zend/Db/Adapter/Abstract.php(635): Varien_Db_Adapter_Pdo_Mysql->query('UPDATE `v1_core...', Array)
#6 /html/update_1.9.3/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(433): Zend_Db_Adapter_Abstract->update('v1_core_email_q...', Array, 'message_id='33'')
#7 /html/update_1.9.3/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Core_Model_Resource_Db_Abstract->save(Object(Mage_Core_Model_Email_Queue))
#8 /html/update_1.9.3/app/code/core/Mage/Core/Model/Email/Queue.php(246): Mage_Core_Model_Abstract->save()
#9 [internal function]: Mage_Core_Model_Email_Queue->send(Object(Mage_Cron_Model_Schedule))
#10 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(326): call_user_func_array(Array, Array)
#11 /html/update_1.9.3/app/code/core/Mage/Cron/Model/Observer.php(72): Mage_Cron_Model_Observer->_processJob(Object(Mage_Cron_Model_Schedule), Object(Mage_Core_Model_Config_Element))
#12 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1358): Mage_Cron_Model_Observer->dispatch(Object(Varien_Event_Observer))
#13 /html/update_1.9.3/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Cron_Model_Observer), 'dispatch', Object(Varien_Event_Observer))
#14 /html/update_1.9.3/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('default', Array)
#15 /html/update_1.9.3/cron.php(78): Mage::dispatchEvent('default')
#16 {main}


问:
Filename ending with period and using FileInfo C#
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

```<code>echo "test" > "\\?\C:\Test\BadFileName."
</code>```

and this is the code I was using to test the file:

```<code>DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}
</code>```

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

答:
Since this is obviously an unsupported scenario, I doubt it can be done without using some low-level file access.

What you could try to do is drop FileInfo and go with
File.Exists(path) and File.ReadAllBytes(path).
These might be able to circumvent the issue.

File Access using SafeFileHandle

The following is untested

Creating an instance of UnmanagedFileLoader (Code below, taken from MSDN), allows you to create a SafeFileHandle object which can be passed to the FileStream constructor in the following way:

```<code>UnmanagedFileLoader ufl = new UnmanagedFileLoader(path);
FileStream fs = new FileStream(ufl.Handle, FileMode.Open);
</code>```

Note: Remember to call ufl.Handle.Dispose().

This should give you a more, shall we say, direct access to the file, and so go around the enforcement of a valid filename that Windows has in place.

UnmanagedFileLoader Code

```<code>class UnmanagedFileLoader
{
    public const short FILE_ATTRIBUTE_NORMAL = 0x80;
    public const short INVALID_HANDLE_VALUE = -1;
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const uint CREATE_NEW = 1;
    public const uint CREATE_ALWAYS = 2;
    public const uint OPEN_EXISTING = 3;

    // Use interop to call the CreateFile function.
    // For more information about CreateFile,
    // see the unmanaged MSDN reference library.
    [DllImport("kernel32.dll", SetLastError = true, CharSet=CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
      uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
      uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    private SafeFileHandle handleValue = null;

    public UnmanagedFileLoader(string Path)
    {
        Load(Path);
    }

    public void Load(string Path)
    {
        if (Path == null || Path.Length == 0)
        {
            throw new ArgumentNullException("Path");
        }

        // Try to open the file.
        handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

        // If the handle is invalid,
        // get the last Win32 error
        // and throw a Win32Exception.
        if (handleValue.IsInvalid)
        {
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }
    }

    public SafeFileHandle Handle
    {
        get
        {
            // If the handle is valid,
            // return it.
            if (!handleValue.IsInvalid)
            {
                return handleValue;
            }
            else
            {
                return null;
            }
        }

    }
}
</code>```

File Date Access using Windows API

The GetFileTimeSample class below, taken from www.pinvoke.net uses another Windows API call, specifically GetFileTime.
This implementation is just an example, you sure will be able to adapt it to get only the date you need. In its current form it will output all three dates.

Usage:

```<code>DateTime fileDateCreated;
DateTime fileDateAccessed;
DateTime fileDateModified;
GetFileTimeSample.GetFileTimes(path, out fileDateCreated, out fileDateAccessed, out fileDateModified);
</code>```

Since C# 7.0 it is possible to declare out variables directly in the function call like so:

```<code>GetFileTimeSample.GetFileTimes(path, out DateTime fileDateCreated, out DateTime fileDateAccessed, out DateTime fileDateModified);
</code>```

GetFileTimeSample

```<code>public class GetFileTimeSample
{
    private const uint GENERIC_READ = 0x80000000;
    private const uint FILE_SHARE_READ = 0x1;
    private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    private const int INVALID_HANDLE_VALUE = -1;
    private const uint OPEN_EXISTING = 3;

    [StructLayout(LayoutKind.Sequential)]
    private struct FILETIME
    {
    public uint dwLowDateTime;
    public uint dwHighDateTime;
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(
    IntPtr hObject
    );

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    private static extern IntPtr CreateFile(
    string lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr SecurityAttributes,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool GetFileTime(
    IntPtr hFile,
    ref FILETIME lpCreationTime,
    ref FILETIME lpLastAccessTime,
    ref FILETIME lpLastWriteTime
    );

    public static void GetFileTimes(string FileName, out DateTime CreationTime, out DateTime LastAccessTime, out DateTime LastWriteTime)
    {
    CreationTime = DateTime.MinValue;
    LastAccessTime = DateTime.MinValue;
    LastWriteTime = DateTime.MinValue;
    IntPtr ptr = IntPtr.Zero;
    FILETIME ftCreationTime = new FILETIME();
    FILETIME ftLastAccessTime = new FILETIME();
    FILETIME ftLastWriteTime = new FILETIME();
    try
    {
        ptr = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
        if (ptr.ToInt32() == INVALID_HANDLE_VALUE)
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        if (GetFileTime(ptr, ref ftCreationTime, ref ftLastAccessTime, ref ftLastWriteTime) != true)
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        CreationTime = DateTime.FromFileTimeUtc((((long)ftCreationTime.dwHighDateTime) << 32) | ((uint)ftCreationTime.dwLowDateTime));
        LastAccessTime = DateTime.FromFileTimeUtc((((long)ftLastAccessTime.dwHighDateTime) << 32) | ((uint)ftLastAccessTime.dwLowDateTime));
        LastWriteTime = DateTime.FromFileTimeUtc((((long)ftLastWriteTime.dwHighDateTime) << 32) | ((uint)ftLastWriteTime.dwLowDateTime));
    }
    catch (Exception e)
    {
        throw (e);
    }
    finally
    {
        if (ptr !=IntPtr.Zero && ptr.ToInt32() != INVALID_HANDLE_VALUE) CloseHandle(ptr);
    }
    }
}
</code>```

Body:
I'm having an issue where a file containing a period at the end of its name cannot be seen by FileInfo. I know that Windows prevents naming files this way, but this data came from a different operating system.

I am able to create a problem file in Windows by using command line:

echo "test" > "\\?\C:\Test\BadFileName."

and this is the code I was using to test the file:

DateTime origAccessDate;
DateTime OrigCreateDate;
long sizeBytes;

string path = @"\\?\C:\Test\BadFileName.";
FileInfo fi = new FileInfo(path);

try
{
     origAccessDate = fi.LastAccessTime;
     OrigCreateDate = fi.CreationTime;
     sizeBytes = fi.Length;
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}

The problem occurs when FileInfo is called on the path. The Exists property is false, even though you can copy/paste the path to confirm it is valid. The goal is not to rename the file in order to read, but to read it in place (as-is).

Body:
Since this is obviously an unsupported scenario, I doubt it can be done without using some low-level file access.

What you could try to do is drop FileInfo and go with
File.Exists(path) and File.ReadAllBytes(path).
These might be able to circumvent the issue.

File Access using SafeFileHandle

The following is untested

Creating an instance of UnmanagedFileLoader (Code below, taken from MSDN), allows you to create a SafeFileHandle object which can be passed to the FileStream constructor in the following way:

UnmanagedFileLoader ufl = new UnmanagedFileLoader(path);
FileStream fs = new FileStream(ufl.Handle, FileMode.Open);

Note: Remember to call ufl.Handle.Dispose().

This should give you a more, shall we say, direct access to the file, and so go around the enforcement of a valid filename that Windows has in place.

UnmanagedFileLoader Code

class UnmanagedFileLoader
{
    public const short FILE_ATTRIBUTE_NORMAL = 0x80;
    public const short INVALID_HANDLE_VALUE = -1;
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const uint CREATE_NEW = 1;
    public const uint CREATE_ALWAYS = 2;
    public const uint OPEN_EXISTING = 3;

    // Use interop to call the CreateFile function.
    // For more information about CreateFile,
    // see the unmanaged MSDN reference library.
    [DllImport("kernel32.dll", SetLastError = true, CharSet=CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
      uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
      uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    private SafeFileHandle handleValue = null;

    public UnmanagedFileLoader(string Path)
    {
        Load(Path);
    }

    public void Load(string Path)
    {
        if (Path == null || Path.Length == 0)
        {
            throw new ArgumentNullException("Path");
        }

        // Try to open the file.
        handleValue = CreateFile(Path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

        // If the handle is invalid,
        // get the last Win32 error
        // and throw a Win32Exception.
        if (handleValue.IsInvalid)
        {
            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        }
    }

    public SafeFileHandle Handle
    {
        get
        {
            // If the handle is valid,
            // return it.
            if (!handleValue.IsInvalid)
            {
                return handleValue;
            }
            else
            {
                return null;
            }
        }

    }
}

File Date Access using Windows API

The GetFileTimeSample class below, taken from www.pinvoke.net uses another Windows API call, specifically GetFileTime.
This implementation is just an example, you sure will be able to adapt it to get only the date you need. In its current form it will output all three dates.

Usage:

DateTime fileDateCreated;
DateTime fileDateAccessed;
DateTime fileDateModified;
GetFileTimeSample.GetFileTimes(path, out fileDateCreated, out fileDateAccessed, out fileDateModified);

Since C# 7.0 it is possible to declare out variables directly in the function call like so:

GetFileTimeSample.GetFileTimes(path, out DateTime fileDateCreated, out DateTime fileDateAccessed, out DateTime fileDateModified);

GetFileTimeSample

public class GetFileTimeSample
{
    private const uint GENERIC_READ = 0x80000000;
    private const uint FILE_SHARE_READ = 0x1;
    private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
    private const int INVALID_HANDLE_VALUE = -1;
    private const uint OPEN_EXISTING = 3;

    [StructLayout(LayoutKind.Sequential)]
    private struct FILETIME
    {
    public uint dwLowDateTime;
    public uint dwHighDateTime;
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(
    IntPtr hObject
    );

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    private static extern IntPtr CreateFile(
    string lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr SecurityAttributes,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile
    );

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool GetFileTime(
    IntPtr hFile,
    ref FILETIME lpCreationTime,
    ref FILETIME lpLastAccessTime,
    ref FILETIME lpLastWriteTime
    );

    public static void GetFileTimes(string FileName, out DateTime CreationTime, out DateTime LastAccessTime, out DateTime LastWriteTime)
    {
    CreationTime = DateTime.MinValue;
    LastAccessTime = DateTime.MinValue;
    LastWriteTime = DateTime.MinValue;
    IntPtr ptr = IntPtr.Zero;
    FILETIME ftCreationTime = new FILETIME();
    FILETIME ftLastAccessTime = new FILETIME();
    FILETIME ftLastWriteTime = new FILETIME();
    try
    {
        ptr = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
        if (ptr.ToInt32() == INVALID_HANDLE_VALUE)
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        if (GetFileTime(ptr, ref ftCreationTime, ref ftLastAccessTime, ref ftLastWriteTime) != true)
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
        CreationTime = DateTime.FromFileTimeUtc((((long)ftCreationTime.dwHighDateTime) << 32) | ((uint)ftCreationTime.dwLowDateTime));
        LastAccessTime = DateTime.FromFileTimeUtc((((long)ftLastAccessTime.dwHighDateTime) << 32) | ((uint)ftLastAccessTime.dwLowDateTime));
        LastWriteTime = DateTime.FromFileTimeUtc((((long)ftLastWriteTime.dwHighDateTime) << 32) | ((uint)ftLastWriteTime.dwLowDateTime));
    }
    catch (Exception e)
    {
        throw (e);
    }
    finally
    {
        if (ptr !=IntPtr.Zero && ptr.ToInt32() != INVALID_HANDLE_VALUE) CloseHandle(ptr);
    }
    }
}


问:
I want to write a tool without usage entry barriers. Do I have to write it in C?
I want to write an open-source tool for use by developers. I want to eliminate entry barriers, so if they like the idea, they just get the tool and start playing with it.

In particular, I don't want an "Oh, should I also install 200Mb of ThatLanguage runtime libraries? Oh, so they don't build on my latest version of Linux?" entry barrier.

Should I write this tool in C, then? Or is Python, or Java, or whatever, already sufficiently widespread to not worry about this sort of things altogether (everyone already has them installed)?

Well, of course I know that they are freaking hugely widespread, but still - are there any major benefits to writing a super-lightweight zero-dependency tool, or am I being too much of a perfectionist?

答:
I would say yes, you have to write it in C. If it were written in any language other than C (except perhaps C++ or Perl), I would definitely stop to consider whether the necessary build tools, runtime tools, and/or interpreter for that language would be available everywhere I might need the tool before getting myself dependent upon it. If the tool were meant for use in build scripts, I would consider it a complete show-stopper, since I can't expect anyone who wants to build my software to have random arbitrary language environments installed.

The reason I mentioned C++ and Perl as exceptions is that they're both largely portable in a formal sense. They have implementations that work without significant ties to the host implementation, and can be built not just on any current popular system but on any system that remotely adheres to standards. Python is quite the opposite, with strong dependencies on the underlying system's dynamic loader; I've been completely unable to get Python to work on various systems that only support static linking.

ocaml is another possible choice that has a very portable implementation, but it's not widely installed and people who aren't familiar with it tend to frown on it for no good reason.


问:
How to add text on a image in html5 and css3
Enclosing the code and how can i add the text on image  how write the code for it.as im working on it</p>

```<code><div class="content">
                <div class="section">
                <div class="box">
                    <a href="#">

                    <img src="./images/pc.jpg" alt style="height: 210px; width: 215px; border: 1px solid black; margin-left: -13px; border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>
                    <br>
                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: -13px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                    <a href="#"><img src="./images/pc.jpg" style="height: 210px; width: 215px; border: 1px solid black; margin-left: 25px;border-bottom: 10px solid blue;"></a>

                </div>

                </div>

                </div>
</code>```

答: Take a look at the following: https://css-tricks.com/text-blocks-over-image/</p>