问:
Focus on input and remove focus using Jquery
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

```<code>Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">
</code>```

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

```<code>$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});
</code>```

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

答:
You can use the .blur

```<code>$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
    $("input").blur(function(){
        $(this).css("background-color", "#ffffff");
    });
});
</code>```

Or you can add class to each part of the html code:

```<code>Name: <input class="name" type="text" name="fullname"><br>
Email: <input class="email" type="text" name="email">
</code>```

And use the following JQuery code to run it.

```<code>$(document).ready(function(){
    $(".name").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".email").css("background-color", "#ffffff");
    });
    $(".email").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".name").css("background-color", "#ffffff");
    });
});
</code>```

Body:
I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore
it actually stays with the focus! how can I remove the backgound from the first one!

Fullname: <input type="text" name="name">

Email: <input type="text" name="email">

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

Body:
You can use the .blur

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
    $("input").blur(function(){
        $(this).css("background-color", "#ffffff");
    });
});

Or you can add class to each part of the html code:

Name: <input class="name" type="text" name="fullname"><br>
Email: <input class="email" type="text" name="email">

And use the following JQuery code to run it.

$(document).ready(function(){
    $(".name").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".email").css("background-color", "#ffffff");
    });
    $(".email").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".name").css("background-color", "#ffffff");
    });
});


来源: stackexchange

问:
JQuery - trigger call on div becoming visible
I have a div that is shown / hidden through CSS media queries.

I want to trigger a JQuery call when this div becomes visible - triggering once if the div changes from

```<code>display: none;
</code>```

to

```<code>display: block;
</code>```

Is this possible to do?

Something like the onclick call, but on the div property changing to visible?

```<code>$(document).on('click', '#mydiv', function() {
}
</code>```

答:
You could use $(window).resize() to detect these css display changes on the desired element:

```<code>$(window).resize(function() {
  var divDisplay = $('.mobileHide').css("display");
  if (divDisplay === "block") {
    $('.status').css('display', 'block');
    //do stuff
  } else {
    $('.status').css('display', 'none');
  }
});
</code>```

See resizable fiddle

ContentLicense: CC BY-SA 3.0

Body:
I have a div that is shown / hidden through CSS media queries.

I want to trigger a JQuery call when this div becomes visible - triggering once if the div changes from

display: none;

to

display: block;

Is this possible to do?

Something like the onclick call, but on the div property changing to visible?

$(document).on('click', '#mydiv', function() {
}

Body:
You could use $(window).resize() to detect these css display changes on the desired element:

$(window).resize(function() {
  var divDisplay = $('.mobileHide').css("display");
  if (divDisplay === "block") {
    $('.status').css('display', 'block');
    //do stuff
  } else {
    $('.status').css('display', 'none');
  }
});

See resizable fiddle


问:
Basic Data Warehouse - How to join data 2 tables away

I have a basic data warehouse setup that represents the police force:

Every FACT_CRIME has an assigned DIM_OFFICER; every DIM_OFFICER is assigned to a DIM_STATION.

What SQL logic can I use to display all FACT_CRIMEs along with the associated DIM_STATION? My issue is that to obtain the DIM_STATION.station_code, I know it must be done via the DIM_OFFICER, since that is the relational link, but I'm not savvy enough with SQL to know how to get data from 2 tables away.

This is a query I have so far, it produces the format I'm after, but not the correct results:

```<code>select
    fact_crime.*, dim_station.station_code
from fact_crime
join dim_station
    on fact_crime.assigned_officer_id
        in (select dim_officer.officer_id from dim_officer where dim_officer.station_id = dim_station.station_id)
group by dim_station.station_code
</code>```

Sample of produced results: (correct format, but incorrect data)

I'm expecting every instance of FACT_CRIME to appear, with the assigned officer's station code additionally appearing in the table.

Thanks in advance to anyone who can point me in the right direction. I'm still trying to get to grips with the basics of SQL, so apologies if I require additional clarification on any responses.

答:
You need two joins, someting like this (I'm guessing because you didn't show many details).

```<code>...
from fact_crime c
join dim_officer o ON c.assigned_officer_id = o.officer_id
join dim_station s ON o.station_id = s.station_id
</code>```

This is a very common SQL pattern, so you'll find the MySQL software does a good job making it efficient.

Pro tip: Avoid the * in SELECT *, especially from result sets that are results of lots of JOIN operations. Instead, use SELECT to give the list of columns you need.

Body:
I have a basic data warehouse setup that represents the police force:

Every FACT_CRIME has an assigned DIM_OFFICER; every DIM_OFFICER is assigned to a DIM_STATION.

What SQL logic can I use to display all FACT_CRIMEs along with the associated DIM_STATION? My issue is that to obtain the DIM_STATION.station_code, I know it must be done via the DIM_OFFICER, since that is the relational link, but I'm not savvy enough with SQL to know how to get data from 2 tables away.

This is a query I have so far, it produces the format I'm after, but not the correct results:

select
    fact_crime.*, dim_station.station_code
from fact_crime
join dim_station
    on fact_crime.assigned_officer_id
        in (select dim_officer.officer_id from dim_officer where dim_officer.station_id = dim_station.station_id)
group by dim_station.station_code

Sample of produced results: (correct format, but incorrect data)

I'm expecting every instance of FACT_CRIME to appear, with the assigned officer's station code additionally appearing in the table.

Thanks in advance to anyone who can point me in the right direction. I'm still trying to get to grips with the basics of SQL, so apologies if I require additional clarification on any responses.

Body:
You need two joins, someting like this (I'm guessing because you didn't show many details).

...
from fact_crime c
join dim_officer o ON c.assigned_officer_id = o.officer_id
join dim_station s ON o.station_id = s.station_id

This is a very common SQL pattern, so you'll find the MySQL software does a good job making it efficient.

Pro tip: Avoid the * in SELECT *, especially from result sets that are results of lots of JOIN operations. Instead, use SELECT to give the list of columns you need.


答:
The dep.var.labels argument is only looking for two values, since you only have two different dependent variables. As an example, the following code uses the mtcars dataset. This code doesn't work correctly:

```<code>library(stargazer)
data(mtcars)
lm1 <- lm(data=mtcars, mpg ~ cyl)
lm2 <- lm(data=mtcars, mpg ~ disp)
lm3 <- lm(data=mtcars, hp ~ cyl)
lm4 <- lm(data=mtcars, hp ~ disp)
stargazer(lm1, lm2, lm3, lm4,
          type = "text",
          dep.var.labels = c("mpg", "mpg", "hp", "hp"),
          column.labels=c("1", "2", "3", "4"),
          column.separate = c(1,1,1,1))
</code>```

Whereas this code generates the correct labels:

```<code>stargazer(lm1, lm2, lm3, lm4,
          type = "text",
          dep.var.labels = c("mpg", "hp"),
          column.labels=c("1", "2", "3", "4"),
          column.separate = c(1,1,1,1))
</code>```

Title: How to make a dependent variable label for each column Stargazer

Body:
I want to format my stargazer table like what is below.
This is my code

stargazer(reg_1a, reg_2a, reg_3a, reg_4a, reg_5a, reg_6a, type="text",
          dep.var.labels = c("Ed76", "Ed76", "Wages", "Wages", "Wages", "Wages"),
          model.names = FALSE,
          title = "Table 3",
          keep = c("nearc4", "ed76"),
          omit.stat = c("rsq", "adj.rsq", "ser", "f"),
          single.row = FALSE,
          column.separate = c(1,1,1,1,1,1),
          multicolumn = TRUE,
          column.labels = c("OLS","OLS","OLS", "OLS", "iv", "iv"))

these are the results I am getting

Table 3
=================================================================
                             Dependent variable:
             ----------------------------------------------------
                   Educ                       Educ
               OLS      OLS      OLS     OLS       iv       iv
               (1)      (2)      (3)     (4)      (5)      (6)
-----------------------------------------------------------------
nearc4       0.290*** 0.273*** 0.043** 0.048***
             (0.081)  (0.077)  (0.018) (0.018)

ed76                                            0.027*** 0.035***
                                                (0.004)  (0.004)

-----------------------------------------------------------------
Observations  3,613    3,613    3,010   3,010    3,010    3,010
=================================================================
Note:                                 *p<0.1; **p<0.05; ***p<0.01

but this is what I want

Table 3
=================================================================

             ----------------------------------------------------
               ed76     ed76     wages   wages     wages   wages
               OLS      OLS      OLS     OLS       iv       iv
               (1)      (2)      (3)     (4)      (5)      (6)
-----------------------------------------------------------------
nearc4       0.290*** 0.273*** 0.043** 0.048***
             (0.081)  (0.077)  (0.018) (0.018)

ed76                                            0.027*** 0.035***
                                                (0.004)  (0.004)

-----------------------------------------------------------------
Observations  3,613    3,613    3,010   3,010    3,010    3,010
=================================================================
Note:                                 *p<0.1; **p<0.05; ***p<0.01

I'm not sure how to assign the dep. variable lines to each column.

Body:
The dep.var.labels argument is only looking for two values, since you only have two different dependent variables. As an example, the following code uses the mtcars dataset. This code doesn't work correctly:

library(stargazer)
data(mtcars)
lm1 <- lm(data=mtcars, mpg ~ cyl)
lm2 <- lm(data=mtcars, mpg ~ disp)
lm3 <- lm(data=mtcars, hp ~ cyl)
lm4 <- lm(data=mtcars, hp ~ disp)
stargazer(lm1, lm2, lm3, lm4,
          type = "text",
          dep.var.labels = c("mpg", "mpg", "hp", "hp"),
          column.labels=c("1", "2", "3", "4"),
          column.separate = c(1,1,1,1))

Whereas this code generates the correct labels:

stargazer(lm1, lm2, lm3, lm4,
          type = "text",
          dep.var.labels = c("mpg", "hp"),
          column.labels=c("1", "2", "3", "4"),
          column.separate = c(1,1,1,1))


问:
How to update table based on count of entries of another table
I've table as below

```<code>Sample
 Source | Action |   DueDate            | Status
  A        Act_1    08DEC2017:00:00:00     Open
  A        Act_1    09DEC2017:00:00:00     closed
  A        Act_2    09DEC2017:00:00:00     Open
  A        Act_2    09DEC2017:00:00:00     closed
  A        Act_3    09DEC2017:00:00:00     Open
  B        Act_1    09DEC2017:00:00:00     Open
  B        Act_2    09DEC2017:00:00:00     closed
</code>```

I want to  add data in my final table according to the count of entries of each Action with respect to the source.

my final table as

```<code>final
 Source | Action | Total_Received | Total_closed | OverDue
   A       Act_1      2                1              1
   A       Act_2      2                1              0
   A       Act_3      1                0              0
   B       Act_1      1                0              0
   B       Act_2      1                1              0
</code>```

Total_Received is Total number of entries/rows

Total_Closed   is Total number of closed entries

Total_overdue  is Total number of open entries whose DueDate is passed

date of this time is 9DEC2017

Kindly tell me to update my table dynamically because there can be many Source types and Action Types in my system.

Have a nice day.

答:
You can do this using conditional aggregation:

```<code>select source, action,
       count(*) as total_received,
       sum(case when status = 'Closed' then 1 else 0 end) as total_closed,
       sum(case when status = 'Open' and DueDate < Today() then 1 else 0 end) as overdue
from t
group by source, action;
</code>```

date/time functions vary among databases.  This uses functions appropriate for SAS proc sql.

Body:
I've table as below

Sample
 Source | Action |   DueDate            | Status
  A        Act_1    08DEC2017:00:00:00     Open
  A        Act_1    09DEC2017:00:00:00     closed
  A        Act_2    09DEC2017:00:00:00     Open
  A        Act_2    09DEC2017:00:00:00     closed
  A        Act_3    09DEC2017:00:00:00     Open
  B        Act_1    09DEC2017:00:00:00     Open
  B        Act_2    09DEC2017:00:00:00     closed

I want to  add data in my final table according to the count of entries of each Action with respect to the source.

my final table as

final
 Source | Action | Total_Received | Total_closed | OverDue
   A       Act_1      2                1              1
   A       Act_2      2                1              0
   A       Act_3      1                0              0
   B       Act_1      1                0              0
   B       Act_2      1                1              0

Total_Received is Total number of entries/rows

Total_Closed   is Total number of closed entries

Total_overdue  is Total number of open entries whose DueDate is passed

date of this time is 9DEC2017

Kindly tell me to update my table dynamically because there can be many Source types and Action Types in my system.

Have a nice day.

Body:
You can do this using conditional aggregation:

select source, action,
       count(*) as total_received,
       sum(case when status = 'Closed' then 1 else 0 end) as total_closed,
       sum(case when status = 'Open' and DueDate < Today() then 1 else 0 end) as overdue
from t
group by source, action;

date/time functions vary among databases.  This uses functions appropriate for SAS proc sql.


问:
Ordering two tables by one datetime with PHP, MYSQL (PDO)
Here are some crazy issues I'm fighting with for a very long time now:
I have a two tables with identical structure, let's assume they are dogs_table and cats_table

```<code>dogs_table:
-id
-dog_posts
-dog_date

cats_table:
-id
-cat_posts
-cat_date
</code>```

I would like to create a timeline from dog_posts and cat_posts, similar to this one:

dog_posts should go to the left side and cat_posts to the right but they must be joined as it's one table, ordered by datetime of each one. (Either way the timeline crushes). Until now I tried using UNIONsimilar to this:

```<code>SELECT cat_posts as posts, cat_date as date, 'cats' as type from cats_table
UNION
SELECT dog_posts as posts, dog_date as date, 'dogs' as type from dogs_table
ORDER BY date desc
</code>```

But this or similar UNION ways absolutely are not working to me, because the make both dogs and cats posts as one and I need to be able output a row either with dog_posts or cat_posts. So, I'm wondering if there is some better way than using UNION or maybe there is a way to achieve this result with UNION too, but I just don't know the right syntax. And I have no idea how to use JOIN too... So, any help will be highly appreciated, thanks a lot to everyone for attention.

答:
An alternative way of what I wrote in the comments is a full outer join.
Usually I don't use full outer joins, but when I do, I use the following method: Select all distinct values from the join columns of both tables (which are dog_date and cat_date in your case). Use it in a subquery and left join the two tables on that columns.

select dogs.dog_post, dates.date, cats.cat_post
from (
    select dog_date as date from dogs_table
    union
    select cat_date as date from cats_table
) dates
left join dogs_table dogs on dogs.dog_date = dates.date
left join cats_table cats on cats.cat_date = dates.date
order by dates.date
```

However - I don't know what you are going to do, if multiple rows have the same date.

Body:
Here are some crazy issues I'm fighting with for a very long time now:
I have a two tables with identical structure, let's assume they are dogs_table and cats_table

dogs_table:
-id
-dog_posts
-dog_date

cats_table:
-id
-cat_posts
-cat_date

I would like to create a timeline from dog_posts and cat_posts, similar to this one:

dog_posts should go to the left side and cat_posts to the right but they must be joined as it's one table, ordered by datetime of each one. (Either way the timeline crushes). Until now I tried using UNIONsimilar to this:

SELECT cat_posts as posts, cat_date as date, 'cats' as type from cats_table
UNION
SELECT dog_posts as posts, dog_date as date, 'dogs' as type from dogs_table
ORDER BY date desc

But this or similar UNION ways absolutely are not working to me, because the make both dogs and cats posts as one and I need to be able output a row either with dog_posts or cat_posts. So, I'm wondering if there is some better way than using UNION or maybe there is a way to achieve this result with UNION too, but I just don't know the right syntax. And I have no idea how to use JOIN too... So, any help will be highly appreciated, thanks a lot to everyone for attention.

Body:
An alternative way of what I wrote in the comments is a full outer join.
Usually I don't use full outer joins, but when I do, I use the following method: Select all distinct values from the join columns of both tables (which are dog_date and cat_date in your case). Use it in a subquery and left join the two tables on that columns.

select dogs.dog_post, dates.date, cats.cat_post
from (
    select dog_date as date from dogs_table
    union
    select cat_date as date from cats_table
) dates
left join dogs_table dogs on dogs.dog_date = dates.date
left join cats_table cats on cats.cat_date = dates.date
order by dates.date

However - I don't know what you are going to do, if multiple rows have the same date.


问:
Problem opening mysql connection in php class
I am trying to create my own class to handle mysql interactions on a test site I'm making.  I can't get the mysqli_connect() to work within the class declaration.  Every time I try to use the class in a script I get this syntax error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\autoshop\classes\class_db.inc.php on line 7

Here is the code I have so far:

```<code><?php
class Db{
    private $host = 'localhost';
    private $db_user = 'username';
    private $db_pass = 'password';
    private $db_name = 'dbname';
    private $con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');

    public function valid_login($login_user, $login_pass){

        if(isset($login_user) && isset($login_pass) && ($login_user !== "") && ($login_pass !== "")){
            include('./includes/functions.php');

            $clean_lu = mysqli_real_escape_string($this->con, $login_user);
            $clean_lp = mysqli_real_escape_string($this->con, $login_pass);

            $login_query = "SELECT hash FROM users WHERE user_name='$clean_lu'";
            $login_results = mysqli_query($this->con, $login_query) or die('bad query');
            $login_hash = mysqli_fetch_array($login_results);

            if(isset($login_hash[0])){
                if(check_hash($clean_lp, $login_hash[0])){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
    }

    mysqli_close($this->con);
}
?>
</code>```

I keep looking at that line and I can't find any bad syntax.

I apologize if this is a really simple solution that's right in front of my face, I'm pretty new at this whole developer thing.

答:
maybe try this</p>

```<code>$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error)
{
trigger_error('Connect Error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create my own class to handle mysql interactions on a test site I'm making.  I can't get the mysqli_connect() to work within the class declaration.  Every time I try to use the class in a script I get this syntax error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\autoshop\classes\class_db.inc.php on line 7

Here is the code I have so far:

<?php
class Db{
    private $host = 'localhost';
    private $db_user = 'username';
    private $db_pass = 'password';
    private $db_name = 'dbname';
    private $con = mysqli_connect($this->host, $this->db_user, $this->db_pass, $this->db_name) or die('failed to connect');

    public function valid_login($login_user, $login_pass){

        if(isset($login_user) && isset($login_pass) && ($login_user !== "") && ($login_pass !== "")){
            include('./includes/functions.php');

            $clean_lu = mysqli_real_escape_string($this->con, $login_user);
            $clean_lp = mysqli_real_escape_string($this->con, $login_pass);

            $login_query = "SELECT hash FROM users WHERE user_name='$clean_lu'";
            $login_results = mysqli_query($this->con, $login_query) or die('bad query');
            $login_hash = mysqli_fetch_array($login_results);

            if(isset($login_hash[0])){
                if(check_hash($clean_lp, $login_hash[0])){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
    }

    mysqli_close($this->con);
}
?>

I keep looking at that line and I can't find any bad syntax.

I apologize if this is a really simple solution that's right in front of my face, I'm pretty new at this whole developer thing.

Body:
maybe try this

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error)
{
trigger_error('Connect Error (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}


问:
Unable to merge dex
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app gradle:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}
</code>```

And my module gradle:

```<code>    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}
</code>```

My second module:

```<code>     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}
</code>```

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D

答:
I had the same problem. I solved it by performing a clean and then building the project from Android Studio 3.0  menu:

build -> clean project

build-> rebuild project

Title: Unable to merge dex

Body:
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}

And my module gradle:

    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}

My second module:

     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D


问:
Synchronous Alamofire Request with DispatchGroup
I need to wait until Alamofire request finishes getting data. (Error or value). I'm calling Alamofire function inside a for loop in another function so that Alamofire requests should be finished before second for loop called. For example; first loop -> first request -> second loop -> second request...so on. Now It goes first loop -> second loop -> and after all loops finishes requests response is turning.

Request Function:

```<code> func like(sender_id: String, completion: @escaping (String?) -> ()){
    let group = DispatchGroup()
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        group.enter()
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
            .responseJSON { (response) -> Void in
                guard response.result.isSuccess else {
                    print("Error while doing : \(response.result.error)")
                    completion(nil)
                    group.leave()
                    return
                }
                if let error = response.error{
                    completion(nil)
                    group.leave()
                    print("Error Occured with Request: \(error)")
                }
                if let jsonData = response.data{
                    let json = JSON(data: jsonData)
                    print(json)
                    group.leave()
                    if let matched = json["match"].bool{
                        completion(matched.description)
                        print("Liked!: \(matched)")
                        if(matched){
                        }
                    }else{
                        group.leave()
                        "There is an error with JSON"
                    }
                }}
    }
}
</code>```

Where I call:

```<code> func like_all(completion: @escaping() -> ()){
    for user in SharedUsers.sharedUser.users{
        if let id = user.id{
            Network.sharedInstance.like(sender_id: id) { result in
                print(result)
            }
        }
        else{
            continue
        }
    }
    completion()
}
</code>```

答:
I solve it by calling like function with index + 1 everytime Alamofire returns value. I also call function in completion part of fetch request.

Here is the code:

```<code>    @objc func action(_ sender: LGButton) {
        sender.titleString = "Started to Like :)"
        Network.sharedInstance.get_rec(completion: { (result) in
            if(result != nil)
            {
                Network.sharedInstance.like(sender: 0, completion: { (result) in
                    //print(result)
                })
            }
        })
}
</code>```

Like Function:

```<code> func like(sender: Int, completion: @escaping (String?) -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        print(sender)
        print(SharedUsers.sharedUser.users.count)
        if(sender < SharedUsers.sharedUser.users.count){
            if let user_id = SharedUsers.sharedUser.users[sender].id{
                Alamofire.request(baseUrl + likeURL + user_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
                    .responseJSON { (response) -> Void in
                        guard response.result.isSuccess else {
                            print("Error while doing : \(response.result.error)")
                            completion(nil)
                            return
                        }
                        if let error = response.error{
                            completion(nil)
                            print("Error Occured with Request: \(error)")
                        }
                        if let jsonData = response.data{
                            let json = JSON(data: jsonData)
                            if let matched = json["match"].bool{
                                completion(matched.description)
                                print("Liked!: \(matched)")
                                if(sender <= SharedUsers.sharedUser.users.count){
                                    self.like(sender: sender + 1, completion: {result in
                                        //print(result)
                                    })
                                }else{
                                    return
                                }
                                if(matched){
                                }
                            }else{
                                "There is an error with JSON"
                            }}}
            }else{return}
        }}}
</code>```

Body:
I need to wait until Alamofire request finishes getting data. (Error or value). I'm calling Alamofire function inside a for loop in another function so that Alamofire requests should be finished before second for loop called. For example; first loop -> first request -> second loop -> second request...so on. Now It goes first loop -> second loop -> and after all loops finishes requests response is turning.

Request Function:

 func like(sender_id: String, completion: @escaping (String?) -> ()){
    let group = DispatchGroup()
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        group.enter()
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
            .responseJSON { (response) -> Void in
                guard response.result.isSuccess else {
                    print("Error while doing : \(response.result.error)")
                    completion(nil)
                    group.leave()
                    return
                }
                if let error = response.error{
                    completion(nil)
                    group.leave()
                    print("Error Occured with Request: \(error)")
                }
                if let jsonData = response.data{
                    let json = JSON(data: jsonData)
                    print(json)
                    group.leave()
                    if let matched = json["match"].bool{
                        completion(matched.description)
                        print("Liked!: \(matched)")
                        if(matched){
                        }
                    }else{
                        group.leave()
                        "There is an error with JSON"
                    }
                }}
    }
}

Where I call:

 func like_all(completion: @escaping() -> ()){
    for user in SharedUsers.sharedUser.users{
        if let id = user.id{
            Network.sharedInstance.like(sender_id: id) { result in
                print(result)
            }
        }
        else{
            continue
        }
    }
    completion()
}

Body:
I solve it by calling like function with index + 1 everytime Alamofire returns value. I also call function in completion part of fetch request.

Here is the code:

    @objc func action(_ sender: LGButton) {
        sender.titleString = "Started to Like :)"
        Network.sharedInstance.get_rec(completion: { (result) in
            if(result != nil)
            {
                Network.sharedInstance.like(sender: 0, completion: { (result) in
                    //print(result)
                })
            }
        })
}

Like Function:

 func like(sender: Int, completion: @escaping (String?) -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        print(sender)
        print(SharedUsers.sharedUser.users.count)
        if(sender < SharedUsers.sharedUser.users.count){
            if let user_id = SharedUsers.sharedUser.users[sender].id{
                Alamofire.request(baseUrl + likeURL + user_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
                    .responseJSON { (response) -> Void in
                        guard response.result.isSuccess else {
                            print("Error while doing : \(response.result.error)")
                            completion(nil)
                            return
                        }
                        if let error = response.error{
                            completion(nil)
                            print("Error Occured with Request: \(error)")
                        }
                        if let jsonData = response.data{
                            let json = JSON(data: jsonData)
                            if let matched = json["match"].bool{
                                completion(matched.description)
                                print("Liked!: \(matched)")
                                if(sender <= SharedUsers.sharedUser.users.count){
                                    self.like(sender: sender + 1, completion: {result in
                                        //print(result)
                                    })
                                }else{
                                    return
                                }
                                if(matched){
                                }
                            }else{
                                "There is an error with JSON"
                            }}}
            }else{return}
        }}}


问:
how to redirect type of website based on user-agent

Do you have such kind of experience? If yes, please let me know how many instances do I need to configure like that?

答:
You are looking for something like the map directive. Example below based on https://serverfault.com/questions/316541/check-several-user-agent-in-nginx</p>

```<code>http {
  map $http_user_agent $ua_redirect {
    default '';
    ~(iPhone|Android) m.domain1.com;
    ~(MSIE|Mozilla) domain2.com;
  }

  server {
    ...
    location / {
      ...
      if ($ua_redirect != '') {
         return 301 http://$ua_redirect$request_uri;
      }
    }
  }
}
</code>```

Body:
You are looking for something like the map directive. Example below based on https://serverfault.com/questions/316541/check-several-user-agent-in-nginx

http {
  map $http_user_agent $ua_redirect {
    default '';
    ~(iPhone|Android) m.domain1.com;
    ~(MSIE|Mozilla) domain2.com;
  }

  server {
    ...
    location / {
      ...
      if ($ua_redirect != '') {
         return 301 http://$ua_redirect$request_uri;
      }
    }
  }
}


问:
Why are grid items not centered?
For some reason two input ranges are making the top two items in the grid off centered.

I am assuming this is because of their shadow DOM styling. Is this actually the case?

Does anybody know why the ranges are making items A and B off centered?

Here is a codepen.

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
}

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="center"></div>
<div id="grid">
  <div id="a">A</div>
  <div id="b">B</div>
  <input type="range" id="c">
  <div id="d"></div>
  <input type="range" id="e">
  <div id="f"></div>
  <div id="g"> </div>
</div></code>```

答:
The Problem

When you don't define the grid column widths using grid-template-columns (for explicit grids) or grid-auto-columns (for implicit grids), the width of each column is left to auto. This means that the widths are determined by the content.

You've defined the layout with grid-template-areas:

```<code>grid-template-areas:  "a a b b"
                      "c c c d"
                      "e e e f"
                      "g g g g" ;
</code>```

But you haven't defined the columns, so they are left to their own devices.

In this case, the auto columns result in a visual (but not actual) misalignment in your grid:

As seen in Chrome:

Solutions

Since you are working with a four-column implicit grid, you can add this rule to your grid container to fix the problem.

```<code>grid-auto-columns: 1fr
</code>```

Now, instead of the container distributing space based on content size, it distributes space evenly among columns.

Chrome, with the adjustment above:

revised codepen

You can also fix the problem with this rule:

```<code>grid-template-columns: repeat(4, 1fr);
</code>```

revised codepen

Browser Variations

By the way, your layout renders differently across Grid-supporting browsers.

Chrome

Firefox

Edge

(I didn't test in Safari.)

Basically, in Firefox and Edge the range input looks like its locked into the first column and doesn't honor the grid-template-areas rule.

This is because of a default setting on this type of input set by these browsers:

Firefox

So basically these inputs are set to width: 12em.

To fix the problem, add this to your code:

```<code>input { width: auto }
</code>```

Now everything should work across all Grid-supporting browsers.

revised codepen

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
  grid-auto-columns: 1fr; /* NEW */
}
input { width: auto; } /* NEW */

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="center"></div>
<div id="grid">
  <div id="a">A</div>
  <div id="b">B</div>
  <input type="range" id="c">
  <div id="d"></div>
  <input type="range" id="e">
  <div id="f"></div>
  <div id="g"> </div>
</div></code>```

Title: Why are grid items not centered?

Body:
For some reason two input ranges are making the top two items in the grid off centered.

I am assuming this is because of their shadow DOM styling. Is this actually the case?

Does anybody know why the ranges are making items A and B off centered?

Here is a codepen.

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
}

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }

A

B

  <input type="range" id="c">

  <input type="range" id="e">

Body:
The Problem

When you don't define the grid column widths using grid-template-columns (for explicit grids) or grid-auto-columns (for implicit grids), the width of each column is left to auto. This means that the widths are determined by the content.

You've defined the layout with grid-template-areas:

grid-template-areas:  "a a b b"
                      "c c c d"
                      "e e e f"
                      "g g g g" ;

But you haven't defined the columns, so they are left to their own devices.

In this case, the auto columns result in a visual (but not actual) misalignment in your grid:

As seen in Chrome:

Solutions

Since you are working with a four-column implicit grid, you can add this rule to your grid container to fix the problem.

grid-auto-columns: 1fr

Now, instead of the container distributing space based on content size, it distributes space evenly among columns.

Chrome, with the adjustment above:

revised codepen

You can also fix the problem with this rule:

grid-template-columns: repeat(4, 1fr);

revised codepen

Browser Variations

By the way, your layout renders differently across Grid-supporting browsers.

Chrome

Firefox

Edge

(I didn't test in Safari.)

Basically, in Firefox and Edge the range input looks like its locked into the first column and doesn't honor the grid-template-areas rule.

This is because of a default setting on this type of input set by these browsers:

Firefox

So basically these inputs are set to width: 12em.

To fix the problem, add this to your code:

input { width: auto }

Now everything should work across all Grid-supporting browsers.

revised codepen

body { margin: 0; background: #0d0d0d; }

#center{width:2px;height:100%;position:absolute;left:calc(50% - 1px);background:red;}

#grid {
  width: 80%;
  height: 30%;
  position: absolute;
  top: 35%;
  left: 10%;
  display: grid;
  grid-template-areas:
    "a a b b"
    "c c c d"
    "e e e f"
    "g g g g"
    ;
  grid-gap: 10px;
  color: #fff;
  box-sizing: border-box;
  border: dotted yellow 1px;
  grid-auto-columns: 1fr; /* NEW */
}
input { width: auto; } /* NEW */

#a, #b { display: flex; justify-content: center; align-items: center; }

#a, #b, #d, #f, #g { background: #1a1a1a; }

#a { grid-area: a; }
#b { grid-area: b; }
#c { grid-area: c; }
#d { grid-area: d; }
#e { grid-area: e; }
#f { grid-area: f; }
#g { grid-area: g; }

<div id="center"></div>
<div id="grid">
  <div id="a">A</div>
  <div id="b">B</div>
  <input type="range" id="c">
  <div id="d"></div>
  <input type="range" id="e">
  <div id="f"></div>
  <div id="g">&nbsp;</div>
</div>


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
Try this: find a big switch statement and refactor it into classes. This was a big 'aha!' moment for me. It is a classic refactoring, illustrates the difference between procedural and OO design, and is not difficult to perform. Then realise that if statements are small switches.

Now, go and read about design patterns. Write some classes using them.

Next, take some set of classes that provide some functionality and rewrite it without return statements and preferably with interfaces. This was another big 'aha!' for me.

In fact, a good bet is to spend a week reading c2.com.

Hope helps you on your journey.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD