问:
Got duplicate key error dup key: { : undefined }
I have an array field called udids in Meteor.users schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:

```<code>new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})
</code>```

However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }.

I tried searching for the documents with udids = undefined in the database: db.users.find({ udids: { $type: 6 } }) ($type: 6 for undefined value) but it returns nothing.

答:
I've not tested this, but it should ideally work.

Used Meteor.users as a collection name. You may want to replace it with whichever collection you want to run the validation against.

Made use of custom function to find at least one doc which contains the field's value in udids.

If you don't have access to the collection on the client side, then you can edit the custom function and have it handled asynchronously.

```<code>new SimpleSchema({
            ...
            'udids': {
                optional: true,
                type: [String], // an array of string eg. ['A','B']
                custom: function() {

                    // this.value = current field's value
                    // Below mongo query will check to see if there is at least one
                    // mongo doc whose udids contains the currently entered field's value.
                    // if found, then return the error message.

                    if (Meteor.users.findOne({
                            udids: {
                                $in: [this.value]
                            }
                        })) {
                        return "duplicateMsg";
                    }
                },
                ...
     });

SimpleSchema.messages({ duplicateMsg:"Udid already exists"});
</code>```

Body:
I have an array field called udids in Meteor.users schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:

new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})

However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }.

I tried searching for the documents with udids = undefined in the database: db.users.find({ udids: { $type: 6 } }) ($type: 6 for undefined value) but it returns nothing.

Body:
I've not tested this, but it should ideally work.

Used Meteor.users as a collection name. You may want to replace it with whichever collection you want to run the validation against.

Made use of custom function to find at least one doc which contains the field's value in udids.

If you don't have access to the collection on the client side, then you can edit the custom function and have it handled asynchronously.

new SimpleSchema({
            ...
            'udids': {
                optional: true,
                type: [String], // an array of string eg. ['A','B']
                custom: function() {

                    // this.value = current field's value
                    // Below mongo query will check to see if there is at least one
                    // mongo doc whose udids contains the currently entered field's value.
                    // if found, then return the error message.

                    if (Meteor.users.findOne({
                            udids: {
                                $in: [this.value]
                            }
                        })) {
                        return "duplicateMsg";
                    }
                },
                ...
     });

SimpleSchema.messages({ duplicateMsg:"Udid already exists"});


来源: stackexchange

问:
SqlConnection Class is missing from Xamarin.Android
Sir,

Made an activity page and declared System.Data.SqlClient to connect it with MSSQL. Then I have declared SqlConnection class, but it showing me error as The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)

below is .xaml code :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text="Enter First Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1" />
    <TextView
        android:text="Enter Last Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText2" />
    <TextView
        android:text="Enter Contact No"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView3" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText3" />
    <Button
        android:text="Save Data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/saveDatabtn1" />
</LinearLayout>
</code>```

.cs code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace MobAppDB
{
    [Activity(Label = "InsertData_Act")]
    public class InsertData_Act : Activity
    {
        static string Constr = "Data Source=HP-PC;Initial Catalog=UserMobileData;User Id=sa;Password=sa@123;";

        //Connection Class
        SqlConnection con = new SqlConnection(Constr);

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //Initialize Controls
            SetContentView(Resource.Layout.InsertData);
            Button butt = FindViewById<Button>(Resource.Id.saveDatabtn1);
            butt.Click += saveDatabtn1_Click;

        }

        private void saveDatabtn1_Click(object sender, System.EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {

            }
        }

    }
}
</code>```

答:
Mysql support for Xamarin.android ? I don't think you are really looking MYSql db which has to be access remotely as none of the platform supports it .

I think what you are looking for is SQLite db not Mysql.

Sqlite is light weight database made for mobile platform.

and the class name you are looking for is.

SQLiteConnection.

More on this you can read from
https://developer.xamarin.com/recipes/android/data/databases/sqlite/

Realm db is another best approach for offline data storage which requires no SQL knowledge.

But you are really looking to support Mysql db in Xamarin.android. Go for it . I won't recommend it at all

https://components.xamarin.com/view/mysql-plugin

ContentLicense: CC BY-SA 3.0

Body:
Sir,

Made an activity page and declared System.Data.SqlClient to connect it with MSSQL. Then I have declared SqlConnection class, but it showing me error as The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)

below is .xaml code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView
        android:text="Enter First Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView1" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1" />
    <TextView
        android:text="Enter Last Name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText2" />
    <TextView
        android:text="Enter Contact No"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView3" />
    <EditText
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText3" />
    <Button
        android:text="Save Data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/saveDatabtn1" />
</LinearLayout>

.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace MobAppDB
{
    [Activity(Label = "InsertData_Act")]
    public class InsertData_Act : Activity
    {
        static string Constr = "Data Source=HP-PC;Initial Catalog=UserMobileData;User Id=sa;Password=sa@123;";

        //Connection Class
        SqlConnection con = new SqlConnection(Constr);

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //Initialize Controls
            SetContentView(Resource.Layout.InsertData);
            Button butt = FindViewById<Button>(Resource.Id.saveDatabtn1);
            butt.Click += saveDatabtn1_Click;

        }

        private void saveDatabtn1_Click(object sender, System.EventArgs e)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {

            }
        }

    }
}


问:
Use Icon from shell32.dll as shortcut icon
I am trying to set the icon of a shortcut pointing to a folder, but cannot find any resources on how to set a shortcut icon to a native icon from shell32.dll. I found This answer on msdn by Rykler, but the answer is outdated. Any help would be appreciated.

Code

```<code>SHFILEINFO shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), (int)0x1000);
// icon index # and path
int IconIndex = shinfo.iIcon
string IconPath = shinfo.szDisplayName
shortcut.IconLocation = ???
</code>```

SHFILEINFO struct: (Taken from This question)

```<code>[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
    public IntPtr hIcon;
    public int iIcon;
    public uint dwAttributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
};

class Win32
{
    [DllImport("shell32.dll")]
    public static extern IntPtr SHGetFileInfo(string pszPath, uint
dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}
</code>```

答:
So, after a little research, it seems not too complicate. At first, take the interface declarations from this question. Include the declarations in your project.

After that, you can use this code:

```<code>public class Q47602417
{
    public static void MakeShortcut(string targetPath)
    {
        var shellLink = new ShellLink();
        ((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
        ((IShellLinkW)shellLink).SetPath(targetPath);
        ((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
        ((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
    }
}
</code>```

One thing to add: this sample contains no error checking! You don't know if the shortcut was created or not. So, change the called interface methods to return integers and add exception checking:

```<code>//...

int SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
int SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);

//.. omitted other details ...

int Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);
</code>```

Now you can check if creating the shortcut acutally works.

```<code>public class Q47602417
{

    public static void MakeShortcut(string targetPath)
    {
        ShellLink shellLink = new ShellLink();
        int hr;
        hr = ((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IShellLinkW)shellLink).SetPath(targetPath);
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
        Marshal.ThrowExceptionForHR(hr);
    }

}
</code>```

Example result:

Body:
I am trying to set the icon of a shortcut pointing to a folder, but cannot find any resources on how to set a shortcut icon to a native icon from shell32.dll. I found This answer on msdn by Rykler, but the answer is outdated. Any help would be appreciated.

Code

SHFILEINFO shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), (int)0x1000);
// icon index # and path
int IconIndex = shinfo.iIcon
string IconPath = shinfo.szDisplayName
shortcut.IconLocation = ???

SHFILEINFO struct: (Taken from This question)

[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
    public IntPtr hIcon;
    public int iIcon;
    public uint dwAttributes;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string szDisplayName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
};

class Win32
{
    [DllImport("shell32.dll")]
    public static extern IntPtr SHGetFileInfo(string pszPath, uint
dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}

Body:
So, after a little research, it seems not too complicate. At first, take the interface declarations from this question. Include the declarations in your project.

After that, you can use this code:

public class Q47602417
{
    public static void MakeShortcut(string targetPath)
    {
        var shellLink = new ShellLink();
        ((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
        ((IShellLinkW)shellLink).SetPath(targetPath);
        ((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
        ((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
    }
}

One thing to add: this sample contains no error checking! You don't know if the shortcut was created or not. So, change the called interface methods to return integers and add exception checking:

//...

int SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
int SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);

//.. omitted other details ...

int Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);

Now you can check if creating the shortcut acutally works.

public class Q47602417
{

    public static void MakeShortcut(string targetPath)
    {
        ShellLink shellLink = new ShellLink();
        int hr;
        hr = ((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IShellLinkW)shellLink).SetPath(targetPath);
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
        Marshal.ThrowExceptionForHR(hr);

        hr = ((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
        Marshal.ThrowExceptionForHR(hr);
    }

}

Example result:


问:
Where to place the 'assets' folder in Android Studio?
I am confused about the assets folder. It doesn't come auto-created in Android Studio, and almost all the forums in which this is discussed talk about Eclipse.

How can the Assets directory be configured in Android Studio?

答: File > New > folder > assets Folder

ContentLicense: CC BY-SA 4.0

Body: File > New > folder > assets Folder


问:
Using tHttpRequest to download an Excel File from Sharepoint with Authentication
I want to download an Excel file from Sharepoint and use it as input for a tFileInputExcel component. tHttpRequest seems to be the only component able to download files from a sharepoint server with authentication.

What of course works is to download the file via tHttpRequest, write the response  to a file, and load that file with the tFileInputExcel component.

Example, but I don't want it like that.

However, I do not want an intermediate file and use the "stream" functionality of the tFileInputExcel component. What I do not achieve is to convert the downloaded content into a stream that is usable by the excel component:

```<code>((java.io.InputStream)globalMap.get("what goes here? And where does it come from?"))
</code>```

Here's an example using the tFileFetch component, but this component is not able to download from sharepoint with authentication.

答:
I extended the tHttpRequest component and created tHttpRequestEx. The new component saves a ByteArrayInputStream to the global map which can be read from the tFileInputExcel component:

```<code>((java.io.ByteArrayInputStream)globalMap.get("tHttpRequestEx_1_INPUT_STREAM"))
</code>```

I uploaded the component on exchange.talend.com.

Of course this has the big disadvantage to use a non-standard component. It may be the better solution to stick with the file download, and use tCreateTemporaryFile to deal with the complexity of creating and deleting a file.

Body:
I want to download an Excel file from Sharepoint and use it as input for a tFileInputExcel component. tHttpRequest seems to be the only component able to download files from a sharepoint server with authentication.

What of course works is to download the file via tHttpRequest, write the response  to a file, and load that file with the tFileInputExcel component.

Example, but I don't want it like that.

However, I do not want an intermediate file and use the "stream" functionality of the tFileInputExcel component. What I do not achieve is to convert the downloaded content into a stream that is usable by the excel component:

((java.io.InputStream)globalMap.get("what goes here? And where does it come from?"))

Here's an example using the tFileFetch component, but this component is not able to download from sharepoint with authentication.

Body:
I extended the tHttpRequest component and created tHttpRequestEx. The new component saves a ByteArrayInputStream to the global map which can be read from the tFileInputExcel component:

((java.io.ByteArrayInputStream)globalMap.get("tHttpRequestEx_1_INPUT_STREAM"))

I uploaded the component on exchange.talend.com.

Of course this has the big disadvantage to use a non-standard component. It may be the better solution to stick with the file download, and use tCreateTemporaryFile to deal with the complexity of creating and deleting a file.


问:
coding, data migration and deployment process using jive
I am new to Jive, currently going through the documentation provided on https://docs.jivesoftware.com/.
what I am looking for is

Any specific editor to write code in jive x

How to migrate data into jive

Deployment process followed by jive. Like where to develop, test, deploy.

So anyone who has worked using jive, can provide some links/tips.

答:
There is no specific editor to write code for Jive. This is a personal preference which might also depend if you are writing a Plugin in Java or an Add-On in JS. I prefer to use IntelliJ in general.

The best option to migrate data into Jive is to use the REST API. It is important to rate-limit the requests to not overload the instance but the API should be able to handle a considerable number of requests, depending on the underlying infrastructure. You could in theory also use the DB to migrate data into Jive but that would require a deep knowledge of the Jive architecture and the chances of breaking something are high.

For development and early testing the best is a local instance, which you can setup following these steps. For full end-to-end testing the best is to have a UAT environment which replicates as much as possible the production instance/infrastructure.


问:
Converting between Swift and Objective C arrays
In my application I have some underlying legacy code written in Objective C, while the overlapping method is written in Swift.

Now the problem is that the Swift code uses Swift arrays [Int], but the Objective C methods require NSArray and NSMutableArray.

How to cast/convert between the different array types?

Swift code:

```<code>/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download([Any](self.remainingOrders)); // then remaining orders need to be passed as NSArray
}
</code>```

Objective C method signatures (should not be modified):

```<code>/* Filters orders that haven't been downloaded yet */
- (NSMutableArray *)filterRemainingOrdersFromOrders:(NSMutableArray *)orders;
/* Downloads orders */
- (void)download:(NSArray*)orders;
</code>```

答:
Here is my solution:</p>

```<code>/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as NSArray as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download(self.remainingOrders); // then remaining orders need to be passed as NSArray
}
</code>```

Body:
In my application I have some underlying legacy code written in Objective C, while the overlapping method is written in Swift.

Now the problem is that the Swift code uses Swift arrays [Int], but the Objective C methods require NSArray and NSMutableArray.

How to cast/convert between the different array types?

Swift code:

/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download([Any](self.remainingOrders)); // then remaining orders need to be passed as NSArray
}

Objective C method signatures (should not be modified):

/* Filters orders that haven't been downloaded yet */
- (NSMutableArray *)filterRemainingOrdersFromOrders:(NSMutableArray *)orders;
/* Downloads orders */
- (void)download:(NSArray*)orders;

Body:
Here is my solution:

/* The remaining orders are finally stored as [Int] */
static var remainingOrders:[Int]! = [Int]()

/* Handles the orders loaded event */
@objc static func ordersLoaded(notification:Notification) {
    let userInfo:Dictionary = notification.userInfo as! Dictionary<String, Any>
    let orders:NSArray = userInfo["orders"] as! NSArray // orders is of type NSArray
    let remainingOrders:NSMutableArray = orderUtils.filterRemainingOrders(fromOrders: orders.mutableCopy() as! NSMutableArray); // but it needs to be passed as NSMutableArray
    self.remainingOrders = remainingOrders as NSArray as! [Int]; // the NSMutableArray needs to be stored as [Int]
    downloadService.download(self.remainingOrders); // then remaining orders need to be passed as NSArray
}


问:
Konvajs layer positions not being set as expected
I have an app where I am panning and zooming multiple layers.

However, when I set the position of the layers they are being updated to the wrong values.

For instance, after calling:

```<code>layer.position({
    x: 12,
    y: 233,
});
</code>```

I would expect

```<code>layer.getClientRect();
</code>```

to return

```<code>{
  x: 12,
  y: 233,
}
</code>```

Instead it returns

```<code>{
  x: -22,
  y: 220,
}
</code>```

Is there any known reason this is happening?

答:
Seems to work for me as advertised in this cut down test. Did you move the stage or something ?

In the snippet below I draw a layer with 4 'corner' rects, display its value from grtClientRect() in 'Layer pos #1' which gives (0, 0), then move the stage to 12, 233 and display its value from grtClientRect() in 'Layer pos #2' which shows (12, 233). I move the layer back up to (12, 23) just for fun thereafter.

var stage = new Konva.Stage({
      container: 'container',
      width: 1600,
      height: 400
    });

// add a layer
var layer = new Konva.Layer();
stage.add(layer);

// add 4 corner rects - code I happened to have to hand
var rectCorner = [];
for (i=0;i<4;i=i+1){
  rectCorner[i] = new Konva.Rect({
        x: 0,
        y: 0,
        width: 50,
        height: 50,
        fill: 'red',
        opacity: 0.5,
        strokeWidth: 0})
    layer.add(rectCorner[i]);
}

// put the rects in the corners to give a known layer space
rectCorner[1].position({x:500, y: 0});
rectCorner[2].position({x:500, y: 150});
rectCorner[3].position({x:0, y: 150});
layer.draw();

// get the client rect now
var p = layer.getClientRect();
$('#info1').html('Layer pos #1=' + p.x + ', ' + p.y);

// move the layer...
layer.position({
    x: 12,
    y: 233,
});

// get the client rect now
var p = layer.getClientRect();
$('#info2').html('Layer pos #2=' + p.x + ', ' + p.y);

// move the layer back to the top...
layer.position({
    x: 12,
    y: 23,
});

stage.draw();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p
{
  padding: 4px;

}
#container
{
  background-color: silver;
  overflow: hidden;
}</code>```

    ```

Body:
I have an app where I am panning and zooming multiple layers.

However, when I set the position of the layers they are being updated to the wrong values.

For instance, after calling:

layer.position({
    x: 12,
    y: 233,
});

I would expect

layer.getClientRect();

to return

{
  x: 12,
  y: 233,
}

Instead it returns

{
  x: -22,
  y: 220,
}

Is there any known reason this is happening?

Body:
Seems to work for me as advertised in this cut down test. Did you move the stage or something ?

In the snippet below I draw a layer with 4 'corner' rects, display its value from grtClientRect() in 'Layer pos #1' which gives (0, 0), then move the stage to 12, 233 and display its value from grtClientRect() in 'Layer pos #2' which shows (12, 233). I move the layer back up to (12, 23) just for fun thereafter.

var stage = new Konva.Stage({
      container: 'container',
      width: 1600,
      height: 400
    });

// add a layer
var layer = new Konva.Layer();
stage.add(layer);

// add 4 corner rects - code I happened to have to hand
var rectCorner = [];
for (i=0;i<4;i=i+1){
  rectCorner[i] = new Konva.Rect({
        x: 0,
        y: 0,
        width: 50,
        height: 50,
        fill: 'red',
        opacity: 0.5,
        strokeWidth: 0})
    layer.add(rectCorner[i]);
}

// put the rects in the corners to give a known layer space
rectCorner[1].position({x:500, y: 0});
rectCorner[2].position({x:500, y: 150});
rectCorner[3].position({x:0, y: 150});
layer.draw();

// get the client rect now
var p = layer.getClientRect();
$('#info1').html('Layer pos #1=' + p.x + ', ' + p.y);

// move the layer...
layer.position({
    x: 12,
    y: 233,
});

// get the client rect now
var p = layer.getClientRect();
$('#info2').html('Layer pos #2=' + p.x + ', ' + p.y);

// move the layer back to the top...
layer.position({
    x: 12,
    y: 23,
});

stage.draw();

p
{
  padding: 4px;

}
#container
{
  background-color: silver;
  overflow: hidden;
}

<div id='info1'></div>
<div id='info2'></div>

  <div id="container"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/konvajs/konva/1.7.6/konva.min.js"></script>
    <script type="text/javascript" src="test.js"></script>


问:
how to read int,double,and sentence of string using same scanner variable
```<code>import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            String s=new String();
            int x=sc.nextInt();
            double y=sc.nextDouble();
            s = sc.next();

            System.out.println("String:"+s);
            System.out.println("Double: "+y);
            System.out.println("Int: "+x);
     }
}
</code>```

it scans only one word pleasd give any suggestions...

答:
You can try this code:

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

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();

    scan.nextLine();
    String s = scan.nextLine();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}
</code>```

Because the Scanner object will read the rest of the line where its previous read left off.

If there is nothing on the line, it simply consumes the newline and moves to the starting of the next line.

After double declaration, you have to write: scan.nextLine();

Body:
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            String s=new String();
            int x=sc.nextInt();
            double y=sc.nextDouble();
            s = sc.next();

            System.out.println("String:"+s);
            System.out.println("Double: "+y);
            System.out.println("Int: "+x);
     }
}

it scans only one word pleasd give any suggestions...

Body:
You can try this code:

import java.util.Scanner;

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = scan.nextInt();
    double d = scan.nextDouble();

    scan.nextLine();
    String s = scan.nextLine();

    System.out.println("String: " + s);
    System.out.println("Double: " + d);
    System.out.println("Int: " + i);
}

Because the Scanner object will read the rest of the line where its previous read left off.

If there is nothing on the line, it simply consumes the newline and moves to the starting of the next line.

After double declaration, you have to write: scan.nextLine();


问:
Add certain class depending on viewport width in Bootstrap
Is there any way to apply a specific class only on specific viewport width? (other than using media queries)

For example
Hello world
 would apply a margin-bottom all the time.

but what if I wanted to apply it only when the view port is larger than sm?

I am using Angular, so the solution could use Angular helpers.

答:
Not sure why you wouldn't want to use @media queries for this, I mean, that's what they're there for. But, if you must use an alternative method, you could detect viewport width with JS/TS and @HostListener to listen to the resize event, then use [ngClass] to apply the class.

Something like:

```<code>viewportWidth: number;

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.viewportWidth = event.target.innerWidth;
}

viewportIsGreaterThan(viewportWidth: number): boolean {
    return this.viewportWidth > viewportWidth;
}
</code>```

Then in your template:

```<code><div [ngClass]="{ 'mb-1' : viewportIsGreaterThan(499) }">Hello world</div>
</code>```

Body:
Not sure why you wouldn't want to use @media queries for this, I mean, that's what they're there for. But, if you must use an alternative method, you could detect viewport width with JS/TS and @HostListener to listen to the resize event, then use [ngClass] to apply the class.

Something like:

viewportWidth: number;

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.viewportWidth = event.target.innerWidth;
}

viewportIsGreaterThan(viewportWidth: number): boolean {
    return this.viewportWidth > viewportWidth;
}

Then in your template:

<div [ngClass]="{ 'mb-1' : viewportIsGreaterThan(499) }">Hello world</div>


问:
Splitting an array dynamically based on values using Javascript/jQuery

I'm trying to find an easier way of splitting an array dynamically based on values of an inner array within a JSON object.

Assume that I am receiving said data from OpenWeatherAPI:

 var jsonData={
    "cod":"200",
    "message":0.0895,
    "cnt":5,
    "list":[
      {
         "dt":1512388800,
         "main":{
            "temp":301.9,
            "temp_min":299.858,
            "temp_max":301.9,
            "pressure":1017.53,
            "sea_level":1020.58,
            "grnd_level":1017.53,
            "humidity":98,
            "temp_kf":2.04
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":80
         },
         "wind":{
            "speed":2.36,
            "deg":161.003
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 12:00:00"
      },
      {
         "dt":1512399600,
         "main":{
            "temp":300.75,
            "temp_min":299.389,
            "temp_max":300.75,
            "pressure":1019.04,
            "sea_level":1022.09,
            "grnd_level":1019.04,
            "humidity":100,
            "temp_kf":1.36
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":2.04,
            "deg":133.002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 15:00:00"
      },
      {
         "dt":1512410400,
         "main":{
            "temp":299.41,
            "temp_min":298.726,
            "temp_max":299.41,
            "pressure":1017.89,
            "sea_level":1020.93,
            "grnd_level":1017.89,
            "humidity":100,
            "temp_kf":0.68
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.08,
            "deg":108.001
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 18:00:00"
      },
      {
         "dt":1512421200,
         "main":{
            "temp":298.19,
            "temp_min":298.19,
            "temp_max":298.19,
            "pressure":1017.39,
            "sea_level":1020.45,
            "grnd_level":1017.39,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.26,
            "deg":94.0002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 21:00:00"
      },
      {
         "dt":1512432000,
         "main":{
            "temp":298.444,
            "temp_min":298.444,
            "temp_max":298.444,
            "pressure":1019.32,
            "sea_level":1022.39,
            "grnd_level":1019.32,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{
            "all":20
         },
         "wind":{
            "speed":2.5,
            "deg":89.0016
         },
         "rain":{

         },
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2017-12-05 00:00:00"
      }
    ],
    "city":{
      "id":1735158,
      "name":"Petaling Jaya",
      "coord":{
         "lat":3.1073,
         "lon":101.6067
      },
      "country":"MY"
     }
    }

 $.each(jsonData['list'], function(index, value) {

              $.each(value, function(index, value){
                if(index == 'dt_txt')
                {
                    var regExDate = new RegExp('^.{0,10}');
                    value = regExDate.exec(value).toString();
                    console.log(value);
                }
              });
     });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

How do I iterate the elements in list to split based on dt_txt?

This is pretty much as far as I got to manually convert the dates into YYYY-MM-DD format but I'm still struggling to make a dynamic array based out of the results that I'm getting:

Result:

EDIT #1:

The end result I'm looking for should look something like this:

```<code>var array20171204 = [{"dt":1512388800,"main":{"temp":301.9,"temp_min":299.858,"temp_max":301.9,"pressure":1017.53,"sea_level":1020.58,"grnd_level":1017.53,"humidity":98,"temp_kf":2.04},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":80},"wind":{"speed":2.36,"deg":161.003},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 12:00:00"},{"dt":1512399600,"main":{"temp":300.75,"temp_min":299.389,"temp_max":300.75,"pressure":1019.04,"sea_level":1022.09,"grnd_level":1019.04,"humidity":100,"temp_kf":1.36},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":68},"wind":{"speed":2.04,"deg":133.002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 15:00:00"},{"dt":1512410400,"main":{"temp":299.41,"temp_min":298.726,"temp_max":299.41,"pressure":1017.89,"sea_level":1020.93,"grnd_level":1017.89,"humidity":100,"temp_kf":0.68},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.08,"deg":108.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 18:00:00"},{"dt":1512421200,"main":{"temp":298.19,"temp_min":298.19,"temp_max":298.19,"pressure":1017.39,"sea_level":1020.45,"grnd_level":1017.39,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.26,"deg":94.0002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 21:00:00"}];

var array20171205 = [{"dt":1512432000,"main":{"temp":298.444,"temp_min":298.444,"temp_max":298.444,"pressure":1019.32,"sea_level":1022.39,"grnd_level":1019.32,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"clouds":{"all":20},"wind":{"speed":2.5,"deg":89.0016},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-05 00:00:00"}];
</code>```

答:
I did not understand the question completely but is this what you were looking for:</p>

```<code>var arr=[];
var list = jsonData['list'];
list.filter(function(item) {
    var temp = item.dt_txt.split(" ")[0];
    arr.push({[temp]: item});
});
</code>```

Body:
I'm trying to find an easier way of splitting an array dynamically based on values of an inner array within a JSON object.

Assume that I am receiving said data from OpenWeatherAPI:

 var jsonData={
    "cod":"200",
    "message":0.0895,
    "cnt":5,
    "list":[
      {
         "dt":1512388800,
         "main":{
            "temp":301.9,
            "temp_min":299.858,
            "temp_max":301.9,
            "pressure":1017.53,
            "sea_level":1020.58,
            "grnd_level":1017.53,
            "humidity":98,
            "temp_kf":2.04
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":80
         },
         "wind":{
            "speed":2.36,
            "deg":161.003
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 12:00:00"
      },
      {
         "dt":1512399600,
         "main":{
            "temp":300.75,
            "temp_min":299.389,
            "temp_max":300.75,
            "pressure":1019.04,
            "sea_level":1022.09,
            "grnd_level":1019.04,
            "humidity":100,
            "temp_kf":1.36
         },
         "weather":[
            {
               "id":803,
               "main":"Clouds",
               "description":"broken clouds",
               "icon":"04n"
            }
         ],
         "clouds":{
            "all":68
         },
         "wind":{
            "speed":2.04,
            "deg":133.002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 15:00:00"
      },
      {
         "dt":1512410400,
         "main":{
            "temp":299.41,
            "temp_min":298.726,
            "temp_max":299.41,
            "pressure":1017.89,
            "sea_level":1020.93,
            "grnd_level":1017.89,
            "humidity":100,
            "temp_kf":0.68
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.08,
            "deg":108.001
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 18:00:00"
      },
      {
         "dt":1512421200,
         "main":{
            "temp":298.19,
            "temp_min":298.19,
            "temp_max":298.19,
            "pressure":1017.39,
            "sea_level":1020.45,
            "grnd_level":1017.39,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02n"
            }
         ],
         "clouds":{
            "all":24
         },
         "wind":{
            "speed":2.26,
            "deg":94.0002
         },
         "rain":{

         },
         "sys":{
            "pod":"n"
         },
         "dt_txt":"2017-12-04 21:00:00"
      },
      {
         "dt":1512432000,
         "main":{
            "temp":298.444,
            "temp_min":298.444,
            "temp_max":298.444,
            "pressure":1019.32,
            "sea_level":1022.39,
            "grnd_level":1019.32,
            "humidity":100,
            "temp_kf":0
         },
         "weather":[
            {
               "id":801,
               "main":"Clouds",
               "description":"few clouds",
               "icon":"02d"
            }
         ],
         "clouds":{
            "all":20
         },
         "wind":{
            "speed":2.5,
            "deg":89.0016
         },
         "rain":{

         },
         "sys":{
            "pod":"d"
         },
         "dt_txt":"2017-12-05 00:00:00"
      }
    ],
    "city":{
      "id":1735158,
      "name":"Petaling Jaya",
      "coord":{
         "lat":3.1073,
         "lon":101.6067
      },
      "country":"MY"
     }
    }

 $.each(jsonData['list'], function(index, value) {

              $.each(value, function(index, value){
                if(index == 'dt_txt')
                {
                    var regExDate = new RegExp('^.{0,10}');
                    value = regExDate.exec(value).toString();
                    console.log(value);
                }
              });
     });

How do I iterate the elements in list to split based on dt_txt?

This is pretty much as far as I got to manually convert the dates into YYYY-MM-DD format but I'm still struggling to make a dynamic array based out of the results that I'm getting:

Result:

EDIT #1:

The end result I'm looking for should look something like this:

var array20171204 = [{"dt":1512388800,"main":{"temp":301.9,"temp_min":299.858,"temp_max":301.9,"pressure":1017.53,"sea_level":1020.58,"grnd_level":1017.53,"humidity":98,"temp_kf":2.04},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":80},"wind":{"speed":2.36,"deg":161.003},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 12:00:00"},{"dt":1512399600,"main":{"temp":300.75,"temp_min":299.389,"temp_max":300.75,"pressure":1019.04,"sea_level":1022.09,"grnd_level":1019.04,"humidity":100,"temp_kf":1.36},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"clouds":{"all":68},"wind":{"speed":2.04,"deg":133.002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 15:00:00"},{"dt":1512410400,"main":{"temp":299.41,"temp_min":298.726,"temp_max":299.41,"pressure":1017.89,"sea_level":1020.93,"grnd_level":1017.89,"humidity":100,"temp_kf":0.68},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.08,"deg":108.001},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 18:00:00"},{"dt":1512421200,"main":{"temp":298.19,"temp_min":298.19,"temp_max":298.19,"pressure":1017.39,"sea_level":1020.45,"grnd_level":1017.39,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":2.26,"deg":94.0002},"rain":{},"sys":{"pod":"n"},"dt_txt":"2017-12-04 21:00:00"}];

var array20171205 = [{"dt":1512432000,"main":{"temp":298.444,"temp_min":298.444,"temp_max":298.444,"pressure":1019.32,"sea_level":1022.39,"grnd_level":1019.32,"humidity":100,"temp_kf":0},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"clouds":{"all":20},"wind":{"speed":2.5,"deg":89.0016},"rain":{},"sys":{"pod":"d"},"dt_txt":"2017-12-05 00:00:00"}];

Body:
I did not understand the question completely but is this what you were looking for:

var arr=[];
var list = jsonData['list'];
list.filter(function(item) {
    var temp = item.dt_txt.split(" ")[0];
    arr.push({[temp]: item});
});


问:
Using "push", the url changes but my entire page goes blank
I am using mobx-react-router but I am having a problem when I use "push" the url changes but my entire page goes  blank. So I think maybe my components are not being re rendered or it is going to a totally new page.

versions

```<code>"mobx": "^3.1.16",
"mobx-react": "^4.2.2",
"mobx-react-devtools": "^4.2.15",
"mobx-react-router": "^4.0.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.1.1",
"babel": "^6.23.0",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"history": "^4.6.3",
"html-webpack-plugin": "^2.29.0",
"webpack": "^3.0.0",
"webpack-dev-server": "^2.5.0"
</code>```

webpack

```<code>  var HtmlWebpackPlugin = require('html-webpack-plugin');
  var path = require("path");
    module.exports = {
        entry: './src/app.js',
        output: {
            path: path.resolve(__dirname, "dist"),
            publicPath: "/",
            filename: 'app.bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                }, {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: 'babel-loader'
                }, {
                    test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }, {
                    test:  /\.(gif|png|jpe?g|svg)$/i,
                    loader: 'file-loader'
                }
            ]
        },
        devServer: {
            historyApiFallback: true
        },
        plugins: [new HtmlWebpackPlugin({template: './src/index.html'})]
    }
</code>```

App.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider  } from 'mobx-react';
import { useStrict } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'

import AppContainer from './components/AppContainer';

const browserHistory = createBrowserHistory();

import stores from '../src/stores/Stores';

const history = syncHistoryWithStore(browserHistory, stores.routingStore);

useStrict(true);

ReactDOM.render(
    <Provider {... stores}>
        <Router history={history}>
           <AppContainer />
        </Router>
    </Provider>,
       document.getElementById('root')
);
</code>```

Stores.js

```<code>import {RouterStore} from 'mobx-react-router';

const routingStore = new RouterStore();

const stores = {
    routingStore,
}

export default stores;
</code>```

AppContainer

```<code>import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {withRouter, Route} from 'react-router'
import MainComponent from '../components/MainComponent'
@withRouter
export default class AppContainer extends Component {
    constructor() {
        super();
    }
    render() {
        return (
            <div>
                 <Route exact path='/' component={MainComponent}/>
            </div>
        )
    }
}
</code>```

MainComponent

```<code>import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

import SecondComponent from './SecondComponent';
import ThirdComponent from './ThirdComponent';

@withRouter
@inject('routingStore')
@observer
export default class MainComponent extends Component {
    constructor() {
        super();
    }
    render() {
     return (
            <div>
                <h1>Main </h1>
                <SecondComponent />
                <Route path='/test/third/:id/data' component={ThirdComponent}/>

            </div>
        )
    }
}
</code>```

SecondComponent

```<code>import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

@inject('routingStore')
@observer
export default class SecondComponent extends Component {
    constructor() {
        super();
    }
    render() {
        const props = this.props;
        const {push} = this.props.routingStore;

     return (
            <div>
                <h1>Second2 </h1>
                <a  onClick={() =>  {push(`/test/third/1/data`);  }}>Render Third Component</a>
            </div>
        )
    }
}
</code>```

ThirdComponent

```<code>import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

@inject('routingStore')
@observer
export default class ThirdComponent extends Component {
    constructor() {
        super();
    }
    render() {
     return (
            <div>
                <h1>Third </h1>
            </div>
        )
    }
}
</code>```

答:
This is because in your AppContainer, you have added the exact property to the / route (<Route exact path='/' component={MainComponent}/>).

Therefore when you change the url to /test/third/:id/data, the path no longer exactly matches /, so the MainComponent unmounts.

Remove the exact prop and this should work fine.

Body:
I am using mobx-react-router but I am having a problem when I use "push" the url changes but my entire page goes  blank. So I think maybe my components are not being re rendered or it is going to a totally new page.

versions

"mobx": "^3.1.16",
"mobx-react": "^4.2.2",
"mobx-react-devtools": "^4.2.15",
"mobx-react-router": "^4.0.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.1.1",
"babel": "^6.23.0",
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"history": "^4.6.3",
"html-webpack-plugin": "^2.29.0",
"webpack": "^3.0.0",
"webpack-dev-server": "^2.5.0"

webpack

  var HtmlWebpackPlugin = require('html-webpack-plugin');
  var path = require("path");
    module.exports = {
        entry: './src/app.js',
        output: {
            path: path.resolve(__dirname, "dist"),
            publicPath: "/",
            filename: 'app.bundle.js'
        },
        module: {
            rules: [
                {
                    test: /\.s?css$/,
                    use: ['style-loader', 'css-loader', 'sass-loader']
                }, {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: 'babel-loader'
                }, {
                    test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }, {
                    test:  /\.(gif|png|jpe?g|svg)$/i,
                    loader: 'file-loader'
                }
            ]
        },
        devServer: {
            historyApiFallback: true
        },
        plugins: [new HtmlWebpackPlugin({template: './src/index.html'})]
    }

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider  } from 'mobx-react';
import { useStrict } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'

import AppContainer from './components/AppContainer';

const browserHistory = createBrowserHistory();

import stores from '../src/stores/Stores';

const history = syncHistoryWithStore(browserHistory, stores.routingStore);

useStrict(true);

ReactDOM.render(
    <Provider {... stores}>
        <Router history={history}>
           <AppContainer />
        </Router>
    </Provider>,
       document.getElementById('root')
);

Stores.js

import {RouterStore} from 'mobx-react-router';

const routingStore = new RouterStore();

const stores = {
    routingStore,
}

export default stores;

AppContainer

import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {withRouter, Route} from 'react-router'
import MainComponent from '../components/MainComponent'
@withRouter
export default class AppContainer extends Component {
    constructor() {
        super();
    }
    render() {
        return (

                 <Route exact path='/' component={MainComponent}/>

        )
    }
}

MainComponent

import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

import SecondComponent from './SecondComponent';
import ThirdComponent from './ThirdComponent';

@withRouter
@inject('routingStore')
@observer
export default class MainComponent extends Component {
    constructor() {
        super();
    }
    render() {
     return (

Main

                <SecondComponent />
                <Route path='/test/third/:id/data' component={ThirdComponent}/>

        )
    }
}

SecondComponent

import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

@inject('routingStore')
@observer
export default class SecondComponent extends Component {
    constructor() {
        super();
    }
    render() {
        const props = this.props;
        const {push} = this.props.routingStore;

     return (

Second2

                  {push(`/test/third/1/data`);  }}>Render Third Component

        )
    }
}

ThirdComponent

import React, {Component} from 'react'
import ReactDOM from 'react-dom';
import {observer, inject} from 'mobx-react';
import {withRouter, Route} from 'react-router'

@inject('routingStore')
@observer
export default class ThirdComponent extends Component {
    constructor() {
        super();
    }
    render() {
     return (

Third

        )
    }
}


问:
What are the differences between editor templates and partial views?
I am simply looking for how these two are different and what are their pros and cons?

It seems you can do all with partial views that you can do with templates.

答: if you mean "inline helpers", they are simply an easier way of building the equivalent of HtmlHelper extension methods - but they are only for use in the specific view.  partial views, on the other hand, can have more logic behind them (via their controller) without violating MVC and they can be easily reused from multiple views</p>

ContentLicense: CC BY-SA 2.5


问:
Bootstrap navbar issue, extra space
This is my website http://webninjas.eu/.
The problem with my navbar is extra space when I press "Get started" button from the top of the page or any element from navbar when the website is in mobile phone resolution.

Screen-shot of the problem.

I know that the problem is comming from z-index but I don't know how to fix.
The difference between 768 < resolution:

```<code>element.style {
    z-index: 1000;
    position: fixed;
    top: 0px;
    margin-left: 0px;
    width: 1035px;
    left: 0px;
}
</code>```

and resolution < 768:

```<code>element.style {
    z-index: auto;
    position: relative;
    top: 0px;
}
</code>```

I have tried to give 768 < resolution parameters to .main-nav-outer but the the results are not even close to what I need.

答:
It is because you have given offset of 102

```<code> $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top - 102
            }, 1500, 'easeInOutExpo');
</code>```

change this to 0

Title: Bootstrap navbar issue, extra space

Body:
This is my website http://webninjas.eu/.
The problem with my navbar is extra space when I press "Get started" button from the top of the page or any element from navbar when the website is in mobile phone resolution.

Screen-shot of the problem.

I know that the problem is comming from z-index but I don't know how to fix.
The difference between 768 < resolution:

element.style {
    z-index: 1000;
    position: fixed;
    top: 0px;
    margin-left: 0px;
    width: 1035px;
    left: 0px;
}

and resolution < 768:

element.style {
    z-index: auto;
    position: relative;
    top: 0px;
}

I have tried to give 768 < resolution parameters to .main-nav-outer but the the results are not even close to what I need.

Body:
It is because you have given offset of 102

 $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top - 102
            }, 1500, 'easeInOutExpo');

change this to 0


问:
Exclude a WooCommerce product category from a WP_Query
I've got the following args defined as a part of my query:

```<code>$args = apply_filters('woocommerce_related_products_args', array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
            array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
        )
    )
) );
$products = new WP_Query( $args );
</code>```

I need to exclude a category called Magazines (slug "magazines") or ID 351 from the query.

I've been trying to include 'category__not_in' => array('magazines'), so it looks like this:

```<code>$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines'),
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );
</code>```

But that just doesn't seem to be working.

What am I doing wrong here?

答:
You should use category__not_in value as an array like this

$query = new WP_Query( array( 'category__not_in' => array( 'magazines' ) ) );

For details check this

WP_Query

So please update your code into this

```<code>$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines')
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );
</code>```

Let me know whether its working or not for you.

Body:
I've got the following args defined as a part of my query:

$args = apply_filters('woocommerce_related_products_args', array(
        'post_type'             => 'product',
        'author'                => $artist,
        'post_status'           => 'publish',
        'meta_query'            => array(
            array(
                'key'           => '_visibility',
                'value'         => array('catalog', 'visible'),
                'compare'       => 'IN'
        )
    )
) );
$products = new WP_Query( $args );

I need to exclude a category called Magazines (slug "magazines") or ID 351 from the query.

I've been trying to include 'category__not_in' => array('magazines'), so it looks like this:

$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines'),
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );

But that just doesn't seem to be working.

What am I doing wrong here?

Body:
You should use category__not_in value as an array like this

$query = new WP_Query( array( 'category__not_in' => array( 'magazines' ) ) );

For details check this

WP_Query

So please update your code into this

$args = apply_filters('woocommerce_related_products_args', array(
            'post_type'             => 'product',
            'author'                => $artist,
            'post_status'           => 'publish',
            'category__not_in'      => array('magazines')
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
            )
        )
    ) );
    $products = new WP_Query( $args );

Let me know whether its working or not for you.


问:
Comparison Error While Converting C# to VB.NET
I am in the process of converting some c# code to that of VB.NET...I am running into error at the following

C#

```<code>if (bytes[i - 1] == ' ')
{
  returnValue.Append("=20");
}
else if (bytes[i - 1] == '\t')
{
  returnValue.Append("=09");
}
</code>```

VB.NET

```<code>If bytes(i - 1) = " "C Then <==error Operator "=" is not defined for types 'Byte' and 'Char'

   returnValue.Append("=20")
ElseIf bytes(i - 1) = ControlChars.Tab Then <==error Operator "=" is not defined for types 'Byte' and 'Char'
   returnValue.Append("=09")
End If
</code>```

答:
Just try using

```<code>Convert.ToChar(bytes(i - 1)) = " "C
</code>```

or

```<code>bytes(i - 1) = Convert.ToByte(" "C)
</code>```

Body:
I am in the process of converting some c# code to that of VB.NET...I am running into error at the following

C#

if (bytes[i - 1] == ' ')
{
  returnValue.Append("=20");
}
else if (bytes[i - 1] == '\t')
{
  returnValue.Append("=09");
}

VB.NET

If bytes(i - 1) = " "C Then <==error Operator "=" is not defined for types 'Byte' and 'Char'

   returnValue.Append("=20")
ElseIf bytes(i - 1) = ControlChars.Tab Then <==error Operator "=" is not defined for types 'Byte' and 'Char'
   returnValue.Append("=09")
End If

Body:
Just try using

Convert.ToChar(bytes(i - 1)) = " "C

or

bytes(i - 1) = Convert.ToByte(" "C)


问:
Jorani / presence.php - Invalid argument supplied for foreach()
After installing, we found an error. How to solve it?

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: hr/presence.php

Line Number: 268

```<code><?php foreach ($summary as $key => $value) { ?>
</code>```

答:
This error appears when the employee has no contract. So you can solve this error by editing the employee causing the error (from HR, list of employees: right click on the employee and choose edit into the context menu) and affecting him a contract.

If you don't have any contract, please start to create a contract from HR menu, list of contracts.

You can get help by joining the Google group of Jorani users: https://groups.google.com/forum/#!forum/jorani

Body:
After installing, we found an error. How to solve it?

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: hr/presence.php

Line Number: 268

<?php foreach ($summary as $key => $value) { ?>


问:
Unsupported operand types in php

if ($opt_selected=="y")
     {
        # code...

          $errorMessage = "";
         $phone = $_POST['phone'];
         $myString = $phone;
         $myArray = explode(',', $myString);
         print_r($myArray);

          if ($errorMessage != "" )
          {
                    echo "
" .$errorMessage. "
" ;

          }
              else

         {
             $max_id=mysqli_query($db,"select max(id) from batch");
             $row = mysqli_fetch_array($max_id);
      //error is for below line :Unsupported operand types
                    $row=$row+1;

                     $res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES (row,'$myArrays')");

                     $delete = mysqli_query($db,'insert into to_numbers_hist select * from to_numbers');
                     $delete = mysqli_query($db,'delete from to_numbers');

            foreach ($myArrays as $myArray) {

                   $ins="INSERT INTO `codexworld`.`to_numbers`(`batch_id`,`phone`)
            VALUES ('$id','$phone')";
            $test=mysqli_query($db,$ins) or die(mysqli_error($db));
            if($test)
            echo "";
            else
            echo "";

            }
/

         }```

Here its giving error like this
Unsupported operand types

so i'm not getting what to do ,please let me correct where i'm wrong

and the for-each loop is it correct no

here i'm entering number in text-box separated by comma ,by splitting those commas and storing into db with generating id we are referring this id in another table
so what i need to do to overcome this problem,

//error is for below line :Unsupported operand types

                    $row=$row+1;

this line giving error

答:
Your $row variable contains an array as you return the data from MySQL using:

```<code>$row = mysqli_fetch_array($max_id);
</code>```

+1 is simply not available for an array. Instead create a variable like $rc=0; (for row count) and increment it in your loop.

It also doesn't make sense to do:

```<code>$res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES (row,'$myArrays')");
</code>```

Your row should most likely be called $row but then you would try to save an array into a numeric column, same applies for the $myArrays variable.

I would recommend to first get yourself familiar with MySQL queries and also take more care about good code quality before continuing on your project.

Title: Unsupported operand types in php

Body:
if ($opt_selected=="y")
     {
        # code...

          $errorMessage = "";
         $phone = $_POST['phone'];
         $myString = $phone;
         $myArray = explode(',', $myString);
         print_r($myArray);

          if ($errorMessage != "" )
          {
                    echo "
" .$errorMessage. "
" ;

          }
              else

         {
             $max_id=mysqli_query($db,"select max(id) from batch");
             $row = mysqli_fetch_array($max_id);
      //error is for below line :Unsupported operand types
                    $row=$row+1;

                     $res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES (row,'$myArrays')");

                     $delete = mysqli_query($db,'insert into to_numbers_hist select * from to_numbers');
                     $delete = mysqli_query($db,'delete from to_numbers');

            foreach ($myArrays as $myArray) {

                   $ins="INSERT INTO `codexworld`.`to_numbers`(`batch_id`,`phone`)
            VALUES ('$id','$phone')";
            $test=mysqli_query($db,$ins) or die(mysqli_error($db));
            if($test)
            echo "";
            else
            echo "";

            }
/

         }

Here its giving error like this
Unsupported operand types

so i'm not getting what to do ,please let me correct where i'm wrong

and the for-each loop is it correct no

here i'm entering number in text-box separated by comma ,by splitting those commas and storing into db with generating id we are referring this id in another table
so what i need to do to overcome this problem,

//error is for below line :Unsupported operand types

                    $row=$row+1;

this line giving error

Body:
Your $row variable contains an array as you return the data from MySQL using:

$row = mysqli_fetch_array($max_id);

+1 is simply not available for an array. Instead create a variable like $rc=0; (for row count) and increment it in your loop.

It also doesn't make sense to do:

$res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES (row,'$myArrays')");

Your row should most likely be called $row but then you would try to save an array into a numeric column, same applies for the $myArrays variable.

I would recommend to first get yourself familiar with MySQL queries and also take more care about good code quality before continuing on your project.


问:
How to remove the gap between navigation icon and toolbar logo?
How can I remove the margin between the navigation icon and toolbar logo.

My toolbar layout

```<code><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/paper9patch"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/toolbarTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">

</android.support.v7.widget.Toolbar>
</code>```

I am inserting logo like this

```<code>   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   toolbar.setContentInsetStartWithNavigation(0);
   getSupportActionBar().setDisplayShowTitleEnabled(false);
   getSupportActionBar().setLogo(R.drawable.sample);
</code>```

my toolbar is looking like this

the logo is almost showing in the middle I want it beside the drawer icon

I searched on stackover flow and all answers tell to use

```<code>app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
</code>```

but its not working . I can say there is no padding for the image it is cropped exactly to edges. If i use tile there is no gap in middle ,the gap appears only when inserted logo.

Is this intended behavior ? Is there any thing else I can do to remove the gap?

Edit : styles i am using

```<code>    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    </style>

   <style name="toolbarTheme" parent="AppTheme">

    <item name="android:textColorPrimary">@color/themeColor</item>
    <item name="android:textColorSecondary">@color/themeColor</item>

    </style>

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</code>```

答:
The Problem was with the image , It did not had any extra space or padding at side but the image resolution was higher .

Solution is :

Just decrease the image resolution of logo and every thing should work normally.

Body:
How can I remove the margin between the navigation icon and toolbar logo.

My toolbar layout

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/paper9patch"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/toolbarTheme"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">

</android.support.v7.widget.Toolbar>

I am inserting logo like this

   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   toolbar.setContentInsetStartWithNavigation(0);
   getSupportActionBar().setDisplayShowTitleEnabled(false);
   getSupportActionBar().setLogo(R.drawable.sample);

my toolbar is looking like this

the logo is almost showing in the middle I want it beside the drawer icon

I searched on stackover flow and all answers tell to use

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"

but its not working . I can say there is no padding for the image it is cropped exactly to edges. If i use tile there is no gap in middle ,the gap appears only when inserted logo.

Is this intended behavior ? Is there any thing else I can do to remove the gap?

Edit : styles i am using


问:
Serverside id_token with Auth_0
I'm somewhat confused with the way I am supposed to handle user information on the server side when using Token-Based Authentication.

I'm building a RESTful Single Page App using React and Flask and I'd like to use an authentication provider as Auth0.

The way I see it, this is the user's workflow:

Enters email + password on the client side

Auth0 confirms this and returns a jwt that is stored in localStorage

When the user posts or gets data from my server, the jwt is sent along the request

The server checks with Auth0 that this token is valid

If this token is valid, then it processes the user's request

What I do not get is how the user's data fits in this pattern, for instance their email address to log a change in my database:

Is it returned at step 2 (the id_token?) and should be passed along as claims in step 3 ?

Or should it be fetched at step 4 when the server checks for the received token?

Thanks for your help!

答:
Yes, if you have the default settings for the client in Auth0 this information regarding the user should be inside your id_token. If you use the JWT debugger at jwt.io and paste your id_token into the encoded section, the right hand side will show the contents of your token.

What this basically does is decode the token. You'll have to do the same thing in your application to use the user's name, email, email_verified, ...

A common practice is to decode the token once (in the front end), when the user logs in. Store this information in a global variable so it's usable throughout your application.

For use in the backend (Python), simple decode decode the token with pyjwt

You'll probably want to use the jsonwebtoken library for handling the decoding in the frontend.

Title: Serverside id_token with Auth_0


问:
Retrofit Post method Without any Argument in android
how can I use post method in retrofit without argument in android, </p>

```<code>@FormUrlEncoded
@POST("/attendanceJson.aspx")
void atendance(Callback<Atendance> callback);
</code>```

答:
```<code>@POST("Common/GetPanelCounts")
Observable<CountPanelDTO> getPanelCounts();

 Observable<CountPanelDTO> listObservable = mApiService.getPanelCounts();
                subscribe(listObservable, dto -> view.setNotificationPanel(dto), new Consumer<Throwable>()
                    {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        view.setNotificationPanel(null);
                    }
                });
</code>```

Body:
how can I use post method in retrofit without argument in android,

@FormUrlEncoded
@POST("/attendanceJson.aspx")
void atendance(Callback<Atendance> callback);


问:
Hyperledger Fabric peer container cannot communicate with couchdb container
I am trying to configure hyperledger fabric network.
I run three zookeepers, three kafkas, three orderers and a couchdb.
They are docker containers and work well. All containers are in the same docker network called ibknet.
After that, I run peer container but it has a problem to detect couchdb container while its starting. Here is my command to run peer container.

docker run -d --name main.stock.ibk.com --hostname main.stock.ibk.com \
-p 7051:7051 \
-p 7053:7053 \
-e CORE_LEDGER_STATE_STATEDATABASE=CouchDB \
-e CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb0:5984 \
--network ibknet hyperledger/fabric-peer:x86_64-1.0.4

Here is the list of running docker containers before executing the command above.

```<code>0b49e1d9e135        hyperledger/fabric-couchdb:x86_64-1.0.4     "tini -- /docker-e..."   28 minutes ago      Up 28 minutes               4369/tcp, 5984/tcp, 9100/tcp   couchdb0
592e81a721f1        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:9050->7050/tcp         orderer2
5a0d0f05770d        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:8050->7050/tcp         orderer1
681894ae835a        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:7050->7050/tcp         orderer0
2c1910c3e293        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   28 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka2
b27ff82abd3d        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   29 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka1
2f84d000c2d6        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   29 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka0
25438ef57579        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper2
c01262ae099e        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper1
f95e92b10b25        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper0
</code>```

And I got this error messages in docker logs when I run the peer container.

```<code>2017-12-01 07:26:34.238 UTC [ledgermgmt] initialize -> INFO 002 Initializing ledger mgmt
2017-12-01 07:26:34.238 UTC [kvledger] NewProvider -> INFO 003 Initializing ledger provider
2017-12-01 07:26:34.624 UTC [couchdb] handleRequest -> WARN 004 Retrying couchdb request in 125ms. Attempt:1  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:34.987 UTC [couchdb] handleRequest -> WARN 005 Retrying couchdb request in 250ms. Attempt:2  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:35.533 UTC [couchdb] handleRequest -> WARN 006 Retrying couchdb request in 500ms. Attempt:3  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:36.279 UTC [couchdb] handleRequest -> WARN 007 Retrying couchdb request in 1s. Attempt:4  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:37.617 UTC [couchdb] handleRequest -> WARN 008 Retrying couchdb request in 2s. Attempt:5  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:39.819 UTC [couchdb] handleRequest -> WARN 009 Retrying couchdb request in 4s. Attempt:6  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:44.019 UTC [couchdb] handleRequest -> WARN 00a Retrying couchdb request in 8s. Attempt:7  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:52.279 UTC [couchdb] handleRequest -> WARN 00b Retrying couchdb request in 16s. Attempt:8  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:27:08.515 UTC [couchdb] handleRequest -> WARN 00c Retrying couchdb request in 32s. Attempt:9  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:27:40.730 UTC [couchdb] handleRequest -> WARN 00d Retrying couchdb request in 1m4s. Attempt:10  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
panic: Error in instantiating ledger provider: Unable to connect to CouchDB, check the hostname and port: Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
</code>```

What do I miss? And I have no idea that where 75.126.101.240 address is from.

Actually, I could succeed in running it with --add-host option by mentioning exactly ip. But I don't think that is a proper way because ip is changing whenever I start docker servers.

Please help this issue. Thanks.

答: Try adding : "--dns-search ." to the docker run command. The resolver on your host system is likely configured to append / search a domain for unknown hosts. "--dns-search ." should force resolution only via the embedded Docker DNS</p>

Body:
I am trying to configure hyperledger fabric network.
I run three zookeepers, three kafkas, three orderers and a couchdb.
They are docker containers and work well. All containers are in the same docker network called ibknet.
After that, I run peer container but it has a problem to detect couchdb container while its starting. Here is my command to run peer container.

docker run -d --name main.stock.ibk.com --hostname main.stock.ibk.com \
-p 7051:7051 \
-p 7053:7053 \
-e CORE_LEDGER_STATE_STATEDATABASE=CouchDB \
-e CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb0:5984 \
--network ibknet hyperledger/fabric-peer:x86_64-1.0.4

Here is the list of running docker containers before executing the command above.

0b49e1d9e135        hyperledger/fabric-couchdb:x86_64-1.0.4     "tini -- /docker-e..."   28 minutes ago      Up 28 minutes               4369/tcp, 5984/tcp, 9100/tcp   couchdb0
592e81a721f1        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:9050->7050/tcp         orderer2
5a0d0f05770d        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:8050->7050/tcp         orderer1
681894ae835a        hyperledger/fabric-orderer:x86_64-1.0.4     "orderer"                28 minutes ago      Up 28 minutes               0.0.0.0:7050->7050/tcp         orderer0
2c1910c3e293        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   28 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka2
b27ff82abd3d        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   29 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka1
2f84d000c2d6        hyperledger/fabric-kafka:x86_64-1.0.4       "/docker-entrypoin..."   29 minutes ago      Up 28 minutes               9092-9093/tcp                  kafka0
25438ef57579        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper2
c01262ae099e        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper1
f95e92b10b25        hyperledger/fabric-zookeeper:x86_64-1.0.4   "/docker-entrypoin..."   29 minutes ago      Up 29 minutes               2181/tcp, 2888/tcp, 3888/tcp   zookeeper0

And I got this error messages in docker logs when I run the peer container.

2017-12-01 07:26:34.238 UTC [ledgermgmt] initialize -> INFO 002 Initializing ledger mgmt
2017-12-01 07:26:34.238 UTC [kvledger] NewProvider -> INFO 003 Initializing ledger provider
2017-12-01 07:26:34.624 UTC [couchdb] handleRequest -> WARN 004 Retrying couchdb request in 125ms. Attempt:1  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:34.987 UTC [couchdb] handleRequest -> WARN 005 Retrying couchdb request in 250ms. Attempt:2  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:35.533 UTC [couchdb] handleRequest -> WARN 006 Retrying couchdb request in 500ms. Attempt:3  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:36.279 UTC [couchdb] handleRequest -> WARN 007 Retrying couchdb request in 1s. Attempt:4  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:37.617 UTC [couchdb] handleRequest -> WARN 008 Retrying couchdb request in 2s. Attempt:5  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:39.819 UTC [couchdb] handleRequest -> WARN 009 Retrying couchdb request in 4s. Attempt:6  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:44.019 UTC [couchdb] handleRequest -> WARN 00a Retrying couchdb request in 8s. Attempt:7  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:26:52.279 UTC [couchdb] handleRequest -> WARN 00b Retrying couchdb request in 16s. Attempt:8  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:27:08.515 UTC [couchdb] handleRequest -> WARN 00c Retrying couchdb request in 32s. Attempt:9  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
2017-12-01 07:27:40.730 UTC [couchdb] handleRequest -> WARN 00d Retrying couchdb request in 1m4s. Attempt:10  Error:Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused
panic: Error in instantiating ledger provider: Unable to connect to CouchDB, check the hostname and port: Get http://couchdb0:5984/: dial tcp 75.126.101.240:5984: getsockopt: connection refused

What do I miss? And I have no idea that where 75.126.101.240 address is from.

Actually, I could succeed in running it with --add-host option by mentioning exactly ip. But I don't think that is a proper way because ip is changing whenever I start docker servers.

Please help this issue. Thanks.


问:
Advanced transparency in a form
Im looking for a way to create form(s) similar in style to the following two..

Ive played with transparency keys, the windows API, but have not successfully done this in Windows Forms.

[broken image]

what im looking for with this post is any references to articles explaining how this can be done, or some code examples. -- but i will accept any kind of input.

I would use Windows Vista/7 Areo glass if it didnt have such horrible alpha-blending issues.

答:
I think you want to adjust the Opacity of the Form.

See this example

Title: Advanced transparency in a form


问:
Format Time from the json Result in angular2
I am trying to format the time from the json result. Here is my code

```<code>if (Object.keys(billNoData).length > 0) {
          for (var x in billNoData) {
               this.dayByBillNoExport.push({
                     'Time': this.datePipe.transform(billNoData[x].BillTime, 'HH:mm'),
                     })
               }
       }
</code>```

I would like to have the time to stored in the array as 14:37.

But I get the below error

```<code>ERROR Error: InvalidPipeArgument: '14:37:04' for pipe 'DatePipe'
at invalidPipeArgumentError (invalid_pipe_argument_error.ts:1)
at DatePipe.transform (date_pipe.ts:91)
at SafeSubscriber.eval [as _next] (sales.component.ts:273)
at SafeSubscriber.__tryOrUnsub (Subscriber.ts:238)
at SafeSubscriber.next (Subscriber.ts:190)
at Subscriber._next (Subscriber.ts:135)
at Subscriber.next (Subscriber.ts:95)
at CatchSubscriber.Subscriber._next (Subscriber.ts:135)
at CatchSubscriber.Subscriber.next (Subscriber.ts:95)
at MapSubscriber._next (map.ts:80)
</code>```

I have imported the DatePipe too.

```<code>import { DatePipe } from '@angular/common';
</code>```

Can someone please help me with this.

答: You passed the wrong arguments "HH:mm" in transform method. Please refer https://angular.io/api/common/DatePipe link.</p>

Body:
I am trying to format the time from the json result. Here is my code

if (Object.keys(billNoData).length > 0) {
          for (var x in billNoData) {
               this.dayByBillNoExport.push({
                     'Time': this.datePipe.transform(billNoData[x].BillTime, 'HH:mm'),
                     })
               }
       }

I would like to have the time to stored in the array as 14:37.

But I get the below error

ERROR Error: InvalidPipeArgument: '14:37:04' for pipe 'DatePipe'
at invalidPipeArgumentError (invalid_pipe_argument_error.ts:1)
at DatePipe.transform (date_pipe.ts:91)
at SafeSubscriber.eval [as _next] (sales.component.ts:273)
at SafeSubscriber.__tryOrUnsub (Subscriber.ts:238)
at SafeSubscriber.next (Subscriber.ts:190)
at Subscriber._next (Subscriber.ts:135)
at Subscriber.next (Subscriber.ts:95)
at CatchSubscriber.Subscriber._next (Subscriber.ts:135)
at CatchSubscriber.Subscriber.next (Subscriber.ts:95)
at MapSubscriber._next (map.ts:80)

I have imported the DatePipe too.

import { DatePipe } from '@angular/common';

Can someone please help me with this.


问:
Xcode Error - Undefined symbols for architecture x86_64?
I'm running Swift 4 and Xcode 9 beta. I get this errors and I have no idea how to solve it. I don't even know what does that mean..

```<code>Undefined symbols for architecture x86_64:
"__T0So22AVCapturePhotoSettingsC12AVFoundation01_abC16SwiftNativeTypesACWP", referenced from:
      __T014InstagramClone26CustomCameraViewControllerC23cameraBtn_TouchUpInsideyypF in CustomCameraViewController.o
  "__T012AVFoundation39_AVCapturePhotoSettingsSwiftNativeTypesPAAE016availablePreviewc11PixelFormatG0Says6UInt32VGfg", referenced from:
      __T014InstagramClone26CustomCameraViewControllerC23cameraBtn_TouchUpInsideyypF in CustomCameraViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Any idea how to solve this?

答:
On my case, I've called settings = AVCapturePhotoSettings() and I got that error.

Eventually the solution was calling a different initialiser. i.e:

```<code>settings = AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecType.jpeg])
</code>```

Body:
I'm running Swift 4 and Xcode 9 beta. I get this errors and I have no idea how to solve it. I don't even know what does that mean..

Undefined symbols for architecture x86_64:
"__T0So22AVCapturePhotoSettingsC12AVFoundation01_abC16SwiftNativeTypesACWP", referenced from:
      __T014InstagramClone26CustomCameraViewControllerC23cameraBtn_TouchUpInsideyypF in CustomCameraViewController.o
  "__T012AVFoundation39_AVCapturePhotoSettingsSwiftNativeTypesPAAE016availablePreviewc11PixelFormatG0Says6UInt32VGfg", referenced from:
      __T014InstagramClone26CustomCameraViewControllerC23cameraBtn_TouchUpInsideyypF in CustomCameraViewController.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any idea how to solve this?

Body:
On my case, I've called settings = AVCapturePhotoSettings() and I got that error.

Eventually the solution was calling a different initialiser. i.e:

settings = AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecType.jpeg])


答:
$row is a resultset . You cannot do $row +1 operation on a resultset

```<code>if ($row) {
      while($data = mysql_fetch_array($data)) {

           $value=$data[max(id)];
           $value=$value+1;

      }

    }
    else {
      echo mysql_error();
    }
</code>```

Use the retrived data $value for your operations

Also change the following too. You had missed $ sign

```<code>$res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES ($row,'$myArrays')");
</code>```

I also doubts what you mean by this line of code

```<code>$delete = mysqli_query($db,'insert into to_numbers_hist select * from to_numbers');
</code>```

Title: Unsupported operand types in php

Body:
$row is a resultset . You cannot do $row +1 operation on a resultset

if ($row) {
      while($data = mysql_fetch_array($data)) {

           $value=$data[max(id)];
           $value=$value+1;

      }

    }
    else {
      echo mysql_error();
    }

Use the retrived data $value for your operations

Also change the following too. You had missed $ sign

$res=mysqli_query($db,"INSERT INTO batch(`id`,`phone`) VALUES ($row,'$myArrays')");

I also doubts what you mean by this line of code

$delete = mysqli_query($db,'insert into to_numbers_hist select * from to_numbers');


问:
Regsvr32 not exiting
I'm registering a dll using regsvr32, after registering is successful regsvr32 still remains in task manager so i'm not able to register another dll without killing it.
I took over the work from someone else, so where should i start looking for in the program that generated dll to fix the problem.</p>

答: Regsvr32 just load the dll and call a specific exported function, so the "hang" is probably not related with Regsvr32 itself, but with the dll you are trying to register.</p>

Title: Regsvr32 not exiting


问:
Is it possible to hide a .glade file from user in GTK?
I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?</p>

答: Yes, that's possible. Give a look to the GResource documentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.</p>