问:
Image Slider Not Working in android
Hi i am trying to make a text Slider and Image Slider in my code, text slider is working fine but Image Slider Not Appearing, i don't know why is it happening

Here is my code

Intro Frag

```<code>public class Intro extends Fragment {
    ViewPager imagePager, textPager;
    MammalAdapter mammalAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mammals_intro, container, false);

        forTextSlider(R.id.mammalIntroTextPager, view);
        forImageSlider(R.id.mammalIntroimagePager, view);

        return view;
    }

    private void forImageSlider(int pager, View view) {
        imagePager = (ViewPager) view.findViewById(pager);
        int [] imageArray = {R.drawable.img1, R.drawable.img2,R.drawable.img3, R.drawable.img4,R.drawable.img5,
                R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10};
        mammalAdapter = new MammalAdapter(getActivity(), "img", imageArray);
        imagePager.setAdapter(mammalAdapter);
    }

    private void forTextSlider(int pager, View view) {
        textPager = (ViewPager) view.findViewById(pager);
        String [] mammalArray = getResources().getStringArray(R.array.mammal_info);
        mammalAdapter = new MammalAdapter(getActivity(), "text", mammalArray);
        textPager.setAdapter(mammalAdapter);
    }

}
</code>```

here is my Adapter Class

```<code>public class MammalAdapter extends PagerAdapter {
    Context context;
    int img[]; String text[];
    String type;

    public MammalAdapter(Context context, String type, String[] text) {
        this.context = context;
        this.text = text;
        this.type = type;
    }

    public MammalAdapter(Context context, String type, int[] img) {

        this.context = context;
        this.img = img;
        this.type = type;
    }

    LayoutInflater layoutInflater;

    @Override
    public int getCount() {
        if(type.equals("image"))
        {
            return img.length;
        }
        else if(type.equals("text")){
            return text.length;
        }
        return 0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view;
        if(type.equals("img"))
        {
            view = layoutInflater.inflate(R.layout.mammal_img_item, container, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.mammalImageItem);
            imageView.setImageResource(img[position]);
            container.addView(view);
            return view;
        }
        else if(type.equals("text")){
            view = layoutInflater.inflate(R.layout.mammal_text_item, container, false);
            TextView textView = (TextView) view.findViewById(R.id.mammalTextItem);
            textView.setText(text[position]);
            container.addView(view);
            return view;
        }

        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }
}
</code>```

my Xml Layout

```<code><android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/mammalIntroTextPager"/>

    <me.relex.circleindicator.CircleIndicator
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/indicator"/>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/mammalIntroimagePager"/>
</code>```

image item xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/purple"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mammalImageItem"/>

</LinearLayout>
</code>```

text item xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/whiteGrey"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mammalTextItem"/>

</LinearLayout>
</code>```

答:
Check "img" instead of "image" in getCount() as below :</p>

```<code>@Override
public int getCount() {
    if(type.equals("img"))
    {
        return img.length;
    }
    else if(type.equals("text")){
        return text.length;
    }
    return 0;
}
</code>```

Title: Image Slider Not Working in android

Body:
Hi i am trying to make a text Slider and Image Slider in my code, text slider is working fine but Image Slider Not Appearing, i don't know why is it happening

Here is my code

Intro Frag

public class Intro extends Fragment {
    ViewPager imagePager, textPager;
    MammalAdapter mammalAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mammals_intro, container, false);

        forTextSlider(R.id.mammalIntroTextPager, view);
        forImageSlider(R.id.mammalIntroimagePager, view);

        return view;
    }

    private void forImageSlider(int pager, View view) {
        imagePager = (ViewPager) view.findViewById(pager);
        int [] imageArray = {R.drawable.img1, R.drawable.img2,R.drawable.img3, R.drawable.img4,R.drawable.img5,
                R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10};
        mammalAdapter = new MammalAdapter(getActivity(), "img", imageArray);
        imagePager.setAdapter(mammalAdapter);
    }

    private void forTextSlider(int pager, View view) {
        textPager = (ViewPager) view.findViewById(pager);
        String [] mammalArray = getResources().getStringArray(R.array.mammal_info);
        mammalAdapter = new MammalAdapter(getActivity(), "text", mammalArray);
        textPager.setAdapter(mammalAdapter);
    }

}

here is my Adapter Class

public class MammalAdapter extends PagerAdapter {
    Context context;
    int img[]; String text[];
    String type;

    public MammalAdapter(Context context, String type, String[] text) {
        this.context = context;
        this.text = text;
        this.type = type;
    }

    public MammalAdapter(Context context, String type, int[] img) {

        this.context = context;
        this.img = img;
        this.type = type;
    }

    LayoutInflater layoutInflater;

    @Override
    public int getCount() {
        if(type.equals("image"))
        {
            return img.length;
        }
        else if(type.equals("text")){
            return text.length;
        }
        return 0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view;
        if(type.equals("img"))
        {
            view = layoutInflater.inflate(R.layout.mammal_img_item, container, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.mammalImageItem);
            imageView.setImageResource(img[position]);
            container.addView(view);
            return view;
        }
        else if(type.equals("text")){
            view = layoutInflater.inflate(R.layout.mammal_text_item, container, false);
            TextView textView = (TextView) view.findViewById(R.id.mammalTextItem);
            textView.setText(text[position]);
            container.addView(view);
            return view;
        }

        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }
}

my Xml Layout

<android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/mammalIntroTextPager"/>

    <me.relex.circleindicator.CircleIndicator
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/indicator"/>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:id="@+id/mammalIntroimagePager"/>

image item xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/purple"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mammalImageItem"/>

</LinearLayout>

text item xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="@color/whiteGrey"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/mammalTextItem"/>

</LinearLayout>

Body:
Check "img" instead of "image" in getCount() as below :

@Override
public int getCount() {
    if(type.equals("img"))
    {
        return img.length;
    }
    else if(type.equals("text")){
        return text.length;
    }
    return 0;
}


来源: stackexchange

问:
Export PATCH/PUT but not POST in @RepositoryRestResource
I am using spring-data-rest and exposing endpoints for CRUD-ing my entities through repositories.

One of entities should be updatable with PATCH/PUT methods, but it shouldn't be possible to create a new instance with POST method.

It seems that both actions go through save method so it seems not possible to export only some of the requests:

```<code>@RestResource(exported = ?)
@Override
<S extends User> S save(S s);
</code>```

What's the best way to accomplish that?

Should I override save method? Write custom Validator?

答:
One solution is to extend WebSecurityConfigurerAdapter (available in spring-security-config) to deny access for POST requests to the target url :

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/path_to_target_url").denyAll();
    }

}
</code>```

Any attempt to POST to the target URL will fail with a 401 Unauthorized error.

ContentLicense: CC BY-SA 3.0

Body:
I am using spring-data-rest and exposing endpoints for CRUD-ing my entities through repositories.

One of entities should be updatable with PATCH/PUT methods, but it shouldn't be possible to create a new instance with POST method.

It seems that both actions go through save method so it seems not possible to export only some of the requests:

@RestResource(exported = ?)
@Override
<S extends User> S save(S s);

What's the best way to accomplish that?

Should I override save method? Write custom Validator?

Body:
One solution is to extend WebSecurityConfigurerAdapter (available in spring-security-config) to deny access for POST requests to the target url :

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/path_to_target_url").denyAll();
    }

}

Any attempt to POST to the target URL will fail with a 401 Unauthorized error.


问:
Select values from multiple dictionaries into list of objects with LINQ
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

```<code>var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}
</code>```

Anyone have a good idea how to solve this?

答:
I feel you dictionary code will not run since it will not allow you to enter duplicate key value in same list. So here I have create a solution using list of Struct

```<code>class Stackoverflow
{
    struct OrderData
    {
        public string OrderID { get; set; }
        public string Row { get; set; }
    }
    static void Main(string[] args)
    {
        string strInputOrderID = "ORD1";

        ////Using Struct List
        List<OrderData> objOrderDataList = new List<OrderData>();

        OrderData objOrderData = new OrderData();
        objOrderData.OrderID = "ORD1";
        objOrderData.Row = "1";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD2";
        objOrderData.Row = "2";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD3";
        objOrderData.Row = "3";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD1";
        objOrderData.Row = "4";
        objOrderDataList.Add(objOrderData);

        List<OrderData> resultOrderDataList = (from data in objOrderDataList
                                               where data.OrderID.Equals(strInputOrderID)
                                               select data).ToList();
        Console.ReadLine();
    }
}
</code>```

I have run it and its working fine.
Kindly check and do let me know in comment.

Body:
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}

Anyone have a good idea how to solve this?

Body:
I feel you dictionary code will not run since it will not allow you to enter duplicate key value in same list. So here I have create a solution using list of Struct

class Stackoverflow
{
    struct OrderData
    {
        public string OrderID { get; set; }
        public string Row { get; set; }
    }
    static void Main(string[] args)
    {
        string strInputOrderID = "ORD1";

        ////Using Struct List
        List<OrderData> objOrderDataList = new List<OrderData>();

        OrderData objOrderData = new OrderData();
        objOrderData.OrderID = "ORD1";
        objOrderData.Row = "1";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD2";
        objOrderData.Row = "2";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD3";
        objOrderData.Row = "3";
        objOrderDataList.Add(objOrderData);

        objOrderData = new OrderData();
        objOrderData.OrderID = "ORD1";
        objOrderData.Row = "4";
        objOrderDataList.Add(objOrderData);

        List<OrderData> resultOrderDataList = (from data in objOrderDataList
                                               where data.OrderID.Equals(strInputOrderID)
                                               select data).ToList();
        Console.ReadLine();
    }
}

I have run it and its working fine.
Kindly check and do let me know in comment.


问:
docker build - exactly 1 argument
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

```<code>docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min
</code>```

I get the error message:

```<code>"docker build" requires exactly 1 argument(s).
</code>```

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

```<code>ln -s docker-devel/Dockerfile.min link1
</code>```

Then I just went through with the command:

```<code>docker build -t dragnn-oss:latest-minimal -f link1 .
</code>```

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

答:
While the other answers are all correct and you've found the solution, I want to point you to the documentation for docker build for anyone stumbling upon this. This is what the command is supposed to look like:

```<code>$ docker build [OPTIONS] PATH
</code>```

In your example, you specified two options (-f and -t). But you didn't specify the PATH argument. Citing the documentation:

The PATH specifies where to find the files for the “context” of the build on the Docker daemon.

The context is sent to the Docker daemon when building an image. You can just use . if you want to use the correct directory as Docker's build context, but as others have mentioned, you can also specify a specific directory, e.g. docker-devel.

Title: docker build - exactly 1 argument

Body:
I've been trying to build syntaxnet on my ubuntu setup and bumped into a problem (simple as it may be) that I had hard time finding the solution to.

Whenever I try to build using the command:

docker build -t dragnn-oss:latest-minimal -f docker-devel/Dockerile.min

I get the error message:

"docker build" requires exactly 1 argument(s).

Now, my docker version is 17.06 and according to this page,
[docker: "build" requires 1 argument. See 'docker build --help', I should be able to specify a Dockerfile that is located in a different directory, so I don't see what the problem is.

Edit: I created a symlink by doing:

ln -s docker-devel/Dockerfile.min link1

Then I just went through with the command:

docker build -t dragnn-oss:latest-minimal -f link1 .

and it worked.

I thought I did not need to put the . at the end since I specified the Dockerfile with -f but learned the mistake.

Body:
While the other answers are all correct and you've found the solution, I want to point you to the documentation for docker build for anyone stumbling upon this. This is what the command is supposed to look like:

$ docker build [OPTIONS] PATH

In your example, you specified two options (-f and -t). But you didn't specify the PATH argument. Citing the documentation:

The PATH specifies where to find the files for the “context” of the build on the Docker daemon.

The context is sent to the Docker daemon when building an image. You can just use . if you want to use the correct directory as Docker's build context, but as others have mentioned, you can also specify a specific directory, e.g. docker-devel.


问:
Get Image from the Storage Folder in View - Laravel 5.4
I'm trying to show the default.jpg avatar picture in my Laravel 5.4 profile.blade.php.

I created a link between the public folder and the storage folder with: php artisan storage:link.

The file is stored:

I check in the source code of my webpage which showed the src="/public/storage/uploads/avatar/default.jpg"

But still no image could be found. Could someone explain to me what I am missing?

答:
You can use this in the view once the storage link is present:

```<code><img src="{{ asset('storage/uploads/avatar/default.jpg') }}" alt="" />
</code>```

That will generate the full asset url to your image.

Body:
You can use this in the view once the storage link is present:

<img src="{{ asset('storage/uploads/avatar/default.jpg') }}" alt="" />

That will generate the full asset url to your image.


问:
In Blackberry, can we create common library that can be used by different applications?
I want to create a common 3rd party library, that can be shared and used by different applications and be consistent. Can we acheive this ?.If yes, how and where will this library be installed ?

and how can these library files be accessed from other apps ?

答: Yes you can do this. You create and compile the libary. You can either install it by itself ahead of the applications that depend on it, or with the applications. The desktop manager can use ALX files generated by the JDE to do this for you, or you can use JAD files for OTA installation. A libarary is just a code module like any other that does not have a desktop icon, so it installs in the same place as the rest of the modules. </p>

ContentLicense: CC BY-SA 2.5


问:
Sticky headers in react-virtualized
I am using a List component in react-virtualized to render a large number of items. In my implementation, the items are sectioned, and I want the section headers to be sticky so that the current section remains visible as users scroll down. Essentially, I need react-virtualized NOT to destroy the section headers as the scroll position changes (but continue to destroy other items). Is there any way to do this right now? I'm open to hacks as long as they aren't too crazy.

答:
We had similar requirements to you - we need a list that was sectioned with support for sticky headers. We could not achieve this with react-virtualized Lists/Grids, so I created https://github.com/marchaos/react-virtualized-sticky-tree which supports sticky headers.

See example here.

Title: Sticky headers in react-virtualized


问:
CSV Export failure from SQL View - line breaks after export
I have a SQL view which contains a column with concatenated text.

This text comes from a function:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[FC01_FunctionName]
    (@OrderNr VARCHAR(200))
RETURNS VARCHAR(2000)
BEGIN
    declare @r varchar(2000)
    declare @z varchar(2000)

    DECLARE cc CURSOR FOR
        SELECT SL.Description
        FROM dbo.[DBName] SL
        WHERE x = @OrderNr AND y = 1

    SET @r = ''

    OPEN cc

    WHILE ( 0 = 0 )
    BEGIN
        fetch next from cc into @z

        if (@@fetch_status <> 0)
            break

        if ( @r = '' )
        begin
            set @r = @z
        end
        else
        begin
            set @r = @r + char(13) + char(10) + @z
        end
    end

    close cc
    deallocate cc

    return @r
end
</code>```

The result looks like:

As you can see sometimes it's just 'one' text-element like 'Call 24 hrs. ...' and sometimes there are multiple text elements like '* Item No ...   Please ...* ...' and so on.

Every time I export the view to a .csv file, I got problems with rows which have more than one text element. It results in a new line for every additional text element and destroys the format (all the yellow marked text should be in one field -> the field with the text '***Item ...'):

After the last (yellow marked) text-element the normal entries go on.

The properties of the job which does the SQL view to .csv export are the following:

```<code>sqlcmd -W -s ";"  -E  -d master -Q "SET NOCOUNT ON; SELECT *  FROM [DB].[dbo].[ViewName];" -o "c:\Temp\XXX.csv"
</code>```

I believe that the export function thinks that the text-elements are separate and thats maybe the reason why the functions decides to spend a new line for every element.
I also believe that I have to change something in the sql function which creates the result for the field or maybe in the view itsself which gets the data.

This is the part of the sql query in the view which gets the data:

```<code>(SELECT [dbo].[FC01_FunctionName] (  x.[FieldName]) ) as [ColumnName],
</code>```

Any ideas? Thanks for you help!

答: Take a look at your text to columns settings in Excel. It may be that the csv export is correct (open in notepad to check) but Excel splits the lines as the file is opened.</p>

Body:
I have a SQL view which contains a column with concatenated text.

This text comes from a function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[FC01_FunctionName]
    (@OrderNr VARCHAR(200))
RETURNS VARCHAR(2000)
BEGIN
    declare @r varchar(2000)
    declare @z varchar(2000)

    DECLARE cc CURSOR FOR
        SELECT SL.Description
        FROM dbo.[DBName] SL
        WHERE x = @OrderNr AND y = 1

    SET @r = ''

    OPEN cc

    WHILE ( 0 = 0 )
    BEGIN
        fetch next from cc into @z

        if (@@fetch_status <> 0)
            break

        if ( @r = '' )
        begin
            set @r = @z
        end
        else
        begin
            set @r = @r + char(13) + char(10) + @z
        end
    end

    close cc
    deallocate cc

    return @r
end

The result looks like:

As you can see sometimes it's just 'one' text-element like 'Call 24 hrs. ...' and sometimes there are multiple text elements like '* Item No ...   Please ...* ...' and so on.

Every time I export the view to a .csv file, I got problems with rows which have more than one text element. It results in a new line for every additional text element and destroys the format (all the yellow marked text should be in one field -> the field with the text '***Item ...'):

After the last (yellow marked) text-element the normal entries go on.

The properties of the job which does the SQL view to .csv export are the following:

sqlcmd -W -s ";"  -E  -d master -Q "SET NOCOUNT ON; SELECT *  FROM [DB].[dbo].[ViewName];" -o "c:\Temp\XXX.csv"

I believe that the export function thinks that the text-elements are separate and thats maybe the reason why the functions decides to spend a new line for every element.
I also believe that I have to change something in the sql function which creates the result for the field or maybe in the view itsself which gets the data.

This is the part of the sql query in the view which gets the data:

(SELECT [dbo].[FC01_FunctionName] (  x.[FieldName]) ) as [ColumnName],

Any ideas? Thanks for you help!


问:
android.renderscript.renderscriptGL issue
I've been trying to create a live wallpaper on android.

I'm using the tutorial mentioned below.

http://mobile.tutsplus.com/tutorials/android/getting-started-with-renderscript-on-android/

I've copied the source code and also installed the support libraries.

I however cannot find support v8 in my SDK folders located in my program files in the windows system :(

These imports work for me after i changed my project properties and added

```<code>renderscript.target=18

renderscript.support.mode=true

sdk.buildtools=18.1.0

import android.renderscript.Allocation;

import android.renderscript.Element;

import android.renderscript.Float2;

import android.renderscript.Matrix4f;
</code>```

but these imports still do not work.

```<code>import android.renderscript.Mesh;

import android.renderscript.ProgramFragment;

import android.renderscript.ProgramFragmentFixedFunction;

import android.renderscript.ProgramRaster;

import android.renderscript.ProgramRaster.CullMode;

import android.renderscript.ProgramStore;

import android.renderscript.ProgramVertex;

android.renderscript.RenderScriptGL;
</code>```

How do I get these to work :(. I have been trying for a while.

Write now in my sdk extras I can see support for v4 but nothing for v8 :(
so because of that import android.support.v8 will also fail.

答:
renderscript-v8.jar you can find by sdk\build-tools\21.1.2\renderscript\lib

```<code>dependencies {
    compile files("libs/renderscript-v8.jar")
}
</code>```

but if you want use RenderScriptGL  you should compileSdkVersion -> 11~13

android {
    compileSdkVersion 13
    buildToolsVersion "25.0.2"

```<code>defaultConfig {
    applicationId "com.carapk.noisefield"
    minSdkVersion 13
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    renderscriptTargetApi 19
    renderscriptSupportModeEnabled false
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}
</code>```

Body:
I've been trying to create a live wallpaper on android.

I'm using the tutorial mentioned below.

http://mobile.tutsplus.com/tutorials/android/getting-started-with-renderscript-on-android/

I've copied the source code and also installed the support libraries.

I however cannot find support v8 in my SDK folders located in my program files in the windows system :(

These imports work for me after i changed my project properties and added

renderscript.target=18

renderscript.support.mode=true

sdk.buildtools=18.1.0

import android.renderscript.Allocation;

import android.renderscript.Element;

import android.renderscript.Float2;

import android.renderscript.Matrix4f;

but these imports still do not work.

import android.renderscript.Mesh;

import android.renderscript.ProgramFragment;

import android.renderscript.ProgramFragmentFixedFunction;

import android.renderscript.ProgramRaster;

import android.renderscript.ProgramRaster.CullMode;

import android.renderscript.ProgramStore;

import android.renderscript.ProgramVertex;

android.renderscript.RenderScriptGL;

How do I get these to work :(. I have been trying for a while.

Write now in my sdk extras I can see support for v4 but nothing for v8 :(
so because of that import android.support.v8 will also fail.

Body:
renderscript-v8.jar you can find by sdk\build-tools\21.1.2\renderscript\lib

dependencies {
    compile files("libs/renderscript-v8.jar")
}

but if you want use RenderScriptGL  you should compileSdkVersion -> 11~13

android {
    compileSdkVersion 13
    buildToolsVersion "25.0.2"

defaultConfig {
    applicationId "com.carapk.noisefield"
    minSdkVersion 13
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    renderscriptTargetApi 19
    renderscriptSupportModeEnabled false
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}


问:
The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation
i tried to install pod on ios project but getting this errors
diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation .
please suggest me something.</p>

答: Open terminal and first of all navigate to the root directory of your application, by using "cd" and then drag and drop your project in terminal. Hit enter and the path will be selected. Use "ls" command to verify that there the xcodeproject file is in that folder. Only then run "pod install" command. </p>


答:
Try this one:

```<code>     <img src="{{ asset('/storage/app/uploads/avatar/default.jpg') }}">
</code>```

And, Your /storage/...../default.jpg should be inside laravel public folder.

Title: Get Image from the Storage Folder in View - Laravel 5.4

Body:
I'm trying to show the default.jpg avatar picture in my Laravel 5.4 profile.blade.php.

I created a link between the public folder and the storage folder with: php artisan storage:link.

The file is stored:

I check in the source code of my webpage which showed the src="/public/storage/uploads/avatar/default.jpg"

But still no image could be found. Could someone explain to me what I am missing?

Body:
Try this one:

     <img src="{{ asset('/storage/app/uploads/avatar/default.jpg') }}">

And, Your /storage/...../default.jpg should be inside laravel public folder.


问:
Adding variables in AndroidManifest.xml, MainActivity.java and MainApplication.java in React Native
Is there a way to pass variables to AndroidManifest.xml, MainActivity.java and MainApplication.java?

I am planning to change the bundleId based on the environment I am running ex.: (com.app.dev and com.app.prod).

Right now I can easily pass variables to AndroidManifest.xml to change the app label, version code, version name and so on except the package name. Whenever I pass the variable "${bundleId}", it does not read the value inside the variable instead it reads the variable itself which is "${bundleId}" so it gives me an error.

Or is there any way on how to do environment setting on AndroidManifest.xml, MainActivity.java and MainApplication.java?

答:
I sorted it out in a much easier way.

I created a folder called dev and prod

Inside these folders are the xml and java files that contains bundle ID or package ID for each environment.

I created a bash script that will copy and paste the AndroidManifest.xml, MainActivity.java and MainApplication.java files from dev or prod folder to /android/app/src/main/... when I run the app.

I worked well :)

Case closed


问:
Change scrollbar position in TextBox?
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

```<code>SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
</code>```

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

答:
I usually do:

```<code>textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();
</code>```

Where selecting 0 characters just moves the cursor to the desired location (in the example code: at the end of the text).

Title: Change scrollbar position in TextBox?

Body:
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

Body:
I usually do:

textBox1.Select(textBox1.Text.Length, 0);
textBox1.ScrollToCaret();

Where selecting 0 characters just moves the cursor to the desired location (in the example code: at the end of the text).


问:
Eclipse Marketplace Not Showing All Search Results
I'm having an issue with the eclipse marketplace where doing a search doesn't show all available results. Searching for "java" I get a list of about 10 available plugins and at the bottom it says "156 matches. Browse for more solutions."

The problem is, when I click to browse more solutions I just get a blank emacs window and I can't seem to get to any of the other search results so I'm stuck with only the first 10 options.

How can I get it to show the rest of the results?

I'm running eclipse on a RedHat 6 Linux server and using a Cygwin XWindow to open it on my PC. My eclipse version info is below.

答:
When clicking on that link, Eclipse should be opening your web browser. Somehow, on your system, Eclipse thinks that Emacs is your web browser. You can fix this on your system set-up, or override that system settings in Eclipse for Eclipse only.

Set Default Browser

Open Preferences

Navigate to General -> Web Browser

Customize your settings

Visit Marketplace Directly

An alternative is to browse to the Eclipse Marketplace directly in your web browser:

https://marketplace.eclipse.org/search/site/java


问:
R looping with text to call different datasets
I want to create similar radar plots from numerous country "data sets" and title each chart accordingly. Can someone help me get the loop right where R recognizes my dataframe? The error I get is:

> Error in is.data.frame(df) : object 'data_i' not found

Code:

```<code>    data_China=rbind(rep(100,1) , rep(1,100) , data)
    data_Indonesia=rbind(rep(100,1) , rep(1,100) , data)
    data_India=rbind(rep(100,1) , rep(1,100) , data)
    data_Kenya=rbind(rep(100,1) , rep(1,100) , data)

    par(mfrow=c(2,2),mar=c(1, 1, 1, 1))

clist <- c("Indonesia", "China", "India", "Kenya")

for (i in clist) {
    # Custom the radarChart !
    radarchart(data_i  , axistype=1 ,

                #custom polygon
                pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 ,

                #custom the grid
                cglcol="grey", cglty=1, axislabcol="black", caxislabels=seq(0,100,20), cglwd=0.8,

                #custom labels
                vlcex=0.6 , title="i"
    )
    }
</code>```

答:
You can place all the datasets into a list, and iterate over that:</p>

```<code>dataList <- list(China = data_China,
                 Indonesia = data_Indonesia,
                 India = data_India,
                 Kenya = data_Kenya)

for (i in 1:length(dataList)) {
radarchart(dataList[[i]] , axistype=1 ,

            #custom polygon
            pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 ,

            #custom the grid
            cglcol="grey", cglty=1, axislabcol="black", caxislabels=seq(0,100,20), cglwd=0.8,

            #custom labels
            vlcex=0.6 , title=names(dataList)[i]
)
}
</code>```

Body:
I want to create similar radar plots from numerous country "data sets" and title each chart accordingly. Can someone help me get the loop right where R recognizes my dataframe? The error I get is:

> Error in is.data.frame(df) : object 'data_i' not found

Code:

    data_China=rbind(rep(100,1) , rep(1,100) , data)
    data_Indonesia=rbind(rep(100,1) , rep(1,100) , data)
    data_India=rbind(rep(100,1) , rep(1,100) , data)
    data_Kenya=rbind(rep(100,1) , rep(1,100) , data)

    par(mfrow=c(2,2),mar=c(1, 1, 1, 1))

clist <- c("Indonesia", "China", "India", "Kenya")

for (i in clist) {
    # Custom the radarChart !
    radarchart(data_i  , axistype=1 ,

                #custom polygon
                pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 ,

                #custom the grid
                cglcol="grey", cglty=1, axislabcol="black", caxislabels=seq(0,100,20), cglwd=0.8,

                #custom labels
                vlcex=0.6 , title="i"
    )
    }

Body:
You can place all the datasets into a list, and iterate over that:

dataList <- list(China = data_China,
                 Indonesia = data_Indonesia,
                 India = data_India,
                 Kenya = data_Kenya)

for (i in 1:length(dataList)) {
radarchart(dataList[[i]] , axistype=1 ,

            #custom polygon
            pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 ,

            #custom the grid
            cglcol="grey", cglty=1, axislabcol="black", caxislabels=seq(0,100,20), cglwd=0.8,

            #custom labels
            vlcex=0.6 , title=names(dataList)[i]
)
}


问:
Memory leakage in angular 2/4
How can i check if there is any Memory Leakage in my Angular 2/4 Application? What is the best tool/way to check that?

答: You can use the Chrome DevTools. To use it go to the Profiles panel, select the Record Allocation Timeline radio button and press the Start button. Now run the action that you suspect is causing the memory leak, and then press the stop recording button when you are finished.

Title: Memory leakage in angular 2/4


问:
Can i develop UWP program using windows 7 and visual studio 2015?
I have a raspberry pi3 with windows 10 IoT and my pc has windows 7. I can't use the XAMP Editor in visual studio 2015 because i need to upgrade my pc to windows 10... Is there a way to develop the app using windows 7?</p>

答:
As noted on the VS 2015 system requirements

```<code>For Windows Store and Windows Universal app development: Windows 8.1 and
Windows Phone 8.1 development require Windows 8.1 Update or later.
</code>```

IOW: Windows 8.1 (fully updated) or Windows 10 is required to develop a UWP.

With VS 2017, UWP development requires Windows 10. See VS 2017 system requirements

Body:
As noted on the VS 2015 system requirements

For Windows Store and Windows Universal app development: Windows 8.1 and
Windows Phone 8.1 development require Windows 8.1 Update or later.

IOW: Windows 8.1 (fully updated) or Windows 10 is required to develop a UWP.

With VS 2017, UWP development requires Windows 10. See VS 2017 system requirements


问:
Can someone look into a web servers folders?
More a web server security question.

Is it possible for someone to "probe" into a folder on a web server, even if an index file is in place?

I assume they can't, but if I wanted to store .pdf applications as random names (93fe3509edif094.pdf) I want to make sure there's no way to list all the pdfs in the folder.

Thank you.

答: Just disable the directory listing in your web server</p>


问:
NPM installation issue ubuntu
I want to install npm for use angular2 with laravel5.2 , but while installation of npm. I got below issue :  </p>

```<code>npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/

/usr/local/lib/node_modules/npm/lib/install.js:298
        [this, (next) => { computeMetadata(this.idealTree); next() }],
                       ^
npm ERR! Unexpected token >

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-06T07_21_24_104Z-debug.log
</code>```

<p>Please let me know if anyone aware about same.  </p>

答:
Try to run:

```<code>curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
</code>```

Double check there is no error during install.

Then restart you ssh session (just in case) by typing exit then re-connect.

Then check your install with node -v.

If it still does not work, you should check which node is used with which node. The problem may be here (an old version of node is installed somewhere else and in use).

Title: NPM installation issue ubuntu

Body:
I want to install npm for use angular2 with laravel5.2 , but while installation of npm. I got below issue :

npm WARN npm npm does not support Node.js v0.10.25
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm You can find the latest version at https://nodejs.org/

/usr/local/lib/node_modules/npm/lib/install.js:298
        [this, (next) => { computeMetadata(this.idealTree); next() }],
                       ^
npm ERR! Unexpected token >

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/swapnily/.npm/_logs/2017-07-06T07_21_24_104Z-debug.log

Please let me know if anyone aware about same.

Body:
Try to run:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Double check there is no error during install.

Then restart you ssh session (just in case) by typing exit then re-connect.

Then check your install with node -v.

If it still does not work, you should check which node is used with which node. The problem may be here (an old version of node is installed somewhere else and in use).


问:
create multiple branch from one trunk
i trying to create multiple branch from trunk , but after creating branch1 if i creating branch2 ,  branch1 source code also getting copy inside branch 2 .

can anyone help me what is correct way to create multiple branch from trunk .
Thanks

答:
Unlike other version control systems, branches are not first class elements or, in other words, Subversion does not have tags and branches among its feature set. Instead, they are emulated with regular directories, under the assumption that copies are cheap. So you branch and tag just like you'd organise your files in your computer.

In your case, you have this peculiar directory structure:

```<code>Testing11
       \_ Trunk
             \_ Branches
                      \_ Dev_Bhavana
                                  \_ Branches
                                           \_ t1
                                           \_ t2
</code>```

No wonder that you can't figure out what its directory contains. You only need to do some clean-up.

Last but not least, Subversion does not enforce any directory structure, but suggests a Repository Layout based in these directory names:

trunk

branches

tags

Pros:

It's automatically obvious for any programmer who joins the team

Some client tools (such as TortoiseSVN) recognise these names and offer you specific features (such as a warning when committing changes to a tag).

Title: create multiple branch from one trunk

Body:
Unlike other version control systems, branches are not first class elements or, in other words, Subversion does not have tags and branches among its feature set. Instead, they are emulated with regular directories, under the assumption that copies are cheap. So you branch and tag just like you'd organise your files in your computer.

In your case, you have this peculiar directory structure:

Testing11
       \_ Trunk
             \_ Branches
                      \_ Dev_Bhavana
                                  \_ Branches
                                           \_ t1
                                           \_ t2

No wonder that you can't figure out what its directory contains. You only need to do some clean-up.

Last but not least, Subversion does not enforce any directory structure, but suggests a Repository Layout based in these directory names:

trunk

branches

tags

Pros:

It's automatically obvious for any programmer who joins the team

Some client tools (such as TortoiseSVN) recognise these names and offer you specific features (such as a warning when committing changes to a tag).


问:
php correct json numbers and strings encoding
I have a problem with encoding php array to json. Part of my data are stings like '555', '3M', part of data are numbers: floats or integers. On frontend I need to receive strings as strings and numbers as numbers as numbers for correct sorting, searching , etc. Php has a JSON_NUMERIC_CHECK, but this will convert my sting '555' value into number. Is there any approach except first converting strings like strings, then numbers with  JSON_NUMERIC_CHECK option and then concatenating result?

答:
Actually, the problem was with numbers. Because I queried numeric data from db, I received it as strings. So I converted string to numbers, and received correctly encoded data on frontend: </p>

```<code>   array_walk_recursive($data, function(&$val) {
        if (is_numeric($val)) $val = (float) $val;
    });
</code>```

Body:
Actually, the problem was with numbers. Because I queried numeric data from db, I received it as strings. So I converted string to numbers, and received correctly encoded data on frontend:

   array_walk_recursive($data, function(&$val) {
        if (is_numeric($val)) $val = (float) $val;
    });


问:
Google nearBy BLE background subscription only for screen on events
As per the current Google nearBy documentation, for background BLE subscription
"low-power scans are triggered only at screen-on events, even when your app is not currently active."
https://developers.google.com/nearby/messages/android/get-beacon-messages#subscribe_in_the_background

The application i was designing needed to notify the user even when the screen is Off.
Is there anyway to get the callback irrespective of this screen-on trigger using the NearBy API approach.

答: Sorry, we don't support this for power reasons. You can implement this using the lower level BluetoothLeScanner API and a background service, but you may be subject to other restrictions on newer versions of Android.</p>


问:
jQuery CSS Property
I used the .css() for changing the border color for an element, and every time I perform the action that trigger the jQuery script, the border changes like it supposed to, but changes back after a second.

This is the code:

$("#form1").submit(function() {
  if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
  $("#foo").css('border', '3px solid red');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<div>
  <form id="form1" name="form1" method="post">
    <div class="textInput">
      PO: <input type="text" class="txtBox" name="foo" id="foo"><br /><br />
    </div>
    <input type="submit" name="Submit" value="Submit" />
  </form>
</div></code>```

No additional JS or css file.

答:
Without knowing but taking the hint this is some form of validation, the suggestion to stop the page being submitted appears to be the correct one - but an adjustment to Ebrahim's answer would be something like this:</p>

```<code>$("#form1").submit(function(e) {
  // do your validation
  if (!$('#foo').val().length) {
    // if it doesn't meet the constraints, do your things to highlight it
    $("#foo").css('border', '3px solid red');
    // then halt the submission process for the user to review
    e.preventDefault();
    // jump from control of this method so it doesn't continue
    return;
  }
  // otherwise, do anything else you need and allow the form to submit
});
</code>```

Title: jQuery CSS Property

Body:
I used the .css() for changing the border color for an element, and every time I perform the action that trigger the jQuery script, the border changes like it supposed to, but changes back after a second.

This is the code:

$("#form1").submit(function() {
  if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
  $("#foo").css('border', '3px solid red');
});

  <form id="form1" name="form1" method="post">

      PO: <input type="text" class="txtBox" name="foo" id="foo">

    <input type="submit" name="Submit" value="Submit" />
  </form>

No additional JS or css file.

Body:
Without knowing but taking the hint this is some form of validation, the suggestion to stop the page being submitted appears to be the correct one - but an adjustment to Ebrahim's answer would be something like this:

$("#form1").submit(function(e) {
  // do your validation
  if (!$('#foo').val().length) {
    // if it doesn't meet the constraints, do your things to highlight it
    $("#foo").css('border', '3px solid red');
    // then halt the submission process for the user to review
    e.preventDefault();
    // jump from control of this method so it doesn't continue
    return;
  }
  // otherwise, do anything else you need and allow the form to submit
});


问:
convert date format to 'YYYYMMDD'
In Javascript, I have date string as shown below:

```<code>var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
</code>```

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

答:
The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.

The Date object also offers methods to extract from the instance the year, month and day.

It's well documented and there are plenty of examples if you just Google for it.

What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.

For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):

```<code>dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d = new Date( dateStr );

---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2
</code>```

If you need to handle timezone properly the easiest way is to use a library like MomentJS

Title: convert date format to 'YYYYMMDD'

Body:
In Javascript, I have date string as shown below:

var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

Body:
The Date object is able to parse dates as string d = new Date( dateStr ); provided that they are properly formatted like the example in your question.

The Date object also offers methods to extract from the instance the year, month and day.

It's well documented and there are plenty of examples if you just Google for it.

What is worth mentioning is that the Date object doesn't handle timezone and the internal date-time is always converted into the client's timezone.

For example here's what I get if I try to parse your date in my browser (I'm in GMT+01):

dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
d = new Date( dateStr );

---> Wed Mar 25 2015 01:00:00 GMT+0100 (CET) = $2

If you need to handle timezone properly the easiest way is to use a library like MomentJS


问:
Tutorial for sending rich media push notification via firebase
Notification service extension is not triggered when notification is sent via firebase. It will show regular notification without image.

What is the exact payload I have to send.

I already tried this payload:

```<code>{ to = fedAu7oCO78:APA91bFAdcwctoVVcj-KtfQwD5hdBN7shcgw9QRgh-xQoLlKgBptqG2fxSYmL9T73BY5yOi81OOFbUVoZJp8b4hwPTCxvK4ZvR6hek, content_available = True, mutable_content = True, notification = { icon = myicon, badge = 1, sound = default, body = testing, title = iostest, NotificationImage = https://NotificationImage/822cf50ae5944995a033c51bf1c857a3banner1.jpg}, data = { mediaUrl = https://www.manijewel.com/NotificationImage/822cf50ae5944995a033c51bf1c857a3banner1.jpg },
priority = high, time_to_live = 6000 }
</code>```

or

```<code>{
   "to": "dWB537Nz1GA:APA91bHIjJ5....",
   "data":
   {
      "message": "Offer!",
      "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
   },
   "notification":
   {
      "body": "Enter your message",
      "sound": "default",
      "content-available": 1,
      "mutable-content": 1
   }
}
</code>```

And I get this:

I am using FCM for my project. It's have rich push notification for a type. I tried to modify most of possible ways to get push from FCM. I got only ordinary push from FCM, not with image.

I am also checking with APNS same coding using push try. I got what expected design for push notification.

Here on ios side payload

```<code>{
  "aps": {
     "alert": "Enter your message",
     "badge": 1,
     "sound": "default",
     "content-available": 1,
     "mutable-content": 1
  },
  "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
}
</code>```

I use the pusher blog And

[1]: https://mobisoftinfotech.com/resources/mguide/ios-10-rich-notifications-tutorial/ to link rich media notification.Please help me how to sort this and where am i doing wrong.

thanx in advance

答:
Payload format should be like below:-</p>

```<code>{
       "to": "dWB537Nz1GA:APA91bHIjJ5....",
       "content_available": true,
       "mutable_content": true,
       "data":
       {
          "message": "Offer!",
          "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
       },
       "notification":
       {
          "body": "Enter your message",
          "sound": "default"
       }
}
</code>```

Body:
Notification service extension is not triggered when notification is sent via firebase. It will show regular notification without image.

What is the exact payload I have to send.

I already tried this payload:

{ to = fedAu7oCO78:APA91bFAdcwctoVVcj-KtfQwD5hdBN7shcgw9QRgh-xQoLlKgBptqG2fxSYmL9T73BY5yOi81OOFbUVoZJp8b4hwPTCxvK4ZvR6hek, content_available = True, mutable_content = True, notification = { icon = myicon, badge = 1, sound = default, body = testing, title = iostest, NotificationImage = https://NotificationImage/822cf50ae5944995a033c51bf1c857a3banner1.jpg}, data = { mediaUrl = https://www.manijewel.com/NotificationImage/822cf50ae5944995a033c51bf1c857a3banner1.jpg },
priority = high, time_to_live = 6000 }

or

{
   "to": "dWB537Nz1GA:APA91bHIjJ5....",
   "data":
   {
      "message": "Offer!",
      "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
   },
   "notification":
   {
      "body": "Enter your message",
      "sound": "default",
      "content-available": 1,
      "mutable-content": 1
   }
}

And I get this:

I am using FCM for my project. It's have rich push notification for a type. I tried to modify most of possible ways to get push from FCM. I got only ordinary push from FCM, not with image.

I am also checking with APNS same coding using push try. I got what expected design for push notification.

Here on ios side payload

{
  "aps": {
     "alert": "Enter your message",
     "badge": 1,
     "sound": "default",
     "content-available": 1,
     "mutable-content": 1
  },
  "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
}

I use the pusher blog And

[1]: https://mobisoftinfotech.com/resources/mguide/ios-10-rich-notifications-tutorial/ to link rich media notification.Please help me how to sort this and where am i doing wrong.

thanx in advance

Body:
Payload format should be like below:-

{
       "to": "dWB537Nz1GA:APA91bHIjJ5....",
       "content_available": true,
       "mutable_content": true,
       "data":
       {
          "message": "Offer!",
          "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
       },
       "notification":
       {
          "body": "Enter your message",
          "sound": "default"
       }
}


答: Generally, no. Instead of creating an "index" file, you may also unset the apache "Options Indexes"</p>

Title: Can someone look into a web servers folders?

Body:
More a web server security question.

Is it possible for someone to "probe" into a folder on a web server, even if an index file is in place?

I assume they can't, but if I wanted to store .pdf applications as random names (93fe3509edif094.pdf) I want to make sure there's no way to list all the pdfs in the folder.

Thank you.


问:
Returning to my if statement
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the         while   statements. Any advice would be appreciated.

```<code>print('Welcome to Word Madness!!')

vowels = list('aeioyu')

consonants = list('bcdfghjklmnpqrstvwxz')

wordCount = 0

complete = False

while not complete:
    mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
    print('You chose to enter: ',str(mode))

#When user chooses to quit program will system exit

    if mode == 'quit':
        print('Sorry to see you go! Come back to Word Madness soon!')
        import sys
        sys.exit(0)

#If vowels are selected then they will be counted

    if mode == 'vowels':
        word = input('Please enter your word!')
        number_of_vowels = sum(word.count(i) for i in vowels)
        print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice == 'n':
            averageV = int(number_of_vowels // wordCount)
            print('Your average number of Vowels was: ',averageV)
            print('Thank you for using Word Madness!')
            complete = True

        else:
            mode = 'vowels'

#If consonants are selected then they will be counted

    elif mode == 'consonants':
        word = input('Please enter your word!')
        number_of_consonants = sum(word.count(i) for i in consonants)
        print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice =='n':
            averageC = int(number_of_consonants // wordCount)
            print('Your average number of Consonants was: ',averageC)
            print('Thank you for using Word Madness!')
            complete = True
#If user has no more words to enter then they are given an average

         else:
            mode == 'consonants'

    else:
        print('ERROR! INVALID INPUT DETECTED!')
</code>```

答:
From your question and the comment, I assume that you want to ask

mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()

only once.  If that is the case, you can move that statement just above the while loop.
Or also, you can give an option whether user really wants to specify the mode again.

Title: Returning to my if statement

Body:
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the         while   statements. Any advice would be appreciated.

print('Welcome to Word Madness!!')

vowels = list('aeioyu')

consonants = list('bcdfghjklmnpqrstvwxz')

wordCount = 0

complete = False

while not complete:
    mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
    print('You chose to enter: ',str(mode))

#When user chooses to quit program will system exit

    if mode == 'quit':
        print('Sorry to see you go! Come back to Word Madness soon!')
        import sys
        sys.exit(0)

#If vowels are selected then they will be counted

    if mode == 'vowels':
        word = input('Please enter your word!')
        number_of_vowels = sum(word.count(i) for i in vowels)
        print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice == 'n':
            averageV = int(number_of_vowels // wordCount)
            print('Your average number of Vowels was: ',averageV)
            print('Thank you for using Word Madness!')
            complete = True

        else:
            mode = 'vowels'

#If consonants are selected then they will be counted

    elif mode == 'consonants':
        word = input('Please enter your word!')
        number_of_consonants = sum(word.count(i) for i in consonants)
        print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice =='n':
            averageC = int(number_of_consonants // wordCount)
            print('Your average number of Consonants was: ',averageC)
            print('Thank you for using Word Madness!')
            complete = True
#If user has no more words to enter then they are given an average

         else:
            mode == 'consonants'

    else:
        print('ERROR! INVALID INPUT DETECTED!')


问:
My script is using .encode('utf-8') a lot. I feel like im doing something wrong
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

```<code># -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """
    <h2 class='title'>{title}</h2>
    <a class='link' href='{link}'>{title}</a>
    <span class='description'>{description}</span>
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')
</code>```

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

```<code>C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)
</code>```

答:
Your kwargs are unicode strings. You should define your template as a unicode string as well, by using the u prefix, then encode once at the end.

```<code>template = u"""
<h2 class='title'>{title}</h2>
<a class='link' href='{link}'>{title}</a>
<span class='description'>{description}</span>
"""
return template.format(title=title, link=link, description=description).encode('utf-8')
</code>```

Body:
The problem i have with this script is that i have to keep calling .encode('utf-8') and this doesn't seem very zen to me. I must be doing something wrong.

# -*- coding: utf-8 -*-

""" Simple rss to html converter """

__version__ = "0.0.1"
__author__ = "Ricky L Wilson"

import StringIO
from feedparser import parse as parsefeed
from bs4 import BeautifulSoup as bs

def entry2html(**kwargs):
    """ Format feedparser entry """
    title = kwargs['title'].encode('utf-8')
    link = kwargs['link'].encode('utf-8')
    description = kwargs['description'].encode('utf-8')
    template = """

{title}

    {title}
    {description}
    """
    return template.format(title=title, link=link, description=description)

def convert_feed(**kwargs):
    """ Main loop """
    out = StringIO.StringIO("")
    for entry in parsefeed(kwargs['url']).entries:
        title = entry['title']
        link = entry['link']
        description = entry['description']
        print >> out, entry2html(title=title, link=link, description=description)
    return bs(out.getvalue(), 'lxml').prettify()

def save_file(url, fname):
    ''' Save data to disc'''
    with open(fname, 'w') as file_object:
        file_object.write(convert_feed(url=url).encode('utf-8'))

print save_file('http://stackoverflow.com/feeds', 'index.html')

PS. If i remove any of them the script will break.

I tried putting # -*- coding: utf-8 -*- at the top of the file but that didn't fix it. i got this error.

C:\Python27>python rss2html.py
  File "rss2html.py", line 40
    save_file('http://stackoverflow.com/feeds', 'index.html')
            ^
SyntaxError: invalid syntax

C:\Python27>python rss2html.py
Traceback (most recent call last):
  File "rss2html.py", line 40, in <module>
    save_file('http://stackoverflow.com/feeds', 'index.html')
  File "rss2html.py", line 38, in save_file
    file_object.write(convert_feed(url=url))
  File "rss2html.py", line 32, in convert_feed
    print >> out, entry2html(title=title, link=link, description=description)
  File "rss2html.py", line 22, in entry2html
    return template.format(title=title, link=link, description=description)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 172: ordinal not in range(128)

Body:
Your kwargs are unicode strings. You should define your template as a unicode string as well, by using the u prefix, then encode once at the end.

template = u"""
<h2 class='title'>{title}</h2>
<a class='link' href='{link}'>{title}</a>
<span class='description'>{description}</span>
"""
return template.format(title=title, link=link, description=description).encode('utf-8')


问:
Decode Base64 encoded data on the java server
Approach: I am encoding simple data to base64 and then sending it to the server. Similarly, i am trying to decode base64 encoded data on Java server but there is always exception that it is unable to decode it properly. Any help is appreciated.

Client Code Snippet(Android Application):

```<code>private String random(int size) {

  Random generator = new Random();
  StringBuilder randomStringBuilder = new StringBuilder();
  //int randomLength = generator.nextInt(size);
  char tempChar;
  for (int i = 0; i < size; i++){
      tempChar = (char) (generator.nextInt(90 - 65) + 65);
      randomStringBuilder.append(tempChar);
  }
  return randomStringBuilder.toString();
}

String data = random(packetSize);
Log.d(data, " Random String");

byte [] encodedBuffer = Base64.encode(data.getBytes("UTF-8"), 0);
DatagramPacket packet =
        new DatagramPacket(encodedBuffer, encodedBuffer.length, address, dstPort);
Log.d(String.valueOf(packetSize), "Sending packet Size");

SocketHandler.getSocket().send(packet);
</code>```

Server Code Snippet:

```<code>private String decodeBase64(String encoded) {
  try
  {
    byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));
    String decodeData = new String(decodedBytes);
    return decodeData;
  }
  catch (Exception e) {
    System.out.println("Unable to decode");
    return null;
  }
}

public void run() {
  try {
    byte[] buf = new byte[1400];
    DatagramPacket packet = packet = new DatagramPacket(buf, buf.length);
    System.out.println("UDP Server waiting");
    while(true)
    {

      try {
        SocketHandler.getSocket().receive(packet);
        System.out.println("Received: " + decodeBase64(new String(packet.getData())));

      }
      catch (SocketException e1) {
        System.out.println("Socket closed " + e1);
      }
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}
</code>```

Exception:

```
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 147
    at java.util.Base64$Decoder.decode0(Base64.java:742)
    at java.util.Base64$Decoder.decode(Base64.java:526)
```

Sample Input(Random String generated):

LVYAGHNVAUUEVNSEQHLHNNHGOHKFJQICSGXMXLJGBICOGJTWGBFLRSROJQWIWCETRXMTDWASGILXCDPRBIYAWFTBRRWN

答:
May be try this

```<code>import java.util.Base64;

public static void main(String[] args)
{
    String input = new String("FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORLVGNHNLALVUEWVXLHUKAMRHSPONMAMRB");
    System.out.println("input " + input);
    byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes());
    System.out.println("encodedBytes " + new String(encodedBytes));
    byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
    System.out.println("output " + new String(decodedBytes));

 }
</code>```

Compiled and executed online it gives

input FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORâLVGNHNLALVUEWVXLHUKAâMRHSPONMAMRB

encodedBytes Rk1LUEFSU1FRVElFTlVEWVdNUldYS0dFRUFPSEZKQkVYTUtHV0NVRkJQSUNFR1lOWEVRV1FERE9YV09Sw6LCgMKMTFZHTkhOTEFMVlVFV1ZYTEhVS0HDosKAwoxNUkhTUE9OTUFNUkI=

output
FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORâLVGNHNLALVUEWVXLHUKAâMRHSPONMAMRB

Body:
Approach: I am encoding simple data to base64 and then sending it to the server. Similarly, i am trying to decode base64 encoded data on Java server but there is always exception that it is unable to decode it properly. Any help is appreciated.

Client Code Snippet(Android Application):

private String random(int size) {

  Random generator = new Random();
  StringBuilder randomStringBuilder = new StringBuilder();
  //int randomLength = generator.nextInt(size);
  char tempChar;
  for (int i = 0; i < size; i++){
      tempChar = (char) (generator.nextInt(90 - 65) + 65);
      randomStringBuilder.append(tempChar);
  }
  return randomStringBuilder.toString();
}

String data = random(packetSize);
Log.d(data, " Random String");

byte [] encodedBuffer = Base64.encode(data.getBytes("UTF-8"), 0);
DatagramPacket packet =
        new DatagramPacket(encodedBuffer, encodedBuffer.length, address, dstPort);
Log.d(String.valueOf(packetSize), "Sending packet Size");

SocketHandler.getSocket().send(packet);

Server Code Snippet:

private String decodeBase64(String encoded) {
  try
  {
    byte[] decodedBytes = Base64.getMimeDecoder().decode(encoded.getBytes("UTF-8"));
    String decodeData = new String(decodedBytes);
    return decodeData;
  }
  catch (Exception e) {
    System.out.println("Unable to decode");
    return null;
  }
}

public void run() {
  try {
    byte[] buf = new byte[1400];
    DatagramPacket packet = packet = new DatagramPacket(buf, buf.length);
    System.out.println("UDP Server waiting");
    while(true)
    {

      try {
        SocketHandler.getSocket().receive(packet);
        System.out.println("Received: " + decodeBase64(new String(packet.getData())));

      }
      catch (SocketException e1) {
        System.out.println("Socket closed " + e1);
      }
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}

Exception:

java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 147
    at java.util.Base64$Decoder.decode0(Base64.java:742)
    at java.util.Base64$Decoder.decode(Base64.java:526)

Sample Input(Random String generated):

LVYAGHNVAUUEVNSEQHLHNNHGOHKFJQICSGXMXLJGBICOGJTWGBFLRSROJQWIWCETRXMTDWASGILXCDPRBIYAWFTBRRWN

Body:
May be try this

import java.util.Base64;

public static void main(String[] args)
{
    String input = new String("FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORLVGNHNLALVUEWVXLHUKAMRHSPONMAMRB");
    System.out.println("input " + input);
    byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes());
    System.out.println("encodedBytes " + new String(encodedBytes));
    byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
    System.out.println("output " + new String(decodedBytes));

 }

Compiled and executed online it gives

input FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORâLVGNHNLALVUEWVXLHUKAâMRHSPONMAMRB

encodedBytes Rk1LUEFSU1FRVElFTlVEWVdNUldYS0dFRUFPSEZKQkVYTUtHV0NVRkJQSUNFR1lOWEVRV1FERE9YV09Sw6LCgMKMTFZHTkhOTEFMVlVFV1ZYTEhVS0HDosKAwoxNUkhTUE9OTUFNUkI=

output
FMKPARSQQTIENUDYWMRWXKGEEAOHFJBEXMKGWCUFBPICEGYNXEQWQDDOXWORâLVGNHNLALVUEWVXLHUKAâMRHSPONMAMRB


问:
Is it possible to draw a report without using birt report designer？
I have a big issue with birt report recently. We all know that we can use birt report designer to draw a report by drag some report elements from palette. But,my leader have a point that if we can draw a simple report without using birt report designer?</p>

答: You can use Excel as a data source and then use the API to pull information out of that or build a report. As mentioned earlier, you can also create the XML that defines the report outside of the designer as well. You could also write JavaScript or other client side code to take the Excel file and extract data from that to use in a report. </p>


问:
Create shortcut of directory
I want to create shortcut of Autostart directory on my desktop.

I know how to create shortcut of any application for example notepad but how can I create shortcut of directory?

I am trying something like this

```<code>$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()
</code>```

Errors:

```<code>+ $objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Ro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException
</code>```

答:
You can use the Environment Class:</p>

```<code>$StartupFolder = [Environment]::GetFolderPath('Startup')
$DesktopFolder = [Environment]::GetFolderPath('Desktop')

$wshshell = New-Object -ComObject WScript.Shell
$link = $wshshell.CreateShortcut((Join-path $DesktopFolder "Autostart.lnk"))
$link.TargetPath = $StartupFolder
$link.Save()
</code>```

Title: Create shortcut of directory

Body:
I want to create shortcut of Autostart directory on my desktop.

I know how to create shortcut of any application for example notepad but how can I create shortcut of directory?

I am trying something like this

$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()

Errors:

+ $objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Ro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

Body:
You can use the Environment Class:

$StartupFolder = [Environment]::GetFolderPath('Startup')
$DesktopFolder = [Environment]::GetFolderPath('Desktop')

$wshshell = New-Object -ComObject WScript.Shell
$link = $wshshell.CreateShortcut((Join-path $DesktopFolder "Autostart.lnk"))
$link.TargetPath = $StartupFolder
$link.Save()


问:
Change scrollbar position in TextBox?
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

```<code>SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);
</code>```

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.

答:
Do try to avoid controlling this directly, it just doesn't work really well.  Set the TextBox.SelectionStart property to ensure the caret is the line you want to make visible.  Then call ScrollToCaret.  The control must have the focus to make this work.  Your user won't have any trouble finding it back.

TextBox is a wrapper for the grand-daddy of controls, it's 23 years old already, older than many SO users I reckon.  Back when 640 KB was enough for everybody and Window 2.0 had to run on a 386SUX or less.  The WPF version has more whistles.

Title: Change scrollbar position in TextBox?

Body:
If I want to change the position of a TextBox's scrollbar, what do I need to do besides this:

SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

This function only changes the scrollbar position, but it doesn't update the actual TextBox (so the scrollbar "scrolls", but the text doesn't). Any suggestions? I'm using Windows Forms and .NET 4, with Visual Studio 2008.


问:
How to use a singleton service from CoreModule inside SharedModule Pipe in Angular (2+)
I have the following top-level structure of modules:

core

shared

app

inside the shared module is a pipe which needs to use a service from the core module.

At the moment Angular is throwing an error when trying to use the pipe: inline template:null:null caused by: No provider for [object Object]!

How would I go about doing this?

The core module is imported by the app module with .forRoot() and has the service required listed as a provider (on the core module).

答:
Have you exported you components from other modules?

For example:

core.module.ts

```<code>  exports: [
    NavigationComponent,
    BreadcrumbsComponent,
    CommonModule
  ]
</code>```

Body:
Have you exported you components from other modules?

For example:

core.module.ts

  exports: [
    NavigationComponent,
    BreadcrumbsComponent,
    CommonModule
  ]


问:
resetStateMachine does not clear its id
I am using a pooled list of StateMachine instances (at present limited to one) and am switching the context that statemachine is working with - however the StateMachine ID is never updated and I end up overwriting my statemachine in the db when i try to persist. More info on how below as well as the question.

My question is why upon calling resetStateMachine (in AbstractStateMachine.java) with a null context (ie trying to create a new context) does this not clear out the current id of the machine (I understand why UUID stays - that is unique to the machine) but id relates to the context also, no? If the context is not null it tries to pull the id from the stateMachineContext

Extracts of relevant sources:

If context is null:

```<code>log.info("Got null context, resetting to initial state and clearing extended state");
this.currentState = this.initialState;
this.extendedState.getVariables().clear();
</code>```

If context is not null:

```<code>this.setId(stateMachineContext.getId());
</code>```

When I later call persist.restore to pull back a state machine context this means I have an old id present and end up overwriting rather than using a new id to persist with.

This is using currently released version 1.2.5.RELEASE

答: Yes, don't see any reason why we would not clear id as well if null context is passed. Would you mind creating a github issue to track that change request?

Title: resetStateMachine does not clear its id

Body:
I am using a pooled list of StateMachine instances (at present limited to one) and am switching the context that statemachine is working with - however the StateMachine ID is never updated and I end up overwriting my statemachine in the db when i try to persist. More info on how below as well as the question.

My question is why upon calling resetStateMachine (in AbstractStateMachine.java) with a null context (ie trying to create a new context) does this not clear out the current id of the machine (I understand why UUID stays - that is unique to the machine) but id relates to the context also, no? If the context is not null it tries to pull the id from the stateMachineContext

Extracts of relevant sources:

If context is null:

log.info("Got null context, resetting to initial state and clearing extended state");
this.currentState = this.initialState;
this.extendedState.getVariables().clear();

If context is not null:

this.setId(stateMachineContext.getId());

When I later call persist.restore to pull back a state machine context this means I have an old id present and end up overwriting rather than using a new id to persist with.

This is using currently released version 1.2.5.RELEASE


问:
JQuery Scheduler with drag and drop
We want to create a customized scheduler in HTML5, CSS3 and JQuery. With the possibility to list items outside of the Scheduler, so that the user can drag the items and drop them inside the Schedule.

Users can not create events inside the Scheduler, they can just drag and drop existing events (that are saved in a database).

We also want to show schedules of user's friends, when the user types the name of a friend in a textbox, so that he can synchronize/organize/discuss his own tasks with the other user.

Is there any jQuery plugin that can do that, and that doesn't give the possibility to create new events inside the scheduler?

I already started to do this from scratch, but I won't be able deliver on time.

答: look at fullcalendar.io scheduler. The scheduler pat it's triple licensed, free for opensource prj</p>

Title: JQuery Scheduler with drag and drop


问:
You can't specify target table for update in FROM clause
I have a simple mysql table:

```<code>CREATE TABLE IF NOT EXISTS `pers` (
  `persID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(35) NOT NULL,
  `gehalt` int(11) NOT NULL,
  `chefID` int(11) DEFAULT NULL,
  PRIMARY KEY (`persID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `pers` (`persID`, `name`, `gehalt`, `chefID`) VALUES
(1, 'blb', 1000, 3),
(2, 'as', 1000, 3),
(3, 'chef', 1040, NULL);
</code>```

I tried to run following update, but I get only the error 1093:

```<code>UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <
(SELECT (
    SELECT MAX(gehalt * 1.05)
    FROM pers MA
    WHERE MA.chefID = MA.chefID)
    AS _pers
))
</code>```

I searched for the error and found from mysql following page http://dev.mysql.com/doc/refman/5.1/en/subquery-restrictions.html, but it doesn't help me.

What shall I do to correct the sql query?

答:
Just as reference, you can also use Mysql Variables to save temporary results, e.g.:

```<code>SET @v1 := (SELECT ... );
UPDATE ... SET ... WHERE x=@v1;
</code>```

https://dev.mysql.com/doc/refman/5.7/en/user-variables.html

Body:
I have a simple mysql table:

CREATE TABLE IF NOT EXISTS `pers` (
  `persID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(35) NOT NULL,
  `gehalt` int(11) NOT NULL,
  `chefID` int(11) DEFAULT NULL,
  PRIMARY KEY (`persID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `pers` (`persID`, `name`, `gehalt`, `chefID`) VALUES
(1, 'blb', 1000, 3),
(2, 'as', 1000, 3),
(3, 'chef', 1040, NULL);

I tried to run following update, but I get only the error 1093:

UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <
(SELECT (
    SELECT MAX(gehalt * 1.05)
    FROM pers MA
    WHERE MA.chefID = MA.chefID)
    AS _pers
))

I searched for the error and found from mysql following page http://dev.mysql.com/doc/refman/5.1/en/subquery-restrictions.html, but it doesn't help me.

What shall I do to correct the sql query?

Body:
Just as reference, you can also use Mysql Variables to save temporary results, e.g.:

SET @v1 := (SELECT ... );
UPDATE ... SET ... WHERE x=@v1;

https://dev.mysql.com/doc/refman/5.7/en/user-variables.html


问:
Connect 4 algorithm in javascript
What is the best way to check 4 in a row in connect 4?

I won't copy the code for the array but it is basically an array of length 42. Each array element holds the X, Y position for drawing and the color

```<code>var board_array = [{x:60, y:55, c:"Red"}, // ... and so on
</code>```

and looks like this:

Initially I took this approach. Here are all the different possible ways someone can win the game. It's not all the possible 4 in a row positions but all the different ways someone can win vertically, horizontally and vertically - you still need to check using some sort of nested for loop

```<code>// Winning vertically
wins[0]  = new Array(0, 7,  14, 21, 28, 35);
wins[1]  = new Array(1, 8,  15, 22, 29, 36);
wins[2]  = new Array(2, 9,  16, 23, 30, 37);
wins[3]  = new Array(3, 10, 17, 24, 31, 38);
wins[4]  = new Array(4, 11, 18, 25, 32, 39);
wins[5]  = new Array(5, 12, 19, 26, 33, 40);
wins[6]  = new Array(6, 13, 20, 27, 34, 41);
// Winning horizontally
wins[7]  = new Array(0,   1,  2,  3,  4,  5,  6);
wins[8]  = new Array(7,   8,  9, 10, 11, 12, 13);
wins[9]  = new Array(14, 15, 16, 17, 18, 19, 20);
wins[10] = new Array(21, 22, 23, 24, 25, 26, 27);
wins[11] = new Array(28, 29, 30, 31, 32, 33, 34);
wins[12] = new Array(35, 36, 37, 38, 39, 40, 41);
// Winning diagonally, left to right
wins[13] = new Array(14, 22, 30, 38);
wins[14] = new Array(7, 15, 23, 31, 39);
wins[15] = new Array(0, 8, 16, 24, 32, 40);
wins[16] = new Array(1, 9, 17, 25, 33, 41);
wins[17] = new Array(2, 10, 18, 26, 34);
wins[18] = new Array(3, 11, 19, 27);
//Winning diagonally, right to left
wins[19] = new Array(20, 26, 32, 38);
wins[20] = new Array(13, 19, 25, 31, 37);
wins[21] = new Array(6,  12, 18, 24, 30, 36);
wins[22] = new Array(5,  11, 17, 23, 29, 35);
wins[23] = new Array(4,  10, 16, 22, 28);
wins[24] = new Array(3,   9, 15, 21);
</code>```

If you think of the board_array as this:

```<code>//0  1  2  3  4  5  6
//7  8  9  10 11 12 13
//14 15 16 17 18 19 20
//21 22 23 24 25 26 27
//28 29 30 31 32 33 34
//35 36 37 38 39 40 41
</code>```

I used a 3-layer for loop and a counter to check wins array against board_array but to no avail. I just wondered if there is a simpler way.

答:
There are a lot of ways to do so. If you want to get rid of the loops, you can use a dynamic-programming-algorithm and calculate the result every time you add a coin.

To do so you must save 4 values per field: horizontal-, vertical-, diagonally-left- and diagonally-right-value

```<code>class Field {
       int horiz;
       int vert;
       int diagLeft;
       int diagRight;
}
</code>```

At the beginning, all fields are initialized with 0 (all values of the field).
If you add a coin to Field, you can calculate the values like that:

```<code>fields[i][j].horiz = fields[i][j+1].horiz + fields[i][j-1].horiz + 1;
fields[i][j].vert = fields[i+1][j].vert + fields[i-1][j].vert + 1;
fields[i][j].diagLeft = fields[i+1][j+1].diagLeft + fields[i-1][j-1].diagLeft +1;
fields[i][j].diagRight = fields[i-1][j-1].diagRight + fields[i+1][j+1]
</code>```

If one of the four calculated values is >= 4, you have a winner.

To handle two player, you can either make a field-Array for each player, or you can use positive and negative values

If you want to avoid checking the bounds (i and j) all the time, you can add a border to your field (so you have left and right one additional column and at the top and at the bottom one additional row)

Title: Connect 4 algorithm in javascript

Body:
What is the best way to check 4 in a row in connect 4?

I won't copy the code for the array but it is basically an array of length 42. Each array element holds the X, Y position for drawing and the color

var board_array = [{x:60, y:55, c:"Red"}, // ... and so on

and looks like this:

Initially I took this approach. Here are all the different possible ways someone can win the game. It's not all the possible 4 in a row positions but all the different ways someone can win vertically, horizontally and vertically - you still need to check using some sort of nested for loop

// Winning vertically
wins[0]  = new Array(0, 7,  14, 21, 28, 35);
wins[1]  = new Array(1, 8,  15, 22, 29, 36);
wins[2]  = new Array(2, 9,  16, 23, 30, 37);
wins[3]  = new Array(3, 10, 17, 24, 31, 38);
wins[4]  = new Array(4, 11, 18, 25, 32, 39);
wins[5]  = new Array(5, 12, 19, 26, 33, 40);
wins[6]  = new Array(6, 13, 20, 27, 34, 41);
// Winning horizontally
wins[7]  = new Array(0,   1,  2,  3,  4,  5,  6);
wins[8]  = new Array(7,   8,  9, 10, 11, 12, 13);
wins[9]  = new Array(14, 15, 16, 17, 18, 19, 20);
wins[10] = new Array(21, 22, 23, 24, 25, 26, 27);
wins[11] = new Array(28, 29, 30, 31, 32, 33, 34);
wins[12] = new Array(35, 36, 37, 38, 39, 40, 41);
// Winning diagonally, left to right
wins[13] = new Array(14, 22, 30, 38);
wins[14] = new Array(7, 15, 23, 31, 39);
wins[15] = new Array(0, 8, 16, 24, 32, 40);
wins[16] = new Array(1, 9, 17, 25, 33, 41);
wins[17] = new Array(2, 10, 18, 26, 34);
wins[18] = new Array(3, 11, 19, 27);
//Winning diagonally, right to left
wins[19] = new Array(20, 26, 32, 38);
wins[20] = new Array(13, 19, 25, 31, 37);
wins[21] = new Array(6,  12, 18, 24, 30, 36);
wins[22] = new Array(5,  11, 17, 23, 29, 35);
wins[23] = new Array(4,  10, 16, 22, 28);
wins[24] = new Array(3,   9, 15, 21);

If you think of the board_array as this:

//0  1  2  3  4  5  6
//7  8  9  10 11 12 13
//14 15 16 17 18 19 20
//21 22 23 24 25 26 27
//28 29 30 31 32 33 34
//35 36 37 38 39 40 41

I used a 3-layer for loop and a counter to check wins array against board_array but to no avail. I just wondered if there is a simpler way.

Body:
There are a lot of ways to do so. If you want to get rid of the loops, you can use a dynamic-programming-algorithm and calculate the result every time you add a coin.

To do so you must save 4 values per field: horizontal-, vertical-, diagonally-left- and diagonally-right-value

class Field {
       int horiz;
       int vert;
       int diagLeft;
       int diagRight;
}

At the beginning, all fields are initialized with 0 (all values of the field).
If you add a coin to Field, you can calculate the values like that:

fields[i][j].horiz = fields[i][j+1].horiz + fields[i][j-1].horiz + 1;
fields[i][j].vert = fields[i+1][j].vert + fields[i-1][j].vert + 1;
fields[i][j].diagLeft = fields[i+1][j+1].diagLeft + fields[i-1][j-1].diagLeft +1;
fields[i][j].diagRight = fields[i-1][j-1].diagRight + fields[i+1][j+1]

If one of the four calculated values is >= 4, you have a winner.

To handle two player, you can either make a field-Array for each player, or you can use positive and negative values

If you want to avoid checking the bounds (i and j) all the time, you can add a border to your field (so you have left and right one additional column and at the top and at the bottom one additional row)


答:
If You don't want to reload page after submit, use ajax like:</p>

```<code>$("#form1").submit(function(event) {
    event.preventDefault();

    $.ajax({
      url: '/your_url',
      dataType: 'json', // or other
      success: function(data) {
        if (data > 0) {
          $('#foo').css('border', '3px solid red');
        }
      }
      error: function (xhr, ajaxOptions, thrownError) {
        $('#foo').css('border', '3px solid red');
      }
    });
});
</code>```

Title: jQuery CSS Property

Body:
I used the .css() for changing the border color for an element, and every time I perform the action that trigger the jQuery script, the border changes like it supposed to, but changes back after a second.

This is the code:

$("#form1").submit(function() {
  if (!$('#foo').val().length) {
    $("#foo").css('border', '3px solid red');
  }
  $("#foo").css('border', '3px solid red');
});

  <form id="form1" name="form1" method="post">

      PO: <input type="text" class="txtBox" name="foo" id="foo">

    <input type="submit" name="Submit" value="Submit" />
  </form>

No additional JS or css file.

Body:
If You don't want to reload page after submit, use ajax like:

$("#form1").submit(function(event) {
    event.preventDefault();

    $.ajax({
      url: '/your_url',
      dataType: 'json', // or other
      success: function(data) {
        if (data > 0) {
          $('#foo').css('border', '3px solid red');
        }
      }
      error: function (xhr, ajaxOptions, thrownError) {
        $('#foo').css('border', '3px solid red');
      }
    });
});


问:
Object to Array of objects conversion in Typescript
I need to convert object to array of object to work with angular2 *ngFor directive. i have got following json object.

```<code>Object {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}
</code>```

I need to convert that into array of object like this:

```<code>[Object]
     0: Object
       CountryID: 87944818
       ISO2: "do"
       ISO3: "u"
       Name: "aliqua sit magna tempor"
</code>```

I have done some work around using Object.keys and map but could not acheive the exact output.
Have tried some thing like that:

```<code>let keys:any[] = [];
        for (let key in value) {
            console.log(key);
            keys.push({key: value[key]});
        }
        console.log(keys);
</code>```

value is the object that need to convert.

答:
Why not just have an array and push the object into it?

```<code>let myObj = {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}
let myArr = [];
myArr.push(myObj);
console.log(myArr);
</code>```

Edit:

Or you can just do:

```<code>myArr = [myObj]
</code>```

Body:
I need to convert object to array of object to work with angular2 *ngFor directive. i have got following json object.

Object {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}

I need to convert that into array of object like this:

[Object]
     0: Object
       CountryID: 87944818
       ISO2: "do"
       ISO3: "u"
       Name: "aliqua sit magna tempor"

I have done some work around using Object.keys and map but could not acheive the exact output.
Have tried some thing like that:

let keys:any[] = [];
        for (let key in value) {
            console.log(key);
            keys.push({key: value[key]});
        }
        console.log(keys);

value is the object that need to convert.

Body:
Why not just have an array and push the object into it?

let myObj = {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}
let myArr = [];
myArr.push(myObj);
console.log(myArr);

Edit:

Or you can just do:

myArr = [myObj]


问:
Get Image from the Storage Folder in View - Laravel 5.4
I'm trying to show the default.jpg avatar picture in my Laravel 5.4 profile.blade.php.

I created a link between the public folder and the storage folder with: php artisan storage:link.

The file is stored:

I check in the source code of my webpage which showed the src="/public/storage/uploads/avatar/default.jpg"

But still no image could be found. Could someone explain to me what I am missing?

答: remove public from the path  src="/public/storage/uploads/avatar/default.jpg"