问:
Cannot import android.support.v7.media
I need to import this to be able to use MediaRouterSelector.

I already updated my Android Support Repository in SDK Manage, but I still can't import this library :/

I want to follow this tutorial:

https://developer.android.com/guide/topics/media/mediarouter.html

So I can add screenshare to my app and connect to my SmartTV.

答:
Update to
Android SDK 25
Android Build Tools v25.0.3
Android Support Repository

Add the dependency
compile 'com.android.support:mediarouter-v7:25.3.1'

Then use the MediaRouteSelector in any of your component.

Hope your build.gradle is like this

```<code>android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
    applicationId "com.example.git.demo"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
</code>```

Just add the below dependency

```<code>dependencies {
compile 'com.android.support:mediarouter-v7:23.2.1'
</code>```

}

Title: Cannot import android.support.v7.media

Body:
Update to
Android SDK 25
Android Build Tools v25.0.3
Android Support Repository

Add the dependency
compile 'com.android.support:mediarouter-v7:25.3.1'

Then use the MediaRouteSelector in any of your component.

Hope your build.gradle is like this

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
    applicationId "com.example.git.demo"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Just add the below dependency

dependencies {
compile 'com.android.support:mediarouter-v7:23.2.1'

}


来源: stackexchange

问:
Why sync bintray with maven central?
I'm building few projects and publish them to bintray. After that i can add resolver that points to my repository and use any library in that repo.

So what is the point to sync your package with maven central?

i see these reasons:

my package will be available in mvnrepository search. I can see usages of my package in other libraries

maven central is default resolver, so i don't need add any other resolvers in sbt

Are there any other reasons? Thanks!

答:
From bintray blog :

Maven Central is “hardwired” into the super-popular Maven 2. As such,
  it is being used by many Maven users of course, but also by Ivy, and
  even by Gradle users (those not familiar with Bintray’s ‘jcenter()’
  repo yet).

So you need to deploy your artifact into Maven Central, but it is somehow painful so Sync is better option.

ContentLicense: CC BY-SA 3.0

Title: Why sync bintray with maven central?


问:
Sidebar menu issue in my site
How Do I Bring The Drop-down Menu In Front Of Other Graphic?
I just applied this CSS class on my side bar it works perfect and things are normal in full screen mode

```<code>.MYfixed {position:fixed;-webkit-backface-visibility: hidden;}
</code>```

but when I collapsed my side bar the sidebar listing tag does not work perfectly.

what can I do?

Look at this image you can understand what I mean.

答:
Apply a higher z-index value to the HTML element that makes up the sidebar.

Watch for the z-index property of other elements in the body so you don't ruin other element's aesthetics, like modals.

Title: Sidebar menu issue in my site

Body:
How Do I Bring The Drop-down Menu In Front Of Other Graphic?
I just applied this CSS class on my side bar it works perfect and things are normal in full screen mode

.MYfixed {position:fixed;-webkit-backface-visibility: hidden;}

but when I collapsed my side bar the sidebar listing tag does not work perfectly.

what can I do?

Look at this image you can understand what I mean.


问:
How to get the current free disk space in Postgres?
I need to be sure that I have at least 1Gb of free disk space before start doing some work in my database. I'm looking for something like this:

```<code>select pg_get_free_disk_space();
</code>```

Is it possible? (I found nothing about it in docs).

PG: 9.3  & OS: Linux/Windows

答:
Here's a plpython2u implementation we've been using for a while.

-- NOTE this function is a security definer, so it carries the superuser permissions
-- even when called by the plebs.
-- (required so we can access the data_directory setting.)
CREATE OR REPLACE FUNCTION get_tablespace_disk_usage()
    RETURNS TABLE (
        path VARCHAR,
        bytes_free BIGINT,
        total_bytes BIGINT
    )
AS $$
import os

data_directory = plpy.execute("select setting from pg_settings where name='data_directory';")[0]['setting']
records = []

for t in plpy.execute("select spcname, spcacl, pg_tablespace_location(oid) as path from pg_tablespace"):
    if t['spcacl']:
        # TODO handle ACLs. For now only show public tablespaces.
        continue

    name = t['spcname']
    if name == 'pg_default':
        path = os.path.join(data_directory, 'default')
    elif name == 'pg_global':
        path = os.path.join(data_directory, 'global')
    else:
        path = t['path']

    # not all tablespaces actually seem to exist(?) in particular, pg_default.
    if os.path.exists(path):
        s = os.statvfs(path)
        total_bytes = s.f_blocks * s.f_frsize
        bytes_free = s.f_bavail * s.f_frsize

        records.append((path, bytes_free, total_bytes))

return records

$$ LANGUAGE plpython2u STABLE SECURITY DEFINER;
```

<p>Usage is something like:</p>

```SELECT path, bytes_free, total_bytes FROM get_tablespace_disk_usage();
```

Body:
I need to be sure that I have at least 1Gb of free disk space before start doing some work in my database. I'm looking for something like this:

select pg_get_free_disk_space();

Is it possible? (I found nothing about it in docs).

PG: 9.3  & OS: Linux/Windows

Body:
Here's a plpython2u implementation we've been using for a while.

-- NOTE this function is a security definer, so it carries the superuser permissions
-- even when called by the plebs.
-- (required so we can access the data_directory setting.)
CREATE OR REPLACE FUNCTION get_tablespace_disk_usage()
    RETURNS TABLE (
        path VARCHAR,
        bytes_free BIGINT,
        total_bytes BIGINT
    )
AS $$
import os

data_directory = plpy.execute("select setting from pg_settings where name='data_directory';")[0]['setting']
records = []

for t in plpy.execute("select spcname, spcacl, pg_tablespace_location(oid) as path from pg_tablespace"):
    if t['spcacl']:
        # TODO handle ACLs. For now only show public tablespaces.
        continue

    name = t['spcname']
    if name == 'pg_default':
        path = os.path.join(data_directory, 'default')
    elif name == 'pg_global':
        path = os.path.join(data_directory, 'global')
    else:
        path = t['path']

    # not all tablespaces actually seem to exist(?) in particular, pg_default.
    if os.path.exists(path):
        s = os.statvfs(path)
        total_bytes = s.f_blocks * s.f_frsize
        bytes_free = s.f_bavail * s.f_frsize

        records.append((path, bytes_free, total_bytes))

return records

$$ LANGUAGE plpython2u STABLE SECURITY DEFINER;

Usage is something like:

SELECT path, bytes_free, total_bytes FROM get_tablespace_disk_usage();


问:
Makefile Wildcards with different input and output names
I have a folder structure in my src folder, which I want to preserve in my obj folder, where all the .o files go. I don not want to use mkdir, since many problems arise with cross-platform use. Instead I did

```<code>$(OBJECTS) := $(patsubst %,obj/%,$(subst /,_,$(SOURCES)))
</code>```

The problem now is, that the input and output file names of the rule that creates those files are different, which means doing

```<code>$(OBJECTS): obj/%.o: %.cpp
    # whatever compile command
</code>```

no longer works, because for an example output of obj/Core_Graphics_Window.o the input is Core/Graphics/Window.cpp.

Can this still be done?

答:
(This is not another answer, just an explanation to kim366's comment).

Why does $(OBJECTS): $(SOURCES) not work?

That expands to

```<code>a.o b.o c.o : a.c b.c c.c
    compiler command
</code>```

This is not a rule that tells make how to create a.o from a.c, b.o from b.c and c.o from c.c

This is in fact three rules; it's equivalent to

```<code>a.o : a.c b.c c.c
    compiler command
b.o : a.c b.c c.c
    compiler command
c.o : a.c b.c c.c
    compiler command
</code>```

In general, you can have two kinds of rules in (GNU) make: explicit rules (where the list of dependencies is specified by hand) and pattern/suffix rules (where the list of dependencies is deduced). In both cases, the target is a single file. In fact, make has difficulties with commands that produce more than one file (source generators like lex, yacc, protobuf, etc).

For example, you can't tell make that protoc creates both a .cc and a .h file:

```<code>%.pb.cc %.pb.h : %.proto
    protoc .... $<
</code>```

This is two separate rules to make, and I've seen it launch two separate protoc processes (with the same command line) when building multiple jobs in parallel.

Body:
I have a folder structure in my src folder, which I want to preserve in my obj folder, where all the .o files go. I don not want to use mkdir, since many problems arise with cross-platform use. Instead I did

$(OBJECTS) := $(patsubst %,obj/%,$(subst /,_,$(SOURCES)))

The problem now is, that the input and output file names of the rule that creates those files are different, which means doing

$(OBJECTS): obj/%.o: %.cpp
    # whatever compile command

no longer works, because for an example output of obj/Core_Graphics_Window.o the input is Core/Graphics/Window.cpp.

Can this still be done?

Body:
(This is not another answer, just an explanation to kim366's comment).

Why does $(OBJECTS): $(SOURCES) not work?

That expands to

a.o b.o c.o : a.c b.c c.c
    compiler command

This is not a rule that tells make how to create a.o from a.c, b.o from b.c and c.o from c.c

This is in fact three rules; it's equivalent to

a.o : a.c b.c c.c
    compiler command
b.o : a.c b.c c.c
    compiler command
c.o : a.c b.c c.c
    compiler command

In general, you can have two kinds of rules in (GNU) make: explicit rules (where the list of dependencies is specified by hand) and pattern/suffix rules (where the list of dependencies is deduced). In both cases, the target is a single file. In fact, make has difficulties with commands that produce more than one file (source generators like lex, yacc, protobuf, etc).

For example, you can't tell make that protoc creates both a .cc and a .h file:

%.pb.cc %.pb.h : %.proto
    protoc .... $<

This is two separate rules to make, and I've seen it launch two separate protoc processes (with the same command line) when building multiple jobs in parallel.


问:
List gets empty on button event
Every time when the button event fired my list gets empty and starts adding items from first index. It is not retaining the old items added on previous click. I am trying to store ids of some element in my list on every button clicked and inserting them into hashset to avoid duplication. kindly help me out with this

Here is my code.

```<code> List<int> venues = new List<int>();
 HashSet<int> hashset = new HashSet<int>();

                id = Convert.ToInt32(Request.QueryString["id"].ToString());

                venues.Add(id);

                foreach (int item1 in venues)
                {

                    if (!hashset.Add(item1))
                    {
                        Response.Write("<script>alert('Duplicate Items');</script>");
                        break;
                    }

                    else
                    {

                        foreach (var items in venues)
                        {
                            con.Open();
                            SqlCommand cmd = con.CreateCommand();
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = "select * from Venues where VenueID = '" + items + "'";
                            cmd.ExecuteNonQuery();
                            DataTable dt = new DataTable();
                            SqlDataAdapter ds = new SqlDataAdapter(cmd);
                            ds.Fill(dt);
                            foreach (DataRow dr in dt.Rows)
                            {
                                Name = dr["Name"].ToString();
                                Address = dr["Address"].ToString();
                                Picture = dr["Picture"].ToString();
                                Price = dr["Price"].ToString();
                            }
                            con.Close();
                            if (Request.Cookies["aa"] == null)
                            {
                                Response.Cookies["aa"].Value = Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);

                            }
                            else
                            {
                                Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                            }
                        }
                    }
                }

            }
</code>```

答:
If this is the whole onClick event function, you should create the lists outside the scope of the function.
For example, create the lists in the Page_Load</p>

Title: List gets empty on button event

Body:
Every time when the button event fired my list gets empty and starts adding items from first index. It is not retaining the old items added on previous click. I am trying to store ids of some element in my list on every button clicked and inserting them into hashset to avoid duplication. kindly help me out with this

Here is my code.

 List<int> venues = new List<int>();
 HashSet<int> hashset = new HashSet<int>();

                id = Convert.ToInt32(Request.QueryString["id"].ToString());

                venues.Add(id);

                foreach (int item1 in venues)
                {

                    if (!hashset.Add(item1))
                    {
                        Response.Write("");
                        break;
                    }

                    else
                    {

                        foreach (var items in venues)
                        {
                            con.Open();
                            SqlCommand cmd = con.CreateCommand();
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = "select * from Venues where VenueID = '" + items + "'";
                            cmd.ExecuteNonQuery();
                            DataTable dt = new DataTable();
                            SqlDataAdapter ds = new SqlDataAdapter(cmd);
                            ds.Fill(dt);
                            foreach (DataRow dr in dt.Rows)
                            {
                                Name = dr["Name"].ToString();
                                Address = dr["Address"].ToString();
                                Picture = dr["Picture"].ToString();
                                Price = dr["Price"].ToString();
                            }
                            con.Close();
                            if (Request.Cookies["aa"] == null)
                            {
                                Response.Cookies["aa"].Value = Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);

                            }
                            else
                            {
                                Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + Name.ToString() + "," + Address.ToString() + "," + Picture.ToString() + "," + Price.ToString();
                                Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                            }
                        }
                    }
                }

            }


问:
Module that rotates each cell of a 3x3 array around the central cell (not a matrix rotation)
I want to rotate an array but not like a basic matrix rotation. If I have a 3x3 array, I want each of the cells to turn around the central cell.

Here is a 3x3 array:

```<code>import numpy as np

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

[[1 2 3]
 [4 5 6]
 [7 8 9]]
</code>```

I want for instance to rotate it by 45 degrees:

```<code>[[2 3 6]
 [1 5 9]
 [4 7 8]]
</code>```

I can't use scipy.ndimage.interpolation.rotate(tab,45) because it applies a basic matrix rotation and this is not what I want.

```<code>import numpy as np
from scipy import ndimage

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

ndimage.interpolation.rotate(tab,45)

[[0 0 0 0]
 [0 2 6 0]
 [0 4 8 0]
 [0 0 0 0]]
</code>```

Does anybody know how this can be achieved?

答:
Your almost had it just use this:

```<code>ndimage.interpolation.rotate(tab,45,reshape=False,mode='nearest')
</code>```

the thing is you need to force the method to not reshape your matrix and also use nearest number as fill in the blank instead of zeros.

The problem with zeros is that some numbers (the ones in the corners) become out of boundaries when you rotate the matrix so you need to "predict" those missing corners by nearest like precised here

output:

```<code>[[2 3 6]
 [1 5 9]
 [4 7 8]]
</code>```

rotate it again it gives:

```<code>[[3 6 9]
 [2 5 8]
 [1 4 7]]
</code>```

etc..

Body:
I want to rotate an array but not like a basic matrix rotation. If I have a 3x3 array, I want each of the cells to turn around the central cell.

Here is a 3x3 array:

import numpy as np

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

[[1 2 3]
 [4 5 6]
 [7 8 9]]

I want for instance to rotate it by 45 degrees:

[[2 3 6]
 [1 5 9]
 [4 7 8]]

I can't use scipy.ndimage.interpolation.rotate(tab,45) because it applies a basic matrix rotation and this is not what I want.

import numpy as np
from scipy import ndimage

tab = np.array([[1,2,3],[4,5,6],[7,8,9]])

ndimage.interpolation.rotate(tab,45)

[[0 0 0 0]
 [0 2 6 0]
 [0 4 8 0]
 [0 0 0 0]]

Does anybody know how this can be achieved?

Body:
Your almost had it just use this:

ndimage.interpolation.rotate(tab,45,reshape=False,mode='nearest')

the thing is you need to force the method to not reshape your matrix and also use nearest number as fill in the blank instead of zeros.

The problem with zeros is that some numbers (the ones in the corners) become out of boundaries when you rotate the matrix so you need to "predict" those missing corners by nearest like precised here

output:

[[2 3 6]
 [1 5 9]
 [4 7 8]]

rotate it again it gives:

[[3 6 9]
 [2 5 8]
 [1 4 7]]

etc..


问:
JQuery - Document width/height - Different values from different browsers
```<code>var maskWidth = $(window).width();
alert(maskWidth);
</code>```

I get 1263 from chrome and firefox (which is 1280 in fact, but with scroll it write a less value). IE print 1259.

How can I fix this problems with JQuery?

答:
This isn't a problem with jQuery, it is returning the value of the displayable portion of your website.

You need to be looking at .innerWidth() here which will return results closer to which you require.

ContentLicense: CC BY-SA 2.5

Body:
var maskWidth = $(window).width();
alert(maskWidth);

I get 1263 from chrome and firefox (which is 1280 in fact, but with scroll it write a less value). IE print 1259.

How can I fix this problems with JQuery?


问:
FactoryGirl: attributes_for not giving me associated attributes
I have a Code model factory like this:

```<code>Factory.define :code do |f|
    f.value "code"
    f.association :code_type
    f.association(:codeable, :factory => :portfolio)
end
</code>```

But when I test my controller with a simple test_should_create_code like this:

```<code>  test "should create code" do
    assert_difference('Code.count') do
      post :create, :code => Factory.attributes_for(:code)
    end
    assert_redirected_to code_path(assigns(:code))
  end
</code>```

... the test fails.  The new record is not created.

In the console, it seems that attributes_for does not return all required attributes like the create does.

```<code>rob@compy:~/dev/my_rails_app$ rails console test
Loading test environment (Rails 3.0.3)
irb(main):001:0> Factory.create(:code)
=> #<Code id: 1, code_type_id: 1, value: "code", codeable_id: 1, codeable_type: "Portfolio", created_at: "2011-02-24 10:42:20", updated_at: "2011-02-24 10:42:20">
irb(main):002:0> Factory.attributes_for(:code)
=> {:value=>"code"}
</code>```

Any ideas?

Thanks,

答:
Here's another way. You probably want to omit the id, created_at and updated_at attributes.

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys

Limitations:

It does not generate attributes for HMT and HABTM associations (as these associations are stored in a join table, not an actual attribute).

Association strategy in the factory must be create, as in association :user, strategy: :create. This strategy can make your factory very slow if you don't use it wisely.

Body:
I have a Code model factory like this:

Factory.define :code do |f|
    f.value "code"
    f.association :code_type
    f.association(:codeable, :factory => :portfolio)
end

But when I test my controller with a simple test_should_create_code like this:

  test "should create code" do
    assert_difference('Code.count') do
      post :create, :code => Factory.attributes_for(:code)
    end
    assert_redirected_to code_path(assigns(:code))
  end

... the test fails.  The new record is not created.

In the console, it seems that attributes_for does not return all required attributes like the create does.

rob@compy:~/dev/my_rails_app$ rails console test
Loading test environment (Rails 3.0.3)
irb(main):001:0> Factory.create(:code)
=> #
irb(main):002:0> Factory.attributes_for(:code)
=> {:value=>"code"}

Any ideas?

Thanks,


问:
Get all mondays in the year
I always have problems figuring out dates functions

```<code>var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
</code>```

I am using this function to get all mondays in a month, current month.

How can I adapt this code to get all remaining mondays in the year?

答:
var x = new Date();
//set the financial year starting date
x.setFullYear(2016, 03, 01);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2017, 03, 01);
var j = 1;
var count = 0;
//getting the all mondays in a financial year
for (var i = 0; x < y; i += j) {
  if (x.getDay() === 1) {
    document.write("Date : " + x.getDate() + "/" +
      (x.getMonth() + 1) + "
");
    x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
    j = 7;
    count++;
  } else {
    j = 1;
    x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
  }
}
document.write("total mondays : " + count + "
");```

Title: Get all mondays in the year

Body:
I always have problems figuring out dates functions

var d = new Date(),
    month = d.getMonth(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === month) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}

I am using this function to get all mondays in a month, current month.

How can I adapt this code to get all remaining mondays in the year?

Body:
var x = new Date();
//set the financial year starting date
x.setFullYear(2016, 03, 01);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2017, 03, 01);
var j = 1;
var count = 0;
//getting the all mondays in a financial year
for (var i = 0; x < y; i += j) {
  if (x.getDay() === 1) {
    document.write("Date : " + x.getDate() + "/" +
      (x.getMonth() + 1) + "<br>");
    x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
    j = 7;
    count++;
  } else {
    j = 1;
    x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
  }
}
document.write("total mondays : " + count + "<br>");


问:
Specifying a custom DateTime format when serializing with Json.Net
I am developing an API to expose some data using ASP.NET Web API.

In one of the API, the client wants us to expose the date in yyyy-MM-dd format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.

One of the solution that I could think of is to create a custom JsonConverter and then put that to the property I need to do the custom formatting

e.g.

```<code>class ReturnObjectA
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get;set;}
}
</code>```

Just wondering if there is some other easy way of doing that.

答:
You could use this approach:

```<code>public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}
</code>```

And use it this way:

```<code>class ReturnObjectA
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}
</code>```

The DateTimeFormat string uses the .NET format string syntax described here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

ContentLicense: CC BY-SA 4.0

Body:
I am developing an API to expose some data using ASP.NET Web API.

In one of the API, the client wants us to expose the date in yyyy-MM-dd format. I don't want to change the global settings (e.g. GlobalConfiguration.Configuration.Formatters.JsonFormatter) for that since it is very specific to this client. And I do developing that in a solution for multiple clients.

One of the solution that I could think of is to create a custom JsonConverter and then put that to the property I need to do the custom formatting

e.g.

class ReturnObjectA
{
    [JsonConverter(typeof(CustomDateTimeConverter))]
    public DateTime ReturnDate { get;set;}
}

Just wondering if there is some other easy way of doing that.

Body:
You could use this approach:

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

And use it this way:

class ReturnObjectA
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
    public DateTime ReturnDate { get;set;}
}

The DateTimeFormat string uses the .NET format string syntax described here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings


问:
Jackson JSON library: how to instantiate a class that contains abstract fields
I want to convert a JSON string into java object, but the class of this object contains abstract fields, which Jackson can't instantiate, and doesn't produce the object. What is the easiest way to tell it about some default implementation of an abstract class, like

```<code>setDefault(AbstractAnimal.class, Cat.class);
</code>```

or to decide about the implementation class based on JSON attribute name, eg. for JSON object:

```<code>{
    ...
    cat: {...}
    ...
}
</code>```

i would just wite:

```<code>setImpl("cat", Cat.class);
</code>```

I know it's possible in Jackson to embed class information inside JSON, but I don't want to complicate the JSON format I use. I want to decide what class to use just by setting default implementation class, or by the attribute name ('cat') - like in XStream library, where you write:

```<code>xStream.alias("cat", Cat.class);
</code>```

Is there a way to do so, especially in one line, or does it require some more code?

答:
A full fledged answer with a very clear example can be found here: https://stackoverflow.com/a/30386694/584947

Jackson refers to this as Polymorphic Deserialization.

It definitely helped me with my issue. I had an abstract class that I was saving in a database and needed to unmarshal it to a concrete instance of a class (understandably).

It will show you how to properly annotate the parent abstract class and how to teach jackson how to pick among the available sub-class candidates at run-time when unmarshaling.

Body:
I want to convert a JSON string into java object, but the class of this object contains abstract fields, which Jackson can't instantiate, and doesn't produce the object. What is the easiest way to tell it about some default implementation of an abstract class, like

setDefault(AbstractAnimal.class, Cat.class);

or to decide about the implementation class based on JSON attribute name, eg. for JSON object:

{
    ...
    cat: {...}
    ...
}

i would just wite:

setImpl("cat", Cat.class);

I know it's possible in Jackson to embed class information inside JSON, but I don't want to complicate the JSON format I use. I want to decide what class to use just by setting default implementation class, or by the attribute name ('cat') - like in XStream library, where you write:

xStream.alias("cat", Cat.class);

Is there a way to do so, especially in one line, or does it require some more code?


问:
Is it posible to write greasemonkey script or add-on for firefox to automaticly add security exception?
Is it posible to write greasemonkey script or add-on for firefox to automaticly add security exception ?

I have plenty of dumb users and I really need to automate this for two of my intranet pages which have wrong certificates.

Thank you very much.

答: I hope not as that would be a huge security hole ! You should create correct certificates for your sites instead. Create a CA and install the public CA certificate on your user's browser so the site certificates will be valid. There are plenty of articles and howtos found via Google that explain how to roll your own CA and create certificates for your sites.


问:
SQL Server and Microsoft.ACE.OLEDB.12.0
I am getting the following:

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error. Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

When I execute the following from a Stored Procedure in SQLServer -

```<code>SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')
</code>```

I have been through all the threads I could find on this topic - but still am having the problem

I have verified that:

The 64 bit Microsoft.ACE.OLEDB.12.0 drivers are loaded

Ad Hoc Distributed Queries is set to 1

Dynamic Parameter and Allow Inprocess are both set to 1

Changed MSSQL to run under my account

The account that is running MSSQL and the account I am using both have full access to C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp

Any help would be appreciated. -wmm

答:
Sadly, OPENROWSET is know to be buggy for ACE.  So there are a bunch of different things to try when trying to tweak it.  Adding and removing a few of the following suggestions will hopefully do it for you:

1) xlsx files need to be called with Excel 12.0 Xml;

2) HDR=YES;  Tells if a header record is present.  It'll crash if there is and you have numerics.  Change to NO if there is no header.

3) IMEX=1;   This allows for mixed numeric and text fields. In case people start mixing letters in with your numerics.

4) There can be registry problems based on ACE 12.0 vs ACE 14.0.  Double check your version.

5) Lastly, weirder than weird... OPENROWSET crashes when you have comments (or don't have comments).  If you have --comment, by putting a space after the dashes, -- comment it sometimes helps.  So if you have comments, try removing them or rearranging them and you may get a surprise.  (I know... it's really a sad state of affairs.)

```<code>SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0 Xml;HDR=YES;IMEX=1;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')
</code>```

Anyway, since OPENROWSET can be a bit unstable, you may want to import data using a different approach with staging tables, or csv files, etc.  But if you get it working, it can be quite nice.

Hope that helps :)

Title: SQL Server and Microsoft.ACE.OLEDB.12.0

Body:
I am getting the following:

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error. Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

When I execute the following from a Stored Procedure in SQLServer -

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')

I have been through all the threads I could find on this topic - but still am having the problem

I have verified that:

The 64 bit Microsoft.ACE.OLEDB.12.0 drivers are loaded

Ad Hoc Distributed Queries is set to 1

Dynamic Parameter and Allow Inprocess are both set to 1

Changed MSSQL to run under my account

The account that is running MSSQL and the account I am using both have full access to C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp

Any help would be appreciated. -wmm

Body:
Sadly, OPENROWSET is know to be buggy for ACE.  So there are a bunch of different things to try when trying to tweak it.  Adding and removing a few of the following suggestions will hopefully do it for you:

1) xlsx files need to be called with Excel 12.0 Xml;

2) HDR=YES;  Tells if a header record is present.  It'll crash if there is and you have numerics.  Change to NO if there is no header.

3) IMEX=1;   This allows for mixed numeric and text fields. In case people start mixing letters in with your numerics.

4) There can be registry problems based on ACE 12.0 vs ACE 14.0.  Double check your version.

5) Lastly, weirder than weird... OPENROWSET crashes when you have comments (or don't have comments).  If you have --comment, by putting a space after the dashes, -- comment it sometimes helps.  So if you have comments, try removing them or rearranging them and you may get a surprise.  (I know... it's really a sad state of affairs.)

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0 Xml;HDR=YES;IMEX=1;Database=c:\Users\v-bimoss\Source\Workspaces\External\Onesite\URLoadDB\Templates\T1-Current.xlsx', 'SELECT * FROM [Sheet1$]')

Anyway, since OPENROWSET can be a bit unstable, you may want to import data using a different approach with staging tables, or csv files, etc.  But if you get it working, it can be quite nice.

Hope that helps :)


问:
Autocomplete Quotes - Get out from within Quotes and Move the Cursor after the Closing Cursor
I like that it autocompletes single and double quotes, but how do I "get out" from within the quotes and move the cursor to the right side of the closing quote?

Example, I start typing:

string = 'Hello World'
```

After I'm done with the letter d, my cursor is stuck there.

So is there a fancy way of hitting Space so that I can move the cursor to the right side out of the closing quote?

答: The best answer is Ctrl+Shift+Enter which completes the current statement and takes you to the next line.

Body:
I like that it autocompletes single and double quotes, but how do I "get out" from within the quotes and move the cursor to the right side of the closing quote?

Example, I start typing:

string = 'Hello World'

After I'm done with the letter d, my cursor is stuck there.

So is there a fancy way of hitting Space so that I can move the cursor to the right side out of the closing quote?


问:
How to create a new div row after every 3rd product in liquid?
How do I wrap my products in a new

 after every 3rd product? I have looked at using the cycle iteration tag but can't quite figure out how to implement properly in my code.

```<code>        {% for product in collection.products %}
            <!-- product -->
            <div class="col-xs-6 col-md-4 product">
                <a href="{{product.url}}" class="product-link"></a>
                <!-- / product-link -->
                <img src="{{ product.featured_image.src | img_url: '480x480' }}" alt="">
                <!-- / product-image -->

                <!-- product-details -->
                <div class="product-details">
                    <h3 class="product-title">{{product.title}}</h3>
                    <h6 class="product-price"> {{ product.price | money }}</h6>
                </div><!-- / product-details -->
            </div><!-- / product -->
          {% endfor %}
</code>```

答:
You might use a modulo calculation applied on forloop.index then apply an if statement according to modulo result.

```<code>{% assign modulo = forloop.index | modulo : 3 %}
{% if modulo == 0 %}
<div class=«row»>
{% endif %}
</code>```

https://help.shopify.com/themes/liquid/filters/math-filters#modulo

Body:
How do I wrap my products in a new

 after every 3rd product? I have looked at using the cycle iteration tag but can't quite figure out how to implement properly in my code.

        {% for product in collection.products %}

{{product.title}}

 {{ product.price | money }}

          {% endfor %}

Body:
You might use a modulo calculation applied on forloop.index then apply an if statement according to modulo result.

{% assign modulo = forloop.index | modulo : 3 %}
{% if modulo == 0 %}
<div class=«row»>
{% endif %}

https://help.shopify.com/themes/liquid/filters/math-filters#modulo


答: If you only want to use it on 3x3 arrays, a simple solution would be to list the indexes in a clockwise/anticlockwise order (eg: [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0), (1, 0)]), then for the rotations you just shift the values according to the list indexes (by degrees/45° places).

Title: Module that rotates each cell of a 3x3 array around the central cell (not a matrix rotation)


问:
Applying a single onChange to all input boxes
An example I came across:

I recently came across the following example:

```<code>activate(event) {
  console.log(event.target.value);
}

render() {
  return (
    <div onChange={this.activate.bind(this)}>
      <input type="radio" value="yes" name="confirm"/> Yes
      <input type="radio" value="no" name="confirm"/> No
    </div>
   )
}
</code>```

This allows an onChange handler to be applied to a parent div of radio buttons rather than each individual radio button.

My questions about this:

Is there any reason why the onChange attribute would be specifically applied to a group of radio buttons and not to groups of other form elements?

Why not place all form fields inside a single div or form element and have only one onChange attribute?

Is this specific to ReactJS, or can something similar be done in basic JavaScript?

答:
I'm not a pro in React but i could say a few things :

You can put onChange on every types of inputs, it's working with select, text, checkboxes.

It's better to use onChange or any listeners directly on the input itself, why ? Because in this function you can easily refer to your input with the "event" params, like that :

function handleChange(event) {
   var value = event.target.value;
}

If you don't do it, you have to refer to the right input and it can be really a mess.

Body:
An example I came across:

I recently came across the following example:

activate(event) {
  console.log(event.target.value);
}

render() {
  return (

      <input type="radio" value="yes" name="confirm"/> Yes
      <input type="radio" value="no" name="confirm"/> No

   )
}

This allows an onChange handler to be applied to a parent div of radio buttons rather than each individual radio button.

My questions about this:

Is there any reason why the onChange attribute would be specifically applied to a group of radio buttons and not to groups of other form elements?

Why not place all form fields inside a single div or form element and have only one onChange attribute?

Is this specific to ReactJS, or can something similar be done in basic JavaScript?


问:
PHP class: Global variable as property in class
I have a global variable outside my class = $MyNumber;

How do I declare this as a property in myClass?

For every method in my class, this is what I do:

```<code>class myClass() {

    private function foo() {
         $privateNumber = $GLOBALS['MyNumber'];
    }

}
</code>```

I want this

```<code>class myClass() {

    //What goes here?
    var $classNumber = ???//the global $MyNumber;

    private function foo() {
         $privateNumber = $this->classNumber;
    }

}
</code>```

EDIT: I want to create a variable based on the global $MyNumber but

 modified before using it in the methods

something like: var $classNumber = global $MyNumber + 100;

答:
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible.  The key is the part where you assign by reference in the constructor.

```<code>$GLOBALS = array(
    'MyNumber' => 1
);

class Foo {
    protected $glob;

    public function __construct() {
        global $GLOBALS;
        $this->glob =& $GLOBALS;
    }

    public function getGlob() {
        return $this->glob['MyNumber'];
    }
}

$f = new Foo;

echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
</code>```

The output will be

```<code>1
2
</code>```

which indicates that it's being assigned by reference, not value.

As I said, it will be a nightmare to debug, so you really shouldn't do this.  Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.

Body:
I have a global variable outside my class = $MyNumber;

How do I declare this as a property in myClass?

For every method in my class, this is what I do:

class myClass() {

    private function foo() {
         $privateNumber = $GLOBALS['MyNumber'];
    }

}

I want this

class myClass() {

    //What goes here?
    var $classNumber = ???//the global $MyNumber;

    private function foo() {
         $privateNumber = $this->classNumber;
    }

}

EDIT: I want to create a variable based on the global $MyNumber but

 modified before using it in the methods

something like: var $classNumber = global $MyNumber + 100;

Body:
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible.  The key is the part where you assign by reference in the constructor.

$GLOBALS = array(
    'MyNumber' => 1
);

class Foo {
    protected $glob;

    public function __construct() {
        global $GLOBALS;
        $this->glob =& $GLOBALS;
    }

    public function getGlob() {
        return $this->glob['MyNumber'];
    }
}

$f = new Foo;

echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";

The output will be

1
2

which indicates that it's being assigned by reference, not value.

As I said, it will be a nightmare to debug, so you really shouldn't do this.  Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.


问:
Intellij 15 + Github - cannot clone repository, getting "Repository Test has Failed" error
I have Intellij 15 and a Github account, and I'm trying to unite the two.  I went into settings -> Version Control, and added Github with the Host and username and password.  When I click "Test" - it works.

I also have installed the GitHub executable, and added it to the settings as well, and that test was successful as well.

Then I go to my project, select VCS from the top menu, then go to "Checkout from Version Control" ---> "GitHub".  It gives me a "Clone Repository Dialog".

This is when things get interesting.  In that dialog, it shows "Git Repository URL" as "-------------------------------" - yes, a whole bunch of dashes, and the error at the bottom is "Repository URL is a malformed URL or non-existent directory"...  Now - I have not found any settings where I can specify it outside of this dialog box, so I don't know where it's taking the URL from...

I enter the correct URL, parent directory, and Directory Name...  Then I click on "Test".  And it gives me "Repository test has failed".  Actually, it gives me that same error regardless of what's in the "Git Repository URL" from that point on - even when I put a bunch of gibberish - it still gives the Test Has failed error.

I have also tried going to "Checkout from Version Control" ---> "Git" - with same results.

I have looked online at different forums and tutorials, and nothing seems to help.  Any advice would be greatly appreciated!!!

Thank you!

Setup pics - tests successful in the setup:

答:
I was also having the same issues with IntelliJ and I tried following:

To Solve this problem, Browse to Git location through a web browser:

Click on Clone button i.e. 2nd menu button on left

Now click the fully qualified link mentioned in the HTTP text box as below:

Fully qualified link

Now copy the above copied link to Clone Repository window in IntelliJ and try again. Test connection and It should be successful


问:
Hide MATLAB figure in the taskbar
I have created a lot of MATLAB figures, using the figure command. All these figures appear as icons in the taskbar (see below). I would like to hide these icons in the taskbar, but the figures themselves should still be visible on the screen.

Any solution for this?

答:
When you create the figures, set the WindowStyle property to docked:

```<code>for k = 1:10
    figure('WindowStyle','docked');
end
</code>```

This way all the figures will open in the main Matlab window, in different tabs, so you won't see them in the taskbar. See below the peek-view from the taskbar at the bottom that previews only 2 windows. Next, you can choose the 'float' option in the Figures window:

and then you can arrange all the figures as you wish:

Title: Hide MATLAB figure in the taskbar

Body:
When you create the figures, set the WindowStyle property to docked:

for k = 1:10
    figure('WindowStyle','docked');
end

This way all the figures will open in the main Matlab window, in different tabs, so you won't see them in the taskbar. See below the peek-view from the taskbar at the bottom that previews only 2 windows. Next, you can choose the 'float' option in the Figures window:

and then you can arrange all the figures as you wish:


问:
Choose entire list if random sample size is too large
In Python, we can randomly sample from a list as so:

```<code>>>> import random
>>> l = [1,2,3]
>>> random.sample(l,2)
[2, 3]
</code>```

However, if the sample size is larger than the list, it returns an error:

```<code>>>> random.sample(l,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 315, in sample
    raise ValueError("Sample larger than population")
ValueError: Sample larger than population
</code>```

Is there an option that will allow random.sample to choose the entire list if the sample size is larger than the list?

答:
There is no such option (see help(random.sample)), but you can always control what you pass:

```<code>random.sample(l, min(len(l),4))
</code>```

Body:
In Python, we can randomly sample from a list as so:

>>> import random
>>> l = [1,2,3]
>>> random.sample(l,2)
[2, 3]

However, if the sample size is larger than the list, it returns an error:

>>> random.sample(l,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/random.py", line 315, in sample
    raise ValueError("Sample larger than population")
ValueError: Sample larger than population

Is there an option that will allow random.sample to choose the entire list if the sample size is larger than the list?

Body:
There is no such option (see help(random.sample)), but you can always control what you pass:

random.sample(l, min(len(l),4))


答:
Just loop through the year instead of the month. The code is the same as yours, it works fine. just changed month -> year and getMonth() -> getYear()</p>

```<code>var d = new Date(),
    year = d.getYear(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getYear() === year) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}
</code>```

Title: Get all mondays in the year

Body:
Just loop through the year instead of the month. The code is the same as yours, it works fine. just changed month -> year and getMonth() -> getYear()

var d = new Date(),
    year = d.getYear(),
    mondays = [];

d.setDate(1);

// Get the first Monday in the month
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getYear() === year) {
    var pushDate = new Date(d.getTime());
    mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
    d.setDate(d.getDate() + 7);
}


问:
Array of structs - struct?
If we pass an array of structs as method parameter, in the method body do we have a reference to an array of structs, or a new array of structs?</p>

答:
When you declare an array of value types, .NET allocates memory on the heap not stack. So it is always referred to be its reference.

The only exception is stackalloc where a memory area is allocated on the stack and can be used unsafely and it is faster that heap access.

Title: Array of structs - struct?


问:
FactoryGirl: why does attributes_for omit some attributes?
I want to use FactoryGirl.attributes_for in controller testing, as in:

```<code>it "raise error creating a new PremiseGroup for this user" do
  expect {
    post :create, {:premise_group => FactoryGirl.attributes_for(:premise_group)}
  }.to raise_error(CanCan::AccessDenied)
end
</code>```

... but this doesn't work because #attributes_for omits the :user_id attribute.  Here is the difference between #create and #attributes_for:

```<code>>> FactoryGirl.create(:premise_group)
=> #<PremiseGroup id: 3, name: "PremiseGroup_4", user_id: 6, is_visible: false, is_open: false)
>> FactoryGirl.attributes_for(:premise_group)
=> {:name=>"PremiseGroup_5", :is_visible=>false, :is_open=>false}
</code>```

Note that the :user_id is absent from #attributes_for.  Is this the expected behavior?

FWIW, my factories file includes definitions for :premise_group and for :user:

```<code>FactoryGirl.define do
  ...
  factory :premise_group do
    sequence(:name) {|n| "PremiseGroup_#{n}"}
    user
    is_visible false
    is_open false
  end
  factory :user do
    ...
  end
end
</code>```

答:
Here is another way:

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys

Limitations:

It does not generate attributes for HMT and HABTM associations (as these associations are stored in a join table, not an actual attribute).

Association strategy in the factory must be create, as in association :user, strategy: :create. This strategy can make your factory very slow if you don't use it wisely.

Body:
I want to use FactoryGirl.attributes_for in controller testing, as in:

it "raise error creating a new PremiseGroup for this user" do
  expect {
    post :create, {:premise_group => FactoryGirl.attributes_for(:premise_group)}
  }.to raise_error(CanCan::AccessDenied)
end

... but this doesn't work because #attributes_for omits the :user_id attribute.  Here is the difference between #create and #attributes_for:

>> FactoryGirl.create(:premise_group)
=> #<PremiseGroup id: 3, name: "PremiseGroup_4", user_id: 6, is_visible: false, is_open: false)
>> FactoryGirl.attributes_for(:premise_group)
=> {:name=>"PremiseGroup_5", :is_visible=>false, :is_open=>false}

Note that the :user_id is absent from #attributes_for.  Is this the expected behavior?

FWIW, my factories file includes definitions for :premise_group and for :user:

FactoryGirl.define do
  ...
  factory :premise_group do
    sequence(:name) {|n| "PremiseGroup_#{n}"}
    user
    is_visible false
    is_open false
  end
  factory :user do
    ...
  end
end


答:
something like:</p>

```<code>random.sample(l) if len(l)<4 else random.sample(l, 4)
</code>```

Title: Choose entire list if random sample size is too large

Body:
something like:

random.sample(l) if len(l)<4 else random.sample(l, 4)


问:
Flex/AS3 - calling a function dynamically using a String?
Is it possible to call a function in AS3 using a string value as the function name e.g.

```<code>var functionName:String = "getDetails";

var instance1:MyObject = new MyObject();

instance1.functionName(); // I know this is so wrong, but it gets the point accross:)
</code>```

UPDATE

The answer from @Taskinoor on accessing a function is correct:

```<code>instance1[functionName]();
</code>```

And to access a property we would use:

```<code>instance1[propertyName]
</code>```

答:
```instance1[functionName]();```

Check this for some details.

Body:
Is it possible to call a function in AS3 using a string value as the function name e.g.

var functionName:String = "getDetails";

var instance1:MyObject = new MyObject();

instance1.functionName(); // I know this is so wrong, but it gets the point accross:)

UPDATE

The answer from @Taskinoor on accessing a function is correct:

instance1[functionName]();

And to access a property we would use:

instance1[propertyName]

Body:
instance1[functionName]();

Check this for some details.


问:
MongoDB encrypted field partial search
Is it possible to partial search(like/regex query) on an encrypted field in mongodb?

I have a field which contains encrypted email id. So in mongo the email some@email.com becomes 1bcuh6762jhjdSOME_ENCRYPTED_VALUE, now is it possible to do partial search on this encrypted value

答:
I came across a similar problem i resolved it, by creating hash of all possible values that were more than 3 letters. and created hash for all possible combinations, you can add the value to be set with pre('save').

In Schema You can create this function:

```<code>function createHash(next) {
    this.hashes = hash.createHashForField(this.text);
    debug(text);
    next();
}

mySchema.pre('save', createHash);
</code>```

A module for hashing hash.js

```<code>const hash = require('crypto');
const adler32 = require('adler32');
const crypto = require('crypto');
const _  = require('lodash');
adler32.register();

module.exports = Hash = {
    /**
     * This method creates hash of given text;
     * @param text - text to hash;
     */
    createHash: (text) => {
        return crypto.createHash('adler32').update(text, 'ascii').digest('hex');
    },
    /**
     *
     * @param text- text separated by spaces
     */
    createHashForText: (text) => {
        "use strict";
        text= text.toLowerCase();
        text= text.trim();
        let textSlices = _.flatten(text.split(' ').filter(x => x.length)
          .map((part) => {
            if (part.length < 3) {
                return part;
            }
            let nameSlices = [];
            for (let index = 2; index < part.length; index ++) {
                let n = part.slice(0, index+1);
                textSlices .push(n);
            }
            return textSlices ;
        }));

        return textSlices .map(n => Hash.createHash(n));
    }
}
</code>```

after that you can migrate all your records like this:

```<code>myModel.find({}).then(docs => {
    docs.forEach(doc => doc.save().catch(console.log))
})
</code>```

Now when search, You will have to use createHash function to make hash of keyword and search it in your database.

I hope this helps.

Title: MongoDB encrypted field partial search

Body:
I came across a similar problem i resolved it, by creating hash of all possible values that were more than 3 letters. and created hash for all possible combinations, you can add the value to be set with pre('save').

In Schema You can create this function:

function createHash(next) {
    this.hashes = hash.createHashForField(this.text);
    debug(text);
    next();
}

mySchema.pre('save', createHash);

A module for hashing hash.js

const hash = require('crypto');
const adler32 = require('adler32');
const crypto = require('crypto');
const _  = require('lodash');
adler32.register();

module.exports = Hash = {
    /**
     * This method creates hash of given text;
     * @param text - text to hash;
     */
    createHash: (text) => {
        return crypto.createHash('adler32').update(text, 'ascii').digest('hex');
    },
    /**
     *
     * @param text- text separated by spaces
     */
    createHashForText: (text) => {
        "use strict";
        text= text.toLowerCase();
        text= text.trim();
        let textSlices = _.flatten(text.split(' ').filter(x => x.length)
          .map((part) => {
            if (part.length < 3) {
                return part;
            }
            let nameSlices = [];
            for (let index = 2; index < part.length; index ++) {
                let n = part.slice(0, index+1);
                textSlices .push(n);
            }
            return textSlices ;
        }));

        return textSlices .map(n => Hash.createHash(n));
    }
}

after that you can migrate all your records like this:

myModel.find({}).then(docs => {
    docs.forEach(doc => doc.save().catch(console.log))
})

Now when search, You will have to use createHash function to make hash of keyword and search it in your database.

I hope this helps.


问:
R - how to get median and mean with string field?
I have a table (Class) like this:

```<code>County    Age.Group
Albany      0-5
Albany      10-15
Albany      10-15
new York    5-10
new York    5-10
new York    0-5
LI          0-5
LI          0-5
LI          0-5
</code>```

I need to get mean and median by County so I know I need to calculate the how many times Albany, New York, and LI appeared in the list and then use the mean and median function. I'm not sure how to do this as I get an error message when I use mean or median as that field is not an integer. Please help.....

答:
Not sure what is your exact expected output if it is not the following, it should help you somewhat forward.</p>

```<code>> # Load data
> df <- data.frame(County    = c("Albany", "Albany", "Albany", "new York",
+                                "new York", "new York", "LI", "LI", "LI"),
+                  Age.Group = c("0-5", "10-15", "10-15", "5-10", "5-10", "0-5",
+                                "0-5", "0-5", "0-5"), stringsAsFactors = FALSE)
>
> # Split the age by "-", resulting in a list
> age_split <- strsplit(df[, 2], split = "-", fixed = TRUE)
>
> # Turn numeric and take middle point of group, sapply turns back into vector
> df$Age.Group.Mean <- sapply(age_split, function(x) mean(as.numeric(x)))
>
> # Print df
> df
    County Age.Group Age.Group.Mean
1   Albany       0-5            2.5
2   Albany     10-15           12.5
3   Albany     10-15           12.5
4 new York      5-10            7.5
5 new York      5-10            7.5
6 new York       0-5            2.5
7       LI       0-5            2.5
8       LI       0-5            2.5
9       LI       0-5            2.5
>
> # Calculate what is needed
> aggregate(Age.Group.Mean ~ County, data = df, median)
    County Age.Group.Mean
1   Albany           12.5
2       LI            2.5
3 new York            7.5
> aggregate(Age.Group.Mean ~ County, data = df, mean)
    County Age.Group.Mean
1   Albany       9.166667
2       LI       2.500000
3 new York       5.833333
</code>```

Body:
I have a table (Class) like this:

County    Age.Group
Albany      0-5
Albany      10-15
Albany      10-15
new York    5-10
new York    5-10
new York    0-5
LI          0-5
LI          0-5
LI          0-5

I need to get mean and median by County so I know I need to calculate the how many times Albany, New York, and LI appeared in the list and then use the mean and median function. I'm not sure how to do this as I get an error message when I use mean or median as that field is not an integer. Please help.....

Body:
Not sure what is your exact expected output if it is not the following, it should help you somewhat forward.

> # Load data
> df <- data.frame(County    = c("Albany", "Albany", "Albany", "new York",
+                                "new York", "new York", "LI", "LI", "LI"),
+                  Age.Group = c("0-5", "10-15", "10-15", "5-10", "5-10", "0-5",
+                                "0-5", "0-5", "0-5"), stringsAsFactors = FALSE)
>
> # Split the age by "-", resulting in a list
> age_split <- strsplit(df[, 2], split = "-", fixed = TRUE)
>
> # Turn numeric and take middle point of group, sapply turns back into vector
> df$Age.Group.Mean <- sapply(age_split, function(x) mean(as.numeric(x)))
>
> # Print df
> df
    County Age.Group Age.Group.Mean
1   Albany       0-5            2.5
2   Albany     10-15           12.5
3   Albany     10-15           12.5
4 new York      5-10            7.5
5 new York      5-10            7.5
6 new York       0-5            2.5
7       LI       0-5            2.5
8       LI       0-5            2.5
9       LI       0-5            2.5
>
> # Calculate what is needed
> aggregate(Age.Group.Mean ~ County, data = df, median)
    County Age.Group.Mean
1   Albany           12.5
2       LI            2.5
3 new York            7.5
> aggregate(Age.Group.Mean ~ County, data = df, mean)
    County Age.Group.Mean
1   Albany       9.166667
2       LI       2.500000
3 new York       5.833333


问:
Time series Python ARIMA (testing,training and forecasting past dates available in data)
I understand that separating data into training and testing provides a way to evaluate how well a model will perform with unseen data.

I am training an ARIMA model and I have daily data from Oct.1 to Nov.22. I am interested in predicting some metric on Dec.14. Do I

Train on all available data and use predict('2015-11-23','2015-12-14') or

Split data into train and test to get performance metrics and use the model trained on training set (oct.1. to Nov.7) and do a predict that includes the test data as well dates into the future, e.g. predict('2015-11-8','2015-12-14').

I hope my question makes sense, happy to clarify if you find this confusing.

Thanks!

答:
If you use all your data for training, then you will not have any way of predicting how well you model generalises to unseen data. That is one problem of not using a test set.

The other problem you will have, is that you will not be able to try different configurations or model hyperparameters unless you decide on some way of doing cross validation.

Data series prediction is specially tricky for cross validation, but I would follow this post's recommendation regarding forward chaining. If you have 6 weeks of data, you could split your data into folds as follows:

fold 1 : training [w1], test [w2]

fold 2 : training [w1 w2], test [w3]

fold 3 : training [w1 w2 w3], test [w4]

fold 4 : training [w1 w2 w3 w4], test [w5]

fold 5 : training [w1 w2 w3 w4 w5], test [w6]


问:
DocuSign REST API ColdFusion: No Unique Envelope IDs
I have ColdFusion code which closely follows this and works fine--for the most part:

https://www.docusign.com/p/RESTAPIGuide/Content/Basic%20Scenarios/Creating%20an%20Envelope%20from%20a%20Template.htm

What I am trying to do is to query a database, find some matching users, and, in a query loop, send them to DocuSign to sign a Templated document. So far so good but what I need to be able to figure out is each user gets a unique EnvelopeID so that I can store them in database and later check the status of each EnvelopeID.

In my code, all returned EnvelopeIDs are the same. Maybe that's because they are all within the same session? I do get an status of 201--which means the Envelope is created.

I could share the code here but it will be long code--it's almost the same as the linked document above.

Any idea?

Thanks!

Update Oh, I have an idea--my loop is only catching the last returned EnvelopeID... will be back soon

答:
Never mind. In my query loop, during SQL UPDATES, I was simply missing the WHERE clause--the API was indeed returning unique EnvelopeIDs when executing within the loop.

Maybe it was the magic of StackOverflow which made me find a solution so quickly!
 ;)


问:
Dokku installation fails
I'm building provisioning ansible script. I often execute it for debug purpose during development. I use digital ocean ubuntu 14 droplet. For a long time everything was ok, but few days ago the same code stopped working (every execution is on a fresh droplet)

I have an error installing Dokku 0.4.3

```<code>--> Installing dokku
OK
deb https://packagecloud.io/dokku/dokku/ubuntu/ trusty main
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 dokku : Depends: docker-engine but it is not installable or
                  docker-engine-cs but it is not installable or
                  lxc-docker but it is not installable
E: Unable to correct problems, you have held broken packages.
</code>```

I use this command for installation:

```<code>wget -qO- https://raw.github.com/progrium/dokku/v0.4.3/bootstrap.sh | sudo DOKKU_TAG=v0.4.3 bash
</code>```

Do anybody know how to solve this issue? Thank's

答: After upgrading dokku to 0.9 issue was sovled</p>

Title: Dokku installation fails

Body:
I'm building provisioning ansible script. I often execute it for debug purpose during development. I use digital ocean ubuntu 14 droplet. For a long time everything was ok, but few days ago the same code stopped working (every execution is on a fresh droplet)

I have an error installing Dokku 0.4.3

--> Installing dokku
OK
deb https://packagecloud.io/dokku/dokku/ubuntu/ trusty main
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 dokku : Depends: docker-engine but it is not installable or
                  docker-engine-cs but it is not installable or
                  lxc-docker but it is not installable
E: Unable to correct problems, you have held broken packages.

I use this command for installation:

wget -qO- https://raw.github.com/progrium/dokku/v0.4.3/bootstrap.sh | sudo DOKKU_TAG=v0.4.3 bash

Do anybody know how to solve this issue? Thank's


问:
JsonPath used for Firebase Rules
I have the following data:

I have the following code:

```<code>   findChats(): Observable<any[]> {
        return this.af.database.list('/chat/', {
            query: {
                orderByChild: 'negativtimestamp'
            }
        }).map(items => {
            const filtered = items.filter(
                item => (item.memberId1 === this.me.uid || item.memberId2 === this.me.uid)
            );
            return filtered;
        });
    }
</code>```

If I use the JsonPath above ('/chat/') to access the database, it returns all matching rows, and then the code filters the results.

I do define the following Database Rule:

```<code>{
  "rules": {
      "chat": {
        "$key": {
            ".read": true
        }
      },
                ....
</code>```

Which I test in the Simulator with:

```<code>/chat/-Ko7w9XTtuRVN4p6CMp7/memberId
</code>```

And it finds a match.

Now when I run the code with this rule, I get:

Error: permission_denied at /chat: Client doesn't have permission to
  access the desired data

Question

Is the reason I cannot get the codes JsonPath to pass the rule because it's just /chat/?

In order for it to match the rule, does the codes JsonPath also have to contain a $key and memberId?

e.g. /chat/-Ko7w9XTtuRVN4p6CMp7/memberId

As you can see from my code, I am trying to get a list of filtered chats, and the code does not know what the $key values are. So is it impossible to apply a rule to the query that will only allow access to matching rows?

UPDATE

My question is similar to this one. I try the following with no success:

```<code>{
  "rules": {
      ".write": "auth != null",
      "chat": {
        "$id": {
            ".read": true
        }
      },
</code>```

UPDATE

I currently have the following rule, that works, but it's not adequate. It checks that the user is authenticated, but not that their auth.id equals either the memberId1 or memberId2.

```<code>{
  "rules": {
    "chat": {
      ".read": "auth != null",
      ".write": "auth != null"
    },
    "message": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}
</code>```

答:
The reason that you're getting the error is that Firebase rules cascade.

Please take a look at the "Read and Write Rules Cascade" and "Rules Are Not Filters" sections of this doc.

Cascading essentially means the following :-

.read and .write rules work from top-down, with shallower rules overriding deeper rules. If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it.

Therefore, if a rule restricts access ( or if the rule is absent ) to a higher node, then you can not access that node.

So, in your case, you can test it out by accessing the /chat/-Ko7w9XTtuRVN4p6CMp7/memberId path from your client code, and you'll see that it works.

The following example from the Firebase doc is a replica of your situation :-

Rules are applied in an atomic manner. That means that a read or write operation is failed immediately if there isn't a rule at that location or at a parent location that grants access. Even if every affected child path is accessible, reading at the parent location will fail completely. Consider this structure:

```<code>{
  "rules": {
    "records": {
      "rec1": {
        ".read": true
      },
      "rec2": {
        ".read": false
      }
    }
  }
}
</code>```

Without understanding that rules are evaluated atomically, it might
  seem like fetching the /records/ path would return rec1 but not rec2.
  The actual result, however, is an error:

Title: JsonPath used for Firebase Rules

Body:
I have the following data:

I have the following code:

   findChats(): Observable<any[]> {
        return this.af.database.list('/chat/', {
            query: {
                orderByChild: 'negativtimestamp'
            }
        }).map(items => {
            const filtered = items.filter(
                item => (item.memberId1 === this.me.uid || item.memberId2 === this.me.uid)
            );
            return filtered;
        });
    }

If I use the JsonPath above ('/chat/') to access the database, it returns all matching rows, and then the code filters the results.

I do define the following Database Rule:

{
  "rules": {
      "chat": {
        "$key": {
            ".read": true
        }
      },
                ....

Which I test in the Simulator with:

/chat/-Ko7w9XTtuRVN4p6CMp7/memberId

And it finds a match.

Now when I run the code with this rule, I get:

Error: permission_denied at /chat: Client doesn't have permission to
  access the desired data

Question

Is the reason I cannot get the codes JsonPath to pass the rule because it's just /chat/?

In order for it to match the rule, does the codes JsonPath also have to contain a $key and memberId?

e.g. /chat/-Ko7w9XTtuRVN4p6CMp7/memberId

As you can see from my code, I am trying to get a list of filtered chats, and the code does not know what the $key values are. So is it impossible to apply a rule to the query that will only allow access to matching rows?

UPDATE

My question is similar to this one. I try the following with no success:

{
  "rules": {
      ".write": "auth != null",
      "chat": {
        "$id": {
            ".read": true
        }
      },

UPDATE

I currently have the following rule, that works, but it's not adequate. It checks that the user is authenticated, but not that their auth.id equals either the memberId1 or memberId2.

{
  "rules": {
    "chat": {
      ".read": "auth != null",
      ".write": "auth != null"
    },
    "message": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}

Body:
The reason that you're getting the error is that Firebase rules cascade.

Please take a look at the "Read and Write Rules Cascade" and "Rules Are Not Filters" sections of this doc.

Cascading essentially means the following :-

.read and .write rules work from top-down, with shallower rules overriding deeper rules. If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it.

Therefore, if a rule restricts access ( or if the rule is absent ) to a higher node, then you can not access that node.

So, in your case, you can test it out by accessing the /chat/-Ko7w9XTtuRVN4p6CMp7/memberId path from your client code, and you'll see that it works.

The following example from the Firebase doc is a replica of your situation :-

Rules are applied in an atomic manner. That means that a read or write operation is failed immediately if there isn't a rule at that location or at a parent location that grants access. Even if every affected child path is accessible, reading at the parent location will fail completely. Consider this structure:

{
  "rules": {
    "records": {
      "rec1": {
        ".read": true
      },
      "rec2": {
        ".read": false
      }
    }
  }
}

Without understanding that rules are evaluated atomically, it might
  seem like fetching the /records/ path would return rec1 but not rec2.
  The actual result, however, is an error:


问:
Facebook callback error
i'm new on android development, got some problems on trying to implement a facebook login with FacebookSDK and didn't find what is needed to resolve this... When i click on the button, the callback returns the following error: SERVER_ERROR: [code] 1675030 [message]: Error performing query. [extra]: Errors while executing operation "ProxyAuthAppLoginStartQuery": At Query.proxy_auth_app_login_start: Failed to resolve field. Then a loading appears and nothing happens.

Here is the Activity code:

```<code>private static final String TAG_CANCEL = "1";
private static final String TAG_ERROR = "2";
public static CallbackManager callbackManager;
private LoginButton loginButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    callbackManager = CallbackManager.Factory.create();

    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call private method
            onFblogin();
        }
    });
}

private void onFblogin() {
    // Set permissions
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    System.out.println("Success");
                    GraphRequest.newMeRequest(
                            loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject json, GraphResponse response) {
                                    if (response.getError() != null) {
                                        // handle error
                                        System.out.println("ERROR");
                                    } else {
                                        System.out.println("Success");
                                        try {

                                            String jsonresult = String.valueOf(json);
                                            System.out.println("JSON Result" + jsonresult);

                                            String str_email = json.getString("email");
                                            String str_id = json.getString("id");
                                            String str_firstname = json.getString("first_name");
                                            String str_lastname = json.getString("last_name");

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }).executeAsync();
                }

                @Override
                public void onCancel() {
                    Log.d(TAG_CANCEL, "On cancel");
                }

                @Override
                public void onError(FacebookException error) {
                    Log.d(TAG_ERROR, error.toString());
                }
            });
}

private void goMainScreen() {
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |
 Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
 data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
</code>```

and the Manifest code:

```<code><?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.breno.tcc">

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar" />

        <meta-data android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id"/>
    </application>

     </manifest>
</code>```

Thanks for the help!

答: Found the problem, i was setting the app id with the wrong value.</p>

Title: Facebook callback error

Body:
i'm new on android development, got some problems on trying to implement a facebook login with FacebookSDK and didn't find what is needed to resolve this... When i click on the button, the callback returns the following error: SERVER_ERROR: [code] 1675030 [message]: Error performing query. [extra]: Errors while executing operation "ProxyAuthAppLoginStartQuery": At Query.proxy_auth_app_login_start: Failed to resolve field. Then a loading appears and nothing happens.

Here is the Activity code:

private static final String TAG_CANCEL = "1";
private static final String TAG_ERROR = "2";
public static CallbackManager callbackManager;
private LoginButton loginButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    callbackManager = CallbackManager.Factory.create();

    setContentView(R.layout.activity_login);

    loginButton = (LoginButton) findViewById(R.id.login_button);

    loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Call private method
            onFblogin();
        }
    });
}

private void onFblogin() {
    // Set permissions
    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    System.out.println("Success");
                    GraphRequest.newMeRequest(
                            loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject json, GraphResponse response) {
                                    if (response.getError() != null) {
                                        // handle error
                                        System.out.println("ERROR");
                                    } else {
                                        System.out.println("Success");
                                        try {

                                            String jsonresult = String.valueOf(json);
                                            System.out.println("JSON Result" + jsonresult);

                                            String str_email = json.getString("email");
                                            String str_id = json.getString("id");
                                            String str_firstname = json.getString("first_name");
                                            String str_lastname = json.getString("last_name");

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }).executeAsync();
                }

                @Override
                public void onCancel() {
                    Log.d(TAG_CANCEL, "On cancel");
                }

                @Override
                public void onError(FacebookException error) {
                    Log.d(TAG_ERROR, error.toString());
                }
            });
}

private void goMainScreen() {
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK |
 Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
 data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

and the Manifest code:

<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.breno.tcc">

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar" />

        <meta-data android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id"/>
    </application>

     </manifest>

Thanks for the help!


问:
compare block helper for handlebars
i working in code to compare values using block helper but the problem every time i run this code i get this error massage on my webpage view

```<code>Error: Missing helper: "compare"
    at Object.<anonymous> (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js:19:13)
    at Object.eval (eval at createFunctionContext (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23),
    <anonymous>:8:91)
    at main (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/runtime.js:175:32)
    at ret (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/runtime.js:178:12)
    at ret (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
    at ExpressHandlebars._renderTemplate (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/express-handlebars/lib/express-handlebars.js:247:12)
    at ExpressHandlebars.<anonymous> (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/express-handlebars/lib/express-handlebars.js:173:21)
</code>```

my index.hbs file

```<code>{{#compare pageCount ">" 1 }}
  <ul class="pagination"></ul>
    {{#compare  currentPage ">" 1  }}

       <li><a href="/?page=1"> «</a></li>
    {{/compare}}

{{/compare}}
</code>```

my auth.js file

```<code>res.render('index', {x:"1888", "personList": personList,data: data, pageSize: pageSize, pageCount: pageCount,currentPage: currentPage});
</code>```

my app.js file

```<code>const exphbs     = require('express-handlebars');
const hbs = exphbs.create({
  // Specify helpers which are only registered on this instance.
  helpers: {
    foo: function () { return 'FOO!'; },
    extname: ".hbs",
    compare: function(lvalue, rvalue, options) {

      if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

      var operator = options.hash.operator || "==";

      var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
      }

      if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

      var result = operators[operator](lvalue,rvalue);

      if( result ) {
        return options.fn(this);
      } else {
        return options.inverse(this);
      }

    }

  }
});

//For Handlebars
app.set('views', './app/views')
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
</code>```

where's the wrong ?

答:
You have a small mistake at app.js file

```<code>const exphbs     = require('express-handlebars');
const hbs = exphbs.create({
//...
});

//For Handlebars
app.set('views', './app/views');
app.engine('.hbs', hbs.engine); // <===== Use `hbs.engine`
app.set('view engine', '.hbs');
</code>```

Title: compare block helper for handlebars

Body:
i working in code to compare values using block helper but the problem every time i run this code i get this error massage on my webpage view

Error: Missing helper: "compare"
    at Object.<anonymous> (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js:19:13)
    at Object.eval (eval at createFunctionContext (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23),
    <anonymous>:8:91)
    at main (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/runtime.js:175:32)
    at ret (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/runtime.js:178:12)
    at ret (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
    at ExpressHandlebars._renderTemplate (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/express-handlebars/lib/express-handlebars.js:247:12)
    at ExpressHandlebars.<anonymous> (/opt/lampp/htdocs/x/chessMult/regtest/using-passport-with-sequelize-and-mysql-master/node_modules/express-handlebars/lib/express-handlebars.js:173:21)

my index.hbs file

{{#compare pageCount ">" 1 }}

    {{#compare  currentPage ">" 1  }}

 «

    {{/compare}}

{{/compare}}

my auth.js file

res.render('index', {x:"1888", "personList": personList,data: data, pageSize: pageSize, pageCount: pageCount,currentPage: currentPage});

my app.js file

const exphbs     = require('express-handlebars');
const hbs = exphbs.create({
  // Specify helpers which are only registered on this instance.
  helpers: {
    foo: function () { return 'FOO!'; },
    extname: ".hbs",
    compare: function(lvalue, rvalue, options) {

      if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

      var operator = options.hash.operator || "==";

      var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
      }

      if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

      var result = operators[operator](lvalue,rvalue);

      if( result ) {
        return options.fn(this);
      } else {
        return options.inverse(this);
      }

    }

  }
});

//For Handlebars
app.set('views', './app/views')
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');

where's the wrong ?

Body:
You have a small mistake at app.js file

const exphbs     = require('express-handlebars');
const hbs = exphbs.create({
//...
});

//For Handlebars
app.set('views', './app/views');
app.engine('.hbs', hbs.engine); // <===== Use `hbs.engine`
app.set('view engine', '.hbs');


问:
SQL: How to get the element from a delimited string by its index?
I have this function (credit: searchsqlserver):

```<code>CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO
</code>```

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

```<code>select * from fnSplit('1,22,333', ',')    --   returns 1 22 333
</code>```

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

```<code>select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1
</code>```

答:
First off, looping splits are not efficient.

Example with an Index Filter

```<code>Select *
 From [dbo].[udf-Str-Parse-8K]('1 22 333 444 5555 666', ' '  )
 Where RetSeq=3
</code>```

Returns

```<code>RetSeq  RetVal
3       333
</code>```

Example without an Index Filter

```<code>Select *
 From [dbo].[udf-Str-Parse-8K]('1 22 333 444 5555 666', ' '  )
</code>```

Returns

```<code>RetSeq  RetVal
1       1
2       22
3       333
4       444
5       5555
6       666
</code>```

The UDF used

```<code>CREATE FUNCTION [dbo].[udf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
</code>```

Body:
I have this function (credit: searchsqlserver):

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

select * from fnSplit('1,22,333', ',')    --   returns 1 22 333

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1

Body:
First off, looping splits are not efficient.

Example with an Index Filter

Select *
 From [dbo].[udf-Str-Parse-8K]('1 22 333 444 5555 666', ' '  )
 Where RetSeq=3

Returns

RetSeq  RetVal
3       333

Example without an Index Filter

Select *
 From [dbo].[udf-Str-Parse-8K]('1 22 333 444 5555 666', ' '  )

Returns

RetSeq  RetVal
1       1
2       22
3       333
4       444
5       5555
6       666

The UDF used

CREATE FUNCTION [dbo].[udf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')