问:
Node.JS HTTPS issue TypeError: Cannot read property 'writeQueueSize' of null
I have a Node.JS HTTPS server and I'm getting randomly the following error

```<code>net.js:729
  if (req.async && this._handle.writeQueueSize != 0)
                               ^

TypeError: Cannot read property 'writeQueueSize' of null
    at TLSSocket.Socket._writeGeneric (net.js:729:32)
    at TLSSocket.Socket._writev (net.js:737:8)
    at doWrite (_stream_writable.js:327:12)
    at clearBuffer (_stream_writable.js:416:5)
    at onwrite (_stream_writable.js:368:7)
    at WriteWrap.afterWrite [as oncomplete] (net.js:824:12)
Worker 33233 died -> 33245 born.
</code>```

I'm using multidomain in the HTTPS, but there isn't a special trigger for this issue, I just see it in the logs randomly.

```<code>try {
    var options = {
        SNICallback: function (domain, cb) {
            if (!secureContext[domain]) {
                domain = 'default';
            }
            cb(null, tls.createSecureContext(secureContext[domain]));
        },
        key: secureContext['default'].key,
        cert: secureContext['default'].cert,
    };
    global.serverHTTPS = https.createServer(options, app);
} catch (err){
    console.error(err.message);
    console.error(err.stack);
}

global.serverHTTPS.on('connection', onConnection);
global.serverHTTPS.on('error', onError);

global.serverHTTPS.listen(global.config.httpsPort);
</code>```

答:
I have recently fixed the same bug. Issue was caused by destroying net.Socket in tls.Server instance. So if you need to destroy a secure connection you should listen secureConnection event.

```<code>try {
    var options = {
        SNICallback: function (domain, cb) {
            if (!secureContext[domain]) {
                domain = 'default';
            }
            cb(null, tls.createSecureContext(secureContext[domain]));
        },
        key: secureContext['default'].key,
        cert: secureContext['default'].cert,
    };
    global.serverHTTPS = https.createServer(options, app);
} catch (err){
   console.error(err.message);
   console.error(err.stack);
}

global.serverHTTPS.on('secureConnection', onConnection);
global.serverHTTPS.on('error', onError);

global.serverHTTPS.listen(global.config.httpsPort);
</code>```

Body:
I have a Node.JS HTTPS server and I'm getting randomly the following error

net.js:729
  if (req.async && this._handle.writeQueueSize != 0)
                               ^

TypeError: Cannot read property 'writeQueueSize' of null
    at TLSSocket.Socket._writeGeneric (net.js:729:32)
    at TLSSocket.Socket._writev (net.js:737:8)
    at doWrite (_stream_writable.js:327:12)
    at clearBuffer (_stream_writable.js:416:5)
    at onwrite (_stream_writable.js:368:7)
    at WriteWrap.afterWrite [as oncomplete] (net.js:824:12)
Worker 33233 died -> 33245 born.

I'm using multidomain in the HTTPS, but there isn't a special trigger for this issue, I just see it in the logs randomly.

try {
    var options = {
        SNICallback: function (domain, cb) {
            if (!secureContext[domain]) {
                domain = 'default';
            }
            cb(null, tls.createSecureContext(secureContext[domain]));
        },
        key: secureContext['default'].key,
        cert: secureContext['default'].cert,
    };
    global.serverHTTPS = https.createServer(options, app);
} catch (err){
    console.error(err.message);
    console.error(err.stack);
}

global.serverHTTPS.on('connection', onConnection);
global.serverHTTPS.on('error', onError);

global.serverHTTPS.listen(global.config.httpsPort);

Body:
I have recently fixed the same bug. Issue was caused by destroying net.Socket in tls.Server instance. So if you need to destroy a secure connection you should listen secureConnection event.

try {
    var options = {
        SNICallback: function (domain, cb) {
            if (!secureContext[domain]) {
                domain = 'default';
            }
            cb(null, tls.createSecureContext(secureContext[domain]));
        },
        key: secureContext['default'].key,
        cert: secureContext['default'].cert,
    };
    global.serverHTTPS = https.createServer(options, app);
} catch (err){
   console.error(err.message);
   console.error(err.stack);
}

global.serverHTTPS.on('secureConnection', onConnection);
global.serverHTTPS.on('error', onError);

global.serverHTTPS.listen(global.config.httpsPort);


来源: stackexchange

问:
copy pointer values *a = *b in golang
```<code>type T struct {
    Id int
    Name string
}

func Copy(a *T, b *T) error {
    b.Id=5
    b.Name="gert"
    a = b
    return nil
}
</code>```

a is still empty, I have to do it like this

```<code>func Copy(a *T, b *T) error {
    b.Id = 5
    b.Name = "gert"
    a.Id = b.Id
    a.Name = b.Name
    return nil
}
</code>```

now a is the same as b

Why and how can I copy *b to *a directly?

答:
This is wrong.It does not work</p>

```<code>func (r *Request) WithContext(ctx context.Context) *Request {
  if ctx == nil {
    panic("nil context")
  }
  r2 := new(Request)
  *r2 = *r
  r2.ctx = ctx
  return r2
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: copy pointer values *a = *b in golang

Body:
type T struct {
    Id int
    Name string
}

func Copy(a *T, b *T) error {
    b.Id=5
    b.Name="gert"
    a = b
    return nil
}

a is still empty, I have to do it like this

func Copy(a *T, b *T) error {
    b.Id = 5
    b.Name = "gert"
    a.Id = b.Id
    a.Name = b.Name
    return nil
}

now a is the same as b

Why and how can I copy *b to *a directly?

Body:
This is wrong.It does not work

func (r *Request) WithContext(ctx context.Context) *Request {
  if ctx == nil {
    panic("nil context")
  }
  r2 := new(Request)
  *r2 = *r
  r2.ctx = ctx
  return r2
}


问:
Viewing SYS schema tables of JBoss EDS/Teiid VDB
Can someone help me understand how to expose the SYS schema objects of a JBoss Teiid Virtual Database when connected via an ODBC-JDBC bridge ?

The client is connecting to ODBC side of the bridge and the JDBC side of it is connecting to the Virtual Database (VDB) running on the JBoss SOA server.

With the current setting only the tables and columns modeled thru the JBoss Studio's Teiid Designer are exposed but not the SYS schema and its underlying objects. Client App is Microstrategy BI application.

答: You are able to traverse all metadata from all used data sources using native JDBC JAVA API. </p>


问:
How to run asp.net mvc 4.5 in visual studio code editor?
I am looking forward to run asp.net mvc apps in vscode but it seems that the only pages that I found on google is with asp.net core which is not what I am looking. Can someone guide me with some steps, I installed some plugins like c# and msbuild. After attempt to run it. it display the following error:

"Failed to launch external program msbuild . spawn msbuild ENOENT"

答:
I've created a gulpfile that handle the build for me:

It starts an IISExpress instance.

Refresh my browser on razor code change.

And automatically rebuild my application when I change C# code.

You can find the gulpfile on my project's Github


问:
Load Xamarin Forms page from android notification
I am trying to load a Xamarin Forms page from an Android Notification. I am really lost on the android side of this, and most of my code has been pieced together from tutorials and blog posts. However nothing really seems to cover exactly this scenario.

I have implemented a very simple interface with dependency service to create the notification with an intent...

```<code>[assembly: Xamarin.Forms.Dependency(typeof(QuoteNotification))]

namespace QuoteApp.Droid
{

    class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true)

                     .SetContentTitle(title)
                     .SetContentText(message)
                     .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }
}
</code>```

this calls an activity -

```<code>namespace QuoteApp.Droid
{
    [Activity(Label = "QuoteApp", MainLauncher = true)]
    class DroidToForms : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            StartActivity(typeof(XFPostPage));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());

        }
    }
}
</code>```

which in turn calls this forms page, all the code here has been in Xamarin.Android project

```<code>namespace QuoteApp.Droid
{

        /// <summary>
        /// This is a Xamarin.Forms screen. It MUST:
        /// * inherit from ANdroidActivity
        /// * call Forms.Init()
        /// * use LoadApplication()
        /// </summary>
        [Activity(Label = "XFPostPage", MainLauncher = true) ]
        public class XFPostPage : Xamarin.Forms.Platform.Android.FormsApplicationActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                Xamarin.Forms.Forms.Init(this, bundle);

            //LoadApplication( new App() ); //how do i send to PostPage.xaml ??

            Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        }
    }
</code>```

this gives the following error in logcat

```<code>07-04 17:51:44.494  7668  7668 E AndroidRuntime: Caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at QuoteApp.Droid.XFPostPage.OnCreate (Android.OS.Bundle bundle) [0x00016] in <ab64801c0fb24acb8457c1d1202cc143>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x0000f] in <d855bac285f44dda8a0d8510b679b1e2>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at (wrapper dynamic-method) System.Object:2780fa42-5931-40d3-8d14-a642f1a3025c (intptr,intptr,intptr)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.n_onCreate(Native Method)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.onCreate(XFPostPage.java:29)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6237)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:5417)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        ... 3 more
</code>```

I have tried a bunch of different ideas all with different runtime errors, my understanding of the Xamarin.Android workings are very limited. eventually i will be using the notification with AlarmManager and further information will be sent to PostPage.Xaml. At the moment i'm just lost at exactly where this is going wrong though?!

Any Help would be hugely appreciated, thanks in advance.

答:
I ended up using OnNewIntent in MainActivity.

there is some excellent information here Processing notifications in Xamarin Forms Android

My Code ended up looking like this.

Call the dependency service to get the android implmentation

```<code>DependencyService.Get<IQuoteNotification>().Notify("words",SelectedQuote.FixedTitle  , SelectedQuote.Id);
</code>```

Which builds notification with the Intent:

```<code>  class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message, int postIndex)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(MainActivity));
            LoadPostPage.PutExtra("NotificationTrue", true);
            LoadPostPage.PutExtra("PostID", postIndex);
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                    .SetContentIntent(pendingIntent)
                    .SetAutoCancel(true)
                    .SetContentTitle(title)
                    .SetContentText(message)
                    .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }
</code>```

then Override OnNewIntent in MainActivity. If the intent is not Built by my QuoteNotification class then send -1 as PostID

```<code>        protected override void OnNewIntent(Intent intent)
    {
        if (intent.HasExtra("NotificationTrue")){
            LoadApplication(new App(intent.GetIntExtra("PostID", -1)));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        base.OnNewIntent(intent);
    }
</code>```

Then in App.Xaml.cs add some logic to navigate to the correct page

```<code>public partial class App : Application
{
    public App(int PostId = -1)
    {
        InitializeComponent();

        if (PostId >= 0)
        {
            MainPage = new NavigationPage(new PostPage(PostId));
        }
        else
            MainPage = new NavigationPage(new MainPage());
</code>```

Body:
I am trying to load a Xamarin Forms page from an Android Notification. I am really lost on the android side of this, and most of my code has been pieced together from tutorials and blog posts. However nothing really seems to cover exactly this scenario.

I have implemented a very simple interface with dependency service to create the notification with an intent...

[assembly: Xamarin.Forms.Dependency(typeof(QuoteNotification))]

namespace QuoteApp.Droid
{

    class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(DroidToForms));
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                .SetContentIntent(pendingIntent)
                .SetAutoCancel(true)

                     .SetContentTitle(title)
                     .SetContentText(message)
                     .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }
}

this calls an activity -

namespace QuoteApp.Droid
{
    [Activity(Label = "QuoteApp", MainLauncher = true)]
    class DroidToForms : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            StartActivity(typeof(XFPostPage));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());

        }
    }
}

which in turn calls this forms page, all the code here has been in Xamarin.Android project

namespace QuoteApp.Droid
{

        ///
        /// This is a Xamarin.Forms screen. It MUST:
        /// * inherit from ANdroidActivity
        /// * call Forms.Init()
        /// * use LoadApplication()
        ///
        [Activity(Label = "XFPostPage", MainLauncher = true) ]
        public class XFPostPage : Xamarin.Forms.Platform.Android.FormsApplicationActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);

                Xamarin.Forms.Forms.Init(this, bundle);

            //LoadApplication( new App() ); //how do i send to PostPage.xaml ??

            Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        }
    }

this gives the following error in logcat

07-04 17:51:44.494  7668  7668 E AndroidRuntime: Caused by: android.runtime.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at QuoteApp.Droid.XFPostPage.OnCreate (Android.OS.Bundle bundle) [0x00016] in <ab64801c0fb24acb8457c1d1202cc143>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_savedInstanceState) [0x0000f] in <d855bac285f44dda8a0d8510b679b1e2>:0
07-04 17:51:44.494  7668  7668 E AndroidRuntime:   at (wrapper dynamic-method) System.Object:2780fa42-5931-40d3-8d14-a642f1a3025c (intptr,intptr,intptr)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.n_onCreate(Native Method)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at md543d03747be5a5b03a21a2a23b8ba191a.XFPostPage.onCreate(XFPostPage.java:29)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6237)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:5417)
07-04 17:51:44.494  7668  7668 E AndroidRuntime:        ... 3 more

I have tried a bunch of different ideas all with different runtime errors, my understanding of the Xamarin.Android workings are very limited. eventually i will be using the notification with AlarmManager and further information will be sent to PostPage.Xaml. At the moment i'm just lost at exactly where this is going wrong though?!

Any Help would be hugely appreciated, thanks in advance.

Body:
I ended up using OnNewIntent in MainActivity.

there is some excellent information here Processing notifications in Xamarin Forms Android

My Code ended up looking like this.

Call the dependency service to get the android implmentation

DependencyService.Get<IQuoteNotification>().Notify("words",SelectedQuote.FixedTitle  , SelectedQuote.Id);

Which builds notification with the Intent:

  class QuoteNotification : IQuoteNotification
    {

        public void Notify(string title, string message, int postIndex)
        {

            //type needs to be derived from java, not xamarin.forms
            Intent LoadPostPage = new Intent(Forms.Context, typeof(MainActivity));
            LoadPostPage.PutExtra("NotificationTrue", true);
            LoadPostPage.PutExtra("PostID", postIndex);
            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                PendingIntent.GetActivity(Forms.Context, pendingIntentId, LoadPostPage, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(Forms.Context)
                    .SetContentIntent(pendingIntent)
                    .SetAutoCancel(true)
                    .SetContentTitle(title)
                    .SetContentText(message)
                    .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }
    }

then Override OnNewIntent in MainActivity. If the intent is not Built by my QuoteNotification class then send -1 as PostID

        protected override void OnNewIntent(Intent intent)
    {
        if (intent.HasExtra("NotificationTrue")){
            LoadApplication(new App(intent.GetIntExtra("PostID", -1)));
            //Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new QuoteApp.PostPage());
        }
        base.OnNewIntent(intent);
    }

Then in App.Xaml.cs add some logic to navigate to the correct page

public partial class App : Application
{
    public App(int PostId = -1)
    {
        InitializeComponent();

        if (PostId >= 0)
        {
            MainPage = new NavigationPage(new PostPage(PostId));
        }
        else
            MainPage = new NavigationPage(new MainPage());

ContentLicense: CC BY-SA 4.0


问:
Issue with deleting items from array in for loop
So I am having a problem with deleting items from an array while in a for loop

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this, 1));
    this.remove();
    console.log(array);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html></code>```

So the problem is that when I click on an item to delete it, it doesn't delete that specific one. No matter which one I click on, it deletes starting from the bottom ("iPhone" to "iPod" to "iPad").

Visually, it deletes the right one but when I go to the console I can see that it deletes from the bottom up. Any help would be so very much appreciated.

答:
you are using array.splice(array.indexOf(this, 1)) wrong, this gives you the clicked element where as array contains text inside that element, you need to do something like this:

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this.innerHTML),1);
    this.remove();
    console.log(array);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html></code>```

Body:
So I am having a problem with deleting items from an array while in a for loop

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this, 1));
    this.remove();
    console.log(array);
  }

}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>

So the problem is that when I click on an item to delete it, it doesn't delete that specific one. No matter which one I click on, it deletes starting from the bottom ("iPhone" to "iPod" to "iPad").

Visually, it deletes the right one but when I go to the console I can see that it deletes from the bottom up. Any help would be so very much appreciated.

Body:
you are using array.splice(array.indexOf(this, 1)) wrong, this gives you the clicked element where as array contains text inside that element, you need to do something like this:

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this.innerHTML),1);
    this.remove();
    console.log(array);
  }

}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html>


问:
Adobe Reader process fails when starting second instance
In our C# WinForms application, we generate PDF files and launch Adobe Reader (or whatever the default system .pdf handler is) via the Process class. Since our PDF files can be large (approx 200K), we handle the Exited event to then clean up the temp file afterwards.

The system works as required when a file is opened and then closed again. However, when a second file is opened (before closing Adobe Reader) the second process immediately exits (since Reader is now using it's MDI powers) and in our Exited handler our File.Delete call should fail because it's locked by the now joined Adobe process. However, in Reader we instead get:

There was an error opening this document. This file cannot be found.

The unusual thing is that if I put a debugger breakpoint before the file deletion and allow it to attempt (and fail) the deletion, then the system behaves as expected!

I'm positive that the file exists and fairly positive that all handles/file streams to the file are closed before starting the process.

We are launching with the following code:

```<code>// Open the file for viewing/printing (if the default program supports it)
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = tempFileName;
if (pdfProcess.StartInfo.Verbs.Contains("open", StringComparer.InvariantCultureIgnoreCase))
{
    var verb = pdfProcess.StartInfo.Verbs.First(v => v.Equals("open", StringComparison.InvariantCultureIgnoreCase));
    pdfProcess.StartInfo.Verb = verb;
}
pdfProcess.StartInfo.Arguments = "/N"; // Specifies a new window will be used! (But not definitely...)
pdfProcess.SynchronizingObject = this;
pdfProcess.EnableRaisingEvents = true;
pdfProcess.Exited += new EventHandler(pdfProcess_Exited);

_pdfProcessDictionary.Add(pdfProcess, tempFileName);

pdfProcess.Start();
</code>```

Note: We are using the _pdfProcessDictionary to store references to the Process objects so that they stay in scope so that Exited event can successfully be raised.

Our cleanup/exited event is:

```<code>void pdfProcess_Exited(object sender, EventArgs e)
{
    Debug.Assert(!InvokeRequired);
    var p = sender as Process;
    try
    {
        if (_pdfProcessDictionary.ContainsKey(p))
        {
            var tempFileName = _pdfProcessDictionary[p];
            if (File.Exists(tempFileName)) // How else can I check if I can delete it!!??
            {
                // NOTE: Will fail if the Adobe Reader application instance has been re-used!
                File.Delete(tempFileName);
                _pdfProcessDictionary.Remove(p);
            }

            CleanOtherFiles(); // This function will clean up files for any other previously exited processes in our dictionary
        }
    }
    catch (IOException ex)
    {
        // Just swallow it up, we will deal with trying to delete it at another point
    }
}
</code>```

Possible solutions:

Detect that the file is still open in another process

Detect that the second process hasn't really been fully exited and that the file is opened in the first process instead

答:
I would suggest following approach:

Create files in user's temp directory (Path.GetTempPath). You can create some sub-folder under it.

Attempt to delete files only when last instance of process gets exited (i.e. you need to count number of processes that you had launched, on exit, decrement the count and when it becomes zero, attempt to delete (all) files that are open so far)

Try to clean-up created sub-folder (under temp directory) while starting and ending the application. You can even attempt for periodic clean-up using timer.

ContentLicense: CC BY-SA 2.5

Body:
In our C# WinForms application, we generate PDF files and launch Adobe Reader (or whatever the default system .pdf handler is) via the Process class. Since our PDF files can be large (approx 200K), we handle the Exited event to then clean up the temp file afterwards.

The system works as required when a file is opened and then closed again. However, when a second file is opened (before closing Adobe Reader) the second process immediately exits (since Reader is now using it's MDI powers) and in our Exited handler our File.Delete call should fail because it's locked by the now joined Adobe process. However, in Reader we instead get:

There was an error opening this document. This file cannot be found.

The unusual thing is that if I put a debugger breakpoint before the file deletion and allow it to attempt (and fail) the deletion, then the system behaves as expected!

I'm positive that the file exists and fairly positive that all handles/file streams to the file are closed before starting the process.

We are launching with the following code:

// Open the file for viewing/printing (if the default program supports it)
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = tempFileName;
if (pdfProcess.StartInfo.Verbs.Contains("open", StringComparer.InvariantCultureIgnoreCase))
{
    var verb = pdfProcess.StartInfo.Verbs.First(v => v.Equals("open", StringComparison.InvariantCultureIgnoreCase));
    pdfProcess.StartInfo.Verb = verb;
}
pdfProcess.StartInfo.Arguments = "/N"; // Specifies a new window will be used! (But not definitely...)
pdfProcess.SynchronizingObject = this;
pdfProcess.EnableRaisingEvents = true;
pdfProcess.Exited += new EventHandler(pdfProcess_Exited);

_pdfProcessDictionary.Add(pdfProcess, tempFileName);

pdfProcess.Start();

Note: We are using the _pdfProcessDictionary to store references to the Process objects so that they stay in scope so that Exited event can successfully be raised.

Our cleanup/exited event is:

void pdfProcess_Exited(object sender, EventArgs e)
{
    Debug.Assert(!InvokeRequired);
    var p = sender as Process;
    try
    {
        if (_pdfProcessDictionary.ContainsKey(p))
        {
            var tempFileName = _pdfProcessDictionary[p];
            if (File.Exists(tempFileName)) // How else can I check if I can delete it!!??
            {
                // NOTE: Will fail if the Adobe Reader application instance has been re-used!
                File.Delete(tempFileName);
                _pdfProcessDictionary.Remove(p);
            }

            CleanOtherFiles(); // This function will clean up files for any other previously exited processes in our dictionary
        }
    }
    catch (IOException ex)
    {
        // Just swallow it up, we will deal with trying to delete it at another point
    }
}

Possible solutions:

Detect that the file is still open in another process

Detect that the second process hasn't really been fully exited and that the file is opened in the first process instead


问:
I wanna make a textbox that can collect the answer and bind with search url
I am trying to create a textbox that can collect the answer and bind it with the search url.

My problems are that I can type in the text box, but it won't the script.

The error being displayed is:

Uncaught TypeError: document.getElementById is not a constructor

at myFunction (index.html:23)

at HTMLButtonElement.onclick (index.html:14)

Tested in Chrome and Maxthon 5

And Here is my Code
https://hastebin.com/uqelimudoc.xml

答:
You don't need new when you're trying to access document.

Also a suggestion would be to use generic word for input name rather than a URL.

Working code snippet

```<code><form id="myForm" method="get">
  Version: <input type="text" name="http://dtht-webfile.000webhostapp.com/SS/#search=" placeholder="Example:0.3.1"><br>
</form>

<button onclick="myFunction()">Search</button>

<p id="version"></p>
<p></p>
<p id="final"></p>

<script type="text/javascript">
function myFunction() {
    var y = document.getElementById("myForm").elements[0].value;
    document.getElementById("version").innerHTML = y;
    // var z = document.getElementById("version").innerHTML;
    // z is same as y

    if (y < 035) {
    document.getElementById("final").innerHTML = "You're Lastest Version.";
   } else {
    document.getElementById("final").innerHTML = "You're Outdated. Please Go Download Lastest.";
   }
}
</script>
</code>```

If you're expecting a number to be user input then it'd be better to use appropriate input type or use regex to allow only number or else you can do the following before comparing y in the above code with Number(y)

Working fiddle - https://jsfiddle.net/k9d9hwbz/

Body:
You don't need new when you're trying to access document.

Also a suggestion would be to use generic word for input name rather than a URL.

Working code snippet

<form id="myForm" method="get">
  Version: <input type="text" name="http://dtht-webfile.000webhostapp.com/SS/#search=" placeholder="Example:0.3.1"><br>
</form>

<button onclick="myFunction()">Search</button>

<p id="version"></p>
<p></p>
<p id="final"></p>

<script type="text/javascript">
function myFunction() {
    var y = document.getElementById("myForm").elements[0].value;
    document.getElementById("version").innerHTML = y;
    // var z = document.getElementById("version").innerHTML;
    // z is same as y

    if (y < 035) {
    document.getElementById("final").innerHTML = "You're Lastest Version.";
   } else {
    document.getElementById("final").innerHTML = "You're Outdated. Please Go Download Lastest.";
   }
}
</script>

If you're expecting a number to be user input then it'd be better to use appropriate input type or use regex to allow only number or else you can do the following before comparing y in the above code with Number(y)

Working fiddle - https://jsfiddle.net/k9d9hwbz/


问:
How can I pass a dynamic filter to the List component with Admin On Rest?
I am using Show to show a student page. On the student page, I want to show a list of many courses and the list must be paginated.

```<code>    export const StudentShow = (props) => (
        <Show title='Student' {...props}>
            <SimpleShowLayout>
                // correctly displays the student ID
                <TextField label='id' source='id' />
                <ReferenceManyField
                    label='Courses'
                    target='course'
                    id='student.id'
                    reference='courses'>
                    // how can I properly pass the student ID to List?
                    <List {...props} filter={{ student: student.id }}>
                        <Datagrid>
                            <TextField source='code' />
                        </Datagrid>
                    </List>
                </ReferenceManyField>
            </SimpleShowLayout>
        </Show>
    );
</code>```

The ReferenceManyField correctly makes an API call to /courses/?student=<studentId>, however List just makes a call to /courses/. I am not able to pass down the student ID to the List component.

How do I pass student ID to the List component?

答:
You can save the StudentId in localStorage on login and use that to create the filter. Haven't tested this. But I think it should work.

Also I am not sure that List is the component that you should be passing as a Child to ReferenceManyField. It should be an iterator component such as DataGrid or SingleFieldList.

https://marmelab.com/admin-on-rest/Fields.html#referencemanyfield

Body:
I am using Show to show a student page. On the student page, I want to show a list of many courses and the list must be paginated.

    export const StudentShow = (props) => (
        <Show title='Student' {...props}>
            <SimpleShowLayout>
                // correctly displays the student ID
                <TextField label='id' source='id' />
                <ReferenceManyField
                    label='Courses'
                    target='course'
                    id='student.id'
                    reference='courses'>
                    // how can I properly pass the student ID to List?
                    <List {...props} filter={{ student: student.id }}>
                        <Datagrid>
                            <TextField source='code' />
                        </Datagrid>
                    </List>
                </ReferenceManyField>
            </SimpleShowLayout>
        </Show>
    );

The ReferenceManyField correctly makes an API call to /courses/?student=<studentId>, however List just makes a call to /courses/. I am not able to pass down the student ID to the List component.

How do I pass student ID to the List component?


问:
I have one text file and in that text file I stored words in 2 columns. I want to store first column in one array and second column in another array
I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.

In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.

```<code>for(int i=0;i<lines.size();i++){
    String[] splitting = lines.get(i).split("\t");
}
</code>```

答:
You could use Scanner to specify delimiter as tab..and use dynamic array i.e. ArrayList for adding columns.

```<code>BufferedReader reader= new BufferedReader(new FileReader("D:/sagar.txt"));
        Scanner sc= new Scanner(reader);
        sc.useDelimiter("\\s+"); // regex for specifying one or more tabs

        List<String> a=new ArrayList<String>();
        List<String> b =new ArrayList<String>();
        while((sc.hasNextLine())){
            a.add(sc.next());
            b.add(sc.next());
        }

        System.out.println("First Column");

        for (String string : a) {

            System.out.println(string);
        }

        System.out.println("Second Column");
        for (String string : b) {
            System.out.println(string);
</code>```

sagar.txt

```<code>hi ssup
hello gm
</code>```

Body:
I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.

In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.

for(int i=0;i<lines.size();i++){
    String[] splitting = lines.get(i).split("\t");
}

Body:
You could use Scanner to specify delimiter as tab..and use dynamic array i.e. ArrayList for adding columns.

BufferedReader reader= new BufferedReader(new FileReader("D:/sagar.txt"));
        Scanner sc= new Scanner(reader);
        sc.useDelimiter("\\s+"); // regex for specifying one or more tabs

        List<String> a=new ArrayList<String>();
        List<String> b =new ArrayList<String>();
        while((sc.hasNextLine())){
            a.add(sc.next());
            b.add(sc.next());
        }

        System.out.println("First Column");

        for (String string : a) {

            System.out.println(string);
        }

        System.out.println("Second Column");
        for (String string : b) {
            System.out.println(string);

sagar.txt

hi ssup
hello gm


问:
How Make Form Input With Auto Tag HTML

How to make form input like above? is it plugin? how to add to my own website?
i want every user make enter, the component auto add tag

答:
You could use following plugins.

CKEditor

TinyMCE

HtmlEditor

Title: How Make Form Input With Auto Tag HTML


问:
Regarding C (not C++) does doing math in comparison statements help or hurt efficiency? What about declaring pointers?
Since people can't seem to read I'm editing the question, and debating removal. I had simplified code representing some logic I'm working on optimizing in a large and very old project. I asked them to not focus so much on the code as much as the concepts of coding in C... I had to use code to help ask question because I'm not sure how to word properly otherwise.

Regarding C (not C++) does doing math in comparison statements help or hurt efficiency? What about declaration of pointers? SORRY can't give code examples as the syntax will be nitpicked to hell before I can get an answer.

答:
Performing comparisons between expression results or storing the values into local variables before the comparison usually does not make much of a difference, except when the computation can be avoided.  Here is a classic example:

```<code>int count_char(const char *s, char c) {
    int count = 0;
    for (int i = 0; i < strlen(s); i++) {
        if (s[i] == c)
           count++;
    }
    return count;
}
</code>```

Computing the length of the string for each iteration is very inefficient.  Computing it once in the loop initial phase is better:

```<code>int count_char(const char *s, char c) {
    int count = 0;
    for (int i = 0, len = strlen(s); i < len; i++) {
        if (s[i] == c)
           count++;
    }
    return count;
}
</code>```

Yet a different approach with pointers (as mentioned in your question) may prove even more efficient:

```<code>int count_char(const char *s, char c) {
    int count = 0;
    while (*s) {
        if (*s++ == c)
           count++;
    }
    return count;
}
</code>```

And here is a tighter version, albeit less readable:

```<code>int count_char(const char *s, char c) {
    int count = 0;
    while (*s) {
        count += (*s++ == c);
    }
    return count;
}
</code>```

Note that all of the above functions should use size_t instead of int for the i, len and count variables as, on some platforms, the length of the string could be larger than the maximum value of type int.

Note also that a very good optimizing compiler could produce similar and efficient code for all versions as strlen() is a pure function and the contents of s can be determined to remain constant during the execution of the function, but it is not necessarily true for more complicated examples.

Body:
Performing comparisons between expression results or storing the values into local variables before the comparison usually does not make much of a difference, except when the computation can be avoided.  Here is a classic example:

int count_char(const char *s, char c) {
    int count = 0;
    for (int i = 0; i < strlen(s); i++) {
        if (s[i] == c)
           count++;
    }
    return count;
}

Computing the length of the string for each iteration is very inefficient.  Computing it once in the loop initial phase is better:

int count_char(const char *s, char c) {
    int count = 0;
    for (int i = 0, len = strlen(s); i < len; i++) {
        if (s[i] == c)
           count++;
    }
    return count;
}

Yet a different approach with pointers (as mentioned in your question) may prove even more efficient:

int count_char(const char *s, char c) {
    int count = 0;
    while (*s) {
        if (*s++ == c)
           count++;
    }
    return count;
}

And here is a tighter version, albeit less readable:

int count_char(const char *s, char c) {
    int count = 0;
    while (*s) {
        count += (*s++ == c);
    }
    return count;
}

Note that all of the above functions should use size_t instead of int for the i, len and count variables as, on some platforms, the length of the string could be larger than the maximum value of type int.

Note also that a very good optimizing compiler could produce similar and efficient code for all versions as strlen() is a pure function and the contents of s can be determined to remain constant during the execution of the function, but it is not necessarily true for more complicated examples.


问:
Reveal CSS animation on scroll
I am trying to get bounce.js to show it's animation, when you scroll down the page. As of now, it just plays all the animations right away. Is there some jQuery code, that can do so that it triggers the css animation, when you reach the element? I do not know what is best practice here.

CSS

```<code>.image {
  width: 100%;
  height: 500px;
  margin-bottom: 60px;
  background-color: #000;
  animation: my-animation 1s linear both;
}
</code>```

Bounce.js

```<code>var bounce = new Bounce();
bounce.scale({
    from: { x: 0.5, y: 0.5 },
    to: { x: 1, y: 1 }
});
bounce.define("my-animation");
</code>```

答:
I don't know how to use Bounce JS, so I'm going to give you my answer in vanilla JavaScript and CSS. :)

First off, the CSS:

```<code>.image{
    width: 100%;
    height: 500px;
    margin-bottom: 60px;
    background-color: #000;
}
.image.animate{ // when the element has class "animate"
    animation: my-animation 1s linear both; // toggle animation
}

@keyframes my-animation{
    0%{
        transform: scale(0.5);
    }
    100%{
        transform: scale(1); // define how far you want them to move along the x / y axis
    }
}
</code>```

And the JavaScript:

```<code>window.addEventListener("scroll", function(e){
    var image = document.querySelector(".image");
    if(this.scrollY == 10){ // if scrolled 10px from the top

        image.classList.add("animate"); // add class "animate"

    } else if(this.scrollY < 10){ // if at top of page

        image.classList.remove("animate"); // remove class "animate"

    }
});
</code>```

Hopefully this helps :)

Title: Reveal CSS animation on scroll

Body:
I am trying to get bounce.js to show it's animation, when you scroll down the page. As of now, it just plays all the animations right away. Is there some jQuery code, that can do so that it triggers the css animation, when you reach the element? I do not know what is best practice here.

CSS

.image {
  width: 100%;
  height: 500px;
  margin-bottom: 60px;
  background-color: #000;
  animation: my-animation 1s linear both;
}

Bounce.js

var bounce = new Bounce();
bounce.scale({
    from: { x: 0.5, y: 0.5 },
    to: { x: 1, y: 1 }
});
bounce.define("my-animation");

Body:
I don't know how to use Bounce JS, so I'm going to give you my answer in vanilla JavaScript and CSS. :)

First off, the CSS:

.image{
    width: 100%;
    height: 500px;
    margin-bottom: 60px;
    background-color: #000;
}
.image.animate{ // when the element has class "animate"
    animation: my-animation 1s linear both; // toggle animation
}

@keyframes my-animation{
    0%{
        transform: scale(0.5);
    }
    100%{
        transform: scale(1); // define how far you want them to move along the x / y axis
    }
}

And the JavaScript:

window.addEventListener("scroll", function(e){
    var image = document.querySelector(".image");
    if(this.scrollY == 10){ // if scrolled 10px from the top

        image.classList.add("animate"); // add class "animate"

    } else if(this.scrollY < 10){ // if at top of page

        image.classList.remove("animate"); // remove class "animate"

    }
});

Hopefully this helps :)


问:
memory alignment issues with union
Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?

```<code>union my_union
{
  int value;
  char bytes[4];
};
</code>```

If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.

Thanks.

答: Yeah, unions would be utterly useless otherwise.</p>

Title: memory alignment issues with union

Body:
Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?

union my_union
{
  int value;
  char bytes[4];
};

If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.

Thanks.


问:
Is mongodb running?
I have installed Mongodb and the PHP drivers on my Unix server.

My question is how can I tell if Mongodb is running? Is there a simple command line query to check status? If I start it once from the shell will it keep running if I exit the shell (this doesn't seem to be the case). How can I make the Mongodb connection persistent and auto start on server reboot?

I can run:

```<code>-bash-3.2$ su
Password:
[root@xxx]# cd /var/lib
[root@xxx]# ./mongodb-linux-i686-1.6.5/bin/mongod
./mongodb-linux-i686-1.6.5/bin/mongod --help for help and startup options
Wed Feb 23 08:06:54 MongoDB starting : pid=7271 port=27017 dbpath=/data/db/ 32-bit

** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
**       see http://blog.mongodb.org/post/137788967/32-bit-limitations

** WARNING: You are running in OpenVZ. This is known to be broken!!!

Wed Feb 23 08:06:54 db version v1.6.5, pdfile version 4.5
Wed Feb 23 08:06:54 git version: 0eb017e9b2828155a67c5612183337b89e12e291
Wed Feb 23 08:06:54 sys info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri
Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_37
Wed Feb 23 08:06:54 [initandlisten] waiting for connections on port 27017
Wed Feb 23 08:06:54 [websvr] web admin interface listening on port 28017
</code>```

If I open a separate shell I can then then connect to mongodb:

```<code>-bash-3.2$ cd /var/lib
-bash-3.2$ ./mongodb-linux-i686-1.6.5/bin/mongo
MongoDB shell version: 1.6.5
connecting to: test
> db.foo.find()
{ "_id" : ObjectId("4d63d7d3eb95985ab19c8feb"), "a" : 1 }
</code>```

However if I close the initial shell I can't connect:

```<code>-bash-3.2$ cd /var/lib
-bash-3.2$ ./mongodb-linux-i686-1.6.5/bin/mongo
MongoDB shell version: 1.6.5
connecting to: test
Wed Feb 23 08:25:10 Error: couldn't connect to server 127.0.0.1 (anon):1154
exception: connect failed
</code>```

答:
this should work fine...</p>
```<code>pgrep mongod
</code>```

Title: Is mongodb running?

Body:
I have installed Mongodb and the PHP drivers on my Unix server.

My question is how can I tell if Mongodb is running? Is there a simple command line query to check status? If I start it once from the shell will it keep running if I exit the shell (this doesn't seem to be the case). How can I make the Mongodb connection persistent and auto start on server reboot?

I can run:

-bash-3.2$ su
Password:
[root@xxx]# cd /var/lib
[root@xxx]# ./mongodb-linux-i686-1.6.5/bin/mongod
./mongodb-linux-i686-1.6.5/bin/mongod --help for help and startup options
Wed Feb 23 08:06:54 MongoDB starting : pid=7271 port=27017 dbpath=/data/db/ 32-bit

** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
**       see http://blog.mongodb.org/post/137788967/32-bit-limitations

** WARNING: You are running in OpenVZ. This is known to be broken!!!

Wed Feb 23 08:06:54 db version v1.6.5, pdfile version 4.5
Wed Feb 23 08:06:54 git version: 0eb017e9b2828155a67c5612183337b89e12e291
Wed Feb 23 08:06:54 sys info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri
Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_37
Wed Feb 23 08:06:54 [initandlisten] waiting for connections on port 27017
Wed Feb 23 08:06:54 [websvr] web admin interface listening on port 28017

If I open a separate shell I can then then connect to mongodb:

-bash-3.2$ cd /var/lib
-bash-3.2$ ./mongodb-linux-i686-1.6.5/bin/mongo
MongoDB shell version: 1.6.5
connecting to: test
> db.foo.find()
{ "_id" : ObjectId("4d63d7d3eb95985ab19c8feb"), "a" : 1 }

However if I close the initial shell I can't connect:

-bash-3.2$ cd /var/lib
-bash-3.2$ ./mongodb-linux-i686-1.6.5/bin/mongo
MongoDB shell version: 1.6.5
connecting to: test
Wed Feb 23 08:25:10 Error: couldn't connect to server 127.0.0.1 (anon):1154
exception: connect failed

Body:
this should work fine...

pgrep mongod


问:
Get image URL instead of content from google drive api
Trying to get image URL instead of file content from Google Drive API.
In the new version this GOOD thing is deprecated.

I searched a lot, on Google developer class there is a method, but its missing in the new version as well.

The problem is that I'm going to get lot of images from the Drive, but don't want to loose the speed of Google trying to path trough my app all images. And this is stupid also.

Is there a way to get those link somehow still?

This is my code I use to get file content:

```<code>$this->client = new \Google_Client();
$this->client->setAuthConfigFile('config.json');
$this->client->setScopes('https://www.googleapis.com/auth/drive');

if (isset($_GET['code'])) $code = $_GET['code'];

if(!isset($_SESSION['access_token'])){
    if (!isset( $code )){
        $auth_url = $this->client->createAuthUrl();
        $filtered_url = filter_var($auth_url, FILTER_SANITIZE_URL);
        return redirect($filtered_url);
    }else{
        $this->client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $this->client->getAccessToken();
        // return redirect('/');
    }
}

$this->service = new \Google_Service_Drive($this->client);
$file_id = '0B3vR4cBcxn4oNm9TSlBzcngyMzQ';
$results = $this->service->files->get($file_id, array('alt' => 'media'));

$imaga = $results->getBody()->getContents();

$imageData = base64_encode($imaga);
$contentType = $results->getHeader("content-type");

$src = 'data: '.$contentType[0].';base64,'.$imageData;
</code>```

答: As of now, I think there's 2 ways you can access your Drive images with the API. That's using webContentLink if you want to download the file and the webViewLink if you want to display the file. Those are the available drive metadata you can use.

Body:
Trying to get image URL instead of file content from Google Drive API.
In the new version this GOOD thing is deprecated.

I searched a lot, on Google developer class there is a method, but its missing in the new version as well.

The problem is that I'm going to get lot of images from the Drive, but don't want to loose the speed of Google trying to path trough my app all images. And this is stupid also.

Is there a way to get those link somehow still?

This is my code I use to get file content:

$this->client = new \Google_Client();
$this->client->setAuthConfigFile('config.json');
$this->client->setScopes('https://www.googleapis.com/auth/drive');

if (isset($_GET['code'])) $code = $_GET['code'];

if(!isset($_SESSION['access_token'])){
    if (!isset( $code )){
        $auth_url = $this->client->createAuthUrl();
        $filtered_url = filter_var($auth_url, FILTER_SANITIZE_URL);
        return redirect($filtered_url);
    }else{
        $this->client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $this->client->getAccessToken();
        // return redirect('/');
    }
}

$this->service = new \Google_Service_Drive($this->client);
$file_id = '0B3vR4cBcxn4oNm9TSlBzcngyMzQ';
$results = $this->service->files->get($file_id, array('alt' => 'media'));

$imaga = $results->getBody()->getContents();

$imageData = base64_encode($imaga);
$contentType = $results->getHeader("content-type");

$src = 'data: '.$contentType[0].';base64,'.$imageData;


问:
PHP 7: Whats bad about passing a non-variable by reference and why a NOTICE if function passed, but an FATAL error if array is passed?
I have the following code:

```<code>$family = cis_resempty(wp_get_post_terms($post->ID,'family'),0);
</code>```

I get the following error:

Notice: Only variables should be passed by reference in
  C:\xampp.....xxx.php on line 18

If I do the following:

```<code>$family = cis_resempty(array('a'),0);
</code>```

I even get

Fatal error: Only variables can be passed by reference in
  C:\xampp...xxx.php on line 16

The function cis_resempty is like this (but its from a library):

```<code>function cis_resempty(&$var,$key) { ... }
</code>```

Found out that if I remove the & reference sign within the parameter list of cis_resempty there are no errors.

If I do this:

```<code>$family = @cis_resempty(wp_get_post_terms($post->ID,'family'),0);
</code>```

There is no notice and everything works - but Netbeans says:

Misuse of the error control operator

But if I do this:

```<code>$family = @cis_resempty(array('a'),0);
</code>```

The fatal error continues to exist.

Why can I pass a function by reference and suppress the notice with the error control operator but if I pass an array I get a fatal error?

Why is it bad to pass a non variable by reference?

答:
The term "non-variable" refers to any variable which the programmer cannot reference by name. These are temporary variables allocated by the executor at runtime: The result of a function call or some other expression, that is not assigned to a named variable.

To pass something by reference only makes sense if the variable being passed by reference is named, so that when the call is over, the caller can access that which was passed by reference to the callee.

When PHP comes across a function call at compile time, the space for the result of the function call, and parameters of the function call are reserved, and then allocated at execution time relative to the execution frame. When you pass the result of a function call by reference, the executor is able to force by-reference behaviour for the variable, because there is space on the heap and it can just ignore that the variable has no name ... it doesn't usually make sense to do that, but remains for backward compatibility reasons.

When PHP comes across a literal (array) at compile time, it allocates the space for the data relative to the op array (function) itself. Because of that difference forcing by-reference behaviour of literals would be dangerous and cause very unexpected behaviour: Consider what would happen when the function is re-entered, concurrently or otherwise.

Body:
I have the following code:

$family = cis_resempty(wp_get_post_terms($post->ID,'family'),0);

I get the following error:

Notice: Only variables should be passed by reference in
  C:\xampp.....xxx.php on line 18

If I do the following:

$family = cis_resempty(array('a'),0);

I even get

Fatal error: Only variables can be passed by reference in
  C:\xampp...xxx.php on line 16

The function cis_resempty is like this (but its from a library):

function cis_resempty(&$var,$key) { ... }

Found out that if I remove the & reference sign within the parameter list of cis_resempty there are no errors.

If I do this:

$family = @cis_resempty(wp_get_post_terms($post->ID,'family'),0);

There is no notice and everything works - but Netbeans says:

Misuse of the error control operator

But if I do this:

$family = @cis_resempty(array('a'),0);

The fatal error continues to exist.

Why can I pass a function by reference and suppress the notice with the error control operator but if I pass an array I get a fatal error?

Why is it bad to pass a non variable by reference?


答:
In the onclick function make the following changes.

```<code>p.onclick = function() {
    array.splice(array.indexOf(this.textContent),1);
    this.remove();
    console.log(array);
  }
</code>```

Title: Issue with deleting items from array in for loop

Body:
In the onclick function make the following changes.

p.onclick = function() {
    array.splice(array.indexOf(this.textContent),1);
    this.remove();
    console.log(array);
  }


问:
Extracting integers from a list
I have a list like this:

```<code>fmt_string="I am a smoker male of 25 years who wants a policy for 30
yrs with a sum assured amount of 1000000 rupees"
</code>```

from the above list I removed stopwords and got this
Now I have a list as following:

```<code>['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs',
'sum', 'assured', 'amount', '1000000', 'rupees']
</code>```

from this list I want to extract just 25, 30 and 1000000, but the code should be something like 25 would be before or after years. 30 could either be after policy and 1000000 can be at any position

finally output should be like:

```<code>'1000000 30 25 male smoker'
</code>```

I just want a robust code that wherever I find these values i return me a list like this.

答:
use re for findall occurances in list and join with comma split this to list and apply reverse() to list and then join ' ' again

your data:

```<code>li = ['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs', 'sum', 'assured', 'amount', '1000000', 'rupees']

temp=",".join([l for l in li if re.findall('1000000|30|25|male|smoker',l)]).split(",")

temp.reverse()
temp = " ".join(temp)
</code>```

Output:

```<code>'1000000 30 25 male smoker'
</code>```

Hope this answer helpful.

Title: Extracting integers from a list

Body:
I have a list like this:

fmt_string="I am a smoker male of 25 years who wants a policy for 30
yrs with a sum assured amount of 1000000 rupees"

from the above list I removed stopwords and got this
Now I have a list as following:

['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs',
'sum', 'assured', 'amount', '1000000', 'rupees']

from this list I want to extract just 25, 30 and 1000000, but the code should be something like 25 would be before or after years. 30 could either be after policy and 1000000 can be at any position

finally output should be like:

'1000000 30 25 male smoker'

I just want a robust code that wherever I find these values i return me a list like this.

Body:
use re for findall occurances in list and join with comma split this to list and apply reverse() to list and then join ' ' again

your data:

li = ['smoker', 'male', '25', 'years', 'wants', 'policy', '30', 'yrs', 'sum', 'assured', 'amount', '1000000', 'rupees']

temp=",".join([l for l in li if re.findall('1000000|30|25|male|smoker',l)]).split(",")

temp.reverse()
temp = " ".join(temp)

Output:

'1000000 30 25 male smoker'

Hope this answer helpful.


问:
Kotlin || Recycleview item is not inflating: Unreachable code on each overridden method of RecycleView.Adapter
I am creating the Custom Recycleview  in Kotlin

I am not getting any exception in the code and it run perfectly but the concern is that item is not getting appear on the Recycleview beacuase the code is unreachable in Adapter class.

Waring :- Unreachable code on the overridden method of RecycleView adapter.

Please check my Adapter and Activity class

Adapter Class

```<code>class CustomRecycleAdapter(val data: ArrayList<String>) : RecyclerView.Adapter<CustomRecycleAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        val v = LayoutInflater.from(parent?.context).inflate(R.layout.recycle_item, parent, false)
        return ViewHolder(v)

    }

    override fun getItemCount(): Int {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        return data.size;
    }

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        val item = data[position]
        println("Data is here==>>> "+item)
        holder?.textViewName?.text = item;
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val textViewName = itemView.findViewById<TextView>(R.id.tvName)

    }
}
</code>```

Activity class

```<code>class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =   findViewById<RecyclerView>(R.id.recycler_view)

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter

    }

}
</code>```

答:
You haven't added a layout manager for the RecyclerView.Just add a LinearLayoutManager OR a GridLayoutManager

recycler_view.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)

Body:
I am creating the Custom Recycleview  in Kotlin

I am not getting any exception in the code and it run perfectly but the concern is that item is not getting appear on the Recycleview beacuase the code is unreachable in Adapter class.

Waring :- Unreachable code on the overridden method of RecycleView adapter.

Please check my Adapter and Activity class

Adapter Class

class CustomRecycleAdapter(val data: ArrayList<String>) : RecyclerView.Adapter<CustomRecycleAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        val v = LayoutInflater.from(parent?.context).inflate(R.layout.recycle_item, parent, false)
        return ViewHolder(v)

    }

    override fun getItemCount(): Int {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        return data.size;
    }

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        val item = data[position]
        println("Data is here==>>> "+item)
        holder?.textViewName?.text = item;
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val textViewName = itemView.findViewById<TextView>(R.id.tvName)

    }
}

Activity class

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =   findViewById<RecyclerView>(R.id.recycler_view)

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter

    }

}


问:
Allman-style anonymous classes
Any recommendations on how to use anonymous classes while staying consistent with Allman indent style? I don't really like anything I've come up with, e.g.</p>

```<code>// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    });

// Assign to variable.
Clazz bar = new Clazz( )
            {
               // Do stuff.
            };
</code>```

答:
The best compromise I came up with for my own code, is indenting the anonymous class a single tabbing level, and putting the closing parentheses on a new line.</p>

```<code>// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    }
);

void func () {
    foo(new Clazz( )
        {
           // Do stuff.
        }
    );
}

// Assign to variable.
Clazz bar = new Clazz( )
    {
        // Do stuff.
    };
</code>```

Title: Allman-style anonymous classes

Body:
Any recommendations on how to use anonymous classes while staying consistent with Allman indent style? I don't really like anything I've come up with, e.g.

// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    });

// Assign to variable.
Clazz bar = new Clazz( )
            {
               // Do stuff.
            };

Body:
The best compromise I came up with for my own code, is indenting the anonymous class a single tabbing level, and putting the closing parentheses on a new line.

// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    }
);

void func () {
    foo(new Clazz( )
        {
           // Do stuff.
        }
    );
}

// Assign to variable.
Clazz bar = new Clazz( )
    {
        // Do stuff.
    };


问:
Wordpress - add %lang% to the beginning of every url/permalink
I need a little guidance on how to accomplish this task I have been looking into over this past week. I have a feeling this has been solved somewhere but after searching all week I can't find it.

I am building a site which is using custom post types as well as pages and regular categories with posts. I have integrated google translate into the site and this works fine with my custom flags using the jQuery on click event and loading the selected language when you visit the site.

However I need to add the 2 character lang code to the beginning of my urls, for example:-

```<code>domain.com/fr/page,
domain.com/fr/category,
domain.com/fr/category/postname,
domain.com/fr/custom_post_type
</code>```

This is my permalinks structure - /%lang%/%category%/%postname%/

I have this in my functions file, hence the %lang% in my permalinks structure.

```<code>function add_lang_tag() {
    add_rewrite_tag('%lang%', '([a-z]{2})');
}
add_action('init', 'add_lang_tag', 10, 0);
</code>```

It works for the regular categories and posts but it does not work for pages, search or custom post types.

For reference this question came seriously close to sloving my problem - Wordpress add_rewrite_tag(), add_rewrite_rule(), and post_link() - The main issue with this solution is that it did not work for regular pages.

I have also tried pretty much all of the multilingual plugins available for wordpress and none of them match my seemingly simple requirements, if I can acheive this pruely through add_rewrite_tag and cvhanging the peralinks I think there might be a few others who could benefit from it.

Thanks for reading.

答:
It may be too late, but still I am giving this for user's who are still looking for this solution ---</p>

```<code>add_action( 'init', 'custom_page_rules' );

function custom_page_rules() {
    global $wp_rewrite;
    $wp_rewrite->page_structure = $wp_rewrite->root . '/%lang%/%pagename%';
}
</code>```

Body:
I need a little guidance on how to accomplish this task I have been looking into over this past week. I have a feeling this has been solved somewhere but after searching all week I can't find it.

I am building a site which is using custom post types as well as pages and regular categories with posts. I have integrated google translate into the site and this works fine with my custom flags using the jQuery on click event and loading the selected language when you visit the site.

However I need to add the 2 character lang code to the beginning of my urls, for example:-

domain.com/fr/page,
domain.com/fr/category,
domain.com/fr/category/postname,
domain.com/fr/custom_post_type

This is my permalinks structure - /%lang%/%category%/%postname%/

I have this in my functions file, hence the %lang% in my permalinks structure.

function add_lang_tag() {
    add_rewrite_tag('%lang%', '([a-z]{2})');
}
add_action('init', 'add_lang_tag', 10, 0);

It works for the regular categories and posts but it does not work for pages, search or custom post types.

For reference this question came seriously close to sloving my problem - Wordpress add_rewrite_tag(), add_rewrite_rule(), and post_link() - The main issue with this solution is that it did not work for regular pages.

I have also tried pretty much all of the multilingual plugins available for wordpress and none of them match my seemingly simple requirements, if I can acheive this pruely through add_rewrite_tag and cvhanging the peralinks I think there might be a few others who could benefit from it.

Thanks for reading.

Body:
It may be too late, but still I am giving this for user's who are still looking for this solution ---

add_action( 'init', 'custom_page_rules' );

function custom_page_rules() {
    global $wp_rewrite;
    $wp_rewrite->page_structure = $wp_rewrite->root . '/%lang%/%pagename%';
}


问:
Error in android studio when opening any project
When ever I am trying to open any new project or old project I am getting issue such as
failed to resolve junit
failed to resolve javax.inject
failed to resolve javax.annotation
 failed to resolve com.google.code.findbugs.
and others. Have tried invalidating , cleaning and even reinstalled android studio nothing works what else to do !

答: remove junit dependancy from gridle(module) file or simple install junit library</p>


问:
How to attach datepicker to a single dynamic inserted input field?
I know this question has been asked for many years, but after reading so many questions related to this I'm still enable to achieve what I want.

I have a table containing a bunch of input fields Those input fields use the jQuery UI datepicker. There is also a button to add a table row.

When I click the button to add a table row, it is added to the modal correctly. But, the datepicker of all input fire at the same time(no similar id used).

Modal code:

```<code><div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <form class="form-horizontal" id="edit-form">
              <div class="form-group">
                <label for="date" class="col-sm-2 text-left">Date</label>
                  <div class="col-sm-10">
                    <div class="table-responsive">
                      <table class="table table-bordered" id="dynamic_field">
                          <tr>
                            <td><input type="text" name="date" placeholder="Enter date"  class="form-control usedatepicker"/></td>
                            <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                          </tr>
                      </table>
                    </div>
                  </div>
              </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary">Save changes</button>
            </div>
            </form>
      </div>
</div>
</code>```

JS code:

```<code>$(document).ready(function(){
      var i=1;
      $('#add').click(function(){
           i++;
           $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="data" placeholder="Enter date" class="form-control usedatepicker" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
           $(".usedatepicker").datepicker();

      });
      $(document).on('click', '.btn_remove', function(){
           var button_id = $(this).attr("id");
           $('#row'+button_id+'').remove();
      });
 });
</code>```

答:
yes, because the problem with Jquery you can't able to attach the event to dynamic element from Jquery. To overcome this issue, you need to reference the previous available element on DOM as a main selector, like this below code.

```<code>$('body').on('focus',".class_of_dynamic_element", function(){
$(this).datepicker();});
</code>```

Now the datapicker will attached to that element.

Body:
I know this question has been asked for many years, but after reading so many questions related to this I'm still enable to achieve what I want.

I have a table containing a bunch of input fields Those input fields use the jQuery UI datepicker. There is also a button to add a table row.

When I click the button to add a table row, it is added to the modal correctly. But, the datepicker of all input fire at the same time(no similar id used).

Modal code:

        <form class="form-horizontal" id="edit-form">

                Date

                            <input type="text" name="date" placeholder="Enter date"  class="form-control usedatepicker"/>
                            <button type="button" name="add" id="add" class="btn btn-success">Add More</button>

              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary">Save changes</button>

            </form>

JS code:

$(document).ready(function(){
      var i=1;
      $('#add').click(function(){
           i++;
           $('#dynamic_field').append('
<input type="text" name="data" placeholder="Enter date" class="form-control usedatepicker" />	<button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button>
');
           $(".usedatepicker").datepicker();

      });
      $(document).on('click', '.btn_remove', function(){
           var button_id = $(this).attr("id");
           $('#row'+button_id+'').remove();
      });
 });

Body:
yes, because the problem with Jquery you can't able to attach the event to dynamic element from Jquery. To overcome this issue, you need to reference the previous available element on DOM as a main selector, like this below code.

$('body').on('focus',".class_of_dynamic_element", function(){
$(this).datepicker();});

Now the datapicker will attached to that element.


问:
Difference between MySQL release versions
What is the difference between mysql-5.5.8.zip and mysql-5.5.8-win32.zip in the http://dev.mysql.com/downloads/mysql/ download page. I have a Win 2K environment, what binary should I use and why does it have a huge size difference between the above?</p>

答:
The smaller package does not contain test suite and embedded server.

Anyway, I suggest you use the MSI installer instead - installation and configuration are way more straightforward.


问:
What's this compression method?
I want to modify a file in this package, but I can't compress it with the same method that was used before (on another PC). Anyone can give me a piece of advice how to compress it and with which software? For example I want to edit the scripts\alienware_light_fx.xml file and then compress the whole package again.

P.S. Sorry for my bad english! :(

答: That is a zip file. Any zip utility can create or modify it. You don't need to recompress the whole thing. A zip utility will allow you to simply replace that one entry.</p>

Title: What's this compression method?


问:
shell script - check mongod server is running
I have a shell script to do some mongo db actions:

e.g. mongo testdb --eval "db.dropDatabase()"

BUT, if the mongod server is not running, I get:

```<code>MongoDB shell version: 2.0.4
connecting to: testdb
Tue May 14 04:33:58 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84
</code>```

Is there a way in mongo I can check the connection status? Eventually I want something like:

```<code>if(mongod is running):
    mongo testdb --eval "db.dropDatabase()"
else:
    echo "pls make sure your mongod is running"
    exit 1
</code>```

答:
try running this in your shell script:-

pgrep mongod

If the value is numeric you know that the process is running, if you get an empty value, flag it as service not running...

Body:
I have a shell script to do some mongo db actions:

e.g. mongo testdb --eval "db.dropDatabase()"

BUT, if the mongod server is not running, I get:

MongoDB shell version: 2.0.4
connecting to: testdb
Tue May 14 04:33:58 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84

Is there a way in mongo I can check the connection status? Eventually I want something like:

if(mongod is running):
    mongo testdb --eval "db.dropDatabase()"
else:
    echo "pls make sure your mongod is running"
    exit 1


问:
ExtJS 6.2 - issue with initConfig
ExtJS version 6.2

I'm not allowed to call initConfig() from my extended textfield, in a contructor. The error it thrown is that,
initConfig should not be called by subclasses, it will be called by Ext.Component(…).

For some reason I can't use callParent() there.
It was available in ExtJS 5.0. Any alternatives for this?

答:
Use Ext.apply(this, cfg) instead of initConfig(). It will solve your issue.

Sample old code:

```<code> constructor: function(cfg){
         this.initConfig(cfg);
    },
</code>```

Sample correct code:

```<code>constructor: function(cfg){
    //this.initConfig(cfg);
    Ext.apply(this, cfg);

},
</code>```

Title: ExtJS 6.2 - issue with initConfig

Body:
Use Ext.apply(this, cfg) instead of initConfig(). It will solve your issue.

Sample old code:

 constructor: function(cfg){
         this.initConfig(cfg);
    },

Sample correct code:

constructor: function(cfg){
    //this.initConfig(cfg);
    Ext.apply(this, cfg);

},


问:
I don't know why this while loop doesn't stop iterating
It's a challenge on codewars.com, but I can't figure out why this while loop doesn't work

def digital_root(n):
    # Creating variable combine to have the sum
    combine = 0
    # as long as n is more than two numbers.
    while n > 10:
        # converting n to string to iterate
        for i in str(n):
            # getting the sum each element in n
            combine += int(i)
        # reset n to be equal to the combined result
        n = combine
    return combine
```

also, any solutions will be appreciated, here is the link to the challenge
https://www.codewars.com/kata/sum-of-digits-slash-digital-root

答:
I would do something like the following:

```<code>def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)

        print combined

        # this is the condition to check if you should stop
        if len(str(combined)) < 2:
            return combined
        else:
            n = combined
            combined = 0
</code>```

EDIT: you could also do it without converting to a str like you did:

```<code>def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)
        print combined
        if combined < 10:
            return combined
        else:
            n = combined
            combined = 0
</code>```

Body:
It's a challenge on codewars.com, but I can't figure out why this while loop doesn't work

def digital_root(n):
    # Creating variable combine to have the sum
    combine = 0
    # as long as n is more than two numbers.
    while n > 10:
        # converting n to string to iterate
        for i in str(n):
            # getting the sum each element in n
            combine += int(i)
        # reset n to be equal to the combined result
        n = combine
    return combine

also, any solutions will be appreciated, here is the link to the challenge
https://www.codewars.com/kata/sum-of-digits-slash-digital-root

Body:
I would do something like the following:

def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)

        print combined

        # this is the condition to check if you should stop
        if len(str(combined)) < 2:
            return combined
        else:
            n = combined
            combined = 0

EDIT: you could also do it without converting to a str like you did:

def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)
        print combined
        if combined < 10:
            return combined
        else:
            n = combined
            combined = 0


问:
How to change the pixel values of an Image?
I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.

So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at trying to remove the noise.
After studying the image data, I found that values of 205 are quite possibly the ones I want to keep the threshold at.

So what I am doing in the code is, open the image and change the pixel values containing 205 to black.
Here is the code for the same:

```<code>from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = im.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
           pixelMap[i,j] = (0,0,0,255)
        pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()
img.save("out.tif")
img.close()
</code>```

The problem is, that the resultant image is just a plain white screen. What have I done wrong?

答:
You basically need a new image with the noise removed, which is pixelsNew.
So whenever you find such a case in pixelMap if 205 in pixelMap[i,j] then set that corresponding value as 0 in pixelsNew pixelNew[i,j] = (0, 0, 0, 255). OTHERWISE just copy the pixel value from pixelMap pixelsNew[i,j] = pixelMap[i,j]

```<code>from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
            pixelsNew[i,j] = (0,0,0,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()
img.save("out.tif")
img.close()
</code>```

Body:
I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.

So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at trying to remove the noise.
After studying the image data, I found that values of 205 are quite possibly the ones I want to keep the threshold at.

So what I am doing in the code is, open the image and change the pixel values containing 205 to black.
Here is the code for the same:

from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = im.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
           pixelMap[i,j] = (0,0,0,255)
        pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()
img.save("out.tif")
img.close()

The problem is, that the resultant image is just a plain white screen. What have I done wrong?

Body:
You basically need a new image with the noise removed, which is pixelsNew.
So whenever you find such a case in pixelMap if 205 in pixelMap[i,j] then set that corresponding value as 0 in pixelsNew pixelNew[i,j] = (0, 0, 0, 255). OTHERWISE just copy the pixel value from pixelMap pixelsNew[i,j] = pixelMap[i,j]

from PIL import Image
im = Image.open('nuvfits1.png')
pixelMap = im.load()

img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        if 205 in pixelMap[i,j]:
            pixelsNew[i,j] = (0,0,0,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
im.close()
img.show()
img.save("out.tif")
img.close()


问:
How to rollback only one branch from development when multiple branches have been merged on it

My workflow:

There is a master branch

There is a dev branch

New feature branches are created based off master as and when required. These feature branches are then merged with dev so we can test it on our development server. Feature branches never take pull of any other branch other than master so they are pure in that any of these can be individually merged with master at any time.

If there is any conflict while merging any feature branch to dev, this is resolved on dev branch itself by switching to dev and then taking pull of that feature branch and resolving conflicts manually while on dev branch. So, no feature branch ever takes pull from dev branch to keep them pure.

Feature branches are based off master because sometimes one or more of the multiple features may not be ready for that month's deployment while all others have been completed and approved. In such cases, we are supposed to roll back the dev branch last month's state and then merge in all the approved branches leaving off the incomplete branches.

Problem/question:

For this month's deployment, one of the 10 features is not ready and we need to pull this out from development so that all others can be tested once on development server without this incomplete branch and then can be merged with master.

First option I can think of is as mentioned above i.e. to rollback dev branch to an older state (say commit abcdef) where none of these feature branches was merged in it. Then I need to merge in all the approved branches only on dev. I can roll back to that old state using git checkout abcdef. But I think it goes to some hanging state after that. How will I be able to merge other branches in it like I would normally do on dev branch?

I also read somewhere about git revert command. Is it possible to resolve my issue using git revert?

Please note that the branch I need to pull out has to be merged in with dev again after this month's deployment.

答:
As long as you specify the parent branch (i.e. the "clean" one), you can do this with git revert. Something like this:

```<code>git revert -m 1 <merge SHA>
</code>```

What this will do is create a new commit that reverts the changes in the merge. If you then later want to undo this (for instance, if you want to re-merge the problem branch), just revert the reverted commit.

Body:
As long as you specify the parent branch (i.e. the "clean" one), you can do this with git revert. Something like this:

git revert -m 1 <merge SHA>

What this will do is create a new commit that reverts the changes in the merge. If you then later want to undo this (for instance, if you want to re-merge the problem branch), just revert the reverted commit.


问:
Set different Tax rates conditionally based on cart item prices in Woocommerce
In My Wordpress e-commerce web site I use WP Hotel Booking, a plugin for hotel room bookings. The checkout process is done using WooCommerce.

The Issue: We have different rooms with different pricing.For example :

Room A price - 1500

Room B Price - 2700

Room c price - 2200

GST Tax is set at 12% for rooms wich price is below 2500 and 18% for rooms above 2500.

Since I am using WP Hotel Booking for this custom product (room Management), I am unable to use the Additional Tax Classes option in woocommerce to set different tax classes.

I need your help in writing a function to check the room value and then decide what tax needs to be set for the given room.

Thanks

答:
This is something accessible and easy.

1°) you need to create in your WooCommerce Tax settings 2 new Tax classes. In this example I have named that tax classes "Tax 12" and "Tax 18". Then for each of them you will have to set a different percentage of 12% and 18%.

2°) Now here is a custom function hooked in woocommerce_before_calculate_totals action hook that is going to apply a tax class based on the product price. I don't use the tax class names, but the tax class slugs, that are in lowercase and spaces are replace by a hyphen.

So Here is that code:

```<code>add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        // get product price
        $price = $cart_item['data']->get_price();

        // Set conditionaly based on price the tax class
        if ( $price < 2500 )
            $cart_item['data']->set_tax_class( 'tax-12' ); // below 2500
        if ( $price >= 2500 )
            $cart_item['data']->set_tax_class( 'tax-18' ); // Above 2500
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on WooCommerce version 3+

Body:
This is something accessible and easy.

1°) you need to create in your WooCommerce Tax settings 2 new Tax classes. In this example I have named that tax classes "Tax 12" and "Tax 18". Then for each of them you will have to set a different percentage of 12% and 18%.

2°) Now here is a custom function hooked in woocommerce_before_calculate_totals action hook that is going to apply a tax class based on the product price. I don't use the tax class names, but the tax class slugs, that are in lowercase and spaces are replace by a hyphen.

So Here is that code:

add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach ( $cart->get_cart() as $cart_item ) {
        // get product price
        $price = $cart_item['data']->get_price();

        // Set conditionaly based on price the tax class
        if ( $price < 2500 )
            $cart_item['data']->set_tax_class( 'tax-12' ); // below 2500
        if ( $price >= 2500 )
            $cart_item['data']->set_tax_class( 'tax-18' ); // Above 2500
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on WooCommerce version 3+


问:
Avoid cycle between java packages SonarQube
I am getting from sonar the following major bug:
Remove the dependency on the source file "src/main/java/com/credorax/brain/model/context/Credential.java" to break a package cycle

Which actually means if i remove the import, it will break the cycle.
I don't understand what they expect me to do to resolve this.

答:
A package cycle is created when a class in package A uses a class in package B, and a class in package B (it may or not be the same class) uses a class in package A (again, maybe the same class, maybe not). This is thought to indicate poor design, and so it's advised against.

Typically, you break package cycles by reconsidering your package design. Maybe A and B should really be one package. Or maybe one of the classes in package A ought to be moved to package B. Or vice versa. But the idea here is that if you drew a diagram of which packages use each other, it would not look like spaghetti.


问:
How to use Pattern Matching where clause in Flink?
I have this Flink program below:

```<code>val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

val dataStream = env.addSource(new FlinkKafkaConsumer010[String](topicChannel1, new SimpleStringSchema(), props))

val partitionedInput = dataStream.keyBy(jsonString => {
  val jsonParser = new JsonParser()
  val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
  jsonObject.get("account")
})

val pattern = Pattern.begin[String]("start").where(jsonString =>
            val jsonParser = new JsonParser()
            val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
            jsonObject.get("account") == "iOS") //ERROR HERE

val patternStream = CEP.pattern(partitionedInput, pattern)
</code>```

I am getting an error at the val pattern = ... line saying Expected IterativeCondition[String], actual: (Nothing) => Unit.

My dataStream consists of JSON objects which I parse in the keyBy to key by the account key inside the JSON object. Then I am trying to create a pattern but I am getting an error when creating the pattern.

答:
Make sure you use the proper API. For scala you should import

```<code>import org.apache.flink.cep.scala.pattern.Pattern
</code>```

rather than

```<code>import org.apache.flink.cep.pattern.Pattern
</code>```

Body:
I have this Flink program below:

val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

val dataStream = env.addSource(new FlinkKafkaConsumer010[String](topicChannel1, new SimpleStringSchema(), props))

val partitionedInput = dataStream.keyBy(jsonString => {
  val jsonParser = new JsonParser()
  val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
  jsonObject.get("account")
})

val pattern = Pattern.begin[String]("start").where(jsonString =>
            val jsonParser = new JsonParser()
            val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
            jsonObject.get("account") == "iOS") //ERROR HERE

val patternStream = CEP.pattern(partitionedInput, pattern)

I am getting an error at the val pattern = ... line saying Expected IterativeCondition[String], actual: (Nothing) => Unit.

My dataStream consists of JSON objects which I parse in the keyBy to key by the account key inside the JSON object. Then I am trying to create a pattern but I am getting an error when creating the pattern.

Body:
Make sure you use the proper API. For scala you should import

import org.apache.flink.cep.scala.pattern.Pattern

rather than

import org.apache.flink.cep.pattern.Pattern