问:
Carousel effect using android-supportv4.viewpager
I need an example of view pager with carousel effect.I've searched through internet but I couldn't find any example.So , have you done anything like this before ? Do you have any examples that I can examine.

答:
You need:

activity_main

item

Custom Fragment

Custom LinearLayout

CustomPagerAdapter

Activity

I use this code:

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:attrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.thedeveloperworldisyours.carouselviewpager.MainActivity">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_view_pager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

</RelativeLayout>
</code>```

item

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <com.thedeveloperworldisyours.carouselviewpager.CustomLinearLayout
        android:id="@+id/item_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/item_size_text" />

        <Button
            android:id="@+id/item_content"
            android:layout_width="230dp"
            android:layout_height="120dp"
            android:background="@android:color/black"/>
    </com.thedeveloperworldisyours.carouselviewpager.CustomLinearLayout>
</LinearLayout>
</code>```

Custom Fragment

```<code>public class CustomFragment extends Fragment {

    public static Fragment newInstance(Activity context, int position, float scale) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putFloat("scale", scale);
        return Fragment.instantiate(context, CustomFragment.class.getName(), bundle);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        LinearLayout linearLayout = (LinearLayout)
                inflater.inflate(R.layout.item, container, false);

        int position = this.getArguments().getInt("position");
        TextView textView = (TextView) linearLayout.findViewById(R.id.item_text);
        textView.setText(String.valueOf(position));

        CustomLinearLayout root = (CustomLinearLayout) linearLayout.findViewById(R.id.item_root);
        float scale = this.getArguments().getFloat("scale");
        root.setScaleBoth(scale);

        return linearLayout;
    }
}
</code>```

Custom LinearLayout

```<code>public class CustomLinearLayout extends LinearLayout {
    private float mScale = BIG_SCALE;

    public CustomLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLinearLayout(Context context) {
        super(context);
    }

    public void setScaleBoth(float scale) {
        this.mScale = scale;
        this.invalidate();    // If you want to see the mScale every time you set
        // mScale you need to have this line here,
        // invalidate() function will call onDraw(Canvas)
        // to redraw the view for you
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // The main mechanism to display mScale animation, you can customize it
        // as your needs
        int w = this.getWidth();
        int h = this.getHeight();
        canvas.scale(mScale, mScale, w / 2, h / 2);

        super.onDraw(canvas);
    }
}
</code>```

The most import thing is the adapter

```<code>public class CustomPagerAdapter extends FragmentPagerAdapter implements ViewPager.PageTransformer {
    public final static float BIG_SCALE = 1.0f;
    public final static float SMALL_SCALE = 0.7f;
    public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;

    private Activity mContext;
    private FragmentManager mFragmentManager;
    private float mScale;

    public CustomPagerAdapter(Activity context, FragmentManager fragmentManager) {
        super(fragmentManager);
        this.mFragmentManager = fragmentManager;
        this.mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // make the first mViewPager bigger than others
        if (position == FIRST_PAGE)
            mScale = BIG_SCALE;
        else
            mScale = SMALL_SCALE;

        return CustomFragment.newInstance(mContext, position, mScale);
    }

    @Override
    public int getCount() {
        return PAGES;
    }

    @Override
    public void transformPage(View page, float position) {
        CustomLinearLayout myLinearLayout = (CustomLinearLayout) page.findViewById(R.id.item_root);
        float scale = BIG_SCALE;
        if (position > 0) {
            scale = scale - position * DIFF_SCALE;
        } else {
            scale = scale + position * DIFF_SCALE;
        }
        if (scale < 0) scale = 0;
        myLinearLayout.setScaleBoth(scale);
    }
}
</code>```

and now the Activity

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

    public final static int PAGES = 5;
    public final static int FIRST_PAGE = 0  ;

    public CustomPagerAdapter mAdapter;
    public ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.activity_main_view_pager);

        mAdapter = new CustomPagerAdapter(this, this.getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setPageTransformer(false, mAdapter);

        // Set current item to the middle page so we can fling to both
        // directions left and right
        mViewPager.setCurrentItem(FIRST_PAGE);

        // Necessary or the mViewPager will only have one extra page to show
        // make this at least however many pages you can see
        mViewPager.setOffscreenPageLimit(3);

        // Set margin for pages as a negative number, so a part of next and
        // previous pages will be showed
        mViewPager.setPageMargin(-400);
    }
}
</code>```

Also you check this Tutorial and this exmple in GitHub.

Body:
You need:

activity_main

item

Custom Fragment

Custom LinearLayout

CustomPagerAdapter

Activity

I use this code:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:attrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.thedeveloperworldisyours.carouselviewpager.MainActivity">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_view_pager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

</RelativeLayout>

item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <com.thedeveloperworldisyours.carouselviewpager.CustomLinearLayout
        android:id="@+id/item_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/item_size_text" />

        <Button
            android:id="@+id/item_content"
            android:layout_width="230dp"
            android:layout_height="120dp"
            android:background="@android:color/black"/>
    </com.thedeveloperworldisyours.carouselviewpager.CustomLinearLayout>
</LinearLayout>

Custom Fragment

public class CustomFragment extends Fragment {

    public static Fragment newInstance(Activity context, int position, float scale) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putFloat("scale", scale);
        return Fragment.instantiate(context, CustomFragment.class.getName(), bundle);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        LinearLayout linearLayout = (LinearLayout)
                inflater.inflate(R.layout.item, container, false);

        int position = this.getArguments().getInt("position");
        TextView textView = (TextView) linearLayout.findViewById(R.id.item_text);
        textView.setText(String.valueOf(position));

        CustomLinearLayout root = (CustomLinearLayout) linearLayout.findViewById(R.id.item_root);
        float scale = this.getArguments().getFloat("scale");
        root.setScaleBoth(scale);

        return linearLayout;
    }
}

Custom LinearLayout

public class CustomLinearLayout extends LinearLayout {
    private float mScale = BIG_SCALE;

    public CustomLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLinearLayout(Context context) {
        super(context);
    }

    public void setScaleBoth(float scale) {
        this.mScale = scale;
        this.invalidate();    // If you want to see the mScale every time you set
        // mScale you need to have this line here,
        // invalidate() function will call onDraw(Canvas)
        // to redraw the view for you
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // The main mechanism to display mScale animation, you can customize it
        // as your needs
        int w = this.getWidth();
        int h = this.getHeight();
        canvas.scale(mScale, mScale, w / 2, h / 2);

        super.onDraw(canvas);
    }
}

The most import thing is the adapter

public class CustomPagerAdapter extends FragmentPagerAdapter implements ViewPager.PageTransformer {
    public final static float BIG_SCALE = 1.0f;
    public final static float SMALL_SCALE = 0.7f;
    public final static float DIFF_SCALE = BIG_SCALE - SMALL_SCALE;

    private Activity mContext;
    private FragmentManager mFragmentManager;
    private float mScale;

    public CustomPagerAdapter(Activity context, FragmentManager fragmentManager) {
        super(fragmentManager);
        this.mFragmentManager = fragmentManager;
        this.mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        // make the first mViewPager bigger than others
        if (position == FIRST_PAGE)
            mScale = BIG_SCALE;
        else
            mScale = SMALL_SCALE;

        return CustomFragment.newInstance(mContext, position, mScale);
    }

    @Override
    public int getCount() {
        return PAGES;
    }

    @Override
    public void transformPage(View page, float position) {
        CustomLinearLayout myLinearLayout = (CustomLinearLayout) page.findViewById(R.id.item_root);
        float scale = BIG_SCALE;
        if (position > 0) {
            scale = scale - position * DIFF_SCALE;
        } else {
            scale = scale + position * DIFF_SCALE;
        }
        if (scale < 0) scale = 0;
        myLinearLayout.setScaleBoth(scale);
    }
}

and now the Activity

public class MainActivity extends AppCompatActivity {

    public final static int PAGES = 5;
    public final static int FIRST_PAGE = 0  ;

    public CustomPagerAdapter mAdapter;
    public ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.activity_main_view_pager);

        mAdapter = new CustomPagerAdapter(this, this.getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setPageTransformer(false, mAdapter);

        // Set current item to the middle page so we can fling to both
        // directions left and right
        mViewPager.setCurrentItem(FIRST_PAGE);

        // Necessary or the mViewPager will only have one extra page to show
        // make this at least however many pages you can see
        mViewPager.setOffscreenPageLimit(3);

        // Set margin for pages as a negative number, so a part of next and
        // previous pages will be showed
        mViewPager.setPageMargin(-400);
    }
}

Also you check this Tutorial and this exmple in GitHub.


来源: stackexchange

问:
How to convert a specific string to integer?
Hi here is the scenario that I have strings like this;

```<code>$a="08";
$b="00";
$c="0";
</code>```

actually this is time part of a datetime i want to get these as integer

答:
It'a simple as casting your variables to integer: </p>

```<code>$a =(int)$a;
</code>```

<p>But, since php is loosely typed, it will usually take care of the type conversion behind the scenes. </p>

ContentLicense: CC BY-SA 3.0

Body:
Hi here is the scenario that I have strings like this;

$a="08";
$b="00";
$c="0";

actually this is time part of a datetime i want to get these as integer

Body:
It'a simple as casting your variables to integer:

$a =(int)$a;

But, since php is loosely typed, it will usually take care of the type conversion behind the scenes.


问:
Inserting dates within an array with PHP
I am getting the starting and ending dates from a form.

I need to put within an array all the date between the former two, including themselves.

I'm using a normal for loop and, at the same time, printing the result, to verify.

Everything appear to be alright.

But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.

This is the code:

```<code>$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff  = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;

$dates = array();

$addDay = $date1;

for ($i = 0; $i < $diffDays; $i++) {
    $dates[$i] = $addDay;
    date_add($addDay, date_interval_create_from_date_string("1 day"));
    echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}

print_r($dates);
</code>```

答:
I would do it that way</p>

```<code>$startDate =  new \DateTime("2017-03-15");
$endDate = new \DateTime("2017-03-22");

$dates = [];
$stop = false;
$date = $startDate;
while(!$stop){
    $dates[] = $date->format('Y-m-d'); // or  $dates[] = $date->format('Y-m-d H:i:s')
    $date->modify('+1 day');
    if($date->getTimestamp() > $endDate->getTimestamp()){
        $stop = true;
    }
}
print_r($dates);
</code>```

Body:
I am getting the starting and ending dates from a form.

I need to put within an array all the date between the former two, including themselves.

I'm using a normal for loop and, at the same time, printing the result, to verify.

Everything appear to be alright.

But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.

This is the code:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff  = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;

$dates = array();

$addDay = $date1;

for ($i = 0; $i < $diffDays; $i++) {
    $dates[$i] = $addDay;
    date_add($addDay, date_interval_create_from_date_string("1 day"));
    echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}

print_r($dates);

Body:
I would do it that way

$startDate =  new \DateTime("2017-03-15");
$endDate = new \DateTime("2017-03-22");

$dates = [];
$stop = false;
$date = $startDate;
while(!$stop){
    $dates[] = $date->format('Y-m-d'); // or  $dates[] = $date->format('Y-m-d H:i:s')
    $date->modify('+1 day');
    if($date->getTimestamp() > $endDate->getTimestamp()){
        $stop = true;
    }
}
print_r($dates);


问:
Why does using foreach to access nodelist children element in JavaScript result in undefined
I am trying to iterate through a NodeList using foreach. When I try to access with the following code, I get undefined in the console.

```<code>foreach = Array.prototype.forEach;
cls= document.getElementsByClassName('classname')
foreach.call(cls,function(some)
{
var ok = some.children;
foreac.call(ok,function(ss)
{
ss
});
});
</code>```

I am trying this code in chrome developer tools. The console is returning 'undefined'. I am able to access by explicitly specifying the list position.

答:
You are getting undefined because basically you are not doing anything with the result. You can return it or e.g. log it to the console.

var foreach = Array.prototype.forEach,
    cls = document.getElementsByClassName('classname');

    foreach.call(cls, function(some) {
      var ok = some.children;
      foreach.call(ok, function(ss) {
        console.log(ss);
      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class='classname'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul></code>```

Anyways I'm not sure if you are doing this for only learning purposes or not, but you are complicating it.

Wouldn't be it easier to just get the specified elements with querySelectorAll  and iterate over it with Array#forEach?

var elems = document.querySelectorAll('ul li');
    elems.forEach(v => console.log(v));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class='classname'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to iterate through a NodeList using foreach. When I try to access with the following code, I get undefined in the console.

foreach = Array.prototype.forEach;
cls= document.getElementsByClassName('classname')
foreach.call(cls,function(some)
{
var ok = some.children;
foreac.call(ok,function(ss)
{
ss
});
});

I am trying this code in chrome developer tools. The console is returning 'undefined'. I am able to access by explicitly specifying the list position.

Body:
You are getting undefined because basically you are not doing anything with the result. You can return it or e.g. log it to the console.

var foreach = Array.prototype.forEach,
    cls = document.getElementsByClassName('classname');

    foreach.call(cls, function(some) {
      var ok = some.children;
      foreach.call(ok, function(ss) {
        console.log(ss);
      });
    });

<ul class='classname'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Anyways I'm not sure if you are doing this for only learning purposes or not, but you are complicating it.

Wouldn't be it easier to just get the specified elements with querySelectorAll  and iterate over it with Array#forEach?

var elems = document.querySelectorAll('ul li');
    elems.forEach(v => console.log(v));

<ul class='classname'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>


问:
convert two dimensional array to object array without duplicates
I have a two dimensional array of colors:

```<code>var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]
</code>```

I want to turn this into an object array and I've successfully done so using a .map

```<code>obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});
</code>```

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

```<code>[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]
</code>```

How can I achieve this?

答:
We can use Array filter() & map() methods to achieve this.

DEMO

// Initial multidimensional array.
var colors = [
               ["Blue", "Red"],
               ["Green","Red"],
               ["Black","Orange"],
               ["Red", "Blue"]
             ];

// Merged colors into single dimensional array.
var merged = [].concat.apply([], colors);

// Apply array filter() method to remove the duplicates.
var filteredData = merged.filter(function(item, index) {
  return merged.indexOf(item) == index
});

// Create an array of objects from the array "filteredData".
var res = filteredData.map(function(item) {
  return {
    "color": item
  }
});

// result
console.log(res);```

Body:
I have a two dimensional array of colors:

var colors = [["Blue", "Red"],["Green","Red"],["Black","Orange"],["Red", "Blue"]]

I want to turn this into an object array and I've successfully done so using a .map

obj = colors.map(function(x) {return
{
    "color1": x[0],
    "color2": x[1]
}});

However I want the new object array to exclude duplicates and just be a list of the colors mentioned (instead of color1 and color2, combine into one). New array should have the format:

[{"color": Blue},
 {"color": Red},
 {"color": Green},
 {"color": Black},
 {"color": Orange}]

How can I achieve this?


问:
Displaying the current frame of a video after skipping using drawtext/start_number not evaluation any variables
I would like to display the current frame number on a video while playing it with ffplay. I have already seen this solution, but when I seek to any part of the video, the counter resets. There's a variable, start_number, which the ffplay documentation says is The starting frame number for the n/frame_num variable. The default value is "0". It seems that n is set to that when starting the video or seeking between I-frames. I thought setting this variable to %{floor(t*60)} would solve my problem, but after running this:

```<code>ffplay -i "video.mp4" -vf drawtext="fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:start_number=floor(t*60):text=%{n}"
</code>```

I got the following console output:

```<code>ffplay version N-84679-gd65b595 Copyright (c) 2003-2017 the FFmpeg developers
  built with gcc 6.3.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-cuda --enable-cuvid --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-nvenc --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenh264 --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-lzma --enable-zlib
  libavutil      55. 51.100 / 55. 51.100
  libavcodec     57. 86.103 / 57. 86.103
  libavformat    57. 67.100 / 57. 67.100
  libavdevice    57.  3.101 / 57.  3.101
  libavfilter     6. 78.100 /  6. 78.100
  libswscale      4.  3.101 /  4.  3.101
  libswresample   2.  4.100 /  2.  4.100
  libpostproc    54.  2.100 / 54.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':=    0B f=0/0
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 2017-03-30T02:49:20.000000Z
    encoder         : Open Broadcaster Software v0.659b
  Duration: 00:05:36.85, start: 0.000000, bitrate: 72636 kb/s
    Stream #0:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 162 kb/s (default)
    Metadata:
  creation_time   : 2017-03-30T02:49:20.000000Z
  handler_name    : Sound Media Handler
Stream #0:1(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p(tv, bt709/bt709/iec61966-2-1), 2560x1440, 72465 kb/s, 60 fps, 60 tbr, 1k tbn, 120 tbc (default)
Metadata:
  creation_time   : 2017-03-30T02:49:20.000000Z
  handler_name    : Video Media Handler
  encoder         : AVC Coding
[drawtext @ 00000000122770e0] [Eval @ 0000000008f3eb60] Undefined constant or missing '(' in 't*60)'
[drawtext @ 00000000122770e0] Unable to parse option value "floor(t*60)"
[drawtext @ 00000000122770e0] [Eval @ 0000000008f3ebd0] Undefined constant or missing '(' in 't*60)'
[drawtext @ 00000000122770e0] Unable to parse option value "floor(t*60)"
[drawtext @ 00000000122770e0] Error setting option start_number to value floor(t*60).
[Parsed_drawtext_0 @ 000000000263eca0] Error applying options to the filter.
Error initializing filter 'drawtext' with args 'fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:start_number=floor(t*60):text=%{n}'
   0.01 A-V:    nan fd=   0 aq=   22KB vq= 5866KB sq=    0B f=0/0
</code>```

In fact, any variable in start_number's assignment invokes this error. I don't know if I have the correct syntax, but does this mean it doesn't evaluate expressions? Or maybe it doesn't accept variables for some reason?

After that downer I tried just setting the text to %{t}, which played the video, but repeatedly gave this error and had no text in the top left corner:

```<code>[Parsed_drawtext_0 @ 0000000003e54ea0] %{t} is not known 0B f=0/0
</code>```

So does the current time variable just not work in drawtext?

Is there another way to write the current frame on the video or even on the console window?

Using Windows 10 Enterprise and the latest build of ffplay for windows at this time.

答:
Assuming the video has a constant frame rate of 60 fps, use</p>
```<code>ffplay -i "video.mp4"
 -vf "drawtext=fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:text='%{eif\:t*60\:d}'"
</code>```

Body:
I would like to display the current frame number on a video while playing it with ffplay. I have already seen this solution, but when I seek to any part of the video, the counter resets. There's a variable, start_number, which the ffplay documentation says is The starting frame number for the n/frame_num variable. The default value is "0". It seems that n is set to that when starting the video or seeking between I-frames. I thought setting this variable to %{floor(t*60)} would solve my problem, but after running this:

ffplay -i "video.mp4" -vf drawtext="fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:start_number=floor(t*60):text=%{n}"

I got the following console output:

ffplay version N-84679-gd65b595 Copyright (c) 2003-2017 the FFmpeg developers
  built with gcc 6.3.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-cuda --enable-cuvid --enable-d3d11va --enable-dxva2 --enable-libmfx --enable-nvenc --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenh264 --enable-libopenjpeg --enable-libopus --enable-librtmp --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-lzma --enable-zlib
  libavutil      55. 51.100 / 55. 51.100
  libavcodec     57. 86.103 / 57. 86.103
  libavformat    57. 67.100 / 57. 67.100
  libavdevice    57.  3.101 / 57.  3.101
  libavfilter     6. 78.100 /  6. 78.100
  libswscale      4.  3.101 /  4.  3.101
  libswresample   2.  4.100 /  2.  4.100
  libpostproc    54.  2.100 / 54.  2.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':=    0B f=0/0
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 2017-03-30T02:49:20.000000Z
    encoder         : Open Broadcaster Software v0.659b
  Duration: 00:05:36.85, start: 0.000000, bitrate: 72636 kb/s
    Stream #0:0(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 162 kb/s (default)
    Metadata:
  creation_time   : 2017-03-30T02:49:20.000000Z
  handler_name    : Sound Media Handler
Stream #0:1(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p(tv, bt709/bt709/iec61966-2-1), 2560x1440, 72465 kb/s, 60 fps, 60 tbr, 1k tbn, 120 tbc (default)
Metadata:
  creation_time   : 2017-03-30T02:49:20.000000Z
  handler_name    : Video Media Handler
  encoder         : AVC Coding
[drawtext @ 00000000122770e0] [Eval @ 0000000008f3eb60] Undefined constant or missing '(' in 't*60)'
[drawtext @ 00000000122770e0] Unable to parse option value "floor(t*60)"
[drawtext @ 00000000122770e0] [Eval @ 0000000008f3ebd0] Undefined constant or missing '(' in 't*60)'
[drawtext @ 00000000122770e0] Unable to parse option value "floor(t*60)"
[drawtext @ 00000000122770e0] Error setting option start_number to value floor(t*60).
[Parsed_drawtext_0 @ 000000000263eca0] Error applying options to the filter.
Error initializing filter 'drawtext' with args 'fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:start_number=floor(t*60):text=%{n}'
   0.01 A-V:    nan fd=   0 aq=   22KB vq= 5866KB sq=    0B f=0/0

In fact, any variable in start_number's assignment invokes this error. I don't know if I have the correct syntax, but does this mean it doesn't evaluate expressions? Or maybe it doesn't accept variables for some reason?

After that downer I tried just setting the text to %{t}, which played the video, but repeatedly gave this error and had no text in the top left corner:

[Parsed_drawtext_0 @ 0000000003e54ea0] %{t} is not known 0B f=0/0

So does the current time variable just not work in drawtext?

Is there another way to write the current frame on the video or even on the console window?

Using Windows 10 Enterprise and the latest build of ffplay for windows at this time.

Body:
Assuming the video has a constant frame rate of 60 fps, use

ffplay -i "video.mp4"
 -vf "drawtext=fontsize=30:box=1:boxcolor=white:fontcolor=black:fontfile=/Windows/Fonts/arial.ttf:text='%{eif\:t*60\:d}'"


问:
ansible wget then exec scripts => get_url equivalent
I always wonder what is the good way to replace the following shell tasks using the "ansible way" (with get_url, etc.):

```<code>- name: Install oh-my-zsh
  shell: wget -qO - https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | bash -
</code>```

or

```<code>- name: Install nodesource repo
  shell: curl -sL https://deb.nodesource.com/setup_5.x | bash -
</code>```

答:
@RaviTezu solution doesn't work because the file/script that you wish to execute must be on the machine where you execute your play/role.

As per the documentation here

The local script at path will be transferred to the remote node and then executed.

So one way to do it is by downloading the file locally and using a task like below:

```<code>- name: execute the script.sh
  script: /local/path/to/script.sh
</code>```

Or you can do this:

```<code>- name: download setup_5.x file to tmp dir
  get_url:
    url: https://deb.nodesource.com/setup_5.x
    dest: /tmp/
    mode: 0755

- name: execute setup_5.x script
  shell: setup_5.x
  args:
    chdir: /tmp/
</code>```

I would go for the first method if you are uploading your own script, the second method is more useful in your case because the script might gets updated in time so you are sure each time you execute it it uses the latest script.

Body:
I always wonder what is the good way to replace the following shell tasks using the "ansible way" (with get_url, etc.):

- name: Install oh-my-zsh
  shell: wget -qO - https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | bash -

or

- name: Install nodesource repo
  shell: curl -sL https://deb.nodesource.com/setup_5.x | bash -

Body:
@RaviTezu solution doesn't work because the file/script that you wish to execute must be on the machine where you execute your play/role.

As per the documentation here

The local script at path will be transferred to the remote node and then executed.

So one way to do it is by downloading the file locally and using a task like below:

- name: execute the script.sh
  script: /local/path/to/script.sh

Or you can do this:

- name: download setup_5.x file to tmp dir
  get_url:
    url: https://deb.nodesource.com/setup_5.x
    dest: /tmp/
    mode: 0755

- name: execute setup_5.x script
  shell: setup_5.x
  args:
    chdir: /tmp/

I would go for the first method if you are uploading your own script, the second method is more useful in your case because the script might gets updated in time so you are sure each time you execute it it uses the latest script.


问:
ReduxForm vs tcomb-form for Native Development
We used ReduxForm in our Web App and we are now trying to build a native app and it seems most of the guys are using tcomb-form.

ReduxForm can be used for native development. Not sure what's the biggest advantage of using tcomb-form.

I tried using it (Didn't explore all the advanced features yet) how ever once we define the schema the basic rendering of the controls is done for you. How ever if you want to customize how a control is displayed i am not sure whether tcomb-form supports it.

Ex:

Here in my Component's render() method:

```<code>let Form= tFormNative.form.Form;

        let options= {
            fields: {
            }
        };

        let username= {
            label: I18n.t('LoginForm.username'),
            maxLength: 12,
            editable: true,

        };

        let email = {
            label: I18n.t('LoginForm.email'),
            keyboardType: 'email-address',
            editable: true,

        };

        let password = {
            label: I18n.t('LoginForm.password'),
            maxLength: 12,
            secureTextEntry: true,
            editable: true,
        };

        let registerForm = tFormNative.struct({
            username: tFormNative.String,
            email: tFormNative.String,
            password: tFormNative.String,
            passwordReEnter: tFormNative.String,
        });

  return(
     <View style={styles.container}>
            <Form
                style={styles.textInput}
                ref='form'
                type={registerForm}
                options={options}
            />
         </View>
  );
</code>```

Now the Label and Control ( based on the type you provided in struct() ) are created.

How ever Lets say i want to use an Icon aling with the Label for each control i am not sure whether that is permitted.

Appreciate any inputs.

Thanks
Sateesh

答:
I would leave this as a comment if I could, but my reputation isn't high enough.

You need to override your form's local template with a custom template which adds an Icon and TextInput for each field.

This gist shows how you can do this.

Body:
We used ReduxForm in our Web App and we are now trying to build a native app and it seems most of the guys are using tcomb-form.

ReduxForm can be used for native development. Not sure what's the biggest advantage of using tcomb-form.

I tried using it (Didn't explore all the advanced features yet) how ever once we define the schema the basic rendering of the controls is done for you. How ever if you want to customize how a control is displayed i am not sure whether tcomb-form supports it.

Ex:

Here in my Component's render() method:

let Form= tFormNative.form.Form;

        let options= {
            fields: {
            }
        };

        let username= {
            label: I18n.t('LoginForm.username'),
            maxLength: 12,
            editable: true,

        };

        let email = {
            label: I18n.t('LoginForm.email'),
            keyboardType: 'email-address',
            editable: true,

        };

        let password = {
            label: I18n.t('LoginForm.password'),
            maxLength: 12,
            secureTextEntry: true,
            editable: true,
        };

        let registerForm = tFormNative.struct({
            username: tFormNative.String,
            email: tFormNative.String,
            password: tFormNative.String,
            passwordReEnter: tFormNative.String,
        });

  return(
     <View style={styles.container}>
            <Form
                style={styles.textInput}
                ref='form'
                type={registerForm}
                options={options}
            />
         </View>
  );

Now the Label and Control ( based on the type you provided in struct() ) are created.

How ever Lets say i want to use an Icon aling with the Label for each control i am not sure whether that is permitted.

Appreciate any inputs.

Thanks
Sateesh


问:
SQL Name search with apostrophe, hyphen, Double uppercase
There is a search filter with alphabet.

I would like the filter to work if I click 'D' it then displays all artist's names like:

```
David McDonald
Alice Duncan
Daniel O'Neill
Beth Douglas-Bain
```

The artist table has a column 'name' which contains first, middle and surname, including apostrophes, hyphens, and double uppercase.

I tried

```<code>SELECT * FROM `artist` WHERE `name` REGEXP BINARY 'D[a-z]'
</code>```

however, that didn't work properly.

I can only use the query from 'WHERE clause' so I cannot use the query from SELECT.

Some problem examples are:

Click 'O' but O'Neill not showing up

Click 'B' then Douglas-Bain showing up, should be 'D', McDonald has same problem too.

The surname of McDonald, O'neill, Douglas-Bain, those makes the query not working well as McDonald and Douglas-Bain have two uppercases, so it appears when I hit 'D'. O'Neill has an apostrophe and double uppercase and I cannot figure it out.

I would really appreciate it if some SQL expert can help me.

答:
Try this

```<code>'(^|[^A-Za-z''])lettervalue'
</code>```

where lettervalue is the selected letter

Tested on the following list of names and got successes on all.

```<code>Daniel Grass
Daniel House
Ronald O'House
Craig McHouse
Tina Dreamer
Orion Fantastic
</code>```

As required,

'(^|[^A-Za-z''])O' pulls "Ronald O'House" and "Orion Fantastic",

'(^|[^A-Za-z''])H' pulls out "Daniel House" (but ignores Craig McHouse)

'(^|[^A-Za-z''])M' pulls out "Craig McHouse"

Body:
There is a search filter with alphabet.

I would like the filter to work if I click 'D' it then displays all artist's names like:

David McDonald
Alice Duncan
Daniel O'Neill
Beth Douglas-Bain

The artist table has a column 'name' which contains first, middle and surname, including apostrophes, hyphens, and double uppercase.

I tried

SELECT * FROM `artist` WHERE `name` REGEXP BINARY 'D[a-z]'

however, that didn't work properly.

I can only use the query from 'WHERE clause' so I cannot use the query from SELECT.

Some problem examples are:

Click 'O' but O'Neill not showing up

Click 'B' then Douglas-Bain showing up, should be 'D', McDonald has same problem too.

The surname of McDonald, O'neill, Douglas-Bain, those makes the query not working well as McDonald and Douglas-Bain have two uppercases, so it appears when I hit 'D'. O'Neill has an apostrophe and double uppercase and I cannot figure it out.

I would really appreciate it if some SQL expert can help me.

Body:
Try this

'(^|[^A-Za-z''])lettervalue'

where lettervalue is the selected letter

Tested on the following list of names and got successes on all.

Daniel Grass
Daniel House
Ronald O'House
Craig McHouse
Tina Dreamer
Orion Fantastic

As required,

'(^|[^A-Za-z''])O' pulls "Ronald O'House" and "Orion Fantastic",

'(^|[^A-Za-z''])H' pulls out "Daniel House" (but ignores Craig McHouse)

'(^|[^A-Za-z''])M' pulls out "Craig McHouse"


问:
Hibernate 4.3 to 5.2 upgrade - cannot simultaneously fetch multiple bags
Trying to upgrade to hibernate 5.2.9 from 4.3.11. Currently using the hibernate native api. After adding the dependency in pom.xml I get the following error when running my units tests:

Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [testApplicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

I have a testApplicationContext.xml with the following:

```<code><bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="org.xxxx.xxxx.xxxx.model"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
</code>```

I updated the sessionFactory and transactionManager from hibernate4 to hibernate5.

pom.xml:

```<code><dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.9.Final</version>
    </dependency>
</code>```

As far as I can tell, the error message implies that there is an issue loading multiple eagerly loaded collections. However, I understand from this that using hibernate-specific annotations and newer versions of hibernate support this use case.

Can anyone help please? Thanks

答:
This issue has been resolved now.

In a couple of my entities I was using a List for @OneToMany.

Changing to Set resulted in the error going away. Not sure as yet why this worked/was supported in Hibernate 4.3.11 and not 5.2.9. I will update this answer if I find any further information.

Further info with regard to List vs Set can be found here and here.

Body:
Trying to upgrade to hibernate 5.2.9 from 4.3.11. Currently using the hibernate native api. After adding the dependency in pom.xml I get the following error when running my units tests:

Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [testApplicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

I have a testApplicationContext.xml with the following:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="org.xxxx.xxxx.xxxx.model"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.format_sql">true</prop>
            <prop key="hibernate.use_sql_comments">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

I updated the sessionFactory and transactionManager from hibernate4 to hibernate5.

pom.xml:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.9.Final</version>
    </dependency>

As far as I can tell, the error message implies that there is an issue loading multiple eagerly loaded collections. However, I understand from this that using hibernate-specific annotations and newer versions of hibernate support this use case.

Can anyone help please? Thanks


问:
Angular2 - No provider for TemplateRef (ng2-bootstrap)
I have been trying several solutios for this error, but didn't find any succesful way to overcome this: No provider for TemplateRef!

Error log:

EXCEPTION: Uncaught (in promise): Error: Error in ./FooterComponent
  class FooterComponent - inline template:15:20 caused by: No provider
  for TemplateRef! Error: Error in ./FooterComponent class
  FooterComponent - inline template:15:20 caused by: No provider for
  TemplateRef!

Unhandled Promise rejection: Error in ./FooterComponent class
  FooterComponent - inline template:15:20 caused by: No provider for
  TemplateRef! ; Zone: angular ; Task: Promise.then ; Value:

footer.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'sa-footer',
  templateUrl: './footer.component.html'
})
export class FooterComponent implements OnInit {

  constructor() {}

  ngOnInit() {}

}
</code>```

footer.component.html

```<code><div class="page-footer">
    <div class="row">
        <div class="col-xs-12 col-sm-6">
            <span class="txt-color-white">myAPP © 2016</span>
        </div>

        <div class="col-xs-6 col-sm-6 text-right hidden-xs">
            <div class="txt-color-white inline-block">
                <i class="txt-color-blueLight hidden-mobile">Last account activity <i class="fa fa-clock-o"></i>
                    <strong>52 mins ago  </strong> </i>

                <div class="btn-group dropup" dropdown>
                    <button class="btn btn-xs dropdown-toggle bg-color-blue txt-color-white" dropdownToggle>
                        <i class="fa fa-link"></i> <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu pull-right text-left" dropdownMenu>
                        <li>
                            <div class="padding-5">
                                <p class="txt-color-darken font-sm no-margin">Download Progress</p>

                                <div class="progress progress-micro no-margin">
                                    <div class="progress-bar progress-bar-success" style="width: 50%;"></div>
                                </div>
                            </div>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <div class="padding-5">
                                <p class="txt-color-darken font-sm no-margin">Server Load</p>

                                <div class="progress progress-micro no-margin">
                                    <div class="progress-bar progress-bar-success" style="width: 20%;"></div>
                                </div>
                            </div>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <div class="padding-5">
                                <p class="txt-color-darken font-sm no-margin">Memory Load <span class="text-danger">*critical*</span>
                                </p>

                                <div class="progress progress-micro no-margin">
                                    <div class="progress-bar progress-bar-danger" style="width: 70%;"></div>
                                </div>
                            </div>
                        </li>
                        <li class="divider"></li>
                        <li>
                            <div class="padding-5">
                                <button class="btn btn-block btn-default">refresh</button>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

I tried to do the following:

Research:
But only found answers / solutions for templates that actually contain some directives like ngIf, ngSwitch, etc. (Forgetting the *, for example)

Add TemplateRef to providers. This is what I get:

Argument of type '{ selector: string; templateUrl: string; providers:
  typeof TemplateRef[]; }' is not assignable to parameter of type
  'Component'.   Types of property 'providers' are incompatible.
      Type 'typeof TemplateRef[]' is not assignable to type 'Provider[]'.
        Type 'typeof TemplateRef' is not assignable to type 'Provider'.
          Type 'typeof TemplateRef' is not assignable to type 'FactoryProvider'.
            Property 'provide' is missing in type 'typeof TemplateRef'.

I will try to see how to add somehow TemplateRef to the app's module providers. But I don't know if this is the solution.
 I hope someone comes out with a solution while I continue researching.

Thank you! :D

答:
Research: But only found answers / solutions for templates that actually contain some directives like ngIf, ngSwitch, etc. (Forgetting the *, for example)

missing * here :

```<code><ul class="dropdown-menu pull-right text-left" dropdownMenu>
</code>```

should be

```<code><ul class="dropdown-menu pull-right text-left" *dropdownMenu>
</code>```

From ng2-bootstrap:

```<code><div class="btn-group" dropdown>
  <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
    Button dropdown <span class="caret"></span>
  </button>
  <ul *dropdownMenu class="dropdown-menu" role="menu">
    <li role="menuitem"><a class="dropdown-item" href="#">Action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
    <li class="divider dropdown-divider"></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Separated link</a>
    </li>
  </ul>
</div>
</code>```

Body:
I have been trying several solutios for this error, but didn't find any succesful way to overcome this: No provider for TemplateRef!

Error log:

EXCEPTION: Uncaught (in promise): Error: Error in ./FooterComponent
  class FooterComponent - inline template:15:20 caused by: No provider
  for TemplateRef! Error: Error in ./FooterComponent class
  FooterComponent - inline template:15:20 caused by: No provider for
  TemplateRef!

Unhandled Promise rejection: Error in ./FooterComponent class
  FooterComponent - inline template:15:20 caused by: No provider for
  TemplateRef! ; Zone: angular ; Task: Promise.then ; Value:

footer.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'sa-footer',
  templateUrl: './footer.component.html'
})
export class FooterComponent implements OnInit {

  constructor() {}

  ngOnInit() {}

}

footer.component.html

            myAPP © 2016

                Last account activity
                    52 mins ago

                    <button class="btn btn-xs dropdown-toggle bg-color-blue txt-color-white" dropdownToggle>

                    </button>

Download Progress

Server Load

Memory Load *critical*

                                <button class="btn btn-block btn-default">refresh</button>

I tried to do the following:

Research:
But only found answers / solutions for templates that actually contain some directives like ngIf, ngSwitch, etc. (Forgetting the *, for example)

Add TemplateRef to providers. This is what I get:

Argument of type '{ selector: string; templateUrl: string; providers:
  typeof TemplateRef[]; }' is not assignable to parameter of type
  'Component'.   Types of property 'providers' are incompatible.
      Type 'typeof TemplateRef[]' is not assignable to type 'Provider[]'.
        Type 'typeof TemplateRef' is not assignable to type 'Provider'.
          Type 'typeof TemplateRef' is not assignable to type 'FactoryProvider'.
            Property 'provide' is missing in type 'typeof TemplateRef'.

I will try to see how to add somehow TemplateRef to the app's module providers. But I don't know if this is the solution.
 I hope someone comes out with a solution while I continue researching.

Thank you! :D

Body:
Research: But only found answers / solutions for templates that actually contain some directives like ngIf, ngSwitch, etc. (Forgetting the *, for example)

missing * here :

<ul class="dropdown-menu pull-right text-left" dropdownMenu>

should be

<ul class="dropdown-menu pull-right text-left" *dropdownMenu>

From ng2-bootstrap:

<div class="btn-group" dropdown>
  <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
    Button dropdown <span class="caret"></span>
  </button>
  <ul *dropdownMenu class="dropdown-menu" role="menu">
    <li role="menuitem"><a class="dropdown-item" href="#">Action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
    <li class="divider dropdown-divider"></li>
    <li role="menuitem"><a class="dropdown-item" href="#">Separated link</a>
    </li>
  </ul>
</div>


问:
Return certain record based on criteria (2)
I asked this question previously, but missed a vital part of my problem.

Return certain record based on criteria

Take this list of results

```<code>Client  |   Date     | YESorNO
-------------------------------
A1      | 01/01/2001 | NO
A1      | 01/01/2002 | NO
A1      | 01/01/2003 | YES
A1      | 01/01/2004 | NO
A1      | 01/01/2005 | NO
A1      | 01/01/2006 | NO
A1      | 01/01/2007 | YES
A1      | 01/01/2008 | YES
A1      | 01/01/2009 | YES

A2      | 01/01/2001 | NO
A2      | 01/01/2002 | NO
A2      | 01/01/2003 | YES
A2      | 01/01/2004 | NO
A2      | 01/01/2005 | YES
A2      | 01/01/2006 | YES

A3      | 01/01/2001 | NO

           ...etc...
</code>```

The list is ordered chronologically and I cannot sort this is any other way other than descending / ascending.

I cannot sort for Yes | NO and find the First() or Last() as this won't give me the required value.

I want to be able to return the first 'YES' after all 'NO's have been accounted for, per Client.

In the above example for Client[A1] row 7 is the record I want returned (on 01/01/2007).

Client[A2] - row 5 (01/01/2005) ..etc

My code is as follows

```<code>var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Client = m.Client,
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);
</code>```

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

User @RenéVogt advised that

```<code>var result = query.AsEnumerable()
                  .TakeWhile(x => x.YESorNO == "YES")
                  .LastOrDefault();
</code>```

would get the job done and it does, but I forgot to add that the query will be returning many Clients and I need the first 'YES' for each Client, therefore the above code won't suffice.

Iterating over my results would be hugely time consuming and whilst that is a solution I would prefer this logic to be within the database query itself (if possible)

Many thanks

答:
What you have to do is grouping by client,and then find the last YES of each one starting from the end. Something like this (ClientList is a List<>, you may have to change it depending on where is your data):

```<code>var query = ClientList.OrderBy(x => x.client).ThenBy(x => x.date).GroupBy(x => x.client);
foreach (var client in query)
{
    var lastYES=client.Reverse().TakeWhile(x => x.YESorNO == "YES")
              .LastOrDefault();
    Console.WriteLine(String.Format("{0} {1}",client.Key,lastYES.date));
}
//Output: A1 01/01/2007 0:00:00
//        A2 01/01/2005 0:00:00
</code>```

Edit

Mansur Anorboev rightly suggested ordering by descending date, thus eliminating the need of Reverse, so the code would be:

```<code>var query = ClientList.OrderBy(x => x.client).ThenByDescending(x => x.date).GroupBy(x => x.client);
foreach (var client in query)
{
    var lastYES=client.TakeWhile(x => x.YESorNO == "YES")
              .LastOrDefault();
    Console.WriteLine(String.Format("{0} {1}",client.Key,lastYES.date));
}
</code>```

Edit 2

I still was not completly happy with my solution, as it is using a foreach. This does everything in one Linq command:

```<code>var query = ClientList.OrderBy(x => x.client)
                      .ThenByDescending(x => x.date)
                      .GroupBy(x => x.client, (key, g) => g.TakeWhile(x => x.YESorNO == "YES").LastOrDefault())
                      .ToList();
</code>```

This returns a list with one element per client and with the correct date.

Body:
I asked this question previously, but missed a vital part of my problem.

Return certain record based on criteria

Take this list of results

Client  |   Date     | YESorNO
-------------------------------
A1      | 01/01/2001 | NO
A1      | 01/01/2002 | NO
A1      | 01/01/2003 | YES
A1      | 01/01/2004 | NO
A1      | 01/01/2005 | NO
A1      | 01/01/2006 | NO
A1      | 01/01/2007 | YES
A1      | 01/01/2008 | YES
A1      | 01/01/2009 | YES

A2      | 01/01/2001 | NO
A2      | 01/01/2002 | NO
A2      | 01/01/2003 | YES
A2      | 01/01/2004 | NO
A2      | 01/01/2005 | YES
A2      | 01/01/2006 | YES

A3      | 01/01/2001 | NO

           ...etc...

The list is ordered chronologically and I cannot sort this is any other way other than descending / ascending.

I cannot sort for Yes | NO and find the First() or Last() as this won't give me the required value.

I want to be able to return the first 'YES' after all 'NO's have been accounted for, per Client.

In the above example for Client[A1] row 7 is the record I want returned (on 01/01/2007).

Client[A2] - row 5 (01/01/2005) ..etc

My code is as follows

var query =
(
    from m in db.MyTable
    where m.Criteria == XYZ
    select new
    {
      Client = m.Client,
      Date = m.Date,
      YESorNO = m.YESorNO
    }
).OrderBy(x => x.Date);

Using .FirstOrDefault(x => x.YesOrNO == "YES") returns the 3rd record.

User @RenéVogt advised that

var result = query.AsEnumerable()
                  .TakeWhile(x => x.YESorNO == "YES")
                  .LastOrDefault();

would get the job done and it does, but I forgot to add that the query will be returning many Clients and I need the first 'YES' for each Client, therefore the above code won't suffice.

Iterating over my results would be hugely time consuming and whilst that is a solution I would prefer this logic to be within the database query itself (if possible)

Many thanks

Body:
What you have to do is grouping by client,and then find the last YES of each one starting from the end. Something like this (ClientList is a List<>, you may have to change it depending on where is your data):

var query = ClientList.OrderBy(x => x.client).ThenBy(x => x.date).GroupBy(x => x.client);
foreach (var client in query)
{
    var lastYES=client.Reverse().TakeWhile(x => x.YESorNO == "YES")
              .LastOrDefault();
    Console.WriteLine(String.Format("{0} {1}",client.Key,lastYES.date));
}
//Output: A1 01/01/2007 0:00:00
//        A2 01/01/2005 0:00:00

Edit

Mansur Anorboev rightly suggested ordering by descending date, thus eliminating the need of Reverse, so the code would be:

var query = ClientList.OrderBy(x => x.client).ThenByDescending(x => x.date).GroupBy(x => x.client);
foreach (var client in query)
{
    var lastYES=client.TakeWhile(x => x.YESorNO == "YES")
              .LastOrDefault();
    Console.WriteLine(String.Format("{0} {1}",client.Key,lastYES.date));
}

Edit 2

I still was not completly happy with my solution, as it is using a foreach. This does everything in one Linq command:

var query = ClientList.OrderBy(x => x.client)
                      .ThenByDescending(x => x.date)
                      .GroupBy(x => x.client, (key, g) => g.TakeWhile(x => x.YESorNO == "YES").LastOrDefault())
                      .ToList();

This returns a list with one element per client and with the correct date.


问:
angular ng-bind-html doesn't work with youtube embed
I try to jsfiddel with the ng-bind-html.
it doesn't seem to work with youtube embed, why?

```<code><div ng-app="App1">
  <div ng-app="App1" ng-controller="Ctrl">
      <div ng-bind-html="youtube">
      </div>
       <p>this is a youtube {{youtube}}</p>
  </div>
</div>
</code>```

script

```<code>var myApp = angular.module('App1', ['ngSanitize']);

myApp.controller('Ctrl', ['$scope', function($scope){
    $scope.youtube = '<iframe width="560" height="315" src="//www.youtube.com/embed/FZSjvWtUxYk" frameborder="0" allowfullscreen></iframe>';

}]);
</code>```

EDIT: Originally my example was simplified to just adding a link, thanks to IvorG I noticed that I didn't add 'ngSanitize' as a dependency, after adding the dependency I edited the question to reflect the original issue I was having: adding a youtube embed.

答:
js code:

```<code>var myApp = angular.module('App1', ['ngSanitize']);
myApp.filter('sanitizer', ['$sce', function($sce) {
        return function(url) {
            return $sce.trustAsHtml(url);
        };
}]);

myApp.controller('Ctrl', ['$scope', function($scope){
$scope.youtube = '<iframe width="560" height="315"    src="//www.youtube.com/embed/FZSjvWtUxYk" frameborder="0" allowfullscreen> </iframe>';

}]);
</code>```

html code:

```<code><div ng-app="App1">
<div ng-app="App1" ng-controller="Ctrl">
<H1>This is a youtube Embeded Video</h1>
  <div ng-bind-html="youtube | sanitizer"></div>
</div>
</div>
</code>```

This works for me.

Body:
I try to jsfiddel with the ng-bind-html.
it doesn't seem to work with youtube embed, why?

this is a youtube {{youtube}}

script

var myApp = angular.module('App1', ['ngSanitize']);

myApp.controller('Ctrl', ['$scope', function($scope){
    $scope.youtube = '';

}]);

EDIT: Originally my example was simplified to just adding a link, thanks to IvorG I noticed that I didn't add 'ngSanitize' as a dependency, after adding the dependency I edited the question to reflect the original issue I was having: adding a youtube embed.

Body:
js code:

var myApp = angular.module('App1', ['ngSanitize']);
myApp.filter('sanitizer', ['$sce', function($sce) {
        return function(url) {
            return $sce.trustAsHtml(url);
        };
}]);

myApp.controller('Ctrl', ['$scope', function($scope){
$scope.youtube = '<iframe width="560" height="315"    src="//www.youtube.com/embed/FZSjvWtUxYk" frameborder="0" allowfullscreen> </iframe>';

}]);

html code:

<div ng-app="App1">
<div ng-app="App1" ng-controller="Ctrl">
<H1>This is a youtube Embeded Video</h1>
  <div ng-bind-html="youtube | sanitizer"></div>
</div>
</div>

This works for me.


问:
jquery not working in mobile browsers
I am making a image uploader using jquery and ajax and it works ok in computer browsers but will not work in mobile browsers. I did get it to work once but i changed something and didn't notice in till it was to late. Can someone please tell me why my coding stops working in mobile browsers.

It seems that the $(document).ready(function(){ is not loading on page load in cell phones but i have other js coding and they all work but this one is the only one that stops working.

```<code><script type="text/javascript">
function _(el){
    return document.getElementById(el);
}
function sendFileToServer(formData,status){
    var uploadURL ="{SITEURL}uploaded/index.php?action=1"; //Upload URL
    var extraData ={}; //Extra Data.
    var jqXHR=$.ajax({
        xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();
            if (xhrobj.upload) {
                xhrobj.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position;
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                    }
                    //Set progress
                    status.setProgress(percent);
                }, false);
            }
            xhrobj.addEventListener('load', function(event) {
                _('returnMessage').innerHTML = event.target.responseText;
            }, false);
            return xhrobj;
        },
        url: uploadURL,
        type: "POST",
        contentType:false,
        processData: false,
        cache: false,
        data: formData,
        success: function(data){
            status.setProgress(100);
            $('#images').load('{SITEURL}uploaded/index.php?action=2 #displayImages').fadeIn("slow");
            $('#setdefaultimg').load('{SITEURL}uploaded/index.php?action=4 #defaultPicture').fadeIn("slow");
            $('#getdefaultimg').load('{SITEURL}uploaded/index.php?action=6 #defaultPicture').fadeIn("slow");
            $("#file").val('');
            $('.statusbar').hide();
        }
    });
    status.setAbort(jqXHR);
}
var rowCount=0;
function createStatusbar(obj){
    rowCount++;
    var row="odd";
    if(rowCount %2 ==0) row ="even";
    this.statusbar = $("<div class='statusbar "+row+"'></div>");
    this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
    this.size = $("<span class='filesize'></span>").appendTo(this.statusbar);
    this.progressBar = $('<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: '+row+'%"></div></div>').appendTo(this.statusbar);
    this.abort = $("<div class='abort'>Abort</div>").appendTo(this.statusbar);
    obj.after(this.statusbar);
    this.setFileNameSize = function(name,size){
        var sizeStr="";
        var sizeKB = size/1024;
        if(parseInt(sizeKB) > 1024){
            var sizeMB = sizeKB/1024;
            sizeStr = sizeMB.toFixed(2)+" MB";
        }else{
            sizeStr = sizeKB.toFixed(2)+" KB";
        }
        this.filename.html(name);
        this.size.html(sizeStr);
    }
    this.setProgress = function(progress){
        var progressBarWidth =progress*this.progressBar.width()/ 100;
        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "%");
        if(parseInt(progress) >= 100){
            this.abort.hide();
        }
    }
    this.setAbort = function(jqxhr){
        var sb = this.statusbar;
        this.abort.click(function(){
            jqxhr.abort();
            sb.hide();
        });
    }
}
function handleFileUpload(files,obj){
    for (var i = 0; i < files.length; i++) {
        var fd = new FormData();
        fd.append('file', files[i]);
        var status = new createStatusbar(obj); //Using this we can set progress.
        status.setFileNameSize(files[i].name,files[i].size);
        sendFileToServer(fd,status);
    }
}
function setDefaultImage(image){
    var formdata = new FormData();
    formdata.append("setDefaultImage", image);
    var ajax = new XMLHttpRequest();
    ajax.addEventListener("load", function(event) {
        $("#setdefaultimg").load('{SITEURL}uploaded/index.php?action=4 #defaultPicture').fadeIn("slow");
        $('#getdefaultimg').load('{SITEURL}uploaded/index.php?action=6 #defaultPicture').fadeIn("slow");
    });
    ajax.addEventListener("error", function(event) {
        $("#returnMessage").innerHTML = "Didn't set the default image";
    });
    ajax.open("POST", "{SITEURL}uploaded/index.php?action=3");
    ajax.send(formdata);
}
function DeleteImage(image){
    var formdata = new FormData();
    formdata.append("PictureName", image);
    var ajax = new XMLHttpRequest();
    ajax.addEventListener("load", function(event) {
        $("#setdefaultimg").load('{SITEURL}uploaded/index.php?action=4 #defaultPicture').fadeIn("slow");
        $('#getdefaultimg').load('{SITEURL}uploaded/index.php?action=6 #defaultPicture').fadeIn("slow");
        $('#images').load('{SITEURL}uploaded/index.php?action=2 #displayImages').fadeIn("slow");
    });
    ajax.addEventListener("error", function(event) {
        $("#returnMessage").innerHTML = "The picture didn't delete please try again";
    });
    ajax.open("POST", "{SITEURL}uploaded/index.php?action=5");
    ajax.send(formdata);
}
$(document).ready(function(){
    $('#images').load('{SITEURL}uploaded/index.php?action=2 #displayImages').fadeIn("slow");
    $('#setdefaultimg').load('{SITEURL}uploaded/index.php?action=4 #defaultPicture').fadeIn("slow");

    var obj = $("#dragandrophandler");
    var obj2 = $("#manualhandler");
    obj.on('dragenter', function (e) {
        e.stopPropagation();
        e.preventDefault();
        $(this).css('border', '2px dotted #0B85A1');
    });
    obj.on('dragover', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });
    obj.on('drop', function (e) {
        $(this).css('border', '2px dotted #0B85A1');
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        //We need to send dropped files to Server
        handleFileUpload(files,$('#statusUpload'));
    });
    $(document).on('dragenter', function (e) {
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('dragover', function (e) {
        e.stopPropagation();
        e.preventDefault();
        obj.css('border', '2px solid #0B85A1');
    });
    $(document).on('drop', function (e) {
        e.stopPropagation();
        e.preventDefault();
        obj.css('border', '2px solid #0B85A1');
    });
    obj.css('border', '2px solid #0B85A1');
    obj2.on('click tap vclick', function (e) {
        var files = _('file').files;
        //We need to send dropped files to Server
        handleFileUpload(files,$('#statusUpload'));
    });
    $("div#images").hover(function () {
        $('span').on('click', function() {
            var imageName = $('img',this).attr('title');
            setDefaultImage(imageName);
        });
    });
    $("div#setdefaultimg").hover(function () {
        var imageName = $('img',this).attr('title');
        $("#deleteImage").click(function(){
            DeleteImage(imageName);
        });
    });
});
</script>
</code>```

Here is the html page that was asked for.

```<code><div id="imageUploader" class="modal fade">
    <!-- INCLUDE uploadhandler.tpl -->
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">{L_3500_1015494} <button class="btn btn-danger btn-xs pull-right" data-dismiss="modal">{L_678}</button></h4>
            </div>
            <div class="modal-body">
                <div class="well">
                    {MAXPICS}<br>{FREEMAXPIC}<br>{ALLOWEDPICTURETYPES}
                </div>
                <div id="returnMessage"></div>
                <ul class="nav nav-tabs" role="tablist">
                    <li class="active"><a href="#dragNdropUploader" data-toggle="tab">Upload Photos</a></li>
                    <li><a href="#Default" data-toggle="tab">Default Picture</a></li>
                    <li><a href="#pickDefault" data-toggle="tab">Uploaded Images</a></li>
                </ul>
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane" id="Default">
                        <div id="setdefaultimg"></div>
                    </div>
                    <div role="tabpanel" class="tab-pane active" id="dragNdropUploader">
                        <div class="well" id="dragandrophandler" align="center"><b>{L_3500_1015894}</b></div>
                        <div class="input-group">
                            <form id="upload_form" enctype="multipart/form-data" method="post">
                                <input type="hidden" name="csrftoken" value="{_CSRFTOKEN}">
                                <div class="input-group-btn">
                                    <input multiple="multiple"  type="file" class="btn btn-info" name="file" id="file">
                                </div >
                                <br>
                                <button type="button" class="btn btn-success"  value="Upload File" id="manualhandler">Upload File</button>
                            </form>
                        </div>
                        <div id="statusUpload"></div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="pickDefault">
                        <div class="alert alert-info" role="alert">Click on the picture that you want to use as your profile default picture.</div>
                        <div id="images"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答: Never mined it was working the hole time and i had to clear my browser cache. Stupid browser cache every time i update the js i have to clear my browser cache every time.</p>

Title: jquery not working in mobile browsers

Body:
I am making a image uploader using jquery and ajax and it works ok in computer browsers but will not work in mobile browsers. I did get it to work once but i changed something and didn't notice in till it was to late. Can someone please tell me why my coding stops working in mobile browsers.

It seems that the $(document).ready(function(){ is not loading on page load in cell phones but i have other js coding and they all work but this one is the only one that stops working.

Here is the html page that was asked for.

{L_3500_1015494} <button class="btn btn-danger btn-xs pull-right" data-dismiss="modal">{L_678}</button>

                    {MAXPICS}
{FREEMAXPIC}
{ALLOWEDPICTURETYPES}

Upload Photos

Default Picture

Uploaded Images

{L_3500_1015894}

                            <form id="upload_form" enctype="multipart/form-data" method="post">
                                <input type="hidden" name="csrftoken" value="{_CSRFTOKEN}">

                                    <input multiple="multiple"  type="file" class="btn btn-info" name="file" id="file">

                                <button type="button" class="btn btn-success"  value="Upload File" id="manualhandler">Upload File</button>
                            </form>

Click on the picture that you want to use as your profile default picture.


问:
Resize image - keep ratio - without background image
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

```<code>.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}
</code>```

and using this:

```<code>background-image: url(<?php the_post_thumbnail(); ?>);
</code>```

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

```<code><div class="featured-image">
   <?php the_post_thumbnail(); ?>
</div>
</code>```

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

答:
Try using inline CSS to achieve it in your HTML template like this:

<div
    class="featured-image"
    style="background-image:url(<?php the_post_thumbnail_url('full'); ?>);">

```

<p>Then use <code>CSS</code> to display the <code>image</code> properly:</p>

<pre class="lang-css prettyprint-override"><code>.featured-image{
   display:inline-block; /** or block, whichever suits your design **/
   background-size:cover;
   background-repeat:no-repeat;
}
</code>```

With this approach, you can even have more elements display on the image within the "featured-image" div.

I've just updated this answer to output the post thumbnail url rather than with the default img tag.

Body:
Im trying to achieve the effect shown on this site:

http://fofwebdesign.co.uk/template/_testing/scale-img/target-ratio-resize.htm

BUT this site does it using a background image for a div. I cannot use the background image as the image is inside Wordpress and it's being brought in dynamically using the following code:

   <?php the_post_thumbnail(); ?>

So I have tried the same approach and tried the following things o try and bring the image in as a background image:

.featured-image {
  max-width: 960px;
  /* actual img width */
  max-height: 150px;
  /* actual img height */*
  height: 150px;
  /* actual img height - IE7 */
  background-image: <?php the_post_thumbnail(); ?>;
  background-size: cover;
  background-position: center;
}

and using this:

background-image: url(<?php the_post_thumbnail(); ?>);

Alas, I cant seem to get it to work - Im not even sure I can use PHP inside a CSS document...

So I'm looking for a way to achieve this image resize just on the following class without using a background image...

   <?php the_post_thumbnail(); ?>

Any help would be massively appreciated - I don't even know if I'm thinking about it correctly or I'm missing something - Thanks!

Example of what I'm trying to achieve here:

Body:
Try using inline CSS to achieve it in your HTML template like this:

<div
    class="featured-image"
    style="background-image:url(<?php the_post_thumbnail_url('full'); ?>);">
</div>

Then use CSS to display the image properly:

.featured-image{
   display:inline-block; /** or block, whichever suits your design **/
   background-size:cover;
   background-repeat:no-repeat;
}

With this approach, you can even have more elements display on the image within the "featured-image" div.

I've just updated this answer to output the post thumbnail url rather than with the default img tag.


问:
InvalidValueError: not an instance of HTMLInputElement
FYI, I'm not a JavaScript Ninja but felt like I'll become one when I did a lot of things based on Google Maps recently.

I implemented a map. User can search for google places and place a marker for it. there's a text box for that. Or user can click on the map to place a marker to the place he's looking for or drag the marker.

Code remains the same. Design changed. Input field's id and name also same. No change to JS code. But this thing ain't working.

Here's the website

Google map is producing an error.

```<code> InvalidValueError: not an instance of HTMLInputElement
</code>```

I tried solution given here
But error still remains.

What could be the possible reason?

Here's the code:

```<code>        var map;
        var marker;
        var latLngC;

        function initialize()
        {
            latLngC = new google.maps.LatLng(14.5800, 121.0000);
            var mapOptions = {
        center: latLngC,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        };

            map = new google.maps.Map(document.getElementById('source_map'),
        mapOptions);

        var marker = new google.maps.Marker({
                position: latLngC,
                map: map,
                draggable: true
            });

            google.maps.event.addListener(marker, 'dragend', function (x)
            {
            document.getElementById('src_lat').value = x.latLng.lat();
            document.getElementById('src_long').value = x.latLng.lng();
            document.getElementById('pickup_location').innerHTML = x.latLng.lat()+' , '+x.latLng.lng();
                var geocoder = new google.maps.Geocoder;
                var infowindow = new google.maps.InfoWindow;
            geocodeLatLng(geocoder, map, infowindow,x.latLng.lat(),x.latLng.lng(),'source_point');
            });

            //Get coordinates,address Upon clicking a location in map (Source Map)
            //By Sajeev
            google.maps.event.addListener(map, 'click', function(x)
            {
            document.getElementById('src_lat').value = x.latLng.lat();
            document.getElementById('src_long').value = x.latLng.lng();
            document.getElementById('pickup_location').innerHTML = x.latLng.lat()+' , '+x.latLng.lng();
                var geocoder = new google.maps.Geocoder;
                var infowindow = new google.maps.InfoWindow;
            geocodeLatLng(geocoder, map, infowindow,x.latLng.lat(),x.latLng.lng(),'source_point');
            });

        //Add marker upon clicking on map
            //google.maps.event.addDomListener(map, 'click', addMarker);
            google.maps.event.addDomListener(map, 'click', function() { addMarker(map); });

        var places1 = new google.maps.places.Autocomplete(document.getElementById('source_point'));
        google.maps.event.addListener(places1, 'place_changed', function () {
            var place1 = places1.getPlace();

            var src_addr = place1.formatted_address;
            var src_lat = place1.geometry.location.lat();
            var src_long = place1.geometry.location.lng();

            var mesg1 = "Address: " + src_addr;
            mesg1 += "\nLatitude: " + src_lat;
            mesg1 += "\nLongitude: " + src_long;
            //alert(mesg1);

                 document.getElementById('src_lat').value = src_lat;
            document.getElementById('src_long').value = src_long;
            document.getElementById('pickup_location').innerHTML = src_lat+' , '+src_long;
        });
        //Add marker upon place change
        //google.maps.event.addDomListener(places1, 'place_changed', addMarker);
            google.maps.event.addDomListener(places1, 'place_changed', function() { addMarker(map); });

        }
        google.maps.event.addDomListener(window,'resize',initialize);
        google.maps.event.addDomListener(window, 'load', initialize);
</code>```

My HTML code looks like this:

```<code>   <form role="form" id="frm_source" name="frm_source" method="POST" action="index_action.php">

        <div class="form-group">
            <label for="source_point"><h2>Pickup Address</h2></label>
            <textarea type="text" id="source_point" name="source_point"  class="form-control" placeholder="Enter your pick up address here"></textarea>
        </div>

        <div class="form-group">
            <label for="pickup_location"><h3>GPS Cordinates</h3></label>
            <hr>
            <p id="pickup_location"></p>
        </div>

        <div class="form-group">
            <input type="hidden" id="src_lat" name="src_lat" placeholder="latitude" >
            <input type="hidden" id="src_long" name="src_long" placeholder="longitude" >
        </div>

    <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Next to enter destination address" />
    </form>
</code>```

Google Map

```<code><div id="source_map"></div>
</code>```

答:
This is an issue of DOM. Your javascript loads before loading your html document.

Make sure your html elements load first and then only load javascript.

Like

and then

  Your javascript code

Body:
FYI, I'm not a JavaScript Ninja but felt like I'll become one when I did a lot of things based on Google Maps recently.

I implemented a map. User can search for google places and place a marker for it. there's a text box for that. Or user can click on the map to place a marker to the place he's looking for or drag the marker.

Code remains the same. Design changed. Input field's id and name also same. No change to JS code. But this thing ain't working.

Here's the website

Google map is producing an error.

 InvalidValueError: not an instance of HTMLInputElement

I tried solution given here
But error still remains.

What could be the possible reason?

Here's the code:

        var map;
        var marker;
        var latLngC;

        function initialize()
        {
            latLngC = new google.maps.LatLng(14.5800, 121.0000);
            var mapOptions = {
        center: latLngC,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        };

            map = new google.maps.Map(document.getElementById('source_map'),
        mapOptions);

        var marker = new google.maps.Marker({
                position: latLngC,
                map: map,
                draggable: true
            });

            google.maps.event.addListener(marker, 'dragend', function (x)
            {
            document.getElementById('src_lat').value = x.latLng.lat();
            document.getElementById('src_long').value = x.latLng.lng();
            document.getElementById('pickup_location').innerHTML = x.latLng.lat()+' , '+x.latLng.lng();
                var geocoder = new google.maps.Geocoder;
                var infowindow = new google.maps.InfoWindow;
            geocodeLatLng(geocoder, map, infowindow,x.latLng.lat(),x.latLng.lng(),'source_point');
            });

            //Get coordinates,address Upon clicking a location in map (Source Map)
            //By Sajeev
            google.maps.event.addListener(map, 'click', function(x)
            {
            document.getElementById('src_lat').value = x.latLng.lat();
            document.getElementById('src_long').value = x.latLng.lng();
            document.getElementById('pickup_location').innerHTML = x.latLng.lat()+' , '+x.latLng.lng();
                var geocoder = new google.maps.Geocoder;
                var infowindow = new google.maps.InfoWindow;
            geocodeLatLng(geocoder, map, infowindow,x.latLng.lat(),x.latLng.lng(),'source_point');
            });

        //Add marker upon clicking on map
            //google.maps.event.addDomListener(map, 'click', addMarker);
            google.maps.event.addDomListener(map, 'click', function() { addMarker(map); });

        var places1 = new google.maps.places.Autocomplete(document.getElementById('source_point'));
        google.maps.event.addListener(places1, 'place_changed', function () {
            var place1 = places1.getPlace();

            var src_addr = place1.formatted_address;
            var src_lat = place1.geometry.location.lat();
            var src_long = place1.geometry.location.lng();

            var mesg1 = "Address: " + src_addr;
            mesg1 += "\nLatitude: " + src_lat;
            mesg1 += "\nLongitude: " + src_long;
            //alert(mesg1);

                 document.getElementById('src_lat').value = src_lat;
            document.getElementById('src_long').value = src_long;
            document.getElementById('pickup_location').innerHTML = src_lat+' , '+src_long;
        });
        //Add marker upon place change
        //google.maps.event.addDomListener(places1, 'place_changed', addMarker);
            google.maps.event.addDomListener(places1, 'place_changed', function() { addMarker(map); });

        }
        google.maps.event.addDomListener(window,'resize',initialize);
        google.maps.event.addDomListener(window, 'load', initialize);

My HTML code looks like this:

   <form role="form" id="frm_source" name="frm_source" method="POST" action="index_action.php">

Pickup Address

            <textarea type="text" id="source_point" name="source_point"  class="form-control" placeholder="Enter your pick up address here"></textarea>

GPS Cordinates

            <input type="hidden" id="src_lat" name="src_lat" placeholder="latitude" >
            <input type="hidden" id="src_long" name="src_long" placeholder="longitude" >

    <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Next to enter destination address" />
    </form>

Google Map


问:
TypeError: $(...).DataTable is not a function
I am trying to work with jQuery's Datatable JS for my project from this link.

I downloaded the complete library from the same source. All the examples given in the package seem to work fine, but when I try to incorporate them in my WebForms,the CSS,JS do not work at all.

Here is what I have done  :

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table id="myTable" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Start date</th>
                    <th>Salary</th>
                </tr>
            </tfoot>
            <tbody>
               <!-- table body -->
            </tbody>
        </table>
    </div>
    <script src="js/jquery.dataTables.js" type="text/javascript"></script>
    <script src="js/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#myTable').DataTable();
        });
    </script>
    </form>
</body>
</html>
</code>```

My file structure for the JS and CSS in my Solution looks as follows :

I have added all the necessary JS and CSS references as shown in the manual. Still the rendering isn't as expected. There is no CSS and even the JS doesn't work.

Also in the console i get the following errors:

```<code>ReferenceError: jQuery is not defined
TypeError: $(...).DataTable is not a function
</code>```

I have still not bound any dynamic data here (like within a repeater or so) still it is not working.

Can someone please guide me in the right direction for this problem ?

答:
This worked for me. But make sure to load the jquery.js before the preferred dataTable.js file. Cheers!</p>

```<code><script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/data-table/jquery.dataTables.js"></script>

 <script>$(document).ready(function () {
    $.noConflict();
    var table = $('# your selector').DataTable();
});</script>
</code>```

Body:
I am trying to work with jQuery's Datatable JS for my project from this link.

I downloaded the complete library from the same source. All the examples given in the package seem to work fine, but when I try to incorporate them in my WebForms,the CSS,JS do not work at all.

Here is what I have done  :

    <title></title>
    <link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css" />

    <form id="form1" runat="server">

                    Name
                    Position
                    Office
                    Age
                    Start date
                    Salary

                    Name
                    Position
                    Office
                    Age
                    Start date
                    Salary

    </form>

My file structure for the JS and CSS in my Solution looks as follows :

I have added all the necessary JS and CSS references as shown in the manual. Still the rendering isn't as expected. There is no CSS and even the JS doesn't work.

Also in the console i get the following errors:

ReferenceError: jQuery is not defined
TypeError: $(...).DataTable is not a function

I have still not bound any dynamic data here (like within a repeater or so) still it is not working.

Can someone please guide me in the right direction for this problem ?

Body:
This worked for me. But make sure to load the jquery.js before the preferred dataTable.js file. Cheers!

<script type="text/javascript" src="~/Scripts/jquery.js"></script>
<script type="text/javascript" src="~/Scripts/data-table/jquery.dataTables.js"></script>

 <script>$(document).ready(function () {
    $.noConflict();
    var table = $('# your selector').DataTable();
});</script>