问:
Creating input text field on marked checkbox in JQuery
I was asked to do something particular, and after trying I eventually found this site https://codepen.io/elmahdim/pen/hlmri from which I'm using the JQuery. I however don't have any knowledge of it so I only understand in parts. What I'm trying to do is upon marking a checkbox an input type="text" appears below it, so if I check 3 results, input type="text"creates 3 fields, etc, and if I uncheck a checkbox, the camp gets deleted.

I've tried to do it by adding

```<code>$("div bb")
{
$('<input type="text" id="textbox" style="width:170px;"/><span> CHF <span>');
            }
</code>```

after $(".hida").hide();but as I have no knowledge of JQuery it obviously didn't work and I don't really know what now. Also before that input, is it possible to add some sort of variable that  is "attached" to the input so I can specificy what that input is for? Like if I check "Mercedes"  in the checkbox, the input type="text" is created and above it the name "Mercedes" then if I check "BMW" it makes another input type="text" with BMW written above it?

Also wruting the code like this $("div bb") { for some reason disabled the $. Not sure why.

答:
One solution:

create an empty element in your html where the input fields
should appear (e.g.

)

find the "on-checkbox-click-event-handler", which happens to be this line in the jquery: $('.mutliSelect input[type="checkbox"]').on('click', function() {

add code to the handler at the correct location, to append/delete a text box (difficult if you don't know jquery at all). The correct location is where jquery looks for the "checked-state" of the checkbox. Use $().append() to create the text field and $().remove() to remove on unchecking the checkbox. Should be something like $("#textfields").append("<input type='text'/>"); you will need to add a class to the input field to later address it when removing.

Working pen:
https://codepen.io/anon/pen/gRdmXj

Happy coding!

Body:
I was asked to do something particular, and after trying I eventually found this site https://codepen.io/elmahdim/pen/hlmri from which I'm using the JQuery. I however don't have any knowledge of it so I only understand in parts. What I'm trying to do is upon marking a checkbox an input type="text" appears below it, so if I check 3 results, input type="text"creates 3 fields, etc, and if I uncheck a checkbox, the camp gets deleted.

I've tried to do it by adding

$("div bb")
{
$('<input type="text" id="textbox" style="width:170px;"/> CHF ');
            }

after $(".hida").hide();but as I have no knowledge of JQuery it obviously didn't work and I don't really know what now. Also before that input, is it possible to add some sort of variable that  is "attached" to the input so I can specificy what that input is for? Like if I check "Mercedes"  in the checkbox, the input type="text" is created and above it the name "Mercedes" then if I check "BMW" it makes another input type="text" with BMW written above it?

Also wruting the code like this $("div bb") { for some reason disabled the $. Not sure why.

Body:
One solution:

create an empty element in your html where the input fields
should appear (e.g. <div id="textfields"></div>)

find the "on-checkbox-click-event-handler", which happens to be this line in the jquery: $('.mutliSelect input[type="checkbox"]').on('click', function() {

add code to the handler at the correct location, to append/delete a text box (difficult if you don't know jquery at all). The correct location is where jquery looks for the "checked-state" of the checkbox. Use $().append() to create the text field and $().remove() to remove on unchecking the checkbox. Should be something like $("#textfields").append("<input type='text'/>"); you will need to add a class to the input field to later address it when removing.

Working pen:
https://codepen.io/anon/pen/gRdmXj

Happy coding!


来源: stackexchange

问:
Automatically recycle app pool before .net debug
Before the start of debugging for my MVC application, I want to recycle the IIS app pool it is using.  I can't find any type of script I could create or setting I could change from online searches.

Does anyone know a way to recycle the assigned app pool when I start the debug process in .NET?

答:
If you want to restart the whole IIS,just issue iisreset command.Or You can write a simple Powershell script to do this

```<code>Import-Module WebAdministration
$mysite = "Default Web Site"
$pool = (Get-Item "IIS:\Sites\$mysite"| Select-Object applicationPool).applicationPool
Restart-WebAppPool $pool
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to restart the whole IIS,just issue iisreset command.Or You can write a simple Powershell script to do this

Import-Module WebAdministration
$mysite = "Default Web Site"
$pool = (Get-Item "IIS:\Sites\$mysite"| Select-Object applicationPool).applicationPool
Restart-WebAppPool $pool


问:
Mocking a Class For Unit Tests
I've Class A that has an instance of another Class B. I've completed unit testing of independent code in Class B. For other operations, Class A invokes methods of Class B, does some processing using other classes and then invokes methods of Class B.

My question is how do I mock the dependency of Class A and complete unit testing of Class B? If Class B uses instance of Class A, I can mock Class A and complete the task. However, in my case Class A uses instance of Class B.

How do I mock in this scenario for unit testing?

答:
This depends on how you have designed your class A and class B.

If they have been well-designed then you can easily make mock implementation for interface IB - interface of B - (using GoogleTest & GoogleMock) then use this mock implementation in unit tests of class A. To see how to use GoogleMock, check GoogleMock CheatSheet.

Otherwise, you may have run into a situation similar to Google Mock: Mock private variable member that is instantiated in target class's constructor then you may need to use some preprocessor directives to break your class A.

Title: Mocking a Class For Unit Tests


问:
Delete batch operation in Azure Storage
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

```<code>TableOperation deleteEntity = TableOperation.delete(entity);
</code>```

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.

答:
No, That was the code without using block operation. Following is the code that includes block operation. Sorry for not mentioning that</p>

```<code> TableBatchOperation batchOperation = new TableBatchOperation();
    List<TableBatchOperation> list = new ArrayList<>();

    if (partitionQuery != null) {
        for (AzureLocationData entity : cloudTable.execute(partitionQuery)) {

            batchOperation.add(TableOperation.delete(entity));
            list.add(batchOperation);    //exception thrown line
        }
        try {
            cloudTable.execute((TableOperation) batchOperation);
        } catch (StorageException e) {
            e.printStackTrace();
            }
            }
</code>```

Title: Delete batch operation in Azure Storage

Body:
I have been trying to implement a DAO method for delete operation for Azure Storage entities. Delete using TableOperation was ok.

TableOperation deleteEntity = TableOperation.delete(entity);

But when I tried it using Batch Operation, It was not supported.

Any suggestions to overcome this issue is highly appreciated.

Body:
No, That was the code without using block operation. Following is the code that includes block operation. Sorry for not mentioning that

 TableBatchOperation batchOperation = new TableBatchOperation();
    List<TableBatchOperation> list = new ArrayList<>();

    if (partitionQuery != null) {
        for (AzureLocationData entity : cloudTable.execute(partitionQuery)) {

            batchOperation.add(TableOperation.delete(entity));
            list.add(batchOperation);    //exception thrown line
        }
        try {
            cloudTable.execute((TableOperation) batchOperation);
        } catch (StorageException e) {
            e.printStackTrace();
            }
            }


问:
Actions to do in a Pull Request with 'requested changes' to notify that changes have been done
I have created a pull request in GitHub that has been reviewed and the reviewer has requested changes. I have done the changes and added a comment in the pull request conversation with a reference to the reviewer so I expect a notification has been sent to him.

Is there any other thing I must do in GitHub to reflect that I have pushed corrections to the requested changes?

答: What you did is standard operating procedure when replying to a change request in a pull request.  Since you pushed your changes, the branch in question has been updated.  If your reviewer's GitHub is configured to not receive notifications he may not have received one, but from your point of view you have met your expectations.  The other Git repositories (e.g. Bitbucket) also behave similarly to this.</p>


问:
Creating a folder with today's date using c++
I am new to c++ programing and working with visual Studio 2015. I want to create a Folder with  a Name of current date in a particular path. I searched on the Internet but I was not able to find the satisfactory solution. Moreover I tried by my own but unfortunately the result is not successful.
I used _mkdir() and CreateFolder().

For example, if i compile the program today (07.07.2017) then it should create a Folder with a Name: "07072017" and if i compile it again then it should Show the message: "Folder already exists".

Thanks in advance.

答:
You could try using WINDOWS API CreateDirectory function if we are talking about windows.
More information : https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx

Use argv[0] to get your .exe current directory from main(int argc, char argv[]) and remember to do #include <windows.h>. You could also try to execute shell or cmd.exe with arguments mkdir folderName to make it.

As for retrieving current date i would recommend reading
How to get current time and date in C++?


问:
iPhone Best practices for large number of animations using UIImageView
Just requesting a little advice animating images on the iphone. I'm building an app that consists of a character with 5 animations.

Each animation consists of roughly 50 images with an average duration of 3 seconds.

I was going to create an array of images for each animation, have these as the source for an UIImageView and switch these as needed. But as you can guess this approach kills my iphone's memory and thus the app. (250 images @ 130K each!)

So this got me wondering how other people get around this? Maybe change the animations to movies?

Thanks for any advice.

答:
Have you tried setting the animationImages property on a UIImageView with an array of UIImages representing your frames.  I have done that in the past and it worked pretty well, but I didn't have as many images as you in my animation.

If there is too much data in your images, you may have to do something more complex, like a sprite atlas.  That method combines a bunch of your frames as one image and then animates the frames by changing the viewable portion of the big image.  That way the whole thing loads at once and the animation just changes the part of the image that the user sees.  Cocos2D has a bunch of functionality around sprite animation.  If the animationImages thing doesn't work, you might want to try that.

--Mike

ContentLicense: CC BY-SA 2.5


问:
Rename multiple files by replacing a particular pattern in the filenames using a shell script

Write a simple script that will automatically rename a number of files. As an example we want the file *001.jpg renamed to user defined string + 001.jpg (ex: MyVacation20110725_001.jpg) The usage for this script is to get the digital camera photos to have file names that make some sense.

I need to write a shell script for this. Can someone suggest how to begin?

答:
this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"

solution  : first identified all jpg files and then replace keyword

```<code>find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \;
</code>```

Body:
this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"

solution  : first identified all jpg files and then replace keyword

find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \;


问:
Difference between universal and nth-child selector to get all direct children?
I wonder, if there is a difference of getting every direct child in css between

```<code>tag > *
</code>```

and

```<code>tag > :nth-child(n)
</code>```

I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.

答:
Take a look at the w3school the :nth-child() selector is for select an specific child, but if you want to select everything from the container, use the * selector. In the case of using :nth-child(n), is the same as using the * selector, and the * uses less space.

Wonder it helps.

Body:
I wonder, if there is a difference of getting every direct child in css between

tag > *

and

tag > :nth-child(n)

I know that the universal selector is slow, but I don't know, what the nth-child selector is doing under the hood.


问:
Can VS Code automatically update JavaScript and TypeScript import paths on file rename/move?
Is there a module for vscode that would update paths towards files? e.g. if I have:

```<code>import './someDir/somelib'
</code>```

and I rename or move somelib, would it automatically update the file path in all the files where it is being referred as above?

答:
This feature was added for JavaScript and TypeScript in VS Code 1.24 (tracking issue)

When you move or rename a file, you will now be prompted to see if you want to update imports:

This is controlled by the javascript.updateImportsOnFileMove.enabled and typescript.updateImportsOnFileMove.enabled settings. Valid values are:

"prompt" — The default. Prompt for each file rename/move

"always" — Always try to update imports automatically without prompting

"never" — Do not update imports and do not prompt

ContentLicense: CC BY-SA 4.0

Body:
Is there a module for vscode that would update paths towards files? e.g. if I have:

import './someDir/somelib'

and I rename or move somelib, would it automatically update the file path in all the files where it is being referred as above?


问:
Improving Python user defined max function
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

```<code>def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'
</code>```

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.

答:
For returning the greatest number from a list the simple algorithm followed is compare two numbers and keep the larger number in a variable, then print the variable OR you can use python shortcut using sort.

Using user defined function:

```<code>def greatest_ele_list(listobj):
    greatest=listobj[0]
    for i in range(len(listobj)):
        if listobj[i]>greatest:
           greatest=listobj[i]
        else:
           pass
    return greatest
print greatest_ele_list([4,5,3,8,1])
</code>```

Using sort:

```<code>def greatest_ele_list(listobj):
    listobj2=listobj.sort()
    return listobj2[-1]
print greatest_ele_list([4,5,3,8,1])
</code>```

Output:  >>> 8

Body:
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.

Body:
For returning the greatest number from a list the simple algorithm followed is compare two numbers and keep the larger number in a variable, then print the variable OR you can use python shortcut using sort.

Using user defined function:

def greatest_ele_list(listobj):
    greatest=listobj[0]
    for i in range(len(listobj)):
        if listobj[i]>greatest:
           greatest=listobj[i]
        else:
           pass
    return greatest
print greatest_ele_list([4,5,3,8,1])

Using sort:

def greatest_ele_list(listobj):
    listobj2=listobj.sort()
    return listobj2[-1]
print greatest_ele_list([4,5,3,8,1])

Output:  >>> 8


问:
Calling Python 2 script from Python 3
I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library). </p>

<p>There is one method in the Python 2 script I want to call from the Python 3 script, but I don't know how to cross this bridge. </p>

答:
Calling different python versions from each other can be done very elegantly using execnet. The following function does the charm:

```<code>import execnet

def call_python_version(Version, Module, Function, ArgumentList):
    gw      = execnet.makegateway("popen//python=python%s" % Version)
    channel = gw.remote_exec("""
        from %s import %s as the_function
        channel.send(the_function(*channel.receive()))
    """ % (Module, Function))
    channel.send(ArgumentList)
    return channel.receive()
</code>```

Example: A my_module.py written in Python 2.7:

```<code>def my_function(X, Y):
    return "Hello %s %s!" % (X, Y)
</code>```

Then the following function calls

```<code>result = call_python_version("2.7", "my_module", "my_function",
                             ["Mr", "Bear"])
print(result)
result = call_python_version("2.7", "my_module", "my_function",
                             ["Mrs", "Wolf"])
print(result)
</code>```

result in

```<code>Hello Mr Bear!
Hello Mrs Wolf!
</code>```

What happened is that a 'gateway' was instantiated waiting
for an argument list with channel.receive(). Once it came in, it as been translated and passed to my_function. my_function returned the string it generated and channel.send(...) sent the string back. On other side of the gateway channel.receive() catches that result and returns it to the caller. The caller finally prints the string as produced by my_function in the python 3 module.

Title: Calling Python 2 script from Python 3

Body:
I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library).

There is one method in the Python 2 script I want to call from the Python 3 script, but I don't know how to cross this bridge.

Body:
Calling different python versions from each other can be done very elegantly using execnet. The following function does the charm:

import execnet

def call_python_version(Version, Module, Function, ArgumentList):
    gw      = execnet.makegateway("popen//python=python%s" % Version)
    channel = gw.remote_exec("""
        from %s import %s as the_function
        channel.send(the_function(*channel.receive()))
    """ % (Module, Function))
    channel.send(ArgumentList)
    return channel.receive()

Example: A my_module.py written in Python 2.7:

def my_function(X, Y):
    return "Hello %s %s!" % (X, Y)

Then the following function calls

result = call_python_version("2.7", "my_module", "my_function",
                             ["Mr", "Bear"])
print(result)
result = call_python_version("2.7", "my_module", "my_function",
                             ["Mrs", "Wolf"])
print(result)

result in

Hello Mr Bear!
Hello Mrs Wolf!

What happened is that a 'gateway' was instantiated waiting
for an argument list with channel.receive(). Once it came in, it as been translated and passed to my_function. my_function returned the string it generated and channel.send(...) sent the string back. On other side of the gateway channel.receive() catches that result and returns it to the caller. The caller finally prints the string as produced by my_function in the python 3 module.


问:
Why am I showing up as two contributors in GitLab?
I am using SmartGit 17 and GitLab Enterprise 8.6.0-ee, on Windows 7 Enterprise.  I upgraded SmartGit not too long ago from version 7.1.  I've been working intermittently on a project (I'm the only person working on this project), and today decided to browse around GitLab a little.  I noticed on the Graphs page, Contributors tab, that it shows two contributors, both of whom are me.  One has my full first and last name, and the other has only my last name.  One has my e-mail address all in lower case and the other has it in mixed case.  Over time, there is a ramp-down from May 28 to a little after July 2 of the one contributor, and a corresponding ramp up of the other one.

I vaguely seem to remember being prompted to enter my name and e-mail address and accepting a default (which was just my last name), and I think it is related to SmartGit, but I can't see to find where this is recorded so I can change it back globally rather than on a per-repository basis.

Can anyone tell me where to look?

Also, I don't konw whether "contributor" means committer or author, or if that matters.

答:
You need to edit your .gitconfig file.

If you're using Ubuntu, just do:

```<code>sudo nano home/<yourUserName>/.gitconfig
</code>```

Then change those 2 lines:

```<code>[user]
    name = enterYourNameHere
    email = enteryourEmailHere
</code>```

Don't forget to do the same thing (with the exact user.name and user.email) on each machine you're using!

"... One has my e-mail address all in lower case and the other has it
  in mixed case."

For your information: This bug has been reported by Gitlab team. See contributor emails in contributors graphs is case sensitive and/or Resolve : contributor emails in contributors graphs is case sensitive

Hope it helps you.

Body:
You need to edit your .gitconfig file.

If you're using Ubuntu, just do:

sudo nano home/<yourUserName>/.gitconfig

Then change those 2 lines:

[user]
    name = enterYourNameHere
    email = enteryourEmailHere

Don't forget to do the same thing (with the exact user.name and user.email) on each machine you're using!

"... One has my e-mail address all in lower case and the other has it
  in mixed case."

For your information: This bug has been reported by Gitlab team. See contributor emails in contributors graphs is case sensitive and/or Resolve : contributor emails in contributors graphs is case sensitive

Hope it helps you.


问:
Unable to filter messages by recipient in Microsoft Graph Api. One or more invalid nodes
I am trying to get a list of messages that are filtered by recipient from Microsoft Graph API. The url I am using for the request is:

https://graph.microsoft.com/beta/me/messages?$filter=toRecipients/any(r: r/emailAddress/address eq '[Email Address]')

But I am getting this is the response:

```<code>{
   "error": {
        "code": "ErrorInvalidUrlQueryFilter",
        "message": "The query filter contains one or more invalid nodes.",
        "innerError": {
            "request-id": "7db712c3-e337-49d9-aa8d-4a5d350d8480",
            "date": "2016-09-28T16:58:34"
        }
    }
}
</code>```

A successful request should look like this (with a lot more data that I have omitted).

```<code>{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#users('99999999-9999-9999-9999-999999999999')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/beta/me/messages?$skip=10",
    "value": [
        {
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "[Name]",
                        "address": "[Email Address]"
                    }
                }
            ],
        }
    ]
}
</code>```

The request works if I remove the filter, and I am able to perform requests with simpler filters.

Is there a problem with my URL, or is there another way to make the request?

答:
After several hours looking for the solution, I found in the office365 documentation that the property toRecipients is not filterable:

https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#MessageResource

I guess that it's the same in the graph api. So the only solution is using search.

Body:
I am trying to get a list of messages that are filtered by recipient from Microsoft Graph API. The url I am using for the request is:

https://graph.microsoft.com/beta/me/messages?$filter=toRecipients/any(r: r/emailAddress/address eq '[Email Address]')

But I am getting this is the response:

{
   "error": {
        "code": "ErrorInvalidUrlQueryFilter",
        "message": "The query filter contains one or more invalid nodes.",
        "innerError": {
            "request-id": "7db712c3-e337-49d9-aa8d-4a5d350d8480",
            "date": "2016-09-28T16:58:34"
        }
    }
}

A successful request should look like this (with a lot more data that I have omitted).

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#users('99999999-9999-9999-9999-999999999999')/messages",
    "@odata.nextLink": "https://graph.microsoft.com/beta/me/messages?$skip=10",
    "value": [
        {
            "toRecipients": [
                {
                    "emailAddress": {
                        "name": "[Name]",
                        "address": "[Email Address]"
                    }
                }
            ],
        }
    ]
}

The request works if I remove the filter, and I am able to perform requests with simpler filters.

Is there a problem with my URL, or is there another way to make the request?


问:
MemberInfo.GetCustomAttributes extensions overload
I noticed there are two methods (one class method and one extension method) with the same signature but different return types in package System.Reflection for class MemberInfo:

Class method:

```<code>public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)
</code>```

Extension method (inside CustomAttributeExtensions):

```<code>public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)
</code>```

I know that calling that method with such parameters will always invoke class method, so I am just wondering:

how to call extension method?

and, above all, what's the purpose of defining an extension with same signature as class method?

答:
You are right, there is MemberInfo.GetCustomAttributes and CustomAttributeExtensions.GetCustomAttributes with effectively the same set of parameters.

If you look at the reference source for each, you can see that the extension method actually delegates back to Attribute.GetCustomAttribute. And that method will eventually get back to MemberInfo.GetCustomAttributes.

So is there a functional difference between those two? No, not really. Then what is the reason why this extension method exists? I unfortunately have no clue. The major benefit of CustomAttributeExtensions are the generic overloads anyway which allow you to get typed attributes back, so I don’t think you would actually want to use GetCustomAttributes in a usual situation.

Body:
I noticed there are two methods (one class method and one extension method) with the same signature but different return types in package System.Reflection for class MemberInfo:

Class method:

public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)

Extension method (inside CustomAttributeExtensions):

public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)

I know that calling that method with such parameters will always invoke class method, so I am just wondering:

how to call extension method?

and, above all, what's the purpose of defining an extension with same signature as class method?


问:
How to swap value in SQL Server?
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

```<code>DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'
</code>```

what i tried

```<code>SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable
</code>```

Result is wrong:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

I want to achieve:

```<code>Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000
</code>```

答:
Just by using NULLIF you can get your desired Result</p>

```<code>SELECT Id
    ,RoomNo
    ,Class
    ,Price
    ,NULLIF(ISRoomNo, RoomNo) NewRoomNo
    ,NULLIF(ISCLASS, Class) AS NewClass
    ,Price
FROM (

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)) ISRoomNo,
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)) ISCLASS

 FROM @MyTable as MyTable
    )DT
</code>```

Title: How to swap value in SQL Server?

Body:
I want to swap the value between the row but I don't have an idea how to make it as I create a script to do it but the answer still not correct. I get the data raw in from the pdf then convert it into excel 'xls'.

Please see the sample below.

DECLARE @MyTable TABLE(Id INT, RoomNo INT, Class VARCHAR(10), Price VARCHAR(255))

INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 1,    21,     'A',        '43,028,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 2,    NULL,   NULL,       '43,896,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 3,    20,     'A',        '42,681,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 4,    NULL,   NULL,       '43,549,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 5,    19,     'A',        '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 6,    NULL,   NULL,       '43,202,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 7,    18,     'A',        '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 8,    NULL,   NULL,       '42,855,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 9,    17,     'A',        '41,467,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 10,   NULL,   NULL,       '42,334,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 11,   16,     'A',        '41,120,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 12,   NULL,   NULL,       '41,987,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 13,   NULL,   'A',        '39,211,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 14,   9,      NULL,       '40,079,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 15,   NULL,   NULL,       '38,691,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 16,   6,      NULL,       '39,385,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 17,   NULL,   'A',        '44,756,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 18,   5,      NULL,       '45,591,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 19,   21,     'B',        '26,598,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 20,   20,     'B',        '26,393,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 21,   NULL,   NULL,       '26,905,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 22,   19,     'B',        '26,189,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 23,   NULL,   NULL,       '26,700,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 24,   18,     'B',        '25,984,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 25,   NULL,   NULL,       '26,496,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 26,   17,     'B',        '25,677,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 27,   NULL,   'B',        '24,041,000'
INSERT INTO @MyTable(Id, RoomNo, Class, Price) SELECT 28,   6,      NULL,       '24,552,000'

what i tried

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)),
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)),
        Price
    FROM @MyTable as MyTable

Result is wrong:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  21          A           43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  20          A           42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  19          A           42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  18          A           41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  17          A           41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  16          A           41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  16          A           39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  9           A           38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  6           A           44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  20          B           26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  19          B           26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  18          B           25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  17          B           24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

I want to achieve:

Id  RoomNo  Class   Price       NewRoomNo   NewClass    Price
1   21      A       43,028,000  NULL        NULL        43,028,000
2   NULL    NULL    43,896,000  21          A           43,896,000
3   20      A       42,681,000  NULL        NULL        42,681,000
4   NULL    NULL    43,549,000  20          A           43,549,000
5   19      A       42,334,000  NULL        NULL        42,334,000
6   NULL    NULL    43,202,000  19          A           43,202,000
7   18      A       41,987,000  NULL        NULL        41,987,000
8   NULL    NULL    42,855,000  18          A           42,855,000
9   17      A       41,467,000  NULL        NULL        41,467,000
10  NULL    NULL    42,334,000  17          A           42,334,000
11  16      A       41,120,000  NULL        NULL        41,120,000
12  NULL    NULL    41,987,000  16          A           41,987,000
13  NULL    A       39,211,000  NULL        NULL        39,211,000
14  9       NULL    40,079,000  9           A           40,079,000
15  NULL    NULL    38,691,000  NULL        NULL        38,691,000
16  6       NULL    39,385,000  6           A           39,385,000
17  NULL    A       44,756,000  NULL        NULL        44,756,000
18  5       NULL    45,591,000  5           A           45,591,000
19  21      B       26,598,000  21          B           26,598,000
20  20      B       26,393,000  NULL        NULL        26,393,000
21  NULL    NULL    26,905,000  20          B           26,905,000
22  19      B       26,189,000  NULL        NULL        26,189,000
23  NULL    NULL    26,700,000  19          B           26,700,000
24  18      B       25,984,000  NULL        NULL        25,984,000
25  NULL    NULL    26,496,000  18          B           26,496,000
26  17      B       25,677,000  17          B           25,677,000
27  NULL    B       24,041,000  NULL        NULL        24,041,000
28  6       NULL    24,552,000  6           B           24,552,000

Body:
Just by using NULLIF you can get your desired Result

SELECT Id
    ,RoomNo
    ,Class
    ,Price
    ,NULLIF(ISRoomNo, RoomNo) NewRoomNo
    ,NULLIF(ISCLASS, Class) AS NewClass
    ,Price
FROM (

SELECT
        *,
        ISNULL(RoomNo, (SELECT TOP 1 RoomNo FROM @MyTable WHERE Id < MyTable.Id AND RoomNo IS NOT NULL ORDER BY ID DESC)) ISRoomNo,
        ISNULL(Class, (SELECT TOP 1 Class FROM @MyTable WHERE Id < MyTable.Id AND Class IS NOT NULL ORDER BY ID DESC)) ISCLASS

 FROM @MyTable as MyTable
    )DT


问:
powershell - Copy-Item creates empty folder
I wanted to copy a bunch of jpg/gif files with starting Name into another location. It works not as intended. It creates addition folders which stays emtpy and do not copy all subfolders. Then I run again through the whole path and remove all empty folders.

How can I prevent Copy-Item from creating addition empty folders?  I want to keep the current path with a new root and add a new subdirectory with the starting letters of the filename and put all the files there.

current folder structure

```<code>F:\pics\2016\071310
|
-----> K001
  |
  ------> 0494434-002394
  ------> 0494434-002394
.
.
------> K0073
</code>```

wanted folder structure

```<code>C:\test\2016\071310
|
-----> K001
  |
  ------> 0494434-002394
     |
     ----> K-G
     ----> K-F
     .
     .
  ------> 0494434-002394
     |
     ----> K-G
     ----> K-F
     .
     .
.
.
------> K0073
</code>```

Here is my code

```<code>$source = "F:\pics\2016\071310"
$destination = "C:\test"
$folder = "K-G\"
$filterKG = [regex] "^K-G.*\.(jpg|gif)"

$bin = Get-ChildItem -Exclude $folder -Path $source -Recurse | Where-Object {($_.Name -match $filterKG) -or ($_.PSIsContainer)}

foreach ($item in $bin){
$new_folder = $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder)

if(-not (Test-Path $new_folder)){
    New-Item -Type dir $new_folder
    Write-Host $new_folder
}
Copy-Item $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder+$item.Name)
}

#remove empty folders which where added
$tdc="C:\test"
do {
  $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ }
} while ($dirs.count -gt 0)
</code>```

答:
Current Script

$_.PSIsContainer - I think you're getting these to keep the folder structure but best to ignore as you're not directly interested in them. AFAICS this is why you're getting empty folders.

-Exclude $folder  - This isn't doing anything; folder with name K-G will still be included.

$item.FullName.ToString() - The ToString() is doing nothing as $item.FullName is already a string. Run $item.Fullname.GetType().Name to see.

Proposed Script

Split-path allows you to get the directory a file is in using -Parent.

.Replace($source,$destination) is as in your original script.

You don't need to hardcode $folder to get it in your destination. Just use $item.Name.SubString(0,3) to get the first 3 letters of a filename.

string manipulation demo

```<code>$bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filterKG)}

foreach ($item in $bin){

    $new_folder = (Split-path $item.Fullname -Parent).Replace($source,$destination) + "\" + $item.Name.SubString(0,3) + "\"

    if(-not (Test-Path $new_folder)){
        New-Item -Type dir $new_folder
        Write-Host $new_folder
    }

    Copy-Item $item.FullName -Destination $new_folder

}
</code>```

Body:
I wanted to copy a bunch of jpg/gif files with starting Name into another location. It works not as intended. It creates addition folders which stays emtpy and do not copy all subfolders. Then I run again through the whole path and remove all empty folders.

How can I prevent Copy-Item from creating addition empty folders?  I want to keep the current path with a new root and add a new subdirectory with the starting letters of the filename and put all the files there.

current folder structure

F:\pics\2016\071310
|
-----> K001
  |
  ------> 0494434-002394
  ------> 0494434-002394
.
.
------> K0073

wanted folder structure

C:\test\2016\071310
|
-----> K001
  |
  ------> 0494434-002394
     |
     ----> K-G
     ----> K-F
     .
     .
  ------> 0494434-002394
     |
     ----> K-G
     ----> K-F
     .
     .
.
.
------> K0073

Here is my code

$source = "F:\pics\2016\071310"
$destination = "C:\test"
$folder = "K-G\"
$filterKG = [regex] "^K-G.*\.(jpg|gif)"

$bin = Get-ChildItem -Exclude $folder -Path $source -Recurse | Where-Object {($_.Name -match $filterKG) -or ($_.PSIsContainer)}

foreach ($item in $bin){
$new_folder = $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder)

if(-not (Test-Path $new_folder)){
    New-Item -Type dir $new_folder
    Write-Host $new_folder
}
Copy-Item $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder+$item.Name)
}

#remove empty folders which where added
$tdc="C:\test"
do {
  $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ }
} while ($dirs.count -gt 0)

Body:
Current Script

$_.PSIsContainer - I think you're getting these to keep the folder structure but best to ignore as you're not directly interested in them. AFAICS this is why you're getting empty folders.

-Exclude $folder  - This isn't doing anything; folder with name K-G will still be included.

$item.FullName.ToString() - The ToString() is doing nothing as $item.FullName is already a string. Run $item.Fullname.GetType().Name to see.

Proposed Script

Split-path allows you to get the directory a file is in using -Parent.

.Replace($source,$destination) is as in your original script.

You don't need to hardcode $folder to get it in your destination. Just use $item.Name.SubString(0,3) to get the first 3 letters of a filename.

string manipulation demo

$bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filterKG)}

foreach ($item in $bin){

    $new_folder = (Split-path $item.Fullname -Parent).Replace($source,$destination) + "\" + $item.Name.SubString(0,3) + "\"

    if(-not (Test-Path $new_folder)){
        New-Item -Type dir $new_folder
        Write-Host $new_folder
    }

    Copy-Item $item.FullName -Destination $new_folder

}


问:
How to convert number to string - VBA
I'm trying to conver a number value to a strin ex. convert 10 to "10"

I tried

```<code>    With Range("B2:B" & NewResizeRange)
      .Value = Range("B2:B" & NewResizeRange).Value
      .NumberFormat = "0" ' Or .NumberFormat = "@"
   End With
</code>```

But it us not converting correctly. Any ideas?

答:
```<code>With Range("A1")
    .NumberFormat = "@"
    .Value = .Value
End With
</code>```

This will make the green triangle for Number stored as text show up and mean that your cell will indeed hold a text value. However, when doing calculations using such a cell as a parameter for the formula, Excel will do some conversion by itself.

If you do not want to use NumberFormat, you could also do:

Range("A1").value = "=""" & Range("A1").value & """" - This creates a formula (If the value was 10, it'll make a formula ="10") that forces the value to evaluate to a string.

Title: How to convert number to string - VBA

Body:
I'm trying to conver a number value to a strin ex. convert 10 to "10"

I tried

    With Range("B2:B" & NewResizeRange)
      .Value = Range("B2:B" & NewResizeRange).Value
      .NumberFormat = "0" ' Or .NumberFormat = "@"
   End With

But it us not converting correctly. Any ideas?

Body:
With Range("A1")
    .NumberFormat = "@"
    .Value = .Value
End With

This will make the green triangle for Number stored as text show up and mean that your cell will indeed hold a text value. However, when doing calculations using such a cell as a parameter for the formula, Excel will do some conversion by itself.

If you do not want to use NumberFormat, you could also do:

Range("A1").value = "=""" & Range("A1").value & """" - This creates a formula (If the value was 10, it'll make a formula ="10") that forces the value to evaluate to a string.


问:
Don't show detail of product in angular4
When I click on item I need

```<code> `<a
  href="#"
  class="list-group-item clearfix"
  (click)="onSelected()">
  <div class="pull-left">
    <h4 class="list-group-item-heading">{{recipe.name}}</h4>
    <p class="list-group-item-text">{{recipe.description}}</p>
  </div>
  <span class="pull-right">
        <img
          [src]="recipe.imagepath"
          alt="{{recipe.name}}"
          class="img-responsive"
          style="max-height: 50px;">
      </span>
</a>`
</code>```

item.ts :

```<code>    import { Component, OnInit,Input} from '@angular/core';
import {Recipe} from '../recipe';
import{RecipeServiceService} from'../../service/recipe-service.service';

@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {

  @Input() recipe:Recipe;

  constructor(private recipeservice:RecipeServiceService) { }

  ngOnInit() {

  }

  onSelected(){
    this.recipeservice.recipeSelected.emit(this.recipe);
    console.log("Item Select",this.recipe);
  }

}
</code>```

Put the selected value in recipeSelected

service.ts

```<code>import{Recipe} from'./../recipe-list/recipe';
import{EventEmitter} from'@angular/core';

export class RecipeServiceService {

  recipeSelected=new EventEmitter<Recipe>();

 private recipes:Recipe[]=[
    new Recipe('انگولار 4', 'بهترین کتاب موجود ', 'http://startupsac.com/wp-content/uploads/2015/10/AngularJS-Logo.jpg'),
    new Recipe('آموزش Asp Core 1.1 برای مبتدیان', 'آپدیت جدید کتاب', 'https://codeopinion.com/wp-content/uploads/2016/02/aspnetcore.png')
    ];

  getAllRecipe(){
   return this.recipes.slice();
  }

}
</code>```

And in recipe component, put the value of recipeSelected in selectedRecipe

recipe.ts

```<code>import { Component, OnInit } from '@angular/core';
import{RecipeServiceService} from'./service/recipe-service.service';
import{Recipe} from'./recipe-list/recipe';

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css'],
  providers:[RecipeServiceService]
})
export class RecipesComponent implements OnInit {

  selectedRecipe:Recipe;
  constructor(private recipeservice:RecipeServiceService) { }

  ngOnInit() {
    this.recipeservice.recipeSelected.subscribe(
      (rec:Recipe)=>{
        this.selectedRecipe=rec;
      })
      console.log("Component Select",this.selectedRecipe);
  }

}
</code>```

html

```<code>    <div class="row">
    <div class="col-md-5">
    <app-recipe-list></app-recipe-list>
  </div>
  <div class="col-md-7">
   <app-recipe-detail *ngIf="selectedRecipe; else infoText"
   [recipe]="selectedRecipe"></app-recipe-detail>
  <ng-template #infoText>
    Please Select Recipe
    </ng-template>
  </div>

</div>
</code>```

It shows me the list but when I click the item it doesn't show me the details of the recipe. How can I solve this problem?

答: It seems you are using a copy of https://github.com/crispinandrade/RecipeBookApp/ code. Try to run it first and compare you copy with it. There is no problem here.</p>

Body:
When I click on item I need

 `

{{recipe.name}}

{{recipe.description}}

`

item.ts :

    import { Component, OnInit,Input} from '@angular/core';
import {Recipe} from '../recipe';
import{RecipeServiceService} from'../../service/recipe-service.service';

@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {

  @Input() recipe:Recipe;

  constructor(private recipeservice:RecipeServiceService) { }

  ngOnInit() {

  }

  onSelected(){
    this.recipeservice.recipeSelected.emit(this.recipe);
    console.log("Item Select",this.recipe);
  }

}

Put the selected value in recipeSelected

service.ts

import{Recipe} from'./../recipe-list/recipe';
import{EventEmitter} from'@angular/core';

export class RecipeServiceService {

  recipeSelected=new EventEmitter<Recipe>();

 private recipes:Recipe[]=[
    new Recipe('انگولار 4', 'بهترین کتاب موجود ', 'http://startupsac.com/wp-content/uploads/2015/10/AngularJS-Logo.jpg'),
    new Recipe('آموزش Asp Core 1.1 برای مبتدیان', 'آپدیت جدید کتاب', 'https://codeopinion.com/wp-content/uploads/2016/02/aspnetcore.png')
    ];

  getAllRecipe(){
   return this.recipes.slice();
  }

}

And in recipe component, put the value of recipeSelected in selectedRecipe

recipe.ts

import { Component, OnInit } from '@angular/core';
import{RecipeServiceService} from'./service/recipe-service.service';
import{Recipe} from'./recipe-list/recipe';

@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css'],
  providers:[RecipeServiceService]
})
export class RecipesComponent implements OnInit {

  selectedRecipe:Recipe;
  constructor(private recipeservice:RecipeServiceService) { }

  ngOnInit() {
    this.recipeservice.recipeSelected.subscribe(
      (rec:Recipe)=>{
        this.selectedRecipe=rec;
      })
      console.log("Component Select",this.selectedRecipe);
  }

}

html

    <app-recipe-list></app-recipe-list>

   <app-recipe-detail *ngIf="selectedRecipe; else infoText"
   [recipe]="selectedRecipe"></app-recipe-detail>
  <ng-template #infoText>
    Please Select Recipe
    </ng-template>

It shows me the list but when I click the item it doesn't show me the details of the recipe. How can I solve this problem?


问:
Interface Builder doesn't show some of my resource images
I have almost 20 images in PNG format added to my current project on Xcode (under the proper group, Resources). Unfortunately, library window's Media tab doesn't show some of them. And if I create an UIImageView and set one of these invisible images from code, nothing shows up. I also tried from IB with adding a UIImageView and set its source image.

Is this problem a image format related issue or is there a tiny detail I'm missing.

What log says:

```<code>Could not load the "07_clock_icon.png" image referenced from a nib in the bundle
</code>```

答:
Same problem was encountered by me. The problem is with the image. The image has been some how corrupted.Try to open the image in photoshop and you will see it doesn't open with photoshop.
I solved the problem by changing the image format to PNG-24  and everything works fine for me.
Hope this will solve your issue.

Regards,

Rupesh R Menon

Body:
I have almost 20 images in PNG format added to my current project on Xcode (under the proper group, Resources). Unfortunately, library window's Media tab doesn't show some of them. And if I create an UIImageView and set one of these invisible images from code, nothing shows up. I also tried from IB with adding a UIImageView and set its source image.

Is this problem a image format related issue or is there a tiny detail I'm missing.

What log says:

Could not load the "07_clock_icon.png" image referenced from a nib in the bundle


问:
Indexing a MYSQL table with many columns
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

```<code>SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1
</code>```

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

```<code>CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);
</code>```

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

答:
You are over complicating your database schema, there is no need to add all those columns, nor to create a ton of indexes.

You can simplify your post table as:

```<code>id | title | (...) | start_at
</code>```

You can then replace this query:

```<code>SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1
</code>```

and instead use the DAYOFWEEK function:

```<code>SELECT * FROM posts WHERE start_at >= '2017-02-01' AND DAYOFWEEK(start_at) = 2
</code>```

(1 = Sunday, 2 = Monday, …, 7 = Saturday).

You can then keep a single index on the start_at column.

Body:
I have a table posts with the following columns:

start_at, sun, mon, tue, wen, thu, fri, sat

start_at is of date type, the others - tinyint.

I make a query the following way:

SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

That is after second AND I set proper day of week dynamically.

What is the best way to index this table? Do I need to make a composite index for each day of a week, for example:

CREATE INDEX mon_index ON posts(start_at,mon);
CREATE INDEX sun_index ON posts(start_at,sun);

If I create 7 indexes for each day of the week, I think INSERT and UPDATE will be really slow.

UPDATED: I do need column for each day of week, because a user sets on which days post will be published. There can be a few days at the same time.

Body:
You are over complicating your database schema, there is no need to add all those columns, nor to create a ton of indexes.

You can simplify your post table as:

id | title | (...) | start_at

You can then replace this query:

SELECT * FROM posts WHERE start_at >= '2017-02-01' AND mon = 1

and instead use the DAYOFWEEK function:

SELECT * FROM posts WHERE start_at >= '2017-02-01' AND DAYOFWEEK(start_at) = 2

(1 = Sunday, 2 = Monday, …, 7 = Saturday).

You can then keep a single index on the start_at column.


问:
Display Exact Copy of Stage
I am working on a new project that will need to show a separate stage on the secondary monitor. This will be a non-interactive stage (only used to display nodes).  I will follow this approach to handle that part.

However, I also want to have a duplicate copy of that stage visible within a pane in my main app. It would need to update itself at the same time the stage does.

Where would I start learning how to implement this? Does Java provide a built-in API to display realtime screenshots of a stage, by chance?

答:
I am no expert but I think there are two ways to do it.

Method 1

Wrap everything of that stage into a main FXML/controller file/class (as a View). Then you need to load that FXML file twice, once in the new stage, the other in a dedicated space you have prepared in your main stage.

The reference of both controller instances should ideally be held at the same object, either in your application class or the class hosting your main stage.

From there, you can either bind values and let the binding API do the work for you.

Example:

Main View:

```<code>public class MainView {
    private Model model = new Model();
    private Pane space; // Dedicated space

    public void spawnView() {
        FXMLLoader spawnViewLoader = new FXMLLoader(getClass().getResource("View.fxml"));
        Parent spawnView = spawnViewLoader.load(); // Need to catch IOException
        ViewController spawnController = spawnViewLoader.getController();
        spawnController.setup(model);

        new Stage(new Scene(view));

        FXMLLoader dupViewLoader = new FXMLLoader(getClass().getResource("View.fxml"));
        Parent dupView = dupViewLoader.load(); // Need to catch IOException
        ViewController dupController = dupViewLoader.getController();
        dupController.setup(model);

        space.getChildren().setAll(dupView);
    }
}
</code>```

Model:

```<code>public class Model {
    private final StringProperty title = new SimpleStringProperty();
    private final StringProperty titleProperty() { return title; }
    private final String getTitle() { return title.get(); }
    private final void setTitle(final String title) { this.title.set(title); }
}
</code>```

View controller:

```<code>public class ViewController {
    @FXML private Label label;

    private Model model;

    public void setup(Model model) {
        if (model == null)
            throw new NullPointerException();

        this.model = model;
        label.textProperty().bind(model.titleProperty());
    }

    // Other stuff
}
</code>```

Be careful of the binding though - I'm quite sure whatever I wrote is going to cause memory leak; both Views will not clean up as long you're holding a reference of model. You can always do it without binding, but it's going to be more tedious to update values.

Method 2

This method is more complex and is likely to be several frames slower. I'm not going to post sample codes as this is not that straight-forward.

You need to have a reference of the Scene of that stage, and use an AnimationTimer to call the snapshot method of the scene object.

Then you need to use an ImageView in your main stage to display the snapshots returned.

Seriously, I think this method would cause the duplicate View to be several frames slower than the original's.

Title: Display Exact Copy of Stage

Body:
I am no expert but I think there are two ways to do it.

Method 1

Wrap everything of that stage into a main FXML/controller file/class (as a View). Then you need to load that FXML file twice, once in the new stage, the other in a dedicated space you have prepared in your main stage.

The reference of both controller instances should ideally be held at the same object, either in your application class or the class hosting your main stage.

From there, you can either bind values and let the binding API do the work for you.

Example:

Main View:

public class MainView {
    private Model model = new Model();
    private Pane space; // Dedicated space

    public void spawnView() {
        FXMLLoader spawnViewLoader = new FXMLLoader(getClass().getResource("View.fxml"));
        Parent spawnView = spawnViewLoader.load(); // Need to catch IOException
        ViewController spawnController = spawnViewLoader.getController();
        spawnController.setup(model);

        new Stage(new Scene(view));

        FXMLLoader dupViewLoader = new FXMLLoader(getClass().getResource("View.fxml"));
        Parent dupView = dupViewLoader.load(); // Need to catch IOException
        ViewController dupController = dupViewLoader.getController();
        dupController.setup(model);

        space.getChildren().setAll(dupView);
    }
}

Model:

public class Model {
    private final StringProperty title = new SimpleStringProperty();
    private final StringProperty titleProperty() { return title; }
    private final String getTitle() { return title.get(); }
    private final void setTitle(final String title) { this.title.set(title); }
}

View controller:

public class ViewController {
    @FXML private Label label;

    private Model model;

    public void setup(Model model) {
        if (model == null)
            throw new NullPointerException();

        this.model = model;
        label.textProperty().bind(model.titleProperty());
    }

    // Other stuff
}

Be careful of the binding though - I'm quite sure whatever I wrote is going to cause memory leak; both Views will not clean up as long you're holding a reference of model. You can always do it without binding, but it's going to be more tedious to update values.

Method 2

This method is more complex and is likely to be several frames slower. I'm not going to post sample codes as this is not that straight-forward.

You need to have a reference of the Scene of that stage, and use an AnimationTimer to call the snapshot method of the scene object.

Then you need to use an ImageView in your main stage to display the snapshots returned.

Seriously, I think this method would cause the duplicate View to be several frames slower than the original's.


问:
direction.service not displaying route between multiple points
I am looping through two loops one with active drivers and other with drivers route.

Within the second loop I am using direction.service for creating road route, I can see markers but the route is not showing.

No errors on console.

Note: the problem is after ROUTING DRIVERS section in snippet.

My code snippet is below:

```<code><script>
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    function initialize(jsondata) {

        var markers = "";

        var lat_lng = [];
        var latlngbounds = "";

        markers = JSON.parse(jsondata);
        console.log(markers);
        var mapOptions = {
            center: new google.maps.LatLng(50.7663, 15.0543),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            navigationControl: true
        };

        lat_lng = new Array();
        latlngbounds = new google.maps.LatLngBounds();
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(
                  document.getElementById("map-canvas"),
                  mapOptions);

        var value = markers.length;

        for (var i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            lat_lng.push(myLatlng);

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                icon:data.IconImage ,
                label: data.maxtime
            });

            (function (marker, data) {
                // Attaching a click event to the current marker
                google.maps.event.addListener(marker, "click", function (e) {

                    infoWindow.setContent(data.addr);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }

        //***********ROUTING DRIVERS****************//

        var pageUrl = '<%=ResolveUrl("~/WebService2.asmx")%>';

        $.ajax({
            type: "POST",
            url: pageUrl + '/GetActiveDrivers',
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function (data) {
                var markersR;
                for (var i = 0; i < JSON.parse(data.d).length; i++) {
                    var obj = JSON.parse(data.d)[i];
                    $.ajax({
                        type: "POST",
                        url: pageUrl + '/GetRouteByDriver',
                        contentType: "application/json; charset=utf-8",
                        data: "{'DriverId':'" + obj.driverId + "'}",
                        dataType: "json",
                        success: function (dataval) {
                            var infowindow = new google.maps.InfoWindow();
                            var flightPlanCoordinates = [];
                            var bounds = new google.maps.LatLngBounds();
                            console.log(JSON.parse(dataval.d))
                            for (j = 0; j < JSON.parse(dataval.d).length; j++) {
                                var objval = JSON.parse(dataval.d)[j];

                                marker = new google.maps.Marker({
                                    position: new google.maps.LatLng(objval.Lat, objval.Lng),
                                    map: map
                                });
                                flightPlanCoordinates.push(marker.getPosition());
                                bounds.extend(marker.position);

                                google.maps.event.addListener(marker, 'click', (function (marker, objval) {
                                    return function () {
                                        infowindow.setContent(objval.Time);
                                        infowindow.open(map, marker);
                                    }
                                })(marker, objval));
                            }

                            map.fitBounds(bounds);
                           // alert(flightPlanCoordinates[0]);
                            var start = flightPlanCoordinates[0];
                            var end = flightPlanCoordinates[flightPlanCoordinates.length - 1];
                            var waypts = [];
                            for (var i = 1; i < flightPlanCoordinates.length - 1; i++) {
                                waypts.push({
                                    location: flightPlanCoordinates[i],
                                    stopover: true
                                });
                            }
                            calcRoute(start, end, waypts);

                        },
                        error: function (requestObject, error, errorThrown) {
                            alert(error);
                        }

                    });

                }
            },
            error: function (requestObject, error, errorThrown) {
                alert(error);
            }

        });
     }
    function calcRoute(start, end, waypts) {
        alert(start);
        var request = {
            origin: start,
            destination: end,
            waypoints: waypts,
            optimizeWaypoints: true,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                 var route = response.routes[0];

            }
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <script type="text/javascript">

  function GetCustomers() {
   var pageUrl = '<%=ResolveUrl("~/WebService2.asmx")%>';

   $.ajax({
       type: "POST",
       url: pageUrl + '/ShowCustomers',
       contentType: "application/json; charset=utf-8",
       data: "{}",
       dataType: "json",
       success: function (data) {
           initialize(data.d);
       },
       error: function (requestObject, error, errorThrown) {
         alert(error);
       }

   });

}
    $(document).ready(function () {
        GetCustomers();
    });
   // setInterval(function () { GetCustomers(); }, 6000);
</script>

<div id = "map-canvas">
</div>
</code>```

答:
You are missing

```<code>directionsDisplay.setMap(map);
</code>```

Place it here:

```<code>  directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                directionsDisplay.setMap(map);
                 var route = response.routes[0];

            }
        });
</code>```

Body:
You are missing

directionsDisplay.setMap(map);

Place it here:

  directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                directionsDisplay.setMap(map);
                 var route = response.routes[0];

            }
        });


问:
Open Camera Instantly when view appears
I have a requirement in my app in which I need to open a camera instantly.
But when I come to that ViewController opening camera is taking time for few seconds. Can any one help me.
I have tried with queues blocks but this doesn't work.
This is the code i have tried so far :==</p>

```<code>    - (void)viewDidLoad {

            [super viewDidLoad];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
                [self onClickCamera:nil];

                //Your code goes in here
                NSLog(@"Main Thread Code");

            }];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self onClickCamera:nil];
//    });

//    dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
//    dispatch_async(queue, ^{
//        [self onClickCamera:nil];
//
//        // Do some computation here.
//
//        // Update UI after computation.
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // Update the UI on the main thread.
//        });
//    });

    }

        - (IBAction)onClickCamera:(id)sender
        {
            NSLog(@"CALeed");
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:NULL];
        }
</code>```

答:
I agree with @SandeepBhandari's answer. You can make change to the following line apart from calling the method to present camera in viewDidAppear() to reduce the delay:

Change

```<code>[self presentViewController:picker animated:YES completion:NULL];
</code>```

to

```<code>[self presentViewController:picker animated:NO completion:NULL];
</code>```

Adding more to this you can predefine your pickerController globally and set all it's properties and parameters in viewDidLoad()

```<code>- (void)viewDidLoad{

    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

}
</code>```

Also initially you can set the backgroundColour of your viewController's main view to black or similar to the colour of your launchScreen to avoid seeing that glitches when camera is presented.

You can also use CATransition to reduce time like follows

```<code>CATransition *transition = [CATransition animation];
    [transition setDuration:0];
    [transition setType:kCATransitionFromBottom];
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [picker.view.layer addAnimation:transition forKey:kCATransitionFromBottom];
</code>```

and then present the picker controller.

Well this is yet not guaranteed to give you desire results as presenting something will obviously take some fraction of time. If you have a good usage of camera in your app then i would suggest to use custom class for it and use AVCaptureVideoPreviewLayer to show the camera.

Title: Open Camera Instantly when view appears

Body:
I have a requirement in my app in which I need to open a camera instantly.
But when I come to that ViewController opening camera is taking time for few seconds. Can any one help me.
I have tried with queues blocks but this doesn't work.
This is the code i have tried so far :==

    - (void)viewDidLoad {

            [super viewDidLoad];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^ {
                [self onClickCamera:nil];

                //Your code goes in here
                NSLog(@"Main Thread Code");

            }];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self onClickCamera:nil];
//    });

//    dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
//    dispatch_async(queue, ^{
//        [self onClickCamera:nil];
//
//        // Do some computation here.
//
//        // Update UI after computation.
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // Update the UI on the main thread.
//        });
//    });

    }

        - (IBAction)onClickCamera:(id)sender
        {
            NSLog(@"CALeed");
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:NULL];
        }

Body:
I agree with @SandeepBhandari's answer. You can make change to the following line apart from calling the method to present camera in viewDidAppear() to reduce the delay:

Change

[self presentViewController:picker animated:YES completion:NULL];

to

[self presentViewController:picker animated:NO completion:NULL];

Adding more to this you can predefine your pickerController globally and set all it's properties and parameters in viewDidLoad()

- (void)viewDidLoad{

    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

}

Also initially you can set the backgroundColour of your viewController's main view to black or similar to the colour of your launchScreen to avoid seeing that glitches when camera is presented.

You can also use CATransition to reduce time like follows

CATransition *transition = [CATransition animation];
    [transition setDuration:0];
    [transition setType:kCATransitionFromBottom];
    [transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
    [picker.view.layer addAnimation:transition forKey:kCATransitionFromBottom];

and then present the picker controller.

Well this is yet not guaranteed to give you desire results as presenting something will obviously take some fraction of time. If you have a good usage of camera in your app then i would suggest to use custom class for it and use AVCaptureVideoPreviewLayer to show the camera.


问:
how can i include files for all functions in php
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

```<code>include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

in index.php

```<code>include('functions.php');
echo rows('books');
</code>```

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

```<code>function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

答:
you need to initiate a new object config inside your function and use the constructer to conect to database like this

```<code>$c=new config();
$con=$c->connect();
$req="SELECT * FROM table";
$conn=$con->query($req);
</code>```

this works if you have done a class config in config.php

Body:
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

in index.php

include('functions.php');
echo rows('books');

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

Body:
you need to initiate a new object config inside your function and use the constructer to conect to database like this

$c=new config();
$con=$c->connect();
$req="SELECT * FROM table";
$conn=$con->query($req);

this works if you have done a class config in config.php


问:
Make text hyperlink in <textarea>
I have a textarea which post plane text to  mysql db table. Now I want to add some hyper references in that text.
how can I do this?
And I don't want to use any editor.</p>

答:
Not possible, textarea is a plain text input control. You need to allow rich-text/mark-up interpreted correctly using WYSIWYG editor

textarea

The TEXTAREA element creates a multi-line text input control. User agents should use the contents of this element as the initial value of the control and should render this text initially.

Title: Make text hyperlink in <textarea>


答:
If you reflow your data into long format, the problem appears to go away.

```<code>library(tidyr)
xy <- gather(df, key = group, value = value, -DateTime)

p <- ggplot(xy, aes(DateTime, y = value, color = group)) + ylab("Val") +
  geom_line() +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))
</code>```

Title: R : How to config ggplotly displaying values on the line graph?

Body:
My plot on ggplotly shows unnecessary info while cursor pointing on the line graph.

Here is my example code :

df <- read.table(text="
                              DateTime,Val1,Val2
                 1  ,2017-07-01 09:32:00      ,401.7542   ,275.5876
                 2  ,2017-07-01 09:30:00      ,402.7049   ,359.2615
                 3  ,2017-07-01 09:29:00      ,402.5912   ,276.4372
                 4  ,2017-07-01 09:28:00      ,402.7526   ,362.6202
                 5  ,2017-07-01 09:27:00      ,402.4538   ,361.3867
                 6  ,2017-07-01 09:26:00      ,401.8847   ,359.6318
                 7  ,2017-07-01 09:25:00      ,402.2666   ,274.8941
                 8  ,2017-07-01 09:24:00      ,403.0774   ,277.4844
                 9  ,2017-07-01 09:23:00      ,403.0516   ,363.3593
                 10 ,2017-07-01 09:22:00      ,402.5764   ,275.4202
                 11 ,2017-07-01 09:21:00      ,402.2379   ,275.0550
                 12 ,2017-07-01 09:20:00      ,401.9060   ,277.2950
                 13 ,2017-07-01 09:19:00      ,401.9451   ,361.0770
                 14 ,2017-07-01 09:18:00      ,401.4484   ,361.3591
                 15 ,2017-07-01 09:17:00      ,402.5519   ,274.8206
                 16 ,2017-07-01 09:16:00      ,402.1426   ,279.2438
                 17 ,2017-07-01 09:15:00      ,402.4618   ,360.7491
                 18 ,2017-07-01 09:14:00      ,403.3124   ,276.4756
                 19 ,2017-07-01 09:13:00      ,402.3604   ,276.7015
                 20 ,2017-07-01 09:12:00      ,402.5518   ,363.2422
                 21 ,2017-07-01 09:11:00      ,404.7830   ,360.2075
                 22 ,2017-07-01 09:10:00      ,403.7317   ,275.8560
                 23 ,2017-07-01 09:09:00      ,403.2151   ,276.8633
                 24 ,2017-07-01 09:08:00      ,404.2897   ,361.6937
                 25 ,2017-07-01 09:07:00      ,403.8227   ,355.2353
                 26 ,2017-07-01 09:06:00      ,402.8998   ,276.0700
                 27 ,2017-07-01 09:05:00      ,403.1328   ,362.2495
                 28 ,2017-07-01 09:04:00      ,404.1612   ,361.9048
                 29 ,2017-07-01 09:03:00      ,403.7537   ,274.9531
                 30 ,2017-07-01 09:02:00      ,402.1621   ,360.7682
                 31 ,2017-07-01 09:01:00      ,403.0805   ,360.8172
                 32 ,2017-07-01 09:00:00      ,403.3630   ,276.2874
                 33 ,2017-07-01 08:59:00      ,402.8351   ,275.9734
                 34 ,2017-07-01 08:58:00      ,403.6484   ,360.5585
                 35 ,2017-07-01 08:57:00      ,403.4342   ,357.7776
                 36 ,2017-07-01 08:56:00      ,402.4444   ,275.8763
                 37 ,2017-07-01 08:55:00      ,403.2913   ,361.2458
                 38 ,2017-07-01 08:54:00      ,403.2985   ,276.7728
                 39 ,2017-07-01 08:53:00      ,403.2600   ,276.6644
                 40 ,2017-07-01 08:52:00      ,401.9991   ,361.2737
                 41 ,2017-07-01 08:51:00      ,404.9158   ,358.2727
                 42 ,2017-07-01 08:50:00      ,403.8922   ,357.0592
                 43 ,2017-07-01 08:49:00      ,403.0070   ,359.5312
                 44 ,2017-07-01 08:48:00      ,404.8530   ,360.1790
                 45 ,2017-07-01 08:47:00      ,404.1543   ,359.4836
                 46 ,2017-07-01 08:46:00      ,403.9200   ,357.9064
                 47 ,2017-07-01 08:45:00      ,403.9197   ,358.6364
                 48 ,2017-07-01 08:44:00      ,406.0925   ,358.6248
                 49 ,2017-07-01 08:43:00      ,401.5529   ,359.9990
                 50 ,2017-07-01 08:42:00      ,402.4422   ,356.6060",sep=",",header=TRUE,stringsAsFactors=FALSE)
df$DateTime <- as.POSIXct(df$DateTime)
library(plotly)
library(ggplot2)
library(scales)

p <- ggplot(df, aes(DateTime)) + ylab("Val") +
  geom_line(aes(y = Val1, col = "Val1"),lwd=0.5) +
  geom_line(aes(y = Val2, col = "Val2"),lwd=0.5) +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))

So how to config format displaying weekdays instead of date and hide that unnecessary line or hide both these 2 info-lines including DateTime to show only Val?

My expected output :

Thanks so much for your helps in advance.

Body:
If you reflow your data into long format, the problem appears to go away.

library(tidyr)
xy <- gather(df, key = group, value = value, -DateTime)

p <- ggplot(xy, aes(DateTime, y = value, color = group)) + ylab("Val") +
  geom_line() +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))


问:
Change position of JavaScript object key and data
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

```<code>var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]
</code>```

And want this sequence to be like this

```<code>var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];
</code>```

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

```<code> var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]
</code>```

答:
The properties in an object are not, and can not be, ordered in any way, so what you're trying to do is not possible. If you want to have a guaranteed order to the values put them in an array instead.

For those who are saying I should use array. I am getting data on basis of this object

In this case you can use Object.keys() and map() to convert the object to an array:

var data = [{
  0: "CHANCE WILLIAM C & KATHRYN L",
  1: "P O BOX 7642 CHICO CA 95927",
  2: "LOT 4 PM 150-99/100",
  3: "040-310-086-000"
}];

var arr = Object.keys(data[0]).map(function(k) {
  return data[0][k];
});
console.log(arr);```

Body:
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]

And want this sequence to be like this

var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

 var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]