问:
Composer won't update due to changes on the current branch
We have composer as our dependency injection framework which will pull in a library we created, foobar, which works fine. The library foobar has 14 version v1.1.1 -> v1.1.14. All the way up to .12 composer updated the app fine. But now we are getting this error:

```<code>Update failed (Source directory /home/username/dev/git/appname/vendor/foorbar/library has unpushed changes on the current branch:
Branch v1.1.14 could not be found on the origin remote and appears to be unpushed)
</code>```

The composer.json:

```<code>{
  "name": "App",
  "description": "Foo Bar",
  "require": {
    "php": ">=5.3.3",
    "zendframework/zendframework": "2.2.",
    "foobarzf2lib/library": "v1.1."
  },
  "minimum-stability": "stable",
  "repositories": [
    {
      "type": "package",
      "package": {
        "name": "foobarzf2lib/library",
        "version": "v1.1.14",
        "source": {
          "url": "https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/foobarzf2lib",
          "type": "git",
          "reference": "test"
        },
        "autoload": {
          "psr-4": {
            "FooBar\\" : "FooBar/"
          }
        }
      }
    }
  ]
}
</code>```

More things to know:

Vendor is ignored in git.

Tried doing $ composer.phar clearcache.

Would be ideal to not have to delete the library every time.

答:
Branch v1.1.14 could not be found on the origin remote and appears to be unpushed)
This means that wherever you're pulling the package from does not have a v1.1.14.
Make sure you push v1.1.14 to the package provider and everything should be fine.

ContentLicense: CC BY-SA 4.0

Body:
We have composer as our dependency injection framework which will pull in a library we created, foobar, which works fine. The library foobar has 14 version v1.1.1 -> v1.1.14. All the way up to .12 composer updated the app fine. But now we are getting this error:

Update failed (Source directory /home/username/dev/git/appname/vendor/foorbar/library has unpushed changes on the current branch:
Branch v1.1.14 could not be found on the origin remote and appears to be unpushed)

The composer.json:

{
  "name": "App",
  "description": "Foo Bar",
  "require": {
    "php": ">=5.3.3",
    "zendframework/zendframework": "2.2.",
    "foobarzf2lib/library": "v1.1."
  },
  "minimum-stability": "stable",
  "repositories": [
    {
      "type": "package",
      "package": {
        "name": "foobarzf2lib/library",
        "version": "v1.1.14",
        "source": {
          "url": "https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/foobarzf2lib",
          "type": "git",
          "reference": "test"
        },
        "autoload": {
          "psr-4": {
            "FooBar\\" : "FooBar/"
          }
        }
      }
    }
  ]
}

More things to know:

Vendor is ignored in git.

Tried doing $ composer.phar clearcache.

Would be ideal to not have to delete the library every time.


来源: stackexchange

问:
Vue Router. Bind data
I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.

Please help me.

HTML:

```<code><div id="app">
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>
</code>```

Script:

```<code>const Foo = { template: '<div>{{foo}}</div>' }
const Bar = { template: '<div>bar</div>' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})
</code>```

{{foo}} bind doesn't work.

Live example:
https://jsfiddle.net/xgrjzsup/4430/

答:
in your case there are two ways you can access that "foo" var.

```<code>{{$parent.foo}}
{{$root.foo}}
</code>```

But consider using Vuex for sharing data in your application - https://github.com/vuejs/vuex
Or pass that foo as a parameter to the route -https://router.vuejs.org/en/essentials/passing-props.html

ContentLicense: CC BY-SA 3.0

Title: Vue Router. Bind data

Body:
I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.

Please help me.

HTML:

Hello App!

    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>

  <router-view></router-view>

Script:

const Foo = { template: '
{{foo}}
' }
const Bar = { template: '
bar
' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})

{{foo}} bind doesn't work.

Live example:
https://jsfiddle.net/xgrjzsup/4430/

Body:
in your case there are two ways you can access that "foo" var.

{{$parent.foo}}
{{$root.foo}}

But consider using Vuex for sharing data in your application - https://github.com/vuejs/vuex
Or pass that foo as a parameter to the route -https://router.vuejs.org/en/essentials/passing-props.html


问:
Laravel How to pass variable from select box to url?
What I am trying to do is basicly passing selected item's slug from a select box to route

```<code>{{ Form::open(['route' => 'list/{category->slug(here)}' ]) }}
<select name="" id="" class="form-control">
    @foreach($categories $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
    @endforeach
</select>
{{ Form::submit('Send') }}
{{ Form::close() }}
</code>```

Can anyone help me?

答:
You can try to use the onchange. Like here:</p>

```<code><select onchange="document.location=this.options[this.selectedIndex].value">
    <option value="{{ route('route_name') }}">caption</option>
</code>```

Body:
What I am trying to do is basicly passing selected item's slug from a select box to route

{{ Form::open(['route' => 'list/{category->slug(here)}' ]) }}
<select name="" id="" class="form-control">
    @foreach($categories $category)
        <option value="{{$category->id}}">{{$category->name}}</option>
    @endforeach
</select>
{{ Form::submit('Send') }}
{{ Form::close() }}

Can anyone help me?

Body:
You can try to use the onchange. Like here:

<select onchange="document.location=this.options[this.selectedIndex].value">
    <option value="{{ route('route_name') }}">caption</option>


问:
Blank SMS from Kannel
I am sending an SMS from my web application in my laptop to a phone. The problem is that the SMS is always blank. Could anyone know what may be wrong. Below is the url I use to pass the variables to kannel(username,password and telephone number have been eXd for obvious reasons). I can receive the sms. But its always blank</p>

```<code>http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=+254xxxxxxxxx&test=message
</code>```

答: I'm guessing you need text=message rather than test=message

ContentLicense: CC BY-SA 2.5

Title: Blank SMS from Kannel

Body:
I am sending an SMS from my web application in my laptop to a phone. The problem is that the SMS is always blank. Could anyone know what may be wrong. Below is the url I use to pass the variables to kannel(username,password and telephone number have been eXd for obvious reasons). I can receive the sms. But its always blank

http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=+254xxxxxxxxx&test=message


问:
Error Exporting .csv from PostgreSQL using Python 3
I have a simple PostgreSQL copy statement that copies a table from a network host (NETWORK-HOST) database to a .csv file on a shared network folder. It works fine in PGAdmin, but when I transfer it to a psycopg2 script, it tells me permission denied. I have double checked to make sure full control is granted to my username on the network share, but that has not made a difference. I am running Windows 10, Python 3 (32 bit), PostgreSQL 9.5.1.

Here is the script in PGAdmin that runs successfully:

```<code>copy "Schema".county_check_audit to '\\NETWORK-HOST\NetworkFolder\county_check.csv' delimiter ',' CSV HEADER;
</code>```

here is the script where I get the permission error:

```<code>import psycopg2
connection = psycopg2.connect(database="db", user="postgres", password="password", host="NETWORK-HOST")
cursor = connection.cursor()
cursor.execute("copy \"Schema\".area_check_audit to '\\\\NETWORK-HOST\\NetworkFolder\\area_check.csv' delimiter ',' CSV HEADER;")
connection.commit()
</code>```

This is the error:

```<code>psycopg2.ProgrammingError: could not open file "\\NETWORK-HOST\NetworkFolder\area_check.csv" for writing: Permission denied
</code>```

Any insights are greatly appreciated.

答:
According to the error message, you have to add write access to the file.

To change file'security access on windows, check : Permission denied when trying to import a CSV file from PGAdmin

I'd suggest to test your code first by trying to write to a file that is on the same host and once you are sure your code is fine, you can debug the access rights to your file on another host.

Body:
I have a simple PostgreSQL copy statement that copies a table from a network host (NETWORK-HOST) database to a .csv file on a shared network folder. It works fine in PGAdmin, but when I transfer it to a psycopg2 script, it tells me permission denied. I have double checked to make sure full control is granted to my username on the network share, but that has not made a difference. I am running Windows 10, Python 3 (32 bit), PostgreSQL 9.5.1.

Here is the script in PGAdmin that runs successfully:

copy "Schema".county_check_audit to '\\NETWORK-HOST\NetworkFolder\county_check.csv' delimiter ',' CSV HEADER;

here is the script where I get the permission error:

import psycopg2
connection = psycopg2.connect(database="db", user="postgres", password="password", host="NETWORK-HOST")
cursor = connection.cursor()
cursor.execute("copy \"Schema\".area_check_audit to '\\\\NETWORK-HOST\\NetworkFolder\\area_check.csv' delimiter ',' CSV HEADER;")
connection.commit()

This is the error:

psycopg2.ProgrammingError: could not open file "\\NETWORK-HOST\NetworkFolder\area_check.csv" for writing: Permission denied

Any insights are greatly appreciated.


问:
Getting last insert id and inserting it into db php MVC
I am trying to get the last inserted id in the database and use that to insert another record(s), in this case, associated images with a particular record. Note: I am using MVC and this is in the model. These 2 operations should happen straight after each other i.e.: the user does't see that there are 2 different inserts happening at the same time.

This is the initial insert:

```<code>public function addAccom($data)
    {
        $this->db->query("INSERT INTO `accommodation` (`name`, `description`, `category`, `slug`) VALUES (:name, :description, :category, :slug)");
        $this->db->bind(":name", $data['name']);
        $this->db->bind(":description", $data['description']);
        $this->db->bind(":category", $data['category']);
        $this->db->bind(":slug", $data['slug']);
        if($this->db->execute()){
        $id = $this->db->lastInsertId();
            return true;
        } else {
            return false;
        }
    }
</code>```

I don't know if this line is correct in the above:

```<code>$id = $this->db->lastInsertId();
</code>```

After this insert, I need to insert more records into another table using that id.

Should I try run another db query in the same query as this or create another query?

This is the second query I had:

```<code>public function addAccomPic($data)
{
    $this->db->query("INSERT INTO `accom_pics` (`accom_id`, `pic_name`) VALUES (:accom_id, :pic_name)");
    $this->db->bind(":accom_id", $data['accom_id']);
    $this->db->bind(":pic_name", $data['pic_name']);
    if($this->db->execute()) {
        return true;
    } else {
        return false;
    }
}
</code>```

Database:

```<code>private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;

    private $dbh; // Is this the same as $link ?
    private $stmt;
    private $error;

    public function __construct() {
        $dsn = "mysql:host=$this->host;dbname=$this->dbname";
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);

        } catch(PDOexception $e) {
            $this->error = $e->getMessage();
            echo $this->error;
        }
    }
</code>```

答:
The first thing i see, it's $id is a local variable. Try to set it as global:</p>

```<code>public $id = null;

public function addAccom($data)
{
    $this->id = $this->db->lastInsertId();
}
</code>```

Body:
I am trying to get the last inserted id in the database and use that to insert another record(s), in this case, associated images with a particular record. Note: I am using MVC and this is in the model. These 2 operations should happen straight after each other i.e.: the user does't see that there are 2 different inserts happening at the same time.

This is the initial insert:

public function addAccom($data)
    {
        $this->db->query("INSERT INTO `accommodation` (`name`, `description`, `category`, `slug`) VALUES (:name, :description, :category, :slug)");
        $this->db->bind(":name", $data['name']);
        $this->db->bind(":description", $data['description']);
        $this->db->bind(":category", $data['category']);
        $this->db->bind(":slug", $data['slug']);
        if($this->db->execute()){
        $id = $this->db->lastInsertId();
            return true;
        } else {
            return false;
        }
    }

I don't know if this line is correct in the above:

$id = $this->db->lastInsertId();

After this insert, I need to insert more records into another table using that id.

Should I try run another db query in the same query as this or create another query?

This is the second query I had:

public function addAccomPic($data)
{
    $this->db->query("INSERT INTO `accom_pics` (`accom_id`, `pic_name`) VALUES (:accom_id, :pic_name)");
    $this->db->bind(":accom_id", $data['accom_id']);
    $this->db->bind(":pic_name", $data['pic_name']);
    if($this->db->execute()) {
        return true;
    } else {
        return false;
    }
}

Database:

private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;

    private $dbh; // Is this the same as $link ?
    private $stmt;
    private $error;

    public function __construct() {
        $dsn = "mysql:host=$this->host;dbname=$this->dbname";
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);

        } catch(PDOexception $e) {
            $this->error = $e->getMessage();
            echo $this->error;
        }
    }

Body:
The first thing i see, it's $id is a local variable. Try to set it as global:

public $id = null;

public function addAccom($data)
{
    $this->id = $this->db->lastInsertId();
}


问:
Wix Installer PropertyRef schema validation error
Adding a PropertyRef element to my Package element produces an error during compilation.

This is my *.wxs file

```<code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension">
  <Product Id="*" Name="MyProduct" Language="1033" Version="!(bind.FileVersion.MyApplication.exe)" Manufacturer="MyManufacturer" UpgradeCode="SOME-GUID">
    <PropertyRef Id="WIX_IS_NETFRAMEWORK_461_OR_LATER_INSTALLED" />
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    ...
  </Product>
  ...
</Wix>
</code>```

This is the error produced by visual studio:

```<code>Schema validation failed with the following error at line 1, column 588: The element 'Product' in namespace 'http://schemas.microsoft.com/wix/2006/wi' has invalid child element 'PropertyRef' in namespace 'http://schemas.microsoft.com/wix/2006/wi'. List of possible elements expected: 'Package'.
</code>```

Looking at the documentation of PropertyRef shows that Product should be a valid parent of PropertyRef.

答:
This error can be fixed by putting the PropertyRef element after the Package element.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension">
  <Product Id="*" Name="MyProduct" Language="1033" Version="!(bind.FileVersion.MyApplication.exe)" Manufacturer="MyManufacturer" UpgradeCode="SOME-GUID">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <PropertyRef Id="WIX_IS_NETFRAMEWORK_461_OR_LATER_INSTALLED" />
    ...
  </Product>
  ...
</Wix>
</code>```

Body:
Adding a PropertyRef element to my Package element produces an error during compilation.

This is my *.wxs file

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension">
  <Product Id="*" Name="MyProduct" Language="1033" Version="!(bind.FileVersion.MyApplication.exe)" Manufacturer="MyManufacturer" UpgradeCode="SOME-GUID">
    <PropertyRef Id="WIX_IS_NETFRAMEWORK_461_OR_LATER_INSTALLED" />
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    ...
  </Product>
  ...
</Wix>

This is the error produced by visual studio:

Schema validation failed with the following error at line 1, column 588: The element 'Product' in namespace 'http://schemas.microsoft.com/wix/2006/wi' has invalid child element 'PropertyRef' in namespace 'http://schemas.microsoft.com/wix/2006/wi'. List of possible elements expected: 'Package'.

Looking at the documentation of PropertyRef shows that Product should be a valid parent of PropertyRef.

Body:
This error can be fixed by putting the PropertyRef element after the Package element.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
 xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension">
  <Product Id="*" Name="MyProduct" Language="1033" Version="!(bind.FileVersion.MyApplication.exe)" Manufacturer="MyManufacturer" UpgradeCode="SOME-GUID">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <PropertyRef Id="WIX_IS_NETFRAMEWORK_461_OR_LATER_INSTALLED" />
    ...
  </Product>
  ...
</Wix>


问:
Why and when to inherit from Collection<T>
I'm tracing legacy code in my project written in C#.

I find the following code:

```<code>public class FooCollection : Collection<IFoo> {};
</code>```

I don't understand why (and when) we need to create our own Collection class like this.

Why not just use the build-in collection (array, List<T>, Dictionary<K,V>, ...)

What's the data structure used in Collection<T> ?? array? or linked list?

答:
I don't understand why (and when) we need to create our own Collection class like this.

One of the main use cases for implementing a custom Collection<T> is serialization.

If you want to customize how the collection is serialized (for example to XML, using XmlSerializable), you can create a custom collection class and implement IXmlSerializable on it. Then, you can change how to read or write the collection by manipulating the Read and Write methods of that interface.

```<code>class MyCollection : Collection<string>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return(null);
    }

    public void WriteXml(XmlWriter writer)
    {
        //// foreach (var item in Items)
            //// writer.Write...
    }

    public void ReadXml(XmlReader reader)
    {
        //// Items.Add(reader.Read...
    }
}
</code>```

This is in most cases preferable compared to implementing IXmlSerializable on the parent class, as it leads to less code overall and promotes reuse (you can reuse the same collection in multiple places and it will be serialized in the same way as long as you use a XmlSerializer to serialize it).

I've used this recently due to a requirement from an external system that needed each element of the collection to generate a XML node with the index of the element appended to it.

The final structure looked somewhat like this:

```<code><MyCollection>
  <Item1>first item</Item1>
  <Item2>second item</Item2>
  ...
</MyCollection>
</code>```

I'm not fond of coupling the collection to the serialization like this, but sometimes it is a valid approach.

Body:
I'm tracing legacy code in my project written in C#.

I find the following code:

public class FooCollection : Collection<IFoo> {};

I don't understand why (and when) we need to create our own Collection class like this.

Why not just use the build-in collection (array, List<T>, Dictionary<K,V>, ...)

What's the data structure used in Collection<T> ?? array? or linked list?

Body:
I don't understand why (and when) we need to create our own Collection class like this.

One of the main use cases for implementing a custom Collection<T> is serialization.

If you want to customize how the collection is serialized (for example to XML, using XmlSerializable), you can create a custom collection class and implement IXmlSerializable on it. Then, you can change how to read or write the collection by manipulating the Read and Write methods of that interface.

class MyCollection : Collection<string>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return(null);
    }

    public void WriteXml(XmlWriter writer)
    {
        //// foreach (var item in Items)
            //// writer.Write...
    }

    public void ReadXml(XmlReader reader)
    {
        //// Items.Add(reader.Read...
    }
}

This is in most cases preferable compared to implementing IXmlSerializable on the parent class, as it leads to less code overall and promotes reuse (you can reuse the same collection in multiple places and it will be serialized in the same way as long as you use a XmlSerializer to serialize it).

I've used this recently due to a requirement from an external system that needed each element of the collection to generate a XML node with the index of the element appended to it.

The final structure looked somewhat like this:

<MyCollection>
  <Item1>first item</Item1>
  <Item2>second item</Item2>
  ...
</MyCollection>

I'm not fond of coupling the collection to the serialization like this, but sometimes it is a valid approach.


问:
I am loading image to tab3 but when sliding my tab recycle view items increased when I come back to first tab
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

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

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}
</code>```

}

答:
you can do this way
create a method inside your RecyclerViewAdapter class like setData(pass your list) and set data to list in your RecyclerViewAdapter class;</p>

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

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);
    adapter = new RecyclerViewAdapter(getContext(), list);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo =
                 postSnapshot.getValue(ImageUploadInfo.class);

              list.add(imageUploadInfo);
            }

             adpter.setData(list);
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();

         progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });
</code>```

Body:
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

`public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}

}

Body:
you can do this way
create a method inside your RecyclerViewAdapter class like setData(pass your list) and set data to list in your RecyclerViewAdapter class;

public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    context = getActivity();

    view = inflater.inflate(R.layout.fragment_news_feeds2,container, false);
    adapter = new RecyclerViewAdapter(getContext(), list);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo =
                 postSnapshot.getValue(ImageUploadInfo.class);

              list.add(imageUploadInfo);
            }

             adpter.setData(list);
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();

         progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });


问:
UITextView Cursor Color not changing iOS 7
I'm trying to set the cursor color of a UITextView based on a user's preferences. They select what color they want with a button.

By default, the textview's cursor color is white. When the user presses the button, it might change to green:

```<code>[_textView setTintColor:[UIColor greenColor]];
[_textView setTextColor:[UIColor greenColor]];
</code>```

I am sure that this method call is working because the textview's text changes color, just not the cursor...

答:
I'm using small hack in UITextViewDelegate method:

```<code>func textViewDidBeginEditing(_ textView: UITextView) {
    let color = textView.tintColor
    textView.tintColor = .clear
    textView.tintColor = color
}
</code>```

UPD

more technological way:

1) implement method in extension:

```<code>extension UITextView {
    func resetTintColor(){
        let color = tintColor
        tintColor = .clear
        tintColor = color
    }
}
</code>```

2) in an UITextViewDelegate implementation:

```<code>func textViewDidBeginEditing(_ textView: UITextView) {
    textView.resetTintColor()
}
</code>```

Body:
I'm trying to set the cursor color of a UITextView based on a user's preferences. They select what color they want with a button.

By default, the textview's cursor color is white. When the user presses the button, it might change to green:

[_textView setTintColor:[UIColor greenColor]];
[_textView setTextColor:[UIColor greenColor]];

I am sure that this method call is working because the textview's text changes color, just not the cursor...

Body:
I'm using small hack in UITextViewDelegate method:

func textViewDidBeginEditing(_ textView: UITextView) {
    let color = textView.tintColor
    textView.tintColor = .clear
    textView.tintColor = color
}

UPD

more technological way:

1) implement method in extension:

extension UITextView {
    func resetTintColor(){
        let color = tintColor
        tintColor = .clear
        tintColor = color
    }
}

2) in an UITextViewDelegate implementation:

func textViewDidBeginEditing(_ textView: UITextView) {
    textView.resetTintColor()
}


问:
Call to system("printf buffer > output.txt") fails to write file when buffer is 1MB
Iam trying to call system to save a buffer to an output, i have to do this with system call, or with execve and pipes(it's a university project).

The buffer is read for a part of a file, and then i have to run a sh on it, and then i can save it to file.
I was trying to just save it to file with the system(), when i replace the buffer with a shorter string it works perfectly, but not with the large buffer.

I use this function to create the command:

```<code>char* command = string_new();
string_append_with_format(&command, "(printf '%s') > %s", buffer, outputName);
</code>```

Here is the link to the functions iam using if you wanna see them, it's a university library.
https://github.com/sisoputnfrba/so-commons-library/blob/master/src/commons/string.c

Is there a limit to the characters you can output with printf command on sh?

What do you recommend me to do? to change this to execve approach?

Thanks, i will add code/information if you need it.

答:
What do you recommend me to do? to change this to execve approach?

The alternatives of system() vs. execve() are choices for how to run another process.  The latter would be combined with fork().  Given that you must use one of these, it is apparent that you are supposed to use an external command to perform the I/O to the eventual destination.  An essential question to answer, then, is which external command to use.

As you have discovered, there are limits to the size of a shell command, and if you pursued a direct conversion to using execve() instead of system() then you would likely discover that there are corresponding limits at that level.  Therefore, your basic approach of passing the data to be printed as an argument to the command is not viable if the possible size of the data is not suitably bounded.  Thus a second, related, essential question is how the data to write are to be conveyed to the external command.

Allow me to suggest using the cat command in place of printf.  With no arguments, cat simply copies its standard input to its standard output.  This solves the problem of providing the data to write to the file: you will arrange for cat to read it from its standard input.  To arrange for the data to go to the destination file, you will need to connect cat's standard output to that file.

As far as the standard input goes, it looks like you would want to establish a pipe() between the main process and its fork()ed child, and to dup2() the read end of that pipe onto the child's standard input.  The child would close the write end of the pipe (important), and the parent would close the read end.

The clean way to handle the output would be for the child to open() the destination file, and to dup2() its file descriptor on to its standard output.

Having performed those redirections, the child would then execve() /usr/bin/cat with no arguments, and the parent would write() or fwrite() the data to the write end of the pipe, then close() the pipe and wait()s for the child to finish.

Body:
Iam trying to call system to save a buffer to an output, i have to do this with system call, or with execve and pipes(it's a university project).

The buffer is read for a part of a file, and then i have to run a sh on it, and then i can save it to file.
I was trying to just save it to file with the system(), when i replace the buffer with a shorter string it works perfectly, but not with the large buffer.

I use this function to create the command:

char* command = string_new();
string_append_with_format(&command, "(printf '%s') > %s", buffer, outputName);

Here is the link to the functions iam using if you wanna see them, it's a university library.
https://github.com/sisoputnfrba/so-commons-library/blob/master/src/commons/string.c

Is there a limit to the characters you can output with printf command on sh?

What do you recommend me to do? to change this to execve approach?

Thanks, i will add code/information if you need it.


答:
Your URL uses the key test where it should use text.

Try the following:

```<code>http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=+254xxxxxxxxx&text=message
</code>```

Reference: Kennel manual

Title: Blank SMS from Kannel

Body:
Your URL uses the key test where it should use text.

Try the following:

http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=+254xxxxxxxxx&text=message

Reference: Kennel manual


问:
how to use javascript timer in a nested repeater?
I'm trying to add a javascript timer for products, if the item have a promotion then show the timer and start the count down.. so what i'm doing is im sending the end date from code behind to the javascript function and the function creates the timer based on the end date. I've been trying for long time the script is working, the issue is i'm not able to loop inside the nested repeater to get the correct countdown control id and index.
hope you guys can help me with this issue.
thanks

HTML Code:

```<code>        <asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="rptdep_ItemDataBound" OnItemCommand="rptdep_Details_Command">
        <ItemTemplate>
            <asp:LinkButton class="navbar-brand" runat="server" ID="LinkButton1" Style="text-decoration: none; margin-right: -25px; border: none; font-size: medium" CommandArgument='<%#Eval("department_code") %>' CommandName="more">
                <asp:Repeater runat="server" ID="rptdeppromo" OnItemDataBound="rptdeppromo_ItemDataBound" OnItemCommand="Item_depPromo_Command">
                    <ItemTemplate>
                        <div runat="server" id="countdown" class="cntdwn"></div>
                    </ItemTemplate>
                </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>
</code>```

Timer JS code:

```<code>function producttimer(compntname, enddate1, col) {
        $(document).ready(function () {

            var $countdown = $('#rptdep_rptdeppromo_' + compntname + '_countdown_' + col);

                // set the date we're counting down to
                var target_date = new Date(enddate1);
                // variables for time units
                var days, hours, minutes, seconds;

                // update the tag with id "countdown" every 1 second
                setInterval(function () {
                    target_date.getTime();

                    // find the amount of "seconds" between now and target
                    var current_date = new Date().getTime();

                    // check for match
                    if (current_date === target_date) {
                    }

                    var seconds_left = (target_date - current_date) / 1000;

                    // do some time calculations
                    days = parseInt(seconds_left / 86400);
                    seconds_left = seconds_left % 86400;

                    hours = parseInt(seconds_left / 3600);
                    seconds_left = seconds_left % 3600;

                    minutes = parseInt(seconds_left / 60);
                    seconds = parseInt(seconds_left % 60);

                    // format countdown string + set tag value
                    $countdown.text(days + "days, " + hours + "hrs, " + minutes + "min, " + seconds + "s");
                }, 1000);
        }); //EOF DOCUMENT.READY
    }
</code>```

C# parent repeater code:

```<code>protected void rptdep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Repeater innerRepeater2 = (Repeater)e.Item.FindControl("rptdeppromo");
        DataRowView drv = (DataRowView)(e.Item.DataItem);

        }
    }
}
</code>```

C# nested repeater code:

```<code>protected void rptdeppromo_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataRowView drv = (DataRowView)(e.Item.DataItem);

DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(drv.Row["publishtdt"]).ToString("dd MMM yyyy"));

        int countw = 0;
        int count = 0;

        if (total < 30)
        {
            count += 1;
            foreach (RepeaterItem item in rptdep.Items)
            {
                countw += 1;
            }
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "counter" + countw, "producttimer('" + countw + "','" + EndDate + "', '" + e.Item.ItemIndex + "');", true);
        }
        else
        {

        }
    }
}
</code>```

答:
the upvoted answer worked for me, but i needed to tweak it a bit. I thought some code may help the next person who looks here.
using the plugin jquery.countup.js (any counter should work): </p>

```<code><div id="div<%# ((RepeaterItem)Container).ItemIndex + 1%>"  class="countdown">
     <%# Eval("EntryDate") %>
</div>

<script type="text/javascript">
    $(function () {
        var elements = document.getElementsByClassName('countdown');
        var len = elements.length;
        for (var i = 0; i < len; ++i) {
            var timerID = elements[i].id;
            var startDate = elements[i].innerText;
            startCounter(startDate, timerID);
        };
    });

    function startCounter(entryDate, timerID) {
        var entDate = new Date(entryDate);
        var year = (entDate).getFullYear();
        var month = (entDate).getMonth() + 1;
        var day = (entDate).getDate();
        var hour = (entDate).getHours();
        var min = (entDate).getMinutes();
        var sec = (entDate).getSeconds();

        $("#" + timerID).empty();
        $("#" + timerID).countup({
            start: new Date(year, month, day, hour, min, sec) //year, month, day, hour, min, sec
        });
    };
</code>```

Body:
I'm trying to add a javascript timer for products, if the item have a promotion then show the timer and start the count down.. so what i'm doing is im sending the end date from code behind to the javascript function and the function creates the timer based on the end date. I've been trying for long time the script is working, the issue is i'm not able to loop inside the nested repeater to get the correct countdown control id and index.
hope you guys can help me with this issue.
thanks

HTML Code:

        <asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="rptdep_ItemDataBound" OnItemCommand="rptdep_Details_Command">
        <ItemTemplate>
            <asp:LinkButton class="navbar-brand" runat="server" ID="LinkButton1" Style="text-decoration: none; margin-right: -25px; border: none; font-size: medium" CommandArgument='<%#Eval("department_code") %>' CommandName="more">
                <asp:Repeater runat="server" ID="rptdeppromo" OnItemDataBound="rptdeppromo_ItemDataBound" OnItemCommand="Item_depPromo_Command">
                    <ItemTemplate>

                    </ItemTemplate>
                </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>

Timer JS code:

function producttimer(compntname, enddate1, col) {
        $(document).ready(function () {

            var $countdown = $('#rptdep_rptdeppromo_' + compntname + '_countdown_' + col);

                // set the date we're counting down to
                var target_date = new Date(enddate1);
                // variables for time units
                var days, hours, minutes, seconds;

                // update the tag with id "countdown" every 1 second
                setInterval(function () {
                    target_date.getTime();

                    // find the amount of "seconds" between now and target
                    var current_date = new Date().getTime();

                    // check for match
                    if (current_date === target_date) {
                    }

                    var seconds_left = (target_date - current_date) / 1000;

                    // do some time calculations
                    days = parseInt(seconds_left / 86400);
                    seconds_left = seconds_left % 86400;

                    hours = parseInt(seconds_left / 3600);
                    seconds_left = seconds_left % 3600;

                    minutes = parseInt(seconds_left / 60);
                    seconds = parseInt(seconds_left % 60);

                    // format countdown string + set tag value
                    $countdown.text(days + "days, " + hours + "hrs, " + minutes + "min, " + seconds + "s");
                }, 1000);
        }); //EOF DOCUMENT.READY
    }

C# parent repeater code:

protected void rptdep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Repeater innerRepeater2 = (Repeater)e.Item.FindControl("rptdeppromo");
        DataRowView drv = (DataRowView)(e.Item.DataItem);

        }
    }
}

C# nested repeater code:

protected void rptdeppromo_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataRowView drv = (DataRowView)(e.Item.DataItem);

DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(drv.Row["publishtdt"]).ToString("dd MMM yyyy"));

        int countw = 0;
        int count = 0;

        if (total < 30)
        {
            count += 1;
            foreach (RepeaterItem item in rptdep.Items)
            {
                countw += 1;
            }
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "counter" + countw, "producttimer('" + countw + "','" + EndDate + "', '" + e.Item.ItemIndex + "');", true);
        }
        else
        {

        }
    }
}

Body:
the upvoted answer worked for me, but i needed to tweak it a bit. I thought some code may help the next person who looks here.
using the plugin jquery.countup.js (any counter should work):

<div id="div<%# ((RepeaterItem)Container).ItemIndex + 1%>"  class="countdown">
     <%# Eval("EntryDate") %>
</div>

<script type="text/javascript">
    $(function () {
        var elements = document.getElementsByClassName('countdown');
        var len = elements.length;
        for (var i = 0; i < len; ++i) {
            var timerID = elements[i].id;
            var startDate = elements[i].innerText;
            startCounter(startDate, timerID);
        };
    });

    function startCounter(entryDate, timerID) {
        var entDate = new Date(entryDate);
        var year = (entDate).getFullYear();
        var month = (entDate).getMonth() + 1;
        var day = (entDate).getDate();
        var hour = (entDate).getHours();
        var min = (entDate).getMinutes();
        var sec = (entDate).getSeconds();

        $("#" + timerID).empty();
        $("#" + timerID).countup({
            start: new Date(year, month, day, hour, min, sec) //year, month, day, hour, min, sec
        });
    };


问:
Propublica API json data into Google Sheets
This is my first post. I am a Google Sheets devotee using add-ons for anything complex. Sans add-on, I lurk (skulk) for snippets that sometimes work. Tired of illegitimate grifting I can't learn from and going back to basics.. I have been working on the below code for several days and after viewing videos and reading tutorials I am stuck.

Accessing: Propublica Campaign Finance API in Google Sheets to download one of several tables I intend to use. 2 functions in my code: getData and populateSheet. Logs show data each time. Sheet shows only the header row.

Here is my public spreadsheet:

https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing

Propublica Campaign Finance API instructions:

"The Campaign Finance API uses a RESTful style. The API only accepts GET requests. All requests begin with: https://api.propublica.org/campaign-finance/v1/.
The API key must be included in all API requests to the server, set as a header: X-API-Key: PROPUBLICA_API_KEY

Here is the code I am using:

```<code>var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'
var params = {
  headers: {'X-API-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
  }

function getData() {
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    return data //Return JSON object recevied from API

}

function populateSheet() {
    var data = getData(); //Get JSON data from the above function
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRowCount = sheet.getLastRow();
    var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];

    sheet.clear();
    sheet.getRange(1, 1, 1, header.length).setValues([header]);

    for (var i = 0; i < data.length; i++) {
        var row = [];
        var nextRow = sheet.getLastRow() + 1;
        row.push(data[i].id, data[i].relative_uri, data[i].name, data[i].address, data[i].city, data[i].state, data[i].zip, data[i].treasurer, data[i].party, data[i].fec_uri, data[i].candidate, data[i].leadership, data[i].super_pac, data[i].sponsor_name, data[i].designation, data[i].filing_frequency, data[i].committee_type, data[i].interest_group)
        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    }
}
</code>```

Thank you in advance for any guidance you may provide (even "go read this and learn")..

答:
In order to pull all of the records rather than just 20 at a time, you need to use a recursive call at the end of your record set to call the entire process again, and get the next batch.

This code alters your API call by changing the URL's "offset" value, incrementing by 20 each time the function is re-run.

You need an "out clause" so that when it hits the last record and the data stream ends, it ends the process. That's found in this line here:

```<code> if (!res || !res[0]) return
</code>```

This has been tested and appears to be working to pull 566 records instead of just 20.

```<code>var params = {
  headers: {'X-API-Key': 'your key'}
  }

var offset = 0;

function getData(offset) {
    var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json?offset='+offset;
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    populateSheet(data,offset);
//    return data //Return JSON object recevied from API
}

function populateSheet(data,offset) {

 // var data = getData(); //Get JSON data from the above function
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRowCount = sheet.getLastRow();
  var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];
  sheet.clear();
  sheet.getRange(1, 1, 1, header.length).setValues([header]);

  // I added below.
  var res = [];
  var lenny = data.results.length;
  var counter = 0;
  data.results.forEach(function(e) {
    var temp = [];
    header.forEach(function(h) {
      temp.push(e[h]);
    });
    res.push(temp);
    counter++;
    Logger.log('counter is '+counter);
    if (counter == lenny) {
      Logger.log('GOT LENNY counter is '+counter);
      offset = offset + 20;
      getData(offset);
    }
  });

  var nextRow = sheet.getLastRow() + 1;
  if (!res || !res[0]) return
  sheet.getRange(nextRow, 1, res.length, res[0].length).setValues(res); // Modified

}
</code>```

Body:
This is my first post. I am a Google Sheets devotee using add-ons for anything complex. Sans add-on, I lurk (skulk) for snippets that sometimes work. Tired of illegitimate grifting I can't learn from and going back to basics.. I have been working on the below code for several days and after viewing videos and reading tutorials I am stuck.

Accessing: Propublica Campaign Finance API in Google Sheets to download one of several tables I intend to use. 2 functions in my code: getData and populateSheet. Logs show data each time. Sheet shows only the header row.

Here is my public spreadsheet:

https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing

Propublica Campaign Finance API instructions:

"The Campaign Finance API uses a RESTful style. The API only accepts GET requests. All requests begin with: https://api.propublica.org/campaign-finance/v1/.
The API key must be included in all API requests to the server, set as a header: X-API-Key: PROPUBLICA_API_KEY

Here is the code I am using:

var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'
var params = {
  headers: {'X-API-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
  }

function getData() {
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    return data //Return JSON object recevied from API

}

function populateSheet() {
    var data = getData(); //Get JSON data from the above function
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRowCount = sheet.getLastRow();
    var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];

    sheet.clear();
    sheet.getRange(1, 1, 1, header.length).setValues([header]);

    for (var i = 0; i < data.length; i++) {
        var row = [];
        var nextRow = sheet.getLastRow() + 1;
        row.push(data[i].id, data[i].relative_uri, data[i].name, data[i].address, data[i].city, data[i].state, data[i].zip, data[i].treasurer, data[i].party, data[i].fec_uri, data[i].candidate, data[i].leadership, data[i].super_pac, data[i].sponsor_name, data[i].designation, data[i].filing_frequency, data[i].committee_type, data[i].interest_group)
        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    }
}

Thank you in advance for any guidance you may provide (even "go read this and learn")..

Body:
In order to pull all of the records rather than just 20 at a time, you need to use a recursive call at the end of your record set to call the entire process again, and get the next batch.

This code alters your API call by changing the URL's "offset" value, incrementing by 20 each time the function is re-run.

You need an "out clause" so that when it hits the last record and the data stream ends, it ends the process. That's found in this line here:

 if (!res || !res[0]) return

This has been tested and appears to be working to pull 566 records instead of just 20.

var params = {
  headers: {'X-API-Key': 'your key'}
  }

var offset = 0;

function getData(offset) {
    var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json?offset='+offset;
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    populateSheet(data,offset);
//    return data //Return JSON object recevied from API
}

function populateSheet(data,offset) {

 // var data = getData(); //Get JSON data from the above function
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRowCount = sheet.getLastRow();
  var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];
  sheet.clear();
  sheet.getRange(1, 1, 1, header.length).setValues([header]);

  // I added below.
  var res = [];
  var lenny = data.results.length;
  var counter = 0;
  data.results.forEach(function(e) {
    var temp = [];
    header.forEach(function(h) {
      temp.push(e[h]);
    });
    res.push(temp);
    counter++;
    Logger.log('counter is '+counter);
    if (counter == lenny) {
      Logger.log('GOT LENNY counter is '+counter);
      offset = offset + 20;
      getData(offset);
    }
  });

  var nextRow = sheet.getLastRow() + 1;
  if (!res || !res[0]) return
  sheet.getRange(nextRow, 1, res.length, res[0].length).setValues(res); // Modified

}


问:
How to filter a dataframe by multiple columns and add a value
```<code>df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')

lst = df[(df['El4'] == el4)] #contains specific rows of df

for i, row in lst.iterrows():
    prop = row['propertyid']
    mouvement = (row['Mouvements']*-1)

    a = invoices[(invoices['propertyReference'] == prop) & (invoices.invoiceGrossAmount == mouvement)]
    invoiceid = a['invoiceId'].values

    mouvement = (mouvement*-1)

    if df[(df.propertyid == prop) & (df.Mouvements == mouvement)]:
        df['id'] = invoiceid
</code>```

I receive the following error:

```<code>The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

I would like to fill in specific values (invoiceId) in the rows of the dataframe where propertyid equals prop and mouvements equals mouvement.

答:
Following up on my comment.  It seems like you're just trying to join (or, in pandas terminology, a merge).

Let's start with your source data:

```<code>df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')
</code>```

From here, we want to try to join the data:

```<code>df = df.merge(invoices, how='left', left_on=['propertyid', 'Mouvements'], right_on=['propertyReference', 'invoiceGrossAmount'])
</code>```

In this join, I'm assuming that 'propertyid' in df matches with 'propertyReference' in invoices and that 'Mouvements' in df matches with 'invoiceGrossAmount' in invoices.  You can adjust as needed.

We're using a left join because we want null values in the original df when we can't find a match in invoices rather than not including those rows (in which case we'd use how='inner' instead).

No need to use a for loop this way.  I remember reading somewhere that if you're using a loop with pandas, there's a good chance there's a better way to do it with a built-in pandas method.

Body:
df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')

lst = df[(df['El4'] == el4)] #contains specific rows of df

for i, row in lst.iterrows():
    prop = row['propertyid']
    mouvement = (row['Mouvements']*-1)

    a = invoices[(invoices['propertyReference'] == prop) & (invoices.invoiceGrossAmount == mouvement)]
    invoiceid = a['invoiceId'].values

    mouvement = (mouvement*-1)

    if df[(df.propertyid == prop) & (df.Mouvements == mouvement)]:
        df['id'] = invoiceid

I receive the following error:

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I would like to fill in specific values (invoiceId) in the rows of the dataframe where propertyid equals prop and mouvements equals mouvement.

Body:
Following up on my comment.  It seems like you're just trying to join (or, in pandas terminology, a merge).

Let's start with your source data:

df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')

From here, we want to try to join the data:

df = df.merge(invoices, how='left', left_on=['propertyid', 'Mouvements'], right_on=['propertyReference', 'invoiceGrossAmount'])

In this join, I'm assuming that 'propertyid' in df matches with 'propertyReference' in invoices and that 'Mouvements' in df matches with 'invoiceGrossAmount' in invoices.  You can adjust as needed.

We're using a left join because we want null values in the original df when we can't find a match in invoices rather than not including those rows (in which case we'd use how='inner' instead).

No need to use a for loop this way.  I remember reading somewhere that if you're using a loop with pandas, there's a good chance there's a better way to do it with a built-in pandas method.


问:
Change dll output in a project using visual studio 2010 express
In VS 2010 express there are a few library projects (dlls) attached to the application project. When building the solution the dlls output to bin/Release/. Is there a way to have the .exe output to bin/Release and the dlls to bin/Release/dll?</p>

答:
You could always have a post build event on the application project that copies all .dll files to a dll directory.

However the assembly loader will not be able to find the dll file and you application will not start.


问:
Vectorising a Matlab double loop involving 3D matrices?
Consider the following matrices in Matlab

```<code>A(:,:,1)=[1 2 3; 4 5 6];
A(:,:,2)=[7 8 9; 10 11 12];
M=size(A,1);
N=size(A,2);
R=size(A,3);
</code>```

I want to create a matrix B of dimension (M*N)x(N-1)xR such that

-for each r=1,...,R,

-for each m=1,...,M

-for each h=1,...,N

-I take A(m,h,r), sum it with each of the N-1 remaining elements in A(m,:,r), and fill B((m-1)*N+h,:,r).

In the example above it should be

```<code>B(:,:,1)=[1+2 1+3;
          2+1 2+3;
          3+1 3+2;
          4+5 4+6;
          5+4 5+6;
          6+4 6+5]

B(:,:,2)=[7+8 7+9;
          8+7 8+9;
          9+7 9+8;
          10+11 10+12;
          11+10 11+12;
          12+10 12+11]
</code>```

This code does what I want but it contains a double loop, which for M,N large may be slow. Could you help me to vectorize?

```<code>for m=1:M
    for h=1:N
        B((m-1)*N+h,:,:)= repmat(A(m,h,:),1,N-1)+[A(m,1:h-1,:) A(m,h+1:N,:)];
    end
end
</code>```

答:
I'm not sure how much more efficient it will be, but you could reduce it to a single loop like so:</p>

```<code>[M, N, R] = size(A);
B = zeros(M*N, N-1, R);
for index = logical(eye(N))
  B(find(index):N:end, :, :) = bsxfun(@plus, A(:, ~index, :), A(:, index, :));
end
</code>```

Body:
Consider the following matrices in Matlab

A(:,:,1)=[1 2 3; 4 5 6];
A(:,:,2)=[7 8 9; 10 11 12];
M=size(A,1);
N=size(A,2);
R=size(A,3);

I want to create a matrix B of dimension (M*N)x(N-1)xR such that

-for each r=1,...,R,

-for each m=1,...,M

-for each h=1,...,N

-I take A(m,h,r), sum it with each of the N-1 remaining elements in A(m,:,r), and fill B((m-1)*N+h,:,r).

In the example above it should be

B(:,:,1)=[1+2 1+3;
          2+1 2+3;
          3+1 3+2;
          4+5 4+6;
          5+4 5+6;
          6+4 6+5]

B(:,:,2)=[7+8 7+9;
          8+7 8+9;
          9+7 9+8;
          10+11 10+12;
          11+10 11+12;
          12+10 12+11]

This code does what I want but it contains a double loop, which for M,N large may be slow. Could you help me to vectorize?

for m=1:M
    for h=1:N
        B((m-1)*N+h,:,:)= repmat(A(m,h,:),1,N-1)+[A(m,1:h-1,:) A(m,h+1:N,:)];
    end
end

Body:
I'm not sure how much more efficient it will be, but you could reduce it to a single loop like so:

[M, N, R] = size(A);
B = zeros(M*N, N-1, R);
for index = logical(eye(N))
  B(find(index):N:end, :, :) = bsxfun(@plus, A(:, ~index, :), A(:, index, :));
end


问:
vref rejects new branches to be pushed
I would like to configure a repository to be accessed by every developer but one particular file should only be modified by certain users.

```<code>RWCD                             = @developer
RW+ refs/tags                    = @developer
RW+ VREF/NAME/version.properties = @versionPropertyModifier
-   VREF/NAME/version.properties = @all
</code>```

This works all fine but there is one problem:
When any developer who is not member of the @versionPropertyModifier group wants to push a new branch the push is rejected with link to the version.properties vref.

Whats wrong with my rule set?

答:
The example for Vref/NAME is not exactly the same:

```<code>repo foo
        RW+                             =   @senior_devs
        RW                              =   @junior_devs

        -   VREF/NAME/Makefile          =   @junior_devs
</code>```

When a senior dev pushes, the VREF is not invoked at all. But when a junior dev pushes, the VREF is invoked, and it returns a list of files changed as virtual refs, looking like this:

```<code>VREF/NAME/file-1
VREF/NAME/dir-2/file-3
...etc...
</code>```

Each of these refs is matched against the access rules. If one of them happens to be the Makefile, then the ref returned (VREF/NAME/Makefile) will match the deny rule and kill the push.

So in your case:

```<code>RWCD                              = @developer
RW+  refs/tags                    = @developer
-    VREF/NAME/version.properties = @versionPropertyModifier
</code>```

Title: vref rejects new branches to be pushed

Body:
I would like to configure a repository to be accessed by every developer but one particular file should only be modified by certain users.

RWCD                             = @developer
RW+ refs/tags                    = @developer
RW+ VREF/NAME/version.properties = @versionPropertyModifier
-   VREF/NAME/version.properties = @all

This works all fine but there is one problem:
When any developer who is not member of the @versionPropertyModifier group wants to push a new branch the push is rejected with link to the version.properties vref.

Whats wrong with my rule set?

Body:
The example for Vref/NAME is not exactly the same:

repo foo
        RW+                             =   @senior_devs
        RW                              =   @junior_devs

        -   VREF/NAME/Makefile          =   @junior_devs

When a senior dev pushes, the VREF is not invoked at all. But when a junior dev pushes, the VREF is invoked, and it returns a list of files changed as virtual refs, looking like this:

VREF/NAME/file-1
VREF/NAME/dir-2/file-3
...etc...

Each of these refs is matched against the access rules. If one of them happens to be the Makefile, then the ref returned (VREF/NAME/Makefile) will match the deny rule and kill the push.

So in your case:

RWCD                              = @developer
RW+  refs/tags                    = @developer
-    VREF/NAME/version.properties = @versionPropertyModifier


答:
Ofc it does not work. you have to set the data on the template you use.

in your case:

```<code>const Foo = {
  template: '<div>{{foo}}</div>',
  data () {
    return {
      foo: 'magic'
    }
  }
}
</code>```

Cheers and happy coding.

Title: Vue Router. Bind data

Body:
I am developing vue app and now I am on step when I should use vue router.
But I have a little problem with data bind into router template.

Please help me.

HTML:

Hello App!

    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>

  <router-view></router-view>

Script:

const Foo = { template: '
{{foo}}
' }
const Bar = { template: '
bar
' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
el: '#app',
  router,
  data: function(){
    return {foo: "asdasdas"}
  }
})

{{foo}} bind doesn't work.

Live example:
https://jsfiddle.net/xgrjzsup/4430/

Body:
Ofc it does not work. you have to set the data on the template you use.

in your case:

const Foo = {
  template: '<div>{{foo}}</div>',
  data () {
    return {
      foo: 'magic'
    }
  }
}

Cheers and happy coding.


问:
Width and Height Equal to its superView using autolayout programmatically?
I've been looking for a lot of snippets in the net and I still can't find the answer to my problem. My question is I have a scrollView(SV) and I want to add a button inside scrollView(SV) programmatically with same width and height of its superview which is scrollView(SV) so that when user rotate the device button will have the same frame of scrollView(SV). how to do the NSLayout/NSLayoutConstraint? thanks</p>

答:
Swift 4 using NSLayoutConstraint:

```<code>footerBoardImageView.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint  = NSLayoutConstraint(item: yourview, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: yourview, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0)
superview.addConstraints([widthConstraint, heightConstraint])
</code>```

Body:
Swift 4 using NSLayoutConstraint:

footerBoardImageView.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint  = NSLayoutConstraint(item: yourview, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: yourview, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0)
superview.addConstraints([widthConstraint, heightConstraint])


问:
Css input shape
I wrote this css to make a form have the little openid logo on the left but I would like the form to retain its default look rather than get that right angley look.</p>

```<code><html>
<head>
<style type="text/css">
.openid-input {
  background: url("http://id.gesellix.de/logo/openid_small_logo_white.gif") no-repeat scroll left center transparent;
  height: 22px;
  line-height: 22px;
  padding-left: 18px;
}
</style>
</head>

<body>
<input type="text" tabindex="100" class="openid-input">
</body>
</html>
</code>```

答:
The default input styling gets overridden as soon as you change the background property.  You must set CSS styling to mimic the default styling, but this can only be accomplished with CSS3.  The following styles match closely on my system:

```<code>border:1px #e4e4e4 solid;
box-shadow:inset 0 1px 2px #000000;
-moz-box-shadow:inset 0 1px 2px #000000;
-webkit-box-shadow:inset 0 1px 2px #000000;
</code>```

I've created an example here (link).

You can get pretty close to the default styling without CSS3 with just:

```<code>border:1px #cccccc solid;
border-top:2px #666666 solid;
</code>```

Title: Css input shape

Body:
I wrote this css to make a form have the little openid logo on the left but I would like the form to retain its default look rather than get that right angley look.

<input type="text" tabindex="100" class="openid-input">

Body:
The default input styling gets overridden as soon as you change the background property.  You must set CSS styling to mimic the default styling, but this can only be accomplished with CSS3.  The following styles match closely on my system:

border:1px #e4e4e4 solid;
box-shadow:inset 0 1px 2px #000000;
-moz-box-shadow:inset 0 1px 2px #000000;
-webkit-box-shadow:inset 0 1px 2px #000000;

I've created an example here (link).

You can get pretty close to the default styling without CSS3 with just:

border:1px #cccccc solid;
border-top:2px #666666 solid;


问:
Deploy small change to google app engine
I want to deploy a change in my app.yaml file to google app engine. Is there a simple way to do this without redeploying the whole app? Is there a way of changing the app.yaml file on the google cloud directly? Or just deploying one file from my Windows directory?

My app is working fine in the virtual environment but I'm having some issues on the google cloud platform. The whole deploying process takes quite a while so I'm looking for a faster way to make a change and test it.

答:
You can use appcfg.py update app.yaml from AppEngine Python SDK:

https://cloud.google.com/appengine/docs/standard/python/tools/appcfg-arguments#update

Use the files argument to upload one or more YAML files that define
  modules. No other types of YAML files can appear in the command line.
  Only the specified modules will be updated.


问:
How do I remove the blank spaces in my csv scrapy
How do I remove the blank spaces in my csv?

I run: scrapy crawl quotes -o quotes.csv.  And output is like that in the picture.

I know it's a windows problem as I have to use below code when working with csv's on windows.  For example when working with selenium.

```<code>with open('C:\\fa.csv', 'a+', newline='', encoding="utf-8") as outfile:
</code>```

Scrapy deals with Csv's differently and I launch with

```<code>scrapy crawl quotes -o quotes.csv

There is no: scrapy crawl quotes -o /n quotes.csv
</code>```

Code:

```<code>import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
                'tags': quote.css('div.tags a.tag::text').extract(),
            }

        next_page = response.css('li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)
</code>```

答:
You could try the following fix:

```<code>from scrapy.conf import settings
from scrapy.contrib.exporter import CsvItemExporter

class FixCsvItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        newline = settings.get('CSV_NEWLINE', '')
        kwargs['newline'] = newline
        super(FixCsvItemExporter, self).__init__(*args, **kwargs)
</code>```

Then, in the settings.py file in your crawler directory you need to add this:

```<code>FEED_EXPORTERS = {
    'csv': 'path.to.sourcefile.FixCsvItemExporter',
}
</code>```

Body:
How do I remove the blank spaces in my csv?

I run: scrapy crawl quotes -o quotes.csv.  And output is like that in the picture.

I know it's a windows problem as I have to use below code when working with csv's on windows.  For example when working with selenium.

with open('C:\\fa.csv', 'a+', newline='', encoding="utf-8") as outfile:

Scrapy deals with Csv's differently and I launch with

scrapy crawl quotes -o quotes.csv

There is no: scrapy crawl quotes -o /n quotes.csv

Code:

import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
                'tags': quote.css('div.tags a.tag::text').extract(),
            }

        next_page = response.css('li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

Body:
You could try the following fix:

from scrapy.conf import settings
from scrapy.contrib.exporter import CsvItemExporter

class FixCsvItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        newline = settings.get('CSV_NEWLINE', '')
        kwargs['newline'] = newline
        super(FixCsvItemExporter, self).__init__(*args, **kwargs)

Then, in the settings.py file in your crawler directory you need to add this:

FEED_EXPORTERS = {
    'csv': 'path.to.sourcefile.FixCsvItemExporter',
}


问:
Basic HTML White square header Bug Homepage
I build by research and copy+paste this fixed Headertitle but unfortunately I have a problem after I load the side and scroll up there is a white space where the title jumps into and than back. Can anyone help me removing this Bug?

Its super annoying...and I tried almost everything to remove it.

I want it that my Title is fixed at one point and stays there in the top layer thats why I also put zindex -999

window.onscroll = function() {myFunction()};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body
  margin: 0;
  font-family: Impact;z-index: 999;
}

.top-container {
  position: absolute;
  text-align: center;
  background: #transparent;
  color: #transparent;
  z-index: 999;
}

.header {
  position: auto;
  padding: auto, auto;
  text-align: center;
  background: #transparent;
  color: #transparent;
  z-index: 999;
}

.content {
  padding: 10px;
  z-index: 999;
}

.sticky {
  position: fixed;
  text-align: center;
  top: 0;
  z-index: 999;
  width: 100%;
}

.sticky + .content {
  position: absolute;
  padding-top: 0px;
  z-index: 999;
}</code>```

97cm

```

答:
Just add your sticky class and get rid of the javascript

```<code><div class="header sticky" id="myHeader">
</code>```

Explanation:

Your sticky class is set up to "stick" the div to the top of the page, but you don't actually assign this class to your
.

Then you have some javascript that checks if you've scrolled down the page and then assigns the .sticky class to your

The white space and "jump" that you're seeing is the delay between you scrolling, and the javascript applying the .sticky class. You always want this
 to be sticky, so just have the sticky class permanently assigned to it, and remove all the javascript.

Body:
I build by research and copy+paste this fixed Headertitle but unfortunately I have a problem after I load the side and scroll up there is a white space where the title jumps into and than back. Can anyone help me removing this Bug?

Its super annoying...and I tried almost everything to remove it.

I want it that my Title is fixed at one point and stays there in the top layer thats why I also put zindex -999

window.onscroll = function() {myFunction()};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

body
  margin: 0;
  font-family: Impact;z-index: 999;
}

.top-container {
  position: absolute;
  text-align: center;
  background: #transparent;
  color: #transparent;
  z-index: 999;
}

.header {
  position: auto;
  padding: auto, auto;
  text-align: center;
  background: #transparent;
  color: #transparent;
  z-index: 999;
}

.content {
  padding: 10px;
  z-index: 999;
}

.sticky {
  position: fixed;
  text-align: center;
  top: 0;
  z-index: 999;
  width: 100%;
}

.sticky + .content {
  position: absolute;
  padding-top: 0px;
  z-index: 999;
}

97cm

Body:
Just add your sticky class and get rid of the javascript

<div class="header sticky" id="myHeader">

Explanation:

Your sticky class is set up to "stick" the div to the top of the page, but you don't actually assign this class to your <div>.

Then you have some javascript that checks if you've scrolled down the page and then assigns the .sticky class to your <div>

The white space and "jump" that you're seeing is the delay between you scrolling, and the javascript applying the .sticky class. You always want this </div> to be sticky, so just have the sticky class permanently assigned to it, and remove all the javascript.


问:
For loop is only checking last value
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

```<code>public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}
</code>```

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

答:
A Java 8 solution would be to avoid the for loop entirely and simply say:</p>

```<code>boolean userFound = collection.stream()
    .map(User::getUsername)
    .anyMatch(n -> n.equals(username))
</code>```

Title: For loop is only checking last value

Body:
I feel like I'm missing something really simple but I can't seem to find much help for it. So I'm designing a login using vaadin and a h2 in mem SQL database. There is a method that returns the values from the database in a list. The trouble is that I'm having problems with the method below. It's meant to iterate through every entry in the list and if it finds a username / password that matches then return true. If not return false.....

public boolean checkUserInDatabase(String username, String email) {
    boolean result = false;
    List<User> localArray = getUserList();

    System.out.println("List retrieved...Checking user in database"+
localArray);
    for (User u : localArray ) {
        if (u.getUsername().equals(username)) {
            result = true;
        }
        else {

            result = false;
        }
    }
    return result;
}

I'm aware that at this point I'm only checking the username however, when I add users to the database it will still only check the last user in that database....thoughts?

Body:
A Java 8 solution would be to avoid the for loop entirely and simply say:

boolean userFound = collection.stream()
    .map(User::getUsername)
    .anyMatch(n -> n.equals(username))


问:
MySQL match all occurrences of a string
I am facing problems with matching string in a mysql query, I am using Laravel. My problem lies in this line

```<code>-> where ('service', 'like', '%'. $request->get('service') . '%')
</code>```

My requested service is hair cut womenand my service at the database is Hair Women Style & Cut. For some reason, these two strings are not matching.

So,

play game won't match with play good two & game

Is the above query supposed to work with this match? Is the special charecter &  hindering the match? I am not experienced with MySQL so I am seeking help.

答:
%string% matches string with 0 or more characters before and after it.

%hair cut% will match cool hair cut but not hair for cut because there is an unmatching word mixed in

if you wish to match words then you have to split the search term and create multiple where clauses.

```<code>$terms = explode(" ", $request->get('service'));
for ($terms as $term)
    $query->where('service', 'like', '%'. $term . '%')
</code>```

the resulting query will be similar to

```<code>WHERE service LIKE '%hair%' AND service LIKE '%cut%'
</code>```

Title: MySQL match all occurrences of a string

Body:
I am facing problems with matching string in a mysql query, I am using Laravel. My problem lies in this line

-> where ('service', 'like', '%'. $request->get('service') . '%')

My requested service is hair cut womenand my service at the database is Hair Women Style & Cut. For some reason, these two strings are not matching.

So,

play game won't match with play good two & game

Is the above query supposed to work with this match? Is the special charecter &  hindering the match? I am not experienced with MySQL so I am seeking help.

Body:
%string% matches string with 0 or more characters before and after it.

%hair cut% will match cool hair cut but not hair for cut because there is an unmatching word mixed in

if you wish to match words then you have to split the search term and create multiple where clauses.

$terms = explode(" ", $request->get('service'));
for ($terms as $term)
    $query->where('service', 'like', '%'. $term . '%')

the resulting query will be similar to

WHERE service LIKE '%hair%' AND service LIKE '%cut%'


问:
How would I change an equation to modulate a number on a line, to one that that modulates on a sine curve?
I'm trying to modulate an alpha value in a Java application I'm building on Android. Right now it goes like this:

```<code>if (goingUp) {
    newAlpha = oldAlpha + rateOfChange;
    if (newAlpha > maxAlpha) {
        newAlpha = maxAlpha;
        goingUp = false;
    }
} else {
    newAlpha = oldAlpha - rateOfChange;
    if (newAlpha < minAlpha) {
        newAlpha = minAlpha;
        goingUp = true;
    }
}
</code>```

Where rateOfChange is an arbitrary int that cannot be greater than maxAlpha. The equation is evaluate every tick in a thread and is independent of time.

Is there a way using only the variables given + Math.PI and other Math elements (I'm assuming Math.Sine will be in there) to get newAlpha to be a number on a Sine?

I'm thinking min and max would be the amp of the wave and rateOfChange would be a product of the Sine function, I just can't figure out how it all goes together.

答:
Your equation will look like this:

y is vertical position at time t, A is the amplitude, f is the frequency, and t is the time (or ticks of your Android clock).

Body:
I'm trying to modulate an alpha value in a Java application I'm building on Android. Right now it goes like this:

if (goingUp) {
    newAlpha = oldAlpha + rateOfChange;
    if (newAlpha > maxAlpha) {
        newAlpha = maxAlpha;
        goingUp = false;
    }
} else {
    newAlpha = oldAlpha - rateOfChange;
    if (newAlpha < minAlpha) {
        newAlpha = minAlpha;
        goingUp = true;
    }
}

Where rateOfChange is an arbitrary int that cannot be greater than maxAlpha. The equation is evaluate every tick in a thread and is independent of time.

Is there a way using only the variables given + Math.PI and other Math elements (I'm assuming Math.Sine will be in there) to get newAlpha to be a number on a Sine?

I'm thinking min and max would be the amp of the wave and rateOfChange would be a product of the Sine function, I just can't figure out how it all goes together.


问:
Use Materializecss Alpha with Vue
Hearing of Materializecss Alpha release I was excited because I was a huge fan of it. But I am confused on how to import it into a typical vue.js app and initializing it plugins

for example, how we implement this in Vue:

```<code>var instance = new M.Carousel({
  fullWidth: true,
  indicators: true
})
</code>```

答:
Without JQuery and with webpack component

0) I tried to use 1.0.0-alpha.2 with npm (npm install materialize-css@next) but...

1) 1.0.0-alpha.2 has an error so meanwhile I cloned the last repo version directly from github and used with npm as local dependency (this will not be needed as soon as alpha.3 will be released):

2) I generated the webpack template with vue-cli

3) I substituted the HelloWorld component with the following one... where I put the carousel initialization code in the mounted method of the component

```<code><template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div class="carousel">
      <div v-for="elem in images">
        <a class="carousel-item" :href="elem.link"><img :src="elem.img" :alt="elem.link"></a>
      </div>
    </div>
  </div>
</template>

<script>
  import M from 'materialize-css'

  export default {
    name: 'Carousel',
    mounted () {
      var elem = document.querySelector('.carousel')
      // eslint-disable-next-line
      var t = new M.Carousel(elem, {
        indicators: true
      })
    },
    data () {
      return {
        msg: 'Welcome to Your Carousel Component',
        images: [
          {
            img: 'http://quintagroup.com/cms/technology/Images/materialize.png',
            link: 'https://github.com/Dogfalo/materialize'
          },
          {
            img: 'https://vuejs.org/images/logo.png',
            link: 'https://vuejs.org/'
          },
          {
            img: 'https://avatars1.githubusercontent.com/u/9919?s=200&v=4',
            link: 'https://github.com'
          }
        ]
      }
    }
  }
</script>
</code>```

4) I added import 'materialize-css/dist/css/materialize.min.css' to main.js

Title: Use Materializecss Alpha with Vue

Body:
Hearing of Materializecss Alpha release I was excited because I was a huge fan of it. But I am confused on how to import it into a typical vue.js app and initializing it plugins

for example, how we implement this in Vue:

var instance = new M.Carousel({
  fullWidth: true,
  indicators: true
})

Body:
Without JQuery and with webpack component

0) I tried to use 1.0.0-alpha.2 with npm (npm install materialize-css@next) but...

1) 1.0.0-alpha.2 has an error so meanwhile I cloned the last repo version directly from github and used with npm as local dependency (this will not be needed as soon as alpha.3 will be released):

2) I generated the webpack template with vue-cli

3) I substituted the HelloWorld component with the following one... where I put the carousel initialization code in the mounted method of the component

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div class="carousel">
      <div v-for="elem in images">
        <a class="carousel-item" :href="elem.link"><img :src="elem.img" :alt="elem.link"></a>
      </div>
    </div>
  </div>
</template>

<script>
  import M from 'materialize-css'

  export default {
    name: 'Carousel',
    mounted () {
      var elem = document.querySelector('.carousel')
      // eslint-disable-next-line
      var t = new M.Carousel(elem, {
        indicators: true
      })
    },
    data () {
      return {
        msg: 'Welcome to Your Carousel Component',
        images: [
          {
            img: 'http://quintagroup.com/cms/technology/Images/materialize.png',
            link: 'https://github.com/Dogfalo/materialize'
          },
          {
            img: 'https://vuejs.org/images/logo.png',
            link: 'https://vuejs.org/'
          },
          {
            img: 'https://avatars1.githubusercontent.com/u/9919?s=200&v=4',
            link: 'https://github.com'
          }
        ]
      }
    }
  }
</script>

4) I added import 'materialize-css/dist/css/materialize.min.css' to main.js


问:
Is there a way to programmatically attach to process with python?
I want to add function in my python code so that whenever I call it, it will auto attach to the process that runs it using the debugger of pycharm.

for example:

```<code># some code
# some code
# attach_here(pid)
# some code
# some code
</code>```

is there way to do that?

答: I'm not familiar with the ability to attach to local processes, but this is effectively how the remote debugger works. Setup PyCharm for remote debug usage, and then in your code when pydevd.settrace(...) is called, it connects to the debugger.

Body:
I want to add function in my python code so that whenever I call it, it will auto attach to the process that runs it using the debugger of pycharm.

for example:

# some code
# some code
# attach_here(pid)
# some code
# some code

is there way to do that?


问:
Compare two data frames with the same schema row by row
I need to compare two tables (i.e data frames) in spark data frame, row by row, and get each row with the smaller value for a specific column. For example:

Let's say I want to get each row with the lower scored subject for each student, so therefore I want this result:

I was thinking of joining both data frame first with id as join attribute, but my original tables are large and have more attributes. It seems that this is doable without join. The closest problem I can found is this but I don't know get how to apply that to my case.

Btw solutions with join are also appreciable, I am just thinking if there can be a better solution.

答:
You cannot do it without join, unless you can guarantee that each both have the same number of partitions and records in each partition. Then you can convert to RDD and zip. Otherwise just join:

```<code>import org.apache.spark.sql.functions.{least, struct}

val df1 = Seq(
  (345, "math", 70), (992, "chem", 76), (223, "bio", 80)
).toDF("id", "subject", "score")

val df2 = Seq(
  (345, "psy", 64), (992, "ant", 94), (223, "math",   45)
).toDF("id", "subject", "score")

df1.alias("df1")
  .join(df2.alias("df2"), Seq("id"))
  .select($"id",
    least(struct($"df1.score", $"df1.subject"),
          struct($"df2.score", $"df2.subject")).alias("score"))
  .select($"id", $"score.subject", $"score.score")

// +---+-------+-----+
// | id|subject|score|
// +---+-------+-----+
// |345|    psy|   64|
// |992|   chem|   76|
// |223|   math|   45|
// +---+-------+-----+
</code>```

or

```<code>import org.apache.spark.sql.functions.when

df1.alias("df1")
  .join(df2.alias("df2"), Seq("id"))
  .select(
    $"id",
    when($"df1.score" < $"df2.score", $"df1.subject").otherwise($"df2.subject").alias("subject"),
     least($"df1.score", $"df2.score").alias("score"))

// +---+-------+-----+
// | id|subject|score|
// +---+-------+-----+
// |345|    psy|   64|
// |992|   chem|   76|
// |223|   math|   45|
// +---+-------+-----+
</code>```

Body:
You cannot do it without join, unless you can guarantee that each both have the same number of partitions and records in each partition. Then you can convert to RDD and zip. Otherwise just join:

import org.apache.spark.sql.functions.{least, struct}

val df1 = Seq(
  (345, "math", 70), (992, "chem", 76), (223, "bio", 80)
).toDF("id", "subject", "score")

val df2 = Seq(
  (345, "psy", 64), (992, "ant", 94), (223, "math",   45)
).toDF("id", "subject", "score")

df1.alias("df1")
  .join(df2.alias("df2"), Seq("id"))
  .select($"id",
    least(struct($"df1.score", $"df1.subject"),
          struct($"df2.score", $"df2.subject")).alias("score"))
  .select($"id", $"score.subject", $"score.score")

// +---+-------+-----+
// | id|subject|score|
// +---+-------+-----+
// |345|    psy|   64|
// |992|   chem|   76|
// |223|   math|   45|
// +---+-------+-----+

or

import org.apache.spark.sql.functions.when

df1.alias("df1")
  .join(df2.alias("df2"), Seq("id"))
  .select(
    $"id",
    when($"df1.score" < $"df2.score", $"df1.subject").otherwise($"df2.subject").alias("subject"),
     least($"df1.score", $"df2.score").alias("score"))

// +---+-------+-----+
// | id|subject|score|
// +---+-------+-----+
// |345|    psy|   64|
// |992|   chem|   76|
// |223|   math|   45|
// +---+-------+-----+


问:
Error: candidate function not viable: 'this' argument has type 'const' but method is not marked const
I have been running into some issues trying to compile a project.  It keeps giving me the message: "candidate function not viable: 'this' argument has type 'const' but method is not marked const".  Below are the functions that this error is appearing by.

```<code>bool operator<(const node& x) const{
    if(name < x.name){
        return true;
    } else{
        return false;
    }
}

bool operator==(const node& x){
    if(name == x.name){
        return true;
    } else{
        return false;
    }
}
</code>```

If anyone has any thoughts or knows where I've gone wrong with using const I'd be extremely grateful.

答:
Change this:

```<code>bool operator==(const node& x) {
</code>```

to this:

```<code>bool operator==(const node& x) const {
</code>```

in order to mark your other function const as well.

Body:
I have been running into some issues trying to compile a project.  It keeps giving me the message: "candidate function not viable: 'this' argument has type 'const' but method is not marked const".  Below are the functions that this error is appearing by.

bool operator<(const node& x) const{
    if(name < x.name){
        return true;
    } else{
        return false;
    }
}

bool operator==(const node& x){
    if(name == x.name){
        return true;
    } else{
        return false;
    }
}

If anyone has any thoughts or knows where I've gone wrong with using const I'd be extremely grateful.

Body:
Change this:

bool operator==(const node& x) {

to this:

bool operator==(const node& x) const {

in order to mark your other function const as well.