问:
Tallying elements in a dataframe that meet a logic check
I have a dataframe (studentData)

```<code>     StudentID   Freshmen    Sophomore      Lot200      Lot700
         001           1           0         200         000
         002           0           1         200         700
         003           1           0         200         000
</code>```

I want a total of what the different academic years spent on parking. If Freshmen is 1 that is their year, similarity for Sophomore being 1.

Want to have this dataframe (costs)

```<code>  Freshmen        Sophomore
  400             900
</code>```

Tried

```<code>    if(length(which(studentData$Freshmen ==1))
       {
          costs$Freshmen <- studentData$Lot200 + studentData$Lot700
       }
</code>```

But this results in returning TRUE for every entry and effectively adding every students expenditure on parking regardless of academic year. Any ideas how I might correct this?

答:
I would do it like tyluRp, using dplyr. In base R, you can get the relevant quantities like so:

```<code>f = sum(studentData[studentData$Freshmen == 1,]$Lot200,
        studentData[studentData$Freshmen == 1,]$Lot700)
s = sum(studentData[studentData$Sophomore == 1,]$Lot200,
        studentData[studentData$Sophomore == 1,]$Lot700)
</code>```

Then use data.frame to build the frame you want.

```<code>df = data.frame(Freshmen = f, Sophomore = s)
</code>```

Tedious, and probably not even the best base R solution. But it's a more idiomatic way of getting the sums you want.

Body:
I have a dataframe (studentData)

     StudentID   Freshmen    Sophomore      Lot200      Lot700
         001           1           0         200         000
         002           0           1         200         700
         003           1           0         200         000

I want a total of what the different academic years spent on parking. If Freshmen is 1 that is their year, similarity for Sophomore being 1.

Want to have this dataframe (costs)

  Freshmen        Sophomore
  400             900

Tried

    if(length(which(studentData$Freshmen ==1))
       {
          costs$Freshmen <- studentData$Lot200 + studentData$Lot700
       }

But this results in returning TRUE for every entry and effectively adding every students expenditure on parking regardless of academic year. Any ideas how I might correct this?

Body:
I would do it like tyluRp, using dplyr. In base R, you can get the relevant quantities like so:

f = sum(studentData[studentData$Freshmen == 1,]$Lot200,
        studentData[studentData$Freshmen == 1,]$Lot700)
s = sum(studentData[studentData$Sophomore == 1,]$Lot200,
        studentData[studentData$Sophomore == 1,]$Lot700)

Then use data.frame to build the frame you want.

df = data.frame(Freshmen = f, Sophomore = s)

Tedious, and probably not even the best base R solution. But it's a more idiomatic way of getting the sums you want.


来源: stackexchange

问:
Need .NET code to execute only when in debug configuration
I have some code that access an API out on the web. One of the API's parameters allows me to let them know that I am testing.

I would like to only set this parameter in my code when I am testing. Currently, I just comment the code out when I do a release build.

Is there an automatic way of doing this based on the build configuration?

答:
This works in asp.net:

```<code>if (System.Web.HttpContext.Current.IsDebuggingEnabled)
    //send email to developer;
else
    //send email to customer;
</code>```

from Rick Strahl @ Detecting-ASPNET-Debug-mode

ContentLicense: CC BY-SA 2.5

Body:
This works in asp.net:

if (System.Web.HttpContext.Current.IsDebuggingEnabled)
    //send email to developer;
else
    //send email to customer;

from Rick Strahl @ Detecting-ASPNET-Debug-mode

ContentLicense: CC BY-SA 3.0


问:
Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users?
I have some css menus on my site that expand with :hover (without js)

This works in a semi-broken way on iDevices, for example a tap will activate the :hover rule and expand the menu, but then tapping elsewhere doesn't remove the :hover. Also if there is a link inside the element that is :hover'ed, you have to tap twice to activate the link (first tap triggers :hover, second tap triggers link).

I've been able to make things work nicely on iphone by binding the touchstart event.

The problem is that sometimes mobile safari still chooses to trigger the :hover rule from the css instead of my touchstart events!

I know this is the problem because when I disable all the :hover rules manually in the css, mobile safari works great (but regular browsers obviously don't anymore).

Is there a way to dynamically "cancel" :hover rules for certain elements when the user is on mobile safari?

See and compare iOS behavior here: http://jsfiddle.net/74s35/3/
Note: that only some css properties trigger the two-click behavior, e.g. display:none; but not background: red; or text-decoration: underline;

答:
I found that ":hover" is unpredictable in iPhone/iPad Safari. Sometimes tap on element make that element ":hover", while sometimes it drifts to other elements.

For the time being, I just have a "no-touch" class at body.

```<code><body class="yui3-skin-sam no-touch">
   ...
</body>
</code>```

And have all CSS rules with ":hover" below ".no-touch":

```<code>.no-touch my:hover{
   color: red;
}
</code>```

Somewhere in the page, I have javascript to remove no-touch class from body.

```<code>if ('ontouchstart' in document) {
    Y.one('body').removeClass('no-touch');
}
</code>```

This doesn't look perfect, but it works anyway.

Body:
I found that ":hover" is unpredictable in iPhone/iPad Safari. Sometimes tap on element make that element ":hover", while sometimes it drifts to other elements.

For the time being, I just have a "no-touch" class at body.

<body class="yui3-skin-sam no-touch">
   ...
</body>

And have all CSS rules with ":hover" below ".no-touch":

.no-touch my:hover{
   color: red;
}

Somewhere in the page, I have javascript to remove no-touch class from body.

if ('ontouchstart' in document) {
    Y.one('body').removeClass('no-touch');
}

This doesn't look perfect, but it works anyway.


问:
Visual Studio 2017 Angular 4 Templates
I am looking for a good Angular 4 template for Visual Studio 2017.  Or what is the best template to use and the way to proceed?  This will be for a Angular 4 SPA web page.</p>

答:
For a barebones Template, independent of backend, and for an overall nice tool to help with Angular 2+ development, look into the Angular CLI, as was mentioned in a comment by Vahx.

Specifically for an app starter template, the ng new command does the following:

The Angular CLI makes it easy to create an application that already
  works, right out of the box. It already follows our best practices!

Once you have a new app, you can then further quickly generate some additional boilerplate / templated code as you progress in development, via the ng generate command:

Generate components, routes, services and pipes with a simple command.
  The CLI will also create simple test shells for all of these.

Check out the Angular CLI Docs page and the main Angular Getting Started Tutorial, for further info.

Although this is not a Visual Studio specific template, it is an option to consider.

Title: Visual Studio 2017 Angular 4 Templates


问:
Convert XML to a data frame
I am looking to transfer data from a .php link into an R data frame, but am having trouble doing so.

Attempts thus far:

```<code>require(XML)
data <- xmlParse("http://www.mahdial-husseini.com/xmlthing.php ")
xml_data <- xmlToList(data)
</code>```

The error I am getting: Error: 1: failed to load HTTP resource

Additionally (and more conceptually), I don't quite understand the nature of the link. Is this XML data in a php file, and if so, when using R to gather data, do I treat it as XML or PHP? Thank you

Title: Convert XML to a data frame

Body:
I am looking to transfer data from a .php link into an R data frame, but am having trouble doing so.

Attempts thus far:

require(XML)
data <- xmlParse("http://www.mahdial-husseini.com/xmlthing.php ")
xml_data <- xmlToList(data)

The error I am getting: Error: 1: failed to load HTTP resource

Additionally (and more conceptually), I don't quite understand the nature of the link. Is this XML data in a php file, and if so, when using R to gather data, do I treat it as XML or PHP? Thank you

Body:
you can use rvest package (and data.table for convenience)

library(data.table)
library(rvest)
a <- read_html("http://www.mahdial-husseini.com/xmlthing.php")
dt <- rbindlist(lapply(a %>% html_nodes(css = "body > ppm1_0 > ppm1_0") %>%
                             xml_attrs(),
                       function(x) as.data.table(t((x)))))
dt <- cbind(dt[,2, with = FALSE],
            as.data.table(lapply(dt[,-2, with = FALSE], as.numeric)))
dt

          site sample month day year hour      jd doy pm25_hourly aod_47
1:      duluth      0     0   0    0    0       0   0           0  0.000
2:                 19    12   0 2004    5       0   0          30  0.000
3:    Sarasota   4545     4   0 2017    0       0   0           0  0.000
4:     Atlanta  11111    10   1 2004   13 2453280 275          23  0.379
5:  Birmingham  11112    10   2 2008   14 2453281 276           0  0.000
6:    Savannah  11113    10   3 2004   13 2453282 277          15  0.181
7:   Fort Knox  11114     6  20 2017   21       0 301          18  0.000
8: Fort Rucker  63738     1   0 2015    0       0   0          40  0.000
   omi_aot omi_no2      fit res      lng     lat rel_humid altitude pressure
1:   0.000   0.000  0.00000   0  84.1000 34.0000         0        0        0
2:   0.000   0.000  0.00000   0  63.6167 38.4161         0        0        0
3:   0.000   0.000  0.00000   0 -82.5300 27.3300         0        0        0
4:   0.148   0.274 16.01850  NA -84.7000 33.7500         0        0        0
5:   0.000   0.000 19.19440   0 -86.8000 33.5200         0        0        0
6:   0.133   0.127  9.00433  NA -81.1000 32.0800         0        0        0
7:   0.000   0.000  0.00000   0 -85.9500 37.9100         0        0        0
8:   0.000   0.000  0.00000   0 -85.7000 31.3400         0        0        0
   signal_received temp_c
1:               0      0
2:               0      0
3:               0      0
4:               0      0
5:               0      0
6:               0      0
7:               0      0
8:               0      0


问:
Is it possible to overload functions in Scilab?
I would like to know how to overload a function in scilab. It doesn't seem to be as simple as in C++. For example,

```<code>function [A1,B1,np1]=pivota_parcial(A,B,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction

//has less input/output variables//operates differently

function [A1,np1]=pivota_parcial(A,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction
</code>```

thanks

Beginner in scilab ....

答:
You can accomplish something like that by combining varargin, varargout and argn() when you implement your function. Take a look at the following example:

```<code>function varargout = pivota_parcial(varargin)
    [lhs,rhs] = argn();
    //first check number of inputs or outputs
    //lhs: left-hand side (number of outputs)
    //rhs: right-hand side (number of inputs)

    if rhs == 4 then
        A  = varargin(1); B = 0;
        n  = varargin(2); k = varargin(3);
        np = varargin(4);
    elseif rhs == 5 then
        A  = varargin(1); B = varargin(2);
        n  = varargin(3); k = varargin(4);
        np = varargin(5);
    else
        error("Input error message");
    end

    //computation goes on and it may depend on (rhs) and (lhs)
    //for the sake of running this code, let's just do:
    A1 = A;
    B1 = B;
    np1 = n;

    //output
    varargout = list(A1,B1,np1);
endfunction
</code>```

First, you use argn() to check how many arguments are passed to the function. Then, you rename them the way you need, doing A = varargin(1) and so on. Notice that B, which is not an input in the case of 4 inputs, is now set to a constant. Maybe you actually need a value for it anyways, maybe not.

After everything is said and done, you need to set your output, and here comes the part in which using only varargout may not satisfy your need. If you use the last line the way it is, varargout = list(A1,B1,np1), you can actually call the function with 0 and up to 3 outputs, but they will be provided in the same sequence as they appear in the list(), like this:

pivota_parcial(A,B,n,k,np);: will run and the first output A1 will be delivered, but it won't be stored in any variable.

[x] = pivota_parcial(A,B,n,k,np);: x will be A1.

[x,y] = pivota_parcial(A,B,n,k,np);: x will be A1 and y will be B1.

[x,y,z] = pivota_parcial(A,B,n,k,np);: x will be A1, y will be B1, z will be np1.

If you specifically need to change the order of the output, you'll need to do the same thing you did with your inputs: check the number of outputs and use that to define varargout for each case. Basically, you'll have to change the last line by something like the following:

```<code>    if lhs == 2 then
        varargout = list(A1,np1);
    elseif lhs == 3 then
        varargout = list(A1,B1,np1);
    else
        error("Output error message");
    end
</code>```

Note that even by doing this, the ability to call this functions with 0 and up to 2 or 3 outputs is retained.

Body:
I would like to know how to overload a function in scilab. It doesn't seem to be as simple as in C++. For example,

function [A1,B1,np1]=pivota_parcial(A,B,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction

//has less input/output variables//operates differently

function [A1,np1]=pivota_parcial(A,n,k,np)
.......//this is just an example// the code doesn't really matter
endfunction

thanks

Beginner in scilab ....

Body:
You can accomplish something like that by combining varargin, varargout and argn() when you implement your function. Take a look at the following example:

function varargout = pivota_parcial(varargin)
    [lhs,rhs] = argn();
    //first check number of inputs or outputs
    //lhs: left-hand side (number of outputs)
    //rhs: right-hand side (number of inputs)

    if rhs == 4 then
        A  = varargin(1); B = 0;
        n  = varargin(2); k = varargin(3);
        np = varargin(4);
    elseif rhs == 5 then
        A  = varargin(1); B = varargin(2);
        n  = varargin(3); k = varargin(4);
        np = varargin(5);
    else
        error("Input error message");
    end

    //computation goes on and it may depend on (rhs) and (lhs)
    //for the sake of running this code, let's just do:
    A1 = A;
    B1 = B;
    np1 = n;

    //output
    varargout = list(A1,B1,np1);
endfunction

First, you use argn() to check how many arguments are passed to the function. Then, you rename them the way you need, doing A = varargin(1) and so on. Notice that B, which is not an input in the case of 4 inputs, is now set to a constant. Maybe you actually need a value for it anyways, maybe not.

After everything is said and done, you need to set your output, and here comes the part in which using only varargout may not satisfy your need. If you use the last line the way it is, varargout = list(A1,B1,np1), you can actually call the function with 0 and up to 3 outputs, but they will be provided in the same sequence as they appear in the list(), like this:

pivota_parcial(A,B,n,k,np);: will run and the first output A1 will be delivered, but it won't be stored in any variable.

[x] = pivota_parcial(A,B,n,k,np);: x will be A1.

[x,y] = pivota_parcial(A,B,n,k,np);: x will be A1 and y will be B1.

[x,y,z] = pivota_parcial(A,B,n,k,np);: x will be A1, y will be B1, z will be np1.

If you specifically need to change the order of the output, you'll need to do the same thing you did with your inputs: check the number of outputs and use that to define varargout for each case. Basically, you'll have to change the last line by something like the following:

    if lhs == 2 then
        varargout = list(A1,np1);
    elseif lhs == 3 then
        varargout = list(A1,B1,np1);
    else
        error("Output error message");
    end

Note that even by doing this, the ability to call this functions with 0 and up to 2 or 3 outputs is retained.


问:
install xgboost on anaconda
I installed xgboost following this link. It works fine with my python3.  My question is what do I need to do to have it work on my anaconda? I tried to import xgboost on my anaconda but failed. Could anyone help me with that? Thank you so much! </p>

答:
you can follow these steps :
 1. In anaconda Prompt type the command  "anaconda search -t conda xgboost"
   it will show the bunch of list of packages according to the OS
 2. select the appropriate name of the "xgboost" package
 3. and type the command "conda install -c mikesilva xgboost"
 note:- my os is win 64 ans python 3.6 so I choose mikesilve

Title: install xgboost on anaconda


问:
How do I do this in Javascript and Django?
I'm used to putting my javascripts in the top of my page in the head section.  In my javascript, I use a lot of template stuff from Django like:  {{ user.id }} {{ post.body }}

I decided to move my javascript into another file, and then import it using: script src=

But since my javascript is in another file now it can't read my Django template stuff.

What do I do? I have Django template stuff all over the javascript, and I must move my javascript to another file.

答:
You could use a JSON array as Samet suggested, or even just regular JS variables.

```<code><script type='text/javascript'>
some_numeric_property = {{variable1}};
some_string_property = '{{variable2}}';
</script>
</code>```

Another way to do it (the way I'd usually go) is to pass all the details you need in via function calls and data- attributes. For example, if I wanted a certain link to pop up an AJAX bubble with a user's profile on hover I might do this:

```<code><a href='/profile/{{user.id}}' onmouseover='show_user_popup({{user_id}})'>{{user.name}}</a>
</code>```

or this (presuming my script was attaching events to links with classes of user-link):

```<code><a href='/profile/{{user.id}}' class='user-link' data-uid='{{user_id}}'>{{user.name}}</a>
</code>```

You could also call these functions in the head of your HTML straight after loading it if desired.

```<code><script type='text/javascript' src='{{MEDIA_URL}}/js/whatever.js'></script>
<script type='text/javascript'>
do_something_with_a_number({{variable1}});
do_something_with_a_string('{{variable2}}');
</script>
</code>```

The advantage of the latter is, because no code gets executed when you load the JS file (with the exception of creating and binding function objects, obviously), you can have the one JS file included on every page on your site, and just call the bits you need on the appropriate pages. This one file would then get cached after the first load (assuming you're sending the right headers), decreasing load times for subsequent pages.

EDIT: security considerations: The method I've described (along with many of the other methods on this page) suggest inserting data as either a) attributes of HTML tags or b) JavaScript entities. This is safe so long as you know the data either a) can't be set by untrusted users or b) is always in a "safe" format (ie the data comes from a SlugField or an IntegerField or something in the database).

However, if neither of those are the case, you'd need to protect against HTML and/or JS injection, by escaping the appropriate characters. Django's default behaviour of HTML entity escaping might protect you in some cases, but it might not, so it's worth checking.

Body:
You could use a JSON array as Samet suggested, or even just regular JS variables.

<script type='text/javascript'>
some_numeric_property = {{variable1}};
some_string_property = '{{variable2}}';
</script>

Another way to do it (the way I'd usually go) is to pass all the details you need in via function calls and data- attributes. For example, if I wanted a certain link to pop up an AJAX bubble with a user's profile on hover I might do this:

<a href='/profile/{{user.id}}' onmouseover='show_user_popup({{user_id}})'>{{user.name}}</a>

or this (presuming my script was attaching events to links with classes of user-link):

<a href='/profile/{{user.id}}' class='user-link' data-uid='{{user_id}}'>{{user.name}}</a>

You could also call these functions in the head of your HTML straight after loading it if desired.

<script type='text/javascript' src='{{MEDIA_URL}}/js/whatever.js'></script>
<script type='text/javascript'>
do_something_with_a_number({{variable1}});
do_something_with_a_string('{{variable2}}');
</script>

The advantage of the latter is, because no code gets executed when you load the JS file (with the exception of creating and binding function objects, obviously), you can have the one JS file included on every page on your site, and just call the bits you need on the appropriate pages. This one file would then get cached after the first load (assuming you're sending the right headers), decreasing load times for subsequent pages.

EDIT: security considerations: The method I've described (along with many of the other methods on this page) suggest inserting data as either a) attributes of HTML tags or b) JavaScript entities. This is safe so long as you know the data either a) can't be set by untrusted users or b) is always in a "safe" format (ie the data comes from a SlugField or an IntegerField or something in the database).

However, if neither of those are the case, you'd need to protect against HTML and/or JS injection, by escaping the appropriate characters. Django's default behaviour of HTML entity escaping might protect you in some cases, but it might not, so it's worth checking.


问:
Spammy structured data Issue (Markup Ok but considered spammy by Google)
I received the message in Search Console about spammy structured data regarding one of my websites. Mind you - It's an older website that has not been up to the standards.

So I  had all the error and warnings fixed and I submitted website for reconsideration. Reconsideration has been refused. Problem is I do not know why? Website pass the structured data testing tool test. There is no errors or warnings. At the moment markup is done within HTML ( not json-ld). Could someone take a look and advise me what I can do to have it fixed according to google guidelines and manual action removed.

I', not so sure if this is important or not, but index page is not the only one to contain markup for LocalBusiness. There are more pages similar to the index one, based on different location.

Website in question is http://www.man-van.biz

Thank you for your help in advance.

答: Problem has been solved. Problem was with duplicated schema markup on aggregate ratings (the same feedback's on all pages). Once I removed it from other pages and kept it only on index page and fix some other issues with markup reconsideration request has been approved and manual action removed.</p>


问:
Error when using system classloader with grapes
I'm writing a simple Groovy program with Java that reads something from the database:

```<code>@Grab('com.oracle:ojdbc6:11.2.0.1.0')
@Grab(group='org.codehaus.groovy', module='groovy-sql', version='2.4.6')

import groovy.sql.Sql

def db = [url: "jdbc:oracle:thin:@localhost:1521:XE",
          user: 'user_kshitiz', password: 'a', driver: 'oracle.jdbc.driver.OracleDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)
</code>```

However, this gives me a java.sql.SQLException: No suitable driver found error.
So I configure grapes to use system classloader:

```<code>@Grapes([
        @Grab('com.oracle:ojdbc6:11.2.0.1.0'),
        @GrabConfig(systemClassLoader = true)
])
</code>```

This too results in following error:

```<code>Information:Groovyc: java.lang.NoSuchMethodException: org.codehaus.groovy.runtime.dgm$518.<init>(java.lang.String, org.codehaus.groovy.reflection.CachedClass, java.lang.Class, [Ljava.lang.Class;)
    at java.lang.Class.getConstructor0(Class.java:2849)
    at java.lang.Class.getConstructor(Class.java:1718)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.createProxy(GeneratedMetaMethod.java:92)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.proxy(GeneratedMetaMethod.java:83)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.isValidMethod(GeneratedMetaMethod.java:68)
    at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3172)
    at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3134)
    at groovy.lang.MetaClassImpl.getMethodWithCachingInternal(MetaClassImpl.java:1330)
    at groovy.lang.MetaClassImpl.createPojoCallSite(MetaClassImpl.java:3367)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPojoSite(CallSiteArray.java:132)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:166)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at groovy.grape.GrapeIvy.grab(GrapeIvy.groovy:271)
    at groovy.grape.Grape.grab(Grape.java:167)
    at groovy.grape.GrabAnnotationTransformation.visit(GrabAnnotationTransformation.java:378)
    at org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:321)
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:546)
    at org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper.compile(GroovyCompilerWrapper.java:58)
    at org.jetbrains.groovy.compiler.rt.DependentGroovycRunner.runGroovyc(DependentGroovycRunner.java:116)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jetbrains.groovy.compiler.rt.GroovycRunner.intMain2(GroovycRunner.java:132)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.runGroovycInThisProcess(InProcessGroovyc.java:156)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.access$000(InProcessGroovyc.java:51)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:85)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

How do I create a database connection in Groovy?

答: JDBC drivers are available on Oracle Maven repository.  Please follow the instructions in this blog for more details. </p>

Body:
I'm writing a simple Groovy program with Java that reads something from the database:

@Grab('com.oracle:ojdbc6:11.2.0.1.0')
@Grab(group='org.codehaus.groovy', module='groovy-sql', version='2.4.6')

import groovy.sql.Sql

def db = [url: "jdbc:oracle:thin:@localhost:1521:XE",
          user: 'user_kshitiz', password: 'a', driver: 'oracle.jdbc.driver.OracleDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

However, this gives me a java.sql.SQLException: No suitable driver found error.
So I configure grapes to use system classloader:

@Grapes([
        @Grab('com.oracle:ojdbc6:11.2.0.1.0'),
        @GrabConfig(systemClassLoader = true)
])

This too results in following error:

Information:Groovyc: java.lang.NoSuchMethodException: org.codehaus.groovy.runtime.dgm$518.<init>(java.lang.String, org.codehaus.groovy.reflection.CachedClass, java.lang.Class, [Ljava.lang.Class;)
    at java.lang.Class.getConstructor0(Class.java:2849)
    at java.lang.Class.getConstructor(Class.java:1718)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.createProxy(GeneratedMetaMethod.java:92)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.proxy(GeneratedMetaMethod.java:83)
    at org.codehaus.groovy.reflection.GeneratedMetaMethod$Proxy.isValidMethod(GeneratedMetaMethod.java:68)
    at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:3172)
    at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:3134)
    at groovy.lang.MetaClassImpl.getMethodWithCachingInternal(MetaClassImpl.java:1330)
    at groovy.lang.MetaClassImpl.createPojoCallSite(MetaClassImpl.java:3367)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPojoSite(CallSiteArray.java:132)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:166)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at groovy.grape.GrapeIvy.grab(GrapeIvy.groovy:271)
    at groovy.grape.Grape.grab(Grape.java:167)
    at groovy.grape.GrabAnnotationTransformation.visit(GrabAnnotationTransformation.java:378)
    at org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:321)
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:931)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:593)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:546)
    at org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper.compile(GroovyCompilerWrapper.java:58)
    at org.jetbrains.groovy.compiler.rt.DependentGroovycRunner.runGroovyc(DependentGroovycRunner.java:116)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jetbrains.groovy.compiler.rt.GroovycRunner.intMain2(GroovycRunner.java:132)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.runGroovycInThisProcess(InProcessGroovyc.java:156)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc.access$000(InProcessGroovyc.java:51)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:85)
    at org.jetbrains.jps.incremental.groovy.InProcessGroovyc$1.call(InProcessGroovyc.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

How do I create a database connection in Groovy?


问:
Excel: Time * 24 returns negative number?
I have a field D19 in time format with value 13:40:00. Assume somone gets payed for 50 $ an hour, I want to create a formula to compute how much he has earned in that time.

Now if found here that

To convert a time to a number of hours, multiply by 24

So in this case the formula would be simply

```<code>= D19 * 24 * 50
</code>```

However the formula

```<code>= D19 * 24
</code>```

returns -10,33333.... The format of the cell where I entered the formula is a number -> standard. Why is it returning a negative number?

答:
When you multiply 13:40:00 by 24 you get 13.67, so when you take 13.67 and subtract 24 (which is one day) you get -10.33333 which is a value you got.

Are you sure you aren't subtracting one day from the value that you calculate? That would be the logical explanation.

Body:
I have a field D19 in time format with value 13:40:00. Assume somone gets payed for 50 $ an hour, I want to create a formula to compute how much he has earned in that time.

Now if found here that

To convert a time to a number of hours, multiply by 24

So in this case the formula would be simply

= D19 * 24 * 50

However the formula

= D19 * 24

returns -10,33333.... The format of the cell where I entered the formula is a number -> standard. Why is it returning a negative number?


问:
Enable bitcode in tvOS framework in Xcode 9.1
I'm developing a framework for tvOS in Xcode 9.1. This framework includes a static library (which I compiled and is bitcode enabled).

The problem is that the framework isn't bitcode enabled. I'm using otool to check whether it is bitcode enable or not:

```<code>tool -l blabla.Framework/myFramwork | grep __LLVM
</code>```

and I get nothing (which means bitcode disabled)

In the build setting in Xcode the option "bitcode enable" doesn't exists.

As I understand bitcode is mandatory for tvOS and the default settings should be YES but somehow it doesn't happened.

What am I missing? What do I need to add?

答: I don't recall there being an option to turn bitcode ON/OFF for tvOS targets in Xcode from the very beginning. May be in the very initial betas, but that option does not exist for tvOS AFAIK, and builds are bitcode enabled by default, as long as you build for the device. Builds for simulators will not be bitcode enabled.</p>

Body:
I'm developing a framework for tvOS in Xcode 9.1. This framework includes a static library (which I compiled and is bitcode enabled).

The problem is that the framework isn't bitcode enabled. I'm using otool to check whether it is bitcode enable or not:

tool -l blabla.Framework/myFramwork | grep __LLVM

and I get nothing (which means bitcode disabled)

In the build setting in Xcode the option "bitcode enable" doesn't exists.

As I understand bitcode is mandatory for tvOS and the default settings should be YES but somehow it doesn't happened.

What am I missing? What do I need to add?


问:
How to set twitter bootstrap modal wider and higher?
How to set twitter bootstrap modal wider and higher?

Example here (please click: Launch demo modal):

http://twitter.github.com/bootstrap/javascript.html#modals

答:
The accepted answer works well, however I would recommend using padding rather than margin. This way you retain the dismiss functionality when you click outside of the modal dialog.</p>

```<code>#myModal {
    width: 700px;
    padding-top: -300px !important;
    padding-left: -350px !important;
}

#myModal .modal-body {
    max-height: 525px;
}
</code>```

Body:
The accepted answer works well, however I would recommend using padding rather than margin. This way you retain the dismiss functionality when you click outside of the modal dialog.

#myModal {
    width: 700px;
    padding-top: -300px !important;
    padding-left: -350px !important;
}

#myModal .modal-body {
    max-height: 525px;
}


问:
Software watchdog causing system reboot if started at bootup
In my device I enabled software watchdog to monitor a file which is updated every 5 second by a application. I have configured software watchdog as below

```<code>file = /data/file_name_to_watch
change = 10
</code>```

Watchdog is getting started at bootup using below command during bootup:

```<code>/usr/sbin/watchdog.sh -f -v -c watchdog.conf
</code>```

Application which is responsible to update the file(file_name_to_watch) is started after watchdog deamon during bootup. File being monitored by watchdog is updated every 5 seconds by the application.

Problem is that watchdog is rebooting the system if it is started at bootup and this same problem doesn't exist when watchdog is not started at bootup but started manually after application is launched.

```<code>dmesg shows "Watchdog did not stop"
</code>```

Also, changing the watchdog configuration file to below didn't help.

```<code>  file = /data/file_name_to_watch
  change = 20
</code>```

I have checked that the file is getting updated before 10 seconds elapsed after watchdog is launched during bootup.

Any pointers to debug this problem will be appreciated.

Code which I am using for watchdog: https://layers.openembedded.org/layerindex/recipe/122/

答:
Debugged and found the problem to be time(NULL) returning a huge number in src/file_stat.c

This was happening due to date being not set very early during bootup.

Body:
In my device I enabled software watchdog to monitor a file which is updated every 5 second by a application. I have configured software watchdog as below

file = /data/file_name_to_watch
change = 10

Watchdog is getting started at bootup using below command during bootup:

/usr/sbin/watchdog.sh -f -v -c watchdog.conf

Application which is responsible to update the file(file_name_to_watch) is started after watchdog deamon during bootup. File being monitored by watchdog is updated every 5 seconds by the application.

Problem is that watchdog is rebooting the system if it is started at bootup and this same problem doesn't exist when watchdog is not started at bootup but started manually after application is launched.

dmesg shows "Watchdog did not stop"

Also, changing the watchdog configuration file to below didn't help.

  file = /data/file_name_to_watch
  change = 20

I have checked that the file is getting updated before 10 seconds elapsed after watchdog is launched during bootup.

Any pointers to debug this problem will be appreciated.

Code which I am using for watchdog: https://layers.openembedded.org/layerindex/recipe/122/


问:
Integrated Windows Authentication using NTLMv2
I'm trying to achieve NTLMv2 type authentication but I'm having problems making it work.

I have configured the client to send the Type-1 GET request using the server's hostname and the domain I'm in.
The server responds with a 401 Unauthorized challenge along with a WWW-Authorize: NTLM <base64-msg>. The base64 contains the following:

```<code>byte[] msg = {(byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P', (byte) '\0',
        0x02, 0, 0, 0, 0, 0, 0, 0, /*msg*/0x28, 0/*length*/, 0, 0, 0x01, (byte) 0b10000010, 0, 0,
        1, 2, 3, 4, 5, 6, 7, 8, //nonce
        0, 0, 0, 0, 0, 0, 0, 0}
</code>```

After that point, I was expecting Internet Explorer to automatically send the Type-3 response that will contain the username and the encrypted challenge using the password hash but instead it does nothing.

I have setup my local IP under the Local Intranet settings and have changed the custom level to use Automatic logon with current username and password.

Should I be doing something manually after receiving the challenge response from the server? I need the browser to do the encryption since I don't have access to the current user's credentials.

The server side component is a custom Java application running on Tomcat 8.0.45. Although I believe it shouldn't be related, I'm adding this in case it is. Also note that the server might also be behind a proxy sometimes (usually in the form of an Apache HTTPD).

答:
You won't need to know how it works under the hood, if you are using IE, but there are details below.

If IE is not responding, you may have a zone conflict. If the IP applies to more than one zone, things get confusing. I'd verify you add the site to trusted sites and make sure the Automatic setting is set for that zone.

I have had great luck with Eric Glass's code and explanations.  http://davenport.sourceforge.net/ntlm.html
The Java in the apendix works and I have had great luck converting it to c# with almost no need to change anything.

Body:
I'm trying to achieve NTLMv2 type authentication but I'm having problems making it work.

I have configured the client to send the Type-1 GET request using the server's hostname and the domain I'm in.
The server responds with a 401 Unauthorized challenge along with a WWW-Authorize: NTLM <base64-msg>. The base64 contains the following:

byte[] msg = {(byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P', (byte) '\0',
        0x02, 0, 0, 0, 0, 0, 0, 0, /*msg*/0x28, 0/*length*/, 0, 0, 0x01, (byte) 0b10000010, 0, 0,
        1, 2, 3, 4, 5, 6, 7, 8, //nonce
        0, 0, 0, 0, 0, 0, 0, 0}

After that point, I was expecting Internet Explorer to automatically send the Type-3 response that will contain the username and the encrypted challenge using the password hash but instead it does nothing.

I have setup my local IP under the Local Intranet settings and have changed the custom level to use Automatic logon with current username and password.

Should I be doing something manually after receiving the challenge response from the server? I need the browser to do the encryption since I don't have access to the current user's credentials.

The server side component is a custom Java application running on Tomcat 8.0.45. Although I believe it shouldn't be related, I'm adding this in case it is. Also note that the server might also be behind a proxy sometimes (usually in the form of an Apache HTTPD).


问:
how to allow a plugin to store data
I plan to propose an application which allow developers to provide plugins for it.

In my scenario, plugins access the application data and methods through a web-services layer, and as a consequence, the developer can expect to store his plugin-data using this layer. We do not want to allow database modification for each plugin which would need it or even provide a direct access to the database.

The question is, do you know, or can you imagine, a system that would suit the need of allowing any kind of data to be store in our database in this context ?

The application is an ASP.NET application, database is SQL Server.

答: if you use a nosql-database then the problem goes away as there is no database-schema to change, all you would have to manage is to make sure that plugins don't mess up eachothers data, some nosql-databases to look at can be found here: What NoSQL solutions are out there for .NET?</p>

Title: how to allow a plugin to store data


问:
IntelliJ IDEA JDK configuration on Mac OS
I am using IntelliJ IDEA 10. Every time when I create a new project, it is asking me to choose JDK for this project. Anyone know how I can configure it and make it easy to use?</p>

答:
The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

```<code>/Library/Java/JavaVirtualMachines/
</code>```

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

```<code>/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
</code>```

You can configure it by going to File -> Project Structure -> SDKs.

Body:
The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

/Library/Java/JavaVirtualMachines/

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

You can configure it by going to File -> Project Structure -> SDKs.


问:
How to extract images from a scanned pdf
I use Tesseract to extract text from scanned PDF. Some of these files also contain images. Is there a way to get those images?

I prepare my scanned pdf for tesseract by converting them in tiff files. But I can't find any command line tool to extract images from them, as pdfimages would do for "text" pdf.

Any idea of a tool (or a combination of tools) that would help me do the job?

答:
In many cases when someone has a PDF and they want to 'get' the images out, a rendering of the page itself to an image is often satisfactory.  However, if you do indeed want to extract the images you need to be careful what tool you use and investigate its reputation and quality of its output.

The first important thing to realize is if a tool claims to "extract the TIFF out of the PDF" or "extract the JPG out of the PDF" then they are misleading you as PDF doesn't contain JPEG or TIFF images per say.  The confusions arises because the compression technology that can be used by those two raster image formats is employed in PDF for compressing image data but it's not the same thing as a JPG file simply 'living' with a PDF.

There are many tools out there, however you will find the quality will vary widely.  Some can handle simple PDFs well, but have size limitations or complex PDFs simply make it crash or hang.  Some can handle RGB data well, but it simply skips or mishandles other color spaces.  Some won't let you have granular control over the data and will simply extract everything and recompress it as JPEG.  To top all of that off, often the image data can be corrupt in some way and the technology you're using has to be able to gracefully handle those scenarios.

If you plan on deploying this as part of an enterprise solution you need a tool capable of handling most any PDF you can find out there in the wild.


问:
navbar dropdown not working in bootstrap4.0
My navbar dropdown menu isn't working, I have included the following stylesheets and js files

```<code><link href='{%static "/css/bootstrap.min.css"%}' rel="stylesheet">
<link href='{%static "/css/narrow-jumbotron.css"%}' rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/static/javascript/bootstrap.min.js"></script>
</code>```

Even after including these the navbar dropdown isn't working

```<code><nav>
   <ul class="nav nav-pills float-right">
     {% url 'home' as home %}
     {% url 'about' as about %}
     {% url 'about' as contact %}
     <li {% if request.path == home %} class="nav-item active" {% endif %}>
       <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
     </li>
     <li {% if request.path == about %}class="nav-item" {% endif %}>
       <a class="nav-link" href="{% url 'about' %}">About</a>
     </li>
     <li {% if request.path == contact %}class="nav-item" {% endif %}>
       <a class="nav-link" href="{% url 'contact' %}">Contact</a>
     </li>
     <li class="nav-item dropdown">
       <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Account</a>
       <div class="dropdown-menu" aria-labelledby="dropdown01">
        {% if not request.user.is_authenticated %}
         <a class="dropdown-item" href="{% url 'account_login' %}">Login</a>
         <a class="dropdown-item" href="{% url 'account_signup' %}">SignUp</a>
         <a class="dropdown-item" href="{% url 'account_logout' %}">LogOut</a>
        {% endif %}
       </div>

     </li>

   </ul>
 </nav>
</code>```

答:
The Bootstrap V4 docs page for the navbar indicate that there are required classes to make the navbar collapse and I copied the previous poster's code, and added them.  This code is working properly with the navbar collapsing at the navbar-expand-lg breakpoint (you can select different breakpoints using -sm, -md, -lg, -xl and you can test it and make the similar changes to your nav code to have it work for Bootstrap V4.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

      Home(current)

      About

      Contact

      Account

        Login
        SignUp
        LogOut

```

Body:
My navbar dropdown menu isn't working, I have included the following stylesheets and js files

<link href='{%static "/css/bootstrap.min.css"%}' rel="stylesheet">
<link href='{%static "/css/narrow-jumbotron.css"%}' rel="stylesheet">

Even after including these the navbar dropdown isn't working

     {% url 'home' as home %}
     {% url 'about' as about %}
     {% url 'about' as contact %}

       Home(current)

       About

       Contact

       Account

        {% if not request.user.is_authenticated %}
         Login
         SignUp
         LogOut
        {% endif %}

Body:
The Bootstrap V4 docs page for the navbar indicate that there are required classes to make the navbar collapse and I copied the previous poster's code, and added them.  This code is working properly with the navbar collapsing at the navbar-expand-lg breakpoint (you can select different breakpoints using -sm, -md, -lg, -xl and you can test it and make the similar changes to your nav code to have it work for Bootstrap V4.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
  <ul class="navbar-nav mr-auto">
    <li {% if request.path==h ome %} class="nav-item active" {% endif %}>
      <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
    </li>
    <li {% if request.path==a bout %}class="nav-item" {% endif %}>
      <a class="nav-link" href="{% url 'about' %}">About</a>
    </li>
    <li {% if request.path==c ontact %}class="nav-item" {% endif %}>
      <a class="nav-link" href="{% url 'contact' %}">Contact</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" href="" id="dropdown01" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Account</a>
      <div class="dropdown-menu" aria-labelledby="dropdown01">
        <a class="dropdown-item" href="{% url 'account_login' %}">Login</a>
        <a class="dropdown-item" href="{% url 'account_signup' %}">SignUp</a>
        <a class="dropdown-item" href="{% url 'account_logout' %}">LogOut</a>
      </div>

    </li>

  </ul>
  </div>
</nav>


问:
Is there a higher-order version of cumtrapz()?

Introduction

Suppose I have N points x(1:N) at which I have function values f(1:N), for example:

```<code>x = [ 0.0795, 0.1327, 0.1395, 0.5133, 0.6470, 0.7358, 0.7640 ];
f = [ 0.0388, 0.4774, 0.4547, 0.0784, 0.3241, 0.2818, 0.9667 ];
</code>```

I want to calculate the cumulative integral of f with respect to x using these data.

Low-Order Solution

In MATLAB, I can do this easily using cumtrapz():

```<code>>> result = cumtrapz( x, f )

result =

     0    0.0137    0.0169    0.1165    0.1434    0.1703    0.1879
</code>```

Problem

Unfortunately, cumtrapz() uses the trapezoidal method for numerical integration, which is insufficient for my purposes.

Higher-order methods exist, like Simpson's Rule, but to my knowledge there isn't a function that performs the cumulative version of Simpson's Rule for nonuniform grids at the MATLAB File Exchange, or anywhere else.

Does a higher-order version of cumtrapz() already exist? If not, what would I have to do to implement it myself?

答:
I don't know of another method however you could use an interpolation with a pchip, spline, or some other method to increase the resolution.  Then use cumtrapz to get a closer approximation of the numeric integral.

It would be up to you to determine what method is applicable to your function.

Example using a sine function and spline

```<code>>> x = linspace(0,pi,5);
>> f = sin(x);
>> intF = cumtrapz(x,f);
error = 2-intF(end)
error =
    0.1039

>> x2 = linspace(x(1),x(end),numel(x)*10); %Up sample by 10x
>> f2 = interp1(x,f,x2,'spline');   %Interpolate with spline
>> intF2 = cumtrapz(x2,f2);
>> error = 2-intF2(end)  %MUCH LESS ERROR
error =
   -0.0038
</code>```

Body:
Introduction

Suppose I have N points x(1:N) at which I have function values f(1:N), for example:

x = [ 0.0795, 0.1327, 0.1395, 0.5133, 0.6470, 0.7358, 0.7640 ];
f = [ 0.0388, 0.4774, 0.4547, 0.0784, 0.3241, 0.2818, 0.9667 ];

I want to calculate the cumulative integral of f with respect to x using these data.

Low-Order Solution

In MATLAB, I can do this easily using cumtrapz():

>> result = cumtrapz( x, f )

result =

     0    0.0137    0.0169    0.1165    0.1434    0.1703    0.1879

Problem

Unfortunately, cumtrapz() uses the trapezoidal method for numerical integration, which is insufficient for my purposes.

Higher-order methods exist, like Simpson's Rule, but to my knowledge there isn't a function that performs the cumulative version of Simpson's Rule for nonuniform grids at the MATLAB File Exchange, or anywhere else.

Does a higher-order version of cumtrapz() already exist? If not, what would I have to do to implement it myself?

Body:
I don't know of another method however you could use an interpolation with a pchip, spline, or some other method to increase the resolution.  Then use cumtrapz to get a closer approximation of the numeric integral.

It would be up to you to determine what method is applicable to your function.

Example using a sine function and spline

>> x = linspace(0,pi,5);
>> f = sin(x);
>> intF = cumtrapz(x,f);
error = 2-intF(end)
error =
    0.1039

>> x2 = linspace(x(1),x(end),numel(x)*10); %Up sample by 10x
>> f2 = interp1(x,f,x2,'spline');   %Interpolate with spline
>> intF2 = cumtrapz(x2,f2);
>> error = 2-intF2(end)  %MUCH LESS ERROR
error =
   -0.0038


问:
Does this MVC controller code need to be refactored or not?
I am writing an CSV/Excel-->MySQL import manager for an MVC application (Kohana/PHP).

I have a controller named "ImportManager" which has an action named "index" (default) which displays in a grid all the valid .csv and .xls files that are in a specific directory and ready for import. The user can then choose the files he wants to import.

However, since .csv files import into one database table and .xls files import into multiple database tables, I needed to handle this abstraction. Hence I created a helper class called SmartImportFile to which I send each file be it .csv or .xls and then I get then ask this "smart" object to add the worksheets from that file (be they one or many) to my collection. Here is my action method in PHP code:

```<code>public function action_index()
{
    $view = new View('backend/application/importmanager');

    $smart_worksheets = array();
    $raw_files = glob('/data/import/*.*');
    if (count($raw_files) > 0)
    {
        foreach ($raw_files as $raw_file)
        {
            $smart_import_file = new Backend_Application_Smartimportfile($raw_file);
            $smart_worksheets = $smart_import_file->add_smart_worksheets_to($smart_worksheets);
        }
    }
    $view->set('smart_worksheets', $smart_worksheets);

    $this->request->response = $view;
}
</code>```

The SmartImportFile class looks like this:

```<code>class Backend_Application_Smartimportfile
{
    protected $file_name;
    protected $file_extension;
    protected $file_size;
    protected $when_file_copied;
    protected $file_name_without_extension;
    protected $path_info;
    protected $current_smart_worksheet = array();

    protected $smart_worksheets = array();

    public function __construct($file_name)
    {
        $this->file_name = $file_name;
        $this->file_name_without_extension = current(explode('.', basename($this->file_name)));

        $this->path_info = pathinfo($this->file_name);
        $this->when_file_copied = date('Y-m-d H:i:s', filectime($this->file_name));
        $this->file_extension = strtolower($this->path_info['extension']);
        $this->file_extension = strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
        if(in_array($this->file_extension, array('csv','xls','xlsx')))
        {
            $this->current_smart_worksheet = array();
            $this->process_file();
        }
    }

    private function process_file()
    {
        $this->file_size = filesize($this->file_name);
        if(in_array($this->file_extension, array('xls','xlsx')))
        {
            if($this->file_size < 4000000)
            {
                $this->process_all_worksheets_of_excel_file();
            }
        }
        else if($this->file_extension == 'csv')
        {
            $this->process_csv_file();
        }

    }

    private function process_all_worksheets_of_excel_file()
    {
        $worksheet_names = Import_Driver_Excel::get_worksheet_names_as_array($this->file_name);
        if (count($worksheet_names) > 0)
        {
            foreach ($worksheet_names as $worksheet_name)
            {
                $this->current_smart_worksheet['name'] = basename($this->file_name).' ('.$worksheet_name.')';
                $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
                $this->current_smart_worksheet['file_size'] = $this->file_size;
                $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;
                $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension.'__'.$worksheet_name;
                $this->assign_database_table_fields();
                $this->smart_worksheets[] = $this->current_smart_worksheet;
            }
        }
    }

    private function process_csv_file()
    {
        $this->current_smart_worksheet['name'] = basename($this->file_name);
        $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
        $this->current_smart_worksheet['file_size'] = $this->file_size;
        $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;

        $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension;
        $this->assign_database_table_fields();

        $this->smart_worksheets[] = $this->current_smart_worksheet;
    }

    private function assign_database_table_fields()
    {
        $db = Database::instance('import_excel');
        $sql = "SHOW TABLE STATUS WHERE name = '".$this->current_smart_worksheet['table_name']."'";
        $result = $db->query(Database::SELECT, $sql, FALSE)->as_array();
        if(count($result))
        {
            $when_table_created = $result[0]['Create_time'];
            $when_file_copied_as_date = strtotime($this->when_file_copied);
            $when_table_created_as_date = strtotime($when_table_created);
            if($when_file_copied_as_date > $when_table_created_as_date)
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoreimport';
            }
            else
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.isuptodate';
            }
            $this->current_smart_worksheet['when_table_created'] = $when_table_created;
        }
        else
        {
            $this->current_smart_worksheet['when_table_created'] = 'backend.application.import.status.tabledoesnotexist';
            $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoimport';
        }
    }

    public function add_smart_worksheets_to(Array $smart_worksheets = array())
    {
        return array_merge($smart_worksheets, $this->get_smart_worksheets());
    }

    public function get_smart_worksheets()
    {
        if ( ! is_array($this->smart_worksheets))
        {
            return array();
        }

        return $this->smart_worksheets;
    }

}
</code>```

In a code review I was told that it might be better not to have a helper class like this but to keep the bulk of the code in the controller action method itself. The argumentation was that you should be able to look at the code in a controller action and see what it does instead of having it call external helper classes outside of itself. I disagree. My argumentation is:

you should create a helper class anytime it makes code clearer, as in this case, it abstracts away the fact that some files have one worksheet or many worksheets in them, and allows for easy future extension, if, say, we want to also import from sqlite files or even directories with files in them, this class abstraction would be able to handle this nicely.

moving the bulk of the code from this helper class back into the controller would force me to create internal variables in the controller which make sense for this particular action, but may or may not make sense to other action methods within the controller.

if I were programming this in C# I would make this helper class a nested class which would literally be an internal data structure that is inside of and only available to the controller class, but since PHP does not allow nested classes, I need to call a class "outside" the controller to help manage this abstraction in a way that makes the code clear and readable

Based on your experience of programming in the MVC pattern, should the above helper class be refactored back into the controller or not?

答:
I agree with you Edward.

Your ImportController does what a Controller is meant to do. It generates the list of files for the user to view and act on, it then passes that list to the View for it to display. I am presuming that you have a process action or similar which is handles the request when a user has selected a file, this file is then passed on to the Helper in question.

The Helper is a perfect example of abstraction and entirely justified in its usage and existence. It is not coupled with the Controller in anyway and doesn't need to be. The Helper could be easily used in other scenarios where the Controller is not present, for example a CRON task, a public API which users can call programmatically without your ImportController.

Your right on the ball with this one. Stick it to 'em!

Body:
I am writing an CSV/Excel-->MySQL import manager for an MVC application (Kohana/PHP).

I have a controller named "ImportManager" which has an action named "index" (default) which displays in a grid all the valid .csv and .xls files that are in a specific directory and ready for import. The user can then choose the files he wants to import.

However, since .csv files import into one database table and .xls files import into multiple database tables, I needed to handle this abstraction. Hence I created a helper class called SmartImportFile to which I send each file be it .csv or .xls and then I get then ask this "smart" object to add the worksheets from that file (be they one or many) to my collection. Here is my action method in PHP code:

public function action_index()
{
    $view = new View('backend/application/importmanager');

    $smart_worksheets = array();
    $raw_files = glob('/data/import/*.*');
    if (count($raw_files) > 0)
    {
        foreach ($raw_files as $raw_file)
        {
            $smart_import_file = new Backend_Application_Smartimportfile($raw_file);
            $smart_worksheets = $smart_import_file->add_smart_worksheets_to($smart_worksheets);
        }
    }
    $view->set('smart_worksheets', $smart_worksheets);

    $this->request->response = $view;
}

The SmartImportFile class looks like this:

class Backend_Application_Smartimportfile
{
    protected $file_name;
    protected $file_extension;
    protected $file_size;
    protected $when_file_copied;
    protected $file_name_without_extension;
    protected $path_info;
    protected $current_smart_worksheet = array();

    protected $smart_worksheets = array();

    public function __construct($file_name)
    {
        $this->file_name = $file_name;
        $this->file_name_without_extension = current(explode('.', basename($this->file_name)));

        $this->path_info = pathinfo($this->file_name);
        $this->when_file_copied = date('Y-m-d H:i:s', filectime($this->file_name));
        $this->file_extension = strtolower($this->path_info['extension']);
        $this->file_extension = strtolower(pathinfo($this->file_name, PATHINFO_EXTENSION));
        if(in_array($this->file_extension, array('csv','xls','xlsx')))
        {
            $this->current_smart_worksheet = array();
            $this->process_file();
        }
    }

    private function process_file()
    {
        $this->file_size = filesize($this->file_name);
        if(in_array($this->file_extension, array('xls','xlsx')))
        {
            if($this->file_size < 4000000)
            {
                $this->process_all_worksheets_of_excel_file();
            }
        }
        else if($this->file_extension == 'csv')
        {
            $this->process_csv_file();
        }

    }

    private function process_all_worksheets_of_excel_file()
    {
        $worksheet_names = Import_Driver_Excel::get_worksheet_names_as_array($this->file_name);
        if (count($worksheet_names) > 0)
        {
            foreach ($worksheet_names as $worksheet_name)
            {
                $this->current_smart_worksheet['name'] = basename($this->file_name).' ('.$worksheet_name.')';
                $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
                $this->current_smart_worksheet['file_size'] = $this->file_size;
                $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;
                $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension.'__'.$worksheet_name;
                $this->assign_database_table_fields();
                $this->smart_worksheets[] = $this->current_smart_worksheet;
            }
        }
    }

    private function process_csv_file()
    {
        $this->current_smart_worksheet['name'] = basename($this->file_name);
        $this->current_smart_worksheet['kind'] = strtoupper($this->file_extension);
        $this->current_smart_worksheet['file_size'] = $this->file_size;
        $this->current_smart_worksheet['when_file_copied'] = $this->when_file_copied;

        $this->current_smart_worksheet['table_name'] = $this->file_name_without_extension;
        $this->assign_database_table_fields();

        $this->smart_worksheets[] = $this->current_smart_worksheet;
    }

    private function assign_database_table_fields()
    {
        $db = Database::instance('import_excel');
        $sql = "SHOW TABLE STATUS WHERE name = '".$this->current_smart_worksheet['table_name']."'";
        $result = $db->query(Database::SELECT, $sql, FALSE)->as_array();
        if(count($result))
        {
            $when_table_created = $result[0]['Create_time'];
            $when_file_copied_as_date = strtotime($this->when_file_copied);
            $when_table_created_as_date = strtotime($when_table_created);
            if($when_file_copied_as_date > $when_table_created_as_date)
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoreimport';
            }
            else
            {
                $this->current_smart_worksheet['status'] = 'backend.application.import.status.isuptodate';
            }
            $this->current_smart_worksheet['when_table_created'] = $when_table_created;
        }
        else
        {
            $this->current_smart_worksheet['when_table_created'] = 'backend.application.import.status.tabledoesnotexist';
            $this->current_smart_worksheet['status'] = 'backend.application.import.status.needtoimport';
        }
    }

    public function add_smart_worksheets_to(Array $smart_worksheets = array())
    {
        return array_merge($smart_worksheets, $this->get_smart_worksheets());
    }

    public function get_smart_worksheets()
    {
        if ( ! is_array($this->smart_worksheets))
        {
            return array();
        }

        return $this->smart_worksheets;
    }

}

In a code review I was told that it might be better not to have a helper class like this but to keep the bulk of the code in the controller action method itself. The argumentation was that you should be able to look at the code in a controller action and see what it does instead of having it call external helper classes outside of itself. I disagree. My argumentation is:

you should create a helper class anytime it makes code clearer, as in this case, it abstracts away the fact that some files have one worksheet or many worksheets in them, and allows for easy future extension, if, say, we want to also import from sqlite files or even directories with files in them, this class abstraction would be able to handle this nicely.

moving the bulk of the code from this helper class back into the controller would force me to create internal variables in the controller which make sense for this particular action, but may or may not make sense to other action methods within the controller.

if I were programming this in C# I would make this helper class a nested class which would literally be an internal data structure that is inside of and only available to the controller class, but since PHP does not allow nested classes, I need to call a class "outside" the controller to help manage this abstraction in a way that makes the code clear and readable

Based on your experience of programming in the MVC pattern, should the above helper class be refactored back into the controller or not?


问:
Twilio TwiML app XML error
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

```<code>[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}
</code>```

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

```<code><?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>
</code>```

答:
I have found I can fix it by replacing

```<code>return TwiML(response);
</code>```

with

```<code>return new TwiMLResult(response.ToString(), new UTF8Encoding());
</code>```

Appears to be some kind of encoding issue using the first method.

Title: Twilio TwiML app XML error

Body:
I have a TwiML app with this code in the Connect action of the CallController. This code is taken straight from the Twilio demos.

[HttpPost]
public virtual ActionResult Connect(string phoneNumber, string called)
{
    var response = new VoiceResponse();

    var dial = new Dial(callerId: "+6138595????");
    if (phoneNumber != null)
    {
        dial.Number(phoneNumber);
    }
    else
    {
        dial.Client("support_agent");
    }
    response.Dial(dial);

    return TwiML(response);
}

When this is called it raises the error "Data at the root level is invalid. Line 1, position 1."

The XML this generates is

<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+6138595????">
    <Client>support_agent</Client>
  </Dial>
</Response>

Body:
I have found I can fix it by replacing

return TwiML(response);

with

return new TwiMLResult(response.ToString(), new UTF8Encoding());

Appears to be some kind of encoding issue using the first method.


问:
Set Value in a field that has a default value of "0.00" set on it already
I am calling the setValue function on a particular field, however the field has a default value of "0.00" set on it. Now what happens is the value that I pass in with the setValue function is appended to the '0.00'</p>

答:
Just call clearValue on the field before you setValue to it. clearValue clears a textarea or a text input element's value.</p>

```<code>browser
 .clearValue('input')
 .setValue('input', '123')
</code>```

Body:
Just call clearValue on the field before you setValue to it. clearValue clears a textarea or a text input element's value.

browser
 .clearValue('input')
 .setValue('input', '123')


问:
Java - public static double not returning
I'm trying to learning Java from zero. I have an exercise that after reading it all over again I can't find why doesn't work. Researching on Google and StackOverflow returned to zero results...

Main objective is to translate dollars to pesetas by just multiplying by a number. I have to use two functions and call them on "main".

My problem is that "convertToPesetas" isn't taking the returned double of "askDollars". Can someone hand me a rope?

```<code>import java.util.Scanner;

public class Converter
{
    public static void main(String[] args){
        askDollars();
        convertToPesetas();
    }

    public static double askDollars(){
        System.out.println("Type the quantity of dollars:");
        Scanner keyboard= new Scanner(System.in);
        double dollars= keyboard.nextDouble();
        System.out.println("Dollars: "+dollars);
        return dollars;
    }
    public static double convertToPesetas(double dollars){
        double pesetas = pesetas*166.386;
        System.out.println(dollars+ "€ equals to: "+pesetas+" pesetas");
        return pesetas;
    }

}
</code>```

答:
Because you're not storing or supplying that value:

```<code>askDollars();
convertToPesetas();
</code>```

Save the returned value in a variable and pass that variable to the next method:

```<code>double dollars = askDollars();
convertToPesetas(dollars);
</code>```

Note: convertToPesetas also returns a value.  You don't seem to need it to do that.  But, you could use that if you take your design in a different direction.  As an academic exercise for your next step, consider three methods:

One which asks for the user input.

One which converts the dollars value to the pesetas value.  This has no input or output, just a method argument and a return value.

One which prints the output.

Each method would do exactly one, simple thing.  And when you have this, you'll find that the second method is free to easily be moved to other objects, etc. because it's entirely independent and not coupled to the user interface in any way.

Body:
I'm trying to learning Java from zero. I have an exercise that after reading it all over again I can't find why doesn't work. Researching on Google and StackOverflow returned to zero results...

Main objective is to translate dollars to pesetas by just multiplying by a number. I have to use two functions and call them on "main".

My problem is that "convertToPesetas" isn't taking the returned double of "askDollars". Can someone hand me a rope?

import java.util.Scanner;

public class Converter
{
    public static void main(String[] args){
        askDollars();
        convertToPesetas();
    }

    public static double askDollars(){
        System.out.println("Type the quantity of dollars:");
        Scanner keyboard= new Scanner(System.in);
        double dollars= keyboard.nextDouble();
        System.out.println("Dollars: "+dollars);
        return dollars;
    }
    public static double convertToPesetas(double dollars){
        double pesetas = pesetas*166.386;
        System.out.println(dollars+ "€ equals to: "+pesetas+" pesetas");
        return pesetas;
    }

}

Body:
Because you're not storing or supplying that value:

askDollars();
convertToPesetas();

Save the returned value in a variable and pass that variable to the next method:

double dollars = askDollars();
convertToPesetas(dollars);

Note: convertToPesetas also returns a value.  You don't seem to need it to do that.  But, you could use that if you take your design in a different direction.  As an academic exercise for your next step, consider three methods:

One which asks for the user input.

One which converts the dollars value to the pesetas value.  This has no input or output, just a method argument and a return value.

One which prints the output.

Each method would do exactly one, simple thing.  And when you have this, you'll find that the second method is free to easily be moved to other objects, etc. because it's entirely independent and not coupled to the user interface in any way.


问:
WebView should use same cookies as fetch
I have done a sign in to my app using the native fetch API. I now need to load an image, so am loading it in a <WebView>, however the webview is not using the cookies from the fetch API outside of the webview. Is it possible to tell webview to use those cookies?

答:
You can post a message containing your cookies content to your Webview using postMessage().

You need to get the ref of the Webview then post the message to your webview.

```<code>let webviewRef = null;

const cookiesContent = 'My cookies bla bla bla'

render() {
    return (
        <WebView
            onLoad={() => webviewRef.postMessage(cookiesContent)}
            ref={webview => { webviewRef = webview; }}
            source={{ uri: 'https://YourUrl' }}
        />
    );
}
</code>```

Then in your Website you can create the cookies and use it

```<code><script>
    document.addEventListener("message", function(data) {
        document.cookie=`cookiesName=${data.data}`;
    });
</script>
</code>```

If you aren't the owner of the website you can still try to inject the javascript with injectedJavaScript props of Webview Component.

```<code>const JsCode = 'document.addEventListener("message", function(data) {
        document.cookie=`cookiesName=${data.data}`;
    });';

  <WebView
        injectedJavaScript={JsCode}
        onLoad={() => webviewRef.postMessage(cookiesContent)}
        ref={webview => { webviewRef = webview; }}
        source={{ uri: 'https://YourUrl' }}
    />
</code>```

Body:
You can post a message containing your cookies content to your Webview using postMessage().

You need to get the ref of the Webview then post the message to your webview.

let webviewRef = null;

const cookiesContent = 'My cookies bla bla bla'

render() {
    return (
        <WebView
            onLoad={() => webviewRef.postMessage(cookiesContent)}
            ref={webview => { webviewRef = webview; }}
            source={{ uri: 'https://YourUrl' }}
        />
    );
}

Then in your Website you can create the cookies and use it

<script>
    document.addEventListener("message", function(data) {
        document.cookie=`cookiesName=${data.data}`;
    });
</script>

If you aren't the owner of the website you can still try to inject the javascript with injectedJavaScript props of Webview Component.

const JsCode = 'document.addEventListener("message", function(data) {
        document.cookie=`cookiesName=${data.data}`;
    });';

  <WebView
        injectedJavaScript={JsCode}
        onLoad={() => webviewRef.postMessage(cookiesContent)}
        ref={webview => { webviewRef = webview; }}
        source={{ uri: 'https://YourUrl' }}
    />


问:
where can i find (edit) the jobs that are going to run in cron.php of drupal?
How can i edit the list of jobs that are going to run at running time of /DocRoot/cron.php in drupal??

in other words, where can i edit the list of drupal jobs that return from drupal_cron_run?

Thanks for your help

答:
I've never heard or read that an UI for it exists. My first intention on your question was:

```<code>konnertz@auedv20:/var/www/vhosts/drupal-6.20$ grep hook_cron * -rn
includes/common.inc:2715:  // Try to allocate enough time to run all the hook_cron implementations.
modules/node/node.module:119: * Implementation of hook_cron().
modules/ping/ping.module:23: * Implementation of hook_cron().
modules/aggregator/aggregator.module:285: * Implementation of hook_cron().
modules/openid/openid.module:669: * Implementation of hook_cron().
modules/trigger/trigger.module:141: *   because some hooks (e.g., hook_cron()) do not have operations.
modules/trigger/trigger.module:314: * Implementation of hook_cron().
modules/search/search.module:261: * Implementation of hook_cron().
modules/dblog/dblog.module:99: * Implementation of hook_cron().
modules/system/system.module:1274: * Implementation of hook_cron().
modules/filter/filter.module:161: * Implementation of hook_cron().
modules/statistics/statistics.module:177: * Implementation of hook_cron().
modules/update/update.module:294: * Implementation of hook_cron().
modules/poll/poll.module:155: * Implementation of hook_cron().
</code>```

This is  a fresh installation. Otherwise there would be more in sites/all/modules.

To not run some jobs one could either comment out the hook_cron in the modules or in
includes/common.php replace line 2747

```<code>     module_invoke_all('cron');
</code>```

with the concrete invoke methods, adhoc i am not sure how to do that.
This is all for drupal 6.

Body:
I've never heard or read that an UI for it exists. My first intention on your question was:

konnertz@auedv20:/var/www/vhosts/drupal-6.20$ grep hook_cron * -rn
includes/common.inc:2715:  // Try to allocate enough time to run all the hook_cron implementations.
modules/node/node.module:119: * Implementation of hook_cron().
modules/ping/ping.module:23: * Implementation of hook_cron().
modules/aggregator/aggregator.module:285: * Implementation of hook_cron().
modules/openid/openid.module:669: * Implementation of hook_cron().
modules/trigger/trigger.module:141: *   because some hooks (e.g., hook_cron()) do not have operations.
modules/trigger/trigger.module:314: * Implementation of hook_cron().
modules/search/search.module:261: * Implementation of hook_cron().
modules/dblog/dblog.module:99: * Implementation of hook_cron().
modules/system/system.module:1274: * Implementation of hook_cron().
modules/filter/filter.module:161: * Implementation of hook_cron().
modules/statistics/statistics.module:177: * Implementation of hook_cron().
modules/update/update.module:294: * Implementation of hook_cron().
modules/poll/poll.module:155: * Implementation of hook_cron().

This is  a fresh installation. Otherwise there would be more in sites/all/modules.

To not run some jobs one could either comment out the hook_cron in the modules or in
includes/common.php replace line 2747

     module_invoke_all('cron');

with the concrete invoke methods, adhoc i am not sure how to do that.
This is all for drupal 6.


问:
Jekyll render partial inside markdown
We are attempting to move sites to Jekyll, and have a BS4 theme.  In order to make it user friendly to the content managers, I've placed the following in my page layout:

```<code><div class="container">
     <div class="row">
          <div class="col-md-12">
                {{ content }}
          </div>
    </div>
</div>
</code>```

However, I'd like to create a liquid tag or filter to allow for full-width images to be injected into the middle of the page.   This would close the three container divs above the image, write out the image, and the create new divs below, and continue to write the markdown file.  i.e.

```<code>{% fullwidth xenia-map.png %}
</code>```

would produce something like this in the middle of the page:

```<code>       </div>
    </div>
</div>
<img src="input.jpg" class="img-responsive" />
<div class="container">
     <div class="row">
          <div class="col-md-12">
</code>```

I have been able to create a filter and a tag (class) that will do 80%, however neither will write out closing  tags at the beginning of the output.  I just get the  tag.

Here's my class:

```<code>class FullWidth < Liquid::Tag
    def initialize(tag_name, image, tokens)
    super
    @image = image.strip
    end

    def render(context)
        "</div></div></div><img src='uploads/#{@image}' class='img-responsive'>"
    end
end

Liquid::Template.register_tag('fw', FullWidth)
</code>```

答:
Your problem looks like an escaping issue.

Although I like the simplicity of your solution, I would consider two alternatives. The first ('include' solution) because it is easier to implement (anyone can make that one work). The second one ('javascript' solution) because it will allow your content editors to use a regular/graphical markdown editor and it will keep your markdown clean and reusable for other purposes.

'Include' solution

Just put an include in your markdown/html:

```<code>{% include fullwidth.html image="/uploads/xenia-map.png" %}
</code>```

... and use this 'fullwidth.html':

```<code>    </div>
  </div>
</div>
<img src="{{ include.image }}" class="img-responsive" />
<div class="container">
  <div class="row">
    <div class="col-md-12">
</code>```

'Javascript' solution

Use this markdown (or let a regular/graphical markdown editor generate this):

```<code>![Xenia map](/uploads/xenia-map.png){: .fullwidth}
</code>```

... and use this jQuery:

```<code>$(document).ready(function(){
  $('img.fullwidth').each(function() {
        var img = $(this).parent().html();
        $(this).unwrap();
        document.body.innerHTML = document.body.innerHTML.replace(img,
            '</div></div></div>'+img+'<div class="container"><div class="row"><div class="col-md-12">');;
  });
});
</code>```

Title: Jekyll render partial inside markdown

Body:
We are attempting to move sites to Jekyll, and have a BS4 theme.  In order to make it user friendly to the content managers, I've placed the following in my page layout:

                {{ content }}

However, I'd like to create a liquid tag or filter to allow for full-width images to be injected into the middle of the page.   This would close the three container divs above the image, write out the image, and the create new divs below, and continue to write the markdown file.  i.e.

{% fullwidth xenia-map.png %}

would produce something like this in the middle of the page:

I have been able to create a filter and a tag (class) that will do 80%, however neither will write out closing  tags at the beginning of the output.  I just get the  tag.

Here's my class:

class FullWidth < Liquid::Tag
    def initialize(tag_name, image, tokens)
    super
    @image = image.strip
    end

    def render(context)
        "

"
    end
end

Liquid::Template.register_tag('fw', FullWidth)

Body:
Your problem looks like an escaping issue.

Although I like the simplicity of your solution, I would consider two alternatives. The first ('include' solution) because it is easier to implement (anyone can make that one work). The second one ('javascript' solution) because it will allow your content editors to use a regular/graphical markdown editor and it will keep your markdown clean and reusable for other purposes.

'Include' solution

Just put an include in your markdown/html:

{% include fullwidth.html image="/uploads/xenia-map.png" %}

... and use this 'fullwidth.html':

    </div>
  </div>
</div>
<img src="{{ include.image }}" class="img-responsive" />
<div class="container">
  <div class="row">
    <div class="col-md-12">

'Javascript' solution

Use this markdown (or let a regular/graphical markdown editor generate this):

![Xenia map](/uploads/xenia-map.png){: .fullwidth}

... and use this jQuery:

$(document).ready(function(){
  $('img.fullwidth').each(function() {
        var img = $(this).parent().html();
        $(this).unwrap();
        document.body.innerHTML = document.body.innerHTML.replace(img,
            '</div></div></div>'+img+'<div class="container"><div class="row"><div class="col-md-12">');;
  });
});