问:
MongoDB with Xamarin.Forms connecting db issue c#
I have the following:

```<code>MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);
</code>```

and at this last line I get this:

```<code>{System.EntryPointNotFoundException: mono_get_runtime_build_info
  at (wrapper managed-to-native)** System.Runtime.InteropServices.RuntimeInformation:mono_get_runtime_build_info ()
  at System.Runtime.InteropServices.RuntimeInformation.get_FrameworkDescription () [0x00000] in <faa8163a322d41a99fc85eb6d1c29040>:0
  at MongoDB.Driver.Core.Connections.ClientDocumentHelper.GetPlatformString () [0x00000] in <077b2160c936411eb67f8073bdcbbe94>:0
  at System.Lazy`1[T].CreateValue () [0x00081] in <d18287e1d683419a8ec3216fd78947b9>:0
  at System.Lazy`1[T].LazyInitValue () [0x00080] in <d18287e1d683419a8ec3216fd78947b9>:0
  at System.Lazy`1[T].get_Value () [0x0003a] in <d18287e1d683419a8ec3216fd78947b9>:0
  at MongoDB.Driver.Core.Connections.ClientDocumentHelper.CreateClientDocument (System.String applicationName) [0x00015] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Connections.ConnectionInitializer..ctor (System.String applicationName) [0x00006] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Connections.BinaryConnectionFactory..ctor (MongoDB.Driver.Core.Configuration.ConnectionSettings settings, MongoDB.Driver.Core.Connections.IStreamFactory streamFactory, MongoDB.Driver.Core.Events.IEventSubscriber eventSubscriber) [0x00040] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Configuration.ClusterBuilder.BuildCluster () [0x0002e] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.ClusterRegistry.CreateCluster (MongoDB.Driver.ClusterKey clusterKey) [0x000ad] in <42bdb488f5094fc1bb90030259d358c6>:0
  at MongoDB.Driver.ClusterRegistry.GetOrCreateCluster (MongoDB.Driver.ClusterKey clusterKey) [0x00021] in <42bdb488f5094fc1bb90030259d358c6>:0
  at MongoDB.Driver.MongoClient..ctor (MongoDB.Driver.MongoClientSettings settings) [0x0002d] in <42bdb488f5094fc1bb90030259d358c6>:0
  at .....ctor () [0x00025] in ...
</code>```

I've tried connecting at this line:

```<code>var client = new MongoClient(settings);
</code>```

without setting, with and without connection string but nothing... I'm able to add documents to the db using command prompt and db.movie.insert as described here
https://www.tutorialspoint.com/mongodb/mongodb_create_database.htm but when I try to connect using the C# driver is like if the server is not running.

Please help! and thanks

答: Try using ip of machine which is a host of your mongo db. But I'd recommend you to develop some server side code, for example using node js. Then send rest based requests to your node js app, and in node js, read and write from/to db. This is far better than what you're trying to accomplish here. Your approach puts your data at risk. </p>

Body:
I have the following:

MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);

and at this last line I get this:

{System.EntryPointNotFoundException: mono_get_runtime_build_info
  at (wrapper managed-to-native)** System.Runtime.InteropServices.RuntimeInformation:mono_get_runtime_build_info ()
  at System.Runtime.InteropServices.RuntimeInformation.get_FrameworkDescription () [0x00000] in <faa8163a322d41a99fc85eb6d1c29040>:0
  at MongoDB.Driver.Core.Connections.ClientDocumentHelper.GetPlatformString () [0x00000] in <077b2160c936411eb67f8073bdcbbe94>:0
  at System.Lazy`1[T].CreateValue () [0x00081] in <d18287e1d683419a8ec3216fd78947b9>:0
  at System.Lazy`1[T].LazyInitValue () [0x00080] in <d18287e1d683419a8ec3216fd78947b9>:0
  at System.Lazy`1[T].get_Value () [0x0003a] in <d18287e1d683419a8ec3216fd78947b9>:0
  at MongoDB.Driver.Core.Connections.ClientDocumentHelper.CreateClientDocument (System.String applicationName) [0x00015] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Connections.ConnectionInitializer..ctor (System.String applicationName) [0x00006] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Connections.BinaryConnectionFactory..ctor (MongoDB.Driver.Core.Configuration.ConnectionSettings settings, MongoDB.Driver.Core.Connections.IStreamFactory streamFactory, MongoDB.Driver.Core.Events.IEventSubscriber eventSubscriber) [0x00040] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.Core.Configuration.ClusterBuilder.BuildCluster () [0x0002e] in <077b2160c936411eb67f8073bdcbbe94>:0
  at MongoDB.Driver.ClusterRegistry.CreateCluster (MongoDB.Driver.ClusterKey clusterKey) [0x000ad] in <42bdb488f5094fc1bb90030259d358c6>:0
  at MongoDB.Driver.ClusterRegistry.GetOrCreateCluster (MongoDB.Driver.ClusterKey clusterKey) [0x00021] in <42bdb488f5094fc1bb90030259d358c6>:0
  at MongoDB.Driver.MongoClient..ctor (MongoDB.Driver.MongoClientSettings settings) [0x0002d] in <42bdb488f5094fc1bb90030259d358c6>:0
  at .....ctor () [0x00025] in ...

I've tried connecting at this line:

var client = new MongoClient(settings);

without setting, with and without connection string but nothing... I'm able to add documents to the db using command prompt and db.movie.insert as described here
https://www.tutorialspoint.com/mongodb/mongodb_create_database.htm but when I try to connect using the C# driver is like if the server is not running.

Please help! and thanks


来源: stackexchange

问:
Getting column cannot be null while trying to use 'insert into select' query
insert into TABLE1
    (id,table2id)

```<code>values
(
    1,
    (select distinct id from TABLE2 s table2 where table2.data='ABC')

);
</code>```

Let us say table2id column of TABLE1 is not nullable. But, (select distinct id from TABLE2 s table2 where table2.data='ABC') query can potentially return null. How to make the above query insert into TABLE1 when (select distinct id from TABLE2 s table2 where table2.data='ABC') query is not returning null without getting 'table2id cannot be null' error message.

答:
Replace 0 with any value you want</p>

```<code>insert into TABLE1 (id,table2id)
values
(
    1,
    COALESCE((SELECT DISTINCT id FROM TABLE2 as table2 WHERE table2.data = 'ABC'),0))
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
insert into TABLE1
    (id,table2id)

values
(
    1,
    (select distinct id from TABLE2 s table2 where table2.data='ABC')

);

Let us say table2id column of TABLE1 is not nullable. But, (select distinct id from TABLE2 s table2 where table2.data='ABC') query can potentially return null. How to make the above query insert into TABLE1 when (select distinct id from TABLE2 s table2 where table2.data='ABC') query is not returning null without getting 'table2id cannot be null' error message.

Body:
Replace 0 with any value you want

insert into TABLE1 (id,table2id)
values
(
    1,
    COALESCE((SELECT DISTINCT id FROM TABLE2 as table2 WHERE table2.data = 'ABC'),0))
);


问:
I want the hyperlink to be in a different place
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
 </tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
 </tr>
 </table>
 <a href="http://www.google.com">Visit Google!</a>
</body>
</html>
</code>```

答: I think you are interested about css positioning. Take a look at this: http://www.barelyfitz.com/screencast/html-training/css/positioning/</p>

ContentLicense: CC BY-SA 2.5

Body:
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

 Visit Google!


问:
failed to open stream: Invalid argument in C:\xampp\htdocs\imgfox\upload.php on line 26 you try upload no/..image.
i got this error while i working in image share service and while i try upload image nothing happens and no image gets upload and please can you add on the code the code which make every image uploaded stored in a folder ?
my service code :

```<code><html>
<head>
     <title>upload images</title>
</head>
<body>

<form action="upload.php" method="POST" enctype="multipart/form-data">
   image:
   <input type="file" name="image"> <input type="submit" value="Upload">
</form>

<?php
// connect to database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("meinimages") or die(mysql_error());

// file properties
$file = $_FILES['image']['tmp_name'];

if (!isset($file))
    echo "please choose an image.";
else
{
 $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
 $image_name = addslashes($_FILES['image']['name']);
 $image_size = getimagesize($image);

 if ($image_size==FALSE)
     echo "you try upload no/..image.";
else
 {
    if (!$insert = mysql_query("INSERT INTO store VALUES ('','$image_name','$image')"))
      echo "problem while upload $image.";
    else
    {
      $lastid = mysql_insert_id();
      echo "image is uploaded.<p />your image:<p /><img src=get.php?id=$lastid>";
    }

 }

}
</code>```

答:
Just use this code ~

```<code><input type="file" name="uploadsrc" />

<?php
move_uploaded_file("uploads/".$_FILES["uploadsrc"]["name"]);
?>
</code>```

No need to shout out your question as everybody can see it!

Body:
i got this error while i working in image share service and while i try upload image nothing happens and no image gets upload and please can you add on the code the code which make every image uploaded stored in a folder ?
my service code :

     <title>upload images</title>

<form action="upload.php" method="POST" enctype="multipart/form-data">
   image:
   <input type="file" name="image"> <input type="submit" value="Upload">
</form>

<?php
// connect to database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("meinimages") or die(mysql_error());

// file properties
$file = $_FILES['image']['tmp_name'];

if (!isset($file))
    echo "please choose an image.";
else
{
 $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
 $image_name = addslashes($_FILES['image']['name']);
 $image_size = getimagesize($image);

 if ($image_size==FALSE)
     echo "you try upload no/..image.";
else
 {
    if (!$insert = mysql_query("INSERT INTO store VALUES ('','$image_name','$image')"))
      echo "problem while upload $image.";
    else
    {
      $lastid = mysql_insert_id();
      echo "image is uploaded.
your image:
";
    }

 }

}

Body:
Just use this code ~

<input type="file" name="uploadsrc" />

<?php
move_uploaded_file("uploads/".$_FILES["uploadsrc"]["name"]);
?>

No need to shout out your question as everybody can see it!


问:
Get Unique records in Spark
I have a dataframe df as mentioned below:

```<code>**customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
     1               A            1           ABC            123         1
     3               Z            r           ERF            789         2
     2               B            X           ABC            123         2
     2               B            X           DEF            456         3
     1               A            1           DEF            456         2
</code>```

I want to create a new dataframe df2, which will have only unique customer ids, but as rule_name and rule_id columns are different for same customer in data, so I want to pick those records which has highest priority for the same customer, so my final outcome should be:

```<code> **customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
         1               A            1           ABC            123         1
         3               Z            r           ERF            789         2
         2               B            X           ABC            123         2
</code>```

Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.

答:
To create df2 you have to first order df by priority and then find unique customers by id. Like this:

```<code>val columns = df.schema.map(_.name).filterNot(_ == "customers").map(col => first(col).as(col))

val df2 = df.orderBy("priority").groupBy("customers").agg(columns.head, columns.tail:_*).show
</code>```

It would give you expected output:

```<code>+----------+--------+-------+----------+--------+---------+
| customers| product| val_id| rule_name| rule_id| priority|
+----------+--------+-------+----------+--------+---------+
|         1|       A|      1|       ABC|     123|        1|
|         3|       Z|      r|       ERF|     789|        2|
|         2|       B|      X|       ABC|     123|        2|
+----------+--------+-------+----------+--------+---------+
</code>```

Title: Get Unique records in Spark

Body:
I have a dataframe df as mentioned below:

**customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
     1               A            1           ABC            123         1
     3               Z            r           ERF            789         2
     2               B            X           ABC            123         2
     2               B            X           DEF            456         3
     1               A            1           DEF            456         2

I want to create a new dataframe df2, which will have only unique customer ids, but as rule_name and rule_id columns are different for same customer in data, so I want to pick those records which has highest priority for the same customer, so my final outcome should be:

 **customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
         1               A            1           ABC            123         1
         3               Z            r           ERF            789         2
         2               B            X           ABC            123         2

Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.

Body:
To create df2 you have to first order df by priority and then find unique customers by id. Like this:

val columns = df.schema.map(_.name).filterNot(_ == "customers").map(col => first(col).as(col))

val df2 = df.orderBy("priority").groupBy("customers").agg(columns.head, columns.tail:_*).show

It would give you expected output:

+----------+--------+-------+----------+--------+---------+
| customers| product| val_id| rule_name| rule_id| priority|
+----------+--------+-------+----------+--------+---------+
|         1|       A|      1|       ABC|     123|        1|
|         3|       Z|      r|       ERF|     789|        2|
|         2|       B|      X|       ABC|     123|        2|
+----------+--------+-------+----------+--------+---------+


问:
What is .NET Core equivalent of Encoding.GetEncodings()
I need to dynamically get list of all encodings and I found this https://msdn.microsoft.com/en-us/library/system.text.encoding.getencodings(v=vs.110).aspx , which works great for the older versions of .net, but I am looking and can't find equivalent for .NET Core.

The solution needs to work on mac and linux.

答: Encoding.GetEncodings() exists as part of .NET Standard 2.0 and .NET Core 2.0. I don't know of any alternative for .NET Core 1.x.


问:
Add context menu in bookmark menu
I am trying to add a context menu item in the bookmark menu of Firefox (with a WebExtension). I read the contextMenus.create() article and the example works for me.

There are a bunch of context types, but none seems to work in the bookmark menu. Is this not possible?

答:
What you desire is not currently possible in a WebExtension. In general, if there is capability that you desire in WebExtensions which does not already exist, you can:

File a Request For Enhancement (a bug) requesting the functionality. In the case of adding an item to the bookmark context menu, such a bug already exists: Bug 1370499: Consider support for bookmark context menus. The general direction from this tracking bug is that adding an entry to the bookmark context menu will be implemented at some point in time.

Create a WebExtension experiment: You can create a WebExtension experiment to implement the functionality. If you create a WebExtension experiment, you can request that it be integrated into Firefox (which may, or may not happen). Having a WebExtension experiment will make it more likely that something along the lines of what you want is implemented, because it reduces the amount of Mozilla developer time required to do so. As WebExtension Experiments are actually legacy add-ons, they will not be able to function in Firefox as of the Release version of Firefox 57 (2017-11-14).

WebExtension experiments support (and legacy add-ons in general) is disabled by default in Firefox Nightly. However, in Nightly, you can enable an about:config preference, extensions.legacy.enabled, which allows you to use legacy extensions, including WebExtension Experiments. This is expected to be also be true in Developer Edition, but has not been verified. WebExtension Experiments and legacy add-ons certainly won't function in the Release version of Firefox 57.

One thing that might improve the chance of having some functionality added to Firefox is to look through what is possible in Chrome extensions. If there is a Chrome extension API which closely matches what you desire, then it's more likely that Mozilla will implement it.

Unfortunately, there is a huge amount of functionality available in the other types of extensions which is not possible in WebExtensions (at least currently, and almost all of it permanently), but it's possible that any specific functionality could implemented. Some things not initially supported have been implemented, at least to a limited extent (e.g. Sidebars).

Title: Add context menu in bookmark menu


问:
Software or Service to Automatically Generate Custom Ordered Lists?
Disclaimer: I'm not a programmer, so this question is non-technical and probably very basic. I am just hoping to be pointed in the right direction...

I want to automate the routine process of compiling custom lists of medical questions by matching a question's attribute tags to the attributes of the patient and ailment. I've built an Access DB which generates lists when queried based on these tags. But I also need to set rules to determine the order the questions are returned in. Otherwise the questions are "out of order" and don't make sense.

Is there a better (and ideally browser based) software or service I could use to achieve such search/reporting functionality? Or does I need to find someone who can add this functionality to my access DB?

Thanks in advance!

答:
It kind of depends on how you generate "lists when queried based on these tags".

If you're using sql to select from the database, then it may just be a matter of adding an "order by" to the end of your query:

eg:

```<code>Select question_no, question from some_table where patient = 'Freddy'
and tag = 'sick' order by question_no
</code>```

Generally speaking, however you are retrieving these questions; the easiest way of ordering them is by one or more columns in the table you're storing the questions (or a related table)

Body:
It kind of depends on how you generate "lists when queried based on these tags".

If you're using sql to select from the database, then it may just be a matter of adding an "order by" to the end of your query:

eg:

Select question_no, question from some_table where patient = 'Freddy'
and tag = 'sick' order by question_no

Generally speaking, however you are retrieving these questions; the easiest way of ordering them is by one or more columns in the table you're storing the questions (or a related table)


问:
jquery.on() get reference to attached listener
I attach an event listeners:

```<code>selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }
</code>```

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

```<code>var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });
</code>```

答:
Instead of using the selector when you call .off() use the target of the current event.

```<code>function handler(event) {
    if (hasLoaded()) {
        $(this).off('DOMSubtreeModified', handler);
        otherStuff(event.email);
    }
}
</code>```

Body:
I attach an event listeners:

selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });

Body:
Instead of using the selector when you call .off() use the target of the current event.

function handler(event) {
    if (hasLoaded()) {
        $(this).off('DOMSubtreeModified', handler);
        otherStuff(event.email);
    }
}


Title: Get Unique records in Spark

Body:
Corey beat me to it, but here's the Scala version:

val df = Seq(
(1,"A","1","ABC",123,1),
(3,"Z","r","ERF",789,2),
(2,"B","X","ABC",123,2),
(2,"B","X","DEF",456,3),
(1,"A","1","DEF",456,2)).toDF("customers","product","val_id","rule_name","rule_id","priority")
val priorities = df.groupBy("customers").agg( min(df.col("priority")).alias("priority"))
val top_rows = df.join(priorities, Seq("customers","priority"), "inner")

+---------+--------+-------+------+---------+-------+
|customers|priority|product|val_id|rule_name|rule_id|
+---------+--------+-------+------+---------+-------+
|        1|       1|      A|     1|      ABC|    123|
|        3|       2|      Z|     r|      ERF|    789|
|        2|       2|      B|     X|      ABC|    123|
+---------+--------+-------+------+---------+-------+


问:
how to making token after 30 minutes with php
I have a function for making token but when refresh page Function creates a new string I want to create a string after 30 minutes with this function .</p>

```<code>function token($length=6){
    $character = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomstring = "";
    $num_valid_chars = strlen($character);
    for ($i = 0; $i < $length; $i++)
    {
        $random_pick = mt_rand(1, $num_valid_chars);
        $random_char = $character[$random_pick-1];
        $randomstring .= $random_char;
    }
    return $randomstring;
}
</code>```

答:
You can store token in cookie which expire after 30 minutes. You can check if cookie has value then take it from cookie otherwise create new token.

```<code><?php
function token($length=6){
    $cookie_name = "token_set";
    if(isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] != "") {
        $randomstring = $_COOKIE[$cookie_name];
    }
    else
    {
        $character = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomstring = "";
        $num_valid_chars = strlen($character);
        for ($i = 0; $i < $length; $i++)
        {
            $random_pick = mt_rand(1, $num_valid_chars);
            $random_char = $character[$random_pick-1];
            $randomstring .= $random_char;
        }

        setcookie($cookie_name, $randomstring, time() + (1800), '/');   //set for 30 mins
    }

    return $randomstring;
}
</code>```

Body:
I have a function for making token but when refresh page Function creates a new string I want to create a string after 30 minutes with this function .

function token($length=6){
    $character = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomstring = "";
    $num_valid_chars = strlen($character);
    for ($i = 0; $i < $length; $i++)
    {
        $random_pick = mt_rand(1, $num_valid_chars);
        $random_char = $character[$random_pick-1];
        $randomstring .= $random_char;
    }
    return $randomstring;
}

Body:
You can store token in cookie which expire after 30 minutes. You can check if cookie has value then take it from cookie otherwise create new token.

<?php
function token($length=6){
    $cookie_name = "token_set";
    if(isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] != "") {
        $randomstring = $_COOKIE[$cookie_name];
    }
    else
    {
        $character = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomstring = "";
        $num_valid_chars = strlen($character);
        for ($i = 0; $i < $length; $i++)
        {
            $random_pick = mt_rand(1, $num_valid_chars);
            $random_char = $character[$random_pick-1];
            $randomstring .= $random_char;
        }

        setcookie($cookie_name, $randomstring, time() + (1800), '/');   //set for 30 mins
    }

    return $randomstring;
}


问:
How to navigate into other divs and access their contents

I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

```<code>console.log($("#toDoListContainer")[0]);
</code>```

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

答:
Hey change your ids to class like this because

Id should be unique.

$('#toDoListContainer').find('div.taskDiv').each(function() {

  var self = $(this);
  // now what ever you want to do
  //like
  console.log(self.attr('data-completed'));
  console.log(self.text())

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div class="taskDiv" data-completed="y">text1</div>
  <div class="taskDiv" data-completed="y">text2</div>
  <div class="taskDiv" data-completed="y">text3</div>
</div></code>```

Body:
I want to to navigate from the #toDoListContainer div into the #taskDiv, how do I do this in jquery.

I want to navigate from div to div to be able to access the data of each div to get the picture to appear

I did the command

console.log($("#toDoListContainer")[0]);

so i was trying to navigate the div like this..

console.log($("#toDoListContainer")[0].children);

I should be able to get into the zeroth div by doing:

console.log($("#toDoListContainer")[0].children[0]);

but I get undefined instead. any Ideas ?

Body:
Hey change your ids to class like this because

Id should be unique.

$('#toDoListContainer').find('div.taskDiv').each(function() {

  var self = $(this);
  // now what ever you want to do
  //like
  console.log(self.attr('data-completed'));
  console.log(self.text())

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="toDoListContainer">
  <div class="taskDiv" data-completed="y">text1</div>
  <div class="taskDiv" data-completed="y">text2</div>
  <div class="taskDiv" data-completed="y">text3</div>
</div>


问:
422 Error: Python POST Request
Im trying to do a POST request to my Rest API which is using Eve as the framework, however whenever I try to POST my JSON I get a 422 Error saying unprocessable entity. My GET Requests work perfectly fine. Here is my schema for my Eve App:

```<code>schema = {
    '_update': {
        'type': 'datetime',
        'minlength': 1,
        'maxlength': 40,
        'required': False,
        'unique': True,
    },
    'Name': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
    'FacebookId': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': True,
    },
    'HighScore': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
}
</code>```

Here is the JSON I am trying to post:

```<code>{"_updated":null,"Name":"John Doe","FacebookId":"12453523434324123","HighScore":15}
</code>```

Here is how I am attempting to do the POST request from my client:

```<code>IDictionary dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as IDictionary;
string name = dict["name"].ToString();
string id = dict["id"].ToString();

Player player = new Player();
player.FacebookId = id;
player.Name = name;
player.HighScore = (int) GameManager.Instance.Points;

// Using Newtonsoft.Json to serialize
var json = JsonConvert.SerializeObject(player);

var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}};

string url = "http://server.com/Players";
var encoding = new UTF8Encoding();
// Using Unity3d WWW class
WWW www = new WWW(url, encoding.GetBytes(json), headers);
StartCoroutine(WaitForRequest(www));
</code>```

答:
you make it so complicated. at first you need a helper method in order to call your service. something like this:

```<code>private static T Call<T>(string url, string body)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = 60 * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "POST";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
        responseString = reader.ReadToEnd();

    return JsonConvert.DeserializeObject<T>(responseString);
}
</code>```

then simply call it like this:

```<code>var url = "http://server.com/Players";
var output=Call<youroutputtype>(url, json);
</code>```

note: i didn't know what is your output type so i just leave it to you.

Title: 422 Error: Python POST Request

Body:
Im trying to do a POST request to my Rest API which is using Eve as the framework, however whenever I try to POST my JSON I get a 422 Error saying unprocessable entity. My GET Requests work perfectly fine. Here is my schema for my Eve App:

schema = {
    '_update': {
        'type': 'datetime',
        'minlength': 1,
        'maxlength': 40,
        'required': False,
        'unique': True,
    },
    'Name': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
    'FacebookId': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': True,
    },
    'HighScore': {
        'type': 'integer',
        'minlength': 1,
        'maxlength': 40,
        'required': True,
        'unique': False,
    },
}

Here is the JSON I am trying to post:

{"_updated":null,"Name":"John Doe","FacebookId":"12453523434324123","HighScore":15}

Here is how I am attempting to do the POST request from my client:

IDictionary dict = Facebook.MiniJSON.Json.Deserialize(result.RawResult) as IDictionary;
string name = dict["name"].ToString();
string id = dict["id"].ToString();

Player player = new Player();
player.FacebookId = id;
player.Name = name;
player.HighScore = (int) GameManager.Instance.Points;

// Using Newtonsoft.Json to serialize
var json = JsonConvert.SerializeObject(player);

var headers = new Dictionary<string, string> {{"Content-Type", "application/json"}};

string url = "http://server.com/Players";
var encoding = new UTF8Encoding();
// Using Unity3d WWW class
WWW www = new WWW(url, encoding.GetBytes(json), headers);
StartCoroutine(WaitForRequest(www));

Body:
you make it so complicated. at first you need a helper method in order to call your service. something like this:

private static T Call<T>(string url, string body)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = 60 * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "POST";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
        responseString = reader.ReadToEnd();

    return JsonConvert.DeserializeObject<T>(responseString);
}

then simply call it like this:

var url = "http://server.com/Players";
var output=Call<youroutputtype>(url, json);

note: i didn't know what is your output type so i just leave it to you.


问:
sed: removing alphanumeric words from a file
I have file with a lot of text, what I want to do is to remove all alphanumeric words.

```<code>Example of words to be removed:

gr8
2006
sdlfj435ljsa
232asa
asld213
ladj2343asda
asd!32
</code>```

what is the best way I can do this?

答:
Assuming the only output you wanted from your sample text is 2006 and you have one word per line:

```<code> sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' /path/to/alnum/file
</code>```

Input

```<code>$ cat alnum
gr8
2006
sdlFj435ljsa
232asa
asld213
ladj2343asda
asd!32
alpha
</code>```

Output

```<code>$ sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' ./alnum
2006
alpha
</code>```

Body:
I have file with a lot of text, what I want to do is to remove all alphanumeric words.

Example of words to be removed:

gr8
2006
sdlfj435ljsa
232asa
asld213
ladj2343asda
asd!32

what is the best way I can do this?

Body:
Assuming the only output you wanted from your sample text is 2006 and you have one word per line:

 sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' /path/to/alnum/file

Input

$ cat alnum
gr8
2006
sdlFj435ljsa
232asa
asld213
ladj2343asda
asd!32
alpha

Output

$ sed '/[[:alpha:]]\+/{/[[:digit:]]\+/d}' ./alnum
2006
alpha


问:
C# Convert exact durations (mm:ss,xx) in ss,xx
My question is how to fix a fail at converting of a time span(m:ss,10th of sec.) in (ss,tenth of seconds);

The Problem is that the Output if this is completely wrong.

```<code>timeInString = "1:09.01";
tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0] * 60) + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));
</code>```

The Output must be 69,01, but is 2949.01.

答:
Move the multiplication outside the parentheses:

```<code>Convert.ToInt32(timeInString[0]) * 60
</code>```

Rationale

The ASCII value of "1" is 49, which is the key to your error and the reason this fails silently.

You start with this code:

```<code>Convert.ToInt32(timeInString[0] * 60)
</code>```

This takes the single-character string timeInString[0] and treats it as an ASCII character for the purposes of multiplication. That is, since C# sees a multiplication sign, it expects multipliable things as operands. It sees the string and thinks, "This is a number behind-the-scenes; let's treat it as one." This amounts to saying:

```<code>Convert.ToInt32(49 * 60)
</code>```

Evaluating the entire expression, you get (49 * 60) + 9 + 0.01 = 2949.01.

What you need to do is move the * 60 outside of the parentheses.

```<code>tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0]) * 60 + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));
</code>```

Body:
My question is how to fix a fail at converting of a time span(m:ss,10th of sec.) in (ss,tenth of seconds);

The Problem is that the Output if this is completely wrong.

timeInString = "1:09.01";
tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0] * 60) + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));

The Output must be 69,01, but is 2949.01.

Body:
Move the multiplication outside the parentheses:

Convert.ToInt32(timeInString[0]) * 60

Rationale

The ASCII value of "1" is 49, which is the key to your error and the reason this fails silently.

You start with this code:

Convert.ToInt32(timeInString[0] * 60)

This takes the single-character string timeInString[0] and treats it as an ASCII character for the purposes of multiplication. That is, since C# sees a multiplication sign, it expects multipliable things as operands. It sees the string and thinks, "This is a number behind-the-scenes; let's treat it as one." This amounts to saying:

Convert.ToInt32(49 * 60)

Evaluating the entire expression, you get (49 * 60) + 9 + 0.01 = 2949.01.

What you need to do is move the * 60 outside of the parentheses.

tmpData.SetTimeDG2((Convert.ToInt32(timeInString[0]) * 60 + Convert.ToInt32(timeInString.Substring(2, 2)) + (Convert.ToDouble(timeInString.Substring(5, 2))/ 100)));


问:
how to access the url inside .success of the $http.get method in angularjs
I have the following controller

```<code>var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
    $scope.urlString = []; //this is filled with values

    for( var i=0; i<3; ++i)
    {
        var currentURL = $scope.urlString[i];
        $http.get(currentURL)
        .success( function(response) {
            //how do I access currentURL here?
            $log.info(this.currURL) //this is printing "undefined"
        });
    }
</code>```

The urls are generated dynamically, and I have to get data from these urls. The urls are generated before the for loop executes (and the url requests are asynchronous).

I tried $.ajax(currentURL) instead of $http.get method, but I got the same result - "undefined".

Is there any way I can access the currentURL and the current value of 'i' inside the .success(function ())?

答:
Instead of using for loop use angular forEach .For more information on angularForeach visit https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=control</p>

```<code>var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
$scope.baseUrl = "http://jsonplaceholder.typicode.com/posts/";
$scope.urlString = [$scope.baseUrl + '1', $scope.baseUrl +'2',$scope.baseUrl + '3']; //this is filled with values

angular.forEach($scope.urlString,function(value,key){

    $http.get(value)
    .success( function(response) {
        $log.info(value)
    });
}
});

app.$inject = ['$scope', '$http', '$log'];
</code>```

Body:
I have the following controller

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
    $scope.urlString = []; //this is filled with values

    for( var i=0; i<3; ++i)
    {
        var currentURL = $scope.urlString[i];
        $http.get(currentURL)
        .success( function(response) {
            //how do I access currentURL here?
            $log.info(this.currURL) //this is printing "undefined"
        });
    }

The urls are generated dynamically, and I have to get data from these urls. The urls are generated before the for loop executes (and the url requests are asynchronous).

I tried $.ajax(currentURL) instead of $http.get method, but I got the same result - "undefined".

Is there any way I can access the currentURL and the current value of 'i' inside the .success(function ())?

Body:
Instead of using for loop use angular forEach .For more information on angularForeach visit https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=control

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
$scope.baseUrl = "http://jsonplaceholder.typicode.com/posts/";
$scope.urlString = [$scope.baseUrl + '1', $scope.baseUrl +'2',$scope.baseUrl + '3']; //this is filled with values

angular.forEach($scope.urlString,function(value,key){

    $http.get(value)
    .success( function(response) {
        $log.info(value)
    });
}
});

app.$inject = ['$scope', '$http', '$log'];


问:
Code a polar function (Gabor) in Matlab
How can I code this function in Matlab?

答:
You don't need to implement this because:

If you have image processing toolbox there is a built-in function for that.

If you don't, you can download an implementation from Mathworks File Exchange.

If for some reason, that's not good enough, you can copy the implementation from Wikipedia.

And finally, if it's an exercise that you should write yourself and external resources are forbidden - then you shouldn't ask it in the first place.

Good luck!

Title: Code a polar function (Gabor) in Matlab

Body: How can I code this function in Matlab?


问:
Equivalent of updateInstead for git fetch -u
As documented and discussed elsewhere, git fetch refuses to fetch the current branch unless you supply the -u option.

This behavior makes perfect sense in most cases, and is obviously the correct default. However, it is not the behavior I want. Instead, I would like something like what the configuration option receive.denyCurrentBranch=updateInstead does: if the current working tree and index match HEAD, then allow the fetch and update working tree; otherwise, refuse the fetch with a similar message to the default. Is there any way to do this without writing my own porcelain command using git fetch -u?

The reason I want this, in case a better workflow is available, is that I am working on a number of projects stored in separate Git repositories. Most of them are just on the dev local branch, which has the dev/master remote branch as its upstream. When I am actually doing development, I do it on a branch named after whatever feature I’m working on, not the dev branch. I want all the remote branches available, so I need to do a git fetch --all -p regularly, and I additionally need to do a git pull in the projects I’m not building so they have the latest code. Because there are a lot of projects, the easiest way is to just loop through them in Bash and run git fetch --all -p; git pull on all of them. Unfortunately, that also runs git pull on the projects I’m currently making changes on, and that might lead to merge conflicts instead of just getting the latest dependencies.

Instead, I would like the projects I’m not currently working on have the working tree updated automatically; then I only need to run git pull on repositories I am currently working on. That way, I can run it only when it’s appropriate, and not worry about merge conflicts when I just want to build against the latest source of the dependent projects.

答:
I additionally need to do a git pull in the projects I’m not building so they have the latest code ... Unfortunately, that also runs git pull on the projects I’m currently making changes on

You can run git pull --ff-only, which fails immediately if there are some local commits.


答:
Don't attempt to parse time strings on your own. Use TimeSpan instead:

```<code>string timeInString = "1:09.01";
TimeSpan interval;
TimeSpan.TryParseExact(timeInString, @"m\:ss\.ff", null, out interval);
Console.WriteLine("Seconds {0}", interval.TotalSeconds);
</code>```

And the problem with your code is that timeInString[0] * 60 is taking the char (unicode) value of 1 instead of the numerical value. So you'd have to parse the char first. Yet, your code would fail if you attempted to enter a string like 11:04.13. Just don't bother parsing this on your own. It's already in the framework. Don't reinvent the wheel.

Title: C# Convert exact durations (mm:ss,xx) in ss,xx

Body:
Don't attempt to parse time strings on your own. Use TimeSpan instead:

string timeInString = "1:09.01";
TimeSpan interval;
TimeSpan.TryParseExact(timeInString, @"m\:ss\.ff", null, out interval);
Console.WriteLine("Seconds {0}", interval.TotalSeconds);

And the problem with your code is that timeInString[0] * 60 is taking the char (unicode) value of 1 instead of the numerical value. So you'd have to parse the char first. Yet, your code would fail if you attempted to enter a string like 11:04.13. Just don't bother parsing this on your own. It's already in the framework. Don't reinvent the wheel.


答:
You will have to use min aggregation on priority column grouping the dataframe by customers and then inner join the original dataframe with the aggregated dataframe and select the required columns.

```<code>val aggregatedDF = dataframe.groupBy("customers").agg(max("priority").as("priority_1"))
      .withColumnRenamed("customers", "customers_1")

    val finalDF = dataframe.join(aggregatedDF, dataframe("customers") === aggregatedDF("customers_1") && dataframe("priority") === aggregatedDF("priority_1"))
    finalDF.select("customers",   "product",   "val_id",  "rule_name",  "rule_id", "priority").show
</code>```

you should have the desired result

Title: Get Unique records in Spark

Body:
I have a dataframe df as mentioned below:

**customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
     1               A            1           ABC            123         1
     3               Z            r           ERF            789         2
     2               B            X           ABC            123         2
     2               B            X           DEF            456         3
     1               A            1           DEF            456         2

I want to create a new dataframe df2, which will have only unique customer ids, but as rule_name and rule_id columns are different for same customer in data, so I want to pick those records which has highest priority for the same customer, so my final outcome should be:

 **customers**   **product**   **val_id**  **rule_name**  **rule_id** **priority**
         1               A            1           ABC            123         1
         3               Z            r           ERF            789         2
         2               B            X           ABC            123         2

Can anyone please help me to achieve it using Spark scala. Any help will be appericiated.

Body:
You will have to use min aggregation on priority column grouping the dataframe by customers and then inner join the original dataframe with the aggregated dataframe and select the required columns.

val aggregatedDF = dataframe.groupBy("customers").agg(max("priority").as("priority_1"))
      .withColumnRenamed("customers", "customers_1")

    val finalDF = dataframe.join(aggregatedDF, dataframe("customers") === aggregatedDF("customers_1") && dataframe("priority") === aggregatedDF("priority_1"))
    finalDF.select("customers",   "product",   "val_id",  "rule_name",  "rule_id", "priority").show

you should have the desired result


问:
Select matching array with aggregate
hotdeal:

```<code>{ "property" : "ATL-D406" }
</code>```

translation:

```<code>{ "property" : "ATL-D406", "language" : "gb", "txt": [{"aaa":"hi", "bbb":"bye"}] }
{ "property" : "ATL-D406", "language" : "ru", "txt": [{"aaa":"priviet", "bbb":"baka"}] }
{ "property" : "ATL-D406", "language" : "cn", "txt": [{"aaa":"??", "bbb":"??"}] }
</code>```

Current result:

```<code>{ "property":"ATL-D406", "language":[ "gb", "ru", "cn" ] }
</code>```

What I would like:

```<code>{ "property":"ATL-D406", "language":"gb", "aaa":"hi", "bbb":"bye" }
</code>```

I cannot understand why my $elemMatch is not working, shouldn't it isolate that particular element in the result from "translation"?

Also once I got it to only take the "gb" language, how do I project "aaa" and "bbb" without them being inside an array?  I tried $resolve but then I get no data at all. Can you $resolve an array in an array? ($resolve "txt")?

```<code>db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        from: 'translation',
        localField: 'property',
        foreignField: 'property',
        as: 'translations'
    } },

    { '$match':
        { 'translations':
            { '$elemMatch': { 'language': 'gb' } }
        }
    },

    { '$project': {
        _id: 0,
        property: 1,
        language: '$translations.language'
    }}
])
</code>```

答:
```<code>db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        from: 'translation',
        localField: 'property',
        foreignField: 'property',
        as: 'translations'
    } },

    { '$unwind': '$translations' },

    { '$match': { 'translations.language': 'gb' } },

    { '$project': {
        _id: 0,
        property: 1,
        language: '$translations.language',
        aaa: '$translations.txt.aaa',
        bbb: '$translations.txt.bbb'
    }}
])
</code>```

Title: Select matching array with aggregate

Body:
hotdeal:

{ "property" : "ATL-D406" }

translation:

{ "property" : "ATL-D406", "language" : "gb", "txt": [{"aaa":"hi", "bbb":"bye"}] }
{ "property" : "ATL-D406", "language" : "ru", "txt": [{"aaa":"priviet", "bbb":"baka"}] }
{ "property" : "ATL-D406", "language" : "cn", "txt": [{"aaa":"??", "bbb":"??"}] }

Current result:

{ "property":"ATL-D406", "language":[ "gb", "ru", "cn" ] }

What I would like:

{ "property":"ATL-D406", "language":"gb", "aaa":"hi", "bbb":"bye" }

I cannot understand why my $elemMatch is not working, shouldn't it isolate that particular element in the result from "translation"?

Also once I got it to only take the "gb" language, how do I project "aaa" and "bbb" without them being inside an array?  I tried $resolve but then I get no data at all. Can you $resolve an array in an array? ($resolve "txt")?

db.hotdeal.aggregate([
    { '$match': {} },
    { '$lookup': {
        from: 'translation',
        localField: 'property',
        foreignField: 'property',
        as: 'translations'
    } },

    { '$match':
        { 'translations':
            { '$elemMatch': { 'language': 'gb' } }
        }
    },

    { '$project': {
        _id: 0,
        property: 1,
        language: '$translations.language'
    }}
])


问:
The apostrophes are not displayed when getting data from MySQL into bootstrap table
When I execute SELECT query in php in order to get data from MySQL DB into bootstrap table, the apostrophes are not displayed correctly in the table rows. In particular, I get Gr�a instead of Grúa.

This is how I get data from MySQL DB:

```<code><?php
  include_once 'include/connect_db.php';

  $query = "SELECT * FROM myTable;";
  $result = ejecutar_query($query);

  $list = array();
  while ($b = mysqli_fetch_array($result)) {
    $list[] = $b;
  }
?>

<td><?php echo $row['name'];?></td>

<!--jQuery Datatable-->
<script>
     $(document).ready(function(){
              $('#myTable').dataTable({
              "sPaginationType":"full_numbers",
              "aaSorting":[[0, "asc"]],
              "bJQueryUI":true
              });

              hideLoading();

     });
</script>
</code>```

Should I change the encoding in MySQL DB or what should I do to solve this issue?

答:
Do not use any encode/decode functions; that just compounds the problem.

See here for discussion of the causes and cures of "black diamond".

Body:
When I execute SELECT query in php in order to get data from MySQL DB into bootstrap table, the apostrophes are not displayed correctly in the table rows. In particular, I get Gr�a instead of Grúa.

This is how I get data from MySQL DB:

<?php
  include_once 'include/connect_db.php';

  $query = "SELECT * FROM myTable;";
  $result = ejecutar_query($query);

  $list = array();
  while ($b = mysqli_fetch_array($result)) {
    $list[] = $b;
  }
?>

<?php echo $row['name'];?>

Should I change the encoding in MySQL DB or what should I do to solve this issue?


问:
Angular 2.3 Component Inheritance
I am trying to put some common code, which adds server errors to the form etc, and would be used in all my form components, in a base form component.

I have simplified the example code to demonstrate my problem.

import { Component, } from '@angular/core';
import { Validators } from '@angular/forms';
import { FormGroup, FormBuilder } from '@angular/forms';

export abstract class BaseFormComponent {
  form: FormGroup;
  fb = new FormBuilder;
  submitted = false;
  busy: boolean;

  onSubmit() {
    this.submitted = true;
    this.busy = true;
  }
}

@Component({
  selector: 'my-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>

        Name
        <input formControlName="name" class="form-control">

      <button type="submit" [disabled]="busy" class="btn btn-primary">Submit</button>
    </form>
  `
})
export class FormComponent extends BaseFormComponent {

  constructor() {
    super();
    this.createForm();
  }

  protected createForm() {
    this.form = this.fb.group({
      name: ['', Validators.compose([Validators.required, Validators.maxLength(10)]) ],
    });
  }
}
```

For some reason I am getting errors that the template cannot find the base class properties.

Error: [21, 24]: The property "form" that you're trying to access does
  not exist in the class declaration. [21, 42]: The method "onSubmit"
  that you're trying to access does not exist in the class declaration.
  [26, 41]: The property "busy" that you're trying to access does not
  exist in the class declaration. [21, 24]: The property "form" that
  you're trying to access does not exist in the class declaration. [21,
  42]: The method "onSubmit" that you're trying to access does not exist
  in the class declaration. [26, 41]: The property "busy" that you're
  trying to access does not exist in the class declaration.

Comparing my code to this article, it seems pretty much identical except I am not decorating the base form class as a component. Decorating the base class does not seem to make any difference anyway.

I am using:

typescript@2.3.4

@angular/common@2.4.7

webpack@2.2.1

答:
To answer my own question. As @estus mentioned, there is nothing wrong with the code and the issue is related to Codelyzer. The issue can be found here.

https://github.com/mgechev/codelyzer/issues/191

A temporary fix to the issue is to simply ignore it by placing the following comment at the top of the file, until issues between tslint and codelyzer has been sorted out.

```<code>// tslint:disable:no-access-missing-member
</code>```

Title: Angular 2.3 Component Inheritance

Body:
I am trying to put some common code, which adds server errors to the form etc, and would be used in all my form components, in a base form component.

I have simplified the example code to demonstrate my problem.

import { Component, } from '@angular/core';
import { Validators } from '@angular/forms';
import { FormGroup, FormBuilder } from '@angular/forms';

export abstract class BaseFormComponent {
  form: FormGroup;
  fb = new FormBuilder;
  submitted = false;
  busy: boolean;

  onSubmit() {
    this.submitted = true;
    this.busy = true;
  }
}

@Component({
  selector: 'my-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>

        Name
        <input formControlName="name" class="form-control">

      <button type="submit" [disabled]="busy" class="btn btn-primary">Submit</button>
    </form>
  `
})
export class FormComponent extends BaseFormComponent {

  constructor() {
    super();
    this.createForm();
  }

  protected createForm() {
    this.form = this.fb.group({
      name: ['', Validators.compose([Validators.required, Validators.maxLength(10)]) ],
    });
  }
}

For some reason I am getting errors that the template cannot find the base class properties.

Error: [21, 24]: The property "form" that you're trying to access does
  not exist in the class declaration. [21, 42]: The method "onSubmit"
  that you're trying to access does not exist in the class declaration.
  [26, 41]: The property "busy" that you're trying to access does not
  exist in the class declaration. [21, 24]: The property "form" that
  you're trying to access does not exist in the class declaration. [21,
  42]: The method "onSubmit" that you're trying to access does not exist
  in the class declaration. [26, 41]: The property "busy" that you're
  trying to access does not exist in the class declaration.

Comparing my code to this article, it seems pretty much identical except I am not decorating the base form class as a component. Decorating the base class does not seem to make any difference anyway.

I am using:

typescript@2.3.4

@angular/common@2.4.7

webpack@2.2.1

Body:
To answer my own question. As @estus mentioned, there is nothing wrong with the code and the issue is related to Codelyzer. The issue can be found here.

https://github.com/mgechev/codelyzer/issues/191

A temporary fix to the issue is to simply ignore it by placing the following comment at the top of the file, until issues between tslint and codelyzer has been sorted out.

// tslint:disable:no-access-missing-member


问:
Graphic image saving in text editor?
I am making a basic text editor from this tutorial here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextArchitecture/Tasks/TextEditor.html

My text editor can save, write, and open documents in RTF and TXT format, but cannot save graphics along with any text. Formatted text is saved, and the graphic does display when the window is open, but does not get saved.

答:
You're almost there, you just need to implement a bit more in your app's Info.plist.

```<code>- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
NSData *data;
[self setString:[textView textStorage]];
NSMutableDictionary *dict =
[NSDictionary dictionaryWithObject:NSRTFTextDocumentType
forKey:NSDocumentTypeDocumentAttribute];
</code>```

Notice that in the method which asks for the data to be saved to file, no matter what, it's set up to use NSRTFTextDocumentType rather than NSRTF*D*TextDocumentType. RTFD means RTF with attachments, which saves an .rtfd document which is actually a package/bundle (a folder that is presented to the user as if it were a single file). Saving as NSRTFTextDocumentType will effectively discard the stuff that can't fit into an RTF document, like the images.

After step 12 is the following:

At this stage of its development, your editor opens and saves documents only with an extension of ????. To enable your application to save and open documents with a recognized file type, you need to use Xcode to configure the document types settings in the application’s property list file in the Resources folder in Xcode. (The Xcode template names the file with your project name followed by -Info.plist.) You can edit this file in Xcode by selecting the file in the Groups & Files list and using the built-in editor. Click the disclosure triangles to edit the value of the first item under CFBundleTypeExtensions to the preferred extension for your document files.

For more information about property list files, see “Storing Document Types Information in the Application's Property List” in Document-Based Applications Overview. For complete details about application property lists, see Runtime Configuration Guidelines.

Basically, right now, you're being passed in a generic DocumentType in that data method shown above. Once you claim in your Info.plist that you can handle RTF and RTFD data (as 2 separate entries), you will be passed in a different value in that method, depending on what the user has chosen in the Format popup button in the NSSavePanel. You can check the value of the passed in type and then specify NSRTFTextDocumentType or NSRTFDTextDocumentType accordingly.

You can probably look at TextEdit's Info.plist to use as the basis of your Document types, though be sure to change the NSDocument subclass name to your own so the NSDocumentController knows what class to use.

Title: Graphic image saving in text editor?

Body:
You're almost there, you just need to implement a bit more in your app's Info.plist.

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
NSData *data;
[self setString:[textView textStorage]];
NSMutableDictionary *dict =
[NSDictionary dictionaryWithObject:NSRTFTextDocumentType
forKey:NSDocumentTypeDocumentAttribute];

Notice that in the method which asks for the data to be saved to file, no matter what, it's set up to use NSRTFTextDocumentType rather than NSRTF*D*TextDocumentType. RTFD means RTF with attachments, which saves an .rtfd document which is actually a package/bundle (a folder that is presented to the user as if it were a single file). Saving as NSRTFTextDocumentType will effectively discard the stuff that can't fit into an RTF document, like the images.

After step 12 is the following:

At this stage of its development, your editor opens and saves documents only with an extension of ????. To enable your application to save and open documents with a recognized file type, you need to use Xcode to configure the document types settings in the application’s property list file in the Resources folder in Xcode. (The Xcode template names the file with your project name followed by -Info.plist.) You can edit this file in Xcode by selecting the file in the Groups & Files list and using the built-in editor. Click the disclosure triangles to edit the value of the first item under CFBundleTypeExtensions to the preferred extension for your document files.

For more information about property list files, see “Storing Document Types Information in the Application's Property List” in Document-Based Applications Overview. For complete details about application property lists, see Runtime Configuration Guidelines.

Basically, right now, you're being passed in a generic DocumentType in that data method shown above. Once you claim in your Info.plist that you can handle RTF and RTFD data (as 2 separate entries), you will be passed in a different value in that method, depending on what the user has chosen in the Format popup button in the NSSavePanel. You can check the value of the passed in type and then specify NSRTFTextDocumentType or NSRTFDTextDocumentType accordingly.

You can probably look at TextEdit's Info.plist to use as the basis of your Document types, though be sure to change the NSDocument subclass name to your own so the NSDocumentController knows what class to use.


问:
React-Native: components only working properly on the last tab loaded in when using react-native-navigation or react-navigation
I have a very simple two tab app:

```<code>import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { TabNavigator } from 'react-navigation';

import {
  Sports,
  News,
} from 'externalComponents';

const MyApp = TabNavigator({
  Sports: { screen: Sports },
  News: { screen: News },
});

AppRegistry.registerComponent('MyApp', () => MyApp);
</code>```

The Sports and News components are provided by another company, and I cannot edit that code. If I load this into a TabBarIOS component, everything works fine and all tabs work as intended. However, with react-native-navigation and react-navigation, only the last tab loaded works properly.

Both the News and Sports components load a JSONDownloadService component like this:

```<code>downloadService = new JSONDownloadService(this);
</code>```

And then it calls this:

```<code>downloadService.getJSON(this.state.url, type)
</code>```

Now in JSONDownloadService because it has been passed the NEWS or SPORTS component in its constructor, it gets passed updateComponent (the part that is not getting called correctly). The getJSON() looks something like this:

```<code>getJSON(url, type) {
  //set up vars...
    fetch(request, init)
        .then(function (response) {
          // ...some code
        })
        .then(function (response) {
            if (response) {
                try {
                 // supposed to call `updateComponent` in News & Sports:
                    callback.updateComponent(response, type);
                }
                catch (err) {
                    console.log(err);
                }
            }
        })
        .catch(function (error) {
            console.error(error);
        });
}
</code>```

The trouble is, updateComponent() is only ever called by the last component loaded in the tabBar. If I switch their positions, only the last one ever works. Except, if I comment out the code relating to JSONDownloadService in the last tab, THEN the first one works fine. It seems that whichever component last uses it prevents the rest from updating. How can I make this work using react-native-navigation or react-navigation?

Thanks in advance for any help!

答:
It turns out, the reason TabBarIOS worked and react-navigation and react-native-navigation didn't was because the latter two load all the tabs at once. In this case it overloaded the JSONDownloadService component.

I was able to fix it in react-navigation at least using this code:

```<code>const MyApp = TabNavigator({
  Sports: { screen: Sports },
  News: { screen: News },
}, {
  lazy: true, //used to be called "lazyLoad"
});
</code>```

it just causes the app to lazily load the content for each tab.

Body:
I have a very simple two tab app:

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { TabNavigator } from 'react-navigation';

import {
  Sports,
  News,
} from 'externalComponents';

const MyApp = TabNavigator({
  Sports: { screen: Sports },
  News: { screen: News },
});

AppRegistry.registerComponent('MyApp', () => MyApp);

The Sports and News components are provided by another company, and I cannot edit that code. If I load this into a TabBarIOS component, everything works fine and all tabs work as intended. However, with react-native-navigation and react-navigation, only the last tab loaded works properly.

Both the News and Sports components load a JSONDownloadService component like this:

downloadService = new JSONDownloadService(this);

And then it calls this:

downloadService.getJSON(this.state.url, type)

Now in JSONDownloadService because it has been passed the NEWS or SPORTS component in its constructor, it gets passed updateComponent (the part that is not getting called correctly). The getJSON() looks something like this:

getJSON(url, type) {
  //set up vars...
    fetch(request, init)
        .then(function (response) {
          // ...some code
        })
        .then(function (response) {
            if (response) {
                try {
                 // supposed to call `updateComponent` in News & Sports:
                    callback.updateComponent(response, type);
                }
                catch (err) {
                    console.log(err);
                }
            }
        })
        .catch(function (error) {
            console.error(error);
        });
}

The trouble is, updateComponent() is only ever called by the last component loaded in the tabBar. If I switch their positions, only the last one ever works. Except, if I comment out the code relating to JSONDownloadService in the last tab, THEN the first one works fine. It seems that whichever component last uses it prevents the rest from updating. How can I make this work using react-native-navigation or react-navigation?

Thanks in advance for any help!

Body:
It turns out, the reason TabBarIOS worked and react-navigation and react-native-navigation didn't was because the latter two load all the tabs at once. In this case it overloaded the JSONDownloadService component.

I was able to fix it in react-navigation at least using this code:

const MyApp = TabNavigator({
  Sports: { screen: Sports },
  News: { screen: News },
}, {
  lazy: true, //used to be called "lazyLoad"
});

it just causes the app to lazily load the content for each tab.


问:
Invalid token format error on use Telegram.bot
I use this code for send a message.

```<code>var bot = new Telegram.Bot.Api("3bd8d2839afbb0ba2c0067578b7b0bc2");
var t = bot.SendTextMessage("@chanelName", "Hi ! Admin ");
</code>```

but get me error:

Invalid token format

App api_hash = 3bd8d2839afbb0ba2c0067578b7b0bc2

答:
your bot token is not valid.
if you didn't have your token just get it from bot father and put in your API object.
you don't need api_hash all you need is your bot token.

Body:
I use this code for send a message.

var bot = new Telegram.Bot.Api("3bd8d2839afbb0ba2c0067578b7b0bc2");
var t = bot.SendTextMessage("@chanelName", "Hi ! Admin ");

but get me error:

Invalid token format

App api_hash = 3bd8d2839afbb0ba2c0067578b7b0bc2


问:
how can i split a string if there is a period and then a space?
Right now I am using .split(/(?<=[.])/) which splits keeps the period.

```<code>string = "Going home. See you soon."
</code>```

=> ["Going home.", "See you soon."]

But what I need is to split on and keep ". "

答:
If it is that straight forward, why you need a regex, just provide the string to split on as</p>

```<code>"Going home. See you soon.".split('. ').map{ |s| "#{s}." }
</code>```

Body:
Right now I am using .split(/(?<=[.])/) which splits keeps the period.

string = "Going home. See you soon."

=> ["Going home.", "See you soon."]

But what I need is to split on and keep ". "

Body:
If it is that straight forward, why you need a regex, just provide the string to split on as

"Going home. See you soon.".split('. ').map{ |s| "#{s}." }


问:
Convert String to Array of Integers in Swift 3?
I'm trying to write an array of numbers in a file. After reading it, the result is a string, I'm wondering how to read an array of numbers or transform the string into array of numbers?

```<code>let file = "sample.txt"
var arr1 = [Int]()
arr1 += 1...100
var text = String(describing: arr1)
var text1 : String = String()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    let path = dir.appendingPathComponent(file)

    // writing
    do {
        try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        text1 = try String(contentsOf: path, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}
}
</code>```

Now the question is how can I transform text1 into an array of numbers?

答:
The question is: if you want to save an array of Int why do write and read a String?

The easiest way to save an array of Int is the property list format.

Although the recommended way in Swift is the PropertyListSerialization class this writes and reads an array of Int by bridging the Swift Array to NSArray.

```<code>let file = "sample.plist"
let arrayToWrite = [Int](1...100)
var arrayToRead = [Int]()

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let url = dir.appendingPathComponent(file)

    // writing

    (arrayToWrite as NSArray).write(to: url, atomically: false)

    //reading

    arrayToRead = NSArray(contentsOf: url) as! [Int]
    print(arrayToRead)
}
</code>```

The swiftier way using PropertyListSerialization is

```<code>// writing

do {
    let data = try PropertyListSerialization.data(fromPropertyList: arrayToWrite, format: .binary, options: 0)
    try data.write(to: url, options: .atomic)
}
catch { print(error) }

//reading

do {
    let data = try Data(contentsOf: url)
    arrayToRead = try PropertyListSerialization.propertyList(from: data, format: nil) as! [Int]

    print(arrayToRead)
}
catch { print(error) }
</code>```

Body:
I'm trying to write an array of numbers in a file. After reading it, the result is a string, I'm wondering how to read an array of numbers or transform the string into array of numbers?

let file = "sample.txt"
var arr1 = [Int]()
arr1 += 1...100
var text = String(describing: arr1)
var text1 : String = String()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    let path = dir.appendingPathComponent(file)

    // writing
    do {
        try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        text1 = try String(contentsOf: path, encoding: String.Encoding.utf8)
    }
    catch {/* error handling here */}
}

Now the question is how can I transform text1 into an array of numbers?

Body:
The question is: if you want to save an array of Int why do write and read a String?

The easiest way to save an array of Int is the property list format.

Although the recommended way in Swift is the PropertyListSerialization class this writes and reads an array of Int by bridging the Swift Array to NSArray.

let file = "sample.plist"
let arrayToWrite = [Int](1...100)
var arrayToRead = [Int]()

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

    let url = dir.appendingPathComponent(file)

    // writing

    (arrayToWrite as NSArray).write(to: url, atomically: false)

    //reading

    arrayToRead = NSArray(contentsOf: url) as! [Int]
    print(arrayToRead)
}

The swiftier way using PropertyListSerialization is

// writing

do {
    let data = try PropertyListSerialization.data(fromPropertyList: arrayToWrite, format: .binary, options: 0)
    try data.write(to: url, options: .atomic)
}
catch { print(error) }

//reading

do {
    let data = try Data(contentsOf: url)
    arrayToRead = try PropertyListSerialization.propertyList(from: data, format: nil) as! [Int]

    print(arrayToRead)
}
catch { print(error) }


问:
Updating state from child component reactjs
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

```<code><SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>
</code>```

Child Component

```<code>handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}
</code>```

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

```<code><SelectWarehouse
  updateTarget={ warehouseId }
/>
</code>```

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.

答:
The simple answer to your question will be No. But why?

What you are asking is very similar to the two-way binding concept which is supported in frameworks like Angular and Vue.js. That means data will flow in and out from the child component to parent component with one binding. React doesn't support this and highly discourage using this approach. It always prefers unidirectional data flow.

So with React, you can send your data from top to bottom of the component tree easily using props. But if you want reverse redirection, from bottom to top, the only option you have is callbacks. You can pass a callback as a prop to your child component and it will invoke the callback with the relevant data when the data is ready. Sometimes, this is hard when we need communication between deeply nested components. So that's where you need to use a state management library like Redux or React context which is discouraged to use if you aren't an experienced developer.

To understand it better I suggest you to read Thinking in React section from React official docs. They believe this approach make it easy to understand how a program works than magical two-way binding.

React makes this data flow explicit to make it easy to understand how
  your program works, but it does require a little more typing than
  traditional two-way data binding.

Also,

Though this sounds complex, it's really just a few lines of code. And
  it's really explicit how your data is flowing throughout the app.

In your case, probably you have to live with it, refactor to a different format which suggested by other answers or use a third party library like react-binding(I haven't used it, so can't recommend).

Body:
I am trying to refactor component elegantly so we can easily use the component for same usecase.

I have two component,

NewPurchaseOrder (parent comp.)

SelectWarehouse (child comp.)

SelectWarehouse component would render the dropdown list of available warehouses in NewPurchaseOrder component.

The parent component has one state warehouseId to track selected warehouse, to update the parent components state (warehouseId) from the child component i am doing this,

Parent Component

<SelectWarehouse
  updateTarget={ ( ghostValue ) => {
    this.setState( {
      warehouseId: ghostValue // updating the state from child comp. value
    }, () => {
      console.log( 'yokygoky', this.state.warehouseId )
    } )
  } }
/>

Child Component

handleChangeWarehouse( e ) {
  this.setState( {
    selectedWarehouse: e.target.value
  }, () => {
    this.props.updateTarget( e.target.value ) // Updating the parent props
  } )
}

Now what i am trying to do, is to send only the state name from the parent instead of sending a function and then update that state of parent component from the child component.
It would look something like this,

<SelectWarehouse
  updateTarget={ warehouseId }
/>

And then update the warehouseId from the child component.

Is it possible?

I have tested it by only sending the state with no luck, also its not possible to bind this context with only a simple state.


问:
How to convert binary to decimal using BigInteger?
I am trying to print decimal number from binary number using BigInteger class.
I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error?
The code is as follows:</p>

```<code>System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);
</code>```

答:
If you are trying to parse the input String as a binary, you should write:

```<code>BigInteger i=new BigInteger(s,2);
</code>```

When you print it

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

it will be displayed in decimal by default.

It doesn't make sense, however, to read the number as int and then convert to String and pass to BigInteger constructor, since that limits the range of numbers that would work.

try:

```<code>s = sc.nextLine();
BigInteger i=new BigInteger(s,2);
System.out.println(i);
</code>```

Body:
I am trying to print decimal number from binary number using BigInteger class.
I am using BigInteger(String val, int radix) constructor of BigInteger class to convert given binary value to decimal but it is printing the exact binary value which is passed in constructor.Waht is the error?
The code is as follows:

System.out.print("Ente the decimal number:");
s=String.valueOf(sc.nextInt());

BigInteger i=new BigInteger(s,10);
System.out.println(i);

Body:
If you are trying to parse the input String as a binary, you should write:

BigInteger i=new BigInteger(s,2);

When you print it

System.out.println(i);

it will be displayed in decimal by default.

It doesn't make sense, however, to read the number as int and then convert to String and pass to BigInteger constructor, since that limits the range of numbers that would work.

try:

s = sc.nextLine();
BigInteger i=new BigInteger(s,2);
System.out.println(i);


问:
Codeigniter form validation many conditions in checking duplicate
Is there a way in codeigniter form validation library to determine a duplicate entry of a persons data if i considered a condition like this:
First Name, Middle Name, Last name, Birth Date is matched in db.

For example i need to check if this person is already exist if the data is matched from the DB considered the-same: First Name,Middle Name, Last name, and Birthdate.

I cannot use is_unique every input type in this situation because what if the person has the same First Name, Last Name and Middle name but the birthdate is different. How can i make a form validation like this in codeigniter?.

Something a query like this:

```<code>SELECT COUNT(patient_id) AS patient_id FROM patients WHERE patients.firstname = "" AND patients.middlename = "" AND patients.lastname = "" AND patients.birthdate = ""
</code>```

if the query results greater than 1 , then it is considered a duplicate entry. how can i do that in codeigniter form validation?

Here is my code in Controller:

```<code>public function addpatient() {

         $this->form_validation->set_rules('pafname', 'pafname', 'trim|required',
            array('required' => 'First name is required')
            );

          $this->form_validation->set_rules('pamname', 'pamname', 'trim|required',
            array('required' => 'Middle name is required')
            );

          $this->form_validation->set_rules('palname', 'palname', 'trim|required',
            array('required' => 'Last name is required')
            );

          $this->form_validation->set_rules('paaddress', 'paaddress', 'trim|required',
            array('required' => 'Address is required')
            );

          $this->form_validation->set_rules('pacontact', 'pacontact', 'trim|required',
            array('required' => 'Contact # is required')
            );

          $this->form_validation->set_rules('pabdate', 'pabdate', 'trim|required',
            array('required' => 'Birthdate is required')
            );

          $this->form_validation->set_rules('psex', 'psex', 'trim|required',
            array('required' => 'Gender is required')
            );

          $this->form_validation->set_rules('pmartialstat', 'pmartialstat', 'trim|required',
            array('required' => 'Martial status is required')
            );

            if ($this->form_validation->run() == TRUE) {

                    $result['status'] = true;
                    $result['message'] = "This patient has no duplicate";
            }else {
                $result['status'] = false;

                $result['message'] = $this->form_validation->error_array();
            }
            echo json_encode($result);
    }
</code>```

答:
Create your own custom validation method. In the custom validation method call the SQL to see if there is a record where all the fields match and return back TRUE/FALSE based off the match.

Something like:

```<code>$this->form_validation->set_rules('pafname', 'pafname', 'trim|required|callback__duplicate_validation',
        array('required' => 'First name is required',
              'callback__duplicate_validation' => 'Duplicate record')
        );

function _duplicate_validation($pafname) {
    // Get _POST data for all fields since only pafname is passed in
    // Call SQL to see if duplicate
    // if duplicate, return FALSE
    // else return TRUE
}
</code>```

Body:
Is there a way in codeigniter form validation library to determine a duplicate entry of a persons data if i considered a condition like this:
First Name, Middle Name, Last name, Birth Date is matched in db.

For example i need to check if this person is already exist if the data is matched from the DB considered the-same: First Name,Middle Name, Last name, and Birthdate.

I cannot use is_unique every input type in this situation because what if the person has the same First Name, Last Name and Middle name but the birthdate is different. How can i make a form validation like this in codeigniter?.

Something a query like this:

SELECT COUNT(patient_id) AS patient_id FROM patients WHERE patients.firstname = "" AND patients.middlename = "" AND patients.lastname = "" AND patients.birthdate = ""

if the query results greater than 1 , then it is considered a duplicate entry. how can i do that in codeigniter form validation?

Here is my code in Controller:

public function addpatient() {

         $this->form_validation->set_rules('pafname', 'pafname', 'trim|required',
            array('required' => 'First name is required')
            );

          $this->form_validation->set_rules('pamname', 'pamname', 'trim|required',
            array('required' => 'Middle name is required')
            );

          $this->form_validation->set_rules('palname', 'palname', 'trim|required',
            array('required' => 'Last name is required')
            );

          $this->form_validation->set_rules('paaddress', 'paaddress', 'trim|required',
            array('required' => 'Address is required')
            );

          $this->form_validation->set_rules('pacontact', 'pacontact', 'trim|required',
            array('required' => 'Contact # is required')
            );

          $this->form_validation->set_rules('pabdate', 'pabdate', 'trim|required',
            array('required' => 'Birthdate is required')
            );

          $this->form_validation->set_rules('psex', 'psex', 'trim|required',
            array('required' => 'Gender is required')
            );

          $this->form_validation->set_rules('pmartialstat', 'pmartialstat', 'trim|required',
            array('required' => 'Martial status is required')
            );

            if ($this->form_validation->run() == TRUE) {

                    $result['status'] = true;
                    $result['message'] = "This patient has no duplicate";
            }else {
                $result['status'] = false;

                $result['message'] = $this->form_validation->error_array();
            }
            echo json_encode($result);
    }

Body:
Create your own custom validation method. In the custom validation method call the SQL to see if there is a record where all the fields match and return back TRUE/FALSE based off the match.

Something like:

$this->form_validation->set_rules('pafname', 'pafname', 'trim|required|callback__duplicate_validation',
        array('required' => 'First name is required',
              'callback__duplicate_validation' => 'Duplicate record')
        );

function _duplicate_validation($pafname) {
    // Get _POST data for all fields since only pafname is passed in
    // Call SQL to see if duplicate
    // if duplicate, return FALSE
    // else return TRUE
}


问:
How to load a menu module in header and footer in joomla?
I have attached joomla's Menu module in my template. But I needed it to load in footer position at the same time. So that if I add another menu it should be get added in both the positions in Header and in the footer... What i want to do to load a menu module to two different positions in a page, in header and in footer.

I had tried to add multiple positions in administrator section for a menu module...

screen shots are as follows

答:
For latest version. Joomla3.x :
Get all the modules by template position(replace position with your template position):

```<code><?php
$modules  = JModuleHelper::getModules("position");
$document = JFactory::getDocument();
$attribs  = array();
$attribs['style'] = 'xhtml';
foreach ($modules as $mod) {
  echo JModuleHelper::renderModule($mod, $attribs);
}
?>
</code>```

Other Solution: you can define position in the template and assign module to that position

Steps:
1.Customize templateDetails.xml file
add
newposition

2.create position in index file of template
in templates/your_template/index.php

```<code><jdoc:include type="modules" name="newposition"   />
</code>```

Body:
For latest version. Joomla3.x :
Get all the modules by template position(replace position with your template position):

<?php
$modules  = JModuleHelper::getModules("position");
$document = JFactory::getDocument();
$attribs  = array();
$attribs['style'] = 'xhtml';
foreach ($modules as $mod) {
  echo JModuleHelper::renderModule($mod, $attribs);
}
?>

Other Solution: you can define position in the template and assign module to that position

Steps:
1.Customize templateDetails.xml file
add
newposition

2.create position in index file of template
in templates/your_template/index.php

<jdoc:include type="modules" name="newposition"   />


问:
I want the hyperlink to be in a different place
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
 </tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
 </tr>
 </table>
 <a href="http://www.google.com">Visit Google!</a>
</body>
</html>
</code>```

答:
```<code>body {
  margin: auto;
}
</code>```

Body:
I am looking to put the hyperlink in a different place. How can I move the google.com link to another place on the page?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

 Visit Google!

Body:
body {
  margin: auto;
}


问:
How to deseralize an XML thats a DataTable?
I have an XML file, and when I used XSD tool to create a class object from the XML, I get a message saying "A column named 'link' already belongs to this DataTable: cannot set a nested table to the same name.

I want to know how I can correctly deserialize this XML file so that I can display the data on an app. This XML file is basically just Rss news feed data.

You can see the entire XML file structure here: https://github.com/karimo94/XMLDemo/blob/master/leaguenews.xml

答:
Look at this design

https://blogs.windows.com/buildingapps/2017/05/01/master-master-detail-pattern/#.WSrAkFuGID4.twitter#7gkbxLDhEVrcmL6M.97

```<code>DataSet ds = new DataSet();
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
        FileStream readStream = new FileStream("leaguenews.xml", FileMode.Open);
        ds = (DataSet)xmlSerializer.Deserialize(readStream);
        readStream.Close();
        dataGridView1.DataSource = ds.Tables[0];
</code>```

Body:
Look at this design

https://blogs.windows.com/buildingapps/2017/05/01/master-master-detail-pattern/#.WSrAkFuGID4.twitter#7gkbxLDhEVrcmL6M.97

DataSet ds = new DataSet();
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
        FileStream readStream = new FileStream("leaguenews.xml", FileMode.Open);
        ds = (DataSet)xmlSerializer.Deserialize(readStream);
        readStream.Close();
        dataGridView1.DataSource = ds.Tables[0];


问:
Meteor collection observe change
The following code fires a client side when a certain info is populated in a collection. sometimes it does not work on smartphone but works fine on desktop Chrome.

Is it correct to call the find and findOne on the collection? not an over kill?  thx

```<code>  'myMethod': function (age, health) {
    Meteor.call('doStuff-that-will-change-the-document');
    myCollection.find().observeChanges({   // <===== find
      changed: function (id, fields) {
        let newDoc = myCollection.findOne({age: age});  // <==== another findOne
        Meteor.users.update({_id: Meteor.user()._id}, {$unset: {'profile.taskInProgress': ''}});
        if (newDoc) {
          if (fields.filed1) {
            lib.dothis1(newDoc, health);
          } else if (fields.field2) {
            lib.dothat(newDoc, health);
          }
        }
      }
    });
  },
</code>```

edit

I need the client code to fire lib.dothis1 or lib.dothat when the field1 and field2 get updated respectively.

答:
If you want to catch what was added, just use the added property - see the docs

Establishes a live query that invokes callbacks when the result of the query changes. In contrast to observe, observeChanges provides only the difference between the old and new result set, not the entire contents of the document that changed.

callbacks may have the following functions as properties:

```<code>added(id, fields) or
</code>```

A new document entered the result set. It has the id and fields
  specified. fields contains all fields of the document excluding the
  _id field. The new document is before the document identified by before, or at the end if before is null.

Than you get a new callback when a new doc is added, which would be more efficient than using find again.

Title: Meteor collection observe change

Body:
The following code fires a client side when a certain info is populated in a collection. sometimes it does not work on smartphone but works fine on desktop Chrome.

Is it correct to call the find and findOne on the collection? not an over kill?  thx

  'myMethod': function (age, health) {
    Meteor.call('doStuff-that-will-change-the-document');
    myCollection.find().observeChanges({   // <===== find
      changed: function (id, fields) {
        let newDoc = myCollection.findOne({age: age});  // <==== another findOne
        Meteor.users.update({_id: Meteor.user()._id}, {$unset: {'profile.taskInProgress': ''}});
        if (newDoc) {
          if (fields.filed1) {
            lib.dothis1(newDoc, health);
          } else if (fields.field2) {
            lib.dothat(newDoc, health);
          }
        }
      }
    });
  },

edit

I need the client code to fire lib.dothis1 or lib.dothat when the field1 and field2 get updated respectively.

Body:
If you want to catch what was added, just use the added property - see the docs

Establishes a live query that invokes callbacks when the result of the query changes. In contrast to observe, observeChanges provides only the difference between the old and new result set, not the entire contents of the document that changed.

callbacks may have the following functions as properties:

added(id, fields) or

A new document entered the result set. It has the id and fields
  specified. fields contains all fields of the document excluding the
  _id field. The new document is before the document identified by before, or at the end if before is null.

Than you get a new callback when a new doc is added, which would be more efficient than using find again.


问:
How can I extract a short part of characters from the string with Regular Expression in Python?
Here is my code:

```<code>s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())
</code>```

and I got the result:

```<code>wish I may, I wish I m
</code>```

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

答:
What are you trying to accomplish here? Your regular expression means it will match any of the following

```<code>'w.*m' will match:
'well my cat is married' -> 'well my cat is m'
'willy wonka had a wonky moped' -> 'willy wonka had a wonky m'
</code>```

You are pretty much saying it should match any phrase that starts with w and ends with m.

wish i m appears twice in the phrase as highlighted below

"I wish I may, I wish I might
Have a dish of fish tonight."

So if that's the phrase you are looking for, your result should be wish I m, wish I m. For that result you'd need this pattern - w[\w\s]*m.  So instead of a greedy .* you are limiting the matched characters to words \w and spaces \s which is all that is in will I m.

Again, it depends on what you are looking for.

```<code>In [1]: import re
In [4]: x = 'I wish I may, I wish I might Have a dish of fish tonight'
In [5]: re.findall(r'w[\w\s]*m', x)
Out[5]: ['wish I m', 'wish I m']
</code>```

Body:
Here is my code:

s = '''I wish I may, I wish I might
Have a dish of fish tonight.'''

import re
m = re.search('w.*m', s)
print(m.group())

and I got the result:

wish I may, I wish I m

If I want to get the result only the first half wish I m, how can I revise my code?

Thanks a lot!

Body:
What are you trying to accomplish here? Your regular expression means it will match any of the following

'w.*m' will match:
'well my cat is married' -> 'well my cat is m'
'willy wonka had a wonky moped' -> 'willy wonka had a wonky m'

You are pretty much saying it should match any phrase that starts with w and ends with m.

wish i m appears twice in the phrase as highlighted below

"I wish I may, I wish I might
Have a dish of fish tonight."

So if that's the phrase you are looking for, your result should be wish I m, wish I m. For that result you'd need this pattern - w[\w\s]*m.  So instead of a greedy .* you are limiting the matched characters to words \w and spaces \s which is all that is in will I m.

Again, it depends on what you are looking for.

In [1]: import re
In [4]: x = 'I wish I may, I wish I might Have a dish of fish tonight'
In [5]: re.findall(r'w[\w\s]*m', x)
Out[5]: ['wish I m', 'wish I m']