问:
Is it ok to register uitableviewcell in cellForRowAt.
Is it ok to register uitableviewcell in cellForRowAt. Before register i will check weather that cell is register or not by dequeue and nil check. Beacuse the tableview I m using its for genreic use across app and will not be sure about kind of cell will be needed.</p>

```<code>var cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!
        if cell == nil {
            tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);
            cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!;
        }
        return cell!;
</code>```

答:
No it's bad.It will register multiple times  because cellForRow atIndex will call several times based on your row counts & will call if you scrolled your tableView.

So i think better to register UITableViewCell in viewDidLoad method once.

```<code>  tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);
</code>```

Body:
Is it ok to register uitableviewcell in cellForRowAt. Before register i will check weather that cell is register or not by dequeue and nil check. Beacuse the tableview I m using its for genreic use across app and will not be sure about kind of cell will be needed.

var cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!
        if cell == nil {
            tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);
            cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!;
        }
        return cell!;

Body:
No it's bad.It will register multiple times  because cellForRow atIndex will call several times based on your row counts & will call if you scrolled your tableView.

So i think better to register UITableViewCell in viewDidLoad method once.

  tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);


来源: stackexchange

问:
javascript merge array of objects, resulting object values in array
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

```<code>[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]
</code>```

to this:

```<code>{
  a: [1, 1],
  b: [2],
  c: [3]
}
</code>```

答:
You can use _.mergeWith() with the spread syntax to combine the objects:

const data = [{"a":1,"b":2},{"a":1,"c":3}];

const result = _.mergeWith({}, ...data, (v1 = [], v2) => [...v1, v2]);

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]

to this:

{
  a: [1, 1],
  b: [2],
  c: [3]
}

Body:
You can use _.mergeWith() with the spread syntax to combine the objects:

const data = [{"a":1,"b":2},{"a":1,"c":3}];

const result = _.mergeWith({}, ...data, (v1 = [], v2) => [...v1, v2]);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

ContentLicense: CC BY-SA 4.0


问:
Graphical bug NSVisualEffectView when app in background
My application has a NSTableView configured as a SourceList.
Under the NSTableView are two NSButton two add/remove items in the table.
The table and the buttons are embedded in a NSVisualEffectView (.behindWindow mode).

The result is great and I can see the background through the table and the buttons, BUT, when the app is in background (I give the focus to another app), the tableview and the buttons become black, and the view is not redrawn, as shown in the picture below (taken with an iPhone, because a screenshot does not show the bug!):

And here is the IB structure of the views:

The container view (CustomView) is layer-backed.

Any lead to solve this problem? Thanks in advance !

答:
The problem was that I was trying to have a NSOutlineView translucent (Behind-window blending), but under a TabView.

Apple UI guidelines (here) state the following:

Use an opaque background when a window contains more than one sidebar, and when using a sidebar in a panel or preferences window. All other times, use a translucent background.

Because of the TabView, I was clearly against this rule which had technical side effects (which led to this post :-)).

--> making the NSOutlineView opaque (not as a SourceList) solved the problem.


问:
Cannot change the background image while the radio button is hovered
I wrote a radio list with image animate. When it was hovered and checked, it can change to another image.
it's works on all of the browsers but on IE its not work when I hover on it.
I don't know if I wrote some css wrong or miss something about ie issue?
the html is:

```<code><ul>
<li>
<input type="radio" id="f-option" name="gender">
<label for="f-option" class="gender female"><img src="images/52x42.png"></label>
<div class="check"></div>
</li>
</ul>
</code>```

and my css is:

```<code>.user-form ul li label.gender.female {
background-image: url(../images/female.png);
}

.user-form input[type=radio]:checked ~ label.gender.female,
.user-form input[type=radio]:hover ~ label.gender.female {
background-image: url(../images/female-checked.png);
}
</code>```

its works all of the browser but not work on ie
can anybody help me fix it?

The online demo is in this bottom of page:
http://bestinthink.com/wg/buy-p1.html

答:
Your example works in modern browsers because they treat hovering over your label element as though you are hovering over the radio element itself, even though the radio element is set to visibility:hidden. IE doesn't behave that way. You have to explicitly hover over the radio element — which you can't do because you've hidden it — to see your input[type=radio]:hover styles.

I suggest changing the background-image on label:hover rather than input[type=radio]:hover. The below code might work for you.

```<code>.user-form input[type=radio]:checked ~ label.gender.female,
.user-form label.gender.female:hover {
   background-image: url(../images/female-checked.png);
}
</code>```

Use it and let me know how it goes.☺

I'll update if I find a less hacky solution.

Body:
I wrote a radio list with image animate. When it was hovered and checked, it can change to another image.
it's works on all of the browsers but on IE its not work when I hover on it.
I don't know if I wrote some css wrong or miss something about ie issue?
the html is:

<input type="radio" id="f-option" name="gender">

and my css is:

.user-form ul li label.gender.female {
background-image: url(../images/female.png);
}

.user-form input[type=radio]:checked ~ label.gender.female,
.user-form input[type=radio]:hover ~ label.gender.female {
background-image: url(../images/female-checked.png);
}

its works all of the browser but not work on ie
can anybody help me fix it?

The online demo is in this bottom of page:
http://bestinthink.com/wg/buy-p1.html

Body:
Your example works in modern browsers because they treat hovering over your label element as though you are hovering over the radio element itself, even though the radio element is set to visibility:hidden. IE doesn't behave that way. You have to explicitly hover over the radio element — which you can't do because you've hidden it — to see your input[type=radio]:hover styles.

I suggest changing the background-image on label:hover rather than input[type=radio]:hover. The below code might work for you.

.user-form input[type=radio]:checked ~ label.gender.female,
.user-form label.gender.female:hover {
   background-image: url(../images/female-checked.png);
}

Use it and let me know how it goes.☺

I'll update if I find a less hacky solution.


问:
How to replace a html tag with nsattribute in swift?
For eg. replace a  tag with bold font. So that it can be applied as attributed text to label, textfield or textview

答:
```<code>extension NSAttributedString {

    func replaceHTMLTag(tag: String, withAttributes attributes: [String: AnyObject]) -> NSAttributedString {
        let openTag = "<\(tag)>"
        let closeTag = "</\(tag)>"

        let resultingText: NSMutableAttributedString = self.mutableCopy() as! NSMutableAttributedString
        while true {
            let plainString = resultingText.string as NSString
            let openTagRange = plainString.range(of: openTag)
            if openTagRange.length == 0 {
                break
            }

            let affectedLocation = openTagRange.location + openTagRange.length

            let searchRange = NSRange(location: affectedLocation, length: plainString.length - affectedLocation)

            let closeTagRange = plainString.range(of: closeTag, options: NSString.CompareOptions.init(rawValue: 0), range: searchRange)

            resultingText.setAttributes(attributes, range: NSRange(location: affectedLocation, length: closeTagRange.location - affectedLocation))
            resultingText.deleteCharacters(in: closeTagRange)
            resultingText.deleteCharacters(in: openTagRange)
        }
        return resultingText as NSAttributedString
    }
}
</code>```


问:
Getting the current logged in user (FullToken Context)
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

```<code>WindowsIdentity.GetCurrent().Name;
</code>```

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

答:
You could try using WMI (System.Management.dll) to get the owner of the explorer.exe process.

```<code>string GetExplorerUser()
{
    var query = new ObjectQuery(
        "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");

    var explorerProcesses = new ManagementObjectSearcher(query).Get();

    foreach (ManagementObject mo in explorerProcesses)
    {
        string[] ownerInfo = new string[2];
        mo.InvokeMethod("GetOwner", (object[])ownerInfo);

        return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
    }

    return string.Empty;
}
</code>```

This relies on the fact that the explorer process is single instance an so you don't end up with the possibility of having several explorer processes running with different user credentials.

ContentLicense: CC BY-SA 2.5

Body:
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

WindowsIdentity.GetCurrent().Name;

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

Body:
You could try using WMI (System.Management.dll) to get the owner of the explorer.exe process.

string GetExplorerUser()
{
    var query = new ObjectQuery(
        "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");

    var explorerProcesses = new ManagementObjectSearcher(query).Get();

    foreach (ManagementObject mo in explorerProcesses)
    {
        string[] ownerInfo = new string[2];
        mo.InvokeMethod("GetOwner", (object[])ownerInfo);

        return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
    }

    return string.Empty;
}

This relies on the fact that the explorer process is single instance an so you don't end up with the possibility of having several explorer processes running with different user credentials.


问:
Formatting arrays specifically in PHP
I have the following PHP code on my website:

```<code><?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>
</code>```

And I want it to be output like so:

```<code>("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)
</code>```

for an SQL string, which will be:

```<code>INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);
</code>```

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

答:
Simply, If you have same count of  $FirstName, $LastName and $BirthDay,

using for loop and array_push you can do it like this:

```<code>$data = array();
$count = count($FirstName);

for($i = 0; $i < $count; $i++ ){

    $insert = [$FirstName[$i],$LastName[$i], $BirthDay[$i]];
    array_push($data,$insert);

}
</code>```

The $data gives you formatted array.

Title: Formatting arrays specifically in PHP

Body:
I have the following PHP code on my website:

<?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>

And I want it to be output like so:

("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)

for an SQL string, which will be:

INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

Body:
Simply, If you have same count of  $FirstName, $LastName and $BirthDay,

using for loop and array_push you can do it like this:

$data = array();
$count = count($FirstName);

for($i = 0; $i < $count; $i++ ){

    $insert = [$FirstName[$i],$LastName[$i], $BirthDay[$i]];
    array_push($data,$insert);

}

The $data gives you formatted array.


问:
MultipleApiVersions not working in OWIN
I am struggling to get Swagger to document multi-tenanted routes in WebApi.I have used this approach before but never in a self-hosted project. It seems MultipleApiVersions is never invoked - when i've added logging code.

StatupConfig.cs

```<code> public class StartupConfig
    {
        private static ILog _logger = LogManager.GetLogger(nameof(StartupConfig));

        public void Configure(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            config.Filters.Add(new ApiKeyAuthorizationFilter());
            config.Filters.Add(new ApiInvocationMetricsFilter());

            var assembly = Assembly.GetExecutingAssembly();
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(assembly);
            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            appBuilder.UseAutofacMiddleware(container);
            appBuilder.UseAutofacWebApi(config);
            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            appBuilder.UseWebApi(config);

            config
             .EnableSwagger(c =>
                {
                   c.MultipleApiVersions(
                          ResolveVersionSupportByRouteConstraint,
                          (vc) =>
                          {
                              vc.Version("v2", "API v2");
                              vc.Version("v1", "API v1");
                          });
                    c.RootUrl((message) => ConfigurationManager.AppSettings["SwaggerRoot"]);
                    c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\API.xml");
                    c.OperationFilter<AddRequiredApiKeyParameter>();
                    c.DescribeAllEnumsAsStrings(true);
                })
             .EnableSwaggerUi(ui =>
                {
                    ui.EnableDiscoveryUrlSelector();
                });
        }

        public static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
        {
            try
            {
                var versionConstraint = (apiDesc.Route.Constraints.ContainsKey("apiVersion"))
                ? apiDesc.Route.Constraints["apiVersion"] as ApiVersionConstraint
                : null;

                return versionConstraint?.AllowedVersion.Split('|').Select(x => x.ToLowerInvariant()).ToList().Contains(targetApiVersion.ToLowerInvariant()) ?? false;
            }
            catch (System.Exception excep)
            {
                _logger.Error("An error occurred resolving version support", excep);
                throw;
            }
        }
    }
</code>```

Note: This predates WebApiVersioning so I am using a route constraint:

```<code>     public class ApiVersion2RoutePrefixAttribute : RoutePrefixAttribute
  {
    private const string RouteBase = "api/{apiVersion:apiVersionConstraint(v2)}";
    private const string PrefixRouteBase = "api/{apiVersion:apiVersionConstraint(v2)}/";

    public ApiVersion2RoutePrefixAttribute(string routePrefix)
      : base(string.IsNullOrWhiteSpace(routePrefix) ? "api/{apiVersion:apiVersionConstraint(v2)}" : "api/{apiVersion:apiVersionConstraint(v2)}/" + routePrefix)
    {
    }
  }
</code>```

Am I missing something here?

Thanks
KH

答:
This problem was solved by ensuring any Name parameters in the Route attribute are unique across both controller versions. I had an operation named Add, with a Route Name parameter of Add across both controllers and this was preventing Swagger from functioning.

i.e this

[Route("", Name = nameof(AddAdvertiser))]

changed to this

[Route("", Name = nameof(V1AddAdvertiser))]

Title: MultipleApiVersions not working in OWIN

Body:
I am struggling to get Swagger to document multi-tenanted routes in WebApi.I have used this approach before but never in a self-hosted project. It seems MultipleApiVersions is never invoked - when i've added logging code.

StatupConfig.cs

 public class StartupConfig
    {
        private static ILog _logger = LogManager.GetLogger(nameof(StartupConfig));

        public void Configure(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            config.Filters.Add(new ApiKeyAuthorizationFilter());
            config.Filters.Add(new ApiInvocationMetricsFilter());

            var assembly = Assembly.GetExecutingAssembly();
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(assembly);
            builder.RegisterWebApiFilterProvider(config);

            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            appBuilder.UseAutofacMiddleware(container);
            appBuilder.UseAutofacWebApi(config);
            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            appBuilder.UseWebApi(config);

            config
             .EnableSwagger(c =>
                {
                   c.MultipleApiVersions(
                          ResolveVersionSupportByRouteConstraint,
                          (vc) =>
                          {
                              vc.Version("v2", "API v2");
                              vc.Version("v1", "API v1");
                          });
                    c.RootUrl((message) => ConfigurationManager.AppSettings["SwaggerRoot"]);
                    c.IncludeXmlComments($@"{System.AppDomain.CurrentDomain.BaseDirectory}\API.xml");
                    c.OperationFilter<AddRequiredApiKeyParameter>();
                    c.DescribeAllEnumsAsStrings(true);
                })
             .EnableSwaggerUi(ui =>
                {
                    ui.EnableDiscoveryUrlSelector();
                });
        }

        public static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
        {
            try
            {
                var versionConstraint = (apiDesc.Route.Constraints.ContainsKey("apiVersion"))
                ? apiDesc.Route.Constraints["apiVersion"] as ApiVersionConstraint
                : null;

                return versionConstraint?.AllowedVersion.Split('|').Select(x => x.ToLowerInvariant()).ToList().Contains(targetApiVersion.ToLowerInvariant()) ?? false;
            }
            catch (System.Exception excep)
            {
                _logger.Error("An error occurred resolving version support", excep);
                throw;
            }
        }
    }

Note: This predates WebApiVersioning so I am using a route constraint:

     public class ApiVersion2RoutePrefixAttribute : RoutePrefixAttribute
  {
    private const string RouteBase = "api/{apiVersion:apiVersionConstraint(v2)}";
    private const string PrefixRouteBase = "api/{apiVersion:apiVersionConstraint(v2)}/";

    public ApiVersion2RoutePrefixAttribute(string routePrefix)
      : base(string.IsNullOrWhiteSpace(routePrefix) ? "api/{apiVersion:apiVersionConstraint(v2)}" : "api/{apiVersion:apiVersionConstraint(v2)}/" + routePrefix)
    {
    }
  }

Am I missing something here?

Thanks
KH


问:
PHP + Mysql : How to insert data having , " ' (Semicolon, Single + Double Quotation Marks)
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

```<code>base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
</code>```

答:
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.

To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.

```<code><?php
// START ESTABLISHING CONNECTION...
 $dsn = 'mysql:host=host_name_here;dbname=db_name_here';
 //DB username
 $uname = 'username_here';
 //DB password
 $pass = 'password_here';

 try
     {

     $db = new PDO($dsn, $uname, $pass);

     $db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
     error_reporting(0);
     } catch (PDOException $ex)
     {
     echo "Database error:" . $ex->getMessage();
     }

// END ESTABLISHING CONNECTION - CONNECTION IS MADE.

 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];
 $hashed_password = password_hash($password, DEFAULT_BCRYPT);

 //Validation on inputs here...

 // Your SQL query... here is a sample one.
 $query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";

 $statement = $db->prepare($query);
 // The values you wish to put in.
 $statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);

 $statement->execute($statementInputs);
 $statement->closeCursor();
?>
</code>```

You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again  to establish a connection to your database.

Body:
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.

Question is simple what is the easiest way to send those sting into the database.

base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.

Body:
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.

To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.

<?php
// START ESTABLISHING CONNECTION...
 $dsn = 'mysql:host=host_name_here;dbname=db_name_here';
 //DB username
 $uname = 'username_here';
 //DB password
 $pass = 'password_here';

 try
     {

     $db = new PDO($dsn, $uname, $pass);

     $db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
     error_reporting(0);
     } catch (PDOException $ex)
     {
     echo "Database error:" . $ex->getMessage();
     }

// END ESTABLISHING CONNECTION - CONNECTION IS MADE.

 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];
 $hashed_password = password_hash($password, DEFAULT_BCRYPT);

 //Validation on inputs here...

 // Your SQL query... here is a sample one.
 $query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";

 $statement = $db->prepare($query);
 // The values you wish to put in.
 $statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);

 $statement->execute($statementInputs);
 $statement->closeCursor();
?>

You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again  to establish a connection to your database.


问:
Using container view with Xamarin and MVVMCross

I am trying to use a Container View within a View Controller (Free Form View) to reuse some components that are common for two views. So far I have a View Controller (Free Form View) with a Ui View and a Container View. Upon opening up the Free Form View, Container View should contain Free Form Purchase View, but when pressing the blue Button, that View should be replaced with the View last View Controller. I have a similar setup for Android where I use Fragments.

I am looking for the best way to navigate between the controllers. I use MVVMCross throughout the application, but I am open to other suggestions that does not involve MVVMCross.

答:
you need to create your own controller which handles swapping of Views in Container View through custom Segue implementation.

You can find detailed step how to do this from Richard Woollcott post: Using the ContainerView to Transition between Views - aka More Fragments in Xamarin.iOS


问:
I need an oracle Sql query to fetch the Product Name, Highest sales of the product in four years and the column name (year)
Table contains, productName, Year2000, Year2001, Year2002 etc. So, productName contains, 1. Milk, 2. Butter, 3. Curd etc, and the Year contains number of product sold like 200, 300 etc.Now I need oracle sql query to find the productName with highest sale in a year along with column name(like, year2000).
Output should be like:
productName: Milk
Year2000: 200

The problem is how to get the particular year column Name like 'Year2002'

答:
I guess this should help you...</p>

```<code>Select product_name, year(date_column), max(sales)
from table_name
group by product_name, year(date_column)
</code>```

Body:
I guess this should help you...

Select product_name, year(date_column), max(sales)
from table_name
group by product_name, year(date_column)


问:
Cannot resolve constructor and method for reason I don't know
```<code>public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
</code>```

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>
</code>```

MainActivity.java

```<code>package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}
</code>```

AndroidManidest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>
</code>```

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

答: Replace this with YourClassName.this then your problem will be solved</p>

Body:
public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>

MainActivity.java

package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}

AndroidManidest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY


问:
Break lines in <input> tag HTML + CSS
I have  tag with type "text", with limit to 2,000 characters.
I want to break lines, but " word-wrap: break-word;" not working because its not a div..

here is the css :

```<code>  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: visible;
  position: relative;
  width: 450px;
  padding-left:5px;
  vertical-align:top;
  box-sizing: border-box;
</code>```

any suggestions ?
thanks

答:
You Cannot change line in input[type="text"] You have to use Textarea or any element with contenteditable="true"

For Example

[contenteditable="true"] {
  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  max-height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: auto;
  position: relative;
  width: 450px;
  padding-left: 5px;
  vertical-align: top;
  box-sizing: border-box;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div contenteditable="true"></div></code>```

Title: Break lines in <input> tag HTML + CSS

Body:
I have  tag with type "text", with limit to 2,000 characters.
I want to break lines, but " word-wrap: break-word;" not working because its not a div..

here is the css :

  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: visible;
  position: relative;
  width: 450px;
  padding-left:5px;
  vertical-align:top;
  box-sizing: border-box;

any suggestions ?
thanks

Body:
You Cannot change line in input[type="text"] You have to use Textarea or any element with contenteditable="true"

For Example

[contenteditable="true"] {
  background: #ffffff;
  -moz-box-sizing: border-box;
  border: 1px solid #CBD5DD;
  border-radius: 2px;
  max-height: 70px;
  max-width: 450px;
  word-wrap: break-word;
  margin: 0;
  min-height: 33px;
  overflow: auto;
  position: relative;
  width: 450px;
  padding-left: 5px;
  vertical-align: top;
  box-sizing: border-box;
}

<div contenteditable="true"></div>


问:
display unique values between two dataframe columns - pyspark
say I have two "ID" columns in 2 dataframes, I want to display ID from DF1 that doesnt exists in DF2

I dont know if I should use join, merge, or isin.

```<code>cond = [df.name != df3.name]
df.join(df3, cond, 'outer').select(df.name, df3.age).collect()
</code>```

not sure if changing the condition will give me the result.

Body:
say I have two "ID" columns in 2 dataframes, I want to display ID from DF1 that doesnt exists in DF2

I dont know if I should use join, merge, or isin.

cond = [df.name != df3.name]
df.join(df3, cond, 'outer').select(df.name, df3.age).collect()

not sure if changing the condition will give me the result.

Body:
In pyspark,you can use leftanti join,

>>> df1 = spark.createDataFrame([(0,'val1'),(1,'val2'),(4,'val4')],['id','val'])
>>> df1.show()
+---+----+
| id| val|
+---+----+
|  0|val1|
|  1|val2|
|  4|val4|
+---+----+

>>> df2 = spark.createDataFrame([(0,'val1'),(1,'val2'),(3,'val3'),(2,'val2')],['id','val'])
>>> df2.show()
+---+----+
| id| val|
+---+----+
|  0|val1|
|  1|val2|
|  3|val3|
|  2|val2|
+---+----+

>>> df1.join(df2,'id','leftanti').show()
+---+----+
| id| val|
+---+----+
|  4|val4|
+---+----+

Similarly,

>>> df2.join(df1,'id','leftanti').show()
+---+----+
| id| val|
+---+----+
|  3|val3|
|  2|val2|
+---+----+


问:
How to save Dataset<Row> in mySQL in spark?
I am using spark standalone cluster in my scenario. I want to read read a JSON file from Azure data lake and using SparkSQL and do some query over it and save the result into a mysql database. I don't know how to do it. A small help will be a great.</p>

```<code>package com.biz.Read_from_ADL;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class App {
    public static void main(String[] args) throws Exception {
        SparkSession spark = SparkSession.builder().appName("Java Spark SQL basic example").getOrCreate();

        Dataset<Row> df = spark.read().json("adl://pare.azuredatalakestore.net/EXCHANGE_DATA/BITFINEX/ETHBTC/MIDPOINT/BITFINEX_ETHBTC_MIDPOINT_2017-06-25.json");

        //df.show();
        df.createOrReplaceTempView("trade");

        Dataset<Row> sqlDF = spark.sql("SELECT * FROM trade");
        sqlDF.show();
    }
}
</code>```

答:
You need to first define the connection properties and jdbc url.

```<code>import java.util.Properties

val connectionProperties = new Properties()
connectionProperties.put("user", "USER_NAME")
connectionProperties.put("password", "PASSWORD")
val jdbc_url = ... // <- use mysql url
import org.apache.spark.sql.SaveMode

spark.sql("select * from diamonds limit 10").withColumnRenamed("table", "table_number")
  .write
  .mode(SaveMode.Append) // <--- Append to the existing table
  .jdbc(jdbc_url, "diamonds_mysql", connectionProperties)
</code>```

Refer here for more detail.

Body:
I am using spark standalone cluster in my scenario. I want to read read a JSON file from Azure data lake and using SparkSQL and do some query over it and save the result into a mysql database. I don't know how to do it. A small help will be a great.

package com.biz.Read_from_ADL;

import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class App {
    public static void main(String[] args) throws Exception {
        SparkSession spark = SparkSession.builder().appName("Java Spark SQL basic example").getOrCreate();

        Dataset<Row> df = spark.read().json("adl://pare.azuredatalakestore.net/EXCHANGE_DATA/BITFINEX/ETHBTC/MIDPOINT/BITFINEX_ETHBTC_MIDPOINT_2017-06-25.json");

        //df.show();
        df.createOrReplaceTempView("trade");

        Dataset<Row> sqlDF = spark.sql("SELECT * FROM trade");
        sqlDF.show();
    }
}

Body:
You need to first define the connection properties and jdbc url.

import java.util.Properties

val connectionProperties = new Properties()
connectionProperties.put("user", "USER_NAME")
connectionProperties.put("password", "PASSWORD")
val jdbc_url = ... // <- use mysql url
import org.apache.spark.sql.SaveMode

spark.sql("select * from diamonds limit 10").withColumnRenamed("table", "table_number")
  .write
  .mode(SaveMode.Append) // <--- Append to the existing table
  .jdbc(jdbc_url, "diamonds_mysql", connectionProperties)

Refer here for more detail.


问:
IntelliJ IDEA Chrome plugin for live update doesn't reload the page
I am used to work on Angular projects where I can simply save my html/css/js change on VS Code and the page reloads automatically with my change. I tried to install the Intellij plugin for live reload, but it doesn't work the same way: nothing is reloaded.

Does anyone know how to fix it?

I've installed both the plugin in my browser and in the IDE.

答:
You need to install JetBrains IDE Support chrome extension:

https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji/related

You also need the LiveEdit plugin for your IDE: go to file -> settings -> plugins -> install jetbrains plugin -> search for "LiveEdit" and install and restart IDE.

Then, from IntelliJ, right click the .html file and choose "debug".

This should open a Chrome window or tab in debugging session, and all changes updated automatically in chrome.

More info: https://www.jetbrains.com/help/idea/live-editing-of-html-css-and-javascript.html#d163908e138


问:
How do I tweak CSS on the Django 1.2.3 admin media?
I would like to make CSS-only adjustments to the admin interface (on an RHEL box I don't have sysadmin privileges to). To that end, I would like a local version of /media/ to tweak.

http://docs.djangoproject.com/en/dev/howto/static-files/ (but not http://docs.djangoproject.com/en/1.2/howto/static-files/) suggests running a manage.py collectstatic or manage.py findstatic, and my Django 1.2.3 manage.py does not recognize those commands. Adding 'django.contrib.staticfiles' to my INSTALLED_APPS also broke things (not found).

I would like to customize the CSS, and the way I envision doing that is by getting a private copy of the media for Django's admin and changing from there. What are my best options for a Django 1.2.3 installation?

答:
Just go to your django installation directory, browser to django->contrib-> admin-> directory and copy paste the media folder to your django projects media directory.

Let us say you have your media in project/media which is statically rendered to web as /media/. If you copy your admin media in project/media your admin media web url would be /media/admin/ hence in your settings.py file: ADMIN_MEDIA_PREFIX = '/media/admin/'

You may then modify your css in media directory as you wish to change the look of admin site.


问:
Is it ok to register uitableviewcell in cellForRowAt.
Is it ok to register uitableviewcell in cellForRowAt. Before register i will check weather that cell is register or not by dequeue and nil check. Beacuse the tableview I m using its for genreic use across app and will not be sure about kind of cell will be needed.</p>

```<code>var cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!
        if cell == nil {
            tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);
            cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!;
        }
        return cell!;
</code>```

答:
No, It is not OK!

Registration of cell into table is one time process.

If you will add register(_, forCellReuseIdentifier: _) to tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) then this registration will be done multiple times causing very small but unwanted performance issue so no need to do it.

Try putting it into viewDidLoad() or similar methods.

Body:
Is it ok to register uitableviewcell in cellForRowAt. Before register i will check weather that cell is register or not by dequeue and nil check. Beacuse the tableview I m using its for genreic use across app and will not be sure about kind of cell will be needed.

var cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!
        if cell == nil {
            tableView.register(UINib(nibName: "TextFieldCell", bundle: nil), forCellReuseIdentifier: textFieldCellIdentifier);
            cell = tableView.dequeueReusableCell(withIdentifier: textFieldCellIdentifier) as! TextFieldCell!;
        }
        return cell!;


问:
Detect clicks inside a Div but outside of a particular child Div in VueJS
I have a page in which I have MCQ Options which looks like this:

This is the HTML Code for the options parts till now:

```<code><div v-for="(option, index) in optionsForFrontend">
            <div class="option">
                <div class="radio-check-item">
                    <input type="radio"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Single'">
                    <input type="checkbox"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Multiple'">
                </div>
                <div class="divider">

                </div>
                <div class="content-item">
                    <vue-markdown :source="option.option"></vue-markdown>
                </div>
            </div>
        </div>
</code>```

I want to select the options by clicking on the option content. So I put a :click="functionToSelectOption" on the outer div ("option") containing checkbox and option content.

The problem is when I select the checkbox, it gets selected and the function "functionToSelectOption" gets called as well since the checkbox is inside the "option" div.

I want to be able to detect a click inside the "option" div but outside radio/checkbox div so I can call the function to toggle the option.

I mostly found similar questions under jquery tags and nothing with VueJS.

答:
You can use event.stopPropagation() in child element.

Here is working JSFiddle Solution: Link

HTML

```<code><div id="app">
<div @click="parent">
    Parent
    <div>
        <input type="checkbox" @click="child">
    </div>
</div>
{{message}}
</code>```

JS

```<code>new Vue({
el: '#app',
data: {
    message: ''
},
methods: {
     parent: function() {
        this.message = 'parent clicked';
    },
    child: function() {
        event.stopPropagation()
    }
}
});
</code>```

Body:
I have a page in which I have MCQ Options which looks like this:

This is the HTML Code for the options parts till now:

                    <input type="radio"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Single'">
                    <input type="checkbox"
                        name="question"
                        :value="index"
                        v-model="picked"
                        v-if="question.metadata.choices === 'Multiple'">

                    <vue-markdown :source="option.option"></vue-markdown>

I want to select the options by clicking on the option content. So I put a :click="functionToSelectOption" on the outer div ("option") containing checkbox and option content.

The problem is when I select the checkbox, it gets selected and the function "functionToSelectOption" gets called as well since the checkbox is inside the "option" div.

I want to be able to detect a click inside the "option" div but outside radio/checkbox div so I can call the function to toggle the option.

I mostly found similar questions under jquery tags and nothing with VueJS.

Body:
You can use event.stopPropagation() in child element.

Here is working JSFiddle Solution: Link

HTML

<div id="app">
<div @click="parent">
    Parent
    <div>
        <input type="checkbox" @click="child">
    </div>
</div>
{{message}}

JS

new Vue({
el: '#app',
data: {
    message: ''
},
methods: {
     parent: function() {
        this.message = 'parent clicked';
    },
    child: function() {
        event.stopPropagation()
    }
}
});


问:
error LNK2005: new and delete already defined in LIBCMTD.lib(new.obj)
I have a Visual studio 2005 solution that has two projects. One is a static library and the other is a executable used to test the features in the static library. The static library uses MFC. I got the following errors when I built the solution. </p>

```<code>uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in LIBCMTD.lib(new.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void __cdecl operator delete(void *)" (??    3@YAXPAX@Z) already defined in LIBCMTD.lib(dbgdel.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new[](unsigned int)" (??_U@YAPAXI@Z) already defined in libcpmtd.lib(newaop.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void __cdecl operator delete[](void *)" (??_V@YAXPAX@Z) already defined in LIBCMTD.lib(delete2.obj)
</code>```

<p>I do not know how to overcome this. Can some one please explain why this error is occuring. Any explanation that gives an overview of .lib files linkage will be highly appreciated. </p>

答:
A header file declared and defined a variable. Possible solutions include:
Declare the variable in .h: extern BOOL MyBool; and then assign to it in a .c or .cpp file: BOOL MyBool = FALSE;.
Declare the variable static.
Declare the variable selectany.

https://msdn.microsoft.com/en-us/library/72zdcz6f.aspx

Body:
I have a Visual studio 2005 solution that has two projects. One is a static library and the other is a executable used to test the features in the static library. The static library uses MFC. I got the following errors when I built the solution.

uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in LIBCMTD.lib(new.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void __cdecl operator delete(void *)" (??    3@YAXPAX@Z) already defined in LIBCMTD.lib(dbgdel.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new[](unsigned int)" (??_U@YAPAXI@Z) already defined in libcpmtd.lib(newaop.obj)
uafxcwd.lib(afxmem.obj) : error LNK2005: "void __cdecl operator delete[](void *)" (??_V@YAXPAX@Z) already defined in LIBCMTD.lib(delete2.obj)

I do not know how to overcome this. Can some one please explain why this error is occuring. Any explanation that gives an overview of .lib files linkage will be highly appreciated.


问:
Which TortoiseGit command can overwrite local files?
I've installed TortoiseGit on Windows. I want to fetch all code from origin/master and all local files may be overwritten.
How can we do this with right clicking on the folder and which TortoiseGit method we should use with parameters?
Or do we always need to open a command prompt and enter the following commands:

```<code>git fetch --all
get reset --hard origin/master
</code>```

答:
You can use the exact same operations in TortoiseGit:

Fetch, then you can open the log and to a reset on origin/master using the context menu (if the branch is not visible, you can show it by enabling "Show all branches in the lower left or selecting it on the branch selector in the obber left).

If you don't have any local changes or commits, you can also just pull.

Body:
I've installed TortoiseGit on Windows. I want to fetch all code from origin/master and all local files may be overwritten.
How can we do this with right clicking on the folder and which TortoiseGit method we should use with parameters?
Or do we always need to open a command prompt and enter the following commands:

git fetch --all
get reset --hard origin/master


问:
Can any one give me some advice to make my for loop more efficient?
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

```<code>$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}
</code>```

答: Changing your if-s to a switch with appropriate breaks or even at worse if..elseif..etc would mean that not all ifs have to be evaluated.</p>

Body:
So I have this for loop with 36 if-queries inside. Any advice on making it more efficient?
You can view the complete code  here

Here's a sample of what it looks like:

$numbers = range(1, 36);
shuffle($numbers);
for ($m =0; $m<37; $m++){
    if ($numbers[$m] == "1"){
        $mirza[$m] = "RUTHIE";
        $mage[$m] = "3";
        $mquote[$m] = "I get to learn a lot of new things here, like sign language!";
        $link[$m] = "http://www.google.com";
    }

    if ($numbers[$m] == "2"){
        $mirza[$m] = "AIDA";
        $mage[$m] = "82";
        $mquote[$m] = "This is like a club and I know and like all the members. It's good therapy.";
        $link[$m] = "/about/";
    }

    if ($numbers[$m] == "3"){
        $mirza[$m] = "AMIRE";
        $mage[$m] = "4";
        $mquote[$m] = "I am learning how to share and make friends.";
        $link[$m] = "/about/";
    }
}


问:
how to store session data in file in expressjs?
When user login, i am storing data in session like this :

```<code>   req.session.user = userData;
</code>```

And it is working fine but when i restart in nodejs, the session is null. Then user need to login again.

I want to create a file based storage for session.But after a lot of search, i got the way to store data in database but i dont want to store session data in database. I want to store data in file.

Is there a nodejs module to store the session data in file?

答:
You can use session-file-store. can refer below working example.

```<code>var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    store: new FileStore,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
</code>```

Body:
When user login, i am storing data in session like this :

   req.session.user = userData;

And it is working fine but when i restart in nodejs, the session is null. Then user need to login again.

I want to create a file based storage for session.But after a lot of search, i got the way to store data in database but i dont want to store session data in database. I want to store data in file.

Is there a nodejs module to store the session data in file?

Body:
You can use session-file-store. can refer below working example.

var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    store: new FileStore,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});


答:
As you are starting activity from onClick() method, so when building an Intent you have to use the Context of current Activity.

Use:

```<code>Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);
</code>```

Instead of:

```<code>Intent numbers = new Intent(this, NumbersActivity.class);
</code>```

FYI, you have to import android.content.Intent to use Intent.

Finally, Clean your project and Build again. I hope your problem will be resolved.

Title: Cannot resolve constructor and method for reason I don't know

Body:
As you are starting activity from onClick() method, so when building an Intent you have to use the Context of current Activity.

Use:

Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);

Instead of:

Intent numbers = new Intent(this, NumbersActivity.class);

FYI, you have to import android.content.Intent to use Intent.

Finally, Clean your project and Build again. I hope your problem will be resolved.


问:
Silverlight: Changing the Background-Brush on MouseOver
in my Silverlight-Application, I want to change the Background-Brush of my button on mouse-over. I made a style for my button and changed the MouseOver-VisualState:

```<code><VisualState x:Name="MouseOver">
    <Storyboard>
    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Background)" Storyboard.TargetName="BorderBackground">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Background>{TemplateBinding BorderBrush}</Background>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>
</code>```

which doesn't work because 'The name "Background" does not exist in the namespace "http://schemas.microsoft.com/client/2007".' Any idea, how I can set the Background-Brush to Border-Brush on mouse-over without doing it with code behind and the appropriate events?

Thanks in advance,

Frank

答: It doesn't work, because I can't use Binding in the VisualStateManager, as explained here: Using TemplateBinding in ObjectAnimationUsingKeyFrames</p>

Body:
in my Silverlight-Application, I want to change the Background-Brush of my button on mouse-over. I made a style for my button and changed the MouseOver-VisualState:

<VisualState x:Name="MouseOver">
    <Storyboard>
    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Background)" Storyboard.TargetName="BorderBackground">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Background>{TemplateBinding BorderBrush}</Background>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

which doesn't work because 'The name "Background" does not exist in the namespace "http://schemas.microsoft.com/client/2007".' Any idea, how I can set the Background-Brush to Border-Brush on mouse-over without doing it with code behind and the appropriate events?

Thanks in advance,

Frank


问:
How to manage multiple notification in service using alarm manager
I have number of toggles like, 2 minute, 4 minute and 24 hours. if user select any one, the service will be start and set repeat time in alarm manager, the Notification will showing for particular selected time.

Now the problem is i want to show the number of title like for 2 minute reminder, 4 minute reminder and 24 hours reminder. how to manage these all the titles in local notification service and manage click event.

My code is How to keep service alive when remove app from stack

Please suggest to find solution.

答:
All the notifications will have a unique id so you can distinguish them on the basis of their id in the Receiver class. All these must be assigned a unique id when they are created to distinguish between them.

You can also define type of notification, so that you will be able to cast different types of notifications with different push messages and its parameters.

The answer to the question you asked in the comment that to set title of a notification :
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle("Title of Notification");


问:
android LocationServices Api not getting location updates when in background
```<code>public class LocationService extends BaseService implements
    LocationListener, Orientation.Listener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createLocationRequest();
        //Location request
        builder mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this)
            .build();
        mGoogleApiClient.connect();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onConnected(Bundle bundle) {
        try {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        catch (SecurityException e) { }
    }

    @Override
    public void onConnectionSuspended(int i) { }

    @Override
    public void onLocationChanged(Location location) {
        // if(location.isFromMockProvider()){
        // Log.d(TAG, "onLocationChanged: From mock location");
        // } else {
        speed = location.getSpeed() * 18 / 5;
        mCurrentLocation = location;
        LatLng local = new LatLng(location.getLatitude(), location.getLongitude());
        if (sharedPreferences.getBoolean(Constants.isRiding, false)) {
            locationArray.add(local);
            //Log.d("location", "onLocationChanged: " + local);
        }

        if (lStart == null) {
            lStart = mCurrentLocation;
            lEnd = mCurrentLocation;
        } else {
            lEnd = mCurrentLocation;
            updateUI();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) { }

    private void updateUI() {
        // doing something here
    }

     public void connect() {
        mGoogleApiClient.connect();
     }

    public static Location returnLocation() {
        return mCurrentLocation;
    }
}
</code>```

**I am using google api client along with locationservices api to get location in background, and its working fine when phone is unlocked but when phone is locked am not getting location updates what am i doing wrong?

It used to work before but i dunno why its not working now
**

答:
for any one who faces the same issue in future

I had degraded my location api in application gradle from com.google.android.gms:play-services:11.0.2 to
com.google.android.gms:play-services:10.0.2

Body:
public class LocationService extends BaseService implements
    LocationListener, Orientation.Listener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createLocationRequest();
        //Location request
        builder mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this)
            .build();
        mGoogleApiClient.connect();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onConnected(Bundle bundle) {
        try {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        catch (SecurityException e) { }
    }

    @Override
    public void onConnectionSuspended(int i) { }

    @Override
    public void onLocationChanged(Location location) {
        // if(location.isFromMockProvider()){
        // Log.d(TAG, "onLocationChanged: From mock location");
        // } else {
        speed = location.getSpeed() * 18 / 5;
        mCurrentLocation = location;
        LatLng local = new LatLng(location.getLatitude(), location.getLongitude());
        if (sharedPreferences.getBoolean(Constants.isRiding, false)) {
            locationArray.add(local);
            //Log.d("location", "onLocationChanged: " + local);
        }

        if (lStart == null) {
            lStart = mCurrentLocation;
            lEnd = mCurrentLocation;
        } else {
            lEnd = mCurrentLocation;
            updateUI();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) { }

    private void updateUI() {
        // doing something here
    }

     public void connect() {
        mGoogleApiClient.connect();
     }

    public static Location returnLocation() {
        return mCurrentLocation;
    }
}

**I am using google api client along with locationservices api to get location in background, and its working fine when phone is unlocked but when phone is locked am not getting location updates what am i doing wrong?

It used to work before but i dunno why its not working now
**


问:
Unable to plot graph on matplotlib
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

```<code>    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334
</code>```

and when I try to plot it by using the following codes:

```<code> dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')
</code>```

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!

答:
Its not clear what your df.values is, but I suspect it is your second DataFrame column?
In that case you can just use the DataFrame.plot() method.

Title: Unable to plot graph on matplotlib

Body:
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334

and when I try to plot it by using the following codes:

 dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!


问:
laravel passport doesn't support authorization_code grant type?

These are the fields that I am posting to /oauth/token from postman but the response is:

##

grant_type:authorization_code

client_id:12

client_secret:WXIfywkQvyHzjrR17sm0xQ72sPr8T6FUDSRPJrkL

code:WF3dQHx7Wr2Ly5UsK/r8TVgKqu6hmjfDaQnNKbHR3wJjuPiHsUPqVgmN45cMQKmopFH7zAm0vXTn5LhMms/19WOu2diV5r04T8Y7HidiWAFDObYCGkW2a3Iaa1KG8Y26EyfYtbhhP+hk87pd12s7S03ZUSqXVcuyFnkW6ip3Up1G+MDQP8htUqu5/cmq2zpRDLCjJZga3PIGFIglWgttcg9lYbVBG5q90FpQk4BMF4KrlOSJSU/73AQvOrtecety1xUvtNU2n2hxiNA4YbSMhQK0SIGFSSjd7EjAS6LZON7WLPLYKgExKCgYwx5ZmsZrQr3/0VP2dyH0/7o+bOEEO054xyB2K07UfBPtg6eobUGY19Vl5kUrIaOIp0EcNnTOiycOEQqIoHzKPLNSPTfvzd1jc6F1LfEJbzzXgEmI1OAfi2VVUduRBxBmqh1lFGFHfWbKD3ipNIBsNGhvvXcw2An7iMMlxDYv+AqUGVfa0mho+Qv19EG3ZTaHs8ykE5aGFoKSOWiDeABXhnUWhHHFJ39WJDL4yWDAhO2u9LFGvEhbOHjYXDAkp5B+wbtWLpoxgyvbmlMJ8Kl77ABVKE6cxk7khjTK7XoFIMVC+zdqVireZpbBja81eEFgUoGPmKIrX/ksp+9CQ9/J3CfZUQWaZO5LVybSo3JYFUwkWYtoNcY=%

redirect_uri:http://site.dzangocart.dev/profile

what i am missing here?

答:
When visiting the endpoint using Postman, set the Header Accept: application/json or Laravel Passport would never know it's an API client . check

https://scotch.io/@neo/getting-started-with-laravel-passport


问:
playing mp3 file in second activity after button is clicked
hello I am very new to android programming.I want Button in first activity and when it is clicked second activity will open and plays mp3 file from sd card i have mention path but mp3 file not plays after running project.I am posting my player.java

This is my class

```<code>public class player extends AppCompatActivity {

Button btPv,btplay,btStop,btPause;
SeekBar sb;
MediaPlayer mp3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);
    ;
    btplay=(Button)findViewById(R.id.btplay);
    btStop=(Button)findViewById(R.id.btstop);
    btPause=(Button)findViewById(R.id.btpause);
    mp3=new MediaPlayer();
    try {
        mp3.setDataSource("sdcard/musicblee/Over_the_horizon.mp3");
        mp3.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    btplay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp3.start();

        }
    });
    btStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {

                mp3.stop();
                mp3.reset();
                mp3.setDataSource("sdcard/musicblee/Over_the_horizon.mp3");
                mp3.prepare();
            } catch (Exception e) {

                e.printStackTrace();
            }

        }
    });
    btPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {

                mp3.pause();
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    });

}

}
</code>```

答:
refer to this link use mp3.setDataSource() like that

```<code>mp3 = MediaPlayer.create(this,Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/musicblee/Over_the_horizon.mp3"));
</code>```

to set mp3 source.
And Also add this permission to your Android Manifest file :

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Body:
hello I am very new to android programming.I want Button in first activity and when it is clicked second activity will open and plays mp3 file from sd card i have mention path but mp3 file not plays after running project.I am posting my player.java

This is my class

public class player extends AppCompatActivity {

Button btPv,btplay,btStop,btPause;
SeekBar sb;
MediaPlayer mp3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);
    ;
    btplay=(Button)findViewById(R.id.btplay);
    btStop=(Button)findViewById(R.id.btstop);
    btPause=(Button)findViewById(R.id.btpause);
    mp3=new MediaPlayer();
    try {
        mp3.setDataSource("sdcard/musicblee/Over_the_horizon.mp3");
        mp3.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    btplay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp3.start();

        }
    });
    btStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {

                mp3.stop();
                mp3.reset();
                mp3.setDataSource("sdcard/musicblee/Over_the_horizon.mp3");
                mp3.prepare();
            } catch (Exception e) {

                e.printStackTrace();
            }

        }
    });
    btPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {

                mp3.pause();
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    });

}

}

Body:
refer to this link use mp3.setDataSource() like that

mp3 = MediaPlayer.create(this,Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/musicblee/Over_the_horizon.mp3"));

to set mp3 source.
And Also add this permission to your Android Manifest file :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


问:
get first occurrence of a space after last occurrence of parenthesis
I'm trying to dice up a dictionary text file (using Sublime text editor) and need to get the first occurrence of a space after the last ) because I need to replace it with a delimiter I can import into Google sheets.

E.g., The following:

```<code>abierto (masculine) open

abjaso (masculine); abjasio (masculine) Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)    lawyer
</code>```

Should be (note the _ delimiter):

```<code>abierto (masculine)_    open

abjaso (masculine); abjasio (masculine)_    Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)_   lawyer
</code>```

How can I accomplish this?

EDIT: I've tried /\)[^\)]+$/g - to get a ) followed by one or more non-) characters, at the end of the string, greedy... but it only finds one result.

答:
You can use greedy match .*\) to get last ) using this regex to match:

```<code>/(.*\)) /
</code>```

and then replace it by:

```<code>$1_\t
</code>```

Where \t is for tab (you can se 4 spaces instead of \t as well.

RegEx Demo

Body:
I'm trying to dice up a dictionary text file (using Sublime text editor) and need to get the first occurrence of a space after the last ) because I need to replace it with a delimiter I can import into Google sheets.

E.g., The following:

abierto (masculine) open

abjaso (masculine); abjasio (masculine) Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)    lawyer

Should be (note the _ delimiter):

abierto (masculine)_    open

abjaso (masculine); abjasio (masculine)_    Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)_   lawyer

How can I accomplish this?

EDIT: I've tried /\)[^\)]+$/g - to get a ) followed by one or more non-) characters, at the end of the string, greedy... but it only finds one result.

Body:
You can use greedy match .*\) to get last ) using this regex to match:

/(.*\)) /

and then replace it by:

$1_\t

Where \t is for tab (you can se 4 spaces instead of \t as well.

RegEx Demo


问:
using reflection to get the name of a parameter
I have a c# .net 2.0CF application where I would like to get not only the type and value of a parameter passed to the function, but also the variable name.

For example:

```<code>void Show<PARAM>(PARAM p)
{
    Debug.WriteLine(string.Format("{0} {1} = {2}", typeof(PARAM).ToString, ???, p.ToString() );
}

bool foo = true;
Show(foo);
</code>```

would output "bool foo = true";

In C++, I can do this with the ## pre-processor macro.

If this can't be done in 2.0, can it be done in 3.5 or 4.0?

Thanks,
PaulH

答: Try using PostSharp it has the support for Compact Framework. </p>

Body:
I have a c# .net 2.0CF application where I would like to get not only the type and value of a parameter passed to the function, but also the variable name.

For example:

void Show<PARAM>(PARAM p)
{
    Debug.WriteLine(string.Format("{0} {1} = {2}", typeof(PARAM).ToString, ???, p.ToString() );
}

bool foo = true;
Show(foo);

would output "bool foo = true";

In C++, I can do this with the ## pre-processor macro.

If this can't be done in 2.0, can it be done in 3.5 or 4.0?

Thanks,
PaulH


问:
Cannot resolve constructor and method for reason I don't know
```<code>public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
</code>```

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>
</code>```

MainActivity.java

```<code>package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}
</code>```

AndroidManidest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>
</code>```

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

答:
replece this with your code

```<code>public void openNumbers (View view) {
    Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);
    startActivity(numbers);
}
</code>```

Body:
public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>

MainActivity.java

package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}

AndroidManidest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

Body:
replece this with your code

public void openNumbers (View view) {
    Intent numbers = new Intent(MainActivity.this, NumbersActivity.class);
    startActivity(numbers);
}


问:
Get parent objects without active childs
I've two models, Doctor and DoctorClinic where a doctor has_many clinics.

doctor.rb:

```<code>has_many :clinics, class_name: 'DoctorClinic', dependent: :destroy
</code>```

doctor_clinic.rb

```<code>belongs_to :doctor
</code>```

DoctorClinic have doctor_id and a boolean active field.

What I want:

I want to get all doctors which does not have any active (active field is true) clinics. If a doctor have two clinics, out of which one is active and other is inactive then doctor should not be selected.

Doctor record will be selected if,

there's no clinics at all

if there's any clinic but all are inactive, i.e. all have active false.

Doctor will not be selected if,

there's any active clinics.

What I've tried so far:

Try 1:

```<code>scope :incomplete_doctors, -> { includes(:clinics)
                                .where("( doctor_clinics.id IS NULL ) OR
                                        ( doctor_clinics.id IS NOT NULL AND
                                            doctor_clinics.active=?)", false )
                              }
</code>```

Try 2:

```<code>scope :incomplete_doctors, -> { where("id NOT IN (?)", self.includes(:clinics)
                            .where("( doctor_clinics.doctor_id IS NULL ) OR
                                      ( doctor_clinics.doctor_id IS NOT NULL AND
                                          doctor_clinics.active=?)", false )
                            .select(:id))
                            }
</code>```

Try 3:

```<code>SELECT "doctors".* FROM "doctors"
  LEFT OUTER JOIN "doctor_clinics" ON "doctor_clinics"."doctor_id" = "doctors"."id"
  WHERE ( ( doctor_clinics.id IS NULL ) OR
          ( doctor_clinics.id IS NOT NULL AND
              doctor_clinics.active='f'))
  GROUP BY doctors.id
    HAVING 'true' <> ANY(array_agg(DISTINCT doctor_clinics.active::TEXT));
</code>```

Success:

I'm able to achieve desired output using following method, but I want to achieve this using a SQL query.

```<code>def active_clinics
  clinics.active_clinics # active_clinics is a scope in Clinic model while give all active clinics
end

def self.incomplete_doctors
  (Doctor.all.map { |d| d unless d.active_clinics.present? }).compact
end
</code>```

答:
Something like this should do the trick in pure SQL

```<code>SELECT *
FROM doctors
WHERE NOT EXISTS (
  SELECT 1
  FROM doctor_clinics
  WHERE
    doctor_clinics.doctor_id = doctors.id
    AND doctor_clinics.active = true
)
</code>```

You should be able to use it with find_by_sql:

```<code>Doctor.find_by_sql(SQL)
</code>```

Have no Rails 3 project to actually test it;-)

Body:
I've two models, Doctor and DoctorClinic where a doctor has_many clinics.

doctor.rb:

has_many :clinics, class_name: 'DoctorClinic', dependent: :destroy

doctor_clinic.rb

belongs_to :doctor

DoctorClinic have doctor_id and a boolean active field.

What I want:

I want to get all doctors which does not have any active (active field is true) clinics. If a doctor have two clinics, out of which one is active and other is inactive then doctor should not be selected.

Doctor record will be selected if,

there's no clinics at all

if there's any clinic but all are inactive, i.e. all have active false.

Doctor will not be selected if,

there's any active clinics.

What I've tried so far:

Try 1:

scope :incomplete_doctors, -> { includes(:clinics)
                                .where("( doctor_clinics.id IS NULL ) OR
                                        ( doctor_clinics.id IS NOT NULL AND
                                            doctor_clinics.active=?)", false )
                              }

Try 2:

scope :incomplete_doctors, -> { where("id NOT IN (?)", self.includes(:clinics)
                            .where("( doctor_clinics.doctor_id IS NULL ) OR
                                      ( doctor_clinics.doctor_id IS NOT NULL AND
                                          doctor_clinics.active=?)", false )
                            .select(:id))
                            }

Try 3:

SELECT "doctors".* FROM "doctors"
  LEFT OUTER JOIN "doctor_clinics" ON "doctor_clinics"."doctor_id" = "doctors"."id"
  WHERE ( ( doctor_clinics.id IS NULL ) OR
          ( doctor_clinics.id IS NOT NULL AND
              doctor_clinics.active='f'))
  GROUP BY doctors.id
    HAVING 'true' <> ANY(array_agg(DISTINCT doctor_clinics.active::TEXT));

Success:

I'm able to achieve desired output using following method, but I want to achieve this using a SQL query.

def active_clinics
  clinics.active_clinics # active_clinics is a scope in Clinic model while give all active clinics
end

def self.incomplete_doctors
  (Doctor.all.map { |d| d unless d.active_clinics.present? }).compact
end

Body:
Something like this should do the trick in pure SQL

SELECT *
FROM doctors
WHERE NOT EXISTS (
  SELECT 1
  FROM doctor_clinics
  WHERE
    doctor_clinics.doctor_id = doctors.id
    AND doctor_clinics.active = true
)

You should be able to use it with find_by_sql:

Doctor.find_by_sql(SQL)

Have no Rails 3 project to actually test it;-)


问:
select from two mysql tables where column value is similar and id is retrieved from previous page
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

```<code>$a=$_POST['home_id']
</code>```

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

```<code>    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a <br/> ";
         echo " $bc2 <br/>";
        ?>
</code>```

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

```<code>  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";
</code>```

答:
```<code>**select tbl_home.name,tbl_office.case_no,tbl_office.color from tbl_office
INNER JOIN tbl_home on tbl_office.case_no = tbl_home.case_no
where tbl_office.case_no ='$a';**
</code>```

<p>I hope this will be working fine until $a(case_no) value is existed in tbl_home or else it doesn't give any rows  </p>

Body:
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

$a=$_POST['home_id']

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a
 ";
         echo " $bc2
";
        ?>

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";

Body:
**select tbl_home.name,tbl_office.case_no,tbl_office.color from tbl_office
INNER JOIN tbl_home on tbl_office.case_no = tbl_home.case_no
where tbl_office.case_no ='$a';**

I hope this will be working fine until $a(case_no) value is existed in tbl_home or else it doesn't give any rows


问:
show div after scrolling in mobile devices
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

```<code>$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}
</code>```

can somebody help me to fix this problem.

thank you

答:
you can try this one as show() and hide() functions are not supported by some of the browsers so this could be a reason.</p>

```<code>To hide:
$(".phonebox").css("display", "none");

To show:
$(".phonebox").css("display", "block");
</code>```

Body:
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}

can somebody help me to fix this problem.

thank you

Body:
you can try this one as show() and hide() functions are not supported by some of the browsers so this could be a reason.

To hide:
$(".phonebox").css("display", "none");

To show:
$(".phonebox").css("display", "block");


问:
How to filter inner array in json using $filter angular js
I want to filter json inner array

this is my array

```<code>{
    "code": "project_create",
    "WFID": ["1, "5", "2", "8", "9", "10", "7"]
 },
 {
   "code": "Task_create",
   "WFID": ["1", "5", "2", "8", "9"]
 },
 {
   "code": "project_update",
   "WFID": ["10", "5", "2", "8", "9"]
 },
</code>```

I want to filter by WFID=1

I try this way

```<code>var saveWorkflowobj = $filter('filter')(tiggers.alltigger, { WFID: WorkFlowID});
</code>```

答:
angular.module('app', []).controller('ctrl', ['$scope', '$filter', function($scope, $filter) {
    $scope.items = [
       {
          "code": "project_create",
          "WFID": ["1", "5", "2", "8", "9", "10", "7"]
       },
       {
         "code": "Task_create",
         "WFID": ["1", "5", "2", "8", "9"]
       },
       {
         "code": "project_update",
         "WFID": ["10", "5", "2", "8", "9"]
       }
    ];

    $scope.result = $filter('filter')($scope.items, {WFID : "1"}, function(a, b){
      return a === b;
    });
}])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//code.angularjs.org/snapshot/angular.min.js"></script>

 <div ng-app='app' ng-controller='ctrl'>
   <ul>
     <li ng-repeat='item in result'>{{item | json}}</li>
   </ul>
 </div></code>```

Body:
I want to filter json inner array

this is my array

{
    "code": "project_create",
    "WFID": ["1, "5", "2", "8", "9", "10", "7"]
 },
 {
   "code": "Task_create",
   "WFID": ["1", "5", "2", "8", "9"]
 },
 {
   "code": "project_update",
   "WFID": ["10", "5", "2", "8", "9"]
 },

I want to filter by WFID=1

I try this way

var saveWorkflowobj = $filter('filter')(tiggers.alltigger, { WFID: WorkFlowID});

Body:
angular.module('app', []).controller('ctrl', ['$scope', '$filter', function($scope, $filter) {
    $scope.items = [
       {
          "code": "project_create",
          "WFID": ["1", "5", "2", "8", "9", "10", "7"]
       },
       {
         "code": "Task_create",
         "WFID": ["1", "5", "2", "8", "9"]
       },
       {
         "code": "project_update",
         "WFID": ["10", "5", "2", "8", "9"]
       }
    ];

    $scope.result = $filter('filter')($scope.items, {WFID : "1"}, function(a, b){
      return a === b;
    });
}])

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

 <div ng-app='app' ng-controller='ctrl'>
   <ul>
     <li ng-repeat='item in result'>{{item | json}}</li>
   </ul>
 </div>