问:
requireJS fails to load Handsontable
I've been struggling a while to get handsontable to work with requireJS.

On its own, handontable works fantastic.

I get the following error:

```<code>app.js:37 Uncaught TypeError: Handsontable is not a constructor
    at app.js:11
    at Object.execCb (require.js:1693)
    at Module.check (require.js:881)
    at Module.<anonymous> (require.js:1136)
    at require.js:134
    at require.js:1186
    at each (require.js:59)
    at Module.emit (require.js:1185)
    at Module.check (require.js:936)
    at Module.enable (require.js:1173)
</code>```

Here is a bare minimum example.
My html code:

```<code><html lang="en"><head>
  <script data-main="static/js/app" src="static/js/require.js">
</script>
  <link rel="stylesheet" media="screen" href="static/css/handsontable.css">
</head>
    <body>
        <div id="example"></div>
    </body>
</html>
</code>```

My app.js code (EDIT: As per Nhor's answer):

```<code>requirejs.config({
    baseUrl: 'static',
    waitSeconds: 10,
    paths: {
        // Handsontable full's requirements is in the plugin directory/
        // I shouldn't need them, but incase.
        'pikaday': 'plugins/pikaday/pikaday',
        'zeroclipboard': 'plugins/zeroclipboard/ZeroClipboard',
        'moment': 'plugins/moment.min',
        // Handsontable is directly in the static folder
        'handsontable': 'handsontable'
    }
});
requirejs([
    'handsontable'
], function(
    Handsontable
) {
    var data = [['', 'Kia', 'Nissan', 'Toyota', 'Honda'],
                ['2008', 10, 11, 12, 13],
                ['2009', 20, 11, 14, 13],
                ['2009', 30, 15, 12, 13]
              ];
    var hot = new Handsontable(document.getElementById('example'), {
      data: data,
      colHeaders: true,
      rowHeaders: true,
      minSpareRows: 1,
      minSpareCols: 1,
    });
});
</code>```

According to hansontable's documentation, handsontable has AMD support https://github.com/handsontable/handsontable. It seems to me there is something I do not understand about requireJS. I haven't had this issue with other modules I imported.

Any help will be greatly appreciated.

答: Which version are you using? Having had exactly the same problem today, reverting to version 0.31.2 fixed it. Using anything below 0.32.0 works fine. I know this might not the a perfect SO solution/response, but it works.</p>

Title: requireJS fails to load Handsontable

Body:
I've been struggling a while to get handsontable to work with requireJS.

On its own, handontable works fantastic.

I get the following error:

app.js:37 Uncaught TypeError: Handsontable is not a constructor
    at app.js:11
    at Object.execCb (require.js:1693)
    at Module.check (require.js:881)
    at Module.<anonymous> (require.js:1136)
    at require.js:134
    at require.js:1186
    at each (require.js:59)
    at Module.emit (require.js:1185)
    at Module.check (require.js:936)
    at Module.enable (require.js:1173)

Here is a bare minimum example.
My html code:

  <link rel="stylesheet" media="screen" href="static/css/handsontable.css">

My app.js code (EDIT: As per Nhor's answer):

requirejs.config({
    baseUrl: 'static',
    waitSeconds: 10,
    paths: {
        // Handsontable full's requirements is in the plugin directory/
        // I shouldn't need them, but incase.
        'pikaday': 'plugins/pikaday/pikaday',
        'zeroclipboard': 'plugins/zeroclipboard/ZeroClipboard',
        'moment': 'plugins/moment.min',
        // Handsontable is directly in the static folder
        'handsontable': 'handsontable'
    }
});
requirejs([
    'handsontable'
], function(
    Handsontable
) {
    var data = [['', 'Kia', 'Nissan', 'Toyota', 'Honda'],
                ['2008', 10, 11, 12, 13],
                ['2009', 20, 11, 14, 13],
                ['2009', 30, 15, 12, 13]
              ];
    var hot = new Handsontable(document.getElementById('example'), {
      data: data,
      colHeaders: true,
      rowHeaders: true,
      minSpareRows: 1,
      minSpareCols: 1,
    });
});

According to hansontable's documentation, handsontable has AMD support https://github.com/handsontable/handsontable. It seems to me there is something I do not understand about requireJS. I haven't had this issue with other modules I imported.

Any help will be greatly appreciated.


来源: stackexchange

问:
Control audio volume with scrolling
I'm  making a website for a school project but i have never worked with coding before - so I'm sorry if i have no clue how to phrase my question properly..

I would like to lower the volume of my audio clip when i scroll down on my website. I'm having a hard time understanding the logic of JavaScript... I kinda want to stick to HTML and CSS as much as possible, but i do have to use jQuery for this, right?

I'm hoping some of you might point me in the right direction.. Thanks in advance!

答:
Take a look at this example, hope may help you starting out (scroll on the video):

$(function() {

  var video = $('#myVideo');
  var videoEl = video[0];
  var delta = 0.1; //you can choose whatever delta ( + delta + volume change speed )
  video.on('wheel', function(event) {
    event.preventDefault(); //prevent default page scroll;
    //check for scroll down
    if (event.originalEvent.deltaY > 0 && videoEl.volume - delta >= 0) {
      videoEl.volume -= delta;
    //check for scroll up
    } else if(event.originalEvent.deltaY < 0 && videoEl.volume + delta <= 1) {
      videoEl.volume += delta;
    }
  });

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  padding: 20px 0;
  background-color: #efefef;
}

body {
  width: 400px;
  padding: 40px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
}

video {
  width: 400px;
  display: block;
}</code>```

<video id="myVideo" autobuffer controls autoplay>
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>```

ContentLicense: CC BY-SA 3.0

Title: Control audio volume with scrolling

Body:
Take a look at this example, hope may help you starting out (scroll on the video):

$(function() {

  var video = $('#myVideo');
  var videoEl = video[0];
  var delta = 0.1; //you can choose whatever delta ( + delta + volume change speed )
  video.on('wheel', function(event) {
    event.preventDefault(); //prevent default page scroll;
    //check for scroll down
    if (event.originalEvent.deltaY > 0 && videoEl.volume - delta >= 0) {
      videoEl.volume -= delta;
    //check for scroll up
    } else if(event.originalEvent.deltaY < 0 && videoEl.volume + delta <= 1) {
      videoEl.volume += delta;
    }
  });

})

html {
  padding: 20px 0;
  background-color: #efefef;
}

body {
  width: 400px;
  padding: 40px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
}

video {
  width: 400px;
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myVideo" autobuffer controls autoplay>
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>


问:
PHP json decode data using foreach
I have this following link and i want to print every item with id using foreach from json decoded string. Do you know how can i get these items using foreach?
sample JSON data</p>

答: Why wouldn't you use function json_decode dedicated for this, that creates object with data? You can then iterate over this object.</p>

Title: PHP json decode data using foreach


问:
searching a 2d array in python - best method + indentation error
I have created the following 2d array (list of lists) in Python:

```<code>#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case
</code>```

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")
</code>```

The output however, is erroneous:

```<code>>>What number are you looking for? 9
>>Found it!
>>not found
</code>```

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

```<code>number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")
</code>```

Erroneous output, still!

```<code>What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found
</code>```

答:
If all you are looking for is if the value exists in the matrix I would go a different route:</p>

```<code>import itertools

matrix=[
     [1,2,3,4,5,6,7],
     [8,9,10,11,12,13,14],
     [15,16,17,18,19,20,21],
       ]

unique_elements = set(itertools.chain(*matrix))
in_matrix = lambda a, set: a in set

print(in_matrix(3, unique_elements))   #True
</code>```

Body:
I have created the following 2d array (list of lists) in Python:

#creating a 2d array (3 rows by 7 columns) and populating it with numbers
matrix=[1,2,3,4,5,6,7],[8,9,10,11,12,13,14],[15,16,17,18,19,20,21]
rows=len(matrix) #finding the max number of rows in the matrix, in this case 3
columns=len(matrix[0]) #finding the max number of columns in each row, 7 in this case

I am trying to search for a specific element in the array (say the number 9), and then print "found", if found, and "not found", if not in the array, with the following code:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
else:
  print("not found")

The output however, is erroneous:

>>What number are you looking for? 9
>>Found it!
>>not found

I have two questions: 1. could someone please explain identatation clearly, with reference to this problem and why the second "not found" always is output.
2. Is there a better more efficient way to do this, without the use of numpy

*note, this is not a duplicate, as I have searched the other entries and they don't quite deal with what I am explicitly asking.

repl.it here:
https://repl.it/IcJ3/3

Someone just suggested an answer as below: (I had already tried this)

https://repl.it/IcJ3/5
Note, it doesn't work at all either:

number=int(input("What number are you looking for?"))
for i in range(rows):
      for j in range(columns):
        if matrix[i][j]==number:
          print("Found it!")
          break
        else:
          print("not found")

Erroneous output, still!

What number are you looking for? 9
not found
not found
not found
not found
not found
not found
not found
not found
Found it!
not found
not found
not found
not found
not found
not found
not found

Body:
If all you are looking for is if the value exists in the matrix I would go a different route:

import itertools

matrix=[
     [1,2,3,4,5,6,7],
     [8,9,10,11,12,13,14],
     [15,16,17,18,19,20,21],
       ]

unique_elements = set(itertools.chain(*matrix))
in_matrix = lambda a, set: a in set

print(in_matrix(3, unique_elements))   #True


问:
How to get single row CodeIgniter
How can I get single row when I call "conversationID",

Right now when I call "conversationID = 0" it show all "conversationID" by 0

message table,

```<code>|ID|conversationID|from|to|
|1|0|3|4
|2|0|4|3
|3|0|3|4
|4|1|2|4
|5|1|4|2
</code>```

Controller

```<code>public function index()
{
    $conversations_inbox = $this->conversation_model->get_conversation_inbox($this->user->info->ID);
    $this->template->loadContent("conversations/index.php", array("conversations_inbox" =>  $conversations_inbox,)
    );
}
</code>```

Model

```<code>public function get_conversation_inbox($userid) {
        $query = $this->db->where("conversations.from_user = ". $userid)->or_where("conversations.to_user = ". $userid)->select("*")->from("conversations")->join("conversation_message", "conversation_message.conversationID = conversations.conversationID")->order_by("conversation_message.date", "DESC")->get();
        return $query->row();
    }

<?php
foreach ($conversations_inbox as $c) { ?>
<li class="mail-starred">
    <div class="mail-from"><a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>"><img src="<?php echo base_url() . $c['store_picture'] ?>" style="width: 40px;height: 40px;margin-right: 10px;">
    <?php echo $c['store_name'] ?></a></div>
    <div class="mail-subject">
    <a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>">Test</a>
    </div>
</li>
<?php } ?>
</code>```

答:
You can get single row with array properties by:

```<code>$row = $query->row_array()
</code>```

Then you can get properties by your table example:

```<code>if ($row) {
    echo $row['ID'];
    echo $row['conversationID'];
    echo $row['from'];
    echo $row['to'];
}
</code>```

Title: How to get single row CodeIgniter

Body:
How can I get single row when I call "conversationID",

Right now when I call "conversationID = 0" it show all "conversationID" by 0

message table,

|ID|conversationID|from|to|
|1|0|3|4
|2|0|4|3
|3|0|3|4
|4|1|2|4
|5|1|4|2

Controller

public function index()
{
    $conversations_inbox = $this->conversation_model->get_conversation_inbox($this->user->info->ID);
    $this->template->loadContent("conversations/index.php", array("conversations_inbox" =>  $conversations_inbox,)
    );
}

Model

public function get_conversation_inbox($userid) {
        $query = $this->db->where("conversations.from_user = ". $userid)->or_where("conversations.to_user = ". $userid)->select("*")->from("conversations")->join("conversation_message", "conversation_message.conversationID = conversations.conversationID")->order_by("conversation_message.date", "DESC")->get();
        return $query->row();
    }

<?php
foreach ($conversations_inbox as $c) { ?>

<a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>"><img src="<?php echo base_url() . $c['store_picture'] ?>" style="width: 40px;height: 40px;margin-right: 10px;">
    <?php echo $c['store_name'] ?>

    <a href="<?php echo base_url("conversations/message/") . $c['conversationID'] ?>">Test

<?php } ?>

Body:
You can get single row with array properties by:

$row = $query->row_array()

Then you can get properties by your table example:

if ($row) {
    echo $row['ID'];
    echo $row['conversationID'];
    echo $row['from'];
    echo $row['to'];
}


问:
knitr executing R code chunks in HTML-style comments
Using Rstudio to edit an Rmarkdown file, I use HTML comments mark out large blocks that I don't want to have processed or in the output. This works just fine in Rstudio, which ignores everything in the comments. However, when I ask Rstudio to knit the document, knitr is executing the R code blocks in the comments.

Here's an MWE .Rmd file:

```<code># Important stuff I want to see
This is what I want to see:
```{r}
pi # I like pi
```
<!---
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r}
cake # I also like cake, but it's undefined
```
-->
</code>```

This causes knitr to fail with Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

Is there an easy way to comment out whole swathes of an Rmarkdown file which prevents knitr from executing the R code chunks in the comments?

I have looked at global comment option for R markdown in knitr and Comments in Markdown, as well as https://yihui.name/knitr/, but didn't find a solution.

答:
Select lines before and after the {r} code chunk and use Control/Shift-C (pc) to comment out.  You will get this kind of syntax; it won't knit, and won't give an error.

```<code><!-- **This section commented out, as not ready to be knit yet** -->
<!-- This is what I do not want to see: -->
<!-- ```{r} -->

```

Body:
Using Rstudio to edit an Rmarkdown file, I use HTML comments mark out large blocks that I don't want to have processed or in the output. This works just fine in Rstudio, which ignores everything in the comments. However, when I ask Rstudio to knit the document, knitr is executing the R code blocks in the comments.

Here's an MWE .Rmd file:

# Important stuff I want to see
This is what I want to see:
```{r}
pi # I like pi
```

This causes knitr to fail with Error in eval(expr, envir, enclos) : object 'cake' not found ... Execution halted

Is there an easy way to comment out whole swathes of an Rmarkdown file which prevents knitr from executing the R code chunks in the comments?

I have looked at global comment option for R markdown in knitr and Comments in Markdown, as well as https://yihui.name/knitr/, but didn't find a solution.

Body:
Select lines before and after the {r} code chunk and use Control/Shift-C (pc) to comment out.  You will get this kind of syntax; it won't knit, and won't give an error.

<!-- **This section commented out, as not ready to be knit yet** -->
<!-- This is what I do not want to see: -->
<!-- ```{r} -->
<!-- cake # I also like cake, but it's undefined -->
<!-- ``` -->


问:
Open WPF window on button click from a form window
Is it possible if I have a window form and upon a click event it opens a window in WPF using C# in Visual Studio?</p>

答:
Just add a wpf project, reference it, and open it in code like

```<code>  private void button1_Click(object sender, EventArgs e)
       {
            new WpfApplication1.MainWindow().Show();
        }
</code>```

Where MainWindow is your window in the WpfApplication1 project.
You need a reference to PresentationCore, Windowsbase and Presentationframework

Body:
Just add a wpf project, reference it, and open it in code like

  private void button1_Click(object sender, EventArgs e)
       {
            new WpfApplication1.MainWindow().Show();
        }

Where MainWindow is your window in the WpfApplication1 project.
You need a reference to PresentationCore, Windowsbase and Presentationframework


问:
Laravel + bootstrap (how to change pages)
i need some help with some changes on a web site for SEO .
i need to:

change some h1 tags to h2

set up a 404 page to a certain adress

set up 301 redirect instead of 302.
how can i archieve that ?

sorry for noobish questions, i've never worked with PHP

答:
Global find and replace regex <(/?)h1> to <$1h2> (NetBeans can do this)

If the route does not exist Laravel will return the 404 page by default. You can force a route to error by doing:

```<code>Route::get("/errorroute",function () {
    abort(404,"Found but not really");
});
</code>```

When you generate a redirect using redirect($url) you can pass a 2nd parameter e.g. redirect($url,301) or redirect(null,301)->back()

If you set up a redirect in your webserver you can specify the redirect code there as well (how depends on the webserver).

Body:
Global find and replace regex <(/?)h1> to <$1h2> (NetBeans can do this)

If the route does not exist Laravel will return the 404 page by default. You can force a route to error by doing:

Route::get("/errorroute",function () {
    abort(404,"Found but not really");
});

When you generate a redirect using redirect($url) you can pass a 2nd parameter e.g. redirect($url,301) or redirect(null,301)->back()

If you set up a redirect in your webserver you can specify the redirect code there as well (how depends on the webserver).


问:
Can sinch api be used with swift
Can we use sinch api to create an instant message app in swift? I tried to import sinch framework in a swift app but after importing I could not import the sinch class into my application. Help please.</p>

答:
Use CocoaPod to install your framework, might be easier.

how to install Pod

in your podfile

```<code>target 'YourApp' do
  pod 'SinchRTC ', '~> 3.1.0'
end
</code>```

open the YourApp.xcworkspace with xcode.
Now, In your file you will just have to import something like

import Sinch

and it might be good.

CocoaPod is really usefull for dependencies. it help you to install / uninstall framework very easily. it's also very nice when you work in team.

Note : change YourApp by your target name

Title: Can sinch api be used with swift

Body:
Use CocoaPod to install your framework, might be easier.

how to install Pod

in your podfile

target 'YourApp' do
  pod 'SinchRTC ', '~> 3.1.0'
end

open the YourApp.xcworkspace with xcode.
Now, In your file you will just have to import something like

import Sinch

and it might be good.

CocoaPod is really usefull for dependencies. it help you to install / uninstall framework very easily. it's also very nice when you work in team.

Note : change YourApp by your target name


问:
Pandas: Adding 0 to a long integer representing a date
I am trying to import a csv into panda. This csv contains a data column as follow (for instance):

20170607155749330: (Year/Month/Day/Hour/Minute/Second/decisecond/centisecond/millisecond). So there are 17 numbers representing the date.

Issue I have is that for this particular dataset is that some row have dates at a different precision, for instance:
2017060715581995 : here there are only 16 numbers since the millisecond is missing.

What I want to do is simple: converting every date for every row in a way that I would end up with 17 digit, by adding a 0 when one of them is missing.

Here is the function I wrote for this:

```<code>def convert_value(val):
   return ('{:0<17}'.format(val))
</code>```

So I try to apply it to every row by just creating a new column such as:

```<code>file_temp['Time_Transformed'] = file_temp.apply( lambda x: convert_value(x["TIME"]) , axis =1)
</code>```

And I am facing two issues:

Firstly, the newly created column is not of integer but of object type;

Secondly, it just does not work, 0 is not added to shorter date.

I tried various other approaches by converting the original data to string but they are not working either.

答:
I would use the ljust string method and convert to integer. Starting from a simple dataframe:

```<code>In [4]: df = pd.DataFrame([20170607155749330,20170607155749])

In [5]: df
Out[5]:
                   0
0  20170607155749330
1     20170607155749
</code>```

we can add a column with:

```<code>In [11]: df['T'] = df[0].apply(lambda x: int(str(x).ljust(17,'0')))

In [12]: df
Out[12]:
                   0                  T
0  20170607155749330  20170607155749330
1     20170607155749  20170607155749000
</code>```

basically we use the ljust(17,'0') which adds 0 to a fixed length of 17 at the end of your integer now as string, and convert back everything to integer.

Body:
I am trying to import a csv into panda. This csv contains a data column as follow (for instance):

20170607155749330: (Year/Month/Day/Hour/Minute/Second/decisecond/centisecond/millisecond). So there are 17 numbers representing the date.

Issue I have is that for this particular dataset is that some row have dates at a different precision, for instance:
2017060715581995 : here there are only 16 numbers since the millisecond is missing.

What I want to do is simple: converting every date for every row in a way that I would end up with 17 digit, by adding a 0 when one of them is missing.

Here is the function I wrote for this:

def convert_value(val):
   return ('{:0<17}'.format(val))

So I try to apply it to every row by just creating a new column such as:

file_temp['Time_Transformed'] = file_temp.apply( lambda x: convert_value(x["TIME"]) , axis =1)

And I am facing two issues:

Firstly, the newly created column is not of integer but of object type;

Secondly, it just does not work, 0 is not added to shorter date.

I tried various other approaches by converting the original data to string but they are not working either.

Body:
I would use the ljust string method and convert to integer. Starting from a simple dataframe:

In [4]: df = pd.DataFrame([20170607155749330,20170607155749])

In [5]: df
Out[5]:
                   0
0  20170607155749330
1     20170607155749

we can add a column with:

In [11]: df['T'] = df[0].apply(lambda x: int(str(x).ljust(17,'0')))

In [12]: df
Out[12]:
                   0                  T
0  20170607155749330  20170607155749330
1     20170607155749  20170607155749000

basically we use the ljust(17,'0') which adds 0 to a fixed length of 17 at the end of your integer now as string, and convert back everything to integer.


问:
How do I get the data to return with multiple elements?
How do I get the data to return in multiple title elements rather than one title element?

Returns this

```<code><title>
    Title 1
    Title 2
    Title 3
</title>
</code>```

Want to return this

```<code><title>Title 1</title>
<title>Title 2</title>
<title>Title 3</title>
</code>```

Code

```<code>(: This gets coordinates from $latLon :)
  let $result := for $coordinates in $latLon/location
                let $lat := $coordinates/lat/text()
                let $lon := $coordinates/lon/text()
(: This uses the coordinates to retrieve a title :)
                let $data := titleDoc:getTitle($lat, $lon)
                let $title := $data//div[@class="title"]/text()
                return
                  <title>{$title}</title>
</code>```

答:
Difficult to answer without seeing the contents of $data.
But something like this should work:</p>

```<code>for $title in $data//div[@class="title"]
return <title>{data($title)}</title>
</code>```

Body:
How do I get the data to return in multiple title elements rather than one title element?

Returns this

<title>
    Title 1
    Title 2
    Title 3
</title>

Want to return this

<title>Title 1</title>
<title>Title 2</title>
<title>Title 3</title>

Code

(: This gets coordinates from $latLon :)
  let $result := for $coordinates in $latLon/location
                let $lat := $coordinates/lat/text()
                let $lon := $coordinates/lon/text()
(: This uses the coordinates to retrieve a title :)
                let $data := titleDoc:getTitle($lat, $lon)
                let $title := $data//div[@class="title"]/text()
                return
                  <title>{$title}</title>

Body:
Difficult to answer without seeing the contents of $data.
But something like this should work:

for $title in $data//div[@class="title"]
return <title>{data($title)}</title>


问:
Keeping track of the page that the user entered through
I'm trying to figure out how keep track of the incoming page a visitor initially entered through and show that as a link throughout the site so that they can return to that initial page if they are navigating around the site.  Essentially the client's model is that they they're going to email links to a potential customer to a specific product page.  They didn't build a navigation on the site with all their products (bad idea I know).  But should the user leave that initial product page after entering through the email link and navigate to the contact page, homepage or wherever else, there's really no way unless they continually click back to find that initial product page they entered through.

So I'm using a PHP CMS (MODx specifically) and using Foxy Cart ecommerce.  As such, I've got jquery and JSON at my disposal to work with.  Unfortunately I have no idea where to start.

Here would be what I assume I need to do:

Have an empty div that's waiting in a sense to receive the incoming link.

Upon entering the product page, the jquery would "grab" the value in the h1 tag and grab the URL as well, store that info the empty div mentioned above.

Here's what I would envision it to be (please feel free to correct me if I'm wrong or if you have a better idea):

```<code><h1>Product Name Here</h1>
<div class="records_first_page_entry_name"><a href="[+first_page_URL+]">[+product_name_here+]</a></div>
</code>```

I would assume that these placeholders (namely [+first_page_URL+] and [+product_name_here+]) would be replaced by their respective values.  Then I would need this div's values to be carried throughout all the pages of my site.

I hope I'm explaining myself correctly.  Thanks!

答:
If you can only use javascript then use cookies

example: http://jsfiddle.net/kEpnW/ (first time it saves the data, second time it shows them so reload the page once)

Part to check if cookie exists (show info) or not (create cookie on first visit)

```<code>$(function(){
    var first_page_title = Cookies['first_page_title'];
    var first_page_url = Cookies['first_page_url'];
    if (first_page)
        {
            var ahref = $('<a>',{text: first_page_title, href: first_page_url});
            $('.records_first_page_entry_name').html( ahref );
        }
    else
        {
            Cookies.create('first_page_title', $('h1').text(), 0);
            Cookies.create('first_page_url', window.location.href, 0);
        }
});
</code>```

Cookie handling code

```<code>var Cookies = {
    init: function () {
        var allCookies = document.cookie.split('; ');
        for (var i=0;i<allCookies.length;i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },
    create: function (name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
        this[name] = value;
    },
    erase: function (name) {
        this.create(name,'',-1);
        this[name] = undefined;
    }
};
Cookies.init();
</code>```

You need to include these on all pages..

Alternatively, you can use PHP session variables to store the same info and display it in your pages.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to figure out how keep track of the incoming page a visitor initially entered through and show that as a link throughout the site so that they can return to that initial page if they are navigating around the site.  Essentially the client's model is that they they're going to email links to a potential customer to a specific product page.  They didn't build a navigation on the site with all their products (bad idea I know).  But should the user leave that initial product page after entering through the email link and navigate to the contact page, homepage or wherever else, there's really no way unless they continually click back to find that initial product page they entered through.

So I'm using a PHP CMS (MODx specifically) and using Foxy Cart ecommerce.  As such, I've got jquery and JSON at my disposal to work with.  Unfortunately I have no idea where to start.

Here would be what I assume I need to do:

Have an empty div that's waiting in a sense to receive the incoming link.

Upon entering the product page, the jquery would "grab" the value in the h1 tag and grab the URL as well, store that info the empty div mentioned above.

Here's what I would envision it to be (please feel free to correct me if I'm wrong or if you have a better idea):

Product Name Here

[+product_name_here+]

I would assume that these placeholders (namely [+first_page_URL+] and [+product_name_here+]) would be replaced by their respective values.  Then I would need this div's values to be carried throughout all the pages of my site.

I hope I'm explaining myself correctly.  Thanks!

Body:
If you can only use javascript then use cookies

example: http://jsfiddle.net/kEpnW/ (first time it saves the data, second time it shows them so reload the page once)

Part to check if cookie exists (show info) or not (create cookie on first visit)

$(function(){
    var first_page_title = Cookies['first_page_title'];
    var first_page_url = Cookies['first_page_url'];
    if (first_page)
        {
            var ahref = $('<a>',{text: first_page_title, href: first_page_url});
            $('.records_first_page_entry_name').html( ahref );
        }
    else
        {
            Cookies.create('first_page_title', $('h1').text(), 0);
            Cookies.create('first_page_url', window.location.href, 0);
        }
});

Cookie handling code

var Cookies = {
    init: function () {
        var allCookies = document.cookie.split('; ');
        for (var i=0;i<allCookies.length;i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },
    create: function (name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
        this[name] = value;
    },
    erase: function (name) {
        this.create(name,'',-1);
        this[name] = undefined;
    }
};
Cookies.init();

You need to include these on all pages..

Alternatively, you can use PHP session variables to store the same info and display it in your pages.


问:
NativeQuery Spring Data return object
I need to implement a query in Spring Data like this :-

```<code>Select User.name, sum(Activity.minutes)
From User, Activity, ActivityStatus
Where User.id = ActivityStatus.userId
And Activity.id = ActivityStatus.activityId
AND ActivityStatus = "COMPLETED"
GROUP BY user.name;
</code>```

So i need to join 3 tables, therefore I have to use @Query with nativeQuery = true ( correct me if I'm wrong here )

And so my Repository method looks like this :-

```<code>@Query(value = "Select User.name, sum(Activity.minutes) as total_minutes
    From User, Activity, ActivityStatus
    Where User.id = ActivityStatus.userId
    And Activity.id = ActivityStatus.activityId
    AND ActivityStatus = "COMPLETED"
    AND User.Type = ?1
    GROUP BY user.name;",
    nativeQuery = true
    )
List<MyObj> getTotalActivityMinutesByUserType(String userType);
</code>```

MyObj class looks like this :-

```<code>public class MyObj {
    String name;
    long total_minutes;

// getter and setter methods

    public MyObj(String name, long total_minutes) {
        this.name = name;
        this.total_minutes = total_minutes;
    }
}
</code>```

My Test Method :-

```<code>@Test
public void TotalActivityTest() throws Exception {
    List<MyObj> objA = myRepository.getTotalActivityMinutesByUser("TEST");

}
</code>```

and i get the following exception :-

org.springframework.core.convert.ConversionFailedException: Failed to
  convert from type [java.lang.Object[]] to type
  [com.mycomp.MyObj] for value '{TEST, 5.0}'; nested
  exception is
  org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type [java.lang.String] to
  type [com.mycomp.dto.MyObj]

I need a way to return the result as MyObj. ( Or at least a way to cast it to MyObj) Is this possible?

EDIT:

Building from @Cepr0's answer My Entity class looks like this :-

```<code>@Entity
public class ActivityStatus extends Base {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private Activity activity;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private User user;

}
</code>```

I am not sure how the JOIN query in JPQL should look like...

答:
Just use Projection and JPQL query:

```<code>public interface NameAndDuration {
    String getName();
    Long getDuaration();
}

@Query("select u.name as name, sum(a.minutes) as duration from User u join u.activityStatus st join st.activity a where st.status = "COMPLETED" and u.type = ?1 group by u.name")
List<NameAndDuration> getNameAndDurationByUserType(String userType);

List<NameAndDuration> list = getNameAndDurationByUserType("TEST");
String userName = list.get(0).getName();
</code>```

This query is probably not exact what you need because I don't know a structure of your entity classes. But if you show them I will correct the query...

Title: NativeQuery Spring Data return object

Body:
I need to implement a query in Spring Data like this :-

Select User.name, sum(Activity.minutes)
From User, Activity, ActivityStatus
Where User.id = ActivityStatus.userId
And Activity.id = ActivityStatus.activityId
AND ActivityStatus = "COMPLETED"
GROUP BY user.name;

So i need to join 3 tables, therefore I have to use @Query with nativeQuery = true ( correct me if I'm wrong here )

And so my Repository method looks like this :-

@Query(value = "Select User.name, sum(Activity.minutes) as total_minutes
    From User, Activity, ActivityStatus
    Where User.id = ActivityStatus.userId
    And Activity.id = ActivityStatus.activityId
    AND ActivityStatus = "COMPLETED"
    AND User.Type = ?1
    GROUP BY user.name;",
    nativeQuery = true
    )
List<MyObj> getTotalActivityMinutesByUserType(String userType);

MyObj class looks like this :-

public class MyObj {
    String name;
    long total_minutes;

// getter and setter methods

    public MyObj(String name, long total_minutes) {
        this.name = name;
        this.total_minutes = total_minutes;
    }
}

My Test Method :-

@Test
public void TotalActivityTest() throws Exception {
    List<MyObj> objA = myRepository.getTotalActivityMinutesByUser("TEST");

}

and i get the following exception :-

org.springframework.core.convert.ConversionFailedException: Failed to
  convert from type [java.lang.Object[]] to type
  [com.mycomp.MyObj] for value '{TEST, 5.0}'; nested
  exception is
  org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type [java.lang.String] to
  type [com.mycomp.dto.MyObj]

I need a way to return the result as MyObj. ( Or at least a way to cast it to MyObj) Is this possible?

EDIT:

Building from @Cepr0's answer My Entity class looks like this :-

@Entity
public class ActivityStatus extends Base {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private Activity activity;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private User user;

}

I am not sure how the JOIN query in JPQL should look like...

Body:
Just use Projection and JPQL query:

public interface NameAndDuration {
    String getName();
    Long getDuaration();
}

@Query("select u.name as name, sum(a.minutes) as duration from User u join u.activityStatus st join st.activity a where st.status = "COMPLETED" and u.type = ?1 group by u.name")
List<NameAndDuration> getNameAndDurationByUserType(String userType);

List<NameAndDuration> list = getNameAndDurationByUserType("TEST");
String userName = list.get(0).getName();

This query is probably not exact what you need because I don't know a structure of your entity classes. But if you show them I will correct the query...


问:
Parse SQL variables with session array in PHP
trying to parse multiple sql variables from one file to another using session arrays but i cant. Whats the part iam missing here?

Thanks in advance.

file1.php

```<code>session_start();
while($row=mysql_fetch_array($result,MYSQL_BOTH)) {
    echo "<tr>";
    $id=$row['id'];
    $array[] = $id;
}
$_SESSION['id'] = $array;
</code>```

file2.php

```<code>session_start();
foreach( $array as $id ) {
    echo $id;
}
</code>```

答:
In your code example you're not reading $array from $_SESSION.

Also keep in mind that $_SESSION stores everything as strings unless you implement your own session handler.

Body:
trying to parse multiple sql variables from one file to another using session arrays but i cant. Whats the part iam missing here?

Thanks in advance.

file1.php

session_start();
while($row=mysql_fetch_array($result,MYSQL_BOTH)) {
    echo "
";
    $id=$row['id'];
    $array[] = $id;
}
$_SESSION['id'] = $array;

file2.php

session_start();
foreach( $array as $id ) {
    echo $id;
}


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
simply wrap your form inside of a span like so:

```<code><div class="my-align">
  <span>
    <form>
      <input type="text">
    <form>
  </span>
</div>
</code>```

then in css

```<code>.my-align{text-align:right;}
.my-align form{text-align:left;}
</code>```

BTW this is only because you do not want to use float.

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
simply wrap your form inside of a span like so:

<div class="my-align">
  <span>
    <form>
      <input type="text">
    <form>
  </span>
</div>

then in css

.my-align{text-align:right;}
.my-align form{text-align:left;}

BTW this is only because you do not want to use float.


问:
Joomla 3.7.2 can't send any emails with contact forms
I'm at the end of my rope here and I'm here to get some help. I'm going to try and explain it as best as I can.

I have a website running on Joomla 3.7.2 which you can visit here: https://www.meteordesign.nl

For some reason my contact form does not work anymore. Whenever I click 'send' the page reloads but no confirmation or an email being sent.

I have tried the following:

Switched from PHP mail to SMTP and send a test mail (came in fine).

Used several other contact form modules and components and even an HTML one which you can find here https://bootstrapious.com/p/bootstrap-recaptcha

They all don't work. I have tried disabling my .htaccess file to see if that solved it but to no avail.

You can find the contact form here:
https://www.meteordesign.nl/contact

I don't know if this is important but recently my hosting provider switched to https. Could that be causing it?

I hope I explained it well. If not feel free to ask me more questions, I really need your help fixing this!

答:
So I finally figured it out...

The problem was the cache settings on Joomla at Global configuration > System > System Cache. I had it on Progressive and after setting it to Conservative my contact form worked again!


答:
In the second code junk you could set eval=F until you have finished this part of your code.

```<code><!--
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r eval=F}
cake # I also like cake, but it's undefined
```
-->
</code>```

Title: knitr executing R code chunks in HTML-style comments

Body:
In the second code junk you could set eval=F until you have finished this part of your code.

<!--
**This section commented out, as not ready to be knit yet**
This is what I do not want to see:
```{r eval=F}
cake # I also like cake, but it's undefined
```
-->


问:
Clear specific timeout
How can I clear this timeout:

```<code>var timeout = setTimeout(function() {
    window.setTimeout(arguments.callee, 1000);
}, 1000)
</code>```

clearTimeout(timeout) don't working..

答:
Store the timeout in a variable that is outside of the scope of the recursion. Also avoid using arguments.callee due to IE's limitations. You can check a working fiddle here.</p>

```<code>var timeout = null;

function updateTimeout() {
    timeout = setTimeout(updateTimeout, 1000)
    console.log('hoi')
}

// Start the timeout
updateTimeout();
</code>```

Title: Clear specific timeout

Body:
How can I clear this timeout:

var timeout = setTimeout(function() {
    window.setTimeout(arguments.callee, 1000);
}, 1000)

clearTimeout(timeout) don't working..

Body:
Store the timeout in a variable that is outside of the scope of the recursion. Also avoid using arguments.callee due to IE's limitations. You can check a working fiddle here.

var timeout = null;

function updateTimeout() {
    timeout = setTimeout(updateTimeout, 1000)
    console.log('hoi')
}

// Start the timeout
updateTimeout();


答:
Here is a code sample:</p>

```<code>$json_data = file_get_contents("http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/profileicon.json");

$data = json_decode($json_data, true);

$items = $data['data'];

foreach($items as $item){
    // Here you can get $item['id'] and $item['image'] and echo or do what you want with that data
}
</code>```

Title: PHP json decode data using foreach

Body:
I have this following link and i want to print every item with id using foreach from json decoded string. Do you know how can i get these items using foreach?
sample JSON data

Body:
Here is a code sample:

$json_data = file_get_contents("http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/profileicon.json");

$data = json_decode($json_data, true);

$items = $data['data'];

foreach($items as $item){
    // Here you can get $item['id'] and $item['image'] and echo or do what you want with that data
}


问:
Angular2: How to load data before rendering the component?
I am trying to load an event from my API before the component gets rendered. Currently I am using my API service which I call from the ngOnInit function of the component.

My EventRegister component:

```<code>import {Component, OnInit, ElementRef} from "angular2/core";
import {ApiService} from "../../services/api.service";
import {EventModel} from '../../models/EventModel';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams, RouterLink} from 'angular2/router';
import {FORM_PROVIDERS, FORM_DIRECTIVES, Control} from 'angular2/common';

@Component({
    selector: "register",
    templateUrl: "/events/register"
    // provider array is added in parent component
})

export class EventRegister implements OnInit {
    eventId: string;
    ev: EventModel;

    constructor(private _apiService: ApiService,
                        params: RouteParams) {
        this.eventId = params.get('id');
    }

    fetchEvent(): void {
        this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
    }

    ngOnInit() {
        this.fetchEvent();
        console.log(this.ev); // Has NO value
    }
}
</code>```

My EventRegister template

<register>
    Hi this sentence is always visible, even if `ev property` is not loaded yet

        I should be visible as soon the `ev property` is loaded. Currently I am never shown.
        {{event.id }}

</register>
```

<p>My API service</p>

```import "rxjs/Rx"
import {Http} from "angular2/http";
import {Injectable} from "angular2/core";
import {EventModel} from '../models/EventModel';

@Injectable()
export class ApiService {
    constructor(private http: Http) { }
    get = {
        event: (eventId: string): Promise<EventModel> => {
            return this.http.get("api/events/" + eventId).map(response => {
                return response.json(); // Has a value
            }).toPromise();
        }
    }
}
```

<p>The component gets rendered before the API call in the <code>ngOnInit</code> function is done fetching the data. So I never get to see the event id in my view template. So it looks like this is a ASYNC problem. I expected the binding of the <code>ev</code> (<code>EventRegister</code> component) to do some work after the <code>ev</code> property was set. Sadly it does not show the <code>div</code> marked with <code>*ngIf="ev"</code> when the property gets set.</p>

<p><strong>Question:</strong> Am I using a good approach? If not; What is the best way to load data before the component is starting to render?</p>

<p><strong>NOTE:</strong> The <code>ngOnInit</code> approach is used in this angular2 tutorial.</p>

<p>EDIT:</p>

<p>Two possible solutions. First was to ditch the <code>fetchEvent</code> and just use the API service in the <code>ngOnInit</code> function.</p>

```ngOnInit() {
    this._apiService.get.event(this.eventId).then(event => this.ev = event);
}
```

<p>Second solution. Like the answer given.</p>

```fetchEvent(): Promise<EventModel> {
    return this._apiService.get.event(this.eventId);
}

ngOnInit() {
    this.fetchEvent().then(event => this.ev = event);
}
```

答:
You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

```<code>import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}
</code>```

and in the module:

```<code>import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }
</code>```

and you can access it in your Component like this:

```<code>/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////
</code>```

And in the Route something like this (usually in the app.routing.ts file):

```<code>////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////
</code>```

Body:
I am trying to load an event from my API before the component gets rendered. Currently I am using my API service which I call from the ngOnInit function of the component.

My EventRegister component:

import {Component, OnInit, ElementRef} from "angular2/core";
import {ApiService} from "../../services/api.service";
import {EventModel} from '../../models/EventModel';
import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams, RouterLink} from 'angular2/router';
import {FORM_PROVIDERS, FORM_DIRECTIVES, Control} from 'angular2/common';

@Component({
    selector: "register",
    templateUrl: "/events/register"
    // provider array is added in parent component
})

export class EventRegister implements OnInit {
    eventId: string;
    ev: EventModel;

    constructor(private _apiService: ApiService,
                        params: RouteParams) {
        this.eventId = params.get('id');
    }

    fetchEvent(): void {
        this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
    }

    ngOnInit() {
        this.fetchEvent();
        console.log(this.ev); // Has NO value
    }
}

My EventRegister template

<register>
    Hi this sentence is always visible, even if `ev property` is not loaded yet

        I should be visible as soon the `ev property` is loaded. Currently I am never shown.
        {{event.id }}

</register>

My API service

import "rxjs/Rx"
import {Http} from "angular2/http";
import {Injectable} from "angular2/core";
import {EventModel} from '../models/EventModel';

@Injectable()
export class ApiService {
    constructor(private http: Http) { }
    get = {
        event: (eventId: string): Promise<EventModel> => {
            return this.http.get("api/events/" + eventId).map(response => {
                return response.json(); // Has a value
            }).toPromise();
        }
    }
}

The component gets rendered before the API call in the ngOnInit function is done fetching the data. So I never get to see the event id in my view template. So it looks like this is a ASYNC problem. I expected the binding of the ev (EventRegister component) to do some work after the ev property was set. Sadly it does not show the div marked with *ngIf="ev" when the property gets set.

Question: Am I using a good approach? If not; What is the best way to load data before the component is starting to render?

NOTE: The ngOnInit approach is used in this angular2 tutorial.

EDIT:

Two possible solutions. First was to ditch the fetchEvent and just use the API service in the ngOnInit function.

ngOnInit() {
    this._apiService.get.event(this.eventId).then(event => this.ev = event);
}

Second solution. Like the answer given.

fetchEvent(): Promise<EventModel> {
    return this._apiService.get.event(this.eventId);
}

ngOnInit() {
    this.fetchEvent().then(event => this.ev = event);
}

Body:
You can pre-fetch your data by using Resolvers in Angular2+, Resolvers process your data before your Component fully be loaded.

There are many cases that you want to load your component only if there is certain thing happening, for example navigate to Dashboard only if the person already logged in, in this case Resolvers are so handy.

Look at the simple diagram I created for you for one of the way you can use the resolver to send the data to your component.

Applying Resolver to your code is pretty simple, I created the snippets for you to see how the Resolver can be created:

import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { MyData, MyService } from './my.service';

@Injectable()
export class MyResolver implements Resolve<MyData> {
  constructor(private ms: MyService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<MyData> {
    let id = route.params['id'];

    return this.ms.getId(id).then(data => {
      if (data) {
        return data;
      } else {
        this.router.navigate(['/login']);
        return;
      }
    });
  }
}

and in the module:

import { MyResolver } from './my-resolver.service';

@NgModule({
  imports: [
    RouterModule.forChild(myRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    MyResolver
  ]
})
export class MyModule { }

and you can access it in your Component like this:

/////
 ngOnInit() {
    this.route.data
      .subscribe((data: { mydata: myData }) => {
        this.id = data.mydata.id;
      });
  }
/////

And in the Route something like this (usually in the app.routing.ts file):

////
{path: 'yourpath/:id', component: YourComponent, resolve: { myData: MyResolver}}
////

ContentLicense: CC BY-SA 4.0


问:
MySQL select 3 rows with the same value
In my "odds" table I have multiple rows with the same "match_id"
I would like to choose only 3 rows per match and then move for another match and again choose 3 rows for that and so on.

Imagine it like distinct but with 3 rows, not only 1.

Is there any way to do it without a loop in laravel 5?

Here is my query which takes multiple (more than 3) rows with the same match_id.

```<code>    \DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->get();
</code>```

Thanks.

答:
I think using the 'take(n)' constraint would work:</p>

```<code>\DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->take(3)
  ->get();
</code>```

Title: MySQL select 3 rows with the same value

Body:
In my "odds" table I have multiple rows with the same "match_id"
I would like to choose only 3 rows per match and then move for another match and again choose 3 rows for that and so on.

Imagine it like distinct but with 3 rows, not only 1.

Is there any way to do it without a loop in laravel 5?

Here is my query which takes multiple (more than 3) rows with the same match_id.

    \DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->get();

Thanks.

Body:
I think using the 'take(n)' constraint would work:

\DB::table('matches as m')
  ->select([    'o.id as odd_id',
                'o.match_id as match_id',
                'o.type_id as type_id',
                'o.outcome as outcome',
                'o.odd as odd',
                'm.date_hour as match_date'
            ])
  ->where('m.created_at','>=',\DB::raw('DATE_SUB(NOW(), INTERVAL 24 HOUR)'))
  ->where('m.status_desc_id','=','1')
  ->join('odds as o', function ($join) {
            $join->on('m.id', '=', 'o.match_id')
                 ->where('o.type_id', '=', 43);

        })
  ->groupBy('o.id')
  ->take(3)
  ->get();


问:
TYPO3 set fe_user group
I have TYPO3 version 7.6.18. I trying create user by code. How to add user group? I see it need create user group object.

```<code>$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager>get('Fhk\\Feusersplus\\Domain\\Model\\User');

$userGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);

$userModel->setUsergroup($userGroup);
$newUser->add($userModel);
</code>```

I think the user did't add to database because I did't set user group. Help me please)

I have corrected my code but it does't add user to database:

```<code> $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

                $userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
                $userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

                $userGroup = $userGroup->findByUid(1);
                $newUserGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
                $newUserGroup->attach($userGroup);

            $userModel->setUsername("sdfdsfdsfs");
                $userModel->setEmail($user_data['email']);
                $gender = 0;
                $password = rand(99999999,9999999999999);
                $userModel->setPassword($password);
                $userModel->setPid(3);
                $userModel->setUsergroup($newUserGroup);

                $newUser->add($userModel);
</code>```

答: You are almost done. You need a UserGroupRepository to retrieve the user group you need and do $userGroup->attach($yourUserGroup).

Title: TYPO3 set fe_user group

Body:
I have TYPO3 version 7.6.18. I trying create user by code. How to add user group? I see it need create user group object.

$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

$userModel = $this->objectManager>get('Fhk\\Feusersplus\\Domain\\Model\\User');

$userGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();

$userModel->setUsername("sdfdsfdsfs");
$userModel->setEmail($user_data['email']);
$gender = 0;
$password = rand(99999999,9999999999999);
$userModel->setPassword($password);

$userModel->setUsergroup($userGroup);
$newUser->add($userModel);

I think the user did't add to database because I did't set user group. Help me please)

I have corrected my code but it does't add user to database:

 $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
            $newUser = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Repository\\UserRepository');

                $userModel = $this->objectManager->get('Fhk\\Feusersplus\\Domain\\Model\\User');
                $userGroup = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Repository\\FrontendUserGroupRepository');

                $userGroup = $userGroup->findByUid(1);
                $newUserGroup = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
                $newUserGroup->attach($userGroup);

            $userModel->setUsername("sdfdsfdsfs");
                $userModel->setEmail($user_data['email']);
                $gender = 0;
                $password = rand(99999999,9999999999999);
                $userModel->setPassword($password);
                $userModel->setPid(3);
                $userModel->setUsergroup($newUserGroup);

                $newUser->add($userModel);


问:
Collapse columns into a new variable
I have a data frame that looks like this.

```<code>name = c("p1","p2","p3","p4")
place = c("f","g","h","i")
v1 = c("x", "NA", "NA", "NA")
v2 = c("NA", "y", "y", "NA")
v3 = c("NA", "NA", "z", "NA")
region = c("n","w","s","e")
grade = c("f1","f2","f3","f4")
df = data.frame(name, place, v1, v2, v3, region, grade)

  name place v1 v2 v3 region grade
1   p1     f  x NA NA      n    f1
2   p2     g NA  y NA      w    f2
3   p3     h NA  y  z      s    f3
4   p4     i NA NA NA      e    f4
</code>```

I would like to add a new character vector v4 that contains the character from any of columns v1 v2 v3.

```<code>  name place v1 v2 v3 v4 region grade
1   p1     f  x NA NA  x      n    f1
2   p2     g NA  y NA  y      w    f2
3   p3     h NA  y  z yz      s    f3
4   p4     i NA NA NA NA      e    f4
</code>```

many thanks

答:
We can use paste after converting the columns to character

```<code>df$V4 <-  gsub("NA", "", do.call(paste, c(df[3:5], sep="")))
df$V4[df$V4==""] <- NA
df$V4
#[1] "x"  "y"  "yz"  NA
</code>```

data

```<code>df <- structure(list(name = c("p1", "p2", "p3", "p4"), place = c("f",
"g", "h", "i"), v1 = c("x", NA, NA, NA), v2 = c(NA, "y", "y",
NA), v3 = c(NA, NA, "z", NA), region = c("n", "w", "s", "e"),
grade = c("f1", "f2", "f3", "f4")), .Names = c("name", "place",
"v1", "v2", "v3", "region", "grade"), class = "data.frame",
 row.names = c("1", "2", "3", "4"))
</code>```

Title: Collapse columns into a new variable

Body:
I have a data frame that looks like this.

name = c("p1","p2","p3","p4")
place = c("f","g","h","i")
v1 = c("x", "NA", "NA", "NA")
v2 = c("NA", "y", "y", "NA")
v3 = c("NA", "NA", "z", "NA")
region = c("n","w","s","e")
grade = c("f1","f2","f3","f4")
df = data.frame(name, place, v1, v2, v3, region, grade)

  name place v1 v2 v3 region grade
1   p1     f  x NA NA      n    f1
2   p2     g NA  y NA      w    f2
3   p3     h NA  y  z      s    f3
4   p4     i NA NA NA      e    f4

I would like to add a new character vector v4 that contains the character from any of columns v1 v2 v3.

  name place v1 v2 v3 v4 region grade
1   p1     f  x NA NA  x      n    f1
2   p2     g NA  y NA  y      w    f2
3   p3     h NA  y  z yz      s    f3
4   p4     i NA NA NA NA      e    f4

many thanks

Body:
We can use paste after converting the columns to character

df$V4 <-  gsub("NA", "", do.call(paste, c(df[3:5], sep="")))
df$V4[df$V4==""] <- NA
df$V4
#[1] "x"  "y"  "yz"  NA

data

df <- structure(list(name = c("p1", "p2", "p3", "p4"), place = c("f",
"g", "h", "i"), v1 = c("x", NA, NA, NA), v2 = c(NA, "y", "y",
NA), v3 = c(NA, NA, "z", NA), region = c("n", "w", "s", "e"),
grade = c("f1", "f2", "f3", "f4")), .Names = c("name", "place",
"v1", "v2", "v3", "region", "grade"), class = "data.frame",
 row.names = c("1", "2", "3", "4"))


问:
How to make scrollable tab in Android?
I have 9 tab but in fill mode. I want to make these thabs scrollable. But i dont know the trick. I tried many methods but still nothing.

My Activity :

```<code>    package com.bani.fragment2;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Fragment 1");
    setSupportActionBar(toolbar);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 4"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 5"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 6"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 7"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 8"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 9"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()     {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch(tab.getPosition()) {
                case 0:
                    viewPager.setCurrentItem(0);
                    toolbar.setTitle("Fragment 1");
                    break;
                case 1:
                    viewPager.setCurrentItem(1);
                    toolbar.setTitle("Fragment 2");
                    break;
                case 2:
                    viewPager.setCurrentItem(2);
                    toolbar.setTitle("Fragment 3");
                    break;
                case 3:
                    viewPager.setCurrentItem(3);
                    toolbar.setTitle("Fragment 4");
                    break;
                case 4:
                    viewPager.setCurrentItem(4);
                    toolbar.setTitle("Fragment 5");
                    break;
                case 5:
                    viewPager.setCurrentItem(5);
                    toolbar.setTitle("Fragment 6");
                    break;
                case 6:
                    viewPager.setCurrentItem(6);
                    toolbar.setTitle("Fragment 7");
                    break;
                case 7:
                    viewPager.setCurrentItem(7);
                    toolbar.setTitle("Fragment 8");
                    break;
                case 8:
                    viewPager.setCurrentItem(8);
                    toolbar.setTitle("Fragment 9");
                    break;
                default:

                    viewPager.setCurrentItem(tab.getPosition());
                    toolbar.setTitle("Fragment 1");
                    break;
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}
</code>```

And this is my layout with Tab:

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toolbar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

</RelativeLayout>
</code>```

Please help me to solve my problem, I tried to set tab gravity to MODE_SCROLLABLE and other way but still not working for me.

答:
Set the Value of setTabMode to TabLayout.MODE_SCROLLABLE

```<code>tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
</code>```

And, you will be able to scroll tabs horizontally.

Title: How to make scrollable tab in Android?

Body:
I have 9 tab but in fill mode. I want to make these thabs scrollable. But i dont know the trick. I tried many methods but still nothing.

My Activity :

    package com.bani.fragment2;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Fragment 1");
    setSupportActionBar(toolbar);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 4"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 5"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 6"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 7"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 8"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 9"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()     {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switch(tab.getPosition()) {
                case 0:
                    viewPager.setCurrentItem(0);
                    toolbar.setTitle("Fragment 1");
                    break;
                case 1:
                    viewPager.setCurrentItem(1);
                    toolbar.setTitle("Fragment 2");
                    break;
                case 2:
                    viewPager.setCurrentItem(2);
                    toolbar.setTitle("Fragment 3");
                    break;
                case 3:
                    viewPager.setCurrentItem(3);
                    toolbar.setTitle("Fragment 4");
                    break;
                case 4:
                    viewPager.setCurrentItem(4);
                    toolbar.setTitle("Fragment 5");
                    break;
                case 5:
                    viewPager.setCurrentItem(5);
                    toolbar.setTitle("Fragment 6");
                    break;
                case 6:
                    viewPager.setCurrentItem(6);
                    toolbar.setTitle("Fragment 7");
                    break;
                case 7:
                    viewPager.setCurrentItem(7);
                    toolbar.setTitle("Fragment 8");
                    break;
                case 8:
                    viewPager.setCurrentItem(8);
                    toolbar.setTitle("Fragment 9");
                    break;
                default:

                    viewPager.setCurrentItem(tab.getPosition());
                    toolbar.setTitle("Fragment 1");
                    break;
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

And this is my layout with Tab:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toolbar"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout"/>

</RelativeLayout>

Please help me to solve my problem, I tried to set tab gravity to MODE_SCROLLABLE and other way but still not working for me.

Body:
Set the Value of setTabMode to TabLayout.MODE_SCROLLABLE

tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

And, you will be able to scroll tabs horizontally.


问:
how to use the wordpress site url and concatination for link href
I work on a wordpress site and i have some trouble to generate the correct href link dynamically to link to different sites. My goal is to link to an id for a site section to scroll to, if you click a specific button/box. The box is wrapped inside an a tag and should get a dynamic link in the href to go to the specified section. The dynamic link should consist of the site url and the site/#id for the section to go to

here is what i have done so far!

My blade file looks like this:

```<code><?php
    $techboxes = $block->getBox();
    $mh_group = "technology-boxes-" . rand();
    global $wp;
    $site_url = home_url(add_query_arg(array(),$wp->request));
?>
<div class="section section--margin-md">
    <div class="section__content">
        <div class="technology-teaser">
            <?php
            $title = $block->getTitle();
            $subtitle = $block->getSubtitle();
            $description = $block->getDescription();
            ?>
            <h2 class="technology-teaser__inner__title">{{$title}}</h2>
            <h3 class="technology-teaser__inner__subtitle">{{$subtitle}}</h3>
            <div class="technology-teaser__inner__description">{{$description}}</div>
        </div>

        <div class="technology-teaser__boxes">
            @foreach ($techboxes as $techbox)
            <?php
            $title = $techbox['title'];
            $description = $techbox['description'];
            $link = $techbox['link'];
            $current_url = $site_url . "/technolgie";
            ?>
            <a href="{{$site_url}}" class="technology-teaser__boxes__box">
                <div class="technology-teaser__boxes__box__image bg-image" style="background-image: url({{$techbox['background']}})">
                </div>
                <div class="technology-teaser__boxes__box__text">
                    <div class="js-matchheight" data-mh="{{ $mh_group }}">
                        <h2 class="technology-teaser__boxes__box__text__title">{{$title}}</h2>

                        <div class="technology-teaser__boxes__box__text__description">
                            {{$description}}
                        </div>
                    </div>
                </div>
                <div class="technology-teaser__boxes__box__text__link btn btn--yellow">
                    <i class="btn__icon white-icon"></i>
                    <span class="btn__text">mehr erfahren</span>
                </div>
            </a>
            @endforeach
        </div>
    </div>
</div>
</code>```

I found

```<code>global $wp;
$site_url = home_url(add_query_arg(array(),$wp->request));
</code>```

which returns the right site url (i checked with var_dump).
Now i would like to add a specific site to the $site_url. I do this with:

```<code>$current_url = $site_url . "/technolgie";
</code>```

here /technolgie is the site the where the link should go to and i will later ad another variable which holds the id of the section on the technolgie site.

If i var_dump $current_url it gives back a string with the right address. However it links not to the right page, it just reloads and do nothing. If i typ in the adress in my browser, it works fine. So im obviously missing something important here and someone of you is having a hint for me about this.

regards daniel.

答:
I got it and the answer is quite easy. Instead of using the sitename you would like to link to you need to concatinate the page id, like so:

```<code>$site_url = home_url(add_query_arg(array(),$wp->request)) . '/' . '?p=44';
</code>```

With this you can use $site_url inside your href and can link to the site.

Body:
I work on a wordpress site and i have some trouble to generate the correct href link dynamically to link to different sites. My goal is to link to an id for a site section to scroll to, if you click a specific button/box. The box is wrapped inside an a tag and should get a dynamic link in the href to go to the specified section. The dynamic link should consist of the site url and the site/#id for the section to go to

here is what i have done so far!

My blade file looks like this:

<?php
    $techboxes = $block->getBox();
    $mh_group = "technology-boxes-" . rand();
    global $wp;
    $site_url = home_url(add_query_arg(array(),$wp->request));
?>

            <?php
            $title = $block->getTitle();
            $subtitle = $block->getSubtitle();
            $description = $block->getDescription();
            ?>

{{$title}}

{{$subtitle}}

{{$description}}

            @foreach ($techboxes as $techbox)
            <?php
            $title = $techbox['title'];
            $description = $techbox['description'];
            $link = $techbox['link'];
            $current_url = $site_url . "/technolgie";
            ?>

{{$title}}

                            {{$description}}

                    mehr erfahren

            @endforeach

I found

global $wp;
$site_url = home_url(add_query_arg(array(),$wp->request));

which returns the right site url (i checked with var_dump).
Now i would like to add a specific site to the $site_url. I do this with:

$current_url = $site_url . "/technolgie";

here /technolgie is the site the where the link should go to and i will later ad another variable which holds the id of the section on the technolgie site.

If i var_dump $current_url it gives back a string with the right address. However it links not to the right page, it just reloads and do nothing. If i typ in the adress in my browser, it works fine. So im obviously missing something important here and someone of you is having a hint for me about this.

regards daniel.

Body:
I got it and the answer is quite easy. Instead of using the sitename you would like to link to you need to concatinate the page id, like so:

$site_url = home_url(add_query_arg(array(),$wp->request)) . '/' . '?p=44';

With this you can use $site_url inside your href and can link to the site.


问:
Ext.Ajax.request sending OPTIONS request cross-domain when jQuery.ajax sends GET
I have a Sencha Touch application calling my web service cross-domain using Ext.Ajax.request. As I have built the web service I've enabled it to access cross-domain requests. However Ext sends an OPTIONS request first as a handshake then a GET request whereas jQuery.ajax just sends a GET request. Due to circumstances outside my control the hosting provider doesn't support OPTIONS requests. At the moment I have resorted to using jQuery for ajax requests and Sencha Touch for the rest of the application. I don't really want to have to load the jQuery library just for this.

Can anyone shed some light on why Ext.Ajax sends an OPTIONS request and is there a way to make it just send a GET?

Thanks

答:
Or you can set with method like this :</p>

```<code>Ext.Ajax.setUseDefaultXhrHeader(false);
Ext.Ajax.request({
                    url: "http://yoururl.domain",
                    success: function(response, eOpt) {
                        console.log('success');
                    },
                    failure: function(response, eOpt) {
                        console.log('error');
                    }
                });
</code>```

Body:
Or you can set with method like this :

Ext.Ajax.setUseDefaultXhrHeader(false);
Ext.Ajax.request({
                    url: "http://yoururl.domain",
                    success: function(response, eOpt) {
                        console.log('success');
                    },
                    failure: function(response, eOpt) {
                        console.log('error');
                    }
                });


问:
WordPress HTML code, help to find
Creating web-site on WordPress, and got problem with finding HTML code of current part.

Web site here

Need to change Services titles and descriptions, but can find this part of code on FTP server. Is it possible to find it? Here the structure of ftp

i supose it must be in index.php, or index-servise.php, i was cheking this files(and all other) there is only functional part of this blocks. Can anybody help me to find this HTML code?

答:
The  tag of your page is located in the header.php file of the current theme you are using. Your theme files are located inside the /wp-content/themes/. You can edit there. To see which theme you are using, access your WP-ADMIN and navigate to Appearence > Themes.

The Services seem to be generated as Widgets, so you should find them in Appearence > Widgets. These are stored in the MySQL database and are not hardcoded in HTML.

Title: WordPress HTML code, help to find

Body:
The <head> tag of your page is located in the header.php file of the current theme you are using. Your theme files are located inside the /wp-content/themes/. You can edit there. To see which theme you are using, access your WP-ADMIN and navigate to Appearence > Themes.

The Services seem to be generated as Widgets, so you should find them in Appearence > Widgets. These are stored in the MySQL database and are not hardcoded in HTML.


问:
enable NSButton if NSTextfield is not empty
I am creating a OSX app and would like to enable a button when all textfield are filled. But do not have  much experience with osx app as there seem to be some difference from ios.

This is what I have tried.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    btnCalculate.enabled = false

}

override func controlTextDidChange(obj: NSNotification) {

    if panelsWideTextField.stringValue.isEmpty {
        btnCalculate.enabled = false
    } else {
        btnCalculate.enabled = true
    }
}
</code>```

Hope someone has a good tip for me :-)

EDIT:

Complete code.

```<code>import Cocoa
//import AppKit

class ViewController: NSViewController, NSTextFieldDelegate {

@IBOutlet weak var panelHightTextField: NSTextField!
@IBOutlet weak var panelWidthTextField: NSTextField!
@IBOutlet weak var panelPitchTextField: NSTextField!
@IBOutlet weak var panelsHighTextField: NSTextField!
@IBOutlet weak var panelsWideTextField: NSTextField!
@IBOutlet weak var resWidthLabel: NSTextField!
@IBOutlet weak var resHightLabel: NSTextField!
@IBOutlet weak var lblScreenWidth: NSTextField!
@IBOutlet weak var lblScreenHight: NSTextField!
@IBOutlet weak var lblScreenArea: NSTextField!
@IBOutlet weak var btnCalculate: NSButton!
@IBOutlet weak var lblAmountPanels: NSTextField!

var panelHight = ""
var panelWidth = ""
var panelPitch = ""
var panelsHigh = ""
var panelsWidth = ""

var resWidth : Float = 0
var resHigh : Float = 0
var screenHight : Float = 0
var screenWidth : Float = 0
var screenArea : Float = 0
var ammountPanels : Float = 0

override func viewDidLoad() {
    super.viewDidLoad()

    btnCalculate.enabled = false

}

override func controlTextDidChange(obj: NSNotification) {
    if panelsWideTextField.stringValue.isEmpty {
        btnCalculate.enabled = true
    } else {
        btnCalculate.enabled = false
    }
}

override var representedObject: AnyObject? {
    didSet {
        // Update the view, if already loaded.
    }
}

@IBAction func calculateResButton(sender: AnyObject) {
    takeUserData()
    calculatehight()
    calculatewidth()
    calculateArea()
    calculateAmountPanels()
}

func takeUserData(){
    panelHight = panelHightTextField.stringValue
    panelWidth = panelWidthTextField.stringValue
    panelPitch = panelPitchTextField.stringValue
    panelsHigh = panelsHighTextField.stringValue
    panelsWidth = panelsWideTextField.stringValue
}

// Calculating resolution and physical hight
func calculatehight(){
    let fpanelHight = Float(panelHight)
    let fpanelPitch = Float(panelPitch)
    let fpanelsHigh = Float(panelsHigh)

    resHigh = fpanelHight! * fpanelsHigh! / fpanelPitch!
    screenHight = fpanelHight! * fpanelsHigh! / 1_000

    printText()

}

// Calculating resolution and physical width
func calculatewidth(){
    let fpanelWidth = Float(panelWidth)
    let fpanelPitch = Float(panelPitch)
    let fpanelsWidth = Float(panelsWidth)

    resWidth = fpanelWidth!*fpanelsWidth!/fpanelPitch!
    screenWidth = fpanelWidth!*fpanelsWidth! / 1_000

    printText()

}

// Calculating sqm of LED screen
func calculateArea(){

    let fpanelHight = Float(panelHight)
    let fpanelsHigh = Float(panelsHigh)
    let fpanelWidth = Float(panelWidth)
    let fpanelsWidth = Float(panelsWidth)

    screenArea = (fpanelHight! * fpanelsHigh!) * (fpanelWidth! * fpanelsWidth!) / 1_000_000

    printText()

}

// Calculating the amount of panels used.
func calculateAmountPanels(){

    let fpanelsHigh = Float(panelsHigh)
    let fpanelsWidth = Float(panelsWidth)

    ammountPanels = (fpanelsWidth! * fpanelsHigh!)

    printText()

}

// Outputting text to labels with correct format.
func printText(){

    let formatResHigh = String(format: "%0.0f", resHigh)
    let formatResWidth = String(format: "%0.0f", resWidth)
    let formatScreenHight = String(format: "%0.2f", screenHight)
    let formatScreenWidth = String(format: "%0.2f", screenWidth)
    let formatScreenArea = String(format: "%0.0f", screenArea)
    let formatAmmountPanels = String(format: "%0.0f", ammountPanels)

    resHightLabel.stringValue = "\(formatResHigh)px"
    resWidthLabel.stringValue = "\(formatResWidth)px"
    lblScreenHight.stringValue = "\(formatScreenHight)m"
    lblScreenWidth.stringValue = "\(formatScreenWidth)m"
    lblScreenArea.stringValue = "\(formatScreenArea) sqm"
    lblAmountPanels.stringValue = "\(formatAmmountPanels)"
}
}
</code>```

答:
I had the same problem but I found simple solution: checkbox can enable and disable NSButton.

```<code>import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var btnCalculate: NSButton!
    @IBOutlet weak var checkBox: NSButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        btnCalculate.enabled = false
        checkBox.state = 0
    }

    @IBAction func checkAgree(sender: NSButton) {
        if btnCalculate.stringValue.characters.count > 0 && checkBox.state == 1 {
            btnCalculate.enabled = true
        } else {
            btnCalculate.enabled = false
        }
    }
}
</code>```

Body:
I am creating a OSX app and would like to enable a button when all textfield are filled. But do not have  much experience with osx app as there seem to be some difference from ios.

This is what I have tried.

override func viewDidLoad() {
    super.viewDidLoad()

    btnCalculate.enabled = false

}

override func controlTextDidChange(obj: NSNotification) {

    if panelsWideTextField.stringValue.isEmpty {
        btnCalculate.enabled = false
    } else {
        btnCalculate.enabled = true
    }
}

Hope someone has a good tip for me :-)

EDIT:

Complete code.

import Cocoa
//import AppKit

class ViewController: NSViewController, NSTextFieldDelegate {

@IBOutlet weak var panelHightTextField: NSTextField!
@IBOutlet weak var panelWidthTextField: NSTextField!
@IBOutlet weak var panelPitchTextField: NSTextField!
@IBOutlet weak var panelsHighTextField: NSTextField!
@IBOutlet weak var panelsWideTextField: NSTextField!
@IBOutlet weak var resWidthLabel: NSTextField!
@IBOutlet weak var resHightLabel: NSTextField!
@IBOutlet weak var lblScreenWidth: NSTextField!
@IBOutlet weak var lblScreenHight: NSTextField!
@IBOutlet weak var lblScreenArea: NSTextField!
@IBOutlet weak var btnCalculate: NSButton!
@IBOutlet weak var lblAmountPanels: NSTextField!

var panelHight = ""
var panelWidth = ""
var panelPitch = ""
var panelsHigh = ""
var panelsWidth = ""

var resWidth : Float = 0
var resHigh : Float = 0
var screenHight : Float = 0
var screenWidth : Float = 0
var screenArea : Float = 0
var ammountPanels : Float = 0

override func viewDidLoad() {
    super.viewDidLoad()

    btnCalculate.enabled = false

}

override func controlTextDidChange(obj: NSNotification) {
    if panelsWideTextField.stringValue.isEmpty {
        btnCalculate.enabled = true
    } else {
        btnCalculate.enabled = false
    }
}

override var representedObject: AnyObject? {
    didSet {
        // Update the view, if already loaded.
    }
}

@IBAction func calculateResButton(sender: AnyObject) {
    takeUserData()
    calculatehight()
    calculatewidth()
    calculateArea()
    calculateAmountPanels()
}

func takeUserData(){
    panelHight = panelHightTextField.stringValue
    panelWidth = panelWidthTextField.stringValue
    panelPitch = panelPitchTextField.stringValue
    panelsHigh = panelsHighTextField.stringValue
    panelsWidth = panelsWideTextField.stringValue
}

// Calculating resolution and physical hight
func calculatehight(){
    let fpanelHight = Float(panelHight)
    let fpanelPitch = Float(panelPitch)
    let fpanelsHigh = Float(panelsHigh)

    resHigh = fpanelHight! * fpanelsHigh! / fpanelPitch!
    screenHight = fpanelHight! * fpanelsHigh! / 1_000

    printText()

}

// Calculating resolution and physical width
func calculatewidth(){
    let fpanelWidth = Float(panelWidth)
    let fpanelPitch = Float(panelPitch)
    let fpanelsWidth = Float(panelsWidth)

    resWidth = fpanelWidth!*fpanelsWidth!/fpanelPitch!
    screenWidth = fpanelWidth!*fpanelsWidth! / 1_000

    printText()

}

// Calculating sqm of LED screen
func calculateArea(){

    let fpanelHight = Float(panelHight)
    let fpanelsHigh = Float(panelsHigh)
    let fpanelWidth = Float(panelWidth)
    let fpanelsWidth = Float(panelsWidth)

    screenArea = (fpanelHight! * fpanelsHigh!) * (fpanelWidth! * fpanelsWidth!) / 1_000_000

    printText()

}

// Calculating the amount of panels used.
func calculateAmountPanels(){

    let fpanelsHigh = Float(panelsHigh)
    let fpanelsWidth = Float(panelsWidth)

    ammountPanels = (fpanelsWidth! * fpanelsHigh!)

    printText()

}

// Outputting text to labels with correct format.
func printText(){

    let formatResHigh = String(format: "%0.0f", resHigh)
    let formatResWidth = String(format: "%0.0f", resWidth)
    let formatScreenHight = String(format: "%0.2f", screenHight)
    let formatScreenWidth = String(format: "%0.2f", screenWidth)
    let formatScreenArea = String(format: "%0.0f", screenArea)
    let formatAmmountPanels = String(format: "%0.0f", ammountPanels)

    resHightLabel.stringValue = "\(formatResHigh)px"
    resWidthLabel.stringValue = "\(formatResWidth)px"
    lblScreenHight.stringValue = "\(formatScreenHight)m"
    lblScreenWidth.stringValue = "\(formatScreenWidth)m"
    lblScreenArea.stringValue = "\(formatScreenArea) sqm"
    lblAmountPanels.stringValue = "\(formatAmmountPanels)"
}
}

Body:
I had the same problem but I found simple solution: checkbox can enable and disable NSButton.

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var btnCalculate: NSButton!
    @IBOutlet weak var checkBox: NSButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        btnCalculate.enabled = false
        checkBox.state = 0
    }

    @IBAction func checkAgree(sender: NSButton) {
        if btnCalculate.stringValue.characters.count > 0 && checkBox.state == 1 {
            btnCalculate.enabled = true
        } else {
            btnCalculate.enabled = false
        }
    }
}