问:
How to use topclient in taobao in node js
I have taken reference from few sites

node js topclient

taobao node package

node-taobao-topclient

What I did:

I installed node-taobao-topclient

My code:

```<code>TopClient = require('node-taobao-topclient');
const client  = new TopClient({
    'appkey': 'xxxx',
    'appsecret': 'xxxxx',
    'REST_URL': 'http://gw.api.taobao.com/router/rest'
});

client.execute('taobao.wlb.imports.general.consign', {
    "session" : "620260160ZZ61473fc31270a2c1f5dcc0efdff78b4c58312482635690",
    'trade_order_id':'245033103766976',
    'resource_id':'5044440108577',
    'store_code':'Tran_Store_775585',
    'first_logistics':'123',
    'first_waybillno':'123',
    'sender_id':'228',
    'cancel_id':'228'
}, function(error, response) {
    if (!error) console.log(response);
    else console.log(error);
})
</code>```

When I run above code I get error :

TypeError: TopClient is not a constructor

As I am new to node I don't how to exactly use such packages as on reference websites they are using it like:

```<code>TopClient = require('./topClient').TopClient;
</code>```

My node-taobao-topclient package looks like below:

Any guidance on how I can use this API in node would be highly appreciated.

答:
The following fragament works well:</p>

```<code>TopClient = require('node-taobao-topclient').default;
</code>```

Body:
I have taken reference from few sites

node js topclient

taobao node package

node-taobao-topclient

What I did:

I installed node-taobao-topclient

My code:

TopClient = require('node-taobao-topclient');
const client  = new TopClient({
    'appkey': 'xxxx',
    'appsecret': 'xxxxx',
    'REST_URL': 'http://gw.api.taobao.com/router/rest'
});

client.execute('taobao.wlb.imports.general.consign', {
    "session" : "620260160ZZ61473fc31270a2c1f5dcc0efdff78b4c58312482635690",
    'trade_order_id':'245033103766976',
    'resource_id':'5044440108577',
    'store_code':'Tran_Store_775585',
    'first_logistics':'123',
    'first_waybillno':'123',
    'sender_id':'228',
    'cancel_id':'228'
}, function(error, response) {
    if (!error) console.log(response);
    else console.log(error);
})

When I run above code I get error :

TypeError: TopClient is not a constructor

As I am new to node I don't how to exactly use such packages as on reference websites they are using it like:

TopClient = require('./topClient').TopClient;

My node-taobao-topclient package looks like below:

Any guidance on how I can use this API in node would be highly appreciated.

Body:
The following fragament works well:

TopClient = require('node-taobao-topclient').default;


来源: stackexchange

问:
Queuing theory for programmers?
After being burnt several times on things that seemed "obviously fast enough" but sucked performance-wise under load, I'm starting to think that my "gut feeling" might be not enough when doing capacity planning, and some theoretical background is necessary.

So - community, can you point me to good resources on applications of queuing theory to programming?

Whatever - articles, case studies, books.

I found a couple of books that seem to be relevant so far; I'd be happy to hear your opinions on them, if you're familiar:

Software Performance and Scalability: A Quantitative Approach

The Art of Computer Systems Performance Analysis: Techniques for Experimental Design, Measurement, Simulation, and Modeling

Performance by Design: Computer Capacity Planning By Example

答:
"The Art of Computer Systems Performance Analysis: ..." by Raj Jain is excellent and the Bible of software performance testing.  (But then I my be biased as I was one of it's (minor) internal reviewers).

However, if you really want to understand this stuff ("The Art..." is more of a survey of methods and principles), then the standards are:

Quantitative Systems Performance..., Lazowska, et. al.: The classic standard introduction for Capacity Planning and QNA (Queueing Network Analysis) for whole-systems performance modelling and prediction.

and

Performance Solutions: A practical guide..., Smith, etc.  Which explains SPE (Software Performance Engineering), which is really what you are trying to do.

I have found both of these to be easy to read and understand, and they are considered the standards of these two practices.

ContentLicense: CC BY-SA 2.5

Title: Queuing theory for programmers?


问:
ToLocalTime shows wrong time
I am running a website in IIS on my local PC, I save a date as UTC and call .ToLocalTime() on it in the front end mvc website. If I run the website on my local PC it outputs the correct date and time adjusted for DST. If I run it in Azure in region UK West I get 1 hour behind. This hasn't been an issue until today i.e. the clocks changed on Saturday. Do I need to raise a ticket with Azure? Or am I doing it wrong?</p>

答:
Azure App server is using  UTC time. If your site is not global just for UK. We can use the following code to get the UK local time.

```<code>DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"); //UK time zone
DateTimeOffset  time = TimeZoneInfo.ConvertTimeFromUtc(utcNow, tz);
lab_time.Text = time.DateTime.ToString(CultureInfo.InvariantCulture); //display the datetime with label.
</code>```

If your website is to be global that you may need to use javascrpt to do that, more detail please refer to another SO Thread.

ContentLicense: CC BY-SA 3.0

Title: ToLocalTime shows wrong time

Body:
Azure App server is using  UTC time. If your site is not global just for UK. We can use the following code to get the UK local time.

DateTime utcNow = DateTime.UtcNow;
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"); //UK time zone
DateTimeOffset  time = TimeZoneInfo.ConvertTimeFromUtc(utcNow, tz);
lab_time.Text = time.DateTime.ToString(CultureInfo.InvariantCulture); //display the datetime with label.

If your website is to be global that you may need to use javascrpt to do that, more detail please refer to another SO Thread.


问:
Disable pagination in Yii2 gridview
How to disable pagination in Yii2 GridView? I am not using any kartik gridview. I am using the default Yii2 Gridview.</p>

答:
Try setting pagination (in your controller) to false, like this:</p>

```<code>$dataProvider = new ActiveDataProvider([
    'query'      => SomeModelClass::find(),
    'pagination' => false,
]);
</code>```

Title: Disable pagination in Yii2 gridview

Body:
Try setting pagination (in your controller) to false, like this:

$dataProvider = new ActiveDataProvider([
    'query'      => SomeModelClass::find(),
    'pagination' => false,
]);


问:
How to stream a generated PDF file to a reader inside a DIV and not the browser?
I have the following code that after a PDF is generated submitting a query to SQL will display in browser. But I am looking is to display the file in a PDF viewer in the page and not using the browser reader. The viewer is inside a DIV. You can see the example shown in the image attached, which I run as test to show the file from the local system and not streaming. This function Response.BinaryWrite(bytes); sends the generated PDF to the browser viewer. How can I do for it to display in the viewer inside the DIV instead?

```<code>string reportLabel = lbReports.Text;

document.Add(table);
document.Close();
byte[] bytes = memoryStream.ToArray();

Response.Clear();
Response.AddHeader("Content-Disposition", "inline");

Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
</code>```

This is the code that should show the generated PDF file in the DIV:

```<code>string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ("blabla.pdf")); /*it shows this PDF as local file just for test*/
memoryStream.Close();
this.Context.ApplicationInstance.CompleteRequest();
</code>```

Image here: sample

The idea is to have the file generated temporarily and the user will decide if saving it or not. I have tried other options, but none seems to work, especially if it is inside a DIV. In other words, I am looking to display the dynamic PDF file using ltEmbed.Text = string.Format(embed, ...);

答:
I had an oppurtunity to do the same kind of task, i did in MVC

my controller Method code looks like this

```<code>        byte[] fileContent = Content;
        string base64 = Convert.ToBase64String(fileContent);
        Response.Headers.Remove("Content-Disposition");
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile.pdf");
        return File(fileContent, "applicaton/pdf");
</code>```

And my javascript is

```<code>        var iframe = document.createElement('iframe');
        iframe.frameBorder = 0;
        iframe.width = "890px";
        iframe.height = "550px";
        iframe.id = "frameForMyPdf";
        iframe.setAttribute("src", "/Home/GetPDFContent?PdfId=101");
        document.getElementById("divPdfPreviewPopup").appendChild(iframe);
</code>```

Body:
I have the following code that after a PDF is generated submitting a query to SQL will display in browser. But I am looking is to display the file in a PDF viewer in the page and not using the browser reader. The viewer is inside a DIV. You can see the example shown in the image attached, which I run as test to show the file from the local system and not streaming. This function Response.BinaryWrite(bytes); sends the generated PDF to the browser viewer. How can I do for it to display in the viewer inside the DIV instead?

string reportLabel = lbReports.Text;

document.Add(table);
document.Close();
byte[] bytes = memoryStream.ToArray();

Response.Clear();
Response.AddHeader("Content-Disposition", "inline");

Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);

This is the code that should show the generated PDF file in the DIV:

string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"698px\" height=\"450px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download Adobe PDF Reader to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ("blabla.pdf")); /*it shows this PDF as local file just for test*/
memoryStream.Close();
this.Context.ApplicationInstance.CompleteRequest();

Image here: sample

The idea is to have the file generated temporarily and the user will decide if saving it or not. I have tried other options, but none seems to work, especially if it is inside a DIV. In other words, I am looking to display the dynamic PDF file using ltEmbed.Text = string.Format(embed, ...);

Body:
I had an oppurtunity to do the same kind of task, i did in MVC

my controller Method code looks like this

        byte[] fileContent = Content;
        string base64 = Convert.ToBase64String(fileContent);
        Response.Headers.Remove("Content-Disposition");
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile.pdf");
        return File(fileContent, "applicaton/pdf");

And my javascript is

        var iframe = document.createElement('iframe');
        iframe.frameBorder = 0;
        iframe.width = "890px";
        iframe.height = "550px";
        iframe.id = "frameForMyPdf";
        iframe.setAttribute("src", "/Home/GetPDFContent?PdfId=101");
        document.getElementById("divPdfPreviewPopup").appendChild(iframe);


问:
Print human friendly Protobuf message
I couldn't find anywhere a possibility to print a human friendly content of a Google Protobuf message.

Is there an equivalent in Python for Java's toString() or C++'s DebugString()?

答:
Here's an example for read/write human friendly text file using protobuf 2.0 in python.

```<code>from google.protobuf import text_format
</code>```

read from a text file

```<code>f = open('a.txt', 'r')
address_book = addressbook_pb2.AddressBook() # replace with your own message
text_format.Parse(f.read(), address_book)
f.close()
</code>```

write to a text file

```<code>f = open('b.txt', 'w')
f.write(text_format.MessageToString(address_book))
f.close()
</code>```

The c++ equivalent is:

```<code>bool ReadProtoFromTextFile(const std::string filename, google::protobuf::Message* proto)
{
    int fd = _open(filename.c_str(), O_RDONLY);
    if (fd == -1)
        return false;

    google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd);
    bool success = google::protobuf::TextFormat::Parse(input, proto);

    delete input;
    _close(fd);
    return success;
}

bool WriteProtoToTextFile(const google::protobuf::Message& proto, const std::string filename)
{
    int fd = _open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return false;

    google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);
    bool success = google::protobuf::TextFormat::Print(proto, output);

    delete output;
    _close(fd);
    return success;
}
</code>```

Title: Print human friendly Protobuf message

Body:
Here's an example for read/write human friendly text file using protobuf 2.0 in python.

from google.protobuf import text_format

read from a text file

f = open('a.txt', 'r')
address_book = addressbook_pb2.AddressBook() # replace with your own message
text_format.Parse(f.read(), address_book)
f.close()

write to a text file

f = open('b.txt', 'w')
f.write(text_format.MessageToString(address_book))
f.close()

The c++ equivalent is:

bool ReadProtoFromTextFile(const std::string filename, google::protobuf::Message* proto)
{
    int fd = _open(filename.c_str(), O_RDONLY);
    if (fd == -1)
        return false;

    google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd);
    bool success = google::protobuf::TextFormat::Parse(input, proto);

    delete input;
    _close(fd);
    return success;
}

bool WriteProtoToTextFile(const google::protobuf::Message& proto, const std::string filename)
{
    int fd = _open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
        return false;

    google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);
    bool success = google::protobuf::TextFormat::Print(proto, output);

    delete output;
    _close(fd);
    return success;
}


问:
iPhone iOS retrieving NSMutableArray from CoreData using a function
I have a function which returns an NSMutableArray which is fetched from CoreData.

```<code>- (NSMutableArray*)getArray:(NSString*)entityName withDescriptor:(NSString*)descriptorKey {
    NSError **error = nil;
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:descriptorKey ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    return [[managedObjectContext executeFetchRequest:request error:error] mutableCopy];
}
</code>```

When i Build and Analyze my project containing this function, i get a analyzer result saying that there is a potential leak of an object allocated at line X (the line is where it returns the mutable copy)

I am calling this function like this:

```<code>myArray = [self getArray:ENTITY_PAGES withDescriptor:DEFAULT_DESCRIPTOR];
</code>```

where myArray is a NSMutableArray property of the class, ENTITY_PAGES and DEFAULT_DESCRIPTOR are NSString constants

I wish to use this function in more than one place so i can reduce the amount of redundancy in my project.

How should i populate myArray from Core Data using a function like this without getting these analyzer problems?

答:
The analyzer is complaining about a potential memory leak because your function is violating one the objective-c memory management rules:

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message.

Change the name of your function appropriately (and make sure you release the returned array at some point) and the analyzer should stop complaining.

Here is the link to the memory management guide:

http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

Body:
I have a function which returns an NSMutableArray which is fetched from CoreData.

- (NSMutableArray*)getArray:(NSString*)entityName withDescriptor:(NSString*)descriptorKey {
    NSError **error = nil;
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:descriptorKey ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    return [[managedObjectContext executeFetchRequest:request error:error] mutableCopy];
}

When i Build and Analyze my project containing this function, i get a analyzer result saying that there is a potential leak of an object allocated at line X (the line is where it returns the mutable copy)

I am calling this function like this:

myArray = [self getArray:ENTITY_PAGES withDescriptor:DEFAULT_DESCRIPTOR];

where myArray is a NSMutableArray property of the class, ENTITY_PAGES and DEFAULT_DESCRIPTOR are NSString constants

I wish to use this function in more than one place so i can reduce the amount of redundancy in my project.

How should i populate myArray from Core Data using a function like this without getting these analyzer problems?


问:
Overlay ImageView on Toolbar
I have this code for my custom toolbar:

```<code> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/new_logo"
                android:adjustViewBounds="true"
                android:padding="5dp"
                android:id="@+id/app_logo" />

        </android.support.v7.widget.Toolbar>
</code>```

Now it looks like this:

What I need to do is this one:

How will I implement that?

答:
You need to take a RelativeLayout as a root as follows :</p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/login_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary">

    </android.support.v7.widget.Toolbar>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_stripe"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:padding="5dp"
        android:id="@+id/app_logo" />

</RelativeLayout>
</code>```

Title: Overlay ImageView on Toolbar

Body:
I have this code for my custom toolbar:

 <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/login_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:src="@drawable/new_logo"
                android:adjustViewBounds="true"
                android:padding="5dp"
                android:id="@+id/app_logo" />

        </android.support.v7.widget.Toolbar>

Now it looks like this:

What I need to do is this one:

How will I implement that?

Body:
You need to take a RelativeLayout as a root as follows :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/login_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary">

    </android.support.v7.widget.Toolbar>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_stripe"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:padding="5dp"
        android:id="@+id/app_logo" />

</RelativeLayout>


问:
Ms Dynamics Integration with Azure Active Directory
I am Using ADAL libs for java to connect MS Dynamics CRM in my backend application. I registered my trial version of CRM Azure Active Direstory and I got clientID and clientsecret from there. So now I can able to connect with my crm.

But my question is If I have multiple CRM Account how should I do this.Is there any api to register the CRM in azure active directory or is there any API to do that using the CRM crendials?

Can anyone please explain me.

答:
AFAIK, the MS Dynamics CRM only support Authorization code grant flow(OAuth).

If you were developing an web app, it should works well for your scenario. Since every user could sign-in the web app and than the web app can delegate the user to integrate with MSDynamics.

More detail authentication with Microsoft Dynamics 365, you can refer the document below:

Connect to Microsoft Dynamics 365 web services using OAuth


问:
Logging messages in Hive .hql file
I have some insert statements to run in Hive. I am planning to put them in .hql file and run it through beeline -f option. Is there a way I can echo some log messages in between inserts so that I know the progress. Like :

echo "Starting the inserts ........."
   insert1

echo "Insert 1 complete"

insert2

echo "Insert script is complete"

I tried putting echo statements by using linux shell command echo as
!echo ""

But it's not recognizing echo as a command

答:
!sh echo ...

```<code>!sh echo "Starting the inserts ........."

insert ...

!sh echo "Insert 1 complete"

insert ...

!sh echo "Insert script is complete"
</code>```

Title: Logging messages in Hive .hql file

Body:
!sh echo ...

!sh echo "Starting the inserts ........."

insert ...

!sh echo "Insert 1 complete"

insert ...

!sh echo "Insert script is complete"


问:
Using jquery, how to populate my table rows with matching pictures using img src="javascript:?
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

```<code>$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="javascript:source_foto" height="80" width="80"/></div>');
        });
</code>```

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.

答:
Since you've used string concatenation it means you know it exists, but why can't you use it in the second instance?</p>

```<code>$(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="' + source_foto + '" height="80" width="80"/></div>');
</code>```

Body:
Consider I have a table, like below, that I am trying to populate with many jpegs for each row, like say BillSmith.jpg and NancyClinton.jpg.

Example Table to be populated with pics:

NY | Smith, Bill (trying to put 'BillSmith.jpg' here)

NY | Clinton, Nancy (trying to put 'NancyClinton.jpg' here)

I am confused with what to put after this part <img src="javascript: in the 2nd to last line of the below code snippet.

$("#html_table tbody td:nth-child(2)").each(function(){
        var the_name = $(this).html();

        // Creates the string of file names ( BillSmith.jpg ) matching the file names of jpeg pics

        var nameList = the_name.split(",");
        var firstLast = nameList[1] + nameList[0];
        var source_foto = "staff_jpegs/"+firstLast+".jpg";

        $(this).html( the_name +'

');
        });

The above code doesnt work because I am assuming a function not a variable can only be after javascript: .

Looking the easy way to get many fotos into their corresponding table rows using more or less this structure.

Body:
Since you've used string concatenation it means you know it exists, but why can't you use it in the second instance?

$(this).html( the_name +'<br><div class="fotos" style="text-align:center"><img src="' + source_foto + '" height="80" width="80"/></div>');


问:
How to create username and password authentication in YII2 using REST Web Services
I wish to create Web Services for each single task so that i do not replicated or rewrite code for same task for different platforms. </p>

答:
What you should do is have a REST file in your model with all the curl operations performed in it for various functions like get data and post data.After that use a object of this class to get and receive parameters if needed.

```<code>    $rest_obj = new RestService("web service URL", 'param1', 'param2');
    $rest_obj->requestName = 'webservice controller name';
    $rest_obj->requestData = '';
    $rest_obj->querydata = $data['request_params'];
    $rest_obj->requestType = "html";
    $rest_obj->responseType = "json";
    $rest_obj->getData();
    $fields_array = $rest_obj->response;
</code>```

If you do this then I think you can use this web service for n number of frontends.
Web services are basically another Yii app with connection to the database  and basically act as backend to a number of frontends.So my advice would be to create a controller and a model to fetch data from the db and connect it using the rest service I gave before and everything should work fine.

Body:
What you should do is have a REST file in your model with all the curl operations performed in it for various functions like get data and post data.After that use a object of this class to get and receive parameters if needed.

    $rest_obj = new RestService("web service URL", 'param1', 'param2');
    $rest_obj->requestName = 'webservice controller name';
    $rest_obj->requestData = '';
    $rest_obj->querydata = $data['request_params'];
    $rest_obj->requestType = "html";
    $rest_obj->responseType = "json";
    $rest_obj->getData();
    $fields_array = $rest_obj->response;

If you do this then I think you can use this web service for n number of frontends.
Web services are basically another Yii app with connection to the database  and basically act as backend to a number of frontends.So my advice would be to create a controller and a model to fetch data from the db and connect it using the rest service I gave before and everything should work fine.


问:
What is the Big-O of a nested loop, where number of iterations in the inner loop is determined by the current iteration of the outer loop?
What is the Big-O time complexity of the following nested loops:

for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
        System.out.println("i = " + i + " j = " + j);
    }
}
```

Would it be O(N^2) still?

答: AFAIL, being begun from inner loop through outer ones is adequate way for calculation of nested loop complexity.

OwnerDisplayName: Simucal

ContentLicense: CC BY-SA 4.0

Body:
What is the Big-O time complexity of the following nested loops:

for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
        System.out.println("i = " + i + " j = " + j);
    }
}

Would it be O(N^2) still?


问:
Chart.js: hiding series by clicking on legend
I'm developing a site that uses chart.js (www.chartjs.org).

I have to make a line chart that shows multiple series of data, that users can hide or show by clicking on the respective legend symbol (similar to this http://js.syncfusion.com/demos/web/#!/azure/chart/linechart).

Is there any way to do it with chartjs?

答:
This is now available in Charts.js

From the documentation http://www.chartjs.org/docs/#chart-configuration-legend-configuration

Legend Configuration

The legend configuration is passed into the options.legend namespace.
The global options for the chart legend is defined in
Chart.defaults.global.legend.

onClick   function(event, legendItem) {}  A callback that is called when a 'click' event is registered on top of a label item

onHover function(event, legendItem) {}    A callback that is
called when a 'mousemove' event is registered on top of a label item


问:
default input border shows differently on div
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

```

Why is that ? and what kind of border will give me the same one as the input ?

答:
It is actually a 2px border. If you change the background of the input, we can see the 2px border. See below with background:#f1f1f1 for the input.

<input style="background:#f1f1f1;">

```

Body:
If I create an input box without any styles (<input>) and then inspect the computed css in devtools I see it has border 2px inset rgb(238, 238, 238)

However if I create a div with the same border it looks very different:

<input>

Why is that ? and what kind of border will give me the same one as the input ?

Body:
It is actually a 2px border. If you change the background of the input, we can see the 2px border. See below with background:#f1f1f1 for the input.

<input style="background:#f1f1f1;">
<br><br>
<div style="border: 2px inset rgb(238, 238, 238); height:15px; width: 169px; "></div>


问:
How to display the name & get the id in JQuery UI Autocomplete?
[Sorry, for my Bad on English]

I would like to know, how can i get the id from array of object using JQuery UI Autocomplete.

It displays the name. But, i want to get the id when i click on submit button.

This is what i have been trying so far.

var cities = [
  {
    id: 1,
    name: "New York"
  },
  {
    id: 2,
    name: "London"
  },
  {
    id: 3,
    name: "Jakarta"
  },
  {
    id: 4,
    name: "Sidney"
  },
  {
    id: 5,
    name: "New Delhi"
  },
  {
    id: 6,
    name: "Tokyo"
  },
  {
    id: 7,
    name: "Madrid"
  }
];

var city_name = [];

for (var i = 0; i < cities.length; i++) {
  city_name.push(cities[i].name);
}

$("#autocomplete").autocomplete({
  source: city_name
});

var getResult = function() {
  var x = document.getElementById("autocomplete").value;
  document.getElementById("result").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
  The result is
  <div id="result"></div>
  <hr>
  <label for="autocomplete">Select your city address : </label>
  <input id="autocomplete">
  <input type="button" onclick="getResult()" value="Submit">
</body>
</html></code>```

Right now as you see, when i click submit button the name on the input doesn't display either in the result div.

答:
Try this:

Jquery:

```<code>$(document).ready(function(){
    var projects = [
        {
            value: "1",
            label: "jQuery"
        },
        {
            value: "2",
            label: "jQuery UI"
        },
        {
            value: "3",
            label: "Sizzle JS"
        }
    ];

    $( "#project" ).autocomplete({
        minLength: 0,
        source: projects,
        focus: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            return false;
        },
        select: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            $( "#project-id" ).val( ui.item.value );

            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<div>" + item.label + "</div>" )
        .appendTo( ul );
    };
});
</code>```

Html:

```<code><div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
</code>```

This will give you id in hidden element.

Working Fiddle

Body:
[Sorry, for my Bad on English]

I would like to know, how can i get the id from array of object using JQuery UI Autocomplete.

It displays the name. But, i want to get the id when i click on submit button.

This is what i have been trying so far.

var cities = [
  {
    id: 1,
    name: "New York"
  },
  {
    id: 2,
    name: "London"
  },
  {
    id: 3,
    name: "Jakarta"
  },
  {
    id: 4,
    name: "Sidney"
  },
  {
    id: 5,
    name: "New Delhi"
  },
  {
    id: 6,
    name: "Tokyo"
  },
  {
    id: 7,
    name: "Madrid"
  }
];

var city_name = [];

for (var i = 0; i < cities.length; i++) {
  city_name.push(cities[i].name);
}

$("#autocomplete").autocomplete({
  source: city_name
});

var getResult = function() {
  var x = document.getElementById("autocomplete").value;
  document.getElementById("result").innerHTML = x;
}

<!doctype html>

  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">

  The result is

  Select your city address :
  <input id="autocomplete">
  <input type="button" onclick="getResult()" value="Submit">

Right now as you see, when i click submit button the name on the input doesn't display either in the result div.

Body:
Try this:

Jquery:

$(document).ready(function(){
    var projects = [
        {
            value: "1",
            label: "jQuery"
        },
        {
            value: "2",
            label: "jQuery UI"
        },
        {
            value: "3",
            label: "Sizzle JS"
        }
    ];

    $( "#project" ).autocomplete({
        minLength: 0,
        source: projects,
        focus: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            return false;
        },
        select: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            $( "#project-id" ).val( ui.item.value );

            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<div>" + item.label + "</div>" )
        .appendTo( ul );
    };
});

Html:

<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">

This will give you id in hidden element.

Working Fiddle


问:
Web publishing in ASP.Net does not publishes for following file formats
I am trying to publish a web site, in which css directory includes different files for font settings.

Following are the file & extensions:

```<code> calibri-webfont.eot
 calibri-webfont.svg
 calibri-webfont.ttf
 calibri-webfont.woff
 calibri-webfont.oft
</code>```

Now when I try to publish website, it just publishes .svg file,other files I need to copy manually.
Whiles publishing following options I have checked:

Replace matching files with local copy

Only files needed to run this application.

Expected: as all those files are required, I want those to be get published automatically, than manually coping those.

How this can be achieved?

答:
file properties by right clicking, then make sure the Build Action property is set to "Content".

Works fine

Body:
I am trying to publish a web site, in which css directory includes different files for font settings.

Following are the file & extensions:

 calibri-webfont.eot
 calibri-webfont.svg
 calibri-webfont.ttf
 calibri-webfont.woff
 calibri-webfont.oft

Now when I try to publish website, it just publishes .svg file,other files I need to copy manually.
Whiles publishing following options I have checked:

Replace matching files with local copy

Only files needed to run this application.

Expected: as all those files are required, I want those to be get published automatically, than manually coping those.

How this can be achieved?


问:
How can I reference control added in ngFor?
I am adding several inputs using ngFor in a template driven form and I would like to add corresponding error messages for when the inputs are invalid.  Normally if I was not using ngFor I would use #inputName="ngModel".  Is there any way for me to do something like this in order to reference the dynamically added input?

Basically I want to do something like this:

```<code><div *ngFor="let field of fields; let i = index">
        <label>{{field.label}}</label> <input [ngModel]="field.value" required #field{{i}}="ngModel" />
        <div *ngIf="field{{i}}.invalid"> This field is required </div>
</div>
</code>```

答:
garth74's answer is almost correct. In forms, the name attribute has to be unique, so that in your case, each input field is recognized as a separate form control. So here use the index to assign the unique name:

name="f{{i}}"
```

<p>... so your code would then look like this:</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let field of fields; let i = index">
  <label>{{field.label}}</label> <input name="f{{i}}" [ngModel]="field.value" required #f="ngModel" />
  <div *ngIf="f.invalid"> This field is required </div>
</div>
</code>```

Here's a

DEMO

Body:
I am adding several inputs using ngFor in a template driven form and I would like to add corresponding error messages for when the inputs are invalid.  Normally if I was not using ngFor I would use #inputName="ngModel".  Is there any way for me to do something like this in order to reference the dynamically added input?

Basically I want to do something like this:

        {{field.label}} <input [ngModel]="field.value" required #field{{i}}="ngModel" />

 This field is required

Body:
garth74's answer is almost correct. In forms, the name attribute has to be unique, so that in your case, each input field is recognized as a separate form control. So here use the index to assign the unique name:

name="f{{i}}"

... so your code would then look like this:

<div *ngFor="let field of fields; let i = index">
  <label>{{field.label}}</label> <input name="f{{i}}" [ngModel]="field.value" required #f="ngModel" />
  <div *ngIf="f.invalid"> This field is required </div>
</div>

Here's a

DEMO


问:
Edge Extension: Need to share credentials with a WPF
I have a WPF app that stores credentials in a local file. I need to be able to access this file from an Edge extension or to somehow communicate the credentials from the WPF to the Edge extension. Can an Edge extension use the File API or is there something similar to Native Messaging for WPF that would allow me to communicate with the Edge extension?</p>

答:
As of builds 15002 and above (only available to Windows Insiders currently), Microsoft Edge supports native messaging to UWAs: https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/native-messaging

If you want to communicate with a WPFapp, you'll need to use the Desktop Bridge to convert it to a UWA before continuing.

If you need to sign up for the Windows Insider Program, you can do so here: https://insider.windows.com. Native messaging will also be available in the Windows 10 Creators Update once it's released publicly!


问:
Function pointer as member of struct in C Invalid initializer
this is my first time posting on here, so please correct me if I'm doing anything wrong.
Ok, so I was given the following struct,function, and main:

```<code>typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;`
</code>```

and

```<code>void big50Print(Integer50 *p)        //Unfortunately, I haven't made it to
{                                    //this part yet.  But once i get the
int i;                               //other function working, this should
if (p == NULL)                      //work fine, as it was given.
{
    printf("(null pointer)\n");
    return;
}
for (i = MAX50 - 1; i >= 0; i--)
    printf("%d", p->digits[i]);
printf("\n");
}
</code>```

and

```<code>int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}
</code>```

And my goal is to create a function that parses the string into an array of integers, backwards, and returns a pointer to the newly allocated Integer50 struct, NULL if memory allocation fails, or if the input str is NULL.  So far, I have this:

```<code>Integer50 *parseString(char *str)   //This is the only one I can edit!
{
int len, i;
Integer50 *a[50]=malloc(sizeof(Integer50)); //this line is most likely wrong
                                            //And where the 'Invalid Initializer'
 len =strlen(str);                          //error is occuring

for (i=0; i<len; i++)            //This part works perfectly and
{                                //converts the string into integers
  a[i]= str[len-1-i]-'0';        //like it should.  The print statement here
 printf("a[%d]= %d, ", i, a[i]); //was just a test to make sure it worked.
}
 a->digits;               //also this line is probably wrong
    printf("\n");
 return a;
}
</code>```

Unfortunately, I'm not very good with pointers yet and this proving to be quite difficult.  If anyone could clear up where I'm going wrong, it'd be greatly appreciated.  Thank you!

答:
Here's your corrected code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX50 50

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

void big50Print(Integer50 *p)        //Unfortunately, I haven't made it to
{                                    //this part yet.  But once i get the
int i;                               //other function working, this should
if (p == NULL)                      //work fine, as it was given.
{
    printf("(null pointer)\n");
    return;
}
for (i = MAX50 - 1; i >= 0; i--)
    printf("%d", p->digits[i]);
printf("\n");
}

Integer50 *parseString(char *str)   //This is the only one I can edit!
{
int len, i;
Integer50 *a =malloc(sizeof(Integer50)); //edited
a->digits = malloc(50 * sizeof(int));     //edited
 len =strlen(str);

for (i=0; i<len; i++)            //This part works perfectly and
{                                //converts the string into integers
  a->digits[i]= str[len-1-i]-'0';        //edited
 printf("a[%d]= %d, ", i, a->digits[i]); //edited
}
 a->digits;               //also this line is probably wrong
  printf("\n");
 return a;
}

int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}
</code>```

The changes are

```<code>Integer50 *a[50]=malloc(sizeof(Integer50));
</code>```

to

```<code>Integer50 *a =malloc(sizeof(Integer50));
</code>```

because you don't want an array of Integer50s, you want an array of ints inside ONE Integer50.

so we add after this line

```<code>a->digits = malloc(50 * sizeof(int));
</code>```

Similarly

```<code>a->digits[i]= str[len-1-i]-'0';
</code>```

The other change is in the printf line

```<code>printf("%d", p->digits[i]);
</code>```

The previous line will output gibberish. This will output the actual data you store int the int * digits.
Also remember to free the allocated memory from the heap using the free() function.
Hope that helps!

Body:
this is my first time posting on here, so please correct me if I'm doing anything wrong.
Ok, so I was given the following struct,function, and main:

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;`

and

void big50Print(Integer50 *p)        //Unfortunately, I haven't made it to
{                                    //this part yet.  But once i get the
int i;                               //other function working, this should
if (p == NULL)                      //work fine, as it was given.
{
    printf("(null pointer)\n");
    return;
}
for (i = MAX50 - 1; i >= 0; i--)
    printf("%d", p->digits[i]);
printf("\n");
}

and

int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}

And my goal is to create a function that parses the string into an array of integers, backwards, and returns a pointer to the newly allocated Integer50 struct, NULL if memory allocation fails, or if the input str is NULL.  So far, I have this:

Integer50 *parseString(char *str)   //This is the only one I can edit!
{
int len, i;
Integer50 *a[50]=malloc(sizeof(Integer50)); //this line is most likely wrong
                                            //And where the 'Invalid Initializer'
 len =strlen(str);                          //error is occuring

for (i=0; i<len; i++)            //This part works perfectly and
{                                //converts the string into integers
  a[i]= str[len-1-i]-'0';        //like it should.  The print statement here
 printf("a[%d]= %d, ", i, a[i]); //was just a test to make sure it worked.
}
 a->digits;               //also this line is probably wrong
    printf("\n");
 return a;
}

Unfortunately, I'm not very good with pointers yet and this proving to be quite difficult.  If anyone could clear up where I'm going wrong, it'd be greatly appreciated.  Thank you!

Body:
Here's your corrected code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX50 50

typedef struct Integer50
{
// a dynamically allocated array to hold a 50
// digit integer, stored in reverse order
int *digits;
} Integer50;

void big50Print(Integer50 *p)        //Unfortunately, I haven't made it to
{                                    //this part yet.  But once i get the
int i;                               //other function working, this should
if (p == NULL)                      //work fine, as it was given.
{
    printf("(null pointer)\n");
    return;
}
for (i = MAX50 - 1; i >= 0; i--)
    printf("%d", p->digits[i]);
printf("\n");
}

Integer50 *parseString(char *str)   //This is the only one I can edit!
{
int len, i;
Integer50 *a =malloc(sizeof(Integer50)); //edited
a->digits = malloc(50 * sizeof(int));     //edited
 len =strlen(str);

for (i=0; i<len; i++)            //This part works perfectly and
{                                //converts the string into integers
  a->digits[i]= str[len-1-i]-'0';        //edited
 printf("a[%d]= %d, ", i, a->digits[i]); //edited
}
 a->digits;               //also this line is probably wrong
  printf("\n");
 return a;
}

int main(void)
{
Integer50 *p;
big50Print(p = parseString("01234567890123456789012345678901234567890123456789"));
return 0;
}

The changes are

Integer50 *a[50]=malloc(sizeof(Integer50));

to

Integer50 *a =malloc(sizeof(Integer50));

because you don't want an array of Integer50s, you want an array of ints inside ONE Integer50.

so we add after this line

a->digits = malloc(50 * sizeof(int));

Similarly

a->digits[i]= str[len-1-i]-'0';

The other change is in the printf line

printf("%d", p->digits[i]);

The previous line will output gibberish. This will output the actual data you store int the int * digits.
Also remember to free the allocated memory from the heap using the free() function.
Hope that helps!


问:
Best service/connection combo for Flex/Server Implementation
I'm starting a Flex app on a pretty big reporting engine and want to know how best to connect to a Postgres Database.  I'd like to create a REST API architecture so I can use the service for more than just the Flex app(mobile possibly).

These are my options I've found:

Datatype: either XML, JSON or AMF

Flex Service: HTTPService or WebService

Server(using PHP): ZendAMF, custom json_encode implementation, Zend_Rest_Server

I've got my views all mapped out, and the api functions designed.  Basically what I need is advice on which Flex / back-end service combo to provide.

Thanks for the advice!

答:
[I] want to know how best to connect to a
  Postgres Database.

Best is very subjective.  You probably don't want to connect to the Postgres database directly from Flex.  Flex is not designed for such things.  I recommend using an application server as middleware.  ColdFusion, .NET, PHP, Java, and just about any other 'current' application server can be used as that middleware.  I would recommend using whatever you (or your team) is familiar with.

For Flex, I strongly recommend you using an AMF implementation.  AMF is a binary format and will give you smaller data transfer packets, plus server side object to client side object conversion.  It'll save you some time writing XML parsing routines, which can be annoying at times.

With ColdFusion, it is pretty easy to create a server side service (CFC) that can be used for AMF, SOAP Web Services, and REST services all at the same time.  You just specify 'access="remote"' on the function definition.  I would expect other server side languages have similar functionality, but never investigated the web service related features of other languages.


问:
MeteorJS setting a different mongodb url to run locally on windows
I am trying to run my mlab mongoDB locally on my computer from MeteorJS, so that when my Meteor code runs and gets put on localhost:3000, I look into the mLab mongoDB collections rather than local collections. I try to set the new mongo url like this on the command prompt:

```<code>set MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing
</code>```

After doing this and running meteor, however, I don't appear to access the mlab collections. Am I doing something wrong?

答:
when i run locally i use this.

```<code>export MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing
</code>```

it works for me. hope it will work for you also.

Body:
I am trying to run my mlab mongoDB locally on my computer from MeteorJS, so that when my Meteor code runs and gets put on localhost:3000, I look into the mLab mongoDB collections rather than local collections. I try to set the new mongo url like this on the command prompt:

set MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing

After doing this and running meteor, however, I don't appear to access the mlab collections. Am I doing something wrong?

Body:
when i run locally i use this.

export MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing

it works for me. hope it will work for you also.


问:
What C datatype should be used for an array which will contain 2-digit HEXADECIMAL values?
I have the following array in a program I am trying to debug:

```<code>static u8 info3[LEN] = {
  06,
  07,
  04,
  00,
  00,
  01,
  00,
  0e,
  03
};
</code>```

and I am getting the following error:

```<code>test.c(45): error C2021: expected exponent value, not ','
</code>```

and line#45 is the line containing 0e,. According to this MSDN resource,

expected exponent value, not 'character'

The character used as the exponent of a floating-point constant is not
  a valid number. Be sure to use an exponent that is in range.

This tells me that the compiler thinks that the compiler thinks that info3 contains Floating Point values. But the values there are actually 2-digit hexadecimal numbers.

So the question is that which datatype should be used here for the values stored in this array?

答:
You should add 0x at these numbers.
For example, 0x01, 0x0e, or the compiler won't treat them as hexadecimal.

And the reason it expect exponent value after e is because you can use scientific notation in C, for example float var = 1.54334E-34.

Body:
I have the following array in a program I am trying to debug:

static u8 info3[LEN] = {
  06,
  07,
  04,
  00,
  00,
  01,
  00,
  0e,
  03
};

and I am getting the following error:

test.c(45): error C2021: expected exponent value, not ','

and line#45 is the line containing 0e,. According to this MSDN resource,

expected exponent value, not 'character'

The character used as the exponent of a floating-point constant is not
  a valid number. Be sure to use an exponent that is in range.

This tells me that the compiler thinks that the compiler thinks that info3 contains Floating Point values. But the values there are actually 2-digit hexadecimal numbers.

So the question is that which datatype should be used here for the values stored in this array?


问:
Sending order to print from android
I have one problem in android. I have one hotel ordering system app and I am using sql server database for that. When I am giving order from my app it gets max orderid from database and print is generated, but when I have multiple device and giving order from that at a time at that time it getting same order id for all three devices, and order is printing in one print not a different print. It happens because of same order id is inserted. So please help me</p>

答:
you have to make orderid unique and also auto increment.
when you insert the row in database orderid is autometically generated. you not need to insert it and after row is inserted then get orderid from the db for inserted row user </p>

Title: Sending order to print from android


问:
Using a toString method to print out adjusted variables
I have a very basic class here that I'm trying to use my first toString() method on.

```<code> public class Shoes
{
   private String style;
   private String color;
   private double size;

   public Shoes()
   {
      this.style = " ";
      this.color = " ";
      this.size = 0;

   }

   public Shoes(String newStyle, String newColor, double newSize)
   {
      this.style = newStyle;
      this.color = newColor;
      this.size = newSize;

      System.out.println(this);

   }

   public String getStyle()
   {
      return style;
   }

   public void setStyle(String newStyle)
   {
      style = newStyle;
   }

   public String getColor()
   {
      return color;
   }

   public void setColor(String newColor)
   {

      color = newColor;
   }

   public double getSize()
   {
      return size;
   }

   public void setSize(double newSize)
   {
      size = newSize;
   }

   public String toString()
   {
      String myEol = System.getProperty("line.separator");
      return new String("Style: " + style + myEol + "Color: " + color + myEol + "Size: " + size);

   }

}
</code>```

I'm trying to have it so that in my main class it will print out the variables data as it changes. Right now I only know how to call it inside of an overloaded constructor, but how would I print it AFTER the data has been changed from its initialized value?

Example of the main class, as you can see I'm using a default and overloaded.

```<code>public class ShoeStore
{
   public static void main(String[] args)
   {

      Shoes nerdShoes = new Shoes();
      Shoes coolShoes = new Shoes("Sandals", "Brown", 8.5);

      nerdShoes.setColor("Tan");
      nerdShoes.setStyle("Walking");
      nerdShoes.setSize(9.5);

      System.out.println("The style of nerdShoes: " + nerdShoes.getStyle());

      coolShoes.setColor("Purple");

      System.out.println("The style of coolShoes: " + coolShoes.getStyle());

   }
}
</code>```

What I've done to Fix It

```<code>public String toString()
   {
      String myEol = System.getProperty("line.separator");
      return new String("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());

   }
</code>```

Instead of calling the variable itself I just called the function! I don't know how I missed that. Now it's printing properly!

答:
once you change the variable with one of your set methods it should automatically assign that to one of your member variables(fields). when you print out the object your toString() method should automatically be called since it overrides the default toString().

```<code>System.out.println(nerdShoes);
</code>```

this will print out

```<code>//toString() method
("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());
</code>```

Body:
I have a very basic class here that I'm trying to use my first toString() method on.

 public class Shoes
{
   private String style;
   private String color;
   private double size;

   public Shoes()
   {
      this.style = " ";
      this.color = " ";
      this.size = 0;

   }

   public Shoes(String newStyle, String newColor, double newSize)
   {
      this.style = newStyle;
      this.color = newColor;
      this.size = newSize;

      System.out.println(this);

   }

   public String getStyle()
   {
      return style;
   }

   public void setStyle(String newStyle)
   {
      style = newStyle;
   }

   public String getColor()
   {
      return color;
   }

   public void setColor(String newColor)
   {

      color = newColor;
   }

   public double getSize()
   {
      return size;
   }

   public void setSize(double newSize)
   {
      size = newSize;
   }

   public String toString()
   {
      String myEol = System.getProperty("line.separator");
      return new String("Style: " + style + myEol + "Color: " + color + myEol + "Size: " + size);

   }

}

I'm trying to have it so that in my main class it will print out the variables data as it changes. Right now I only know how to call it inside of an overloaded constructor, but how would I print it AFTER the data has been changed from its initialized value?

Example of the main class, as you can see I'm using a default and overloaded.

public class ShoeStore
{
   public static void main(String[] args)
   {

      Shoes nerdShoes = new Shoes();
      Shoes coolShoes = new Shoes("Sandals", "Brown", 8.5);

      nerdShoes.setColor("Tan");
      nerdShoes.setStyle("Walking");
      nerdShoes.setSize(9.5);

      System.out.println("The style of nerdShoes: " + nerdShoes.getStyle());

      coolShoes.setColor("Purple");

      System.out.println("The style of coolShoes: " + coolShoes.getStyle());

   }
}

What I've done to Fix It

public String toString()
   {
      String myEol = System.getProperty("line.separator");
      return new String("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());

   }

Instead of calling the variable itself I just called the function! I don't know how I missed that. Now it's printing properly!

Body:
once you change the variable with one of your set methods it should automatically assign that to one of your member variables(fields). when you print out the object your toString() method should automatically be called since it overrides the default toString().

System.out.println(nerdShoes);

this will print out

//toString() method
("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());


问:
KeyError in append dict
I have large peace of data, iterate true this in loop and append values by key:

```<code>for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']),
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})
</code>```

Sometimes i got : KeyError: 'roomsCount' or KeyError: 'totalArea' etc. if key doesn't exist.

How i can set default value for any key in case if this key not exist? Without repeat try: except for each of my key:value pairs

答:
How i can set default value for any key in case if this key not exist?

The dict.setdefault() method is likely what you want here:

```<code>d = {'hits': 10, 'gold': 5}
print( d.setdefault('weapons', 0) )
print( d.setdefault('hits', 10) )
</code>```

Title: KeyError in append dict

Body:
I have large peace of data, iterate true this in loop and append values by key:

for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']),
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})

Sometimes i got : KeyError: 'roomsCount' or KeyError: 'totalArea' etc. if key doesn't exist.

How i can set default value for any key in case if this key not exist? Without repeat try: except for each of my key:value pairs

Body:
How i can set default value for any key in case if this key not exist?

The dict.setdefault() method is likely what you want here:

d = {'hits': 10, 'gold': 5}
print( d.setdefault('weapons', 0) )
print( d.setdefault('hits', 10) )


问:
LISP very simple list question
Im learning lisp and im pretty new at this so i was wondering...

if i do this:

```<code>(defparameter *list-1* (list 1 2))
(defparameter *list-2* (list 2 3))
(defparameter *list-3* (append *list-1* *list-2*))
</code>```

And then

```<code>(setf (first *list-2*) 1)
*list-3*
</code>```

I will get (1 2 1 4)

I know this is because the append is going to "save resources" and create a new list for the first chunk, but will actually just point to the second chunk, coz if i do:

```<code>(setf (first *list-1*) 0)
*list-3*
</code>```

I will get (1 2 1 4) instade of the more logical (0 2 1 4)

So my question is, what other cases are like this in lisp, how do you black belt lispers know how to deal with this stuff that is not intuitive or consistent?

答:
So my question is, what other cases are like this in lisp, how do you black belt lispers know how to deal with this stuff that is not intuitive or consistent?

By reading the fine manual?  Hyperpsec explicitly states:

[...] the list structure of each of lists except the last is copied.  The last argument is not copied; it becomes the cdr of the final dotted pair of the concatenation of the preceding lists, or is returned directly if there are no preceding non-empty lists.

OwnerDisplayName: DFectuoso

Title: LISP very simple list question

Body:
Im learning lisp and im pretty new at this so i was wondering...

if i do this:

(defparameter *list-1* (list 1 2))
(defparameter *list-2* (list 2 3))
(defparameter *list-3* (append *list-1* *list-2*))

And then

(setf (first *list-2*) 1)
*list-3*

I will get (1 2 1 4)

I know this is because the append is going to "save resources" and create a new list for the first chunk, but will actually just point to the second chunk, coz if i do:

(setf (first *list-1*) 0)
*list-3*

I will get (1 2 1 4) instade of the more logical (0 2 1 4)

So my question is, what other cases are like this in lisp, how do you black belt lispers know how to deal with this stuff that is not intuitive or consistent?

OwnerDisplayName: huaiyuan


问:
Replace multiple different images on one PDF template page with itext (itextsharp)
We have an ASP.NET application that users use to generate certain reports. So far we had one PDF template that had one image on it, and we would just replace that image with our programatically generated one (graph).

We have used code from this site for that:http://blog.rubypdf.com/2007/12/12/how-to-replace-images-in-a-pdf/

Problem now is that we have two different images on one PDF page, and the code from link above selects both images on one page and replaces them all at once with our generated image.

Does anyone have any idea how to replace multiple different images on one page with itext?

Thanks

答:
Ugh.  First, let me rewrite some of that source.

```<code>PdfReader pdf = new PdfReader("in.pdf");
PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("c:\\out.pdf"));
PdfWriter writer = stp.getWriter();
Image img = Image.getInstance("image.png");
PdfDictionary pg = pdf.getPageN(1);
PdfDictionary res = pg.getAsDict.get(PdfName.RESOURCES);
PdfDictionary xobj = res.getAsDict(PdfName.XOBJECT);
if (xobj != null) {
  for (Iterator<PdfName> it = xobj.getKeys().iterator(); it.hasNext(); ) {
    PdfObject obj = xobj.get(it.next());
    if (obj.isIndirect()) {
      PdfDictionary tg = (PdfDictionary)PdfReader.getPdfObject(obj);
      PdfName type = tg.getAsName(PdfName.SUBTYPE));
      if (PdfName.IMAGE.equals(type)) {
        PdfReader.killIndirect(obj);
        Image maskImage = img.getImageMask();
        if (maskImage != null)
          writer.addDirectImageSimple(maskImage);
        writer.addDirectImageSimple(img, (PRIndirectReference)obj);
        break;
      }
    }
  }
}
</code>```

Whew.  the getAs functions can save you quite a bit of knuckle-grease and make your code much clearer.

Now.  You need to be able to differentiate between the various images.  If you're willing to hard-code things, you could find out what the resource names are and go that route:

```<code>String imageResName[] = {"Img1", "Img2" ... };
Image img[] = {Image.getInstance("foo.png"), Image.getInstance("bar.png"), ... };
for (int i = 0; i < imageResName.length; ++i) {
  PdfName curKey = new PdfName(imageResName[i]);
  PdfIndirectReference ref = xobj.getAsIndirect(curKey);
  PdfReader.killIndirect( ref );
  Image maskImage = img[i].getImageMask();
  if (maskImage != null) {
    writer.addDirectImageSimple(maskImage);
  }
  writer.addDirectImageSimple(img[i], (PRIndirectReference)ref);
}
</code>```

If you're not willing to go with hardcoded resource names (and no one would fault you, quite the opposite, particularly when the order they appear (and thus the number on the end) depends on their order in a hash map... [shudder]), you may be able to differentiate based on image width and height.

```<code>//keep the original for loop, stepping through resource names
if (PdfName.IMAGE.equals(type)) {
  float width = tg.getAsNumber(PdfName.WIDTH).floatValue();
  float height = tg.getAsNumber(PdfName.HEIGHT).floatValue();

  Image img = getImageFromDimensions(width, height);

  Image maskImage = img.getImageMask();
  ...
}
</code>```

Body:
Ugh.  First, let me rewrite some of that source.

PdfReader pdf = new PdfReader("in.pdf");
PdfStamper stp = new PdfStamper(pdf, new FileOutputStream("c:\\out.pdf"));
PdfWriter writer = stp.getWriter();
Image img = Image.getInstance("image.png");
PdfDictionary pg = pdf.getPageN(1);
PdfDictionary res = pg.getAsDict.get(PdfName.RESOURCES);
PdfDictionary xobj = res.getAsDict(PdfName.XOBJECT);
if (xobj != null) {
  for (Iterator<PdfName> it = xobj.getKeys().iterator(); it.hasNext(); ) {
    PdfObject obj = xobj.get(it.next());
    if (obj.isIndirect()) {
      PdfDictionary tg = (PdfDictionary)PdfReader.getPdfObject(obj);
      PdfName type = tg.getAsName(PdfName.SUBTYPE));
      if (PdfName.IMAGE.equals(type)) {
        PdfReader.killIndirect(obj);
        Image maskImage = img.getImageMask();
        if (maskImage != null)
          writer.addDirectImageSimple(maskImage);
        writer.addDirectImageSimple(img, (PRIndirectReference)obj);
        break;
      }
    }
  }
}

Whew.  the getAs functions can save you quite a bit of knuckle-grease and make your code much clearer.

Now.  You need to be able to differentiate between the various images.  If you're willing to hard-code things, you could find out what the resource names are and go that route:

String imageResName[] = {"Img1", "Img2" ... };
Image img[] = {Image.getInstance("foo.png"), Image.getInstance("bar.png"), ... };
for (int i = 0; i < imageResName.length; ++i) {
  PdfName curKey = new PdfName(imageResName[i]);
  PdfIndirectReference ref = xobj.getAsIndirect(curKey);
  PdfReader.killIndirect( ref );
  Image maskImage = img[i].getImageMask();
  if (maskImage != null) {
    writer.addDirectImageSimple(maskImage);
  }
  writer.addDirectImageSimple(img[i], (PRIndirectReference)ref);
}

If you're not willing to go with hardcoded resource names (and no one would fault you, quite the opposite, particularly when the order they appear (and thus the number on the end) depends on their order in a hash map... [shudder]), you may be able to differentiate based on image width and height.

//keep the original for loop, stepping through resource names
if (PdfName.IMAGE.equals(type)) {
  float width = tg.getAsNumber(PdfName.WIDTH).floatValue();
  float height = tg.getAsNumber(PdfName.HEIGHT).floatValue();

  Image img = getImageFromDimensions(width, height);

  Image maskImage = img.getImageMask();
  ...
}


问:
Transposing the list based on property names in C#
I have a class with the following properties

```<code>    public class Curve
    {
        public string CurveName { get; set; }

        public string RefSource { get; set; }
        public int price1 { get; set; }
        public int price2 { get; set; }
        public int price3 { get; set; }

        public static List<Curve> GetCurveList()
        {
            List<Curve> data = new List<Curve>()
            {
                new Curve() { CurveName="Lamar", price1 = 1, price2 = 101,price3=104,RefSource="Tome" },
                new Curve() { CurveName="Lamar", price1 = 2, price2 = 201,price3=204,RefSource="Richard" }
    }
</code>```

I need it to get transformed in another list as following properties

```<code>curveName=lamar,refSource=richard ,hour=(name of the property of price1, price2,price3)taking integer of the last part of the enclosed property,value associated with the price property

curveName=lamar,refSource=Tom,hour=(name of the property of price1, price2,price3)taking integer of the last part of the enclosed property,value associated with the price property
</code>```

basically the two items of the source list should result into a new list of 6 rows based on the refsource and each property captioned as price and it need to look like below

```
Name    RefSource   Hour    Value
lamar   tom        1           1
lamar   tom        2         101
lamar   tom        3         104
lamar   richard    1          2
lamar   richard    2         201
lamar   richard    3         204
```

The hour column is suffix of property name Price1, price2, price3 in the source list.

答:
Try this:

```<code>var query =
    from curve in Curve.GetCurveList()
    from result in new []
    {
        new { curve.CurveName, curve.RefSource, Hour = 1, Value = curve.price1 },
        new { curve.CurveName, curve.RefSource, Hour = 2, Value = curve.price2 },
        new { curve.CurveName, curve.RefSource, Hour = 3, Value = curve.price3 },
    }
    select result;
</code>```

That gives me:

Body:
I have a class with the following properties

    public class Curve
    {
        public string CurveName { get; set; }

        public string RefSource { get; set; }
        public int price1 { get; set; }
        public int price2 { get; set; }
        public int price3 { get; set; }

        public static List<Curve> GetCurveList()
        {
            List<Curve> data = new List<Curve>()
            {
                new Curve() { CurveName="Lamar", price1 = 1, price2 = 101,price3=104,RefSource="Tome" },
                new Curve() { CurveName="Lamar", price1 = 2, price2 = 201,price3=204,RefSource="Richard" }
    }

I need it to get transformed in another list as following properties

curveName=lamar,refSource=richard ,hour=(name of the property of price1, price2,price3)taking integer of the last part of the enclosed property,value associated with the price property

curveName=lamar,refSource=Tom,hour=(name of the property of price1, price2,price3)taking integer of the last part of the enclosed property,value associated with the price property

basically the two items of the source list should result into a new list of 6 rows based on the refsource and each property captioned as price and it need to look like below

Name    RefSource   Hour    Value
lamar   tom        1           1
lamar   tom        2         101
lamar   tom        3         104
lamar   richard    1          2
lamar   richard    2         201
lamar   richard    3         204

The hour column is suffix of property name Price1, price2, price3 in the source list.

Body:
Try this:

var query =
    from curve in Curve.GetCurveList()
    from result in new []
    {
        new { curve.CurveName, curve.RefSource, Hour = 1, Value = curve.price1 },
        new { curve.CurveName, curve.RefSource, Hour = 2, Value = curve.price2 },
        new { curve.CurveName, curve.RefSource, Hour = 3, Value = curve.price3 },
    }
    select result;

That gives me:


问:
How to remove repeated foreach values in jquery
I am working now wordpress this is my code

```<code>jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>
</code>```

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

```<code>53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
</code>```

But i want out put

```<code> 53.95
39.95
29.95
27.95
</code>```

this only.please help me.

答:
```<code>use array_unique() function of php that avoid duplicate entries.

answer 2.

jQuery(document).ready(function () {
<?php
$var= $product->get_available_variations();
$arr = array();
 foreach ($var as $key => $test)
{
if(!in_array($test['display_price'],$arr))
{
  $check=$test['display_price'];
?>
 var check='<?php echo $check;?>';

 jQuery('<p>'+check+'</p>').appendTo('.variation_buttons_wrapper');

 <?php

 $arr[]=$test['display_price'];
}
}
 ?>

this will help.
</code>```

Body:
I am working now wordpress this is my code

jQuery(document).ready(function () {

 <?php
 $var= $product->get_available_variations();
 foreach ($var as $key => $test)
 {

$check=$test['display_price'];
 ?>
 var check='<?php echo $check;?>';

 jQuery('
'+check+'
').appendTo('.variation_buttons_wrapper');

 <?php
 }
 ?>

Actually my task is split foreach values and append another div.But my answer is again and again repeated.My out put is there,

53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95
53.95
39.95
29.95
27.95

But i want out put

 53.95
39.95
29.95
27.95

this only.please help me.


问:
Free AspectJ code samples for the web
I am a newbie to AspectJ and to learn it I am trying to search for some open-source simple applications that use AspectJ for the web but I am unable to retrieve any. I am trying to build a filter through this technology but I am not able to find any working examples that are suited in particular to Eclipse/Tomcat. </p>

答: You can get (many variations) of a simple e-commerce application built using Spring+AspectJ from http://manning.com/laddad2 (click on "Source Code" link).</p>

Title: Free AspectJ code samples for the web


问:
Replace
 tag with
 tag using php
```<code><div style = "text-align:left;" class="ref"> Text </div>
</code>```

I want to replace
 with
 without losing attributes.

Any help is appreciated.

答:
Try This:

```<code>$str = '<div style = "text-align:left;" class="ref"> Text </div>';

$newstr = preg_replace('/<div [^<]*?class="([^<]*?ref.*?)">(.*?)<\/div>/','<p class="$1">$2</p>',$str);

echo $newstr;
</code>```

Output :
 Text

Title: Replace <div> tag with <p> tag using php

Body:
 Text

I want to replace
 with
 without losing attributes.

Any help is appreciated.

Body:
Try This:

$str = '<div style = "text-align:left;" class="ref"> Text </div>';

$newstr = preg_replace('/<div [^<]*?class="([^<]*?ref.*?)">(.*?)<\/div>/','<p class="$1">$2</p>',$str);

echo $newstr;

Output : <p class="ref"> Text </p>


答:
To write hexadecimal numbers in C, you write 0x followed by hex digits. So two-digit hex numbers in C would look like

```<code>0x6a
0x0e
0xff
0x29
0xbc
</code>```

When you write 0e the compiler complains because an e in that position indicates "times 10 to the". For example

35e22

means 35 times 10 to the 22 power and

1e9

is one billion (one times ten to the 9th power).

If you write

```<code>0e
</code>```

It looks like zero times ten to the........  and the compiler complains because you did not give the exponent.

Title: What C datatype should be used for an array which will contain 2-digit HEXADECIMAL values?

Body:
To write hexadecimal numbers in C, you write 0x followed by hex digits. So two-digit hex numbers in C would look like

0x6a
0x0e
0xff
0x29
0xbc

When you write 0e the compiler complains because an e in that position indicates "times 10 to the". For example

35e22

means 35 times 10 to the 22 power and

1e9

is one billion (one times ten to the 9th power).

If you write

0e

It looks like zero times ten to the........  and the compiler complains because you did not give the exponent.


问:
Why protected members can be overridden by public members in TypeScript?
I am new to Typescript, and I tried to played around a little with TypeScript in this playground. I noticed that in TypeScript, a protected member in base class can be overridden by public members:

```<code>class Base {
    protected name: string = '!'
}

class Derived extends Base{
    public name: string = '?'
}
</code>```

On the one hand, this makes sense to me since the Liskov Substitution Principle still holds: base class has stricter requirements than derived class. But on the other hand, I noticed that private member cannot be overridden by protected or public one, which seems inconsistent to me:

```<code>class Base {
    private name: string = '!'
}

class Derived extends Base{
    public name: string = '?'  // ERROR!
}
</code>```

Thus I wonder:

Is my observation an intended behavior or a bug in Typescript?

If it's intended, why this inconsistency exists? Why not TypeScript requires all overriding members having the same accessibility as members in base class? Or allowing all derived members with higher accessibility overriding members in base class?

答:
javascript has no this capability as in java called it is a field rewrite.let's look a code snippet in java:

```<code>class Base {
    protected String name = "!";

    public String bar() {
        return name;
    }
}

class Derived extends Base {
    public String name = "?";

    public String foo() {
        return name;
    }
}
</code>```

when you hold an a kind of Derived instance it in java. then it.foo() return "?" and it.bar() return "!".but why both methods return "?" in javascript,due to the javascript behavior occurs in runtime and bind this type to Derived in Base,so you can't rewrite fields in javascript.Are you remember Function.prototype.call(thisArg)?In Derived class that doing something like this,if you call the bar method on Derived instance,it actually bind Derived type to the Base class. you can disallow to do such thing is make the field private in Base and let the compiler tell you this errors only in typescript.

Body:
I am new to Typescript, and I tried to played around a little with TypeScript in this playground. I noticed that in TypeScript, a protected member in base class can be overridden by public members:

class Base {
    protected name: string = '!'
}

class Derived extends Base{
    public name: string = '?'
}

On the one hand, this makes sense to me since the Liskov Substitution Principle still holds: base class has stricter requirements than derived class. But on the other hand, I noticed that private member cannot be overridden by protected or public one, which seems inconsistent to me:

class Base {
    private name: string = '!'
}

class Derived extends Base{
    public name: string = '?'  // ERROR!
}

Thus I wonder:

Is my observation an intended behavior or a bug in Typescript?

If it's intended, why this inconsistency exists? Why not TypeScript requires all overriding members having the same accessibility as members in base class? Or allowing all derived members with higher accessibility overriding members in base class?

Body:
javascript has no this capability as in java called it is a field rewrite.let's look a code snippet in java:

class Base {
    protected String name = "!";

    public String bar() {
        return name;
    }
}

class Derived extends Base {
    public String name = "?";

    public String foo() {
        return name;
    }
}

when you hold an a kind of Derived instance it in java. then it.foo() return "?" and it.bar() return "!".but why both methods return "?" in javascript,due to the javascript behavior occurs in runtime and bind this type to Derived in Base,so you can't rewrite fields in javascript.Are you remember Function.prototype.call(thisArg)?In Derived class that doing something like this,if you call the bar method on Derived instance,it actually bind Derived type to the Base class. you can disallow to do such thing is make the field private in Base and let the compiler tell you this errors only in typescript.


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答: Make id as primary and combine id and classid as unique. It will prevent from inserting duplicate from the sql end.</p>

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')


问:
Best Datepicker for feeding 'pickable' dates
I'm looking for a jQuery datepicker plugin that I can 'feed' available dates.

Example input:
22-01-2017
23-01-2017
28-01-2017
02-02-2017

Output:
-a datepicker that only allows the dates from the example input.

Daterange wouldn't really work here, as certain dates could be skipped. Does anyone know a (customizeable) jquery plugin that allows this?

Thanks in advance!

答:
Check out my plugin here: https://codecanyon.net/item/caleran-date-range-picker/19454049

And there's a disableDays filter in the plugin, you can use it backwards to enable the days you want.

Like this:

```<code><script type="text/javascript">
  $("#caleran").caleran({
    disableDays: function(day){
      var enabledDays = [
         moment("22-01-2017", "DD-MM-YYYY"),
         moment("23-01-2017", "DD-MM-YYYY"),
         moment("28-01-2017 ", "DD-MM-YYYY"),
         moment("02-02-2017", "DD-MM-YYYY")
      ];
      return $.grep(enabledDays, function(d){ return d.isSame(day,"day"); }).length > 0;
    }
  });
</script>
</code>```

Demo here: http://rettica.com/caleran/docs/readme.html#custom-disabled-ranges-with-callback-

Body:
Check out my plugin here: https://codecanyon.net/item/caleran-date-range-picker/19454049

And there's a disableDays filter in the plugin, you can use it backwards to enable the days you want.

Like this:

<script type="text/javascript">
  $("#caleran").caleran({
    disableDays: function(day){
      var enabledDays = [
         moment("22-01-2017", "DD-MM-YYYY"),
         moment("23-01-2017", "DD-MM-YYYY"),
         moment("28-01-2017 ", "DD-MM-YYYY"),
         moment("02-02-2017", "DD-MM-YYYY")
      ];
      return $.grep(enabledDays, function(d){ return d.isSame(day,"day"); }).length > 0;
    }
  });
</script>

Demo here: http://rettica.com/caleran/docs/readme.html#custom-disabled-ranges-with-callback-


问:
Opera Mini social login issue with loginradius.com
We are working on a react application(voot.com) and it is live for mobile.

Live url: https://m-origin.voot.com

We are facing many issues with opera mini and one of them is:

We are not able to social login by using loginradius.com. When we click on 'continue with facebook', app redirects to loginradius.com which is third party. But we din't get any response to our server from loginradius that's why user is not logged in by social login.

We are using a js file for loginradius coming from http://cdn.loginradius.com/hub/prod/js/CustomInterface.2.js.

We have written a callback funtion expecting from loginradius to return to that callback. But that callback function is not calling in opera mini browser rest browsers are working fine.

答:
Look like opera mini open popup (as new tab because of mobile browser). My recommendation is not to open the new window in case of mobile devices. follow steps to fix this problem

1.Add this template to your page

```<code><script id="loginradiuscustom_tmpl_mobile" type="text/html"><div class="<%=Name%>">
<a class="anchor_<%=Name%>" href="javascript:void()" onclick="window.location.href = '<%=Endpoint%>&same_window=1&callback=<%=createCurrentRoute(window.location.href)%>'">
<span class="icon-image-<%=Name%>" ></span>
<span class="<%=Name%>-text">Continue with <%=Name%></span>
</a>
</div></script>
</code>```

2.Add this method to detect mobile devices

```<code>function detectmob() {
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}
</code>```

3.replace the following line

```<code>options.templatename = "loginradiuscustom_tmpl";
</code>```

with

```<code>if(detectmob()){
    options.templatename = "loginradiuscustom_tmpl_mobile";
}else{
    options.templatename = "loginradiuscustom_tmpl";
}
</code>```

Body:
Look like opera mini open popup (as new tab because of mobile browser). My recommendation is not to open the new window in case of mobile devices. follow steps to fix this problem

1.Add this template to your page

<script id="loginradiuscustom_tmpl_mobile" type="text/html"><div class="<%=Name%>">
<a class="anchor_<%=Name%>" href="javascript:void()" onclick="window.location.href = '<%=Endpoint%>&same_window=1&callback=<%=createCurrentRoute(window.location.href)%>'">
<span class="icon-image-<%=Name%>" ></span>
<span class="<%=Name%>-text">Continue with <%=Name%></span>
</a>
</div></script>

2.Add this method to detect mobile devices

function detectmob() {
 if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 || navigator.userAgent.match(/Windows Phone/i)
 ){
    return true;
  }
 else {
    return false;
  }
}

3.replace the following line

options.templatename = "loginradiuscustom_tmpl";

with

if(detectmob()){
    options.templatename = "loginradiuscustom_tmpl_mobile";
}else{
    options.templatename = "loginradiuscustom_tmpl";
}


问:
So NOW why is my bean null?
I recently asked this question regarding pulling beans out of an applicationContext. The answer was indeed helpful, but now it seems I have a problem with accessing this bean from a class outside the test. In other words, my test instantiates a class which uses a bean from an application context, but this bean keeps coming up null.

My test sets up the application context like this:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class SearcherTests {
</code>```

My test programmatically instantiates the Repository class:

```<code>    Repository searcher = new Repository();
</code>```

My Repository class has the following member variable:

```<code> @Resource
 private MyFactory myFactory;
</code>```

If I understand Spring correctly, this should look to the current application context for a bean named myFactory. According to the test, the current application context should be applicationContext-test.xml, which contains a definition for myFactory:

```<code> <bean id="myFactory"
    name="myFactory"
    class="com.foo.Mocks"
    factory-method="createMockFactory" />
</code>```

In the future, this factory method will return a mock. But at the moment, it just returns a regular Factory object:

```<code>public class Mocks {

 public static MyFactory createMockFactory() {
  return new MyFactory();
 }
}
</code>```

When I run the app from my browser, the myFactory variable was correctly instantiated from the bean definition in applicationContext.xml. In my test, to make sure that my applicationContext-test.xml is working, I have this same bean listed as a member variable just like I do in the Repository class. While running the test, the myFactory variable in the file containing the test looks exactly as I'd expect it to. However, when I get to the Repository class, the myFactory variable in that class is null. It seems as though this class is not instantiating the myFactory variable based on the bean definition in applicationContext-test.xml. Can someone tell me why?

Update

I changed the searcher variable so that it is a Spring bean, rather than instantiating the Repository class manually, and now the myFactory variable has been populated within the Repository class. Can someone explain why this needs to be a bean in order to work?

答: If you instantiate Repository yourself, then Spring doesn't get involved, and the dependencies won't get injected. It doesn't happen magically, Spring has to be in the loop somehow - the instance has to be passed through Spring processing layers, and a direct instantiation prevents that.

Title: So NOW why is my bean null?

Body:
I recently asked this question regarding pulling beans out of an applicationContext. The answer was indeed helpful, but now it seems I have a problem with accessing this bean from a class outside the test. In other words, my test instantiates a class which uses a bean from an application context, but this bean keeps coming up null.

My test sets up the application context like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
public class SearcherTests {

My test programmatically instantiates the Repository class:

    Repository searcher = new Repository();

My Repository class has the following member variable:

 @Resource
 private MyFactory myFactory;

If I understand Spring correctly, this should look to the current application context for a bean named myFactory. According to the test, the current application context should be applicationContext-test.xml, which contains a definition for myFactory:

 <bean id="myFactory"
    name="myFactory"
    class="com.foo.Mocks"
    factory-method="createMockFactory" />

In the future, this factory method will return a mock. But at the moment, it just returns a regular Factory object:

public class Mocks {

 public static MyFactory createMockFactory() {
  return new MyFactory();
 }
}

When I run the app from my browser, the myFactory variable was correctly instantiated from the bean definition in applicationContext.xml. In my test, to make sure that my applicationContext-test.xml is working, I have this same bean listed as a member variable just like I do in the Repository class. While running the test, the myFactory variable in the file containing the test looks exactly as I'd expect it to. However, when I get to the Repository class, the myFactory variable in that class is null. It seems as though this class is not instantiating the myFactory variable based on the bean definition in applicationContext-test.xml. Can someone tell me why?

Update

I changed the searcher variable so that it is a Spring bean, rather than instantiating the Repository class manually, and now the myFactory variable has been populated within the Repository class. Can someone explain why this needs to be a bean in order to work?


问:
How to improve primitive VBA code for DCF model?
I'm new to VBA and I've been trying to create a program that allows me to take a starting cash amount, discount that amount by a certain discount rate, and also multiply the discount rate by n years to find a given discounted cash flow based upon a given number of years. Does anyone have any tips for how I could make this code more efficient? Also, what are some tips for using a loop to sum together different sums of cash, such as "(100/1.01) + (100/1.01^2) + (100/1.01^3)?" Thanks in advance!     </p>

```<code>Sub DCF()

Dim z As Double, CashFlow As Double, DiscRate As Double, Periods As Double

CashFlow = InputBox("Enter initial cash flow: ", "Cash Flow")
DiscRate = InputBox("Enter discount rate in decimal form: ", "Discount Rate")
Periods = InputBox("How many periods (in years) are there?", "Periods")

z = CashFlow / (1 + DiscRate) ^ Periods

MsgBox Format(z, "$0.00")

End Sub
</code>```

答:
The code you have is fine and only requires a loop to create the discounted cash flow.  This should do what you want:</p>

```<code>Sub DCF()

  Dim z As Double, CashFlow As Double, DiscRate As Double, Periods As Double: z = 0#

  CashFlow = InputBox("Enter initial cash flow: ", "Cash Flow")
  DiscRate = InputBox("Enter discount rate in decimal form: ", "Discount Rate")
  Periods = InputBox("How many periods (in years) are there?", "Periods")

  Dim i As Integer
  For i = 1 To Periods:
    z = z + CashFlow / (1# + DiscRate) ^ i
  Next

  MsgBox Format(z, "$0.00")

End Sub
</code>```

Body:
I'm new to VBA and I've been trying to create a program that allows me to take a starting cash amount, discount that amount by a certain discount rate, and also multiply the discount rate by n years to find a given discounted cash flow based upon a given number of years. Does anyone have any tips for how I could make this code more efficient? Also, what are some tips for using a loop to sum together different sums of cash, such as "(100/1.01) + (100/1.01^2) + (100/1.01^3)?" Thanks in advance!

Sub DCF()

Dim z As Double, CashFlow As Double, DiscRate As Double, Periods As Double

CashFlow = InputBox("Enter initial cash flow: ", "Cash Flow")
DiscRate = InputBox("Enter discount rate in decimal form: ", "Discount Rate")
Periods = InputBox("How many periods (in years) are there?", "Periods")

z = CashFlow / (1 + DiscRate) ^ Periods

MsgBox Format(z, "$0.00")

End Sub

Body:
The code you have is fine and only requires a loop to create the discounted cash flow.  This should do what you want:

Sub DCF()

  Dim z As Double, CashFlow As Double, DiscRate As Double, Periods As Double: z = 0#

  CashFlow = InputBox("Enter initial cash flow: ", "Cash Flow")
  DiscRate = InputBox("Enter discount rate in decimal form: ", "Discount Rate")
  Periods = InputBox("How many periods (in years) are there?", "Periods")

  Dim i As Integer
  For i = 1 To Periods:
    z = z + CashFlow / (1# + DiscRate) ^ i
  Next

  MsgBox Format(z, "$0.00")

End Sub


问:
File removed with option removing references and deleted from finder directly now showing the warning XCode 8
How can I remove the warning that is showing in XCode?

Warning:

file:///Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m:

warning: Missing file: /Users/harjotsingh/Desktop/CoreDataOBJC/CoreDataOBJC/ViewController.m is missing from working copy

Actually, I have tried all the methods cleaning the project and deleting the installed app from simulator and also deleting the build from library.

Certainly, there is a way to suppress the warning by hiding it. I don't want to hide the warnings. I want to remove them. Could someone suggest me the good way because I am trying this from months and not getting the solution to remove them.

Edited: I have selected remove references for ViewController.m and then deleted the file from finder and it is then showing me the warning.

答:
In Xcode, click on Project Navigator. Select ViewController.m and from the File Inspector present on the right hand side select the small folder icon. Now you can select the location of the file in Finder and click choose.
This will create a reference to the file whose reference is being shown as missing.


问:
remove some elements if no children
i need to remove some elements if no children...

this will work...

```<code>$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});
</code>```

but it will look for all elements... i need to limit to some elements.. so i made this..

```<code>elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})
</code>```

but it doesn't work..

答:
You can use the id, classor tag in the jQuery selector. Try the following way:

$("div:empty").remove();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div><span>test</span></div>
<div></div></code>```

Title: remove some elements if no children

Body:
i need to remove some elements if no children...

this will work...

$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});

but it will look for all elements... i need to limit to some elements.. so i made this..

elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})

but it doesn't work..

Body:
You can use the id, classor tag in the jQuery selector. Try the following way:

$("div:empty").remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div><span>test</span></div>
<div></div>