问:
VBA do until loop code to copy range of cells to other range till same value
I made a excel sheet where certain range of cells (J11 to J36) values are updated when value in the G1 is entered.

And, then values from J11 to J36 are manually entered (or copied) to D11 to D36.
By doing this, again values of J11 to J36 will get changed. SO, then I do iterative calculation to make both ranges same.

Is there any macro code to automate this?

I tried to do until loop but it only copies first range that is J11.

FYI, in range J11 to J36, in betwen there are title rows which are J19,J20,J28,J29 that should be skipped while copying.

My current code is below,

```<code>Sub DoUntilloop()

Dim i As Integer

i = 11
For i = 11 To 16

Do Until i > 16
Cells(i, 4).Value = Cells(i, 10)
i = i + 1
Loop

Next i

End Sub
</code>```

Any help on this would be greatly appreciated.

答:
You current loop should actually be processing rows 11 to 16, not just 11 as you state in the question.  However, it is designed poorly, as there is no need to have two loops - the outer loop is effectively doing nothing as it is currently written.</p>

```<code>Sub DoUntilloop()

    Dim i As Long

    For i = 11 To 36
        If i <> 19 And i <> 20 And i <> 28 And i <> 29 Then
            Cells(i, "D").Value = Cells(i, "J").Value
        End If
    Next i

End Sub
</code>```

Body:
I made a excel sheet where certain range of cells (J11 to J36) values are updated when value in the G1 is entered.

And, then values from J11 to J36 are manually entered (or copied) to D11 to D36.
By doing this, again values of J11 to J36 will get changed. SO, then I do iterative calculation to make both ranges same.

Is there any macro code to automate this?

I tried to do until loop but it only copies first range that is J11.

FYI, in range J11 to J36, in betwen there are title rows which are J19,J20,J28,J29 that should be skipped while copying.

My current code is below,

Sub DoUntilloop()

Dim i As Integer

i = 11
For i = 11 To 16

Do Until i > 16
Cells(i, 4).Value = Cells(i, 10)
i = i + 1
Loop

Next i

End Sub

Any help on this would be greatly appreciated.

Body:
You current loop should actually be processing rows 11 to 16, not just 11 as you state in the question.  However, it is designed poorly, as there is no need to have two loops - the outer loop is effectively doing nothing as it is currently written.

Sub DoUntilloop()

    Dim i As Long

    For i = 11 To 36
        If i <> 19 And i <> 20 And i <> 28 And i <> 29 Then
            Cells(i, "D").Value = Cells(i, "J").Value
        End If
    Next i

End Sub


来源: stackexchange

问:
How to update date in table based on two criteria from a select
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like</p>

```<code>UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)
</code>```

答:
I think this is what you looking for:

```<code>UPDATE A
  SET
      A.DATE = GETDATE()
FROM TableA AS A
WHERE EXISTS
(
    SELECT 1
    FROM TableB AS B
    WHERE B.userid = A.userid
          AND B.planName = A.planName
);
</code>```

this will update all the rows in your table A that have the exact combination(s) of userid and planName that exist in table B

so if Table A has the following:

```<code>userid planName
1       A
2       A
1       B
</code>```

and Table B has the following

```<code>userid planName
1       A
1       B
</code>```

it will only update the following in Table A:

```<code>userid planName
1       A
1       B
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like

UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)

Body:
I think this is what you looking for:

UPDATE A
  SET
      A.DATE = GETDATE()
FROM TableA AS A
WHERE EXISTS
(
    SELECT 1
    FROM TableB AS B
    WHERE B.userid = A.userid
          AND B.planName = A.planName
);

this will update all the rows in your table A that have the exact combination(s) of userid and planName that exist in table B

so if Table A has the following:

userid planName
1       A
2       A
1       B

and Table B has the following

userid planName
1       A
1       B

it will only update the following in Table A:

userid planName
1       A
1       B


问:
Print Rails Engine Version Number in View
I've been manually updating a Rails Engine version number in the engines footer view.

The version file is in the standard lib/ENGINENAME/version.rb folder is there a way I can get the engine's footer view to print out the engine's version number so I don't have to manually update it all the time?

Thanks in Advance.

答:
I ended up using this snippet of code thanks to the provided information in the comments under my question.</p>

```<code> Enginename::VERSION
</code>```

Body:
I ended up using this snippet of code thanks to the provided information in the comments under my question.

 Enginename::VERSION


问:
Ubuntu Linux - Spawning an application when a USB device is plugged in
I'm trying to get an application to run whenever a USB device is plugged in: Flash drive, Camera, phone, etc. I'll probably start with a simple application like "Hello World". So basically, when I plug in a camera, flash drive, or phone I want my computer to spawn a "Hello World" application.

Is it possible to create this sort of functionality on the latest version of Ubuntu Linux? Would I need to create an application to listen for this event? What I would rather do is just have it work without having an to have an application running to catch it. Is this possible?

Anything I need to write will be in C. If someone could point me in the right direction, I would be very grateful.

Thanks,
T

答: What you want is a udev rule -- udev is a daemon that waits for kernel events (like hardware mounts) and processes a set of "rules" that you define. There's a nice tutorial here which has several examples at the end that match your request.</p>

ContentLicense: CC BY-SA 2.5


问:
DNN ModuleID not being passed from the code behind to the ascx
Backstory: I use a DNN (DotNetNuke) content management system to host VB.NET/Angular1 modules.

I'm currently having an issue where a value in the code-behind is not accessible in the View.ascx of my module. This is causing a fatal runtime error.

The code behind where the value is being passed to a publicly defined variable

The View.ascx where the variable is being used

```<code>Erreur: icod est présentement indisponible.
DotNetNuke.Services.Exceptions.ModuleLoadException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection. ---> System.Web.HttpCompileException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection.
à System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
à System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
à DotNetNuke.UI.ControlUtilities.LoadControl[T](TemplateControl containerControl, String ControlSrc)
à DotNetNuke.UI.Modules.WebFormsModuleControlFactory.CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleControlFactory.LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleHost.LoadModuleControl() --- Fin de la trace de la pile d'exception interne --
</code>```

I noticed that they reference View.ascx(2) as if there are two physical versions of the file in the project or on the server, but this is not the case.

Any ideas on what may be going on here? Please let me know should the post require additional information.

答:
I've resolved the issue by rebuilding my local development instance of DNN to a version higher than that of the production instance and rebuilt the module. I believe one of the DLLs we use in our environment, PetaPoco was causing an issue when the module was installed on a lower version of DNN. Previously my local copy of DNN was 9.1.0.367, it is now 9.1.1.129 whereas the production instance is at 9.1.1.113 .

It's not ideal that fixing it required a total reinstantiation of my development environment, but I believe a simple upgrade to an equal or greater version of the destination site would have fixed the issue as well.

Body:
Backstory: I use a DNN (DotNetNuke) content management system to host VB.NET/Angular1 modules.

I'm currently having an issue where a value in the code-behind is not accessible in the View.ascx of my module. This is causing a fatal runtime error.

The code behind where the value is being passed to a publicly defined variable

The View.ascx where the variable is being used

Erreur: icod est présentement indisponible.
DotNetNuke.Services.Exceptions.ModuleLoadException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection. ---> System.Web.HttpCompileException: C:\inetpub\wwwroot\FRANCO-NORD-www1\DesktopModules\icod\View.ascx(2): error BC30451: 'modID' n'est pas déclaré. Il peut être inaccessible en raison de son niveau de protection.
à System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
à System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
à System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
à DotNetNuke.UI.ControlUtilities.LoadControl[T](TemplateControl containerControl, String ControlSrc)
à DotNetNuke.UI.Modules.WebFormsModuleControlFactory.CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleControlFactory.LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration)
à DotNetNuke.UI.Modules.ModuleHost.LoadModuleControl() --- Fin de la trace de la pile d'exception interne --

I noticed that they reference View.ascx(2) as if there are two physical versions of the file in the project or on the server, but this is not the case.

Any ideas on what may be going on here? Please let me know should the post require additional information.


问:
SQL transform id and add where statement before join
I am pretty new to SQL. Here is an operation I am sure is simple for a lot of you. I am trying to join two tables across databases on the same server – dbB and dbA, and TableA (with IdA) and TableB (with IdB) respectively. But before doing that I want to transform column IdA into a number, where I would like to remove the “:XYZ” character from its values and add a where statement for another column in dbA too. Below I show my code for the join but I am not sure how to convert the values of the column. This allows me to match idAwith idB in the join. Thanks a ton in advance.

```<code>Select replace(idA, “:XYZ”, "")
from dbA.TableA guid
where event like “%2015”
left join dbB.TableB own
on guid.idA = own.idB
</code>```

答:
Few things

FROM, Joins, WHERE (unless you use subqueries) syntax order it's also the order of execution (notice select isn't listed as its near the end in order of operation but first syntactically!)

alias/fully qualify columns when multiple tables are involved so we know what field comes from what table.

order of operations has the SQL doing the from and JOINS 1st thus what you do in the select isn't available (not in scope yet) for the compiler, this is why you can't use select column aliases in the from, where or even group by as well.

I don't like Select * usually but as I don't know what columns you really need... I used it here.

As far as where before the join.  most SQL compilers anymore use cost based optimization and figure out the best execution plan given your data tables and what not involved.  So just put the limiting criteria in the where in this case since it's limiting the left table of the left join.  If you needed to limit data on the right table of a left join, you'd put the limit on the join criteria; thus allowing it to filter as it joins.

probably need to cast IDA as integer (or to the same type as IDB)  I used trim to eliminate spaces but if there are other non-display characters, you'd have issues with the left join matching)

.

```<code>SELECT guild.*, own.*
FROM dbA.TableA guid
LEFT JOIN  dbB.TableB own
  on cast(trim(replace(guid.idA, ':XYZ', '')) as int) = own.idB
WHERE guid.event like '%2015'
</code>```

Or materialize the transformation first by using a subquery so IDA in its transformed state before the join (like algebra ()'s matter and get processed inside out)

```<code>SELECT *
FROM (SELECT cast(trim(replace(guid.idA, ':XYZ', '')) as int) as idA
      FROM dbA.TableA guid
      WHERE guid.event like '%2015') B
LEFT JOIN  dbB.TableB own
  on B.IDA  = own.idB
</code>```

Body:
I am pretty new to SQL. Here is an operation I am sure is simple for a lot of you. I am trying to join two tables across databases on the same server – dbB and dbA, and TableA (with IdA) and TableB (with IdB) respectively. But before doing that I want to transform column IdA into a number, where I would like to remove the “:XYZ” character from its values and add a where statement for another column in dbA too. Below I show my code for the join but I am not sure how to convert the values of the column. This allows me to match idAwith idB in the join. Thanks a ton in advance.

Select replace(idA, “:XYZ”, "")
from dbA.TableA guid
where event like “%2015”
left join dbB.TableB own
on guid.idA = own.idB

Body:
Few things

FROM, Joins, WHERE (unless you use subqueries) syntax order it's also the order of execution (notice select isn't listed as its near the end in order of operation but first syntactically!)

alias/fully qualify columns when multiple tables are involved so we know what field comes from what table.

order of operations has the SQL doing the from and JOINS 1st thus what you do in the select isn't available (not in scope yet) for the compiler, this is why you can't use select column aliases in the from, where or even group by as well.

I don't like Select * usually but as I don't know what columns you really need... I used it here.

As far as where before the join.  most SQL compilers anymore use cost based optimization and figure out the best execution plan given your data tables and what not involved.  So just put the limiting criteria in the where in this case since it's limiting the left table of the left join.  If you needed to limit data on the right table of a left join, you'd put the limit on the join criteria; thus allowing it to filter as it joins.

probably need to cast IDA as integer (or to the same type as IDB)  I used trim to eliminate spaces but if there are other non-display characters, you'd have issues with the left join matching)

.

SELECT guild.*, own.*
FROM dbA.TableA guid
LEFT JOIN  dbB.TableB own
  on cast(trim(replace(guid.idA, ':XYZ', '')) as int) = own.idB
WHERE guid.event like '%2015'

Or materialize the transformation first by using a subquery so IDA in its transformed state before the join (like algebra ()'s matter and get processed inside out)

SELECT *
FROM (SELECT cast(trim(replace(guid.idA, ':XYZ', '')) as int) as idA
      FROM dbA.TableA guid
      WHERE guid.event like '%2015') B
LEFT JOIN  dbB.TableB own
  on B.IDA  = own.idB


问:
MYSQL QUERY if exists then get that specific column value and compare with new value
I am trying to compare a new value with the existing value from data based in a SQL statement, i.e. go to table get the specific value and check if the value is greater then the new value then update some other table, else do nothing.

My problem is that i am not able to convert the query value as a string to compare in a if statement.

My code:

```<code>IF (EXISTS (SELECT * FROM table_1 WHERE   Id =NEW.Id and  time = NEW.time ORDER BY price ASC LIMIT 1)) THEN

        IF (price <  NEW.price) THEN
//----------^^^^^^----------------- there is one column in table_1 not able to convert it to string to check in if statement///

            UPDATE historical SET low_price = NEW.price  WHERE  id =NEW.Id and date_time = NEW.time;

        END IF;
    END IF;
</code>```

答:
If price is a column in table_1, you can move the second if condition to the first if condition.</p>

```<code>IF (EXISTS (SELECT * FROM table_1 WHERE   Id =NEW.Id and  time = NEW.time and price <  NEW.price ORDER BY price ASC LIMIT 1)) THEN

        UPDATE historical SET low_price = NEW.price  WHERE  id =NEW.Id and date_time = NEW.time;

END IF;
</code>```

Body:
I am trying to compare a new value with the existing value from data based in a SQL statement, i.e. go to table get the specific value and check if the value is greater then the new value then update some other table, else do nothing.

My problem is that i am not able to convert the query value as a string to compare in a if statement.

My code:

IF (EXISTS (SELECT * FROM table_1 WHERE   Id =NEW.Id and  time = NEW.time ORDER BY price ASC LIMIT 1)) THEN

        IF (price <  NEW.price) THEN
//----------^^^^^^----------------- there is one column in table_1 not able to convert it to string to check in if statement///

            UPDATE historical SET low_price = NEW.price  WHERE  id =NEW.Id and date_time = NEW.time;

        END IF;
    END IF;

Body:
If price is a column in table_1, you can move the second if condition to the first if condition.

IF (EXISTS (SELECT * FROM table_1 WHERE   Id =NEW.Id and  time = NEW.time and price <  NEW.price ORDER BY price ASC LIMIT 1)) THEN

        UPDATE historical SET low_price = NEW.price  WHERE  id =NEW.Id and date_time = NEW.time;

END IF;


问:
WSO2 mapping email to user via ldap
I am attempting to add google as an identity provider to wso2.  I have
it configured to the point where wso2 send me to google for
authentication and google returns an email address.  wso2 is then trying
to use the email address as the username.  It is using the following
ldap filter query:

```<code>    (&(objectClass=account)(uid=myemail@domain.edu))
</code>```

When it should be using something like:

```<code>    (&(objectClass=account)(mail=myemail@domain.edu))
</code>```

How do I affect this change in wso2?

答:
The solution was to edit repository/conf/user-mgmt.xml and fine the line:

```<code>(&(objectClass=account)(uid=?))
</code>```

and modify it to:

```<code>(&(objectClass=account)(|(uid=?)(mail=?)))
</code>```

This allows it to find the ldap entry if it is passed a username or an email address.

Title: WSO2 mapping email to user via ldap

Body:
I am attempting to add google as an identity provider to wso2.  I have
it configured to the point where wso2 send me to google for
authentication and google returns an email address.  wso2 is then trying
to use the email address as the username.  It is using the following
ldap filter query:

    (&(objectClass=account)(uid=myemail@domain.edu))

When it should be using something like:

    (&(objectClass=account)(mail=myemail@domain.edu))

How do I affect this change in wso2?

Body:
The solution was to edit repository/conf/user-mgmt.xml and fine the line:

(&(objectClass=account)(uid=?))

and modify it to:

(&(objectClass=account)(|(uid=?)(mail=?)))

This allows it to find the ldap entry if it is passed a username or an email address.


问:
php get info from mysql
So by the way i want to get the nickname of member by faction id. but its not printing name. whats wrong with my code? when i print $nickname its not giving me anything too.</p>

```<code><?php
require 'db.php';
session_start();

$result = $mysqli->query("SELECT nickname FROM members WHERE fraction='3'");

print($result->num_rows);
?>
  <div class="form">

      <ul class="tab-group">
        <li class="tab"><a href="#lspd">LS-PD</a></li>
        <li class="tab active"><a href="#ballas">BALLAS</a></li>
      </ul>

      <div class="tab-content">
        <div id="ballas">
          <h1>Ballas</h1>

          <form action="index.php" method="post" autocomplete="off">

          <div class="top-row">
            <div class="field-wrap">
              <label>
                Name<span class="req">*</span>
              </label>
            </div>
          </div>
          <?php
          if ($result->num_rows > 0)
          {
            while($row = $result->fetch_assoc())
            {
              echo "<p class='monitoring-name'>" . $row['nickname'] . "</p><br>";
            }
          }
          ?>
          </form>
        </div>
      </div><!-- tab-content -->

</div> <!-- /form -->
</code>```

答:
This may help you. Add a check to make sure that your query is right, so if it is then it will run the code, else it will generate an error:</p>

```<code>$query = "SELECT nickname FROM members WHERE fraction = 3";
if ($result = $mysqli->query($query))
{
    if ($result->num_rows > 0)
    {
        while($row = $result->fetch_assoc())
        {
            echo "<p class='monitoring-name'>" . $row['nickname'] . "</p><br>";
        }
    }
    else
    {
        echo "No results found"; // pretty clear?
    }
}
else
{
    // if there's an error with your query it will display this message:
    echo "There was a problem with your query";
}
</code>```

Title: php get info from mysql

Body:
So by the way i want to get the nickname of member by faction id. but its not printing name. whats wrong with my code? when i print $nickname its not giving me anything too.

<?php
require 'db.php';
session_start();

$result = $mysqli->query("SELECT nickname FROM members WHERE fraction='3'");

print($result->num_rows);
?>

LS-PD

BALLAS

Ballas

          <form action="index.php" method="post" autocomplete="off">

                Name*

          <?php
          if ($result->num_rows > 0)
          {
            while($row = $result->fetch_assoc())
            {
              echo "
" . $row['nickname'] . "

";
            }
          }
          ?>
          </form>

Body:
This may help you. Add a check to make sure that your query is right, so if it is then it will run the code, else it will generate an error:

$query = "SELECT nickname FROM members WHERE fraction = 3";
if ($result = $mysqli->query($query))
{
    if ($result->num_rows > 0)
    {
        while($row = $result->fetch_assoc())
        {
            echo "<p class='monitoring-name'>" . $row['nickname'] . "</p><br>";
        }
    }
    else
    {
        echo "No results found"; // pretty clear?
    }
}
else
{
    // if there's an error with your query it will display this message:
    echo "There was a problem with your query";
}


问:
Google OAuth Redirect Uri Mismatch (authorization_code)
I am having a problem to understand the correct purpose of the redirect uri. Following the Google tutorial the javascript API allows me to get a authorizationCode without any redirect URI at all.

Then I send this code to my server and try to call the /token endpoint with this code. But then it will return a "redirect URI mismatch" which probably means that I need to define the same redirect_uri for this endpoint than I did with the javascript API. My only problem is that I dont specify any on my website.

Anyone knows how to correctly use them?

The flow I am trying to achieve is the following:
- Javascript website asks user for permission, getting the authorization code
- Code is sent to my server
- Server receives access/refresh token with this code and stores it safely

答: Please pass your javascript origin in the "redirect_uri" parameter when you are exchanging the code. This should work.</p>


问:
Soundcloud iframe doesn't work with UIWebView swift
I'm using iframe and 'Widget API' to control the streaming.
When i call 'Play(); or 'Pause();' the play button is changing but is not playing audio.

```<code>@IBOutlet weak var videoWebView: UIWebView!
var soundCloudIsLoaded : Bool = false
var isPlaying : Bool = false

override func viewDidLoad() {
    super.viewDidLoad()

    self.videoWebView.isUserInteractionEnabled = true
    self.videoWebView.allowsInlineMediaPlayback = true
    var htmlString = "<iframe id=\"sc-widget\" width=\"100%\" height=\"350\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F1848538&color=ff5500&auto_play=false&hide_related=true&show_comments=false&show_user=false&show_reposts=false&buying=false&liking=false&download=false&sharing=false&show_artwork=false&show_playcount=false\" playsinline></iframe><script src=\"https://w.soundcloud.com/player/api.js\" type=\"text/javascript\"></script><script type=\"text/javascript\">var duration = 0;var position = 0;var isLoaded = false;var isPaused = true;var widgetIframe = document.getElementById('sc-widget'), widget = SC.Widget(widgetIframe), newSoundUrl = '{{url}}';widget.load(newSoundUrl, { show_artwork: false, hide_related : true, show_comments : false, show_user : false, show_reposts : false, buying : false, liking : false, download : false, sharing : false, show_playcount : false});widget.bind(SC.Widget.Events.READY, function(){ isLoaded = true; widget.getDuration(function(dur){ duration = parseInt(dur); }); setInterval(function() { widget.getDuration(function(dur){ duration = parseInt(dur); }); widget.getPosition(function(pos){ position = parseInt(pos); }); }, 500);});widget.bind(SC.Widget.Events.PLAY, function(){ isPaused = false;});widget.bind(SC.Widget.Events.PAUSE, function(){ isPaused = true;});function Play() { widget.play();}function Pause() { widget.pause();}function Toggle() { widget.toggle();}function SeekTo(milliseconds) { widget.seekTo(milliseconds); widget.getPosition(function(pos){ position = parseInt(pos); }); }function getDuration() { return duration;}function getPosition() { return position;}function soundCloudIsLoaded(){ return isLoaded;}function IsPaused(){ return isPaused;}</script>"
    htmlString = htmlString.replacingOccurrences(of: "{{url}}", with: "URL")
    self.videoWebView.loadHTMLString(htmlString, baseURL: nil)
    self.videoWebView.delegate = self
}

@IBAction func playButtonAction(_ sender: Any) {
        if self.soundCloudIsLoaded {
            self.isPlaying = !self.isPlaying

            if self.isPlaying {
                let _ = self.videoWebView.stringByEvaluatingJavaScript(from: "Play();")
                self.playButton.setTitle("Pause", for: .normal)
            } else {
                let _ = self.videoWebView.stringByEvaluatingJavaScript(from: "Pause();")
                self.playButton.setTitle("Play", for: .normal)
            }
        }
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    self.soundCloudIsLoaded = true
}
</code>```

In htmlString I have this code:

```<code><iframe id="sc-widget" width="100%" height="350" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F1848538&color=ff5500&auto_play=false&hide_related=true&show_comments=false&show_user=false&show_reposts=false&buying=false&liking=false&download=false&sharing=false&show_artwork=false&show_playcount=false"></iframe>
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<script type="text/javascript">

var duration = 0;
var position = 0;
var isLoaded = false;
var isPaused = true;

var widgetIframe    = document.getElementById('sc-widget'),
    widget          = SC.Widget(widgetIframe),
    newSoundUrl     = '{{url}}';

widget.load(newSoundUrl, {
    show_artwork: false,
    auto_play : false,
    hide_related : true,
    show_comments : false,
    show_user : false,
    show_reposts : false,
    buying : false,
    liking : false,
    download : false,
    sharing : false,
    show_playcount : false
});

widget.bind(SC.Widget.Events.READY, function(){
    isLoaded = true;
    widget.getDuration(function(dur){
        duration = parseInt(dur);
    });
    setInterval(function() {
        widget.getPosition(function(pos){
            position = parseInt(pos);
        });
        widget.getDuration(function(dur){
            duration = parseInt(dur);
        });
    }, 500);
});

widget.bind(SC.Widget.Events.PLAY, function(){
    isPaused = false;
});

widget.bind(SC.Widget.Events.PAUSE, function(){
    isPaused = true;
});

function Play() {
    widget.play();
}

function Pause() {
    widget.pause();
}

function Toggle() {
    widget.toggle();
}

function SeekTo(milliseconds) {
    widget.seekTo(milliseconds);
    widget.getPosition(function(pos){
        position = parseInt(pos);
    });
}

function getDuration() {
    return duration;
}

function getPosition() {
    return position;
}

function soundCloudIsLoaded(){
    return isLoaded;
}

function IsPaused(){
    return isPaused;
}

</script>
</code>```

This code used to work fine, but it stopped working suddenly on IOS webView. This works fine on Desktop Browser.

答:
Just replace UIWebView with WKWebView:

```<code>import UIKit
import WebKit

class ViewController: UIViewController {
    @IBOutlet weak var playButton: UIButton!
    var isPlaying : Bool = false
    var webView: WKWebView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: self.view.bounds, configuration: webConfiguration)
        if let webView = webView {
            self.view.addSubview(webView)
            let viewBindingsDict = ["subView": webView]
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:"H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict))
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:"V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict))

            self.view.bringSubview(toFront: self.playButton)
            var htmlString = "<iframe id=\"sc-widget\" width=\"100%\" height=\"350\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F1848538&color=ff5500&auto_play=false&hide_related=true&show_comments=false&show_user=false&show_reposts=false&buying=false&liking=false&download=false&sharing=false&show_artwork=false&show_playcount=false\" playsinline></iframe><script src=\"https://w.soundcloud.com/player/api.js\" type=\"text/javascript\"></script><script type=\"text/javascript\">var duration = 0;var position = 0;var isLoaded = false;var isPaused = true;var widgetIframe = document.getElementById('sc-widget'), widget = SC.Widget(widgetIframe), newSoundUrl = '{{url}}';widget.load(newSoundUrl, { show_artwork: false, hide_related : true, show_comments : false, show_user : false, show_reposts : false, buying : false, liking : false, download : false, sharing : false, show_playcount : false});widget.bind(SC.Widget.Events.READY, function(){ isLoaded = true; widget.getDuration(function(dur){ duration = parseInt(dur); }); setInterval(function() { widget.getDuration(function(dur){ duration = parseInt(dur); }); widget.getPosition(function(pos){ position = parseInt(pos); }); }, 500);});widget.bind(SC.Widget.Events.PLAY, function(){ isPaused = false;});widget.bind(SC.Widget.Events.PAUSE, function(){ isPaused = true;});function Play() { widget.play();}function Pause() { widget.pause();}function Toggle() { widget.toggle();}function SeekTo(milliseconds) { widget.seekTo(milliseconds); widget.getPosition(function(pos){ position = parseInt(pos); }); }function getDuration() { return duration;}function getPosition() { return position;}function soundCloudIsLoaded(){ return isLoaded;}function IsPaused(){ return isPaused;}</script>"
            htmlString = htmlString.replacingOccurrences(of: "{{url}}", with: "https://soundcloud.com/hunterhayesofficial/rescue")

            webView.loadHTMLString(htmlString, baseURL: nil)
        }
    }

    @IBAction func playButtonAction(_ sender: Any) {
        self.isPlaying = !self.isPlaying

        if self.isPlaying {
            let _ = webView?.evaluateJavaScript("Play();") { [weak self] responce, error in
                guard error == nil else {
                    print("An error occured: \(String(describing: error?.localizedDescription))")
                    return
                }
                self?.playButton.setTitle("Pause", for: .normal)
            }
        } else {
            let _ = webView?.evaluateJavaScript("Pause();") { [weak self] responce, error in
                guard error == nil else {
                    print("An error occured: \(String(describing: error?.localizedDescription))")
                    return
                }
                self?.playButton.setTitle("Play", for: .normal)
            }
        }
    }
}
</code>```

Body:
I'm using iframe and 'Widget API' to control the streaming.
When i call 'Play(); or 'Pause();' the play button is changing but is not playing audio.

@IBOutlet weak var videoWebView: UIWebView!
var soundCloudIsLoaded : Bool = false
var isPlaying : Bool = false

override func viewDidLoad() {
    super.viewDidLoad()

    self.videoWebView.isUserInteractionEnabled = true
    self.videoWebView.allowsInlineMediaPlayback = true
    var htmlString = ""
    htmlString = htmlString.replacingOccurrences(of: "{{url}}", with: "URL")
    self.videoWebView.loadHTMLString(htmlString, baseURL: nil)
    self.videoWebView.delegate = self
}

@IBAction func playButtonAction(_ sender: Any) {
        if self.soundCloudIsLoaded {
            self.isPlaying = !self.isPlaying

            if self.isPlaying {
                let _ = self.videoWebView.stringByEvaluatingJavaScript(from: "Play();")
                self.playButton.setTitle("Pause", for: .normal)
            } else {
                let _ = self.videoWebView.stringByEvaluatingJavaScript(from: "Pause();")
                self.playButton.setTitle("Play", for: .normal)
            }
        }
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    self.soundCloudIsLoaded = true
}

In htmlString I have this code:

This code used to work fine, but it stopped working suddenly on IOS webView. This works fine on Desktop Browser.

Body:
Just replace UIWebView with WKWebView:

import UIKit
import WebKit

class ViewController: UIViewController {
    @IBOutlet weak var playButton: UIButton!
    var isPlaying : Bool = false
    var webView: WKWebView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: self.view.bounds, configuration: webConfiguration)
        if let webView = webView {
            self.view.addSubview(webView)
            let viewBindingsDict = ["subView": webView]
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:"H:|[subView]|", options: [], metrics: nil, views: viewBindingsDict))
            view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:"V:|[subView]|", options: [], metrics: nil, views: viewBindingsDict))

            self.view.bringSubview(toFront: self.playButton)
            var htmlString = "<iframe id=\"sc-widget\" width=\"100%\" height=\"350\" scrolling=\"no\" frameborder=\"no\" src=\"https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F1848538&amp;color=ff5500&amp;auto_play=false&amp;hide_related=true&amp;show_comments=false&amp;show_user=false&amp;show_reposts=false&amp;buying=false&amp;liking=false&amp;download=false&amp;sharing=false&amp;show_artwork=false&amp;show_playcount=false\" playsinline></iframe><script src=\"https://w.soundcloud.com/player/api.js\" type=\"text/javascript\"></script><script type=\"text/javascript\">var duration = 0;var position = 0;var isLoaded = false;var isPaused = true;var widgetIframe = document.getElementById('sc-widget'), widget = SC.Widget(widgetIframe), newSoundUrl = '{{url}}';widget.load(newSoundUrl, { show_artwork: false, hide_related : true, show_comments : false, show_user : false, show_reposts : false, buying : false, liking : false, download : false, sharing : false, show_playcount : false});widget.bind(SC.Widget.Events.READY, function(){ isLoaded = true; widget.getDuration(function(dur){ duration = parseInt(dur); }); setInterval(function() { widget.getDuration(function(dur){ duration = parseInt(dur); }); widget.getPosition(function(pos){ position = parseInt(pos); }); }, 500);});widget.bind(SC.Widget.Events.PLAY, function(){ isPaused = false;});widget.bind(SC.Widget.Events.PAUSE, function(){ isPaused = true;});function Play() { widget.play();}function Pause() { widget.pause();}function Toggle() { widget.toggle();}function SeekTo(milliseconds) { widget.seekTo(milliseconds); widget.getPosition(function(pos){ position = parseInt(pos); }); }function getDuration() { return duration;}function getPosition() { return position;}function soundCloudIsLoaded(){ return isLoaded;}function IsPaused(){ return isPaused;}</script>"
            htmlString = htmlString.replacingOccurrences(of: "{{url}}", with: "https://soundcloud.com/hunterhayesofficial/rescue")

            webView.loadHTMLString(htmlString, baseURL: nil)
        }
    }

    @IBAction func playButtonAction(_ sender: Any) {
        self.isPlaying = !self.isPlaying

        if self.isPlaying {
            let _ = webView?.evaluateJavaScript("Play();") { [weak self] responce, error in
                guard error == nil else {
                    print("An error occured: \(String(describing: error?.localizedDescription))")
                    return
                }
                self?.playButton.setTitle("Pause", for: .normal)
            }
        } else {
            let _ = webView?.evaluateJavaScript("Pause();") { [weak self] responce, error in
                guard error == nil else {
                    print("An error occured: \(String(describing: error?.localizedDescription))")
                    return
                }
                self?.playButton.setTitle("Play", for: .normal)
            }
        }
    }
}


问:
How to change the color of Preprocessor Conditionals such as #if in Vistual Studio?
Is there a method to change the color of  Preprocessor Conditionals such as,

```<code>#if
#ifdef
#ifndef
#endif
</code>```

I do work on large C libraries which use plenty of  Preprocessor Conditionals and as you can see in the example below, this really limits the readability of the code as C programmers conventionally do not indent these conditionals.
Graying out these lines using Keywork Highlighting would be a big help on not confusing these un-indented lines as the end of long if statements etc.

Example code,

```<code>    ...
   if( ... )
    {

        for( uint8_t i = 0, k = 0; i < FOO; i += 16, k++ )
        {
            for( uint8_t j = 0; j < 16; j++ )
            {
#if defined( BAZ ) || defined( BAR )
                if( ... )
#else
                if( ... )
#endif
                {
                    if( ... )
                    {
                        continue;
                    }
#if defined( BAZ_ ) || defined( BAR_ ) || defined( FOO_ )
                    if( ... )
                    {
                        if( ... )
                        {
                            continue;
                        }
                    }
#endif
                    if( ... )
                    {
                        continue;
                    }
                    if( ... )
                    {
                        foo++;
                        continue;
                    }
                }
            }
        }
    }
    ...
</code>```

Note: I have phrased the question for Visual Studio, however, I will be using the solution in Atmel Studio which is basically a re-badged version of the same software. I have successfully install most of the VS add-ons to Atmel Studio in the past but tbh I haven't given a R# a go, if your solution is going to include it.

Update:

After posting the question I actually noticed the Syntax Highlighting on Stackoverflow does an amazing job doing exactly what I have in mind. The # conditions are grayed out and the rest of the code reads beautifully. I would like to be able to do the same on VS/AS.

答:
A year or two ago I ran across the solution: Naggy. Among several other features (which I find useful), it grays out preprocessor conditionals just like you expect and want.

In Atmel Studio 7.0 it's available in the built-in Extensions Gallery. Install from there, restart AS, and you're good to go. There are no options or configuration settings; it's very simple, and works great.

I also had it working in Atmel Studio 6.2, but seems like I had to install it manually or something. This AVR Freaks thread should help.

Body:
Is there a method to change the color of  Preprocessor Conditionals such as,

#if
#ifdef
#ifndef
#endif

I do work on large C libraries which use plenty of  Preprocessor Conditionals and as you can see in the example below, this really limits the readability of the code as C programmers conventionally do not indent these conditionals.
Graying out these lines using Keywork Highlighting would be a big help on not confusing these un-indented lines as the end of long if statements etc.

Example code,

    ...
   if( ... )
    {

        for( uint8_t i = 0, k = 0; i < FOO; i += 16, k++ )
        {
            for( uint8_t j = 0; j < 16; j++ )
            {
#if defined( BAZ ) || defined( BAR )
                if( ... )
#else
                if( ... )
#endif
                {
                    if( ... )
                    {
                        continue;
                    }
#if defined( BAZ_ ) || defined( BAR_ ) || defined( FOO_ )
                    if( ... )
                    {
                        if( ... )
                        {
                            continue;
                        }
                    }
#endif
                    if( ... )
                    {
                        continue;
                    }
                    if( ... )
                    {
                        foo++;
                        continue;
                    }
                }
            }
        }
    }
    ...

Note: I have phrased the question for Visual Studio, however, I will be using the solution in Atmel Studio which is basically a re-badged version of the same software. I have successfully install most of the VS add-ons to Atmel Studio in the past but tbh I haven't given a R# a go, if your solution is going to include it.

Update:

After posting the question I actually noticed the Syntax Highlighting on Stackoverflow does an amazing job doing exactly what I have in mind. The # conditions are grayed out and the rest of the code reads beautifully. I would like to be able to do the same on VS/AS.


问:
Using Razor, how do I render a Boolean to a JavaScript variable?
How do I render a Boolean to a JavaScript variable in a cshtml file?

Presently this shows a syntax error:

```<code><script type="text/javascript" >

    var myViewModel = {
        isFollowing: @Model.IsFollowing  // This is a C# bool
    };
</script>
</code>```

答:
Because a search brought me here: in ASP.NET Core, IJsonHelper doesn't have an Encode() method.  Instead, use Serialize(). E.g.:

```<code>isFollowing: @Json.Serialize(Model.IsFollowing)
</code>```

Body:
Because a search brought me here: in ASP.NET Core, IJsonHelper doesn't have an Encode() method.  Instead, use Serialize(). E.g.:

isFollowing: @Json.Serialize(Model.IsFollowing)


问:
sfValidatorFile 'mime_type' validation not working in production server
I've built a backend with a couple of models, one of them, Products, supports image uploading. Locally the file uploading works very fine. When I did the deploy, it stopped working: the form validation fails because of wrong mime type (error is: "Invalid mime type (jpeg image data, exif standard).") for the image field, even when i'm using the same JPG image that i used to test locally.

I'll show you my form class code:

```<code>class ProductForm extends BaseProductForm
{
  public function configure()
  {
    ...

    /* Widgets */
    ...
    $this->widgetSchema['image_1'] = new sfWidgetFormInputFileEditable(array(
      'file_src' => '/'.basename(sfConfig::get('sf_upload_dir')).'/products/normal_'.$this->getObject()->getImage_1(),
      'is_image' => true,
      'edit_mode' => strlen($this->getObject()->getImage_1()) > 0,
      'delete_label' => 'remover el archivo actual',
      'template'  => '<div>%file%<br />%input%</div>'
    ));
    ...

    /* Validators */
    $this->validatorSchema['image_1'] = new sfValidatorFileImage(array(
      'required' => (! $this->getObject()->getImage_1()),
      'max_size' => '5252880',
      'path' => sfConfig::get('sf_upload_dir').'/products/original',
      'mime_types' => 'web_images',
      'min_width' =>  470,
      'max_width' => 99999,
      'min_height' =>  306,
      'max_height' => 99999,
      'validated_file_class' => 'sfResizedFile',   // This class creates the thumbnails
    ), array(
      'required' => 'Tenés que seleccionar una imagen principal.',
      'max_size' => 'El tamaño máximo es 5 MB',
      //'mime_types' => 'Sólo se permiten imágenes para web (jpg, png, gif)',
      'invalid_image' => '%value% no es un archivo de imagen.',
      'min_width' => 'El ancho de "%value%" es muy chico (mínimo %min_width% pixels).',
      'min_height' => 'El alto de "%value%" es muy chico (mínimo %min_height% pixels).',
    ));
    $this->validatorSchema['image_1_delete'] = new sfValidatorPass();
    ...
  }
  ...
</code>```

sfValidatorFileImage is just a custom validator class that extends sfValidatorFile with size checks. I've tried with the regular sfValidatorFile class just in case, but the error persists. Does mime types have something to do with server configuration? And why would it break on a regular web server?

Speed in answer is really appreciated since this was needed deployed today.

答:
The only solution I could find is commenting the first item in the array of "mime_type_guessers" option of the sfValidatorFile class, the one that reads "guessFromFileinfo", specifically. Here is the code:

(lib/vendor/symfony/lib/validator/sfValidatorFile.class.php - line 62 aprox.)

```<code>$this->addOption('mime_type_guessers', array(
  //array($this, 'guessFromFileinfo'),
  array($this, 'guessFromMimeContentType'),
  array($this, 'guessFromFileBinary'),
));
</code>```

Also, copying this file to lib/ and commenting the line in that file didn't worked, Symfony did always used the one in lib/vendor/symfony/lib/ so I did the change there.

Body:
I've built a backend with a couple of models, one of them, Products, supports image uploading. Locally the file uploading works very fine. When I did the deploy, it stopped working: the form validation fails because of wrong mime type (error is: "Invalid mime type (jpeg image data, exif standard).") for the image field, even when i'm using the same JPG image that i used to test locally.

I'll show you my form class code:

class ProductForm extends BaseProductForm
{
  public function configure()
  {
    ...

    /* Widgets */
    ...
    $this->widgetSchema['image_1'] = new sfWidgetFormInputFileEditable(array(
      'file_src' => '/'.basename(sfConfig::get('sf_upload_dir')).'/products/normal_'.$this->getObject()->getImage_1(),
      'is_image' => true,
      'edit_mode' => strlen($this->getObject()->getImage_1()) > 0,
      'delete_label' => 'remover el archivo actual',
      'template'  => '
%file%
%input%
'
    ));
    ...

    /* Validators */
    $this->validatorSchema['image_1'] = new sfValidatorFileImage(array(
      'required' => (! $this->getObject()->getImage_1()),
      'max_size' => '5252880',
      'path' => sfConfig::get('sf_upload_dir').'/products/original',
      'mime_types' => 'web_images',
      'min_width' =>  470,
      'max_width' => 99999,
      'min_height' =>  306,
      'max_height' => 99999,
      'validated_file_class' => 'sfResizedFile',   // This class creates the thumbnails
    ), array(
      'required' => 'Tenés que seleccionar una imagen principal.',
      'max_size' => 'El tamaño máximo es 5 MB',
      //'mime_types' => 'Sólo se permiten imágenes para web (jpg, png, gif)',
      'invalid_image' => '%value% no es un archivo de imagen.',
      'min_width' => 'El ancho de "%value%" es muy chico (mínimo %min_width% pixels).',
      'min_height' => 'El alto de "%value%" es muy chico (mínimo %min_height% pixels).',
    ));
    $this->validatorSchema['image_1_delete'] = new sfValidatorPass();
    ...
  }
  ...

sfValidatorFileImage is just a custom validator class that extends sfValidatorFile with size checks. I've tried with the regular sfValidatorFile class just in case, but the error persists. Does mime types have something to do with server configuration? And why would it break on a regular web server?

Speed in answer is really appreciated since this was needed deployed today.

Body:
The only solution I could find is commenting the first item in the array of "mime_type_guessers" option of the sfValidatorFile class, the one that reads "guessFromFileinfo", specifically. Here is the code:

(lib/vendor/symfony/lib/validator/sfValidatorFile.class.php - line 62 aprox.)

$this->addOption('mime_type_guessers', array(
  //array($this, 'guessFromFileinfo'),
  array($this, 'guessFromMimeContentType'),
  array($this, 'guessFromFileBinary'),
));

Also, copying this file to lib/ and commenting the line in that file didn't worked, Symfony did always used the one in lib/vendor/symfony/lib/ so I did the change there.


问:
Convert Number into english Word-Meaning using XSLT
I am very much new to XSLT and have a weird requirement for which I have not found any solution. Server side we have XSLT of version 2.0.

Input number can be from Zero (0) to any value up to 8-digit number.
I need to convert this into its English Word-Meaning following specific format.

If number is of 5 digit (Example - 28651) then First three set will be of 5-Astric (*****) followed by 2-space, so total 7.

If English word of any digit contains less than 5 letter (example 6 SIX then it must be followed by 2+2=4 spaces to make it equivalent to 5 letter English WORD)

For the Last digit of the number must also followed by 2 spaces as above.

```<code>   INPUT       OUTPUT (Without Enclosing Double-Quote)

    9375 = "*****  *****  *****  *****  NINE   THREE  SEVEN  FIVE   "
    8623 = "*****  *****  *****  *****  EIGHT  SIX    TWO    THREE  "
       0 = "*****  *****  *****  *****  *****  *****  *****  ZERO   "
   28651 = "*****  *****  *****  TWO    EIGHT  SIX    FIVE   ONE    "

40378623 = "FOUR   ZERO   THREE  SEVEN  EIGHT  SIX    TWO    THREE  "
</code>```

I am not able to perform any below operation which is quite easy with Java.

1.)  Assign any value to existing variable back.
2.)  Taking the reverse of the number (345 to 543)
3.)  Fetch out each digit separately in any array or something.

This is what I was thinking for its approach.

答:
I wrote something like this below to achieve my requirement which is very basic way of coding as i am novice to its syntax. But this is working in a way what I need for. I agree this is not a good practice of coding.</p>

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

      <xsl:template name="digits">

        <xsl:param name="text" />

        <xsl:if test="$text != ''">

          <xsl:variable name="letter" select="substring($text, 1, 1)" />

          <xsl:if test="$letter = '0'">
           <xsl:text>ZERO   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '1'">
           <xsl:text>ONE    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '2'">
           <xsl:text>TWO    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '3'">
           <xsl:text>THREE  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '4'">
           <xsl:text>FOUR   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '5'">
           <xsl:text>FIVE   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '6'">
           <xsl:text>SIX    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '7'">
           <xsl:text>SEVEN  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '8'">
           <xsl:text>EIGHT  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '9'">
           <xsl:text>NINE   </xsl:text>
          </xsl:if>

          <xsl:call-template name="digits">
            <xsl:with-param name="text" select="substring-after($text, $letter)" />
          </xsl:call-template>

        </xsl:if>

      </xsl:template>

      <xsl:template match="/">
          <xsl:variable name="Vnum">
             <xsl:number value="/Payment/Amount"/>
          </xsl:variable>
          <xsl:variable name="Vlen">
            <xsl:value-of select="string-length($Vnum)" />
          </xsl:variable>

                    <xsl:if test="$Vlen = '1'">
                        <xsl:text>*****  *****  *****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '2'">
                        <xsl:text>*****  *****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '3'">
                        <xsl:text>*****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '4'">
                        <xsl:text>*****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '5'">
                        <xsl:text>*****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '6'">
                        <xsl:text>*****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '7'">
                        <xsl:text>*****  </xsl:text>
                    </xsl:if>

          <xsl:call-template name="digits">
            <xsl:with-param name="text" select="$Vnum"/>
          </xsl:call-template>
      </xsl:template>
    </xsl:stylesheet>
</code>```

Body:
I am very much new to XSLT and have a weird requirement for which I have not found any solution. Server side we have XSLT of version 2.0.

Input number can be from Zero (0) to any value up to 8-digit number.
I need to convert this into its English Word-Meaning following specific format.

If number is of 5 digit (Example - 28651) then First three set will be of 5-Astric (*****) followed by 2-space, so total 7.

If English word of any digit contains less than 5 letter (example 6 SIX then it must be followed by 2+2=4 spaces to make it equivalent to 5 letter English WORD)

For the Last digit of the number must also followed by 2 spaces as above.

   INPUT       OUTPUT (Without Enclosing Double-Quote)

    9375 = "*****  *****  *****  *****  NINE   THREE  SEVEN  FIVE   "
    8623 = "*****  *****  *****  *****  EIGHT  SIX    TWO    THREE  "
       0 = "*****  *****  *****  *****  *****  *****  *****  ZERO   "
   28651 = "*****  *****  *****  TWO    EIGHT  SIX    FIVE   ONE    "

40378623 = "FOUR   ZERO   THREE  SEVEN  EIGHT  SIX    TWO    THREE  "

I am not able to perform any below operation which is quite easy with Java.

1.)  Assign any value to existing variable back.
2.)  Taking the reverse of the number (345 to 543)
3.)  Fetch out each digit separately in any array or something.

This is what I was thinking for its approach.

Body:
I wrote something like this below to achieve my requirement which is very basic way of coding as i am novice to its syntax. But this is working in a way what I need for. I agree this is not a good practice of coding.

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

      <xsl:template name="digits">

        <xsl:param name="text" />

        <xsl:if test="$text != ''">

          <xsl:variable name="letter" select="substring($text, 1, 1)" />

          <xsl:if test="$letter = '0'">
           <xsl:text>ZERO   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '1'">
           <xsl:text>ONE    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '2'">
           <xsl:text>TWO    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '3'">
           <xsl:text>THREE  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '4'">
           <xsl:text>FOUR   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '5'">
           <xsl:text>FIVE   </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '6'">
           <xsl:text>SIX    </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '7'">
           <xsl:text>SEVEN  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '8'">
           <xsl:text>EIGHT  </xsl:text>
          </xsl:if>
          <xsl:if test="$letter = '9'">
           <xsl:text>NINE   </xsl:text>
          </xsl:if>

          <xsl:call-template name="digits">
            <xsl:with-param name="text" select="substring-after($text, $letter)" />
          </xsl:call-template>

        </xsl:if>

      </xsl:template>

      <xsl:template match="/">
          <xsl:variable name="Vnum">
             <xsl:number value="/Payment/Amount"/>
          </xsl:variable>
          <xsl:variable name="Vlen">
            <xsl:value-of select="string-length($Vnum)" />
          </xsl:variable>

                    <xsl:if test="$Vlen = '1'">
                        <xsl:text>*****  *****  *****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '2'">
                        <xsl:text>*****  *****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '3'">
                        <xsl:text>*****  *****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '4'">
                        <xsl:text>*****  *****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '5'">
                        <xsl:text>*****  *****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '6'">
                        <xsl:text>*****  *****  </xsl:text>
                    </xsl:if>
                    <xsl:if test="$Vlen = '7'">
                        <xsl:text>*****  </xsl:text>
                    </xsl:if>

          <xsl:call-template name="digits">
            <xsl:with-param name="text" select="$Vnum"/>
          </xsl:call-template>
      </xsl:template>
    </xsl:stylesheet>


问:
Lost the ability to use Transformers after migrating to JPA from Hibernate
In our legacy Hibernate-dependent code, which I'm converting to JPA, we had one Direct SQL-based query with a transformer.

```<code>// 1. Create Hibernate Query object
org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());

// 2. Run a transformer
query.setResultTransformer(Transformers.aliasToBean(User.class));

// 3. Obtain Result List
List results = query.list();
</code>```

But now that I've converted this to JPA (which is still using Direct SQL), I can't use the Transformer step anymore, because the JPA syntax doesn't support it.

If I omit the Transformer step, I get a case-sensitivity error as follows regarding one of my fields,

```<code> org.hibernate.QueryException: could not resolve property: ID of: USER_T
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:62)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1859)
</code>```

Because my UserT object has the field named as id (lowercase). My guess is the Transformer is necessary here, but I can't use it with the new JPA syntax.

答:
try this :

```<code>org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
query.createAlias("id", "ID")
query.setResultTransformer(Transformers.aliasToBean(User.class));
</code>```

from AliasToBeanResultTransformer source example :

```<code> *    List resultWithAliasedBean = s.createCriteria(Enrolment.class)
 *          .createAlias("student", "st")
 *          .createAlias("course", "co")
 *          .setProjection( Projections.projectionList()
 *                  .add( Projections.property("co.description"), "courseDescription" )
 *          )
 *          .setResultTransformer( new AliasToBeanResultTransformer(StudentDTO.class) )
 *          .list();
</code>```

also you can extend AliasToBeanResultTransformer and overide method transformTuple(). and apply overided transformer for setResultTransformer()

Body:
In our legacy Hibernate-dependent code, which I'm converting to JPA, we had one Direct SQL-based query with a transformer.

// 1. Create Hibernate Query object
org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());

// 2. Run a transformer
query.setResultTransformer(Transformers.aliasToBean(User.class));

// 3. Obtain Result List
List results = query.list();

But now that I've converted this to JPA (which is still using Direct SQL), I can't use the Transformer step anymore, because the JPA syntax doesn't support it.

If I omit the Transformer step, I get a case-sensitivity error as follows regarding one of my fields,

 org.hibernate.QueryException: could not resolve property: ID of: USER_T
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:62)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1859)

Because my UserT object has the field named as id (lowercase). My guess is the Transformer is necessary here, but I can't use it with the new JPA syntax.

Body:
try this :

org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
query.createAlias("id", "ID")
query.setResultTransformer(Transformers.aliasToBean(User.class));

from AliasToBeanResultTransformer source example :

 *    List resultWithAliasedBean = s.createCriteria(Enrolment.class)
 *          .createAlias("student", "st")
 *          .createAlias("course", "co")
 *          .setProjection( Projections.projectionList()
 *                  .add( Projections.property("co.description"), "courseDescription" )
 *          )
 *          .setResultTransformer( new AliasToBeanResultTransformer(StudentDTO.class) )
 *          .list();

also you can extend AliasToBeanResultTransformer and overide method transformTuple(). and apply overided transformer for setResultTransformer()


问:
c# WinForms - Pass main window's style to dialog boxes
I was just wondering if there was a simpler way of passing style values from the main form to dialog boxes.

My application has user-settable style properties for all the different control types; ForeColor, BackColor, Button ForeColor, Button BackColor, Button FlatStyle etc. I want the dialog boxes to share the same, consistent style.

At the moment, I pass each of these properties to a dialog boxes like this;

(this example shows one of the more simple dialog forms, some have more control types and a lot more style properties)

```<code>using System;
using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public partial class ConfirmDialog : Form
    {
        public Color ButtonBackColour { private get; set; }
        public Color ButtonForeColour { private get; set; }
        public FlatStyle ButtonFlatStyle { private get; set; }

        public string Message { private get; set; }
        public ConfirmDialog()
        {
            InitializeComponent();
        }

        private void ConfirmDialog_Load(object sender, EventArgs e)
        {
            buttonYES.ForeColor = ButtonForeColour;
            buttonCancel.ForeColor = ButtonForeColour;

            buttonYES.BackColor = ButtonBackColour;
            buttonCancel.BackColor = ButtonBackColour;

            buttonYES.FlatStyle = ButtonFlatStyle;
            buttonCancel.FlatStyle = ButtonFlatStyle;

            lblMsg.Text = Message;
        }
    }
}
</code>```

Ok, now I have a static class which I use to hold the dialog  Initializers;

```<code>using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static bool ConfirmDialog(string message, Color foreColour, Color backColour, Color buttonBackColour, Color buttonForeColour, FlatStyle buttonFlatStyle)// more style properties to come later on(flatstyle style props etc)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = foreColour,
                BackColor = backColour,
                ButtonBackColour = buttonBackColour,
                ButtonForeColour = buttonForeColour,
                ButtonFlatStyle = buttonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}
</code>```

And finally, this is the mess of arguments I have to include...

```<code>private void buttonDelete_Click(object sender, EventArgs e)
{
    if (ShowDialog.ConfirmDialog("Are you sure you want to delete...?", this.ForeColour, this.BackColour, buttonDelete.BackColour, buttonDelete.ForeColour, buttonDelete.FlatStyle))// any button from main form will do
    {
        // Delete stuff...
    }
}
</code>```

I am unsure if the static class is redundant, but it will make things a lot easier when the dialog boxes start to mount up.

So instead of having to pass all of these individual style properties around, I was wondering if there is a cleaner way. I know there is no Form.Style property. I suppose I could create one. But I wanted to check first with the Gurus to see if I am missing anything.

答: make sure, all the properties of the main form in [formname].designer.cs are public statics, and in de showdialog you can call them with for example: if you form is called Form1: this.ForceColor = Form1.ForceColor being that those properties are indeed public statics </p>

Body:
I was just wondering if there was a simpler way of passing style values from the main form to dialog boxes.

My application has user-settable style properties for all the different control types; ForeColor, BackColor, Button ForeColor, Button BackColor, Button FlatStyle etc. I want the dialog boxes to share the same, consistent style.

At the moment, I pass each of these properties to a dialog boxes like this;

(this example shows one of the more simple dialog forms, some have more control types and a lot more style properties)

using System;
using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public partial class ConfirmDialog : Form
    {
        public Color ButtonBackColour { private get; set; }
        public Color ButtonForeColour { private get; set; }
        public FlatStyle ButtonFlatStyle { private get; set; }

        public string Message { private get; set; }
        public ConfirmDialog()
        {
            InitializeComponent();
        }

        private void ConfirmDialog_Load(object sender, EventArgs e)
        {
            buttonYES.ForeColor = ButtonForeColour;
            buttonCancel.ForeColor = ButtonForeColour;

            buttonYES.BackColor = ButtonBackColour;
            buttonCancel.BackColor = ButtonBackColour;

            buttonYES.FlatStyle = ButtonFlatStyle;
            buttonCancel.FlatStyle = ButtonFlatStyle;

            lblMsg.Text = Message;
        }
    }
}

Ok, now I have a static class which I use to hold the dialog  Initializers;

using System.Drawing;
using System.Windows.Forms;

namespace MyApplication
{
    public static class ShowDialog
    {
        public static bool ConfirmDialog(string message, Color foreColour, Color backColour, Color buttonBackColour, Color buttonForeColour, FlatStyle buttonFlatStyle)// more style properties to come later on(flatstyle style props etc)
        {
            bool confirm = false;
            using (ConfirmDialog Dialog = new ConfirmDialog()
            {
                Message = message,
                ForeColor = foreColour,
                BackColor = backColour,
                ButtonBackColour = buttonBackColour,
                ButtonForeColour = buttonForeColour,
                ButtonFlatStyle = buttonFlatStyle
            })
            {
                DialogResult dr = Dialog.ShowDialog();
                if (dr == DialogResult.Yes)
                {
                    confirm = true;
                }
                else
                {
                    confirm = false;
                }
            }
            return confirm;
        }
    }
}

And finally, this is the mess of arguments I have to include...

private void buttonDelete_Click(object sender, EventArgs e)
{
    if (ShowDialog.ConfirmDialog("Are you sure you want to delete...?", this.ForeColour, this.BackColour, buttonDelete.BackColour, buttonDelete.ForeColour, buttonDelete.FlatStyle))// any button from main form will do
    {
        // Delete stuff...
    }
}

I am unsure if the static class is redundant, but it will make things a lot easier when the dialog boxes start to mount up.

So instead of having to pass all of these individual style properties around, I was wondering if there is a cleaner way. I know there is no Form.Style property. I suppose I could create one. But I wanted to check first with the Gurus to see if I am missing anything.


问:
Background does not change onclick function
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }</code>```

  <button onclick="load()">Change background</button>

```

答:
Your issue is in this line:

```<code>document.getElementsByClassName("firstDiv")...
</code>```

getElementsByClassName returns an HTMLCollection like reported in the doc.

You need to change that line with:

```<code>document.getElementsByClassName("firstDiv")[0]
</code>```

The snippet:

function load() {
  document.getElementsByClassName('firstDiv')[0].style.backgroundImage
 = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.firstDiv, .secondDiv {
    width: 50%;
    height:100vh;
    float: left;
}

.firstDiv {
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}</code>```

    <button onclick="load()">Change background</button>

```

Body:
what's wrong with my code? For some reason my function load() does not change .firstDiv background?

I can't find any mistakes.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }

  <button onclick="load()">Change background</button>

Body:
Your issue is in this line:

document.getElementsByClassName("firstDiv")...

getElementsByClassName returns an HTMLCollection like reported in the doc.

You need to change that line with:

document.getElementsByClassName("firstDiv")[0]

The snippet:

function load() {
  document.getElementsByClassName('firstDiv')[0].style.backgroundImage
 = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}

.firstDiv, .secondDiv {
    width: 50%;
    height:100vh;
    float: left;
}

.firstDiv {
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}

<div class="firstDiv"></div>
<div class="firstDiv"></div>

<div class="secondDiv">
    <button onclick="load()">Change background</button>
</div>


问:
js setAttribute with Array
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

```<code>AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }
</code>```

答:
gradRoll is undefined because the variable name is gardRoll, a typo that you repeated in the first alert but not in the second one.

It seems like you only wish to edit the X value of the rotation so try this:

```<code>el.setAttribute("rotation", gardRoll + ' 0 ' + '0');
</code>```

Note that I used the variable with the typo in it.

It's a bit dirty I know but it worked for me when I had a similar issue with the position component.

Title: js setAttribute with Array

Body:
I have a problem with setAttribute. I set an Array as the value of rotation, but it doesn't work.  Alert of gradRoll is a number. But the type of gradRoll is undefined. Why? Can anybody help me? thanks in advance.

AFRAME.registerComponent('clockhand_roll',{
    schema:{
      type:'string', default: "secondClockhand"
    },

    init:function(){
      var data = this.data;
      var el=this.el;

      var oTime= new Date();
      var curTime;

      var clockhandPositonArray;

      if(data == "secondClockhand" ){
        curTime = oTime.getSeconds();
      }else if(data == "minuteClockhand"){
        curTime = oTime.getMinutes();
      }else if(data == "hourClockhand"){
        curTime = oTome.getHours;
      }else {
        alert("invalid input!");
      }

      //alert(curTime);
      //clockhandPositonArray=getClockhandPosition(curTime, data);
      //alert(el.getAttribute("rotation"));

      //el.setAttribute("rotation", 'clockhandPositonArray');

      setClockhandPosition(el, curTime, data);

    }
  });

  function setClockhandPosition(el, curTime, typeOfClockhand){
    var gradForOneUnit;
    var gradRoll;
    var rotationArray;

    if(typeOfClockhand == "secondClockhand" || typeOfClockhand == "minuteClockhand"){
      gradForOneUnit=360/60;
    }else if(typeOfClockhand == "hourClockhand"){
      gradForOneUnit=360/12;
    }

    gardRoll=curTime*gradForOneUnit;

    //alert(gardRoll); //number: 354!!!!!!!!!!!!!!!!!!!! why??????
    //alert(typeof(gradRoll)); //undefined!!!!!!!!!!!!!  why??????

    rotationArray=[curTime*gradForOneUnit, 0, 0];

    //alert(typeof(rotationArray));//object
    //alert(typeof(el.getAttribute("rotation"))); //object

    //alert(rotationArray); //number: 162 , 0, 0

    el.setAttribute("rotation", rotationArray); //dosn't work.
  }

Body:
gradRoll is undefined because the variable name is gardRoll, a typo that you repeated in the first alert but not in the second one.

It seems like you only wish to edit the X value of the rotation so try this:

el.setAttribute("rotation", gardRoll + ' 0 ' + '0');

Note that I used the variable with the typo in it.

It's a bit dirty I know but it worked for me when I had a similar issue with the position component.


问:
Can't use either View() or edit() functions, getting "Error in .External2(C_dataviewer, x, title) : invalid device" error message
I'm running R through the Terminal in a Mac OSX Snow Leopard system.

I get this error message when trying to use View():

Error in .External2(C_dataviewer, x, title) : invalid device In
  addition: Warning messages: 1: In View(a) :   locale not supported by
  Xlib: some X ops will operate in C locale 2: In View(a) : X cannot set
  locale modifiers 3: In View(a) :   unable to create fontset
  --fixed-medium-r----120------

And this error message when trying to use edit():

Error in .External2(C_dataentry, datalist, modes) : invalid device In
  addition: Warning messages: 1: In edit.data.frame(a) :   locale not
  supported by Xlib: some X ops will operate in C locale 2: In
  edit.data.frame(a) : X cannot set locale modifiers 3: In
  edit.data.frame(a) :   unable to create fontset
  --fixed-medium-r----120------

I can't find information about this particular problem. What can I do to fix this?

sessionInfo() returns:

```<code>R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
</code>```

答:
The cause for my problem: View(dataset) in the rchunk where we load up data.

I had it here because I loaded in data like data <-read_excel("name")
And had View there because I copied and pasted it from my console, but it's not needed.

Body:
I'm running R through the Terminal in a Mac OSX Snow Leopard system.

I get this error message when trying to use View():

Error in .External2(C_dataviewer, x, title) : invalid device In
  addition: Warning messages: 1: In View(a) :   locale not supported by
  Xlib: some X ops will operate in C locale 2: In View(a) : X cannot set
  locale modifiers 3: In View(a) :   unable to create fontset
  --fixed-medium-r----120------

And this error message when trying to use edit():

Error in .External2(C_dataentry, datalist, modes) : invalid device In
  addition: Warning messages: 1: In edit.data.frame(a) :   locale not
  supported by Xlib: some X ops will operate in C locale 2: In
  edit.data.frame(a) : X cannot set locale modifiers 3: In
  edit.data.frame(a) :   unable to create fontset
  --fixed-medium-r----120------

I can't find information about this particular problem. What can I do to fix this?

sessionInfo() returns:

R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base


问:
I'm utilizing an if/else statement to separate a data set into positive/negative values but have ran into an unused argument error
I'm trying to separate a set of data with an if statement based on if a value is positive. I had it working and it generated correct data but it stopped and generated the unused argument error when I generated new data.
Here is the code I used.

```<code>In:
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_grouped1
cd2 = data_grouped2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
ifelse(data_frame$dis >= 0, f = c(f,data_frame$dis),y = c(y,data_frame$dis))
</code>```

This generates the error:

```<code>Error in if (x > 0) { : missing value where TRUE/FALSE needed
</code>```

When I type this function seperate from the if statment it works so I am confused as to the issue.
I tried a workaround with:

```<code>for(x in c(dis[1:100])){if(x >= 0){f = c(f,x)}else{y=c(y,x)}}
</code>```

but got the error:

```<code>Error in if (x > 0) { : missing value where TRUE/FALSE needed
</code>```

Not sure how to fix this.

答:
So the problem is that the way you're introducing f and y in the ifelse function, is the way function arguments are introduced. You get the error, because the function is expecting a command for what to do when the statement is TRUE or FALSE, and instead you're giving it an argument that it's not expecting.

One way to work around that is to create a new variable in dis and take it from there. So it would look like:

```<code>data_frame$pos<- ifelse(data_frame$dis >= 0, 1, 0)
f<- data_frame$dis[which(data_frame$pos == 1)]
y<- data_frame$dis[which(data_frame$pos == 0)]
</code>```

Body:
I'm trying to separate a set of data with an if statement based on if a value is positive. I had it working and it generated correct data but it stopped and generated the unused argument error when I generated new data.
Here is the code I used.

In:
data_random1 = runif(100,1,100)
data_random2 = runif(100,1,100)
cd1 = data_grouped1
cd2 = data_grouped2
smth_ln = lowess(cd1,cd2)
dis = smth_ln$y - cd2
data_frame = data.frame(cd1,cd2,dis)
f = c()
y = c()
ifelse(data_frame$dis >= 0, f = c(f,data_frame$dis),y = c(y,data_frame$dis))

This generates the error:

Error in if (x > 0) { : missing value where TRUE/FALSE needed

When I type this function seperate from the if statment it works so I am confused as to the issue.
I tried a workaround with:

for(x in c(dis[1:100])){if(x >= 0){f = c(f,x)}else{y=c(y,x)}}

but got the error:

Error in if (x > 0) { : missing value where TRUE/FALSE needed

Not sure how to fix this.

Body:
So the problem is that the way you're introducing f and y in the ifelse function, is the way function arguments are introduced. You get the error, because the function is expecting a command for what to do when the statement is TRUE or FALSE, and instead you're giving it an argument that it's not expecting.

One way to work around that is to create a new variable in dis and take it from there. So it would look like:

data_frame$pos<- ifelse(data_frame$dis >= 0, 1, 0)
f<- data_frame$dis[which(data_frame$pos == 1)]
y<- data_frame$dis[which(data_frame$pos == 0)]


问:
Can Google Analytics track conversions inside a JS widget on a 3rd party site?
I'm working on a project that includes a javascript widget that can be wrapped around a video to enable subtitles. I'd like to track clicks when a person has the tool embedded on their site, in order to optimize UX.

Does anyone know if this is possible?

答:
Yes. You're most likely dealing with an implementation of custom variables in Google Analytics.

Here's an example of how Yottaa used custom variables to measure page load time, which is also a JavaScript-based event.


问:
Removing only a certain value in Spotfire
I am trying to graph data in a column titled "position".
This column contains the following data:  "Left", "Right", "Center", and, "--".   Unfortunately, the data I am pulling automatically enters "--" when none of the 3 apply.
I am able to remove the "--" when the column only has 1 value, but cannot figure out an expression to change the "--" to null while keeping the values of "Left", "Right", or "Center" unchanged.
Any help would be greatly appreciated!</p>

答:
Add calculated column and use Substitute(Arg1, Arg2, Arg3)

```<code>Substitute([Column],"--","")
</code>```

Spotfire Reference

```<code>Replaces all occurrences of Arg2 in Arg1 with Arg3.
The search is case sensitive.

Example:
Substitute("Test","t","ting")
Returns:
"Testing"
</code>```

Body:
Add calculated column and use Substitute(Arg1, Arg2, Arg3)

Substitute([Column],"--","")

Spotfire Reference

Replaces all occurrences of Arg2 in Arg1 with Arg3.
The search is case sensitive.

Example:
Substitute("Test","t","ting")
Returns:
"Testing"


问:
JSON response shows as true↵ with wrong length
I am new to AJAX and making a simple login system with AJAX and PHP. My JSON response shows as true↵ with length 6. Where is the problem, and how can I solve it?

AJAX

```<code>$('document').ready(function() {
  $("#login-form").on("submit", (function(e) {
    e.preventDefault();
    var data = $("#login-form").serialize();

    $.ajax({
      type: 'POST',
      url: 'login-response.php',
      data: data,

      success: function(response) {
        console.log(response.length);

        if (response == true) {
          $("#btn-login").html('<img src="btn-ajax-loader.gif" />   Signing In ...');
          setTimeout(' window.location.href = "demo.php"; ', 4000);
        } else {
          $("#error").fadeIn(1000, function() {
            $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>   ' + response + ' !</div>');
            $("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span>   Sign In');
          });
        }
      }
    });
  }));
});
</code>```

login-response.php

```<code>session_start();
$user_email = $_POST['user_email'];
$user_password = $_POST['password'];

if ($user_email == 'admin' && $user_password == '123') {
    $_SESSION['user_session'] = $user_email;
    echo json_encode(true);
}
else {
    echo "email or password does not exist."; // wrong details
}
</code>```

答:
As per my comment: json_encode(true) will not return a valid JSON. Instead, you will want to encode an array of sorts. There are many ways to do it, but one way is to simply encode an array that is ['success' => true], in other words:

```<code>session_start();
$user_email = $_POST['user_email'];
$user_password = $_POST['password'];

if ($user_email == 'admin' && $user_password == '123') {
    $_SESSION['user_session'] = $user_email;
    echo json_encode(array('success' => true));
}
else {
    echo json_encode(array('success' => false, 'message' => 'email or password does not exist.'));
}
</code>```

Note that you should also encode your failure message, because your jQuery expects to receive something in JSON.

Once you receive this response in your jQuery logic, you can simply check if the response has a success object with the value of true, i.e.:

```<code>$.ajax({
    type: 'POST',
    url: 'login-response.php',
    data: data,
    dataType: 'json'
})
.done(function(response) {
    if (response.success) {
        $("#btn-login").html('<img src="btn-ajax-loader.gif" />   Signing In ...');
        setTimeout(' window.location.href = "demo.php"; ', 4000);
    } else {
        $("#error").fadeIn(1000, function() {
            // Your error message is accessible via `response.message`
            $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>   ' + response.message + ' !</div>');
            $("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span>   Sign In');
        });
    }
});
</code>```

Some notes:

Request status is accessible via response.success. Of course, depending on personal preference, you may have alternatives in returning exit status, such as using an exit code (0 indicates ok, anything other than 0 means an error)

Your failure response message will be accessible via response.message

p/s: Remember that the jqXHR.success method is deprecated! Use jqXHR.done() instead ;)

Body:
I am new to AJAX and making a simple login system with AJAX and PHP. My JSON response shows as true↵ with length 6. Where is the problem, and how can I solve it?

AJAX

$('document').ready(function() {
  $("#login-form").on("submit", (function(e) {
    e.preventDefault();
    var data = $("#login-form").serialize();

    $.ajax({
      type: 'POST',
      url: 'login-response.php',
      data: data,

      success: function(response) {
        console.log(response.length);

        if (response == true) {
          $("#btn-login").html('   Signing In ...');
          setTimeout(' window.location.href = "demo.php"; ', 4000);
        } else {
          $("#error").fadeIn(1000, function() {
            $("#error").html('
    ' + response + ' !
');
            $("#btn-login").html('   Sign In');
          });
        }
      }
    });
  }));
});

login-response.php

session_start();
$user_email = $_POST['user_email'];
$user_password = $_POST['password'];

if ($user_email == 'admin' && $user_password == '123') {
    $_SESSION['user_session'] = $user_email;
    echo json_encode(true);
}
else {
    echo "email or password does not exist."; // wrong details
}

Body:
As per my comment: json_encode(true) will not return a valid JSON. Instead, you will want to encode an array of sorts. There are many ways to do it, but one way is to simply encode an array that is ['success' => true], in other words:

session_start();
$user_email = $_POST['user_email'];
$user_password = $_POST['password'];

if ($user_email == 'admin' && $user_password == '123') {
    $_SESSION['user_session'] = $user_email;
    echo json_encode(array('success' => true));
}
else {
    echo json_encode(array('success' => false, 'message' => 'email or password does not exist.'));
}

Note that you should also encode your failure message, because your jQuery expects to receive something in JSON.

Once you receive this response in your jQuery logic, you can simply check if the response has a success object with the value of true, i.e.:

$.ajax({
    type: 'POST',
    url: 'login-response.php',
    data: data,
    dataType: 'json'
})
.done(function(response) {
    if (response.success) {
        $("#btn-login").html('<img src="btn-ajax-loader.gif" /> &nbsp; Signing In ...');
        setTimeout(' window.location.href = "demo.php"; ', 4000);
    } else {
        $("#error").fadeIn(1000, function() {
            // Your error message is accessible via `response.message`
            $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; ' + response.message + ' !</div>');
            $("#btn-login").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign In');
        });
    }
});

Some notes:

Request status is accessible via response.success. Of course, depending on personal preference, you may have alternatives in returning exit status, such as using an exit code (0 indicates ok, anything other than 0 means an error)

Your failure response message will be accessible via response.message

p/s: Remember that the jqXHR.success method is deprecated! Use jqXHR.done() instead ;)


问:
Rails server not staring - There was an error while trying to load the gem 'omniauth-linkedin' in ruby on rails
I'm absolutely new to ruby on rails application. I'm stuck with an error while starting the rails server, it shows:

```<code>There was an error while trying to load the gem omniauth-linkedin. (Bundler::GemRequireError).
</code>```

Following are the version that I'm using:

ruby 2.1.8

Rails 4.0.13

omniauth-linkedin (0.2.0)

Any help would be appreciated.

答:
I think that gem is not working anymore, prolly you'll want to use:</p>

```<code>gem 'omniauth-linkedin-oauth2'
</code>```

Body:
I'm absolutely new to ruby on rails application. I'm stuck with an error while starting the rails server, it shows:

There was an error while trying to load the gem omniauth-linkedin. (Bundler::GemRequireError).

Following are the version that I'm using:

ruby 2.1.8

Rails 4.0.13

omniauth-linkedin (0.2.0)

Any help would be appreciated.

Body:
I think that gem is not working anymore, prolly you'll want to use:

gem 'omniauth-linkedin-oauth2'


问:
Spring Security Java Config same url allowed for anonymous user and for others authentication needed
In Spring Security Java Config

```<code>protected void configure(HttpSecurity http) throws Exception {

      http.antMatcher("/guest/**").authenticated;

}
</code>```

What if I want this same url to be allowed access to a particular principal or a User.

And others Authentication needed. Is it possible?

答:
If you want to completely bypass any security checks for certain URLs, you could do the following:

```<code>@Override
public void configure(WebSecurity web) throws Exception {
    // configuring here URLs for which security filters
    // will be disabled (this is equivalent to using
    // security="none")
    web
        .ignoring()
            .antMatchers(
                    "/guest/**"
            )
    ;
}
</code>```

This is equivalent to the following XML snippet:

```<code><sec:http security="none" pattern="/guest/**" />
</code>```

Body:
In Spring Security Java Config

protected void configure(HttpSecurity http) throws Exception {

      http.antMatcher("/guest/**").authenticated;

}

What if I want this same url to be allowed access to a particular principal or a User.

And others Authentication needed. Is it possible?

Body:
If you want to completely bypass any security checks for certain URLs, you could do the following:

@Override
public void configure(WebSecurity web) throws Exception {
    // configuring here URLs for which security filters
    // will be disabled (this is equivalent to using
    // security="none")
    web
        .ignoring()
            .antMatchers(
                    "/guest/**"
            )
    ;
}

This is equivalent to the following XML snippet:

<sec:http security="none" pattern="/guest/**" />


问:
Restrict Topic creation/alteration
I've a 3-node unsecured kafka(v0.10.2.1) cluster with topic auto creation and deletion disabled with the following in server.properties

```<code>auto.create.topics.enable=false
delete.topic.enable=true
</code>```

Topics are then created/altered on the cluster using bin/kafka-topics.sh. However, it looks like anyone can create topics on the cluster once they know the end points.

Is there a way to lock down topic creation/alteration to specific hosts to prevent abuses?

Edit 1:

Since ACL was suggested, I tried to restrict topic creation to select hosts using kafka-acls.sh.

I restarted the brokers after adding the following to server.properties, .

```<code>authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
allow.everyone.if.no.acl.found=true
</code>```

I tried the below to restrict topic creation on localhost.

```<code> bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:* --cluster --operation Create --allow-host 127.0.0.1
</code>```

However, I was still able to create topics from an other host using kafka-topics.sh with the right endpoints.  Is it the case that ACLs can't be used without authentication?

答:
You need to use access control lists (ACLs) to restrict such operations  and that implies knowing who the caller is, so you need kafka to be secured by an authentication mechanism in the first place.

ACLs: http://kafka.apache.org/documentation.html#security_authz

Authentication can be done using SSL or SASL or by plugging in a custom provider, see the preceding sections of the same document.

Disabling auto-creation is not an access control mechanism, it only means that trying to produce to or consume from a topic will not create it automatically.

Title: Restrict Topic creation/alteration

Body:
I've a 3-node unsecured kafka(v0.10.2.1) cluster with topic auto creation and deletion disabled with the following in server.properties

auto.create.topics.enable=false
delete.topic.enable=true

Topics are then created/altered on the cluster using bin/kafka-topics.sh. However, it looks like anyone can create topics on the cluster once they know the end points.

Is there a way to lock down topic creation/alteration to specific hosts to prevent abuses?

Edit 1:

Since ACL was suggested, I tried to restrict topic creation to select hosts using kafka-acls.sh.

I restarted the brokers after adding the following to server.properties, .

authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
allow.everyone.if.no.acl.found=true

I tried the below to restrict topic creation on localhost.

 bin/kafka-acls.sh --authorizer-properties zookeeper.connect=localhost:2181 --add --allow-principal User:* --cluster --operation Create --allow-host 127.0.0.1

However, I was still able to create topics from an other host using kafka-topics.sh with the right endpoints.  Is it the case that ACLs can't be used without authentication?


问:
Is it possible to use PostgreSQL with Google AppMaker?
The documentation mentions that MySQL can be used:

Your app can access tens of gigabytes of data stored in Google Cloud
  SQL, a MySQL relational database hosted on Google Cloud Platform.

However, it seems to be have been written before PostgreSQL was available on Google Cloud SQL.

答:
Support for PostgreSQL is not available. See https://developers.google.com/appmaker/models/cloudsql, it says:

Note: App Maker supports only MySQL databases. You can't use
  PostgreSQL.