问:
log4php + PHP 7 - catching and logging Throwable
I am having trouble logging a "TypeError" with log4php. I suspect this is because I recently upgraded from php 5.5 to 7.1.

Usually, my syntax looks like this:

```<code><?

use Logger;

class MyClass
{
    /** @var Logger */
    private $logger;

    function __construct(array $configParams)
    {
        Logger::configure('logger.xml');
        $this->logger = Logger::getLogger(__CLASS__);
    }

    public function dostuff()
    {
        try
        {
            // ...
        }
        catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex);
        }
    }
}

?>
</code>```

The above syntax will print lots of info to the log file, including a stack trace. However after reading the latest php7 docs, I believe I'm meant to handle the \Throwable interface, in order to catch both errors and exceptions (which is great). So I replace the above catch with the following:

```<code>catch (\Throwable $ex)
</code>```

This still prints stack-trace information for my exceptions, but when a "TypeError" is caught, nothing gets printed to the log file.

I assume that this is due to log4php not knowing how to log errors. How can I log errors using log4php in a universal way?

Thanks,

答:
Try to fix this

```<code>$this->logger->error("ERROR CAUGHT", $ex);
</code>```

with

```<code>$this->logger->error("ERROR CAUGHT : " . $ex->getMessage());
</code>```

log4php's documentation says that error method has just one parameter.

Body:
I am having trouble logging a "TypeError" with log4php. I suspect this is because I recently upgraded from php 5.5 to 7.1.

Usually, my syntax looks like this:

<?

use Logger;

class MyClass
{
    /** @var Logger */
    private $logger;

    function __construct(array $configParams)
    {
        Logger::configure('logger.xml');
        $this->logger = Logger::getLogger(__CLASS__);
    }

    public function dostuff()
    {
        try
        {
            // ...
        }
        catch (Exception $ex)
        {
            $this->logger->error("ERROR CAUGHT", $ex);
        }
    }
}

?>

The above syntax will print lots of info to the log file, including a stack trace. However after reading the latest php7 docs, I believe I'm meant to handle the \Throwable interface, in order to catch both errors and exceptions (which is great). So I replace the above catch with the following:

catch (\Throwable $ex)

This still prints stack-trace information for my exceptions, but when a "TypeError" is caught, nothing gets printed to the log file.

I assume that this is due to log4php not knowing how to log errors. How can I log errors using log4php in a universal way?

Thanks,

Body:
Try to fix this

$this->logger->error("ERROR CAUGHT", $ex);

with

$this->logger->error("ERROR CAUGHT : " . $ex->getMessage());

log4php's documentation says that error method has just one parameter.


来源: stackexchange

问:
C# - Getting the current day of the month without month/year
Is there any way to get the day of the month as an int/string? E.G it's the 5th of June, I want the system to return 5 to me.</p>

答:
sure,

as an integer, it's just DateTime.Today.Day

    as a string it's DateTime.Today.Day.ToString("0")

ContentLicense: CC BY-SA 3.0


问:
background color not shown when there is image
I am trying to create a canvas where user can either add background image or background color and write a text over them. However i could not show background color when there is background image. I have created a fiddle of that to show an example. You can try add image and add color button in the fiddle.

http://jsbin.com/sukuvoqahi/edit?html,js,output

Here is my code

```<code>const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('image');
  canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
    canvasRef.renderAll();
  });
});

addBackgroundColor.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('color');
  canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
  })
});
</code>```

答:
Just remove the Backgroud Image.
I am new to FabricJS, so I am not sure if that is the best way to do it.
But this solution seems to work:

```<code>canvasRef.setBackgroundImage(null) => {
    canvasRef.renderAll();
});
canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
});
</code>```

Here is a working demo:

JSBin

Body:
I am trying to create a canvas where user can either add background image or background color and write a text over them. However i could not show background color when there is background image. I have created a fiddle of that to show an example. You can try add image and add color button in the fiddle.

http://jsbin.com/sukuvoqahi/edit?html,js,output

Here is my code

const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('image');
  canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
    canvasRef.renderAll();
  });
});

addBackgroundColor.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('color');
  canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
  })
});

Body:
Just remove the Backgroud Image.
I am new to FabricJS, so I am not sure if that is the best way to do it.
But this solution seems to work:

canvasRef.setBackgroundImage(null) => {
    canvasRef.renderAll();
});
canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
});

Here is a working demo:

JSBin


问:
C++ templates: How to conditionally compile different code based on data type?
Here's a small example that illustrates the essence of my question:

```<code>#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}
</code>```

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

答:
You can use template specialization.

```<code>template<typename T>
class STRING {
public:
 T *    memory   ;
 int    size     ;
 int    capacity ;
public:
 STRING() {
    size     =   0 ;
    capacity = 128 ;
    memory   = ( T *) malloc( capacity * sizeof(T) ) ;
 }
STRING const & operator=(T * buf);
};
</code>```

And you define a specialization for the type you want

```<code>template<> STRING<achar_t> const & STRING<achar_t>::operator=(achar_t * buf)
{
    strcpy(memory, buf );
    return *this;
}

template<> STRING<wchar_t> const & STRING<wchar_t>::operator=(wchar_t * buf)
{
    wcscpy( memory, buf );
    return *this;
}
</code>```

I didn't test this code but you can find more information here http://en.cppreference.com/w/cpp/language/template_specialization

Body:
Here's a small example that illustrates the essence of my question:

#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

Body:
You can use template specialization.

template<typename T>
class STRING {
public:
 T *    memory   ;
 int    size     ;
 int    capacity ;
public:
 STRING() {
    size     =   0 ;
    capacity = 128 ;
    memory   = ( T *) malloc( capacity * sizeof(T) ) ;
 }
STRING const & operator=(T * buf);
};

And you define a specialization for the type you want

template<> STRING<achar_t> const & STRING<achar_t>::operator=(achar_t * buf)
{
    strcpy(memory, buf );
    return *this;
}

template<> STRING<wchar_t> const & STRING<wchar_t>::operator=(wchar_t * buf)
{
    wcscpy( memory, buf );
    return *this;
}

I didn't test this code but you can find more information here http://en.cppreference.com/w/cpp/language/template_specialization


问:
Why is Popen("cmd.exe echo a", shell=True) not running "echo"?
This leads to a bigger problem I am having here with Popen().

The following does not do what I thought it should:

```<code>x = subprocess.Popen("cmd.exe echo a", stdout=PIPE, shell=True)
print (x.stdout.read())
</code>```

Returns the "title" message of the cmd console, but echo a is never executed.

Same with:

```<code>x = subprocess.Popen(["cmd.exe", "echo a"], stdout=PIPE)
print (x.stdout.read())
</code>```

and

```<code>cmd = "cmd.exe echo a"
x = subprocess.Popen(shlex.split(cmd), stdout=PIPE)
print (x.stdout.read())
</code>```

End result is in open cmd terminal that prints the standard "Microsoft Windows version..." and a CLI position of C:\Python36>.

答:
The command processor cmd.exe is implicit when you specify shell=True.

```<code>>>> x = subprocess.Popen("echo a", stdout=subprocess.PIPE, shell=True)
>>> print (x.stdout.read())
a
</code>```

By invoking it explicitly you fire up a nested command console, as if you had typed cmd.exe at the prompt. Its output doesn't go to Popen()'s pipe.

Body:
This leads to a bigger problem I am having here with Popen().

The following does not do what I thought it should:

x = subprocess.Popen("cmd.exe echo a", stdout=PIPE, shell=True)
print (x.stdout.read())

Returns the "title" message of the cmd console, but echo a is never executed.

Same with:

x = subprocess.Popen(["cmd.exe", "echo a"], stdout=PIPE)
print (x.stdout.read())

and

cmd = "cmd.exe echo a"
x = subprocess.Popen(shlex.split(cmd), stdout=PIPE)
print (x.stdout.read())

End result is in open cmd terminal that prints the standard "Microsoft Windows version..." and a CLI position of C:\Python36>.

Body:
The command processor cmd.exe is implicit when you specify shell=True.

>>> x = subprocess.Popen("echo a", stdout=subprocess.PIPE, shell=True)
>>> print (x.stdout.read())
a

By invoking it explicitly you fire up a nested command console, as if you had typed cmd.exe at the prompt. Its output doesn't go to Popen()'s pipe.


问:
How to merge 2 strings alternately in rails?
I have 2 strings:

```<code>a = "qwer"

b = "asd"

Result = "qawsedr"
</code>```

Same is the length of b is greater than a. show alternate the characters.

What is the best way to do this? Should I use loop?

答:
Sebastián's answer gets the job done, but it's needlessly complex. Here's an alternative:

```<code>def merge_alternately(a, b)
  len = [a.size, b.size].max
  Array.new(len) {|n| [ a[n], b[n] ] }.join
end
merge_alternately("ab", "zsd")
# => "azbsd"
</code>```

The first line gets the size of the longer string. The second line uses the block form of the Array constructor; it yields the indexes from 0 to len-1 to the block, resulting in an array like [["a", "z"], ["b", "s"], [nil, "d"]]. join turns it into a string, conveniently calling to_s on each item, which turns nil into "".

Here's another version that does basically the same thing, but skips the intermediate arrays:

```<code>def merge_alternately(a, b)
  len = [a.size, b.size].max
  len.times.reduce("") {|s, i| s + a[i].to_s + b[i].to_s }
end
</code>```

len.times yields an Enumerator that yields the indexes from 0 to len-1. reduce starts with an empty string s and in each iteration appends the next characters from a and b (or ""—nil.to_s—if a string runs out of characters).

You can see both on repl.it: https://repl.it/I6c8/1

Just for fun, here's a couple more solutions. This one works a lot like Sebastián's solution, but pads the first array of characters with nils if it's shorter than the second:

```<code>def merge_alternately(a, b)
  a, b = a.chars, b.chars
  a[b.size - 1] = nil if a.size < b.size
  a.zip(b).join
end
</code>```

And it wouldn't be a Ruby answer without a little gsub:

```<code>def merge_alternately2(a, b)
  if a.size < b.size
    b.gsub(/./) { a[$`.size].to_s + $& }
  else
    a.gsub(/./) { $& + b[$`.size].to_s }
  end
end
</code>```

See these two on repl.it: https://repl.it/I6c8/2

Body:
I have 2 strings:

a = "qwer"

b = "asd"

Result = "qawsedr"

Same is the length of b is greater than a. show alternate the characters.

What is the best way to do this? Should I use loop?

Body:
Sebastián's answer gets the job done, but it's needlessly complex. Here's an alternative:

def merge_alternately(a, b)
  len = [a.size, b.size].max
  Array.new(len) {|n| [ a[n], b[n] ] }.join
end
merge_alternately("ab", "zsd")
# => "azbsd"

The first line gets the size of the longer string. The second line uses the block form of the Array constructor; it yields the indexes from 0 to len-1 to the block, resulting in an array like [["a", "z"], ["b", "s"], [nil, "d"]]. join turns it into a string, conveniently calling to_s on each item, which turns nil into "".

Here's another version that does basically the same thing, but skips the intermediate arrays:

def merge_alternately(a, b)
  len = [a.size, b.size].max
  len.times.reduce("") {|s, i| s + a[i].to_s + b[i].to_s }
end

len.times yields an Enumerator that yields the indexes from 0 to len-1. reduce starts with an empty string s and in each iteration appends the next characters from a and b (or ""—nil.to_s—if a string runs out of characters).

You can see both on repl.it: https://repl.it/I6c8/1

Just for fun, here's a couple more solutions. This one works a lot like Sebastián's solution, but pads the first array of characters with nils if it's shorter than the second:

def merge_alternately(a, b)
  a, b = a.chars, b.chars
  a[b.size - 1] = nil if a.size < b.size
  a.zip(b).join
end

And it wouldn't be a Ruby answer without a little gsub:

def merge_alternately2(a, b)
  if a.size < b.size
    b.gsub(/./) { a[$`.size].to_s + $& }
  else
    a.gsub(/./) { $& + b[$`.size].to_s }
  end
end

See these two on repl.it: https://repl.it/I6c8/2


问:
What is the Best way to handle a lot of data on a Recycleview
I need to load a long list of data (5000-1000) on a RecycleView, and each items of the RecycleView has many details, so 5 TextView, 1 ImageView and a ProgressBar. All the data are stored on the SQLite DB.
Is it better to load an ArrayList<Object> which contains all the data and them set it to the adapter or is it better to load the data on the adapter?
Please consider I have other thing to do on the adapter like retriving the images (with Glide).
Any suggestion or consideration would be helpful!

Thank you

答:
You can try to show only a portion of the data and use a Recycler View's OnScroll Listener to load and show more when the user has reached the end of the recycler view (basically, a pagination). This way, you won't have to pay the full payload of loading all data at once.

Hope this helps!


问:
Content not updating on changing tabs in viewpager - Tablayout
I am  storing dynamic ids from arraylist to each tabs that are created dynamically and

I have used ViewPagerOnTabSelectedListener , and it is getting id of the tab that is clicked and stores it in a sharedpreference.

I am using that id from sharedpreference  into fragment get the customlist in each tab based on that id.

NOw, the problem is the customlist is not getting refreshed on tab click , but it has already fetched old values , its not getting updated as per the id from the sharedpreference

public class ScrollableTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ConnectionClass connectionClass;
    ArrayList<String> al,idal,pidal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollable_tabs);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        connectionClass = new ConnectionClass();

        al = new ArrayList<String>();
        idal = new ArrayList<String>();
        pidal = new ArrayList<String>();

        ScrollableTabsActivity.DoLogin doLogin = new ScrollableTabsActivity.DoLogin();
        doLogin.execute("");

    }

    private void setupTags() {
        int i;

        for(i=0;i<al.size();i++) {
          /*  Tag t= new Tag();
            t.setId(idal.get(i));
            tabLayout.getTabAt(i).setTag(t);
*/

            tabLayout.getTabAt(i).setTag(idal.get(i));

        }

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager){
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);

             //   CharSequence numTab = ((Tag)tab.getTag()).getId();
                CharSequence numTab = tab.getTag().toString();

                SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor2 = preferences2.edit();

                editor2.putString("tabselected",numTab.toString());
                editor2.putString("Authentication_Status", "true");
                editor2.apply();

            }

        });
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        int i;
        for(i=0;i<al.size();i++){

        adapter.addFrag(new MainActivity(), al.get(i),idal.get(i));

        }
        viewPager.setAdapter(adapter);

    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private final List<String> mFragmentId = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {

                return mFragmentList.get(position);

        }

        @Override
        public int getCount() {
            return mFragmentList.size();

        }

        public void addFrag(Fragment fragment, String title,String id) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
            mFragmentId.add(id);

        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
            case R.id.action_cart:
                cart();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Launching new activity
     * */
    private void cart() {
        Intent i = new Intent(ScrollableTabsActivity.this, Cart.class);
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(500);
        MainActivity m= new MainActivity();
        m.vacatelist();

    }

    public class DoLogin extends AsyncTask<String,String,String>
    {
        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(String r) {

            if(isSuccess) {
                SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor2 = preferences2.edit();

                editor2.putString("tabselected",idal.get(0).toString());
                editor2.putString("Authentication_Status", "true");
                editor2.apply();

                setupViewPager(viewPager);
                tabLayout.setupWithViewPager(viewPager);
                setupTags();

            }
            else {
                Toast.makeText(ScrollableTabsActivity.this,r, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                    z = "Error in connection with SQL server";
                } else {
                    String query = "SELECT ID,Category_ItemName,Pi_Category_ID FROM [dbo].[MainMenuDetail] where Pi_Category_ID=0 and Delete_category=0";
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery(query);
                    while (rs.next())
                    {
                        idal.add(rs.getString("ID"));
                        al.add(rs.getString("Category_ItemName"));
                        pidal.add(rs.getString("Pi_Category_ID"));

                    }
                    z = "Successful";
                    isSuccess=true;
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                z = "Exceptions";
            }

            return z;
        }

    }
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class MainActivity extends android.support.v4.app.Fragment {
 // Log tag

 private static final String TAG = MainActivity.class.getSimpleName();
 ConnectionClass connectionClass;
 // Movies json url
 String url="http://i.imgur.com/mQPXunb.png";
 private List<Movie> movieList = new ArrayList<Movie>();
 private ListView listView;
 private CustomListAdapter adapter;
 private List templist = new ArrayList();
 String image_url = "http://app.dartenogroup.com/admin/img/";
 String image_url2="";
 NetworkImageView img;
 String restid;
 Movie movie;
 String tabselected;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  return inflater.inflate(R.layout.activity_main, container, false);
 }
 @Override
 public void onViewCreated(View view,Bundle savedInstanceState){
  super.onViewCreated(view,savedInstanceState);

  SharedPreferences prfs = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
  restid = prfs.getString("restid", "");

  SharedPreferences prfs2 = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_PRIVATE);
  tabselected = prfs2.getString("tabselected", "");
  Toast.makeText(getActivity(), tabselected, Toast.LENGTH_SHORT).show();

  connectionClass = new ConnectionClass();
  listView = (ListView) view.findViewById(R.id.list);
  adapter = new CustomListAdapter(getActivity(), movieList);
  listView.setAdapter(adapter);

  img = (NetworkImageView) view.findViewById(R.id.thumbnail);

  // changing action bar color
  //getActionBar().setBackgroundDrawable(
  // new ColorDrawable(Color.parseColor("#ffffff")));

  DoLogin  doLogin = new DoLogin();
  doLogin.execute("");

  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Intent i2 = new Intent(getActivity(), ViewProduct.class);
    TextView tv=(TextView)view.findViewById(R.id.itemid);
    i2.putExtra("value",tv.getText().toString());
    startActivity(i2);
   }
  });

 }

 /**
  * On selecting action bar icons
  * */
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // Take appropriate action for each action item click
  switch (item.getItemId()) {
   case R.id.action_cart:
    cart();
    return true;

   default:
    return super.onOptionsItemSelected(item);
  }
 }

 /**
  * Launching new activity
  * */
 private void cart() {
  Intent i = new Intent(getActivity(), Cart.class);
  startActivity(i);
 }

 public class DoLogin extends AsyncTask<String,String,String>
 {
  String z = "";
  Boolean isSuccess = false;

  @Override
  protected void onPreExecute() {
   movieList.clear();
   templist.clear();
  }

  @Override
  protected void onPostExecute(String r) {

   if(isSuccess) {

    updatelist();
    Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(500);
   }
   else{
    Toast.makeText(getActivity(),z,Toast.LENGTH_SHORT).show();
   }
  }

  @Override
  protected String doInBackground(String... params) {

    try {
     Connection con = connectionClass.CONN ();
     if (con == null) {
      z = "Error in connection with SQL server";
     } else {

      String query = "select * from [dbo].[MainMenuDetail] WHERE Delete_category = 0 AND Pi_Category_ID ='"+tabselected+"'" ;
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {

       movie = new Movie();
       movie.setId(rs.getString("ID"));
       movie.setItemname(rs.getString("Category_ItemName"));
       movie.setDescription(rs.getString("Category_SHortDesc"));
       movie.setPrice(rs.getString("Category_Price"));
       image_url2=rs.getString("show_Image");
       String img= image_url+image_url2;
       movie.setThumbnailUrl(img);
       update();
      }
      z = "Successful";
      isSuccess=true;
     }
    }
    catch (Exception ex)
    {
     isSuccess = false;
     z = "Exceptions";
    }

   return z;
  }
 }

 public void updatelist(){
  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    movieList.addAll(templist);
    adapter.notifyDataSetChanged();
   }
  });
 }
 public void refreshlist(){

  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    adapter.notifyDataSetChanged();
   }
  }); }

 public void vacatelist(){
  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    movieList.clear();
   }
  });
 }

 public void update(){
  templist.add(movie);
 }

}</code>```

答:
you can try this

```<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
    CharSequence numTab = tab.getTag().toString();
    SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor editor2 = preferences2.edit();

    editor2.putString("tabselected",numTab.toString());
    editor2.putString("Authentication_Status", "true");
    editor2.apply();

    // super called last
    super.onTabSelected(tab);
}
</code>```

or store ViewPagerAdapter adapter "globally" on top of ScrollableTabsActivity (not only inside setupViewPager method)

```<code>ViewPagerAdapter adapter;

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    //rest of your code
}
</code>```

and then

```<code>@Override
public void onTabSelected(TabLayout.Tab tab) {
    // your current code
    adapter.notifyDataSetChanged(); //ViewPagerAdapter's adapter
}
</code>```

Body:
I am  storing dynamic ids from arraylist to each tabs that are created dynamically and

I have used ViewPagerOnTabSelectedListener , and it is getting id of the tab that is clicked and stores it in a sharedpreference.

I am using that id from sharedpreference  into fragment get the customlist in each tab based on that id.

NOw, the problem is the customlist is not getting refreshed on tab click , but it has already fetched old values , its not getting updated as per the id from the sharedpreference

public class ScrollableTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ConnectionClass connectionClass;
    ArrayList<String> al,idal,pidal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrollable_tabs);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        connectionClass = new ConnectionClass();

        al = new ArrayList<String>();
        idal = new ArrayList<String>();
        pidal = new ArrayList<String>();

        ScrollableTabsActivity.DoLogin doLogin = new ScrollableTabsActivity.DoLogin();
        doLogin.execute("");

    }

    private void setupTags() {
        int i;

        for(i=0;i<al.size();i++) {
          /*  Tag t= new Tag();
            t.setId(idal.get(i));
            tabLayout.getTabAt(i).setTag(t);
*/

            tabLayout.getTabAt(i).setTag(idal.get(i));

        }

        tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager){
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);

             //   CharSequence numTab = ((Tag)tab.getTag()).getId();
                CharSequence numTab = tab.getTag().toString();

                SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor2 = preferences2.edit();

                editor2.putString("tabselected",numTab.toString());
                editor2.putString("Authentication_Status", "true");
                editor2.apply();

            }

        });
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        int i;
        for(i=0;i<al.size();i++){

        adapter.addFrag(new MainActivity(), al.get(i),idal.get(i));

        }
        viewPager.setAdapter(adapter);

    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private final List<String> mFragmentId = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {

                return mFragmentList.get(position);

        }

        @Override
        public int getCount() {
            return mFragmentList.size();

        }

        public void addFrag(Fragment fragment, String title,String id) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
            mFragmentId.add(id);

        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
            case R.id.action_cart:
                cart();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Launching new activity
     * */
    private void cart() {
        Intent i = new Intent(ScrollableTabsActivity.this, Cart.class);
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(500);
        MainActivity m= new MainActivity();
        m.vacatelist();

    }

    public class DoLogin extends AsyncTask<String,String,String>
    {
        String z = "";
        Boolean isSuccess = false;

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(String r) {

            if(isSuccess) {
                SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor2 = preferences2.edit();

                editor2.putString("tabselected",idal.get(0).toString());
                editor2.putString("Authentication_Status", "true");
                editor2.apply();

                setupViewPager(viewPager);
                tabLayout.setupWithViewPager(viewPager);
                setupTags();

            }
            else {
                Toast.makeText(ScrollableTabsActivity.this,r, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                    z = "Error in connection with SQL server";
                } else {
                    String query = "SELECT ID,Category_ItemName,Pi_Category_ID FROM [dbo].[MainMenuDetail] where Pi_Category_ID=0 and Delete_category=0";
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery(query);
                    while (rs.next())
                    {
                        idal.add(rs.getString("ID"));
                        al.add(rs.getString("Category_ItemName"));
                        pidal.add(rs.getString("Pi_Category_ID"));

                    }
                    z = "Successful";
                    isSuccess=true;
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                z = "Exceptions";
            }

            return z;
        }

    }
}

public class MainActivity extends android.support.v4.app.Fragment {
 // Log tag

 private static final String TAG = MainActivity.class.getSimpleName();
 ConnectionClass connectionClass;
 // Movies json url
 String url="http://i.imgur.com/mQPXunb.png";
 private List<Movie> movieList = new ArrayList<Movie>();
 private ListView listView;
 private CustomListAdapter adapter;
 private List templist = new ArrayList();
 String image_url = "http://app.dartenogroup.com/admin/img/";
 String image_url2="";
 NetworkImageView img;
 String restid;
 Movie movie;
 String tabselected;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  return inflater.inflate(R.layout.activity_main, container, false);
 }
 @Override
 public void onViewCreated(View view,Bundle savedInstanceState){
  super.onViewCreated(view,savedInstanceState);

  SharedPreferences prfs = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
  restid = prfs.getString("restid", "");

  SharedPreferences prfs2 = getActivity().getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_PRIVATE);
  tabselected = prfs2.getString("tabselected", "");
  Toast.makeText(getActivity(), tabselected, Toast.LENGTH_SHORT).show();

  connectionClass = new ConnectionClass();
  listView = (ListView) view.findViewById(R.id.list);
  adapter = new CustomListAdapter(getActivity(), movieList);
  listView.setAdapter(adapter);

  img = (NetworkImageView) view.findViewById(R.id.thumbnail);

  // changing action bar color
  //getActionBar().setBackgroundDrawable(
  // new ColorDrawable(Color.parseColor("#ffffff")));

  DoLogin  doLogin = new DoLogin();
  doLogin.execute("");

  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Intent i2 = new Intent(getActivity(), ViewProduct.class);
    TextView tv=(TextView)view.findViewById(R.id.itemid);
    i2.putExtra("value",tv.getText().toString());
    startActivity(i2);
   }
  });

 }

 /**
  * On selecting action bar icons
  * */
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // Take appropriate action for each action item click
  switch (item.getItemId()) {
   case R.id.action_cart:
    cart();
    return true;

   default:
    return super.onOptionsItemSelected(item);
  }
 }

 /**
  * Launching new activity
  * */
 private void cart() {
  Intent i = new Intent(getActivity(), Cart.class);
  startActivity(i);
 }

 public class DoLogin extends AsyncTask<String,String,String>
 {
  String z = "";
  Boolean isSuccess = false;

  @Override
  protected void onPreExecute() {
   movieList.clear();
   templist.clear();
  }

  @Override
  protected void onPostExecute(String r) {

   if(isSuccess) {

    updatelist();
    Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(500);
   }
   else{
    Toast.makeText(getActivity(),z,Toast.LENGTH_SHORT).show();
   }
  }

  @Override
  protected String doInBackground(String... params) {

    try {
     Connection con = connectionClass.CONN ();
     if (con == null) {
      z = "Error in connection with SQL server";
     } else {

      String query = "select * from [dbo].[MainMenuDetail] WHERE Delete_category = 0 AND Pi_Category_ID ='"+tabselected+"'" ;
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {

       movie = new Movie();
       movie.setId(rs.getString("ID"));
       movie.setItemname(rs.getString("Category_ItemName"));
       movie.setDescription(rs.getString("Category_SHortDesc"));
       movie.setPrice(rs.getString("Category_Price"));
       image_url2=rs.getString("show_Image");
       String img= image_url+image_url2;
       movie.setThumbnailUrl(img);
       update();
      }
      z = "Successful";
      isSuccess=true;
     }
    }
    catch (Exception ex)
    {
     isSuccess = false;
     z = "Exceptions";
    }

   return z;
  }
 }

 public void updatelist(){
  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    movieList.addAll(templist);
    adapter.notifyDataSetChanged();
   }
  });
 }
 public void refreshlist(){

  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    adapter.notifyDataSetChanged();
   }
  }); }

 public void vacatelist(){
  new Handler(Looper.getMainLooper()).post(new Runnable() {
   @Override
   public void run() {
    movieList.clear();
   }
  });
 }

 public void update(){
  templist.add(movie);
 }

}

Body:
you can try this

@Override
public void onTabSelected(TabLayout.Tab tab) {
    CharSequence numTab = tab.getTag().toString();
    SharedPreferences preferences2 = getSharedPreferences("AUTHENTICATION_FILE_NAME2", Context.MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor editor2 = preferences2.edit();

    editor2.putString("tabselected",numTab.toString());
    editor2.putString("Authentication_Status", "true");
    editor2.apply();

    // super called last
    super.onTabSelected(tab);
}

or store ViewPagerAdapter adapter "globally" on top of ScrollableTabsActivity (not only inside setupViewPager method)

ViewPagerAdapter adapter;

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    //rest of your code
}

and then

@Override
public void onTabSelected(TabLayout.Tab tab) {
    // your current code
    adapter.notifyDataSetChanged(); //ViewPagerAdapter's adapter
}


问:
Azure AD how to prevent app users from login into azure portal
I am using ADAL to auth mobile app users to my Azure AD and that works fine, but the flip side to the coin is that they can also login to portal.azure.com, how can I prevent that? I don't want users to have access to my azure portal at all, only the apps I grant them access to.</p>

答:
There is a portal setting: Portal.Azure.com > Azure Active Directory > User Settings > Administration portal > Restrict access to Azure AD administration portal (Yes/No).

No lets a non-administrator use this Azure AD administration portal experience to access Azure AD resources that the user has permission to read, or manage resources they own. Yes restricts all non-administrators from accessing any Azure AD data in the administration portal, but does not restrict such access using PowerShell  or another client such as Visual Studio.


问:
Categorical Data - One-hot encoding
I have a large list of strings. Each string is a different example in the training dataset and contains a list of categories, whereby each category is separated by a comma. Eg.

```<code>mesh = ['aligator, dog, cat', 'cat, mouse, aligator', '']
</code>```

Some examples may not belong to any category and so will be represented as an empty string.

I wish to use one-hot encoding to encode these categories for use in machine learning.

How can I do this? I do not have a complete list of categories and there are approximately 5,000 possible categories.

答:
Demo:

```<code>In [64]: from sklearn.feature_extraction.text import CountVectorizer

In [65]: cv = CountVectorizer()

In [66]: X = cv.fit_transform(mesh)

In [67]: X.A
Out[67]:
array([[1, 1, 1, 0],
       [1, 1, 0, 1]], dtype=int64)
</code>```

column names:

```<code>In [68]: cv.get_feature_names()
Out[68]: ['aligator', 'cat', 'dog', 'mouse']
</code>```

We can visualize it using Pandas.SparseDataFrame:

```<code>In [135]: import pandas as pd

In [136]: pd.SparseDataFrame(X, columns=cv.get_feature_names(), default_fill_value=0)
Out[136]:
   aligator  cat  dog  mouse
0         1    1    1      0
1         1    1    0      1
</code>```

Title: Categorical Data - One-hot encoding

Body:
I have a large list of strings. Each string is a different example in the training dataset and contains a list of categories, whereby each category is separated by a comma. Eg.

mesh = ['aligator, dog, cat', 'cat, mouse, aligator', '']

Some examples may not belong to any category and so will be represented as an empty string.

I wish to use one-hot encoding to encode these categories for use in machine learning.

How can I do this? I do not have a complete list of categories and there are approximately 5,000 possible categories.

Body:
Demo:

In [64]: from sklearn.feature_extraction.text import CountVectorizer

In [65]: cv = CountVectorizer()

In [66]: X = cv.fit_transform(mesh)

In [67]: X.A
Out[67]:
array([[1, 1, 1, 0],
       [1, 1, 0, 1]], dtype=int64)

column names:

In [68]: cv.get_feature_names()
Out[68]: ['aligator', 'cat', 'dog', 'mouse']

We can visualize it using Pandas.SparseDataFrame:

In [135]: import pandas as pd

In [136]: pd.SparseDataFrame(X, columns=cv.get_feature_names(), default_fill_value=0)
Out[136]:
   aligator  cat  dog  mouse
0         1    1    1      0
1         1    1    0      1


问:
Windows phone 7, silverlight - How to catch EndpointNotFoundException when calling async web service?
I'm calling a web service from within a Silverlight Windows phone 7 application which works fine if the web service is available. If the web service is unavailable then an unhandled exception is caught but I don't seem able to catch it myself. My attempt is as follows:

```<code>            //Get list of providers from Webservice
        RSAServiceClient proxy = new RSAServiceClient();
        proxy.GetSuppliersCompleted += new System.EventHandler<GetSuppliersCompletedEventArgs>(ProxyGetSuppliersCompleted);
        try
        {
            proxy.GetSuppliersAsync();
        }
        catch (EndpointNotFoundException)
        {
            //TODO: Handle webserice not being available
        }
        catch (Exception)
        {
            throw;
        }
</code>```

But this doesn't catch the exception and obviously GetSuppliersCompleted never get's called so I can't catch it there.

I then thought I may be able to detect it by checking the connection state (proxy.State) but this despite the web service not running returns CommunicationState.Opened.

Any idea's where I can handle this?

Apologies if I've missed something but I have searched and not found a solution.

答:
I have exactly the same problem.
The behaviour is different from Desktop-Silverlight where the exception is handled, to WindowsPhone-Silverlight where connection exceptions are not handled at all.

I created a topic here : http://forums.create.msdn.com/forums/t/69485.aspx

Nobody has any real answer.
Ah, yes, there is a trick : you can manually modify the reference.cs in order to manually catch the exception.... But if you have lot of functions, it becomes a nightmare.

Maybe Microsoft developers didn't test all the connection usecases, and they forget to implement this one (which is a big one).

ContentLicense: CC BY-SA 2.5

Body:
I'm calling a web service from within a Silverlight Windows phone 7 application which works fine if the web service is available. If the web service is unavailable then an unhandled exception is caught but I don't seem able to catch it myself. My attempt is as follows:

            //Get list of providers from Webservice
        RSAServiceClient proxy = new RSAServiceClient();
        proxy.GetSuppliersCompleted += new System.EventHandler<GetSuppliersCompletedEventArgs>(ProxyGetSuppliersCompleted);
        try
        {
            proxy.GetSuppliersAsync();
        }
        catch (EndpointNotFoundException)
        {
            //TODO: Handle webserice not being available
        }
        catch (Exception)
        {
            throw;
        }

But this doesn't catch the exception and obviously GetSuppliersCompleted never get's called so I can't catch it there.

I then thought I may be able to detect it by checking the connection state (proxy.State) but this despite the web service not running returns CommunicationState.Opened.

Any idea's where I can handle this?

Apologies if I've missed something but I have searched and not found a solution.


问:
Neo4j OGM Connect to existing Embeded DB
good day. i have some theoretical question.
i made application that uses neo4j to traverse graphs and make some external calculations on each node. traverse process initiated by external event.
during traverse process nodes properties may change according calculation results.
this made by

```<code>new GraphDatabaseFactory().newEmbeddedDatabase(new File (this.DB_PATH));
GraphDatabaseService.traversalDescription();
</code>```

now i'd like to use neo4j OGM to use domain classes in path extenders code  instead self-made node-wrappers. also i`d like to use domain classes to populate DB with nodes and relations , and change properties of nodes from external source (REST for example).
But i can't find way to get Session or SessionFactory to existing and operational database.
is it possible to  connect to database , created as embedded and conducting some calculations in one module , from another module by BOLT protocol, execute some queries, use OGM features?

答:
The OGM cannot be used from path expanders / traversals (at least not easily).

To use OGM with embedded database you have 2 options

use the standard configuration as described in the reference documentation

set use Components.setDriver to set the driver manually, see e.g. this answer for details

Body:
good day. i have some theoretical question.
i made application that uses neo4j to traverse graphs and make some external calculations on each node. traverse process initiated by external event.
during traverse process nodes properties may change according calculation results.
this made by

new GraphDatabaseFactory().newEmbeddedDatabase(new File (this.DB_PATH));
GraphDatabaseService.traversalDescription();

now i'd like to use neo4j OGM to use domain classes in path extenders code  instead self-made node-wrappers. also i`d like to use domain classes to populate DB with nodes and relations , and change properties of nodes from external source (REST for example).
But i can't find way to get Session or SessionFactory to existing and operational database.
is it possible to  connect to database , created as embedded and conducting some calculations in one module , from another module by BOLT protocol, execute some queries, use OGM features?


答:
We can use tidyverse

```<code>library(dplyr)
df %>%
   group_by(id, type) %>%
   summarise_at(vars(starts_with("C")), mean) %>%
   transmute(avg = mean(Cz, C4, C3))
</code>```

Title: How to average data row-wise over a specific set of columns by two factors

Body:
I have a set of data with 26 columns. I would like to do a row-wise average over all columns starting with a C by id AND type:

dput(head(df,4))
structure(list(P7 = c(0.266687798848186, 0.243782451327742, 0.256932437720159,
0.298861598151174), P4 = c(0.198233672667731, 0.0917952258522064,
0.0911852809187542, 0.0896079263551856), Cz = c(0.236398290801764,
0.0864552727199747, 0.0745517747485495, 0.141094205953345), Pz = c(0.134887167694073,
0.0747942533151883, 0.0955856952160322, 0.0351423350784724),
    P3 = c(0.191077740741983, 0.0671666001582164, 0.15631145309625,
    0.0784718768200876), P8 = c(0.746777191136397, 0.560405877368518,
    0.600967378548292, 0.536464030748274), O1 = c(0.178986458890412,
    0.0630053138978704, 0.0774329882095566, 0.0691776190155007
    ), O2 = c(0.366020592243935, 0.145930065883011, 0.265438304721104,
    0.161825120181983), T8 = c(0.166974498667532, 0.193021656050489,
    0.213308929827665, 0.213890447571556), F8 = c(0.263718560854391,
    0.131907696650378, 0.111178337073373, 0.231875668810878),
    C4 = c(0.269114234615308, 0.125279019411176, 0.0913937842967784,
    0.230858661872378), F4 = c(0.231465667185867, 0.161178083318531,
    0.216487717434052, 0.171471377435883), FP2 = c(0.180752958268289,
    0.226079727116054, 0.284591837287001, 0.0666576126271971),
    Fz = c(0.25772461457411, 0.11393640031093, 0.0915436977625258,
    0.22075971063348), C3 = c(0.251047419087495, 0.116387810932296,
    0.0658483596391047, 0.217611910888088), F3 = c(0.265273001053431,
    0.126774002131214, 0.125733221613179, 0.233189075725804),
    FP1 = c(0.142119646773935, 0.221130756519951, 0.318851412027302,
    0.0888396971594962), T7 = c(0.249976523730528, 0.0650165785671064,
    0.108231023089731, 0.235791252265216), F7 = c(0.244199373827059,
    0.116417055069381, 0.0661299818628654, 0.237627682382219),
    id = c(1L, 1L, 1L, 1L), Time = 1:4, Segment = c(1L, 1L, 1L,
    1L), TimeLower = c(-Inf, -Inf, -Inf, -Inf), TimeUpper = c(180,
    180, 180, 180), Group = structure(c(2L, 2L, 2L, 2L), .Label = c("C",
    "N"), class = "factor"), type = structure(c(1L, 1L, 1L, 1L
    ), .Label = c("alpha", "beta", "gamma", "delta", "theta"), class = c("ordered",
    "factor"))), .Names = c("P7", "P4", "Cz", "Pz", "P3", "P8",
"O1", "O2", "T8", "F8", "C4", "F4", "FP2", "Fz", "C3", "F3",
"FP1", "T7", "F7", "id", "Time", "Segment", "TimeLower", "TimeUpper",
"Group", "type"), row.names = c(NA, 4L), class = "data.frame")

For example I'd like to average in a row-wise fashion all data belonging to columns Cz,C4 and C3 for types=alpha, beta, gamma, delta and theta. And do this by the column id.

Body:
We can use tidyverse

library(dplyr)
df %>%
   group_by(id, type) %>%
   summarise_at(vars(starts_with("C")), mean) %>%
   transmute(avg = mean(Cz, C4, C3))


问:
Ubuntu bash script output correct value - A script calls another script
I have a script that calls another script, but the output from the script seems to be wrong. Below is my code:

print_output.sh

```<code>#!/bin/bash
echo $1
total=$(eval $1 | awk '{sum+=$1} END {print sum}')
echo "Total is $total"
</code>```

try.sh

```<code>#!/bin/bash
./print_output.sh "ssh $1 'cd /somelocation/logs; cat data-$1.txt' | grep ..."

Usuage is: ./try.sh ukdry-01
</code>```

I expect the output to be:

```<code>uk
</code>```

along with the "Total is 11" in this case. But the output is appearing as "cat data.txt".

Where I am going wrong? As I expect the input to be "ukdry-01". The "cat data.txt" is a command that be evaluated (i.e eval $1) from print_output.sh and executed within the script.

data.txt contains for example

```<code>1 AUTH
2 AND
8 BOOLEAN
</code>```

The idea is that the total is printed. The script will ssh to a user inputted to an hostname i.e. ukdry-01, goes to data-ukdry-01.txt through cat and then logs out and performs a grep on the data found. The data is filtered is fed into print_output.sh which are all integers and prints out a total of column one. The usuage has to be the script name i.e. ./try.sh ukdry-01 where internally it calls ./print_output and then the ssh commands etc.

答:
Below is what had worked for me:

```<code>try.sh
#!/bin/bash
./print_output.sh $@ "ssh $1 'cd /somelocation/logs; cat data-$1.txt' | grep ..."

Usuage is: ./try.sh ukdry-01
</code>```

The $@ copies the positional parameters and I can make use of ukdry-01 as $1.

Body:
I have a script that calls another script, but the output from the script seems to be wrong. Below is my code:

print_output.sh

#!/bin/bash
echo $1
total=$(eval $1 | awk '{sum+=$1} END {print sum}')
echo "Total is $total"

try.sh

#!/bin/bash
./print_output.sh "ssh $1 'cd /somelocation/logs; cat data-$1.txt' | grep ..."

Usuage is: ./try.sh ukdry-01

I expect the output to be:

uk

along with the "Total is 11" in this case. But the output is appearing as "cat data.txt".

Where I am going wrong? As I expect the input to be "ukdry-01". The "cat data.txt" is a command that be evaluated (i.e eval $1) from print_output.sh and executed within the script.

data.txt contains for example

1 AUTH
2 AND
8 BOOLEAN

The idea is that the total is printed. The script will ssh to a user inputted to an hostname i.e. ukdry-01, goes to data-ukdry-01.txt through cat and then logs out and performs a grep on the data found. The data is filtered is fed into print_output.sh which are all integers and prints out a total of column one. The usuage has to be the script name i.e. ./try.sh ukdry-01 where internally it calls ./print_output and then the ssh commands etc.

Body:
Below is what had worked for me:

try.sh
#!/bin/bash
./print_output.sh $@ "ssh $1 'cd /somelocation/logs; cat data-$1.txt' | grep ..."

Usuage is: ./try.sh ukdry-01

The $@ copies the positional parameters and I can make use of ukdry-01 as $1.


问:
Remove specific branch commits from the middle of master branch
I have a large number of commits (hundreds) that belong to a specific branch, that was merged to master long time ago (there are new commits after that merge).
Any idea on how do I remove those commits from master?. Not one by one with git-revert as suggested. More like a filter-branch command.
Thank you</p>

答:
Then what you have to do is fairly simple: Identify the revision before the branch you want to remove from history was merged. Check out this revision.... then cherry-pick all revisions following the merge.

Suppose the revision before the merge is revision A, merge revision is B and the branch you are working is called 'someBranch'. Then, you could do this:

```<code>git checkout A
git cherry-pick B..someBranch
</code>```

If you like the results, then you can repoint someBranch to the current revision:

```<code>git branch -f someBranch
git checkout someBranch
</code>```

When you rewrite a branch and other people are working on the "old branch", then there is friction in order to push this new "rewritten" history, so keep that in mind.

Body:
Then what you have to do is fairly simple: Identify the revision before the branch you want to remove from history was merged. Check out this revision.... then cherry-pick all revisions following the merge.

Suppose the revision before the merge is revision A, merge revision is B and the branch you are working is called 'someBranch'. Then, you could do this:

git checkout A
git cherry-pick B..someBranch

If you like the results, then you can repoint someBranch to the current revision:

git branch -f someBranch
git checkout someBranch

When you rewrite a branch and other people are working on the "old branch", then there is friction in order to push this new "rewritten" history, so keep that in mind.


问:
unix command for grand total
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a unix command (no script)

suppose

```<code>7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208
</code>```

assume this is in a file

I want the total of all the values.
thanks in advance

答:
The best one-liner I can come up with is</p>

```<code>awk '{sum += $0} END {print sum}' file
</code>```

Title: unix command for grand total

Body:
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a unix command (no script)

suppose

7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208

assume this is in a file

I want the total of all the values.
thanks in advance

Body:
The best one-liner I can come up with is

awk '{sum += $0} END {print sum}' file


问:
Laravel 5.4 OrderBy through a relationship
I´m triying to order by name through a relationship hasMany. If I order in second foreach, doesn't work, I´m understand that I have to do that on the first foreach but How can I do that?
Maybe I can do that in the Controller but I don´t know how. This is my code:

In the view:

```<code>@foreach($data['tags'] as $tag)
        <tr>

            <td>{!! date('d-m-Y', strtotime($tag->created_at)) !!}</td>

            <td>
                @foreach($tag->langs()->orderBy('name', 'asc')->get() as $tag_lang)
                    @include('panel.partials.list_name', ['value' => $tag_lang, 'route' => 'tags.edit', 'id' => $tag->id, 'name' => $tag_lang->name])
                @endforeach
            </td>
        </tr>
    @endforeach
</code>```

The relationship in Tag:

```<code>public function langs()
{
    return $this->hasMany('App\Models\LangTag');
}
</code>```

The relationship in LangTag:

```<code>public function tag()
{
    return $this->belongsTo('App\Models\Tag');
}
</code>```

The controller:

```<code>public function index()
    {
        $data['tags'] = Tag::paginate(25);
        return view('panel.tags.index', compact('data'));
    }
</code>```

答:
You can eager load it with ordering while you fetch tags. Cleaner solution.</p>

```<code>public function index()
{
    $tags = Tag::with('langs')->paginate(25);

    return view('panel.tags.index', compact('tags'));
}

@foreach($tags as $tag)
<tr>
    <td>{{ $tag->created_at->format('d-m-Y') }}</td>
    <td>
        @foreach($tag->langs->sortBy('name') as $lang)
            @include('panel.partials.list_name', [
                'value' => $lang,
                'route' => 'tags.edit',
                'id' => $tag->id,
                'name' => $lang->name
            ])
        @endforeach
    </td>
</tr>
@endforeach
</code>```

Body:
I´m triying to order by name through a relationship hasMany. If I order in second foreach, doesn't work, I´m understand that I have to do that on the first foreach but How can I do that?
Maybe I can do that in the Controller but I don´t know how. This is my code:

In the view:

@foreach($data['tags'] as $tag)

            {!! date('d-m-Y', strtotime($tag->created_at)) !!}

                @foreach($tag->langs()->orderBy('name', 'asc')->get() as $tag_lang)
                    @include('panel.partials.list_name', ['value' => $tag_lang, 'route' => 'tags.edit', 'id' => $tag->id, 'name' => $tag_lang->name])
                @endforeach

    @endforeach

The relationship in Tag:

public function langs()
{
    return $this->hasMany('App\Models\LangTag');
}

The relationship in LangTag:

public function tag()
{
    return $this->belongsTo('App\Models\Tag');
}

The controller:

public function index()
    {
        $data['tags'] = Tag::paginate(25);
        return view('panel.tags.index', compact('data'));
    }

Body:
You can eager load it with ordering while you fetch tags. Cleaner solution.

public function index()
{
    $tags = Tag::with('langs')->paginate(25);

    return view('panel.tags.index', compact('tags'));
}

@foreach($tags as $tag)
<tr>
    <td>{{ $tag->created_at->format('d-m-Y') }}</td>
    <td>
        @foreach($tag->langs->sortBy('name') as $lang)
            @include('panel.partials.list_name', [
                'value' => $lang,
                'route' => 'tags.edit',
                'id' => $tag->id,
                'name' => $lang->name
            ])
        @endforeach
    </td>
</tr>
@endforeach


问:
Does Appium need Xcode for run automated testing on iOS device?
I'm trying to run automated testing on iOS devices without installing Xcode, but seem like it doesn't work.

So I just want to know that Does Appium really need Xcode for run automated testing on iOS device? and why?

答: Yes you need xcode to run you test on ios. And yes it supports native, hybrid as well as browsers.</p>


问:
html5 canvas loading circle image
I'm trying to create a loading circle from an image in HTML5 canvas.

Here's the result I expect when percentage is at 50%:

here's what I've done after a lot of tests: (the blue stroke is just to see the circle, it'll be removed after)

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = 50;
    var Y       = 50;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle=pattern;
   ctx.fill();
    ctx.strokeStyle = "blue";
    ctx.stroke();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas></canvas></code>```

as you can see, the result here isn't as excepted

What is wrong?

答:
const img = new Image();
img.src = "http://i.imgur.com/HVJBZ1L.png";
img.onload = imageLoaded;
var W,H; // width and height when image ready
const ctx = canvas.getContext("2d");
// define the distance of the progress 0- 100
const min = 0;
const max = 100;
var pattern;
var radius;
// get pattern, radius canvas size from image ans start animation
function imageLoaded(){
    requestAnimationFrame(mainLoop);
    W = this.width;
    H = this.height;
    pattern = ctx.createPattern(this, 'no-repeat');
    radius = W / 2;
    canvas.width  = W;
    canvas.height = H;
}
// draw the background and forground images
// amount is the amount of progress. amount >= min amount <= max
function draw(amount) {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    ctx.fillStyle=pattern;
    ctx.strokeStyle = "blue";
    ctx.beginPath();
    ctx.arc(  // draw inside circle CCW
      W/2,
      H/2,
      radius - 17,
      ((amount - min) / (max-min)) * Math.PI * 2 - Math.PI / 2,
      -Math.PI / 2,
      true
    );
    ctx.arc( // draw outer circle CW
      W/2,
      H/2,
      radius,
      -Math.PI / 2,
      ((amount - min) / (max-min)) * Math.PI * 2 - Math.PI / 2
    );
    ctx.closePath();
   ctx.fill();
    ctx.stroke();
}

// animate the thing.
function mainLoop(time){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    draw((time / 50) % max);

    requestAnimationFrame(mainLoop);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { border : 2px solid black;}</code>```

<canvas id="canvas"></canvas>```

Title: html5 canvas loading circle image

Body:
I'm trying to create a loading circle from an image in HTML5 canvas.

Here's the result I expect when percentage is at 50%:

here's what I've done after a lot of tests: (the blue stroke is just to see the circle, it'll be removed after)

var img = new Image();
img.onload = draw;
img.src = "http://i.imgur.com/HVJBZ1L.png";

var canvas = document.getElementsByTagName("canvas")[0];

canvas.width  = 500;
canvas.height = 500;

var ctx = canvas.getContext("2d");

function draw() {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    var X       = 50;
    var Y       = 50;
    var Radius  = img.width / 2;
    var end     = 40;
    var start   = 0;
    var PI2     = Math.PI * 2;
    var quart   = Math.PI / 2;
    var pct     = 50 / 100;
    var extent  = (end - start) * pct;
    var current = (end - start) / 100 * PI2 * pct - quart;

    var pattern = ctx.createPattern(img, 'no-repeat');

    ctx.beginPath();
    ctx.arc(X, Y, Radius, -quart, current);
    ctx.closePath();
    ctx.fillStyle=pattern;
   ctx.fill();
    ctx.strokeStyle = "blue";
    ctx.stroke();
}

<canvas></canvas>

as you can see, the result here isn't as excepted

What is wrong?

Body:
const img = new Image();
img.src = "http://i.imgur.com/HVJBZ1L.png";
img.onload = imageLoaded;
var W,H; // width and height when image ready
const ctx = canvas.getContext("2d");
// define the distance of the progress 0- 100
const min = 0;
const max = 100;
var pattern;
var radius;
// get pattern, radius canvas size from image ans start animation
function imageLoaded(){
    requestAnimationFrame(mainLoop);
    W = this.width;
    H = this.height;
    pattern = ctx.createPattern(this, 'no-repeat');
    radius = W / 2;
    canvas.width  = W;
    canvas.height = H;
}
// draw the background and forground images
// amount is the amount of progress. amount >= min amount <= max
function draw(amount) {
    ctx.globalAlpha = 0.5
    ctx.drawImage(img, 0, 0);
    ctx.globalAlpha = 1;

    ctx.fillStyle=pattern;
    ctx.strokeStyle = "blue";
    ctx.beginPath();
    ctx.arc(  // draw inside circle CCW
      W/2,
      H/2,
      radius - 17,
      ((amount - min) / (max-min)) * Math.PI * 2 - Math.PI / 2,
      -Math.PI / 2,
      true
    );
    ctx.arc( // draw outer circle CW
      W/2,
      H/2,
      radius,
      -Math.PI / 2,
      ((amount - min) / (max-min)) * Math.PI * 2 - Math.PI / 2
    );
    ctx.closePath();
   ctx.fill();
    ctx.stroke();
}

// animate the thing.
function mainLoop(time){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    draw((time / 50) % max);

    requestAnimationFrame(mainLoop);
}

canvas { border : 2px solid black;}

<canvas id="canvas"></canvas>


问:
Date TIme Filter on Kendo UI for Angular 2
I have been facing trouble implementing datetime filter using Kendo UI for Angular 2. Has anyone been able to work around this issue? If so please do let me know, hopefully with snippet on how to implement the same.

答:
```<code>    <kendo-grid-column field="startTime" title="Started"
        [filter]="'date'"
        format="{0:MM/dd/yyyy HH:mm:ss}">
    </kendo-grid-column>
</code>```


问:
Interleaving array_agg in postgres
I have a postgres query in which I want to interleave my array_agg statements :

```<code>SELECT client_user_id,
       (array_agg(question), array_agg(client_intake_question_id), array_agg(answer)) as answer
FROM client_intake_answer
LEFT OUTER JOIN client_intake_question
ON       client_intake_question.id = client_user_id
GROUP BY client_user_id
</code>```

Gives me the following:

```<code> 5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")
</code>```

I would like the results to be:

```<code>  5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"
</code>```

How do I do this?

答:
To interleave or splice together multiple array_agg's you can do the following: </p>

```<code>SELECT client_user_id,
   array_agg('[' || client_intake_question_id || question || ',' || answer || ']') as answer
FROM client_intake_answer
LEFT OUTER JOIN
client_intake_question ON  client_intake_question.id = client_user_id
GROUP BY client_user_id
</code>```

Title: Interleaving array_agg in postgres

Body:
I have a postgres query in which I want to interleave my array_agg statements :

SELECT client_user_id,
       (array_agg(question), array_agg(client_intake_question_id), array_agg(answer)) as answer
FROM client_intake_answer
LEFT OUTER JOIN client_intake_question
ON       client_intake_question.id = client_user_id
GROUP BY client_user_id

Gives me the following:

 5 | ("{""Have you ever received counselling?"",""Have you ever received counselling or mental health support in the past?""}","{1,2}","{yes,no}")

I would like the results to be:

  5 | ("{""Have you ever received counselling?", 1, "yes"",""Have you ever received counselling or mental health support in the past?", 2, "no""}"

How do I do this?

Body:
To interleave or splice together multiple array_agg's you can do the following:

SELECT client_user_id,
   array_agg('[' || client_intake_question_id || question || ',' || answer || ']') as answer
FROM client_intake_answer
LEFT OUTER JOIN
client_intake_question ON  client_intake_question.id = client_user_id
GROUP BY client_user_id


问:
Oozie validation command throwing Error: One file must be specified
I am trying to use validate method expose by oozie but stuck with error mentioned below.
As per Apache Documentation:
https://oozie.apache.org/docs/3.3.2/DG_CommandLineTool.html#Validating_a_Workflow_XML

oozie validate xx_logger_import/workflow.xml -oozie http://localhost:11000/oozie
Error: One file must be specified

Cloudera CDH-5.8 version is in use.
Oozie Version:

```<code>oozie admin -oozie http://localhost:11000/oozie  -version
Oozie server build version: 4.1.0-cdh5.8.0
</code>```

答:
The workflow xml that you are trying to validate should be the last parameter in your validate command -

Example -
oozie validate -oozie $Oozie_URL /home/abc/workflow.xml

Valid workflow-app

oozie validate   : validate a workflow, coordinator, bundle XML file

```<code>             -auth <arg>    select authentication type [SIMPLE|KERBEROS]
             -oozie <arg>   Oozie URL
</code>```

*

Body:
I am trying to use validate method expose by oozie but stuck with error mentioned below.
As per Apache Documentation:
https://oozie.apache.org/docs/3.3.2/DG_CommandLineTool.html#Validating_a_Workflow_XML

oozie validate xx_logger_import/workflow.xml -oozie http://localhost:11000/oozie
Error: One file must be specified

Cloudera CDH-5.8 version is in use.
Oozie Version:

oozie admin -oozie http://localhost:11000/oozie  -version
Oozie server build version: 4.1.0-cdh5.8.0

Body:
The workflow xml that you are trying to validate should be the last parameter in your validate command -

Example -
oozie validate -oozie $Oozie_URL /home/abc/workflow.xml

Valid workflow-app

oozie validate   : validate a workflow, coordinator, bundle XML file

             -auth <arg>    select authentication type [SIMPLE|KERBEROS]
             -oozie <arg>   Oozie URL

*


问:
Rails 5, How to name two models with an associated table?
Given the following two models:

```<code>ChefPosition (Executive, Sous, etc...)
Skills (Creativity, speed, quality)
</code>```

I'm working to create a table that defines what skills are defined per ChefPosition. So far I have:

```<code>ChefPositionSkill (chef_position_id, skill_id)
</code>```

In the Rails 5 world, am I naming the models correctly? If so, what would be the right way to name a controller that returns the skills per ChefPosition, something like:

```<code>ChefPositionSkillController < ApplicationController

  def index
    @ChefPositionSkills = Skill.where(:chef_position => params[:chef_position_id]
    render json: @ChefPositionSkills, status: status
  end
end
</code>```

Is this right?

答:
The conventions can take a while to get used to, but in general:

You would have the following tables and foreign keys (plural):

```<code>chef_positions
* id
* name
* ...

skills
* id
* name
* ...

chef_position_skills
* id
* chef_position_id
* skill_id
</code>```

Then you could define models for each table with their associations (singular):

```<code>class ChefPosition < ApplicationRecord
  has_many :chef_position_skills
  has_many :skills, through: :chef_position_skills
end

class Skill < ApplicationRecord
  has_many :chef_position_skills
  has_many :chef_positions, through: :chef_position_skills
end

class ChefPositionSkill < ApplicationRecord
  belongs_to :chef_position
  belongs_to :skill
end
</code>```

If you wanted an endpoint to access all of the chef position skills for a given position, you might create a nested route in config/routes.rb:

```<code>resources :chef_positions, only: [] do
  resources :chef_position_skills, only: [:index]
end
</code>```

This would define a route at /chef_positions/:chef_position_id/chef_position_skills.

Then you could create a controller (plural) to find the list of chef position skills given a chef position:

```<code>class ChefPositionSkillsController < ApplicationController
  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given the following two models:

ChefPosition (Executive, Sous, etc...)
Skills (Creativity, speed, quality)

I'm working to create a table that defines what skills are defined per ChefPosition. So far I have:

ChefPositionSkill (chef_position_id, skill_id)

In the Rails 5 world, am I naming the models correctly? If so, what would be the right way to name a controller that returns the skills per ChefPosition, something like:

ChefPositionSkillController < ApplicationController

  def index
    @ChefPositionSkills = Skill.where(:chef_position => params[:chef_position_id]
    render json: @ChefPositionSkills, status: status
  end
end

Is this right?

Body:
The conventions can take a while to get used to, but in general:

You would have the following tables and foreign keys (plural):

chef_positions
* id
* name
* ...

skills
* id
* name
* ...

chef_position_skills
* id
* chef_position_id
* skill_id

Then you could define models for each table with their associations (singular):

class ChefPosition < ApplicationRecord
  has_many :chef_position_skills
  has_many :skills, through: :chef_position_skills
end

class Skill < ApplicationRecord
  has_many :chef_position_skills
  has_many :chef_positions, through: :chef_position_skills
end

class ChefPositionSkill < ApplicationRecord
  belongs_to :chef_position
  belongs_to :skill
end

If you wanted an endpoint to access all of the chef position skills for a given position, you might create a nested route in config/routes.rb:

resources :chef_positions, only: [] do
  resources :chef_position_skills, only: [:index]
end

This would define a route at /chef_positions/:chef_position_id/chef_position_skills.

Then you could create a controller (plural) to find the list of chef position skills given a chef position:

class ChefPositionSkillsController < ApplicationController
  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end
end


问:
Entity Framework Repository Pattern why not return Iqueryable?
There are several good blogs about how to implement the repository pattern together with the unit-of-work pattern using generic classes.

Implementing a Data Access Layer with Entity Framework 6.1

Implementing the Repository and Unit of Work Patterns

The Idea is, to define a generic interface IRepository and a class Repository that hides how the data is actually accessed. It can be accessed using Entity Framework DbContext, or maybe the repository is an in memory collection for unit testing.

```<code>public interface public interface IRepository<T> where T : class
{
    T GetById(int Id);
    void DeleteById(int Id);

    void Add(T entity);
    void Update(T entity);

    etc.
}
</code>```

Quite often I see that several Query functions are added that are similar to Queryable and/or Enumerable functions.

For instance in Implementing a data access layer I see:

```<code>/// Returns an IEnumerable based on the query, order clause and the properties included
/// <param name="query">Link query for filtering.</param>
/// <param name="orderBy">Link query for sorting.</param>
/// <param name="includeProperties">Navigation properties seperated by comma for eager loading.</param>
/// <returns>IEnumerable containing the resulting entity set.</returns>
IEnumerable<T> GetByQuery(Expression<Func<T, bool>> query = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "");

/// <summary>
/// Returns the first matching entity based on the query.
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
T GetFirst(Expression<Func<T, bool>> predicate);
</code>```

If the interface had a function IQueryable GetQuery(), then I wouldn't have to make functions like GetFirst() and GetByQuery().

Question: Why is this not recommended? Can people change the data in an undesirable way?

答:
One of the reasons we use the repository pattern is to encapsulate fat queries. These queries make it hard to read, understand and test actions in ASP.NET MVC controllers. Also, as your application grows, the chances of you repeating a fat query in multiple places increases. With the repository pattern, we encapsulate these queries inside repository classes. The result is slimmer, cleaner, more maintainable and easier-to-test actions. Consider this example:

```<code>var orders = context.Orders
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);
</code>```

Here we are directly using a DbContext without the repository pattern. When your repository methods return IQueryable, someone else is going to get that IQueryable and compose a query on top of it. Here’s the result:

```<code>var orders = repository.GetOrders()
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);
</code>```

Can you see the difference between these two code snippets? The only difference is in the first line. In the first example, we use context.Orders, in the second we use repository.GetOrders(). So, what problem is this repository solving? Nothing!

Your repositories should return domain objects. So, the GetOrders() method should return an IEnumerable. With this, the second example can be re-written as:

```<code>var orders = repository.GetOrders(1234);
</code>```

See the difference?
Retrieved from Mr. Hamedani blog

Body:
There are several good blogs about how to implement the repository pattern together with the unit-of-work pattern using generic classes.

Implementing a Data Access Layer with Entity Framework 6.1

Implementing the Repository and Unit of Work Patterns

The Idea is, to define a generic interface IRepository and a class Repository that hides how the data is actually accessed. It can be accessed using Entity Framework DbContext, or maybe the repository is an in memory collection for unit testing.

public interface public interface IRepository<T> where T : class
{
    T GetById(int Id);
    void DeleteById(int Id);

    void Add(T entity);
    void Update(T entity);

    etc.
}

Quite often I see that several Query functions are added that are similar to Queryable and/or Enumerable functions.

For instance in Implementing a data access layer I see:

/// Returns an IEnumerable based on the query, order clause and the properties included
/// <param name="query">Link query for filtering.</param>
/// <param name="orderBy">Link query for sorting.</param>
/// <param name="includeProperties">Navigation properties seperated by comma for eager loading.</param>
/// <returns>IEnumerable containing the resulting entity set.</returns>
IEnumerable<T> GetByQuery(Expression<Func<T, bool>> query = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "");

///
/// Returns the first matching entity based on the query.
///
/// <param name="predicate"></param>
/// <returns></returns>
T GetFirst(Expression<Func<T, bool>> predicate);

If the interface had a function IQueryable GetQuery(), then I wouldn't have to make functions like GetFirst() and GetByQuery().

Question: Why is this not recommended? Can people change the data in an undesirable way?

Body:
One of the reasons we use the repository pattern is to encapsulate fat queries. These queries make it hard to read, understand and test actions in ASP.NET MVC controllers. Also, as your application grows, the chances of you repeating a fat query in multiple places increases. With the repository pattern, we encapsulate these queries inside repository classes. The result is slimmer, cleaner, more maintainable and easier-to-test actions. Consider this example:

var orders = context.Orders
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);

Here we are directly using a DbContext without the repository pattern. When your repository methods return IQueryable, someone else is going to get that IQueryable and compose a query on top of it. Here’s the result:

var orders = repository.GetOrders()
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);

Can you see the difference between these two code snippets? The only difference is in the first line. In the first example, we use context.Orders, in the second we use repository.GetOrders(). So, what problem is this repository solving? Nothing!

Your repositories should return domain objects. So, the GetOrders() method should return an IEnumerable. With this, the second example can be re-written as:

var orders = repository.GetOrders(1234);

See the difference?
Retrieved from Mr. Hamedani blog


问:
Is it possible to have one thread per gdb instance?
Now I know that gdb enables us to switch between threads executing.

But, but, for greater convenience, I'd like to know if it's possible to have as many terminal emulators open as threads in the application, and have a gdb instance in each of these emulators, each bound to a particular thread?

答:
and have a gdb instance in each of these emulators, each bound to a
  particular thread

You can't attach multiple gdb instances to the same process. This is a limitation of ptrace syscall used by gdb. From man ptrace:

```<code>   EPERM  The specified process cannot be traced.  This could be because
          the tracer has insufficient privileges (the required
          capability is CAP_SYS_PTRACE); unprivileged processes cannot
          trace processes that they cannot send signals to or those
          running set-user-ID/set-group-ID programs, for obvious
          reasons.  Alternatively, the process may already be being
          traced, or (on kernels before 2.6.26) be init(1) (PID 1).
</code>```

Body:
and have a gdb instance in each of these emulators, each bound to a
  particular thread

You can't attach multiple gdb instances to the same process. This is a limitation of ptrace syscall used by gdb. From man ptrace:

   EPERM  The specified process cannot be traced.  This could be because
          the tracer has insufficient privileges (the required
          capability is CAP_SYS_PTRACE); unprivileged processes cannot
          trace processes that they cannot send signals to or those
          running set-user-ID/set-group-ID programs, for obvious
          reasons.  Alternatively, the process may already be being
          traced, or (on kernels before 2.6.26) be init(1) (PID 1).


问:
Java: Strange result after decompiling
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

```<code>public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}
</code>```

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

答: The Java bytecode supports constructs that are not valid in Java source code. Obfuscators exploit that fact by modifying bytecode to use those constructs (while still giving the same result as the un-obfuscated bytecode).</p>

Title: Java: Strange result after decompiling

Body:
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?


问:
SCOPE_IDENTITY when inserting values
I got this error message when trying to execute my ORM program.

NHibernate.Exceptions.GenericADOException: 'could not insert:
  [NHibernateWinFormsApp.Employee][SQL: INSERT INTO Employee DEFAULT
  VALUES; select SCOPE_IDENTITY()]'

This is my mapping file EDIT

```<code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="NHibernateWinFormsApp"
                   namespace="NHibernateWinFormsApp">

  <class name="Employee">
    <id name="EmployeeId" column="EmployeeId">
      <column name="EmployeeId" not-null="true" />
      <column name="FirstName" />
      <column name="LastName" />
      <generator class="native"/>
    </id>

    <bag name="Department" table="EmployeeDepartment" >
      <key column="EmployeeId" not-null="true" />
      <many-to-many class="Department" column="DepartmentId"/>
    </bag>
  </class>

  <class name="Department">
    <id name="DepartmentId">
      <column name="DepartmentId" not-null="true" />
      <column name="DepartmentName" />
      <generator class="native"/>
    </id>

    <bag name="Employee" table="EmployeeDepartment" inverse="true">
      <key column="DepartmentId" not-null="true"/>
      <many-to-many class="Employee" column="EmployeeId"/>
    </bag>
    <property name="DepartmentName" type="string"/>
  </class>

</hibernate-mapping>
</code>```

And, into my session:

```<code>DepartmentRepository departmentRepository = new DepartmentRepository(session);

// get department by id
Department department = departmentRepository.GetById(int.Parse(textDepartment.Text));
employeeData.Department = new List<Department>();
employeeData.Department.Add(department);
department.Employee.Add(employeeData);
</code>```

Does anyone know how to solve this small problem?

答:
It looks like you have not mapped some columns which must have different values between two records. So they are always inserted with null, but you can only have one such employee, causing all other inserts to fail.

Either remove that constraint, or relax it (by replacing it with a filtered unique index ignoring null values), or map those columns to some properties and give them unique values for each employee.

But well, bottom line of your trouble is: always consult all InnerException and their specific properties if any. That is not a NHibernate specific advice, you should do that with all exceptions you encounter.

Title: SCOPE_IDENTITY when inserting values

Body:
I got this error message when trying to execute my ORM program.

NHibernate.Exceptions.GenericADOException: 'could not insert:
  [NHibernateWinFormsApp.Employee][SQL: INSERT INTO Employee DEFAULT
  VALUES; select SCOPE_IDENTITY()]'

This is my mapping file EDIT

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="NHibernateWinFormsApp"
                   namespace="NHibernateWinFormsApp">

  <class name="Employee">
    <id name="EmployeeId" column="EmployeeId">
      <column name="EmployeeId" not-null="true" />
      <column name="FirstName" />
      <column name="LastName" />
      <generator class="native"/>
    </id>

    <bag name="Department" table="EmployeeDepartment" >
      <key column="EmployeeId" not-null="true" />
      <many-to-many class="Department" column="DepartmentId"/>
    </bag>
  </class>

  <class name="Department">
    <id name="DepartmentId">
      <column name="DepartmentId" not-null="true" />
      <column name="DepartmentName" />
      <generator class="native"/>
    </id>

    <bag name="Employee" table="EmployeeDepartment" inverse="true">
      <key column="DepartmentId" not-null="true"/>
      <many-to-many class="Employee" column="EmployeeId"/>
    </bag>
    <property name="DepartmentName" type="string"/>
  </class>

</hibernate-mapping>

And, into my session:

DepartmentRepository departmentRepository = new DepartmentRepository(session);

// get department by id
Department department = departmentRepository.GetById(int.Parse(textDepartment.Text));
employeeData.Department = new List<Department>();
employeeData.Department.Add(department);
department.Employee.Add(employeeData);

Does anyone know how to solve this small problem?


问:
MSI Installer file/folder permissions
I'm trying to install a set of files within the programdata folder using basic MSI installer. As the content of the files are dynamic and generated during the installation process, I'm creating the files in C# code during installation.

The files are created in the appropriate folders, and everything is good, except the files permissions. As I understand, files are supposed to inherit their permissions from the parent folder (if enabled), but in this case, this does not happen. The files I create should be writable for regular users, and i do not wan't to set permissions explicitly for each file created. Could the problem be that the installer runs with different permissions, and therefore the files does not inherit the permissions from their parent folders?

Thanks in advance for any help.

答: I had the very similar problem and I was able to solve it using the example here. </p>

Title: MSI Installer file/folder permissions


问:
Error calling Appregistry.runApplication in react-native
I am trying to run a react-native app on android emulator, but I am getting an error like

Error calling Appregistry.runApplication

AVD: 'Nexus_5X_API_23(AVD) - 6.0
OS:Windows 10

Please help on this?

答:
For me I just needed to add the platform tools to my Path environment variable so that react-native can start the adb server.

I was getting:

```<code>'adb' is not recognized as an internal tool or program
</code>```

To fix this I added the following to my Path environment variable.

```<code>C:\Users\<Username>\AppData\Local\Adnroid\sdk\platform-tools
</code>```

Then running react-native run-android worked!

Body:
For me I just needed to add the platform tools to my Path environment variable so that react-native can start the adb server.

I was getting:

'adb' is not recognized as an internal tool or program

To fix this I added the following to my Path environment variable.

C:\Users\<Username>\AppData\Local\Adnroid\sdk\platform-tools

Then running react-native run-android worked!


问:
json: cannot unmarshal array into Go value of type main.Posts
I'm trying to read a json file with golang but i'm getting this error.
I've checked almost every question about it but still couldnt get it.

Here's the example json file:
https://jsonplaceholder.typicode.com/posts

And my code:

```<code>package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Posts struct {
    Post []struct{
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
    }
}

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    parsed := json.Unmarshal([]byte(content), &posts)

    //fmt.Println(string(content))

    fmt.Println(parsed)

}
</code>```

答:
That JSON is, at its root, an array. You're trying to unmarshal it into an object, which contains, as a field, an array - hence the error that you passed an object when the JSON is an array. You want to pass an array (or slice, really), as in:</p>

```<code>type Post struct {
    UserId int `json:"userId"`
    ID int `json:"id"`
    Title string `json:"title"`
    Body string `json:"body"`
}

//...

var posts []Post
err := json.Unmarshal([]byte(content), &posts)

// Check err, do stuff with posts
</code>```

Body:
I'm trying to read a json file with golang but i'm getting this error.
I've checked almost every question about it but still couldnt get it.

Here's the example json file:
https://jsonplaceholder.typicode.com/posts

And my code:

package main

import (
    "net/http"
    "log"
    "fmt"
    "io/ioutil"
    "encoding/json"
)

type Posts struct {
    Post []struct{
        UserId int `json:"userId"`
        ID int `json:"id"`
        Title string `json:"title"`
        Body string `json:"body"`
    }
}

func main (){
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts")

    if err != nil {
        log.Fatal(err)
    }

    content, _ := ioutil.ReadAll(resp.Body)

    var posts Posts

    parsed := json.Unmarshal([]byte(content), &posts)

    //fmt.Println(string(content))

    fmt.Println(parsed)

}

Body:
That JSON is, at its root, an array. You're trying to unmarshal it into an object, which contains, as a field, an array - hence the error that you passed an object when the JSON is an array. You want to pass an array (or slice, really), as in:

type Post struct {
    UserId int `json:"userId"`
    ID int `json:"id"`
    Title string `json:"title"`
    Body string `json:"body"`
}

//...

var posts []Post
err := json.Unmarshal([]byte(content), &posts)

// Check err, do stuff with posts