问:
IDX10603: The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits. KeySize reported: '32'. Parameter name: key.KeySize
I was just working with Asp.Net Core Web API, and implementing Authentication. And I am calling this API from an Angular Application. But I am always getting an error as below.

IDX10603: The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits. KeySize reported: '32'. Parameter name: key.KeySize

Below is my code for ConfigureServices in Startup.cs file.

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<APIContext>(option => option.UseInMemoryDatabase("AngularApp"));

                services.AddCors(options => options.AddPolicy("Cors", builder =>
                {
                    builder.AllowAnyOrigin().
                    AllowAnyMethod().
                    AllowAnyHeader();
                }
                ));

                var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret phase"));

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        IssuerSigningKey = signinKey,
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        ValidateLifetime = false,
                        ValidateIssuerSigningKey = true,
                        ValidateActor = false,
                        ClockSkew = TimeSpan.Zero
                    };
                });
                services.AddMvc();

                var serviceProvider = services.BuildServiceProvider();
                return serviceProvider;
            }
</code>```

And I am using JwtPackagein my controller as follows.

```<code>JwtPackage CreateJwtToken(User usr)
        {
            var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authnetication"));
            var signInCredentials = new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Sub,usr.Id)
            };
            var jwt = new JwtSecurityToken(claims: claims, signingCredentials: signInCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return new JwtPackage() { FirstName = usr.FirstName, Token = encodedJwt };
        }
</code>```

Can you please help me to fix this issue? Thank you.

答:
Ah, it was my mistake, a simple one. I was not providing enough characters for the secret key name.

I changed my signinkey to this one,

```<code>var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authentication"));
</code>```

from,

```<code>var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret phase"));
</code>```

That solved my issue, as the HmacSha256 in the line SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)should be greater than 128 bits. In short, just use a long string as the key.

Body:
I was just working with Asp.Net Core Web API, and implementing Authentication. And I am calling this API from an Angular Application. But I am always getting an error as below.

IDX10603: The algorithm: 'HS256' requires the SecurityKey.KeySize to be greater than '128' bits. KeySize reported: '32'. Parameter name: key.KeySize

Below is my code for ConfigureServices in Startup.cs file.

public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<APIContext>(option => option.UseInMemoryDatabase("AngularApp"));

                services.AddCors(options => options.AddPolicy("Cors", builder =>
                {
                    builder.AllowAnyOrigin().
                    AllowAnyMethod().
                    AllowAnyHeader();
                }
                ));

                var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret phase"));

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        IssuerSigningKey = signinKey,
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        ValidateLifetime = false,
                        ValidateIssuerSigningKey = true,
                        ValidateActor = false,
                        ClockSkew = TimeSpan.Zero
                    };
                });
                services.AddMvc();

                var serviceProvider = services.BuildServiceProvider();
                return serviceProvider;
            }

And I am using JwtPackagein my controller as follows.

JwtPackage CreateJwtToken(User usr)
        {
            var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authnetication"));
            var signInCredentials = new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Sub,usr.Id)
            };
            var jwt = new JwtSecurityToken(claims: claims, signingCredentials: signInCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            return new JwtPackage() { FirstName = usr.FirstName, Token = encodedJwt };
        }

Can you please help me to fix this issue? Thank you.

Body:
Ah, it was my mistake, a simple one. I was not providing enough characters for the secret key name.

I changed my signinkey to this one,

var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is my custom Secret key for authentication"));

from,

var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret phase"));

That solved my issue, as the HmacSha256 in the line SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)should be greater than 128 bits. In short, just use a long string as the key.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Git Push Error in Android Studio
How to resolve

EmptyThrowable: Repository not found for root /path local, error while pushing my code on git don't know why I am getting this error

答: may be you are not login your github account correctly. Login again and try.</p>

ContentLicense: CC BY-SA 3.0

Title: Git Push Error in Android Studio


问:
gflags linker-error: undefined reference
I installed gflags:

```<code>$ ls /usr/local/lib/ | grep gflags
libgflags.a
libgflags_nothreads.a
$ ls /usr/local/include/ | grep gflags
gflags
</code>```

And included <gflags/gflags.h>

```<code>#include <gflags/gflags.h>

DEFINE_bool(a, false, "test");

int main(int argc, char **argv) {
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    return 0;
}
</code>```

But i got a linker-error!

```<code>$ g++ -lgflags a.cpp
/tmp/cchKYAWZ.o: In function `main':
/home/wonter/gflags-2.2.1/build/a.cpp:6: undefined reference to `google::ParseCommandLineFlags(int*, char***, bool)'
/tmp/cchKYAWZ.o: In function `__static_initialization_and_destruction_0(int, int)':
/home/wonter/gflags-2.2.1/build/a.cpp:3: undefined reference to `google::FlagRegisterer::FlagRegisterer<bool>(char const*, char const*, char const*, bool*, bool*)'
collect2: error: ld returned 1 exit status
</code>```

I tried $ g++ /usr/local/lib/libgflags.a a.cpp -o test, but got a same error.

My platform is Ubuntu 17.10, GCC version is gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)

Is it because of my GCC version of the problem?

答:
You need to link against gflags not include the archive in compile command line:

```<code>$ g++ -Wl,-Bstatic -lgflags,--as-needed a.cpp -o test
</code>```

If there is only a static library, g++ linker can handle that. So basically you just need to tell compiler/linker that you need gflags:

```<code>$ g++ a.cpp -o test -lgflags
</code>```

Body:
I installed gflags:

$ ls /usr/local/lib/ | grep gflags
libgflags.a
libgflags_nothreads.a
$ ls /usr/local/include/ | grep gflags
gflags

And included <gflags/gflags.h>

#include <gflags/gflags.h>

DEFINE_bool(a, false, "test");

int main(int argc, char **argv) {
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    return 0;
}

But i got a linker-error!

$ g++ -lgflags a.cpp
/tmp/cchKYAWZ.o: In function `main':
/home/wonter/gflags-2.2.1/build/a.cpp:6: undefined reference to `google::ParseCommandLineFlags(int*, char***, bool)'
/tmp/cchKYAWZ.o: In function `__static_initialization_and_destruction_0(int, int)':
/home/wonter/gflags-2.2.1/build/a.cpp:3: undefined reference to `google::FlagRegisterer::FlagRegisterer<bool>(char const*, char const*, char const*, bool*, bool*)'
collect2: error: ld returned 1 exit status

I tried $ g++ /usr/local/lib/libgflags.a a.cpp -o test, but got a same error.

My platform is Ubuntu 17.10, GCC version is gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)

Is it because of my GCC version of the problem?

Body:
You need to link against gflags not include the archive in compile command line:

$ g++ -Wl,-Bstatic -lgflags,--as-needed a.cpp -o test

If there is only a static library, g++ linker can handle that. So basically you just need to tell compiler/linker that you need gflags:

$ g++ a.cpp -o test -lgflags


问:
Redirect to a particular viewcontroller when redirecting from reset password mail ios
In my app I have a Home viewcontroller from where user can login, reset password, and skip to other pages.

If I click "Forgot password", I will get a mail where I can reset password. When I redirect back from email, I want the app to stay in the same Home viewcontroller.

If my flow is : click on "Forgot password" from home viewcontroller -> then move to ForgotPassword viewcontrollers -> exit app -> then go to my mail and do reset password , even then I want the app to open in the home page itself when it comes to foreground, not on any other viewcontrollers from where I exited the app or minimised the app.

How can I do this? Thank you

答:
You can do it by manage flag after change password and go app on background.

Let me explain, In the AppDelegate take one global var isChangedPwd = false. When end use will go on reset password screen and successfully reset password then you need to make isChangedPwd = true and then manage flag in applicationDidEnterBackground like below

```<code>func applicationDidEnterBackground(_ application: UIApplication) {
     if isChangedPwd {
        exit(0)
     }
}
</code>```

It means when your isChangedPwd will be true and App will goes in background then your app will exit and will be launch at initial level.

NOTE : If you don't want to use exit(0) and not start app at initial level then you can redirect to Home page by below code.

```<code>func applicationDidEnterBackground(_ application: UIApplication) {
         if isChangedPwd {
            for viewCon in (self.navigationController?.viewControllers)! {
              if viewCon is HomePageViewController {
                self.navigationController?.popToViewController(viewCon, animated: true)
                break
              }
            }
        }
    }
</code>```

Body:
You can do it by manage flag after change password and go app on background.

Let me explain, In the AppDelegate take one global var isChangedPwd = false. When end use will go on reset password screen and successfully reset password then you need to make isChangedPwd = true and then manage flag in applicationDidEnterBackground like below

func applicationDidEnterBackground(_ application: UIApplication) {
     if isChangedPwd {
        exit(0)
     }
}

It means when your isChangedPwd will be true and App will goes in background then your app will exit and will be launch at initial level.

NOTE : If you don't want to use exit(0) and not start app at initial level then you can redirect to Home page by below code.

func applicationDidEnterBackground(_ application: UIApplication) {
         if isChangedPwd {
            for viewCon in (self.navigationController?.viewControllers)! {
              if viewCon is HomePageViewController {
                self.navigationController?.popToViewController(viewCon, animated: true)
                break
              }
            }
        }
    }


问:
Python Boolean mask using a dictionary
I am trying to compute a value given a condition on the time of day. The vectors/series are the net solar radiation for a given hour and the time the data was colected. When the value was obtained during daylight I have to multiply said value by .1, and when the value was obtained in nighttime I multiply the value by .5. The thing is that the daylight hours change noticeably month by month (week by week even) as the daylight dictionary shows below:

I'm trying to create a boolean mask (withindaylight) which would help me apply the calculation/multiplication WITHOUT using a for-loop over every value in the 'time' vector and and checking it against daylight dictionary which is what I'm currently doing:

```<code>def Ghr(time, Rn):
    #soil heatflux cal
    #time is a single vale of the time vector
    mon = time.strftime('%b') #strips the month

    #sunrise -sunset hours from 1st of the month (sr,ss) to end of the month
    #Jan-1st SR 8:17, Jan-31st SR 07:47
    #Jan-1st SS 16:03, Jan-31st SS 16:52

    daylight = {'Jan':('08:00', '16:25'),
            'Feb':('07:20', '17:20'),
            'Mar':('06:45', '18:40'),
            'Apr':('06:05', '20:05'),
            'May':('05:10', '20:55'),
            'Jun':('04:50', '21:25'),
            'Jul':('05:10', '21:15'),
            'Aug':('05:50', '20:30'),
            'Sep':('06:45', '19:25'),
            'Oct':('07:00', '17:30'),
            'Nov':('07:25', '16:15'),
            'Dec':('08:05', '16:00')}

    #strips the hour and minute from the daylight dictionary
    #then withindaylight is the boolean  after checking the
    #time the data was collected against the these stripped values

    daybegin = dt.strptime(daylight[mon][0], '%H:%M').time()
    dayend= dt.strptime(daylight[mon][1], '%H:%M').time()

    withindaylight = daybegin <= time.time() <= dayend

    #I want to apply the boolean mask such that it produces the following,
    #but returns a vector and not just a single value

    if withindaylight:
        return .1*Rn   #I want to return a series and not just a single value

    else:
        return .5*Rn
</code>```

答:
There were several things that needed to happen with my code:

How to make sure that each instance of my 'time' was mapped to correct month as the key from the 'daylight'...

How to extract the tuple to a separate list

conversion of the tuple holding the string into a time object in a pd.Series

converting to a mask and applying the multiplication

I solved these issues with the following code:

```<code>def Ghr(time, Rn):
    """Soil Heat flux calculator"""

    #sunrise -sunset hours from 1st of the month (sr,ss) to end of the month
    #Jan-1st SR 8:17, Jan-31st SR 07:47
    #Jan-1st SS 16:03, Jan-31st SS 16:52

    daylight = {'Jan':('08:00', '16:25'),
            'Feb':('07:20', '17:20'),
            'Mar':('06:45', '18:40'),
            'Apr':('06:05', '20:05'),
            'May':('05:10', '20:55'),
            'Jun':('04:50', '21:25'),
            'Jul':('05:10', '21:15'),
            'Aug':('05:50', '20:30'),
            'Sep':('06:45', '19:25'),
            'Oct':('07:00', '17:30'),
            'Nov':('07:25', '16:15'),
            'Dec':('08:05', '16:00')}

    #this maps the month of 'time' as to the dictionary daylight
    #then unzips the tuple to daystart and dayend lists which
    #are then converted to pandas.Series objects for use in boolean mask
    daystart, dayend = zip(*time.dt.strftime('%b').map(daylight))

    #dt.strftime extracts the 'Mon' ('%b') from the DateTime object and
    #maps it to the dictionary and saves the morning and dusk hours respectively

    #conversion to pandas series
    daystart=pd.Series(pd.to_datetime(daystart).time)
    dayend=pd.Series(pd.to_datetime(dayend).time)
    t=pd.Series(time.dt.time)
    #the above converts the strings to datetime objects and saves it
    #to a pandas Series, t is just a to_Series conversion

    light_mask = t.between(daystart, dayend)
    #this mask will be used to designate which values get multiplied by
    #either .1 or .5

    #True values get multiplied by .1 (The inversion is because
    #pd.Series.where() only changes the values which are False)
    Ghr = Rn.where(np.invert(light_mask), Rn*.1)

    #False values multiplied by *.5
    Ghr = Rn.where(light_mask, Ghr*.5)

    return Ghr
</code>```

Title: Python Boolean mask using a dictionary

Body:
I am trying to compute a value given a condition on the time of day. The vectors/series are the net solar radiation for a given hour and the time the data was colected. When the value was obtained during daylight I have to multiply said value by .1, and when the value was obtained in nighttime I multiply the value by .5. The thing is that the daylight hours change noticeably month by month (week by week even) as the daylight dictionary shows below:

I'm trying to create a boolean mask (withindaylight) which would help me apply the calculation/multiplication WITHOUT using a for-loop over every value in the 'time' vector and and checking it against daylight dictionary which is what I'm currently doing:

def Ghr(time, Rn):
    #soil heatflux cal
    #time is a single vale of the time vector
    mon = time.strftime('%b') #strips the month

    #sunrise -sunset hours from 1st of the month (sr,ss) to end of the month
    #Jan-1st SR 8:17, Jan-31st SR 07:47
    #Jan-1st SS 16:03, Jan-31st SS 16:52

    daylight = {'Jan':('08:00', '16:25'),
            'Feb':('07:20', '17:20'),
            'Mar':('06:45', '18:40'),
            'Apr':('06:05', '20:05'),
            'May':('05:10', '20:55'),
            'Jun':('04:50', '21:25'),
            'Jul':('05:10', '21:15'),
            'Aug':('05:50', '20:30'),
            'Sep':('06:45', '19:25'),
            'Oct':('07:00', '17:30'),
            'Nov':('07:25', '16:15'),
            'Dec':('08:05', '16:00')}

    #strips the hour and minute from the daylight dictionary
    #then withindaylight is the boolean  after checking the
    #time the data was collected against the these stripped values

    daybegin = dt.strptime(daylight[mon][0], '%H:%M').time()
    dayend= dt.strptime(daylight[mon][1], '%H:%M').time()

    withindaylight = daybegin <= time.time() <= dayend

    #I want to apply the boolean mask such that it produces the following,
    #but returns a vector and not just a single value

    if withindaylight:
        return .1*Rn   #I want to return a series and not just a single value

    else:
        return .5*Rn

Body:
There were several things that needed to happen with my code:

How to make sure that each instance of my 'time' was mapped to correct month as the key from the 'daylight'...

How to extract the tuple to a separate list

conversion of the tuple holding the string into a time object in a pd.Series

converting to a mask and applying the multiplication

I solved these issues with the following code:

def Ghr(time, Rn):
    """Soil Heat flux calculator"""

    #sunrise -sunset hours from 1st of the month (sr,ss) to end of the month
    #Jan-1st SR 8:17, Jan-31st SR 07:47
    #Jan-1st SS 16:03, Jan-31st SS 16:52

    daylight = {'Jan':('08:00', '16:25'),
            'Feb':('07:20', '17:20'),
            'Mar':('06:45', '18:40'),
            'Apr':('06:05', '20:05'),
            'May':('05:10', '20:55'),
            'Jun':('04:50', '21:25'),
            'Jul':('05:10', '21:15'),
            'Aug':('05:50', '20:30'),
            'Sep':('06:45', '19:25'),
            'Oct':('07:00', '17:30'),
            'Nov':('07:25', '16:15'),
            'Dec':('08:05', '16:00')}

    #this maps the month of 'time' as to the dictionary daylight
    #then unzips the tuple to daystart and dayend lists which
    #are then converted to pandas.Series objects for use in boolean mask
    daystart, dayend = zip(*time.dt.strftime('%b').map(daylight))

    #dt.strftime extracts the 'Mon' ('%b') from the DateTime object and
    #maps it to the dictionary and saves the morning and dusk hours respectively

    #conversion to pandas series
    daystart=pd.Series(pd.to_datetime(daystart).time)
    dayend=pd.Series(pd.to_datetime(dayend).time)
    t=pd.Series(time.dt.time)
    #the above converts the strings to datetime objects and saves it
    #to a pandas Series, t is just a to_Series conversion

    light_mask = t.between(daystart, dayend)
    #this mask will be used to designate which values get multiplied by
    #either .1 or .5

    #True values get multiplied by .1 (The inversion is because
    #pd.Series.where() only changes the values which are False)
    Ghr = Rn.where(np.invert(light_mask), Rn*.1)

    #False values multiplied by *.5
    Ghr = Rn.where(light_mask, Ghr*.5)

    return Ghr


问:
Error 1053 the service did not respond to the start or control request in a timely fashion
I have created and installed a service a couple of times. Initially it was working fine, but after some changes in the service Code it start giving the error when I restart the service in Services.msc :

Error 1053: the service did not respond to the start or control request in a    timely fashion

Code:

```<code>public partial class AutoSMS : ServiceBase
{
    public AutoSMS()
    {
        InitializeComponent();
        eventLog1.Clear();

        if (!System.Diagnostics.EventLog.SourceExists("MySource"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";

        Timer checkForTime = new Timer(5000);
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;

    }

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("In OnStart");
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In onStop.");
    }

    void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {
        string Time = "15:05:00";
        DateTime dateTime = DateTime.ParseExact(Time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

        if (DateTime.Now == dateTime) ;
            eventLog1.WriteEntry(Time);
    }
}
</code>```

Here is my main method code

```<code>static void Main()
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new AutoSMS()
    };
    ServiceBase.Run(ServicesToRun);
}
</code>```

I also tried the following steps :

Go to Start > Run > and type regedit

Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control

With the control folder selected, right click in the pane on the right and - select new DWORD Value

Name the new DWORD: ServicesPipeTimeout

Right-click ServicesPipeTimeout, and then click Modify

Click Decimal, type '180000', and then click OK

Restart the computer

I used to install and uninstall it with following command :

```<code>installutil AutoSMS.exe

installutil /u AutoSMS.exe
</code>```

答:
I have installed .Net 4.6 on my WindowsServer computer and the error was fixed.

Your control should be this way:

Check the .net version of your WindowsService

Then check the .net version of your computer

Match that version, since it's probably not matched

Body:
I have created and installed a service a couple of times. Initially it was working fine, but after some changes in the service Code it start giving the error when I restart the service in Services.msc :

Error 1053: the service did not respond to the start or control request in a    timely fashion

Code:

public partial class AutoSMS : ServiceBase
{
    public AutoSMS()
    {
        InitializeComponent();
        eventLog1.Clear();

        if (!System.Diagnostics.EventLog.SourceExists("MySource"))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog");
        }
        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";

        Timer checkForTime = new Timer(5000);
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;

    }

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("In OnStart");
    }

    protected override void OnStop()
    {
        eventLog1.WriteEntry("In onStop.");
    }

    void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {
        string Time = "15:05:00";
        DateTime dateTime = DateTime.ParseExact(Time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

        if (DateTime.Now == dateTime) ;
            eventLog1.WriteEntry(Time);
    }
}

Here is my main method code

static void Main()
{
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new AutoSMS()
    };
    ServiceBase.Run(ServicesToRun);
}

I also tried the following steps :

Go to Start > Run > and type regedit

Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control

With the control folder selected, right click in the pane on the right and - select new DWORD Value

Name the new DWORD: ServicesPipeTimeout

Right-click ServicesPipeTimeout, and then click Modify

Click Decimal, type '180000', and then click OK

Restart the computer

I used to install and uninstall it with following command :

installutil AutoSMS.exe

installutil /u AutoSMS.exe


问:
how to integrate jade and reactjs components
What is best approach to integrate Wekan which is meteorjs app but UI is written using Jade with coreui template which is meteorjs app but UI is written in ReactJs. </p>

答: Maybe you need a babel plugin like "babel-plugin-transform-react-pug", to learn more, click here</p>


问:
How to increase the counter value when clicking the button in java script
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo">
      <span id="box1" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;"></span>
      <span id="box2" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box3" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box4" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box5" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box6" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box7" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box8" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box9" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box10"style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

答:
Here is your modified function to obtain the desired results.

```<code>    <div class="divInfo2">
        <input type="text" id="value" value="0">
    </div>
    <div class="IncDrc">
        <input id="incBtn" type="button" value="+" onclick="myFun('inc','box');">
        <input id="decBtn" type="button" value="-" onclick="myFun('dec','box');">
    </div>
    <div>
        <p id="demo"></p>
    </div>
</code>```

Your javascript code will be like this-

```<code> var counter = 0;
 var numBoxes = 10;

 function myFun(task, showDiv) {
     if (task == 'inc') {
         counter++;
     } else if (task == 'dec') {
         counter--;
     }

     var ele = document.getElementById(showDiv + counter);
     if (counter > numBoxes) {
         document.getElementById("incBtn").addEventListener("click", function() {
             document.getElementById("demo").innerHTML = "Limit Is Over";
         });
     } else {
         ele.style.display = "block";
     }
     if (counter > 0) {
         ele.style.display = "block";
     } else {
         document.getElementById("decBtn").addEventListener("click", function() {
             document.getElementById("demo").innerHTML = "Limit Is Over";
         });
     }
 }
</code>```

Body:
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }

      <input type="text" id="value" value="0">

      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">

Body:
Here is your modified function to obtain the desired results.

    <div class="divInfo2">
        <input type="text" id="value" value="0">
    </div>
    <div class="IncDrc">
        <input id="incBtn" type="button" value="+" onclick="myFun('inc','box');">
        <input id="decBtn" type="button" value="-" onclick="myFun('dec','box');">
    </div>
    <div>
        <p id="demo"></p>
    </div>

Your javascript code will be like this-

 var counter = 0;
 var numBoxes = 10;

 function myFun(task, showDiv) {
     if (task == 'inc') {
         counter++;
     } else if (task == 'dec') {
         counter--;
     }

     var ele = document.getElementById(showDiv + counter);
     if (counter > numBoxes) {
         document.getElementById("incBtn").addEventListener("click", function() {
             document.getElementById("demo").innerHTML = "Limit Is Over";
         });
     } else {
         ele.style.display = "block";
     }
     if (counter > 0) {
         ele.style.display = "block";
     } else {
         document.getElementById("decBtn").addEventListener("click", function() {
             document.getElementById("demo").innerHTML = "Limit Is Over";
         });
     }
 }


问:
How to display Current date in HTML?
How to display Current date (DD mon YYYY) in HTML, this has to be implemented in Php code   </p>

```<code><div class="container-fluid" style="padding: 0rem 1rem;">
  <h3>Attendance : {current_date} </h3>
  <hr>
  <p id="Page_MsgBox" style="padding: 0rem 1rem;"></p>
  <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
    {$attendance_table}
  </div>
</div>
</code>```

答:
Try this:</p>

```<code>n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
<p id="date"></p>
</code>```

Title: How to display Current date in HTML?

Body:
How to display Current date (DD mon YYYY) in HTML, this has to be implemented in Php code

Attendance : {current_date}

    {$attendance_table}

Body:
Try this:

n =  new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
<p id="date"></p>


问:
Do entry components need selectors in Angular?
Do entry components (those components which are loaded imperatively by the router and never declaratively by their selectors) need selectors?

For example:

```<code>@Component(
    selector: 'app-example', // <-- is this needed?
    // ...
)
export class ExampleComponent {}
</code>```

答:
No In angualr, A selector is not always needed, In this case you have a top component of a module that is loaded by router and displayed.

This feature is supported, and you can refer it in the docs

Body:
Do entry components (those components which are loaded imperatively by the router and never declaratively by their selectors) need selectors?

For example:

@Component(
    selector: 'app-example', // <-- is this needed?
    // ...
)
export class ExampleComponent {}


问:
Need help with text box input
It's actually a grid column but it functions just like a textbox. I need it to be able to accept numbers only, but it has to be able to accept numbers with leading 0's. What would I use as a mask to get this result? If I do any kind of numeric mask then it will cut off the leading 0's, eg 002456841. If I don't use a numeric mask, then characters will be accepted which is unacceptable.

Am I not thinking outside of the box enough with this? I was also thinking like maybe instead of a mask using a loop or something to make sure it's only numbers and erase/pop up a message if it's not...but I just don't know, I would rather just have the box so it only accepts numbers but any number.

答: Just read each key press and reject any that fall outside of your range. Implementation depends on if this is a web grid or a windows/wpf grid.</p>

ContentLicense: CC BY-SA 2.5

Title: Need help with text box input


问:
Unable to delete HDFS Corrupt files
I am unable to delete corrupt files present in my HDFS. Namenode has run into Safe mode. Total number of blocks are 980, out of which 978 have reported. When I run the following command,

```<code>sudo -u hdfs hdfs dfsadmin -report
</code>```

The report generated is,

```<code>Safe mode is ON
Configured Capacity: 58531520512 (54.51 GB)
Present Capacity: 35774078976 (33.32 GB)
DFS Remaining: 32374509568 (30.15 GB)
DFS Used: 3399569408 (3.17 GB)
DFS Used%: 9.50%
Under replicated blocks: 0
Blocks with corrupt replicas: 0
Missing blocks: 0
Missing blocks (with replication factor 1): 0
-------------------------------------------------
Live datanodes (1):

Name: 10.0.2.15:50010 (quickstart.cloudera)
Hostname: quickstart.cloudera
Decommission Status : Normal
Configured Capacity: 58531520512 (54.51 GB)
DFS Used: 3399569408 (3.17 GB)
Non DFS Used: 19777388544 (18.42 GB)
DFS Remaining: 32374509568 (30.15 GB)
DFS Used%: 5.81%
DFS Remaining%: 55.31%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 2
Last contact: Tue Nov 14 10:39:58 IST 2017
</code>```

And for the following command when executed,

```<code>sudo -u hdfs hdfs fsck /
</code>```

The output is,

```<code>Connecting to namenode via http://quickstart.cloudera:50070/fsck?ugi=hdfs&path=%2F
FSCK started by hdfs (auth:SIMPLE) from /10.0.2.15 for path / at Tue Nov 14 10:41:25 IST 2017
/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728: CORRUPT blockpool BP-1914853243-127.0.0.1-1500467607052 block blk_1073743141

/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728: MISSING 1 blocks of total size 83 B..
/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta: CORRUPT blockpool BP-1914853243-127.0.0.1-1500467607052 block blk_1073743142

/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta: MISSING 1 blocks of total size 83 B
Status: CORRUPT
Total size: 3368384392 B (Total open files size: 166 B)
Total dirs: 286
Total files:    966
Total symlinks:     0 (Files currently being written: 3)
Total blocks (validated):   980 (avg. block size 3437126 B) (Total open file blocks (not validated): 2)
********************************
UNDER MIN REPL'D BLOCKS:    2 (0.20408164 %)
dfs.namenode.replication.min:   1
CORRUPT FILES:  2
MISSING BLOCKS: 2
MISSING SIZE:       166 B
CORRUPT BLOCKS:     2
********************************
Minimally replicated blocks:    978 (99.79592 %)
Over-replicated blocks: 0 (0.0 %)
Under-replicated blocks:    0 (0.0 %)
Mis-replicated blocks:      0 (0.0 %)
Default replication factor: 1
Average block replication:  0.9979592
Corrupt blocks:     2
Missing replicas:       0 (0.0 %)
Number of data-nodes:       1
Number of racks:        1
FSCK ended at Tue Nov 14 10:41:26 IST 2017 in 774 milliseconds
The filesystem under path '/' is CORRUPT
</code>```

Can anyone please help in either correcting the corrupted blocks, (or) deleting them? Thanks in advance.

答:
As it's said that Namenode is in Safe mode, first turn it off.

```<code>hdfs dfsadmin -safemode leave
</code>```

Then execute either of commands

```<code>hdfs fsck / | egrep -v '^\.+$' | grep -v replica | grep -v Replica
</code>```

or

```<code>hdfs fsck hdfs://quickstart.cloudera:50070/ | egrep -v '^\.+$' | grep -v replica | grep -v Replica
</code>```

The output would be somewhat similar to

```<code>/path/to/filename.fileextension: CORRUPT blockpool BP-1016133662-10.29.100.41-1415825958975 block blk_1073904305

/path/to/filename.fileextension: MISSING 1 blocks of total size 15620361 B
</code>```

In your case corrupted files are already listed. So execute below commands

```<code>hdfs dfs -rm /hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728
hdfs dfs -rm /hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta
</code>```

And don't enter into Safemode. Just continue working.
Yippee!!

Title: Unable to delete HDFS Corrupt files

Body:
I am unable to delete corrupt files present in my HDFS. Namenode has run into Safe mode. Total number of blocks are 980, out of which 978 have reported. When I run the following command,

sudo -u hdfs hdfs dfsadmin -report

The report generated is,

Safe mode is ON
Configured Capacity: 58531520512 (54.51 GB)
Present Capacity: 35774078976 (33.32 GB)
DFS Remaining: 32374509568 (30.15 GB)
DFS Used: 3399569408 (3.17 GB)
DFS Used%: 9.50%
Under replicated blocks: 0
Blocks with corrupt replicas: 0
Missing blocks: 0
Missing blocks (with replication factor 1): 0
-------------------------------------------------
Live datanodes (1):

Name: 10.0.2.15:50010 (quickstart.cloudera)
Hostname: quickstart.cloudera
Decommission Status : Normal
Configured Capacity: 58531520512 (54.51 GB)
DFS Used: 3399569408 (3.17 GB)
Non DFS Used: 19777388544 (18.42 GB)
DFS Remaining: 32374509568 (30.15 GB)
DFS Used%: 5.81%
DFS Remaining%: 55.31%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 2
Last contact: Tue Nov 14 10:39:58 IST 2017

And for the following command when executed,

sudo -u hdfs hdfs fsck /

The output is,

Connecting to namenode via http://quickstart.cloudera:50070/fsck?ugi=hdfs&path=%2F
FSCK started by hdfs (auth:SIMPLE) from /10.0.2.15 for path / at Tue Nov 14 10:41:25 IST 2017
/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728: CORRUPT blockpool BP-1914853243-127.0.0.1-1500467607052 block blk_1073743141

/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728: MISSING 1 blocks of total size 83 B..
/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta: CORRUPT blockpool BP-1914853243-127.0.0.1-1500467607052 block blk_1073743142

/hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta: MISSING 1 blocks of total size 83 B
Status: CORRUPT
Total size: 3368384392 B (Total open files size: 166 B)
Total dirs: 286
Total files:    966
Total symlinks:     0 (Files currently being written: 3)
Total blocks (validated):   980 (avg. block size 3437126 B) (Total open file blocks (not validated): 2)
********************************
UNDER MIN REPL'D BLOCKS:    2 (0.20408164 %)
dfs.namenode.replication.min:   1
CORRUPT FILES:  2
MISSING BLOCKS: 2
MISSING SIZE:       166 B
CORRUPT BLOCKS:     2
********************************
Minimally replicated blocks:    978 (99.79592 %)
Over-replicated blocks: 0 (0.0 %)
Under-replicated blocks:    0 (0.0 %)
Mis-replicated blocks:      0 (0.0 %)
Default replication factor: 1
Average block replication:  0.9979592
Corrupt blocks:     2
Missing replicas:       0 (0.0 %)
Number of data-nodes:       1
Number of racks:        1
FSCK ended at Tue Nov 14 10:41:26 IST 2017 in 774 milliseconds
The filesystem under path '/' is CORRUPT

Can anyone please help in either correcting the corrupted blocks, (or) deleting them? Thanks in advance.

Body:
As it's said that Namenode is in Safe mode, first turn it off.

hdfs dfsadmin -safemode leave

Then execute either of commands

hdfs fsck / | egrep -v '^\.+$' | grep -v replica | grep -v Replica

or

hdfs fsck hdfs://quickstart.cloudera:50070/ | egrep -v '^\.+$' | grep -v replica | grep -v Replica

The output would be somewhat similar to

/path/to/filename.fileextension: CORRUPT blockpool BP-1016133662-10.29.100.41-1415825958975 block blk_1073904305

/path/to/filename.fileextension: MISSING 1 blocks of total size 15620361 B

In your case corrupted files are already listed. So execute below commands

hdfs dfs -rm /hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.default.1509701903728
hdfs dfs -rm /hbase/oldWALs/quickstart.cloudera%2C60020%2C1509698296866.meta.1509701932269.meta

And don't enter into Safemode. Just continue working.
Yippee!!


问:
Understanding RxJS debounce semantics
From this article:

```<code> const debouncedInput = example.debounceTime(5);

 const subscribe = debouncedInput.subscribe(val => {
   console.log(`Debounced Input: ${val}`);
 });
</code>```

After the first keyup will the debouncedInput wait to call the observer for 5 milliseconds?

Also suppose the user keeps typing before the 5 millisecond interval expires.  Does the debouncedInput Observable wait until an uninterrupted 5 millisecond period passes before publishing the event / source value?

In terms of an example (Per the very helpful marble diagram in @OJKwon s answer)  suppose the - represents a millisecond.  And we have the following:

```<code> -a--b--c-------d
</code>```

In this case the timer that monitors the interval will be restarted at:

2 ms when a is typed

5 ms when b is typed

8 ms when c is typed

9, 10, 11, 12, 13 ms pass

abc gets emitted at 13 ms because there was not other event in that period

The timer starts again when d is typed at 14 ms

abcd is emitted at 19 ms because no other value is typed

答:
What the debounceTime operator does is delay the source observable emission by the specified timeframe. If another source value is emitted during the delay it:

Drops previous value

Resets the interval timer

Wait to see whether the interval will pass without more source values being emitted.

Finally if the are no values emitted during the interval it will emit the last value.

RxJSs marble test diagram illustrates this quite well.  Lets review a few cases.

When we have source.debountTime(20),

all source value emission occurs after 20

const source =   '-a--------b------';
 const expected = '---a--------b----';

all of source values are just simply delayed.

if some source value emitted subsequently in 20ms

const source =   '-a--bc--d---|';
const expected =  '---a---c--d-|';

emitted a delayed by 20ms, b dropped since c emitted before timespan of 20ms for next emission, then d is delayed by 20ms after c does.

To summarize the debounceTime operator functions as a rate limiter only allowing a single value to be emitted in given timeframe.

Title: Understanding RxJS debounce semantics

Body:
From this article:

 const debouncedInput = example.debounceTime(5);

 const subscribe = debouncedInput.subscribe(val => {
   console.log(`Debounced Input: ${val}`);
 });

After the first keyup will the debouncedInput wait to call the observer for 5 milliseconds?

Also suppose the user keeps typing before the 5 millisecond interval expires.  Does the debouncedInput Observable wait until an uninterrupted 5 millisecond period passes before publishing the event / source value?

In terms of an example (Per the very helpful marble diagram in @OJKwon s answer)  suppose the - represents a millisecond.  And we have the following:

 -a--b--c-------d

In this case the timer that monitors the interval will be restarted at:

2 ms when a is typed

5 ms when b is typed

8 ms when c is typed

9, 10, 11, 12, 13 ms pass

abc gets emitted at 13 ms because there was not other event in that period

The timer starts again when d is typed at 14 ms

abcd is emitted at 19 ms because no other value is typed


问:
Prevent drag event to interfere with input elements in Firefox using HTML5 drag/drop
It seems that an input element loses a lot of functionality when put into an element with draggable="true". This only seems to occur in firefox.

See my jsfiddle:
http://jsfiddle.net/WC9Fe/3/

Html:

```<code><div id="drag" draggable="true">
    Drag this div <br />
    <input id="message" type="text" />
</div>
<div id="drop">
    Drop area
</div>
</code>```

JS:

```<code>$('#drag').on('dragstart', function(e){
    e.originalEvent.dataTransfer.setData('Text', $('#message').val());
    e.originalEvent.dataTransfer.effectAllowed = 'move';
});

var drop = $('#drop');
drop.on('dragover', function(e){
    e.preventDefault();
});
drop.on('dragenter', function(e){
    e.preventDefault();
});
drop.on('drop', function(e){
    alert('Target succesfully dropped: ' + e.originalEvent.dataTransfer.getData('Text'));
    e.preventDefault();
});
</code>```

Now try to select text in the input using firefox. Seems impossible. Try the same in IE/Chrome. Seems to work just fine.

答: I have also found using onmouseenter and onmouseleave to toggle the draggable attribute works better because it places the cursor in the input box where you actually click. When using onfocus/onblur, the cursor always goes to the start or end of the text even if you click in the middle.</p>

Body:
It seems that an input element loses a lot of functionality when put into an element with draggable="true". This only seems to occur in firefox.

See my jsfiddle:
http://jsfiddle.net/WC9Fe/3/

Html:

    Drag this div

    <input id="message" type="text" />

    Drop area

JS:

$('#drag').on('dragstart', function(e){
    e.originalEvent.dataTransfer.setData('Text', $('#message').val());
    e.originalEvent.dataTransfer.effectAllowed = 'move';
});

var drop = $('#drop');
drop.on('dragover', function(e){
    e.preventDefault();
});
drop.on('dragenter', function(e){
    e.preventDefault();
});
drop.on('drop', function(e){
    alert('Target succesfully dropped: ' + e.originalEvent.dataTransfer.getData('Text'));
    e.preventDefault();
});

Now try to select text in the input using firefox. Seems impossible. Try the same in IE/Chrome. Seems to work just fine.


问:
Shiny input to set function in server
I'm working on building a shiny app to show a non-homogeneous Poisson process.  I have 3 different lambda function to select from, and would like to display a plot of lambda over time.  My solution is to use a selectInput with the 3 functions as values.

ui.R

```<code>shinyUI(
  navbarPage(
    title = "Non-Homogenious Poisson Process",
    tabPanel("Home",
             fluidPage(
               sidebarLayout(
                 sidebarPanel(

                   #select lambda function
                   selectInput("l_fun",
                               "Select Lambda Function:",
                               c("f(t) = |sin(t)|","f(t) = t","f(t) = log(t)")
                               )#end selectInput
                 ),#end sidebarPanel
                 mainPanel(
                   textOutput("test")
                 )#end mainPanel
               )#end sidebarLayout
             )#end fluidPage
    )#end tabPanel 'Home'
  )#end navbarPage
)#end shinyUI
</code>```

Server.R

```<code>library(shiny)

shinyServer(function(input, output) {

  t_intervals <- 0:100

  l_calculation <- reactive({
    switch(input$l_fun,
           "f(t) = |sin(t)|" = function(t) abs(sin(t)),
           "f(t) = t" = function(t) t,
           "f(t) = log(t)" = function(t) log(t)
           )#end switch
  })#end l_

  y <- l_calculation(t_intervals)#calculate lambda

  output$test <- renderText({
    paste0(y,sep=",",collapse = ",")
  })
})
</code>```

When I run the server outside of shiny, everything works.  But in shiny i get Warning: Error in l_calculation: unused argument (t_intervals).

It's been a while since I've used shiny.  Also right now I'm just trying to display the lambda values, the plot is coming next.

答:
I've tried making the minimal changes to your code that would make it work. You do not call a reactive like a function, with arguments. Reactive variables can be accessed only by calling them without arguments. The "arguments" of reactive variables are reactive values (such as input values or other reactive variables), but there are implicit - you do not pass parameters into them.

Take a look at this code and hopefully it can help you understand it better.

```<code>library(shiny)

ui <- navbarPage(
  title = "Non-Homogenious Poisson Process",
  tabPanel("Home",
           fluidPage(
             sidebarLayout(
               sidebarPanel(

                 #select lambda function
                 selectInput("l_fun",
                             "Select Lambda Function:",
                             c("f(t) = |sin(t)|","f(t) = t","f(t) = log(t)")
                 )#end selectInput
               ),#end sidebarPanel
               mainPanel(
                 textOutput("test")
               )#end mainPanel
             )#end sidebarLayout
           )#end fluidPage
  )#end tabPanel 'Home'
)#end navbarPage

server <- function(input, output, session) {
  t_intervals <- 0:100

  l_calculation <- reactive({
    switch(input$l_fun,
           "f(t) = |sin(t)|" = function(t) abs(sin(t)),
           "f(t) = t" = function(t) t,
           "f(t) = log(t)" = function(t) log(t)
    )#end switch
  })#end l_

  #calculate lambda
  y <- reactive({
    l_function <- l_calculation()
    l_function(t_intervals)
  })

  output$test <- renderText({
    paste0(y(),sep=",",collapse = ",")
  })
}

shinyApp(ui, server)
</code>```

Title: Shiny input to set function in server

Body:
I'm working on building a shiny app to show a non-homogeneous Poisson process.  I have 3 different lambda function to select from, and would like to display a plot of lambda over time.  My solution is to use a selectInput with the 3 functions as values.

ui.R

shinyUI(
  navbarPage(
    title = "Non-Homogenious Poisson Process",
    tabPanel("Home",
             fluidPage(
               sidebarLayout(
                 sidebarPanel(

                   #select lambda function
                   selectInput("l_fun",
                               "Select Lambda Function:",
                               c("f(t) = |sin(t)|","f(t) = t","f(t) = log(t)")
                               )#end selectInput
                 ),#end sidebarPanel
                 mainPanel(
                   textOutput("test")
                 )#end mainPanel
               )#end sidebarLayout
             )#end fluidPage
    )#end tabPanel 'Home'
  )#end navbarPage
)#end shinyUI

Server.R

library(shiny)

shinyServer(function(input, output) {

  t_intervals <- 0:100

  l_calculation <- reactive({
    switch(input$l_fun,
           "f(t) = |sin(t)|" = function(t) abs(sin(t)),
           "f(t) = t" = function(t) t,
           "f(t) = log(t)" = function(t) log(t)
           )#end switch
  })#end l_

  y <- l_calculation(t_intervals)#calculate lambda

  output$test <- renderText({
    paste0(y,sep=",",collapse = ",")
  })
})

When I run the server outside of shiny, everything works.  But in shiny i get Warning: Error in l_calculation: unused argument (t_intervals).

It's been a while since I've used shiny.  Also right now I'm just trying to display the lambda values, the plot is coming next.

Body:
I've tried making the minimal changes to your code that would make it work. You do not call a reactive like a function, with arguments. Reactive variables can be accessed only by calling them without arguments. The "arguments" of reactive variables are reactive values (such as input values or other reactive variables), but there are implicit - you do not pass parameters into them.

Take a look at this code and hopefully it can help you understand it better.

library(shiny)

ui <- navbarPage(
  title = "Non-Homogenious Poisson Process",
  tabPanel("Home",
           fluidPage(
             sidebarLayout(
               sidebarPanel(

                 #select lambda function
                 selectInput("l_fun",
                             "Select Lambda Function:",
                             c("f(t) = |sin(t)|","f(t) = t","f(t) = log(t)")
                 )#end selectInput
               ),#end sidebarPanel
               mainPanel(
                 textOutput("test")
               )#end mainPanel
             )#end sidebarLayout
           )#end fluidPage
  )#end tabPanel 'Home'
)#end navbarPage

server <- function(input, output, session) {
  t_intervals <- 0:100

  l_calculation <- reactive({
    switch(input$l_fun,
           "f(t) = |sin(t)|" = function(t) abs(sin(t)),
           "f(t) = t" = function(t) t,
           "f(t) = log(t)" = function(t) log(t)
    )#end switch
  })#end l_

  #calculate lambda
  y <- reactive({
    l_function <- l_calculation()
    l_function(t_intervals)
  })

  output$test <- renderText({
    paste0(y(),sep=",",collapse = ",")
  })
}

shinyApp(ui, server)


问:
Is there limit on the number of data points to plot HighChart
I am using HighChart to plot Graph of the Telemetry data saved in cloud

Data Points on X-Axis is : Time

Data Points on Y-Axis is : Value

My Issue:

When the data requested is huge say >9000, HighChart errs out and doesn't plot the graph. (Note : I haven't checked the count limit , Hight Chart is able to plot- but when the number is smaller it always plots the graph)

What is the limit of data

Is there any limit of data to plot the graph?
Or is it that I have missed out something that handles this.

Please suggest a way to solve this issue.

The graph used to plot Chart in my app is

```<code>var chart_PT1 = new Highcharts.Chart({
        chart: {
            renderTo: 'signal_high_container'//'PT_1_high_container',
        },
        title: {
            text: 'IO Signal  Data'
        },

    subtitle: {
        text: 'Source: GPS Modem'
    },

    yAxis: {
        title: {
            text: 'Value'
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },

    xAxis: {
        type: 'datetime',
        //categories: dddDate,
        labels: {
            enabled: true,
            formatter: function () { return ddd[this.value][0]; },//<===== throw error here

        }
    },
    series: [{
        data: ddd,
        name: SignalName
    }]
});
});
</code>```

It throws an exception in formatter at ddd[this.value][0] saying something like the index for ddd[this.value] not valid

```<code> xAxis: {
           ....
                formatter: function () { return ddd[this.value][0]; },//<===== throw error here
</code>```

答:
Newer versions of highcharts have a turboThreshold option under plot options that places restrictions on data > 1000 plots. Look-up 'turboThreshold' in the docs for a better explanation.

Ref: https://api.highcharts.com/highcharts/plotOptions.series.turboThreshold

Body:
I am using HighChart to plot Graph of the Telemetry data saved in cloud

Data Points on X-Axis is : Time

Data Points on Y-Axis is : Value

My Issue:

When the data requested is huge say >9000, HighChart errs out and doesn't plot the graph. (Note : I haven't checked the count limit , Hight Chart is able to plot- but when the number is smaller it always plots the graph)

What is the limit of data

Is there any limit of data to plot the graph?
Or is it that I have missed out something that handles this.

Please suggest a way to solve this issue.

The graph used to plot Chart in my app is

var chart_PT1 = new Highcharts.Chart({
        chart: {
            renderTo: 'signal_high_container'//'PT_1_high_container',
        },
        title: {
            text: 'IO Signal  Data'
        },

    subtitle: {
        text: 'Source: GPS Modem'
    },

    yAxis: {
        title: {
            text: 'Value'
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },

    xAxis: {
        type: 'datetime',
        //categories: dddDate,
        labels: {
            enabled: true,
            formatter: function () { return ddd[this.value][0]; },//<===== throw error here

        }
    },
    series: [{
        data: ddd,
        name: SignalName
    }]
});
});

It throws an exception in formatter at ddd[this.value][0] saying something like the index for ddd[this.value] not valid

 xAxis: {
           ....
                formatter: function () { return ddd[this.value][0]; },//<===== throw error here


问:
Uncaught ReferenceError: google is not defined in google maps
getting error in java script all things works normal then why give this error,
i won't able to run the code which is written below this and this is google function which is important to use so how can i remove or is there any other way to solve the error </p>

```<code>//Error is given on this line
google.maps.event.addDomListener(window, 'load', initGoogleMap);

//because of error this code not works
        google.maps.event.addListener(marker, 'click', function() {
            if(!marker.open){
                infoWindow.open(map,marker);
                marker.open = true;
            }
            else{
                infoWindow.close();
                marker.open = false;
            }
            google.maps.event.addListener(map, 'click', function() {
                infoWindow.close();
                marker.open = false;
            });
        });
</code>```

答:
```<code>google.maps.event.addDomListener(window, 'load', initGoogleMap);
</code>```

Above code is for calling the function initGoogleMap at the time of window load. So there will be following reason of giving the error:

The function initGoogleMap you have not defined.

This is calling before the google map library load.

To resolve this follow the below statements:

Remove or comment this line.

Add the code onload = initGoogleMap() in the body tag. After that your body tag will be like this:

Hope it will help you. If you have any query, asked me.

Body:
getting error in java script all things works normal then why give this error,
i won't able to run the code which is written below this and this is google function which is important to use so how can i remove or is there any other way to solve the error

//Error is given on this line
google.maps.event.addDomListener(window, 'load', initGoogleMap);

//because of error this code not works
        google.maps.event.addListener(marker, 'click', function() {
            if(!marker.open){
                infoWindow.open(map,marker);
                marker.open = true;
            }
            else{
                infoWindow.close();
                marker.open = false;
            }
            google.maps.event.addListener(map, 'click', function() {
                infoWindow.close();
                marker.open = false;
            });
        });

Body:
google.maps.event.addDomListener(window, 'load', initGoogleMap);

Above code is for calling the function initGoogleMap at the time of window load. So there will be following reason of giving the error:

The function initGoogleMap you have not defined.

This is calling before the google map library load.

To resolve this follow the below statements:

Remove or comment this line.

Add the code onload = initGoogleMap() in the body tag. After that your body tag will be like this:

<body onload = initGoogleMap()>

Hope it will help you. If you have any query, asked me.


问:
how to have custom width column in html
I want to have different num of columns in a html table rows below is the structure which i want to achieve but couldn't succeed yet. Please guide me to achieve this

```<code>                   <tr>
                       <td>
                       </td>
                       <td>
                       </td>
                   </tr>
                   <tr>
                       <td width="33%">
                       </td>

                       <td width="33%">
                       </td>

                       <td width="33%">
                       </td>
                   </tr>
                   <tr>
                       <td>
                       </td>
                       <td>
                       </td>
                   </tr>
</code>```

答:
Try This way

```<code><table cellpadding="0" cellspacing="0">
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>50%</td>
                <td>50%</td>
            </tr>
        </table>
    </td>

</tr>
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>33%</td>
                <td>33%</td>
                <td>33%</td>
            </tr>
        </table>
    </td>

</tr>
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>50%</td>
                <td>50%</td>
            </tr>
        </table>
    </td>

</tr>
</code>```

CSS

```<code>table{
  width:100%;
  border:0px solid #ddd;

}
table.innerTable td{
  border:1px solid #999;
}
</code>```

https://jsfiddle.net/8j1ptbty/3/

Title: how to have custom width column in html

Body:
Try This way

<table cellpadding="0" cellspacing="0">
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>50%</td>
                <td>50%</td>
            </tr>
        </table>
    </td>

</tr>
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>33%</td>
                <td>33%</td>
                <td>33%</td>
            </tr>
        </table>
    </td>

</tr>
<tr>
    <td>
        <table cellpadding="0" cellspacing="0" class="innerTable" border="0">
            <tr>
                <td>50%</td>
                <td>50%</td>
            </tr>
        </table>
    </td>

</tr>

CSS

table{
  width:100%;
  border:0px solid #ddd;

}
table.innerTable td{
  border:1px solid #999;
}

https://jsfiddle.net/8j1ptbty/3/


问:
How do I print the success message
How do I print the success message in this JSON code using PHP

```<code>{
    "status": 0,

     " result":{
           "status":"success"
               }

}
</code>```

答:
```<code>$response = {"status":"success"};
$data = json_decode(response ,TRUE); //converts to associative array
if($data['status'] == 'success'){
echo 'You are success';
}
</code>```

Title: How do I print the success message

Body:
How do I print the success message in this JSON code using PHP

{
    "status": 0,

     " result":{
           "status":"success"
               }

}


答:
```<code>...

str_replace("{current_date}",date("d-m-Y"));

...
</code>```

You mean like this ?

Title: How to display Current date in HTML?

Body:
...

str_replace("{current_date}",date("d-m-Y"));

...

You mean like this ?


问:
Simple Form inputs rendered outside form tag
I am facing a strange issue related to the generation of an automatic form by devise for log in.

This is my view:

```<code># app/views/devise/sessions/new.html.haml
.jumbotron
  %h2= t('devise.sessions.new')
  = simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f|
    = f.error_notification
    .form-inputs
      = f.input :email, required: false, autofocus: true
      = f.input :password, required: false
      = f.input :remember_me, as: :boolean if devise_mapping.rememberable?
    .form-actions
      = f.button :submit, t('devise.sessions.new')
  %br/
  = render 'devise/shared/links'
</code>```

This used to render the following:

Accedi

<form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users/sign_in?locale=it" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="{authenticity_token}" />

Email<input class="form-control string email optional" autofocus="autofocus" type="email" value="" name="user[email]" id="user_email" />

Password<input class="form-control password optional" type="password" name="user[password]" id="user_password" />

<input value="0" type="hidden" name="user[remember_me]" /><input class="boolean optional" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me" />Ricordami

<input type="submit" name="commit" value="Accedi" class="btn btn-default" data-disable-with="Accedi" />

</form>

```
</div>
</div>
</p>

<p>For a very strange reason, the same view is rendered now as:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div id='content'><div class='jumbotron'>
        <h2>Accedi</h2>
          <div class='form-inputs'>
          <div class="form-group email optional user_email"><label class="control-label email optional" for="user_email">Email</label><input class="form-control string email optional" autofocus="autofocus" type="email" value="" name="user[email]" id="user_email" /></div>
          <div class="form-group password optional user_password"><label class="control-label password optional" for="user_password">Password</label><input class="form-control password optional" type="password" name="user[password]" id="user_password" /></div>
          <div class="form-group boolean optional user_remember_me"><div class="checkbox"><input value="0" type="hidden" name="user[remember_me]" /><label class="boolean optional" for="user_remember_me"><input class="boolean optional" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me" />Ricordami</label></div></div>
        </div>
        <div class='form-actions'>
          <input type="submit" name="commit" value="Accedi" class="btn btn-default" data-disable-with="Accedi" />
        </div>
      <form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users/sign_in?locale=it" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="{authenticity_token}" /></form>
        <!-- something else -->
 </div></div></code>```

Basically all my form-inputs and my form-actions are now rendered outside the form tag.

Do you have any idea of what could be causing this issue - since I haven't changed anything since a while?

From Gemfile:

```<code>gem 'rails', '~> 5.0.2'
gem 'devise', '~> 4.3'
gem 'simple_form', '~> 3.4'
</code>```

Thank you in advance

Update

If I check the diff of the commit generating this issue, I see that the changed files are:

```<code># $ git diff --name-only master..refactoring-branch
app/controllers/albums_controller.rb
app/controllers/crud/albums_controller.rb
app/controllers/crud/events_controller.rb
app/helpers/albumizr_helper.rb
app/models/album.rb
app/models/event.rb
app/views/albums/index.html.haml
app/views/layouts/_nav.html.haml
config/locales/layout/navbar.en.yml
config/locales/layout/navbar.it.yml
config/locales/models/album.en.yml
config/locales/models/album.it.yml
config/routes.rb
db/migrate/20171113151343_create_albums.rb
db/schema.rb
spec/factories/album.rb
spec/models/album_spec.rb
</code>```

I really don't really see any direct impact on what simple_form is supposed to do..

答:
I figured out what was the issue.

When I using external services, I prefer to create builders delegating the generation of the html code to some views (e.g. for charts, iframes, etc)

In this case the problem was with app/helpers/albumizr_helper.rb.

```<code># frozen_string_literal: true

module AlbumizrHelper
  include ActionView::Helpers::TagHelper

  attr_accessor :output_buffer

  def photogallery_item(url)
    # rubocop:disable Rails/OutputSafety
    content_tag :div, class: 'photogallery-item' do
      content_tag(:div, build_albumizr_iframe(url), class: 'embed-responsive-item')
        content_tag(:div, build_albumizr_button, class: 'text-center')
    end.html_safe
    # rubocop:enable Rails/OutputSafety
  end

  private

  def build_albumizr_iframe(url)
    content_tag(
      :iframe, nil, class: 'iframe-fullscreen', allowfullscreen: '', height: '100%',
                    scrolling: 'no', src: url, width: '100%'
    )
  end

  def build_albumizr_button
    content_tag(:button, class: 'btn btn-primary fullscreen-btn', role: :button) do
      content_tag(:i, nil, class: 'glyphicon glyphicon-fullscreen')
        ' FullScreen'
    end
  end
end
</code>```

When I create some class including ActionView::Helpers::TagHelper, I set attr_accessor :output_buffer in order to get the code generated.

In this case, this was creating some conflict with the output buffer of simple form, so I created a separated class under lib/ and everything works fine.

I was misled but this answer

Body:
I am facing a strange issue related to the generation of an automatic form by devise for log in.

This is my view:

# app/views/devise/sessions/new.html.haml
.jumbotron
  %h2= t('devise.sessions.new')
  = simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f|
    = f.error_notification
    .form-inputs
      = f.input :email, required: false, autofocus: true
      = f.input :password, required: false
      = f.input :remember_me, as: :boolean if devise_mapping.rememberable?
    .form-actions
      = f.button :submit, t('devise.sessions.new')
  %br/
  = render 'devise/shared/links'

This used to render the following:

Accedi

<form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users/sign_in?locale=it" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="{authenticity_token}" />

Email<input class="form-control string email optional" autofocus="autofocus" type="email" value="" name="user[email]" id="user_email" />

Password<input class="form-control password optional" type="password" name="user[password]" id="user_password" />

<input value="0" type="hidden" name="user[remember_me]" /><input class="boolean optional" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me" />Ricordami

<input type="submit" name="commit" value="Accedi" class="btn btn-default" data-disable-with="Accedi" />

</form>

For a very strange reason, the same view is rendered now as:

Accedi

Email<input class="form-control string email optional" autofocus="autofocus" type="email" value="" name="user[email]" id="user_email" />

Password<input class="form-control password optional" type="password" name="user[password]" id="user_password" />

<input value="0" type="hidden" name="user[remember_me]" /><input class="boolean optional" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me" />Ricordami

          <input type="submit" name="commit" value="Accedi" class="btn btn-default" data-disable-with="Accedi" />

      <form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users/sign_in?locale=it" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="{authenticity_token}" /></form>

Basically all my form-inputs and my form-actions are now rendered outside the form tag.

Do you have any idea of what could be causing this issue - since I haven't changed anything since a while?

From Gemfile:

gem 'rails', '~> 5.0.2'
gem 'devise', '~> 4.3'
gem 'simple_form', '~> 3.4'

Thank you in advance

Update

If I check the diff of the commit generating this issue, I see that the changed files are:

# $ git diff --name-only master..refactoring-branch
app/controllers/albums_controller.rb
app/controllers/crud/albums_controller.rb
app/controllers/crud/events_controller.rb
app/helpers/albumizr_helper.rb
app/models/album.rb
app/models/event.rb
app/views/albums/index.html.haml
app/views/layouts/_nav.html.haml
config/locales/layout/navbar.en.yml
config/locales/layout/navbar.it.yml
config/locales/models/album.en.yml
config/locales/models/album.it.yml
config/routes.rb
db/migrate/20171113151343_create_albums.rb
db/schema.rb
spec/factories/album.rb
spec/models/album_spec.rb

I really don't really see any direct impact on what simple_form is supposed to do..

Body:
I figured out what was the issue.

When I using external services, I prefer to create builders delegating the generation of the html code to some views (e.g. for charts, iframes, etc)

In this case the problem was with app/helpers/albumizr_helper.rb.

# frozen_string_literal: true

module AlbumizrHelper
  include ActionView::Helpers::TagHelper

  attr_accessor :output_buffer

  def photogallery_item(url)
    # rubocop:disable Rails/OutputSafety
    content_tag :div, class: 'photogallery-item' do
      content_tag(:div, build_albumizr_iframe(url), class: 'embed-responsive-item')
        content_tag(:div, build_albumizr_button, class: 'text-center')
    end.html_safe
    # rubocop:enable Rails/OutputSafety
  end

  private

  def build_albumizr_iframe(url)
    content_tag(
      :iframe, nil, class: 'iframe-fullscreen', allowfullscreen: '', height: '100%',
                    scrolling: 'no', src: url, width: '100%'
    )
  end

  def build_albumizr_button
    content_tag(:button, class: 'btn btn-primary fullscreen-btn', role: :button) do
      content_tag(:i, nil, class: 'glyphicon glyphicon-fullscreen')
        ' FullScreen'
    end
  end
end

When I create some class including ActionView::Helpers::TagHelper, I set attr_accessor :output_buffer in order to get the code generated.

In this case, this was creating some conflict with the output buffer of simple form, so I created a separated class under lib/ and everything works fine.

I was misled but this answer


问:
Only display the values to the right of a Decimal Number
I use SQL Server 2005 and need to test whether values in a column that's metadata has been specified as DECIMAL(18.3) actually contains data that has values to the right of the Decimal point, and if so, what these values are.

I've read a few articles that only discuss how to drop off the decimal places or how to round the values, but not how to ONLY display what is stored to the right of the decimal point.

Your help would be greatly appreciated.

Kind Regards,

Ignacio.

答:
```<code>SELECT decimalnumber - FLOOR(decimalnumber) AS decimalpart
FROM mytable
WHERE decimalnumber - FLOOR(decimalnumber) > 0
</code>```

OwnerDisplayName: Ignacio

LastEditorDisplayName: cletus

OwnerDisplayName: gkrogers


问:
Loader object not firing complete event after an external css/swf file got loaded
Hi
I am a bit stuck here for the past few days. I have a SWF running in Security.LOCAL_TRUSTED sandbox.

I can load my JPEGs and simple SWFs without any problems

```<code>var loader:Loader = new Loader();
loader.load(new URLRequest('file:///test.jpg'));
</code>```

But once, I successfully load a SWF created from an CSS (e.g. myfont.swf) file using Flash Builder 4 (Compile CSS to SWF), then I am unable to load any images or SWFs again as I was before.

The process events are getting fired and looks like its loading but the complete event never gets fired. Neither does any other IOError or Security warning occur.

Can the loaded SWF (myfont.swf) change the sandbox of the loading swf? Or what am I missing here.

CSS for myfont.swf

```<code>/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

@font-face {
    src: url("../assets/fonts/Arial.ttf");
    fontFamily: "Arial";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}

@font-face {
    src: url("../assets/fonts/Arial Bold.ttf");
    fontFamily: "Arial";
    fontWeight: "bold";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}
</code>```

答:
Okay I solved it, how ever I don't understand quite why.

The css/swf files I was loading where not on same directory as the main SWF file.

now that I am loading my font via file://./fonts/arial.swf everything seems to work.

If ever someone else get stuck; Looks like the location of the loaded file matters.

Anyone any ideas why that is?

Body:
Hi
I am a bit stuck here for the past few days. I have a SWF running in Security.LOCAL_TRUSTED sandbox.

I can load my JPEGs and simple SWFs without any problems

var loader:Loader = new Loader();
loader.load(new URLRequest('file:///test.jpg'));

But once, I successfully load a SWF created from an CSS (e.g. myfont.swf) file using Flash Builder 4 (Compile CSS to SWF), then I am unable to load any images or SWFs again as I was before.

The process events are getting fired and looks like its loading but the complete event never gets fired. Neither does any other IOError or Security warning occur.

Can the loaded SWF (myfont.swf) change the sandbox of the loading swf? Or what am I missing here.

CSS for myfont.swf

/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

@font-face {
    src: url("../assets/fonts/Arial.ttf");
    fontFamily: "Arial";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}

@font-face {
    src: url("../assets/fonts/Arial Bold.ttf");
    fontFamily: "Arial";
    fontWeight: "bold";
    embedAsCFF: true;
    unicodeRange:
        U+0000-U+007F,
        U+00A0-U+00FF,
        U+2000-U+206F,
        U+20A0-U+20CF;
}


问:
How to calculate Levenshtein ratio/distance for rows in my column in python?
I have a dataframe with only one column , and 1000 rows in that column.
I need to compare all rows and find Levenshtein distance for all rows . how Do i calculate that ratio or distance in python

I have a dataframe as following:

```<code>  #Df
  StepDescription
  click confirm button when done
  you have logged on
  please log in to proceed
  click on confirm button
  Dolb was released successfully
  Enter your details
  validate the statement
  Aval was released sucessfully
</code>```

How to do i Calculate Levenshtein ration for all these

Code I have written to iterate through loops but after  iterating how to proceed.

```<code>  import Levenshtein
  import pandas as pd
  data_dist = pd.read_csv('path\Data_TestDescription.csv')
  df = pd.DataFrame(data_dist)
  for index, row in df.iterrows():
</code>```

Body:
I have a dataframe with only one column , and 1000 rows in that column.
I need to compare all rows and find Levenshtein distance for all rows . how Do i calculate that ratio or distance in python

I have a dataframe as following:

  #Df
  StepDescription
  click confirm button when done
  you have logged on
  please log in to proceed
  click on confirm button
  Dolb was released successfully
  Enter your details
  validate the statement
  Aval was released sucessfully

How to do i Calculate Levenshtein ration for all these

Code I have written to iterate through loops but after  iterating how to proceed.

  import Levenshtein
  import pandas as pd
  data_dist = pd.read_csv('path\Data_TestDescription.csv')
  df = pd.DataFrame(data_dist)
  for index, row in df.iterrows():

Body:
As asked in a comment, the percentage is desired, I'll keep the accepteds answer and add just the new part:

import numpy as np
import pandas as pd
from Levenshtein import distance
from itertools import product

#df = ...

dist = [distance(*x) for x in product(df.StepDescription, repeat=2)]

dist_df = pd.DataFrame(np.array(dist).reshape(df.shape[0], df.shape[0]))
dist_df

    0   1   2   3   4   5   6   7
0   0  23  23  13  29  25  25  28
1  23   0  18  18  23  18  18  23
2  23  18   0  20  25  21  19  24
3  13  18  20   0  27  19  21  26
4  29  23  25  27   0  26  23   5
5  25  18  21  19  26   0  19  25
6  25  18  19  21  23  19   0  21
7  28  23  24  26   5  25  21   0

dist_df_percentage = dist_df // min(x for x in dist if x > 0) * 100

     0    1    2    3    4    5    6    7
0    0  460  460  260  580  500  500  560
1  460    0  360  360  460  360  360  460
2  460  360    0  400  500  420  380  480
3  260  360  400    0  540  380  420  520
4  580  460  500  540    0  520  460  100
5  500  360  420  380  520    0  380  500
6  500  360  380  420  460  380    0  420
7  560  460  480  520  100  500  420    0


问:
What's the difference between Red/Black deployment and Blue/Green Deployment?
I've heard both used to describe the idea of deploying an update on new machines while keeping old machines active, ready to rollback if an issue occurs. I've also heard it used to describe sharing load between updated services and old service, again for the purpose of a rollbacks —sometimes terminating inactive older patches and sometimes not.

My understanding also is that it is strictly for cloud services.

Can someone help to demystify these terms?

答:
Both blue/green and red/black deployment represent the same concept.

While the first is the most common term, the latter seems to be used mainly in Netflix and their tools (like Spinnaker).

They apply only to cloud, virtualized or containerized services in the sense your infrastructure has to be automatable in order to make sense of this approach.


问:
Creating a horizontal bar chart in R to display sequence of activities
The dataset "patients" is an eventlog of patients visiting a clinic and getting treatment. The script below gives a data frame with traces or sequence of activities in the eventlog, trace_id and absolute frequency of the cases following the particular trace. I wish to create a dynamic horizontal bar chart using ggplot2 or plotly such that the traces are represented like the snapshot attached with the absolute frequency in % at the top of the bar with axes labels.

Thanks and please help!

```<code>library("bupaR")
traces(patients, output_traces = T, output_cases = F)
</code>```

答:
Hope this helps (I am not able to get frequency however)

```<code>library(splitstackshape)

tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr.df <- cSplit(tr, "trace", ",")

tr.df <- tr.df[,c(1,4:9)]
tr.df <- melt(tr.df, id.vars = "trace_id")

windows()
ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value, label =
value)) +
geom_tile(colour = "white") +
geom_text(colour = "white", fontface = "bold", size = 2) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none")
</code>```

EDIT 1:

```<code>library(splitstackshape)
library(bupaR)
library(ggplot2)

tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr.df <- cSplit(tr, "trace", ",")

tr.df <- tr.df[,c(1,4:9)]
tr.df <- melt(tr.df, id.vars = "trace_id")
tr.df <- tr.df[order(tr.df$trace_id),]

tr.label <- data.frame(id = tr$trace_id, freq = tr$absolute_frequency)
tr.label <- tr.label[order(tr.label$id),]

windows()
ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value, label = value)) +
geom_tile(colour = "white") +
geom_text(colour = "white", fontface = "bold", size = 2) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none") +
geom_text(data = tr.label, aes(label = freq, y = id, x = 6), nudge_x = 0.3,
          colour = "black", fontface = "bold", inherit.aes = FALSE)
</code>```

Body:
The dataset "patients" is an eventlog of patients visiting a clinic and getting treatment. The script below gives a data frame with traces or sequence of activities in the eventlog, trace_id and absolute frequency of the cases following the particular trace. I wish to create a dynamic horizontal bar chart using ggplot2 or plotly such that the traces are represented like the snapshot attached with the absolute frequency in % at the top of the bar with axes labels.

Thanks and please help!

library("bupaR")
traces(patients, output_traces = T, output_cases = F)

Body:
Hope this helps (I am not able to get frequency however)

library(splitstackshape)

tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr.df <- cSplit(tr, "trace", ",")

tr.df <- tr.df[,c(1,4:9)]
tr.df <- melt(tr.df, id.vars = "trace_id")

windows()
ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value, label =
value)) +
geom_tile(colour = "white") +
geom_text(colour = "white", fontface = "bold", size = 2) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none")

EDIT 1:

library(splitstackshape)
library(bupaR)
library(ggplot2)

tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr.df <- cSplit(tr, "trace", ",")

tr.df <- tr.df[,c(1,4:9)]
tr.df <- melt(tr.df, id.vars = "trace_id")
tr.df <- tr.df[order(tr.df$trace_id),]

tr.label <- data.frame(id = tr$trace_id, freq = tr$absolute_frequency)
tr.label <- tr.label[order(tr.label$id),]

windows()
ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value, label = value)) +
geom_tile(colour = "white") +
geom_text(colour = "white", fontface = "bold", size = 2) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none") +
geom_text(data = tr.label, aes(label = freq, y = id, x = 6), nudge_x = 0.3,
          colour = "black", fontface = "bold", inherit.aes = FALSE)


问:
d3 zoom behavior in React Native
In React Native I draw my charts with d3 and ART libraries.

```<code>export default class DevTest extends React.Component {

    static defaultProps = {
        width: 300,
        height: 150,
    }

    mainScaleX = d3Scale.scaleTime()
        .domain(d3Array.extent(chartDataTo, data => data.date))
        .range([0, this.props.width])

    mainScaleY = d3Scale.scaleLinear()
        .domain(d3Array.extent(chartDataTo, data => data.value))
        .range([this.props.height, 0])

    rawChartValue = d3Shape.line()
        .x(data => this.mainScaleX(data.date))
        .y(data => this.mainScaleY(data.value))

    render(){

        return (
            <View>
                <Surface width = {this.props.width} height = {this.props.height}>
                    <Group x = {0} y = {0}>
                        <Shape
                            d = {this.rawChartValue(chartData)}
                            stroke = "#000"
                            strokeWidth = {1}
                        />
                    </Group>
                </Surface>
            </View>
        )
    }
}
</code>```

Is there any way to implement d3 svg-like zoom behavior, but without DOM mutation. For example, using some d3 pure functions with just x and y values as input to rescale mainScaleX and mainScaleY?

答:
You can use PanResponder from react-native and zoomIdentity from d3-zoom for that purpose.

Code example looks sometihng like this

```<code>componentWillMount() {
    this._panResponder = PanResponder.create({
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onPanResponderMove: (event, { dx, dy }) => {
            const zoomIdentity = d3Zoom.zoomIdentity.translate(dx, dy)
            this._onDrag(zoomIdentity)
        },
    });
}

_onDrag(zoomIdentity){
    this.setState({
        rescaledX: zoomIdentity.rescaleX(this.state.mainScaleX),
        rescaledY: zoomIdentity.rescaleY(this.state.mainScaleY)
    })
}
</code>```

And you pass your rescaled{X, Y} to a chart component

```<code>render(){
    return (
        <View {...this._panResponder.panHandlers}>
            <Component
                {...this.props}
                scaleX = {this.state.rescaledX}
                scaleY = {this.state.rescaledY}
            />
        </View>
    )
}
</code>```

Title: d3 zoom behavior in React Native

Body:
In React Native I draw my charts with d3 and ART libraries.

export default class DevTest extends React.Component {

    static defaultProps = {
        width: 300,
        height: 150,
    }

    mainScaleX = d3Scale.scaleTime()
        .domain(d3Array.extent(chartDataTo, data => data.date))
        .range([0, this.props.width])

    mainScaleY = d3Scale.scaleLinear()
        .domain(d3Array.extent(chartDataTo, data => data.value))
        .range([this.props.height, 0])

    rawChartValue = d3Shape.line()
        .x(data => this.mainScaleX(data.date))
        .y(data => this.mainScaleY(data.value))

    render(){

        return (
            <View>
                <Surface width = {this.props.width} height = {this.props.height}>
                    <Group x = {0} y = {0}>
                        <Shape
                            d = {this.rawChartValue(chartData)}
                            stroke = "#000"
                            strokeWidth = {1}
                        />
                    </Group>
                </Surface>
            </View>
        )
    }
}

Is there any way to implement d3 svg-like zoom behavior, but without DOM mutation. For example, using some d3 pure functions with just x and y values as input to rescale mainScaleX and mainScaleY?

Body:
You can use PanResponder from react-native and zoomIdentity from d3-zoom for that purpose.

Code example looks sometihng like this

componentWillMount() {
    this._panResponder = PanResponder.create({
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onPanResponderMove: (event, { dx, dy }) => {
            const zoomIdentity = d3Zoom.zoomIdentity.translate(dx, dy)
            this._onDrag(zoomIdentity)
        },
    });
}

_onDrag(zoomIdentity){
    this.setState({
        rescaledX: zoomIdentity.rescaleX(this.state.mainScaleX),
        rescaledY: zoomIdentity.rescaleY(this.state.mainScaleY)
    })
}

And you pass your rescaled{X, Y} to a chart component

render(){
    return (
        <View {...this._panResponder.panHandlers}>
            <Component
                {...this.props}
                scaleX = {this.state.rescaledX}
                scaleY = {this.state.rescaledY}
            />
        </View>
    )
}


问:
Trouble installing phonegap plugin push with Ionic 2
I'm currently trying to develop an application with some plugins, here is the list :

```<code>com.googlemaps.ios 2.5.0 "Google Maps SDK for iOS"
cordova-plugin-camera 2.4.1 "Camera"
cordova-plugin-compat 1.2.0 "Compat"
cordova-plugin-console 1.1.0 "Console"
cordova-plugin-crop 0.3.1 "CropPlugin"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-facebook4 1.9.1 "Facebook Connect"
cordova-plugin-geolocation 2.4.3 "Geolocation"
cordova-plugin-googlemaps 2.1.1 "cordova-plugin-googlemaps"
cordova-plugin-ionic-webview 1.1.15 "cordova-plugin-ionic-webview"
cordova-plugin-screen-orientation 2.0.1 "Screen Orientation"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.4-dev "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-plugin-x-socialsharing 5.2.1 "SocialSharing"
es6-promise-plugin 4.1.0 "Promise"
info.protonet.imageresizer 0.1.1 "Image Resizer"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-push 2.1.0 "PushPlugin"
</code>```

Since I installed the PushPlugin, I have no more possibility to build the app, I have the following error :

```<code>A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
   > For input string: "+"
</code>```

I tried to edit project.properties, build.gradle.. From what i read on internet, this is a conflict version between different google based plugins. I can't figure out how to make these plugins work together.. Thank you in advance for help !

答:
Solve it as follows:

Go to platform-> android -> project.properties and assign a version number for com.google.android.gms:play-services-{}:11.0.1 ( Match all play service dependency version )

If you recompile now, it will complain about google-services.json file. You can create and download it from here. Save that file in the root folder of your ionic project.

It should recompile now without errors. You read through this git thread.

Body:
I'm currently trying to develop an application with some plugins, here is the list :

com.googlemaps.ios 2.5.0 "Google Maps SDK for iOS"
cordova-plugin-camera 2.4.1 "Camera"
cordova-plugin-compat 1.2.0 "Compat"
cordova-plugin-console 1.1.0 "Console"
cordova-plugin-crop 0.3.1 "CropPlugin"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-facebook4 1.9.1 "Facebook Connect"
cordova-plugin-geolocation 2.4.3 "Geolocation"
cordova-plugin-googlemaps 2.1.1 "cordova-plugin-googlemaps"
cordova-plugin-ionic-webview 1.1.15 "cordova-plugin-ionic-webview"
cordova-plugin-screen-orientation 2.0.1 "Screen Orientation"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.4-dev "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-plugin-x-socialsharing 5.2.1 "SocialSharing"
es6-promise-plugin 4.1.0 "Promise"
info.protonet.imageresizer 0.1.1 "Image Resizer"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-push 2.1.0 "PushPlugin"

Since I installed the PushPlugin, I have no more possibility to build the app, I have the following error :

A problem occurred evaluating root project 'android'.
> Failed to apply plugin [class 'com.google.gms.googleservices.GoogleServicesPlugin']
   > For input string: "+"

I tried to edit project.properties, build.gradle.. From what i read on internet, this is a conflict version between different google based plugins. I can't figure out how to make these plugins work together.. Thank you in advance for help !


问:
Running UFT test through Amazon Web Services instance of UFT
Due to the budget that we currently have and only needing to run UFT for maybe an hour a day, we are trying to integrate an Amazon Web Services instance of UFT since they charge by the hour.

My question is this:
We are trying to run our test at 9am every day, we already have a vba script that opens the correct test and runs it successfully through a windows scheduled task, is this possible if we are using an AWS instance of UFT? I have never used AWS so I am not aware of any restrictions or complications that might arise.

I guess what I am looking for is how would we go about logging in to AWS, make sure that the UFT instance is being used, and run a test all without having to touch anything

答:
MicroFocus just announced StormRunner Functional (SRF) which allows testing in the cloud (promotional video). You can upload UFT tests (currently only web or mobile) and then schedule the test to run daily, you pay for usage of SRF which covers the AWS instance as well as the UFT license.

SRF has been discontinued, it is no more, it has ceased to be. StormRunner Functional has expired and gone to meet its maker. It's a stiff, bereft of life. It's pushing up the daisies. SRF is an ex product.


问:
Unable to execute query in jasper studio query dialog. but the query is ok

In jasper studio jdbc connection is ok. it can fetch table information from my database. but the problem is after execute the query it show error message. don't find any reason for this error. Query****SELECT  SUM(DEBIT_AMOUNT), SUM(CREDIT_AMOUNT), COST_CENTER_ID FROM  ACCTG_COST_CENTER_TRANS WHERE GL_ACCOUNT_ID= '10012' GROUP BY GL_ACCOUNT_ID

答: The error indicates a ClassCastException. Is it possible that field COST_CENTER_ID was declared as type java.lang.Boolean instead of java.lang.String?