问:
How can I open my phone settings with a menu item click in android studio?
I need to open my phone settings by a click of a menu item "Open Device Settings" Here I had tried something, But when I try to run the project,the app crashes when I clicked the menu item, when I checked the Logcat it shows No activity to handle intent. Should I need to create another activity? Even if I create another activity, I don't know how to proceed further. Please help me friends.

MainActivity.java

```<code>import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.androidmenu.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
</code>```

content_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="arun.com.androidmenu.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

menu_main.xml:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="arun.com.androidmenu.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Open Device Settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_exit"
        android:orderInCategory="100"
        android:title="Exit"
        app:showAsAction="never" />
</menu>
</code>```

Here's my coding., I need to open my device settings when I click the Open
Device settings menu item. Please let me know the mistakes what I've done, Thanks.

答:
Use this
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
This would solve your problem.</p>

Body:
I need to open my phone settings by a click of a menu item "Open Device Settings" Here I had tried something, But when I try to run the project,the app crashes when I clicked the menu item, when I checked the Logcat it shows No activity to handle intent. Should I need to create another activity? Even if I create another activity, I don't know how to proceed further. Please help me friends.

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.androidmenu.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="arun.com.androidmenu.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

menu_main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="arun.com.androidmenu.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Open Device Settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_exit"
        android:orderInCategory="100"
        android:title="Exit"
        app:showAsAction="never" />
</menu>

Here's my coding., I need to open my device settings when I click the Open
Device settings menu item. Please let me know the mistakes what I've done, Thanks.


来源: stackexchange

问:
Receiving error message 'Extension host terminated unexpectedly.' in Visual Studio Code
I have been looking around and I haven't found any answers to my issue.

I keep getting this error "Extension host terminated unexpectedly."    and I have tried removing all of my extensions, reinstalling the program, trying different versions of vscode including the insider versions.

The way I get this isssue isn't from trying to use the debugger or trying to use some sort of extension, as I said before I removed all of them and the error keeps on coming back, it's simply from opening the application. I'm not entirely sure how to continue? I have had to use another editor because the error just doesn't go away. I will just have to wait for another update of Visual Studio Code I assume? I've had the issue since tuesday this week, guessing since the latest update.

Above is the error message I get. It is closed by esc but reappears very shortly after, every time.

When I open developer tools, this is what I find in the console.

Running vscode from command prompt with Code.exe --disable-extensions doesn't help.

Visual Studio Code version:   1.16.1

I appreciate any help.

Linking my github issue on Microsoft/vscode as reference

答:
Me too. My failure has no "Code":

Extension host terminated unexpectedly. Code:  null  Signal:  SIGABRT

MessageService.ts

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How can I get an object inside a javascript event handler?
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

```<code>var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}
</code>```

What I expect is:

```<code>this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3
</code>```

But what I get is:

```<code>this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3
</code>```

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

答:
This is one of the tricky things about closure. You are creating those event handlers with a closure over entry. They all have access to that variable, that exact variable. Consequently once those events fire they get only the last value set to entry. You need to break the closure. Here is one way.

```<code>function addClickHandlers() {
  var entries = [{id: 1},{id: 2},{id: 3}];
  var i = entries.length;
  while (i--) {
    var entry = entries[i];
    document.getElementById(entry.id).onclick = getClickHandler(entry);
  }
}

function getClickHandler(entry) {
  return function() {
    console.log("this.id: " + this.id);
    console.log("entry.id: " + entry.id);
  };
}
</code>```

Note: I changed your for loop into a while just because it's the fastest way to loop in javascript when order isn't important and I think it's slick.

Added for completeness

There are some other methods designed to deal with this situation. I find that I use them all the time.

In Ext there is createDelegate

```<code>myhandler.createDelegate(scope, [arguments], [appendArgs]);
</code>```

For javascript 1.8.5 there is Function.prototype.bind

```<code>myhandler.bind(scope, arguments)
</code>```

Writing Function.prototype.bind is pretty easy (lifted from here)

```<code>Function.prototype.bind = function(self, var_args) {
  var thisFunc = this;
  var leftArgs = Array.slice(arguments, 1);
  return function(var_args) {
    var args = leftArgs.concat(Array.slice(arguments, 0));
    return thisFunc.apply(self, args);
  };
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}

What I expect is:

this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3

But what I get is:

this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

Body:
This is one of the tricky things about closure. You are creating those event handlers with a closure over entry. They all have access to that variable, that exact variable. Consequently once those events fire they get only the last value set to entry. You need to break the closure. Here is one way.

function addClickHandlers() {
  var entries = [{id: 1},{id: 2},{id: 3}];
  var i = entries.length;
  while (i--) {
    var entry = entries[i];
    document.getElementById(entry.id).onclick = getClickHandler(entry);
  }
}

function getClickHandler(entry) {
  return function() {
    console.log("this.id: " + this.id);
    console.log("entry.id: " + entry.id);
  };
}

Note: I changed your for loop into a while just because it's the fastest way to loop in javascript when order isn't important and I think it's slick.

Added for completeness

There are some other methods designed to deal with this situation. I find that I use them all the time.

In Ext there is createDelegate

myhandler.createDelegate(scope, [arguments], [appendArgs]);

For javascript 1.8.5 there is Function.prototype.bind

myhandler.bind(scope, arguments)

Writing Function.prototype.bind is pretty easy (lifted from here)

Function.prototype.bind = function(self, var_args) {
  var thisFunc = this;
  var leftArgs = Array.slice(arguments, 1);
  return function(var_args) {
    var args = leftArgs.concat(Array.slice(arguments, 0));
    return thisFunc.apply(self, args);
  };
};


问:
C# Mono NLog Could not load file or assembly When Deployed to Raspberry PI
I have just begun messing with C# on my Raspberry Pi and it seems to be going well. I am developing my C# application on my Arch Linux machine with Monodevelop and scp-ing everything in the bin/Debug/ directory to my Raspberry Pi and then running "mono my.exe". This has worked with some simple applications I have played with but I am having trouble with NLog. The executable runs fine on my development machine but I get this exception on the Raspberry Pi:

```<code>mono NLogTest.exe

Unhandled Exception:
System.TypeInitializationException: The type initializer for 'NLogTest.MainClass' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly or one of its dependencies.
  at NLog.LogFactory.get_Configuration () [0x000aa] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (NLog.LogFactory+LoggerCacheKey cacheKey) [0x0012c] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (System.String name) [0x00011] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogManager.GetCurrentClassLogger () [0x0000a] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLogTest.MainClass..cctor () [0x00000] in <689b8644ac61434f9d79427c3bf696a7>:0
   --- End of inner exception stack trace ---
</code>```

It seems as if NLog can't find the config file but it is in the same directory.

The simple example I am using is:

```<code>using System;
using NLog;
namespace NLogTest
{
    class MainClass
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing NLog");
            logger.Trace("A Trace!!");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");
            Console.Write("DONE LOGGING!");
        }
    }
}
</code>```

and my NLog.config file is pretty simple:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false">
    <targets>
        <target xsi:type="File"
            name="logFile"
            fileName="The.log"
            />
    </targets>
    <rules>
        <logger name="*" writeTo="logFile" minlevel="Info" />
    </rules>
</nlog>
</code>```

The directory on my Raspberry Pi contains the exe, the NLog.config file, and the NLog.dll.

I installed the mono-runtime package from apt on the Raspberry pi. On my development machine, the Monodevelop build options for the project are set to target "Mono/.NET 4.5". I didn't think it would matter that I am developing on an x86 machine and deploying to an ARM-A machine because I thought the mono runtime would handle the architecture differences.

Any help here would be appreciated, thanks.

答:
Think the problem is that NLog was born in the Windows world with case-insensitive filenames. Linux is case sensitive.

You have to specify the path to the nlog.config manually (with the right case):

```<code>LogManager.Configuration = new XmlLoggingConfiguration("path/nlog.config");
</code>```

You have to delay the call to LogManager.GetCurrentClassLogger() until having loaded the configuration manually.

Body:
I have just begun messing with C# on my Raspberry Pi and it seems to be going well. I am developing my C# application on my Arch Linux machine with Monodevelop and scp-ing everything in the bin/Debug/ directory to my Raspberry Pi and then running "mono my.exe". This has worked with some simple applications I have played with but I am having trouble with NLog. The executable runs fine on my development machine but I get this exception on the Raspberry Pi:

mono NLogTest.exe

Unhandled Exception:
System.TypeInitializationException: The type initializer for 'NLogTest.MainClass' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly or one of its dependencies.
  at NLog.LogFactory.get_Configuration () [0x000aa] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (NLog.LogFactory+LoggerCacheKey cacheKey) [0x0012c] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogFactory.GetLogger (System.String name) [0x00011] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLog.LogManager.GetCurrentClassLogger () [0x0000a] in <eb9f75c9ffa040549f1fea1320a5bf6c>:0
  at NLogTest.MainClass..cctor () [0x00000] in <689b8644ac61434f9d79427c3bf696a7>:0
   --- End of inner exception stack trace ---

It seems as if NLog can't find the config file but it is in the same directory.

The simple example I am using is:

using System;
using NLog;
namespace NLogTest
{
    class MainClass
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public static void Main(string[] args)
        {
            Console.WriteLine("Testing NLog");
            logger.Trace("A Trace!!");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");
            Console.Write("DONE LOGGING!");
        }
    }
}

and my NLog.config file is pretty simple:

<?xml version="1.0" encoding="UTF-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false">
    <targets>
        <target xsi:type="File"
            name="logFile"
            fileName="The.log"
            />
    </targets>
    <rules>
        <logger name="*" writeTo="logFile" minlevel="Info" />
    </rules>
</nlog>

The directory on my Raspberry Pi contains the exe, the NLog.config file, and the NLog.dll.

I installed the mono-runtime package from apt on the Raspberry pi. On my development machine, the Monodevelop build options for the project are set to target "Mono/.NET 4.5". I didn't think it would matter that I am developing on an x86 machine and deploying to an ARM-A machine because I thought the mono runtime would handle the architecture differences.

Any help here would be appreciated, thanks.

Body:
Think the problem is that NLog was born in the Windows world with case-insensitive filenames. Linux is case sensitive.

You have to specify the path to the nlog.config manually (with the right case):

LogManager.Configuration = new XmlLoggingConfiguration("path/nlog.config");

You have to delay the call to LogManager.GetCurrentClassLogger() until having loaded the configuration manually.


问:
EmojiCode - Trying to figure out how to download packages
I know you can import packages using

 allegro

but I'm trying to understand this - how to download, what means what, how to import effectively.

```<code> Fatal Error: Could not load package "allegro" dlopen(/usr/local/EmojicodePackages/allegro-v0/allegro.so, 1): Library not loaded: /usr/local/opt/allegro/lib/liballegro.5.2.dylib
Referenced from: /usr/local/EmojicodePackages/allegro-v0/allegro.so
Reason: image not found.
fish: 'emojicode app.emojib' terminated by signal SIGABRT (Abort)
</code>```

答:
Yo, I figured it out and it wasn't another guy figuring it out I did it all myself:

```<code>brew install allegro
</code>```

Right in that command boi.

You GOTTA have that homebrew huh.

Body:
I know you can import packages using

 allegro

but I'm trying to understand this - how to download, what means what, how to import effectively.

 Fatal Error: Could not load package "allegro" dlopen(/usr/local/EmojicodePackages/allegro-v0/allegro.so, 1): Library not loaded: /usr/local/opt/allegro/lib/liballegro.5.2.dylib
Referenced from: /usr/local/EmojicodePackages/allegro-v0/allegro.so
Reason: image not found.
fish: 'emojicode app.emojib' terminated by signal SIGABRT (Abort)

Body:
Yo, I figured it out and it wasn't another guy figuring it out I did it all myself:

brew install allegro

Right in that command boi.

You GOTTA have that homebrew huh.


问:
http://localhost/richmedia/format/?id=Jazz-Cash-HTML-5-Polite-Billboard "want to remove ?id= from URL"
Hi there i am working on SEO friendly URLs here is who my url look alike

http://localhost/richmedia/format/?id=Jazz-Cash-HTML-5-Polite-Billboard

This is the part where i am sending request with get method

```<code>  <form method="GET" action="format/" target="_blank">
                      <button class="btn btn-primary btn-block" type="submit" >Preview</button>

                      <input type="hidden" value="'.$seo_title.'" name="id">
                </form>
</code>```

this is what i write in .htacces file

```<code>    RewriteEngine On
RewriteRule ^creative-zone$ index.php [NC,L]
RewriteRule ^agencies$ agencies.php [NC,L]
RewriteRule ^advertisers$ advertisers.php [NC,L]
RewriteRule ^about-us$ about.php [NC,L]
RewriteRule ^format/?$ format.php?id=$1 [NC,L]
RewriteRule ^(.*)format/([0-9a-zA-Z_-]+)$ format.php?id=$1 [NC,L]
</code>```

i want to remove this "?id="section from my url. Every Thing is working fine But this ?id= need to be fixex. Need Help. Thanks in advance.

答:
You want to make sure the application still handles the parameter correctly but the answer is fairly straight forward:

RewriteRule ^([0-9A-Za-z_-])?$ index.php?yourparam=$1 [NC,L]

In other words, look for a string after the root, then convert that to an id on the server side.

However when generating the links you'll need to address the id= 'thing'

Your links might look like
link to stuff

which would then be converted to

?id=my_foo_bar

Body:
Hi there i am working on SEO friendly URLs here is who my url look alike

http://localhost/richmedia/format/?id=Jazz-Cash-HTML-5-Polite-Billboard

This is the part where i am sending request with get method

  <form method="GET" action="format/" target="_blank">
                      <button class="btn btn-primary btn-block" type="submit" >Preview</button>

                      <input type="hidden" value="'.$seo_title.'" name="id">
                </form>

this is what i write in .htacces file

    RewriteEngine On
RewriteRule ^creative-zone$ index.php [NC,L]
RewriteRule ^agencies$ agencies.php [NC,L]
RewriteRule ^advertisers$ advertisers.php [NC,L]
RewriteRule ^about-us$ about.php [NC,L]
RewriteRule ^format/?$ format.php?id=$1 [NC,L]
RewriteRule ^(.*)format/([0-9a-zA-Z_-]+)$ format.php?id=$1 [NC,L]

i want to remove this "?id="section from my url. Every Thing is working fine But this ?id= need to be fixex. Need Help. Thanks in advance.

Body:
You want to make sure the application still handles the parameter correctly but the answer is fairly straight forward:

RewriteRule ^([0-9A-Za-z_-])?$ index.php?yourparam=$1 [NC,L]

In other words, look for a string after the root, then convert that to an id on the server side.

However when generating the links you'll need to address the id= 'thing'

Your links might look like
<a href="my_foo_bar" title="click to see my foo bar">link to stuff</a>

which would then be converted to

?id=my_foo_bar


问:
div floats to next line
I have a prototype lightbox that will float the second element if the text within it exceeds 28 characters. What am I doing wrong??

This is my current CSS and HTML

// Parent Div
.lightbox-item {
  z-index: 8200;
  top: 50vh;
  left: 50vw;
  width: auto;
  max-height: 650px;
  height: auto;
  display: inline-block;
  background: #fff;
  position: fixed;
}
// First Child div
.lightbox-item .avatarBox {
  height: 155px;
  width: 155px;
  position: relative;
  float: left;
  padding: 0;
  background: green;
}
// Second Child div
.lightbox-item .infoBox {
  padding: 10px 5px 0 0;
  height: auto
  position: relative;
  width: auto;
  float: left;
  background: orange;
}
// Third Child div
.lightbox-item .person-info-wrap {
  width: 100%;
  display: block !important;
  position: relative;
  z-index: 5;
  height: auto;
  clear: left;
}

// Secondary elements nested inside 2nd & 3rd Child div
.lightbox-item .infoBox .gallery-member_fullname{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-member_title{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-member_company{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-company_location{margin: 0 auto;line-height:1em;text-align:left;}

.lightbox-item .person-info {
  padding: 10px 0 25px 0;
  margin: 0 auto;
  background-color: red;
  color: #fff;
  width: auto;
  height: auto;
  min-height: 275px;
}

.lightbox-item .person-info h3 {
  text-transform: uppercase;
  font-size: 1.5em;
  font-weight: 600;
  font-family: "Lato", sans-serif;
  line-height: 30px;
  width: 320px;
  margin: 0 auto;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div class="lightbox-item" style="opacity: 1; transform: matrix(1, 0, 0, 1, -224.5, -226);">
      <div class="avatarBox"></div>
      <div class="infoBox">
        <h2 class="gallery-member_fullname">Bill Gates</h2>
        <div class="gallery-member_title">Founder</div>
        <div class="gallery-member_company">Bill and Melinda Gates Found</div>
        <div class="gallery-company_location">Nashville, TN 28277
          <br>United States</div>
      </div>
      <div class="person-info-wrap" style="opacity: 1;">
        <div class="person-info">
          <h3>Active committees</h3>
          <ul class="subList">
            <li class="subList-item"></li>
          </ul>
        </div>
      </div>
    </div></code>```

I have the first 2 divs floating to the left and then the 3rd element is set to block and clearing left. The result I'm trying to achieve is so that if the text expands in the 2nd child element the parent container ( lightbox-item) should expand as well.

THE REAL ISSUE

Sorry, I don't believe I made my problem clear. The second child element(infoBox) floats to the next line when the viewport size decrease below 768px I believe. The parent element expands as expect if viewport size is greater than ~768px.

答:
You must use CSS Media Query to write a specific CSS for a special size
https://www.w3schools.com/cssref/css3_pr_mediaquery.asp</p>

Title: div floats to next line

Body:
I have a prototype lightbox that will float the second element if the text within it exceeds 28 characters. What am I doing wrong??

This is my current CSS and HTML

// Parent Div
.lightbox-item {
  z-index: 8200;
  top: 50vh;
  left: 50vw;
  width: auto;
  max-height: 650px;
  height: auto;
  display: inline-block;
  background: #fff;
  position: fixed;
}
// First Child div
.lightbox-item .avatarBox {
  height: 155px;
  width: 155px;
  position: relative;
  float: left;
  padding: 0;
  background: green;
}
// Second Child div
.lightbox-item .infoBox {
  padding: 10px 5px 0 0;
  height: auto
  position: relative;
  width: auto;
  float: left;
  background: orange;
}
// Third Child div
.lightbox-item .person-info-wrap {
  width: 100%;
  display: block !important;
  position: relative;
  z-index: 5;
  height: auto;
  clear: left;
}

// Secondary elements nested inside 2nd & 3rd Child div
.lightbox-item .infoBox .gallery-member_fullname{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-member_title{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-member_company{margin: 0 auto;line-height:1em;text-align:left;}
.lightbox-item .infoBox .gallery-company_location{margin: 0 auto;line-height:1em;text-align:left;}

.lightbox-item .person-info {
  padding: 10px 0 25px 0;
  margin: 0 auto;
  background-color: red;
  color: #fff;
  width: auto;
  height: auto;
  min-height: 275px;
}

.lightbox-item .person-info h3 {
  text-transform: uppercase;
  font-size: 1.5em;
  font-weight: 600;
  font-family: "Lato", sans-serif;
  line-height: 30px;
  width: 320px;
  margin: 0 auto;
  text-align: center;
}

Bill Gates

Founder

Bill and Melinda Gates Found

Nashville, TN 28277

United States

Active committees

I have the first 2 divs floating to the left and then the 3rd element is set to block and clearing left. The result I'm trying to achieve is so that if the text expands in the 2nd child element the parent container ( lightbox-item) should expand as well.

THE REAL ISSUE

Sorry, I don't believe I made my problem clear. The second child element(infoBox) floats to the next line when the viewport size decrease below 768px I believe. The parent element expands as expect if viewport size is greater than ~768px.


问:
Laravel 5.5 - Polymorphic relationships
Let's say I have four tables (models) in Laravel:

User.php

```<code>id - integer
name - string
</code>```

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'token_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function embeds()
    {
        return $this->hasManyThrough('App\Post', 'App\Role');
    }
}
</code>```

UserRoles.php

```<code>id - integer
user_id - integer
role_id - integer
</code>```

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserRoles extends Pivot
{
    protected $guarded = [];

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function user()
    {
        return $this->belongsToMany(User::class, 'user_id');
    }
}
</code>```

Role.php

```<code>id - integer
name - string
</code>```

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];

    public function roles()
    {
        return $this->belongsToMany(UserRoles::class);
    }
}
</code>```

Post.php

```<code>id - integer
title - string
body - text
role_id - integer
</code>```

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];
}
</code>```

As you can see, a UserRoles is a pivot table to connect Users with Roles. And Posts can only be associated with one role (tech spec req).

How would make the  relationships in Eloquent make it so I can have a user get every single Post they can see through the Roles they are assigned?

I have revised looking through the Laravel Relationships documentation and I have seen Many-to-Many polymorphic relationships but it seems I keep getting: SQLSTATE[42S02]: Base table or view not found: 1146 Table or some sort.

What am I doing wrong?

答:
Well, a pivot table does need a model. You need four tables and three Models.

You almost got the tables right. Just rename the UserRole table to role_user to follow Laravel convention.

The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

And here is how you should set up the models:

```<code>// User.php

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->hasManyThrough(Post::class, Role::class);
    }

// Role.php

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
</code>```

Title: Laravel 5.5 - Polymorphic relationships

Body:
Let's say I have four tables (models) in Laravel:

User.php

id - integer
name - string

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'token_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function embeds()
    {
        return $this->hasManyThrough('App\Post', 'App\Role');
    }
}

UserRoles.php

id - integer
user_id - integer
role_id - integer

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserRoles extends Pivot
{
    protected $guarded = [];

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function user()
    {
        return $this->belongsToMany(User::class, 'user_id');
    }
}

Role.php

id - integer
name - string

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];

    public function roles()
    {
        return $this->belongsToMany(UserRoles::class);
    }
}

Post.php

id - integer
title - string
body - text
role_id - integer

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Don't auto-apply mass assignment protection.
     *
     * @var array
     */
    protected $guarded = [];
}

As you can see, a UserRoles is a pivot table to connect Users with Roles. And Posts can only be associated with one role (tech spec req).

How would make the  relationships in Eloquent make it so I can have a user get every single Post they can see through the Roles they are assigned?

I have revised looking through the Laravel Relationships documentation and I have seen Many-to-Many polymorphic relationships but it seems I keep getting: SQLSTATE[42S02]: Base table or view not found: 1146 Table or some sort.

What am I doing wrong?

Body:
Well, a pivot table does need a model. You need four tables and three Models.

You almost got the tables right. Just rename the UserRole table to role_user to follow Laravel convention.

The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

And here is how you should set up the models:

// User.php

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function posts()
    {
        return $this->hasManyThrough(Post::class, Role::class);
    }

// Role.php

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }


问:
How to insert a block into a node or template in Drupal 7?
In Drupal 6, it was easy to insert a block into a template with the following code:

```<code>$block = module_invoke('views', 'block', 'view', 'block_name');
print $block['content'];
</code>```

However, using the same instructions in Drupal 7 does not seem to work. I have looked around and cannot find the new method.

Does Drupal 7 have a routine that can allow for programmatically inserting a block into a template or node?

答: Have a look how Drupal does it in _block_render_blocks. The result of that function gets passed to drupal_render.</p>

Body:
In Drupal 6, it was easy to insert a block into a template with the following code:

$block = module_invoke('views', 'block', 'view', 'block_name');
print $block['content'];

However, using the same instructions in Drupal 7 does not seem to work. I have looked around and cannot find the new method.

Does Drupal 7 have a routine that can allow for programmatically inserting a block into a template or node?


问:
Remove Android App Title Bar
I understand that these properties in the manifest:

```<code>android:theme="@android:style/Theme.NoTitleBar"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
</code>```

can remove the title bar.
However, I constantly check the Graphical Layout when I am modifying my app. When I look at the Graphical Layout I still see the title bar. I want to remove the title bar in a way that I don't have to see it during the development of the game.

答:
Just use this</p>

```<code>getSupportActionBar().hide();
</code>```

Title: Remove Android App Title Bar

Body:
I understand that these properties in the manifest:

android:theme="@android:style/Theme.NoTitleBar"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

can remove the title bar.
However, I constantly check the Graphical Layout when I am modifying my app. When I look at the Graphical Layout I still see the title bar. I want to remove the title bar in a way that I don't have to see it during the development of the game.

Body:
Just use this

getSupportActionBar().hide();


问:
How select where left chars in 2 columns equal all cases of 2 columns in 2nd table that equal some value for another column in 2nd table
key_table

```<code>key1    key2    ansr
36  7600    IU-3
36  9500    OPD
01  0100    T3 R
01  0104    T3 L
01  3900    T4 R
03  0202    T3 R
</code>```

base_table

```<code>base1   base2
367123  7600jjkl
01juty  0202qqrr
018723  3900juyt
03ppot  0202qrt
3674t5  9500qqpp
01y756  0100hutt
</code>```

I want to be able to return all rows from base_table where the first 2 chars of base1 and the first 4 chars of base2 equal are together in a row with some answer in key_table.

Thus, a search to match OPD as ansr in key_table would return only the base_table row:

```<code>base1   base2
3674t5  9500qqpp
</code>```

While a search to match T3 R  as ansr in key_table would return the base_table rows:

```<code>base1   base2
01y756  0100hutt
03ppot  0202qrt
</code>```

I tried the following, grimacing as I submitted, without success:

```<code>SELECT *
  FROM `base_table`
 WHERE left(`base1`,2) = key1
   and left(`base2`,4) = key2 in (SELECT `key1`,`key2` FROM `key_table` WHERE `ansr` = 'R-1')
</code>```

I think I can accomplish this with an inner join, but am wondering if there is a way to do this more like my futile attempt above.

答:
Try this:

```<code>SELECT * FROM base_table WHERE
CONCAT(left(base1,2), left(base2,4))
in (SELECT CONCAT(key1, key2) FROM key_table WHERE ansr = 'OPD')
</code>```

Output is:

```<code>3674t5 9500qqpp
</code>```

Body:
key_table

key1    key2    ansr
36  7600    IU-3
36  9500    OPD
01  0100    T3 R
01  0104    T3 L
01  3900    T4 R
03  0202    T3 R

base_table

base1   base2
367123  7600jjkl
01juty  0202qqrr
018723  3900juyt
03ppot  0202qrt
3674t5  9500qqpp
01y756  0100hutt

I want to be able to return all rows from base_table where the first 2 chars of base1 and the first 4 chars of base2 equal are together in a row with some answer in key_table.

Thus, a search to match OPD as ansr in key_table would return only the base_table row:

base1   base2
3674t5  9500qqpp

While a search to match T3 R  as ansr in key_table would return the base_table rows:

base1   base2
01y756  0100hutt
03ppot  0202qrt

I tried the following, grimacing as I submitted, without success:

SELECT *
  FROM `base_table`
 WHERE left(`base1`,2) = key1
   and left(`base2`,4) = key2 in (SELECT `key1`,`key2` FROM `key_table` WHERE `ansr` = 'R-1')

I think I can accomplish this with an inner join, but am wondering if there is a way to do this more like my futile attempt above.

Body:
Try this:

SELECT * FROM base_table WHERE
CONCAT(left(base1,2), left(base2,4))
in (SELECT CONCAT(key1, key2) FROM key_table WHERE ansr = 'OPD')

Output is:

3674t5 9500qqpp


问:
Print the row only if the string does not exist in a specific column taking account each group of strings in other column by UNIX
So, I have the following tabulated file with thousand rows:

```<code>NP_000007.1     ACADM   1457    rs1061337       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000057.1     C8B     1078    rs1013579       117
NP_000057.1     C8B     932     rs856847        345
NP_000057.1     C8B     932     rs856831        not_match
NP_000057.1     C8B     932     rs856841        429
NP_000076.2     CLCNKB  48      rs5251          334
</code>```

I would like to delete those rows for each group of strings grouped in first column if at least appears not_match pattern one time in fifth column. Thus, only the rows grouped by the same string in first column that corresponding to only numbers in fifth column are printed.

The desired output would be:

```<code>NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334
</code>```

I think to do it in some steps separating the rows with "not_match" pattern and the numbers in fifth column and then see if there are coincidences in first column by a hash and discard these coincidences. However I would like to do in one step in the same file. How could I get it in Unix environment? Thanks in advance

Body:
So, I have the following tabulated file with thousand rows:

NP_000007.1     ACADM   1457    rs1061337       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000007.1     ACADM   2761    rs2229249       not_match
NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000057.1     C8B     1078    rs1013579       117
NP_000057.1     C8B     932     rs856847        345
NP_000057.1     C8B     932     rs856831        not_match
NP_000057.1     C8B     932     rs856841        429
NP_000076.2     CLCNKB  48      rs5251          334

I would like to delete those rows for each group of strings grouped in first column if at least appears not_match pattern one time in fifth column. Thus, only the rows grouped by the same string in first column that corresponding to only numbers in fifth column are printed.

The desired output would be:

NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334

I think to do it in some steps separating the rows with "not_match" pattern and the numbers in fifth column and then see if there are coincidences in first column by a hash and discard these coincidences. However I would like to do in one step in the same file. How could I get it in Unix environment? Thanks in advance

Body:
Alternative sort + awk solution:

sort -k1,1 -k5,5r file | awk '!($1 in a){ a[$1]=$5 }a[$1]!="not_match"'

The output:

NP_000019.2     AGL     1094    rs1042090       1398
NP_000019.2     AGL     1094    rs1042090       1395
NP_000076.2     CLCNKB  48      rs5251          334


问:
Prolog: searching if 2 elements in a list occur equally
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

```<code>count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).
</code>```

答:
Here's a more compact version of occurrences/5 with if_/3 and =/3:

```<code>occurrences([],_A,_B,N,N).
occurrences([H|T],A,B,N0,M0) :-
   elem_x_count_(H,A,N1,N0),
   elem_x_count_(H,B,M1,M0),
   occurrences(T,A,B,N1,M1).

elem_x_count_(E,X,New,Old) :-
   if_(E=X, New is Old+1, New=Old).
</code>```

In this version there is only one recursive rule that uses elem_x_count_/4 to increment the corresponding counter arguments if the head of the list matches A and B respectively or to leave them unchanged otherwise. The calling predicates remain unchanged:

```<code>occurrences(List,A,B) :-
   dif(A,B),
   occurrences(List,A,B,0,0).
</code>```

or

```<code>occurrences(List) :-
   occurrences(List,a,b,0,0).
</code>```

This way the predicate succeeds deterministically if all three arguments are ground (no need to press ; after true since there are no choicepoints left open). Here's the example query from the older version with occurrences/3:

```<code>?- occurrences([a,a,b,b],a,b).
true.
</code>```

Another difference is that the number of dif/2 constraints is lower. For example:

```<code>?- occurrences([a,a,b,b,c,c,d],X,Y).
X = a,
Y = b ;
X = a,
Y = c ;
X = b,
Y = a ;
X = c,
Y = a ;
X = b,
Y = c ;
X = c,
Y = b ;
dif(X, d),
dif(X, c),
dif(X, b),
dif(X, a),
dif(X, Y),
dif(Y, d),
dif(Y, c),
dif(Y, b),
dif(Y, a).
</code>```

Only the last solution of this query differs from my previous version. It describes the same result but all the difs that appeared twice in the other version now only appear once. The other example queries yield the same answers.

Body:
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).

Body:
Here's a more compact version of occurrences/5 with if_/3 and =/3:

occurrences([],_A,_B,N,N).
occurrences([H|T],A,B,N0,M0) :-
   elem_x_count_(H,A,N1,N0),
   elem_x_count_(H,B,M1,M0),
   occurrences(T,A,B,N1,M1).

elem_x_count_(E,X,New,Old) :-
   if_(E=X, New is Old+1, New=Old).

In this version there is only one recursive rule that uses elem_x_count_/4 to increment the corresponding counter arguments if the head of the list matches A and B respectively or to leave them unchanged otherwise. The calling predicates remain unchanged:

occurrences(List,A,B) :-
   dif(A,B),
   occurrences(List,A,B,0,0).

or

occurrences(List) :-
   occurrences(List,a,b,0,0).

This way the predicate succeeds deterministically if all three arguments are ground (no need to press ; after true since there are no choicepoints left open). Here's the example query from the older version with occurrences/3:

?- occurrences([a,a,b,b],a,b).
true.

Another difference is that the number of dif/2 constraints is lower. For example:

?- occurrences([a,a,b,b,c,c,d],X,Y).
X = a,
Y = b ;
X = a,
Y = c ;
X = b,
Y = a ;
X = c,
Y = a ;
X = b,
Y = c ;
X = c,
Y = b ;
dif(X, d),
dif(X, c),
dif(X, b),
dif(X, a),
dif(X, Y),
dif(Y, d),
dif(Y, c),
dif(Y, b),
dif(Y, a).

Only the last solution of this query differs from my previous version. It describes the same result but all the difs that appeared twice in the other version now only appear once. The other example queries yield the same answers.


问:
How do I get the width and height of a doc generated with FPDF
How can I get height and width of a document in FPDF.

For example, I've next line:

```<code>$this->Cell(200,5,'ATHLETIC DE COLOMBIA S.A.',1,1,'C',1);
</code>```

But, I want to do something like:

```<code>// $x = width of page
$this->Cell($x,5,'ATHLETIC DE COLOMBIA S.A.',1,1,'C',1);
</code>```

答:
Update: November 2017

Nowadasy, you can simply call GetPageWidth and GetPageHeight methods.

```<code>$pdf = new FPDF();
$pdf->addPage("P", "A4");

$pdf->GetPageWidth();  // Width of Current Page
$pdf->GetPageHeight(); // Height of Current Page
</code>```

Body:
How can I get height and width of a document in FPDF.

For example, I've next line:

$this->Cell(200,5,'ATHLETIC DE COLOMBIA S.A.',1,1,'C',1);

But, I want to do something like:

// $x = width of page
$this->Cell($x,5,'ATHLETIC DE COLOMBIA S.A.',1,1,'C',1);

Body:
Update: November 2017

Nowadasy, you can simply call GetPageWidth and GetPageHeight methods.

$pdf = new FPDF();
$pdf->addPage("P", "A4");

$pdf->GetPageWidth();  // Width of Current Page
$pdf->GetPageHeight(); // Height of Current Page


问:
Combining geometry in opengles
I've been trying to combine all my geometry together and draw them all at once with one call to glDrawElements. However, the only way I've been getting the objects to draw is with a for loop like

```<code>  for (int i = 0; i < TOTAL_NUMBER_OF_INDICES; i += NUMBER_OF_INDICES_PER_OBJECT) {
    glDrawElements(GL_TRIANGLE_STRIP, NUMBER_OF_INDICES_TO_DRAW, GL_UNSIGNED_BYTE, &indices[i]);
  }
</code>```

If I call glDrawElements drawing all the indices at once, OpenGL thinks that it's all one object. From what I've been reading, I think using a VBO may be the solution, but I haven't been successful to do that with OpenGLES 1.1. So if creating a VBO is the solution to my problem, it'd be great if somebody could help with that.

答:
While using a VBO might still be a good idea what you ultimately need to do is trick OpenGL into rendering a single "object" or sequence of vertices so that it displays as a set of discrete elements. The technique for doing this is to add "degenerate triangles" (e.g. triangles that can't be properly rendered like ones whose vertices are co-linear) in between the vertices of the objects that you want to display.

There's a good explanation of it in the answer below if you want more details.

OpenGL: efficient way to render a batch of geometry?

Title: Combining geometry in opengles

Body:
I've been trying to combine all my geometry together and draw them all at once with one call to glDrawElements. However, the only way I've been getting the objects to draw is with a for loop like

  for (int i = 0; i < TOTAL_NUMBER_OF_INDICES; i += NUMBER_OF_INDICES_PER_OBJECT) {
    glDrawElements(GL_TRIANGLE_STRIP, NUMBER_OF_INDICES_TO_DRAW, GL_UNSIGNED_BYTE, &indices[i]);
  }

If I call glDrawElements drawing all the indices at once, OpenGL thinks that it's all one object. From what I've been reading, I think using a VBO may be the solution, but I haven't been successful to do that with OpenGLES 1.1. So if creating a VBO is the solution to my problem, it'd be great if somebody could help with that.


问:
Javascript addEventListener function call
Can anyone please tell me how can I make the function strikeText work? I get this error in browser inspect.

Uncaught ReferenceError: newButton is not defined
      at HTMLButtonElement.strikeText (todo.js:29)

PS: The inline function works but if I want to make a separate function it is not working.

HTML

```<code><!DOCUMENT html>
<html>

<head>
   <title>To Do List</title>
</head>

<body>
   <form id="myForm">
      <input type="text" id="inputId" value="">
      <button type="button" id="submitButton">Add</button>
      <ul id="list">
         <li>
            <button type="button">Do that</button>
         </li>
         <li>
            <button type="button">Do this</button>
         </li>
      </ul>
   </form>
   <script src="todo.js">
   </script>
</body>

</html>
</code>```

JavaScript

```<code>var submitB = document.getElementById("submitButton");
var striked = false;
submitB.addEventListener("click", addLi);

function addLi() {
    var input = document.getElementById("inputId").value;
    var newButton = document.createElement("button");
    var ulList = document.getElementById("list");
    var newLi = document.createElement("li");
    var newText = document.createTextNode(input);
    newButton.appendChild(newText);
    newButton.addEventListener("click", strikeText);
    newButton.setAttribute("type", "button");
    newLi.appendChild(newButton);
    ulList.appendChild(newLi);
    var reset = document.getElementById("myForm").reset();
}

function strikeText() {
    striked = !striked;
    switch (striked) {
        case true:
            newButton.style.textDecoration = "line-through";
            break;
        case false:
            newButton.style.textDecoration = "none";
            break;
    }
}
</code>```

答:
Its working here with the snippet as below.. so only possible reason will be where you javascript code is make sure its executed after load and accessed after DOM is ready

var submitB = document.getElementById("submitButton");
var striked=false;

submitB.addEventListener("click", addLi);

function addLi() {
  var input = document.getElementById("inputId").value;
  var newButton = document.createElement("button");
  var ulList = document.getElementById("list");
  var newLi = document.createElement("li");
  var newText = document.createTextNode(input);

  newButton.appendChild(newText);
  newButton.addEventListener("click",strikeText);
  newButton.setAttribute("type", "button");

  newLi.appendChild(newButton);
  ulList.appendChild(newLi);
  var reset = document.getElementById("myForm").reset();
}

function strikeText(){

  striked=!striked;
  switch(striked){
    case true:
    newButton.style.textDecoration="line-through";
    break;
    case false:
    newButton.style.textDecoration="none";
    break;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCUMENT html>
<html>

<head>

    <title>To Do List</title>

</head>

<body>

    <form id="myForm">
        <input type="text" id="inputId" value="">
        <button type="button" id="submitButton">Add</button>
        <ul id="list">
            <li><button type="button">Do that</button></li>
            <li><button type="button">Do this</button></li>
        </ul>
    </form>

    <script src="todo.js">

    </script>

</body>

</html></code>```

Body:
Can anyone please tell me how can I make the function strikeText work? I get this error in browser inspect.

Uncaught ReferenceError: newButton is not defined
      at HTMLButtonElement.strikeText (todo.js:29)

PS: The inline function works but if I want to make a separate function it is not working.

HTML

<!DOCUMENT html>

   <title>To Do List</title>

   <form id="myForm">
      <input type="text" id="inputId" value="">
      <button type="button" id="submitButton">Add</button>

            <button type="button">Do that</button>

            <button type="button">Do this</button>

   </form>

JavaScript

var submitB = document.getElementById("submitButton");
var striked = false;
submitB.addEventListener("click", addLi);

function addLi() {
    var input = document.getElementById("inputId").value;
    var newButton = document.createElement("button");
    var ulList = document.getElementById("list");
    var newLi = document.createElement("li");
    var newText = document.createTextNode(input);
    newButton.appendChild(newText);
    newButton.addEventListener("click", strikeText);
    newButton.setAttribute("type", "button");
    newLi.appendChild(newButton);
    ulList.appendChild(newLi);
    var reset = document.getElementById("myForm").reset();
}

function strikeText() {
    striked = !striked;
    switch (striked) {
        case true:
            newButton.style.textDecoration = "line-through";
            break;
        case false:
            newButton.style.textDecoration = "none";
            break;
    }
}

Body:
Its working here with the snippet as below.. so only possible reason will be where you javascript code is make sure its executed after load and accessed after DOM is ready

var submitB = document.getElementById("submitButton");
var striked=false;

submitB.addEventListener("click", addLi);

function addLi() {
  var input = document.getElementById("inputId").value;
  var newButton = document.createElement("button");
  var ulList = document.getElementById("list");
  var newLi = document.createElement("li");
  var newText = document.createTextNode(input);

  newButton.appendChild(newText);
  newButton.addEventListener("click",strikeText);
  newButton.setAttribute("type", "button");

  newLi.appendChild(newButton);
  ulList.appendChild(newLi);
  var reset = document.getElementById("myForm").reset();
}

function strikeText(){

  striked=!striked;
  switch(striked){
    case true:
    newButton.style.textDecoration="line-through";
    break;
    case false:
    newButton.style.textDecoration="none";
    break;
  }
}

<!DOCUMENT html>
<html>

<head>

    <title>To Do List</title>

</head>

<body>

    <form id="myForm">
        <input type="text" id="inputId" value="">
        <button type="button" id="submitButton">Add</button>
        <ul id="list">
            <li><button type="button">Do that</button></li>
            <li><button type="button">Do this</button></li>
        </ul>
    </form>

    <script src="todo.js">

    </script>

</body>

</html>


问:
Azure Function Nuget Cache restore failing with "The user name or password is incorrect."
I have an Azure Function I deploy as a part of an ARM template. This Azure Function references a few external .NET DLLs. I have added the reference to these DLLs in the project.json file:

project.json:

```<code>{
    "frameworks": {
        "net46": {
            "dependencies": {
                "Microsoft.IdentityModel.Clients.ActiveDirectory":"3.13.8",
                "Newtonsoft.Json":  "10.0.2",
                 "Microsoft.CrmSdk.CoreAssemblies" : "8.2.0.2"
            }
        }
    }
 }
</code>```

When I click run, the Nuget Cache restore is kicked off. It fails with "The user name or password is incorrect."

The strange thing is the Nuget Packages are being copied to the Functions Nuget cache correctly, but the project.lock.json file is failing to be created. It appears the username / password error is thrown after the Nuget cache restore completes and when Azure tries to write the project.lock.json file. The compile then fails as the project.lock.json file is not created.

```<code>2017-11-14T21:06:34.892 Restoring packages.
2017-11-14T21:06:34.892 Starting NuGet restore
2017-11-14T21:06:36.239 Function started (Id=1340feea-174d-4bee-97f2-e06afc2e2d6e)
2017-11-14T21:06:36.239 Package references have been updated.
2017-11-14T21:06:36.239 Restoring packages.
2017-11-14T21:06:36.239 Starting NuGet restore
2017-11-14T21:06:36.955 Restoring packages for D:\home\site\wwwroot\ProvisionUserToCRM\project.json...
2017-11-14T21:06:37.456 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/index.json
2017-11-14T21:06:37.486 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/3.13.8/microsoft.identitymodel.clients.activedirectory.3.13.8.nupkg
2017-11-14T21:06:37.705 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json
2017-11-14T21:06:37.705 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
2017-11-14T21:06:37.800 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/index.json
2017-11-14T21:06:37.800 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/8.2.0.2/microsoft.crmsdk.coreassemblies.8.2.0.2.nupkg
2017-11-14T21:06:37.881 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/index.json
2017-11-14T21:06:37.881 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/6.1.7600.16394/microsoft.identitymodel.6.1.7600.16394.nupkg
2017-11-14T21:06:38.002 Installing Microsoft.IdentityModel 6.1.7600.16394.
2017-11-14T21:06:38.362 Installing Microsoft.CrmSdk.CoreAssemblies 8.2.0.2.
2017-11-14T21:06:38.939 Restoring packages for D:\home\site\wwwroot\ProvisionUserToCRM\project.json...
2017-11-14T21:06:39.113 Installing Newtonsoft.Json 10.0.2.
2017-11-14T21:06:39.255 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/index.json
2017-11-14T21:06:39.284 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/3.13.8/microsoft.identitymodel.clients.activedirectory.3.13.8.nupkg
2017-11-14T21:06:39.455 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json
2017-11-14T21:06:39.455 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
2017-11-14T21:06:39.470 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/index.json
2017-11-14T21:06:39.470 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/8.2.0.2/microsoft.crmsdk.coreassemblies.8.2.0.2.nupkg
2017-11-14T21:06:39.490 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/index.json
2017-11-14T21:06:39.502 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/6.1.7600.16394/microsoft.identitymodel.6.1.7600.16394.nupkg
2017-11-14T21:06:39.642 Installing Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8.
2017-11-14T21:06:41.211 Installing Microsoft.IdentityModel 6.1.7600.16394.
2017-11-14T21:06:42.367 Installing Microsoft.CrmSdk.CoreAssemblies 8.2.0.2.
2017-11-14T21:06:46.398 Installing Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8.
2017-11-14T21:06:49.197 Installing Newtonsoft.Json 10.0.2.
2017-11-14T21:06:52.171 The user name or password is incorrect.
2017-11-14T21:06:52.189
2017-11-14T21:06:52.189
2017-11-14T21:06:52.189 Packages restored.
2017-11-14T21:06:52.500 Script for function 'ProvisionUserToCRM' changed. Reloading.
2017-11-14T21:06:52.813 run.csx(2,18): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
2017-11-14T21:06:52.813 run.csx(3,8): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
</code>```

Does anyone know why this error is displayed? It seems to come intermittently for me. Seems like a bug in Azure Functions. Are there any known work arounds?

I found enabling 'Slots' preview feature on Azure Functions actually resolves this issue, but 'Slots' will not work for me as they are not compatible with Azure Logic Apps.

答:
Looks like Microsoft has confirmed this is a bug in Azure Functions
https://github.com/Azure/Azure-Functions/issues/590

The only work around I am aware of is to:

enable slots feature

keep re deploying your ARM template until it works

(I did not verify this) but I suspect it would work if you manually generated and dropped the lock file to the Functions file system. You could generate the lock file locally with visual studio. I suspect this would work because from what I observed is the NuGet packages seem to be restored correctly, and the error comes during the write of the JSON file. The compiler must reference the lock file rather than the actual NuGet cache when trying to compile (hence why the error is coming even though the DLL actually exists).

Body:
I have an Azure Function I deploy as a part of an ARM template. This Azure Function references a few external .NET DLLs. I have added the reference to these DLLs in the project.json file:

project.json:

{
    "frameworks": {
        "net46": {
            "dependencies": {
                "Microsoft.IdentityModel.Clients.ActiveDirectory":"3.13.8",
                "Newtonsoft.Json":  "10.0.2",
                 "Microsoft.CrmSdk.CoreAssemblies" : "8.2.0.2"
            }
        }
    }
 }

When I click run, the Nuget Cache restore is kicked off. It fails with "The user name or password is incorrect."

The strange thing is the Nuget Packages are being copied to the Functions Nuget cache correctly, but the project.lock.json file is failing to be created. It appears the username / password error is thrown after the Nuget cache restore completes and when Azure tries to write the project.lock.json file. The compile then fails as the project.lock.json file is not created.

2017-11-14T21:06:34.892 Restoring packages.
2017-11-14T21:06:34.892 Starting NuGet restore
2017-11-14T21:06:36.239 Function started (Id=1340feea-174d-4bee-97f2-e06afc2e2d6e)
2017-11-14T21:06:36.239 Package references have been updated.
2017-11-14T21:06:36.239 Restoring packages.
2017-11-14T21:06:36.239 Starting NuGet restore
2017-11-14T21:06:36.955 Restoring packages for D:\home\site\wwwroot\ProvisionUserToCRM\project.json...
2017-11-14T21:06:37.456 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/index.json
2017-11-14T21:06:37.486 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/3.13.8/microsoft.identitymodel.clients.activedirectory.3.13.8.nupkg
2017-11-14T21:06:37.705 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json
2017-11-14T21:06:37.705 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
2017-11-14T21:06:37.800 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/index.json
2017-11-14T21:06:37.800 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/8.2.0.2/microsoft.crmsdk.coreassemblies.8.2.0.2.nupkg
2017-11-14T21:06:37.881 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/index.json
2017-11-14T21:06:37.881 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/6.1.7600.16394/microsoft.identitymodel.6.1.7600.16394.nupkg
2017-11-14T21:06:38.002 Installing Microsoft.IdentityModel 6.1.7600.16394.
2017-11-14T21:06:38.362 Installing Microsoft.CrmSdk.CoreAssemblies 8.2.0.2.
2017-11-14T21:06:38.939 Restoring packages for D:\home\site\wwwroot\ProvisionUserToCRM\project.json...
2017-11-14T21:06:39.113 Installing Newtonsoft.Json 10.0.2.
2017-11-14T21:06:39.255 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/index.json
2017-11-14T21:06:39.284 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel.clients.activedirectory/3.13.8/microsoft.identitymodel.clients.activedirectory.3.13.8.nupkg
2017-11-14T21:06:39.455 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/index.json
2017-11-14T21:06:39.455 CACHE https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
2017-11-14T21:06:39.470 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/index.json
2017-11-14T21:06:39.470 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.crmsdk.coreassemblies/8.2.0.2/microsoft.crmsdk.coreassemblies.8.2.0.2.nupkg
2017-11-14T21:06:39.490 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/index.json
2017-11-14T21:06:39.502 CACHE https://api.nuget.org/v3-flatcontainer/microsoft.identitymodel/6.1.7600.16394/microsoft.identitymodel.6.1.7600.16394.nupkg
2017-11-14T21:06:39.642 Installing Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8.
2017-11-14T21:06:41.211 Installing Microsoft.IdentityModel 6.1.7600.16394.
2017-11-14T21:06:42.367 Installing Microsoft.CrmSdk.CoreAssemblies 8.2.0.2.
2017-11-14T21:06:46.398 Installing Microsoft.IdentityModel.Clients.ActiveDirectory 3.13.8.
2017-11-14T21:06:49.197 Installing Newtonsoft.Json 10.0.2.
2017-11-14T21:06:52.171 The user name or password is incorrect.
2017-11-14T21:06:52.189
2017-11-14T21:06:52.189
2017-11-14T21:06:52.189 Packages restored.
2017-11-14T21:06:52.500 Script for function 'ProvisionUserToCRM' changed. Reloading.
2017-11-14T21:06:52.813 run.csx(2,18): error CS0234: The type or namespace name 'IdentityModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
2017-11-14T21:06:52.813 run.csx(3,8): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)

Does anyone know why this error is displayed? It seems to come intermittently for me. Seems like a bug in Azure Functions. Are there any known work arounds?

I found enabling 'Slots' preview feature on Azure Functions actually resolves this issue, but 'Slots' will not work for me as they are not compatible with Azure Logic Apps.


问:
Insert new line after any amount of numeric characters
I need to insert a new line, or delimiter, in a text file after a "numeric" string consisting of 10 numbers, then a "-", then either 1 to 4 numbers...

Example:

```<code>randomtext,1234567890-1234blahblah
</code>```

Should be:

```<code>randomtext,1234567890-1234, blahblah
</code>```

Or:

```<code>randomtext,1234567890-1234
blahblah
</code>```

Note that the set of numbers will always be 10 characters, the numbers after the - will either 1,2,3 or 4 characters.

I've used sed a lot for similar tasks, but can't find a way to work with the last set of numbers which vary from 1 to 4 characters....

I really hope someone can help!

Many thanks!

Body:
I need to insert a new line, or delimiter, in a text file after a "numeric" string consisting of 10 numbers, then a "-", then either 1 to 4 numbers...

Example:

randomtext,1234567890-1234blahblah

Should be:

randomtext,1234567890-1234, blahblah

Or:

randomtext,1234567890-1234
blahblah

Note that the set of numbers will always be 10 characters, the numbers after the - will either 1,2,3 or 4 characters.

I've used sed a lot for similar tasks, but can't find a way to work with the last set of numbers which vary from 1 to 4 characters....

I really hope someone can help!

Many thanks!

Body:
$ echo randomtext,1234567890-1234blahblah |
  sed -E 's/[0-9]{10}+-[0-9]{1,4}/&\n/'

randomtext,1234567890-1234
blahblah


问:
let UITableView animate selection if user-initiated
I have a tableView with allowsMultipleSelection set to true. In a custom UITableViewCell subclass, I have overwritten setSelected:animated. This gets called when I select cells (by tapping), and also when I scroll, as cells are being reused. Now, I would expect that the use case of the animated parameter is so that selection can be animated for user interaction, and not be animated when the state simply changes due to cell reuse. However, animated is always passed as false, regardless of how this gets called. Is animated ever true when this is invoked by UIKit stuff?

Of course, I can explicitly distinguish between user interaction and cell reuse by (a) removing allowsMultipleSelection, (b) implementing UITableViewDelegate's didSelect and didDeselect methods, and (c) calling setSelected with animated: true from both those methods. But that seems like duplicating a lot of native behaviour just to change a small detail; I could save a delegate implementation and let my code read more intuitively (at least to me) if I could somehow get the tableView to pass animated: true by default when selection or deselection is user-initiated. Is there any way to make tableViews do this?

EDIT: not to mention, explicitly calling setSelected from the didSelect and didDeselect delegate methods doesn't really work, because it is still also called by the tableView.

答:
I´m assuming you are selecting the cell with

```<code>cell.isSelected = true
</code>```

The selection affects the appearance of labels, image, and background. When the selected state of a cell is set to true, it draws the background for selected cells with its title in white. The default value is false. If you set the selection state to true through this property, the transition to the new state appearance is not animated. For animated selected-state transitions, see the setSelected(_:animated:) method.

As you can see using isSelected has the animated transition with false by default.

Try this instead:

```<code>cell.setSelected(true, animated: true)
</code>```

Documentation

Body:
I´m assuming you are selecting the cell with

cell.isSelected = true

The selection affects the appearance of labels, image, and background. When the selected state of a cell is set to true, it draws the background for selected cells with its title in white. The default value is false. If you set the selection state to true through this property, the transition to the new state appearance is not animated. For animated selected-state transitions, see the setSelected(_:animated:) method.

As you can see using isSelected has the animated transition with false by default.

Try this instead:

cell.setSelected(true, animated: true)

Documentation


问:
Sizing problem with WPF's grid layout
Here's my problem. I have three controls in a row (they capture people's names). The controls themselves size themselves to an appropriate size. I want to space these three controls horizontally to be evenly spaced along the line. This bit is easy:

```<code><Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition />
  </Grid.RowDefinitions>
  <Border Grid.Row="0" Grid.Column="0" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="1" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="2" BorderThickness="2" Height="50" Width="50" />
</Grid>
</code>```

The problem comes when I want to hide the second entry. If I set its visibility to collapsed, I would want the two remaining items to be equally spaced. This does not happen, the middle column remains at 1/3 of the grid's width.

I have tried various combinations of grids and stackpanels but cannot find a way around this. I am trying to find a fairly generic solution as this situation may arise again.

Visually, it should look like:

```<code>   +----------------------------------------------+
   | +------------+ +------------+ +------------+ |
   | |aardvark    | |beatle      | |cat         | |
   | +------------+ +------------+ +------------+ |
   +----------------------------------------------+
</code>```

Note that the inner boxes use the width=* to size them to 1/3 but the controls inside the boxes are not stretched.

答:
Do you still get the same problem if you change all 3 :

<ColumnDefinition Width="Auto" />

For Reference:
http://msdn.microsoft.com/en-us/library/system.windows.controls.columndefinition.width%28VS.96%29.aspx

Title: Sizing problem with WPF's grid layout

Body:
Here's my problem. I have three controls in a row (they capture people's names). The controls themselves size themselves to an appropriate size. I want to space these three controls horizontally to be evenly spaced along the line. This bit is easy:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition />
  </Grid.RowDefinitions>
  <Border Grid.Row="0" Grid.Column="0" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="1" BorderThickness="2" Height="50" Width="50" />
  <Border Grid.Row="0" Grid.Column="2" BorderThickness="2" Height="50" Width="50" />
</Grid>

The problem comes when I want to hide the second entry. If I set its visibility to collapsed, I would want the two remaining items to be equally spaced. This does not happen, the middle column remains at 1/3 of the grid's width.

I have tried various combinations of grids and stackpanels but cannot find a way around this. I am trying to find a fairly generic solution as this situation may arise again.

Visually, it should look like:

   +----------------------------------------------+
   | +------------+ +------------+ +------------+ |
   | |aardvark    | |beatle      | |cat         | |
   | +------------+ +------------+ +------------+ |
   +----------------------------------------------+

Note that the inner boxes use the width=* to size them to 1/3 but the controls inside the boxes are not stretched.


问:
How to update/change schemaExtension owner app
Is there a way to update schemaExtension owner?

E.g. when someone deletes the app that created schemaExtension and schemaExtension is orphaned.

答:
From the documentation:

The appId of the application that is the owner of the schema extension. This property can be supplied on creation, to set the owner.  If not supplied, then the calling application's appId will be set as the owner. In either case, the signed-in user must be the owner of the application. Once set, this property is read-only and cannot be changed.


答:
As jmargolisvt said, the newButton is an unknown variable in your strikeText function. Solution: use 'this' instead:

```<code>case true:
this.style.textDecoration="line-through";
break;
case false:
this.style.textDecoration="none";
break;
</code>```

Also, what worked in my case was using the strikeText parameter:

```<code>function strikeText(event){
  striked=!striked;
  switch(striked){
    case true:
    event.target.style.textDecoration="line-through";
    break;
    case false:
    event.target.style.textDecoration="none";
    break;
  }
}
</code>```

Title: Javascript addEventListener function call

Body:
As jmargolisvt said, the newButton is an unknown variable in your strikeText function. Solution: use 'this' instead:

case true:
this.style.textDecoration="line-through";
break;
case false:
this.style.textDecoration="none";
break;

Also, what worked in my case was using the strikeText parameter:

function strikeText(event){
  striked=!striked;
  switch(striked){
    case true:
    event.target.style.textDecoration="line-through";
    break;
    case false:
    event.target.style.textDecoration="none";
    break;
  }
}


问:
Force LiveData Observer inside a Fragment to receive a change after coming visible again?
I am implementing Android Architecture Components. Imagine a case like the following where your Fragment is observing a LiveData to change its UI. User minimizes the app and the state is changed (in my case from the repository). So the Observer from the Fragment is not triggered with a change because the Fragment is not visible. But then, when the user comes back to the app it doesn't trigger the new state. If the state is changed again (while the Fragment is visible), the Observer receives the change. Do you know any way to force an update when fragment is visible again?

```<code>override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    vm = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
    vm.getStatus()?.observe(this, Observer<MyRepository.Status> { status ->
        if (status != null) {
            when (status) {
                NONE -> setNoneUI()
                LOADING -> setLoadingUI()
                CONTENT -> setContentUI()
                ERROR -> setErrorUI()
            }
        }
    })
}
</code>```

答:
Actually your activity should receive the latest state from LiveData when it is visible again, as explained in this video and described here:

Always up to date data: If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the
  background receives the latest data right after it returns to the
  foreground.

I just tested it in my own application, works as described. So there must be another error in your application: Do you set the LiveData correctly from your repository class? Maybe a different thread / postValue problem?

Body:
I am implementing Android Architecture Components. Imagine a case like the following where your Fragment is observing a LiveData to change its UI. User minimizes the app and the state is changed (in my case from the repository). So the Observer from the Fragment is not triggered with a change because the Fragment is not visible. But then, when the user comes back to the app it doesn't trigger the new state. If the state is changed again (while the Fragment is visible), the Observer receives the change. Do you know any way to force an update when fragment is visible again?

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    vm = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)
    vm.getStatus()?.observe(this, Observer<MyRepository.Status> { status ->
        if (status != null) {
            when (status) {
                NONE -> setNoneUI()
                LOADING -> setLoadingUI()
                CONTENT -> setContentUI()
                ERROR -> setErrorUI()
            }
        }
    })
}


问:
NVD - JSON to CSV with Python
I am trying to download the NVD CVE. Here is my pythoncode:

```<code>import requests
import re

r = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED')
for filename in re.findall("nvdcve-1.0-[0-9]*\.json\.zip",r.text):
    print(filename)
    r_file = requests.get("https://static.nvd.nist.gov/feeds/json/cve/1.0/" + filename, stream=True)
    with open("nvd/" + filename, 'wb') as f:
        for chunk in r_file:
            f.write(chunk)
</code>```

Now I want to write all JSON-files ina  csv-file with this format:

```<code>Name, Value, Description, ..., ...
Name, Value, Description, ..., ...
</code>```

Can somebody help me?

答:
The following should get you started, giving you two columns, ID,VendorName,DescriptionandVendorValues`:

```<code>import requests
import re
import zipfile
import io
import json
import csv

with open("nvdcve-1.0-2017.json") as f_json:
r = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED')

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['ID', 'VendorName', 'Description', 'VersionValues'])

    for filename in re.findall("nvdcve-1.0-[0-9]*\.json\.zip", r.text):
        print("Downloading {}".format(filename))
        r_zip_file = requests.get("https://static.nvd.nist.gov/feeds/json/cve/1.0/" + filename, stream=True)
        zip_file_bytes = io.BytesIO()

        for chunk in r_zip_file:
            zip_file_bytes.write(chunk)

        zip_file = zipfile.ZipFile(zip_file_bytes)

        for json_filename in zip_file.namelist():
            print("Extracting {}".format(json_filename))
            json_raw = zip_file.read(json_filename).decode('utf-8')
            json_data = json.loads(json_raw)

            for entry in json_data['CVE_Items']:
                try:
                    vendor_name = entry['cve']['affects']['vendor']['vendor_data'][0]['vendor_name']
                except IndexError:
                    vendor_name = "unknown"

                try:
                    url = entry['cve']['references']['reference_data'][0]['url']
                except IndexError:
                    url = ''

                try:
                    vv = []

                    for pd in entry['cve']['affects']['vendor']['vendor_data'][0]['product']['product_data']:
                        for vd in pd['version']['version_data']:
                            vv.append(vd['version_value'])

                    version_values = '/'.join(vv)
                except IndexError:
                    version_values = ''

                csv_output.writerow([
                    entry['cve']['CVE_data_meta']['ID'],
                    url,
                    vendor_name,
                    entry['cve']['description']['description_data'][0]['value'],
                    version_values])
</code>```

This downloads the zipfile into memory. It then extracts all files one at a time into memory and converts the json into a Python datas structure using json.loads(). For each entry in CVE_Items it then extracts a couple of the fields and writes them to a CSV file.

As the JSON data is highly structured, you will need to consider how you would want to represent all of the fields in a CSV file. Currently it extras two "useful" fields and stores those.

Alternatively instead of making your own CSV you could work with Pandas:

```<code>df = pd.read_json(json_raw)
df.to_csv(f_output)
</code>```

Remove the csv_output lines. This though would need some extra work to decide on how it should be formatted.

Title: NVD - JSON to CSV with Python

Body:
I am trying to download the NVD CVE. Here is my pythoncode:

import requests
import re

r = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED')
for filename in re.findall("nvdcve-1.0-[0-9]*\.json\.zip",r.text):
    print(filename)
    r_file = requests.get("https://static.nvd.nist.gov/feeds/json/cve/1.0/" + filename, stream=True)
    with open("nvd/" + filename, 'wb') as f:
        for chunk in r_file:
            f.write(chunk)

Now I want to write all JSON-files ina  csv-file with this format:

Name, Value, Description, ..., ...
Name, Value, Description, ..., ...

Can somebody help me?

Body:
The following should get you started, giving you two columns, ID,VendorName,DescriptionandVendorValues`:

import requests
import re
import zipfile
import io
import json
import csv

with open("nvdcve-1.0-2017.json") as f_json:
r = requests.get('https://nvd.nist.gov/vuln/data-feeds#JSON_FEED')

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['ID', 'VendorName', 'Description', 'VersionValues'])

    for filename in re.findall("nvdcve-1.0-[0-9]*\.json\.zip", r.text):
        print("Downloading {}".format(filename))
        r_zip_file = requests.get("https://static.nvd.nist.gov/feeds/json/cve/1.0/" + filename, stream=True)
        zip_file_bytes = io.BytesIO()

        for chunk in r_zip_file:
            zip_file_bytes.write(chunk)

        zip_file = zipfile.ZipFile(zip_file_bytes)

        for json_filename in zip_file.namelist():
            print("Extracting {}".format(json_filename))
            json_raw = zip_file.read(json_filename).decode('utf-8')
            json_data = json.loads(json_raw)

            for entry in json_data['CVE_Items']:
                try:
                    vendor_name = entry['cve']['affects']['vendor']['vendor_data'][0]['vendor_name']
                except IndexError:
                    vendor_name = "unknown"

                try:
                    url = entry['cve']['references']['reference_data'][0]['url']
                except IndexError:
                    url = ''

                try:
                    vv = []

                    for pd in entry['cve']['affects']['vendor']['vendor_data'][0]['product']['product_data']:
                        for vd in pd['version']['version_data']:
                            vv.append(vd['version_value'])

                    version_values = '/'.join(vv)
                except IndexError:
                    version_values = ''

                csv_output.writerow([
                    entry['cve']['CVE_data_meta']['ID'],
                    url,
                    vendor_name,
                    entry['cve']['description']['description_data'][0]['value'],
                    version_values])

This downloads the zipfile into memory. It then extracts all files one at a time into memory and converts the json into a Python datas structure using json.loads(). For each entry in CVE_Items it then extracts a couple of the fields and writes them to a CSV file.

As the JSON data is highly structured, you will need to consider how you would want to represent all of the fields in a CSV file. Currently it extras two "useful" fields and stores those.

Alternatively instead of making your own CSV you could work with Pandas:

df = pd.read_json(json_raw)
df.to_csv(f_output)

Remove the csv_output lines. This though would need some extra work to decide on how it should be formatted.


问:
The anti-forgery token could not be decrypted
I have a form:

```<code>@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()...
</code>```

and action:

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl, string City)
{
}
</code>```

occasionally (once a week), I get the error:

The anti-forgery token could not be decrypted. If this application is
  hosted by a Web Farm or cluster, ensure that all machines are running
  the same version of ASP.NET Web Pages and that the configuration
  specifies explicit encryption and validation keys. AutoGenerate cannot
  be used in a cluster.

i try add to webconfig:

```<code><machineKey validationKey="AutoGenerate,IsolateApps"
    decryptionKey="AutoGenerate,IsolateApps" />
</code>```

but the error still appears occasionally

I noticed this error occurs, for example when a person came from one computer and then trying another computer

Or sometimes an auto value set with incorrect data type like bool to integer to the form field by any jQuery code please also check it.

答: I get this error when the page is old ('stale').  A refresh of the token via a page reload resolves my problem.  There seems to be some timeout period.</p>

Body:
I have a form:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()...

and action:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl, string City)
{
}

occasionally (once a week), I get the error:

The anti-forgery token could not be decrypted. If this application is
  hosted by a Web Farm or cluster, ensure that all machines are running
  the same version of ASP.NET Web Pages and that the configuration
  specifies explicit encryption and validation keys. AutoGenerate cannot
  be used in a cluster.

i try add to webconfig:

<machineKey validationKey="AutoGenerate,IsolateApps"
    decryptionKey="AutoGenerate,IsolateApps" />

but the error still appears occasionally

I noticed this error occurs, for example when a person came from one computer and then trying another computer

Or sometimes an auto value set with incorrect data type like bool to integer to the form field by any jQuery code please also check it.


问:
Jenkins retore NuGet packages in MAC OS
I do not know how to restore NuGet packages from my Xamarin forms solution on a MacOS machine as it does not run .exe. how to make? Could a step by step be possible?

Execute Shell:

nuget /Users/Shared/Jenkins/Downloads/NuGet.exe restore MyProject.sln
  /Users/Shared/Jenkins/tmp/jenkins8846835388185628663.sh: line 2:
  nuget: command not found

答:
Execute Shell:

```<code>/Library/Frameworks/Mono.framework/Versions/5.4.1/bin/nuget restore MyProject.sln
</code>```

I entered the path to my nuget which in the case was this down with the restore command and the solution name. Worked perfectly.

Title: Jenkins retore NuGet packages in MAC OS

Body:
Execute Shell:

/Library/Frameworks/Mono.framework/Versions/5.4.1/bin/nuget restore MyProject.sln

I entered the path to my nuget which in the case was this down with the restore command and the solution name. Worked perfectly.


问:
Move gcloud image from container registry to compute
I've pushed a docker image to gcloud container registry.

I want to create a new compute instance, in the same project, using the image in the container registry.

Ideally gcloud compute images list would show images in my project's container registry.  Is this possible?

Thanks.

答: Does gcloud container images list not suit your needs?