问:
Issue with a SELECT statement within a IN
I'm trying to select a bunch of rows from my first table depending of values from my second table.

To realize that, I came up with the following query :

```<code>SELECT *

FROM table2 t2
WHERE t2.id IN(

    SELECT subquery.id

    FROM
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=10 AND t1.value=0)

    ) AS subquery

    INNER JOIN
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=20 AND i.value=1)

    ) AS subquery2

    on subquery.id=subquery2.id

)
</code>```

Depending of the property and value from table1, a specific list of id will be selected to be used as a condition for the final SELECT with the table2.

The subquery in itself is working, I tested it and I could retrieve the good  id.

```<code>+------+
|  id  |
|------|
|  18  |
|  55  |
¦      ¦
</code>```

Problem is, the IN isn't working, at the end of the final SELECT I retrieved all the rows from table2 instead of the ones respecting the condition of having the same id as the subquery retrieved earlier.

```<code>+------+------+---
|  id  | name |
|------|------|---
|  1   |  xx  |
|  2   |  yy  |
¦      ¦      ¦
</code>```

So my question is :

Why is the subquery ignored in my IN statement and is there a way to bypass that problem ?

EDIT

Here is a SQLFiddle as requested, but strangely, the code I posted is working here but not for my database.

答:
```<code>SELECT * FROM table2 t2
INNER JOIN
    (SELECT
            subquery.id
        FROM
            (SELECT
                id
            FROM
                table1 t1
            WHERE
                (t1.property = 10 AND t1.value = 0)) AS subquery
                INNER JOIN
            (SELECT
                id
            FROM
                table1 t1
            WHERE
                (t1.property = 20 AND i.value = 1)) AS subquery2 ON subquery.id = subquery2.id)Z ON Z.id=t2.id
</code>```

You can try above code.
Hope this will help.

Body:
I'm trying to select a bunch of rows from my first table depending of values from my second table.

To realize that, I came up with the following query :

SELECT *

FROM table2 t2
WHERE t2.id IN(

    SELECT subquery.id

    FROM
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=10 AND t1.value=0)

    ) AS subquery

    INNER JOIN
    (

        SELECT id

        FROM table1 t1
        WHERE (t1.property=20 AND i.value=1)

    ) AS subquery2

    on subquery.id=subquery2.id

)

Depending of the property and value from table1, a specific list of id will be selected to be used as a condition for the final SELECT with the table2.

The subquery in itself is working, I tested it and I could retrieve the good  id.

+------+
|  id  |
|------|
|  18  |
|  55  |
¦      ¦

Problem is, the IN isn't working, at the end of the final SELECT I retrieved all the rows from table2 instead of the ones respecting the condition of having the same id as the subquery retrieved earlier.

+------+------+---
|  id  | name |
|------|------|---
|  1   |  xx  |
|  2   |  yy  |
¦      ¦      ¦

So my question is :

Why is the subquery ignored in my IN statement and is there a way to bypass that problem ?

EDIT

Here is a SQLFiddle as requested, but strangely, the code I posted is working here but not for my database.

Body:
SELECT * FROM table2 t2
INNER JOIN
    (SELECT
            subquery.id
        FROM
            (SELECT
                id
            FROM
                table1 t1
            WHERE
                (t1.property = 10 AND t1.value = 0)) AS subquery
                INNER JOIN
            (SELECT
                id
            FROM
                table1 t1
            WHERE
                (t1.property = 20 AND i.value = 1)) AS subquery2 ON subquery.id = subquery2.id)Z ON Z.id=t2.id

You can try above code.
Hope this will help.


来源: stackexchange

问:
MS SQL Server Row GUID Column
I apologize for asking what seems like a tired question, but no forum response or documentation I've read seems to provide an adequate answer.

What is the purpose of the Row GUID Column property in MS SQL Server 2008?

Let me extend on that. I've seen "Don't use GUID as the PK" repeated as the answer for this question, which seems to be completely unrelated to me. If I set Row GUID Column is it forcing that GUID column to be the primary key or something?

To rephrase my original question: If I have a GUID column in my table that does not play any role in indexing, do I stand to gain anything from setting that GUID column as the Row GUID Column?

答: No it doesn't force it as the PK. It does mean you can't create a second uniqueidentifier and specify that as the Row GUID Column</p>

ContentLicense: CC BY-SA 2.5

Title: MS SQL Server Row GUID Column


问:
Is it possible to have a wildcard in the middle of a sub/sub-subdomain etc?
If I wanted to have a website domain which reads at.______.last.com, where the middle word/domain can change OR not be there at all (e.g. at.long.last.com, at.final.last.com OR without e.g. at.last.com), is this possible or would that require manually making sub domains for every single entry?

答:
You can't change. With Wildcard SSL you can only change sub domain name.

Example 1:

If you have issued Wildcard SSL certificate for *.domainname.com then you can secure:

mail.domainname.com
login.domainname.com

Example 2:

If you have issued Wildcard SSL certificate for *.subdomain.domain.com then you can secure:

blog.subdomain.domain.com
signup.subdomain.domain.com

But you can't change the middle of the subdomain name.

ContentLicense: CC BY-SA 3.0


问:
Removing Realm Data in the applicationWillTerminate
I have the following case, I delete the non-actual data from Realm when the application is thrown from the device's memory. I have a special FriendRealmManager class, this class contains the function clearCache, it deletes users (which are not friends at the moment). When I call this manager in the applicationWillTerminate function, after I return to the application, I see that this function did not work, because there are models of users who are no longer friends. I tried to move the code of the clearCache function into the applicationWillTerminate and this works. Tell me please, is it possible to do something like that to work functions from different managers in applicationWillTerminate?

I tried both the normal function and the static one.

It doesn't work

```<code>func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        FriendRealmManager.clearCache()
    }

class FriendRealmManager {

    static func clearCache() {
        DispatchQueue.main.async {
            do {
                let realm = try Realm()
                try realm.write {
              let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
                }
            } catch {
                debugPrint(error.localizedDescription)
            }
        }
    }
}
</code>```

It works

```<code>func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    do {
        let realm = try! Realm()
        try realm.write {
       let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
        }
    } catch {
        debugPrint(error.localizedDescription)
    }
}
</code>```

答:
The most probable reason for your function not working is that you call it as an asynchronous function and the system terminates your app before your function could execute. Looking at the official documentation of applicationWillTerminate, it states that

Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

Hence, I would suggest deleting the DispatchQueue.main.async part from your function and just running your deletion synchronously.

Body:
I have the following case, I delete the non-actual data from Realm when the application is thrown from the device's memory. I have a special FriendRealmManager class, this class contains the function clearCache, it deletes users (which are not friends at the moment). When I call this manager in the applicationWillTerminate function, after I return to the application, I see that this function did not work, because there are models of users who are no longer friends. I tried to move the code of the clearCache function into the applicationWillTerminate and this works. Tell me please, is it possible to do something like that to work functions from different managers in applicationWillTerminate?

I tried both the normal function and the static one.

It doesn't work

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        FriendRealmManager.clearCache()
    }

class FriendRealmManager {

    static func clearCache() {
        DispatchQueue.main.async {
            do {
                let realm = try Realm()
                try realm.write {
              let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
                }
            } catch {
                debugPrint(error.localizedDescription)
            }
        }
    }
}

It works

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    do {
        let realm = try! Realm()
        try realm.write {
       let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
        }
    } catch {
        debugPrint(error.localizedDescription)
    }
}


问:
Notification Intent Not starting Actiivty android
I am trying to start an Activity on a Notification Click but it never get started. Below is my code for sending Notification:

```<code>Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("Notification", type);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
        Notification n = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(type)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .build();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, n);
</code>```

I never get call to that activity on click of notification.

答:
try this one

  Replace Splash_Activity.class with you activity and make sure you have register this class in Manifest.xml

```<code> protected void displayNotification(Context context, String[] strContent) {
            try {
                int numMessages = 0;

                /* Invoking the default notification service */
                NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);

                mBuilder.setContentTitle("New "+strContent[0].trim());
                mBuilder.setContentText("You've received new "+strContent[0].trim());
                mBuilder.setTicker("New "+strContent[0].trim()+" Alert!");
                mBuilder.setSmallIcon(R.drawable.ic_notif);
                mBuilder.setAutoCancel(true);
                mBuilder.setColor(context.getResources().getColor(R.color.ColorPrimary));
                mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
                mBuilder.setDefaults(Notification.DEFAULT_ALL);
                mBuilder.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000});

                mBuilder.setLights(Color.RED, 3000, 3000);
             mBuilder.setNumber(++numMessages);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

                String[] events = new String[strContent.length-1];
                for(int i=0; i<strContent.length-1; i++){
                    events[i] = new String(strContent[i+1].trim());
                }

                inboxStyle.setBigContentTitle("New "+strContent[0].trim()+" received!");

                for (int i=0; i < events.length; i++) {
                    inboxStyle.addLine(events[i]);
                }

                mBuilder.setStyle(inboxStyle);

                /* Creates an explicit intent for an Activity in your app */
                Intent resultIntent = new Intent(this, Splash_Activity.class);

                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addParentStack(Splash_Activity.class);

                /* Adds the Intent that starts the Activity to the top of the stack */
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                /* notificationID allows you to update the notification later on. */
                mNotificationManager.notify(9999, mBuilder.build());
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
</code>```

Body:
I am trying to start an Activity on a Notification Click but it never get started. Below is my code for sending Notification:

Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra("Notification", type);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
        Notification n = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(type)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .build();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(0, n);

I never get call to that activity on click of notification.

Body:
try this one

  Replace Splash_Activity.class with you activity and make sure you have register this class in Manifest.xml

 protected void displayNotification(Context context, String[] strContent) {
            try {
                int numMessages = 0;

                /* Invoking the default notification service */
                NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);

                mBuilder.setContentTitle("New "+strContent[0].trim());
                mBuilder.setContentText("You've received new "+strContent[0].trim());
                mBuilder.setTicker("New "+strContent[0].trim()+" Alert!");
                mBuilder.setSmallIcon(R.drawable.ic_notif);
                mBuilder.setAutoCancel(true);
                mBuilder.setColor(context.getResources().getColor(R.color.ColorPrimary));
                mBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
                mBuilder.setDefaults(Notification.DEFAULT_ALL);
                mBuilder.setVibrate(new long[] {1000, 1000, 1000, 1000, 1000});

                mBuilder.setLights(Color.RED, 3000, 3000);
             mBuilder.setNumber(++numMessages);

            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

                String[] events = new String[strContent.length-1];
                for(int i=0; i<strContent.length-1; i++){
                    events[i] = new String(strContent[i+1].trim());
                }

                inboxStyle.setBigContentTitle("New "+strContent[0].trim()+" received!");

                for (int i=0; i < events.length; i++) {
                    inboxStyle.addLine(events[i]);
                }

                mBuilder.setStyle(inboxStyle);

                /* Creates an explicit intent for an Activity in your app */
                Intent resultIntent = new Intent(this, Splash_Activity.class);

                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addParentStack(Splash_Activity.class);

                /* Adds the Intent that starts the Activity to the top of the stack */
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                /* notificationID allows you to update the notification later on. */
                mNotificationManager.notify(9999, mBuilder.build());
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }


问:
Libgdx - how to properly dispose sound files
When should a sound effect be disposed of?

I'm a bit confused about sound effects vs music.  With music, I just dispose of it when a level is complete as I have the music just repeat until the end of the level and then that music is no longer used.  With sound effects, they play for a short time so I'm not sure what happens when one is done and a new one plays of the same sound.

For example, the player character can shoot a gun and each time the shoot sound plays.  So if the player shoots 6 times, is that sound effect handled like 6 separate sounds which need to be disposed of or is a sound file only to be disposed of once when no longer needed regardless of how many times it is used?

答:
For Small Projects/Games :

Any Sound that you're using on PlayScreen, create once in Game's create() method and use inside your game not dispose them.

```<code>Sound sound = Gdx.audio.newSound(Gdx.files.internal("data/mysound.mp3"));
</code>```

Dispose sound in dispose() method of ApplicationListener, that is called when you exit your Game.

Create your Sound in show() method of Screen Interface, and dispose them in dispose() of Screen but dispose() of Screen is not called by framework so you need to call by yourself so call dispose() method from hide() method of Screen.

Use AssetManager and manage your resource by loading ,unloading by your requirement and dispose your AssetManager in dispose in ApplicationListener.

For Big Porjects/Game in Resource wise

You must use AssetManager because you've to manage lot's of resources.

Body:
For Small Projects/Games :

Any Sound that you're using on PlayScreen, create once in Game's create() method and use inside your game not dispose them.

Sound sound = Gdx.audio.newSound(Gdx.files.internal("data/mysound.mp3"));

Dispose sound in dispose() method of ApplicationListener, that is called when you exit your Game.

Create your Sound in show() method of Screen Interface, and dispose them in dispose() of Screen but dispose() of Screen is not called by framework so you need to call by yourself so call dispose() method from hide() method of Screen.

Use AssetManager and manage your resource by loading ,unloading by your requirement and dispose your AssetManager in dispose in ApplicationListener.

For Big Porjects/Game in Resource wise

You must use AssetManager because you've to manage lot's of resources.


问:
How can i select random elements from dropdown lists which has tagname as
?
I tried this thing and it works perfectly when the tag name is selected, but when I use Select select = new Select(); in the tag name div, or something, it fails to work and prompts me with the following error:  org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".

```<code><div stop-propagation="click" class="custom-select-search">
    <input class="undefined ng-pristine ng-valid ng-touched" type="text" autocomplete="off" ng-model="searchTerm">
</div>
<ul role="menu">
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">166</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">164</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">165</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">166</a>
    </li>
</ul>
</code>```

This is my code:

```<code>        WebElement elements = driver.findElement(serial);
        Select ComboBoxValues = new Select(elements);
        List <WebElement> weblist = ComboBoxValues.getOptions();
        int iCnt = weblist.size();
        Random num = new Random();
        int iSelect = num.nextInt(iCnt);
        ComboBoxValues.selectByIndex(iSelect);
        System.out.println("Element Name 1 : " +elements.getAttribute("value"));
</code>```

Can anyone tell me to do this.

答:
As per selenium select documentation,

***Open Declaration org.openqa.selenium.support.ui.Select

Models a SELECT tag, providing helper methods to select and deselect options.

which mean SELECT can be used for drop-downs with select tag only. You applications drop-downs are made using DIV tag. that's the reason your code doesn't works on your web page

Title: How can i select random elements from dropdown lists which has tagname as <div>?

Body:
I tried this thing and it works perfectly when the tag name is selected, but when I use Select select = new Select(); in the tag name div, or something, it fails to work and prompts me with the following error:  org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".

    <input class="undefined ng-pristine ng-valid ng-touched" type="text" autocomplete="off" ng-model="searchTerm">

        166

        164

        165

        166

This is my code:

        WebElement elements = driver.findElement(serial);
        Select ComboBoxValues = new Select(elements);
        List <WebElement> weblist = ComboBoxValues.getOptions();
        int iCnt = weblist.size();
        Random num = new Random();
        int iSelect = num.nextInt(iCnt);
        ComboBoxValues.selectByIndex(iSelect);
        System.out.println("Element Name 1 : " +elements.getAttribute("value"));

Can anyone tell me to do this.


问:
How to store variable from option value to controller and save it in database with Laravel?
I'm trying to save variables from my view to controller and then save it in databases but im getting MethodNotAllowedHttpException.

Here are my view

```<code><form method="POST" action="{{ route('absensi.store') }}">

      <div class="form-group">
        <label name="nim"><h3>NIM :</h3></label>
        <select name ="mahasiswasn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the Student Number">
        @foreach($nim as $nm)
          <option value="{{ $nm->nim }}">{{ $nm->nim}}</option>
        @endforeach
      </select>
      </div>

      <div class="form-group">
        <label name="matkul"><h3> MK :</h3></label>
        <select name ="matkulsn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the subject">
        @foreach($matkul as $mkl)
          <option value="{{ $mkl->nama }}">{{ $mkl->nama}}</option>
        @endforeach
      </select>
      </div>

      <div class="form-group">
        <label name="hari">Hari :</label>
        <input id="hari" name="hari" class="form-control">
      </div>

      <div class="form-group">
        <label name="status">Status :</label>
        <input id="status" name="status" class="form-control">
      </div>

      <input type="submit" value="Add Absensi " class="btn btn-success btn-lg btn-block">
      <input type="hidden" name="_token" value="{{ Session::token() }}">

    </form>
</code>```

My Controller (AbsensiController)

```<code>public function store(Request $request)
    {
           $this->validate($request,array(
                'nim' =>'required',
                'matkul' =>'required',
                'hari' =>'required',
                'status' =>'required'
                ));

            //store in database
            $post = new PostAbsensi;

            $post->nim = $request->get('mahasiswasn');
            $post->mk = $request->get('matkulsn');
            $post->hari = $request->get('hari');
            $post->status = $request->get('status');

            $post->save();

            Session::flash('success','data successfully saved!');

            return redirect()->route('absensi.show', $post->id);
    }
</code>```

My Routes :

```<code>Route::resource('absensi','AbsensiController');
</code>```

Please Help, thank you for your attention.

Edit :

Here are my other view(IndexAbsensi)

```<code><form method="POST" action="{{ url('absensi.create') }}">
                      <input type="submit" value=" + Tambah Absensi " class="btn btn-success btn-lg btn-block">
                      <input type="hidden" name="_token" value="{{ csrf_token() }}">
  </form>
</code>```

so my thought is that when i press the button it will go to the AbsensiController@create and then return my form view, however im also getting Methodnotallowedhttpexception with this.

答:
can you try

```<code>public function store(Request $request)
{
       $this->validate($request,array(
            'nim' =>'required',
            'matkul' =>'required',
            'hari' =>'required',
            'status' =>'required'
            ));

        //store in database
        $post = new PostAbsensi;

        $post->nim = $request->mahasiswasn;
        $post->mk = $request->matkulsn;
        $post->hari = $request->hari;
        $post->status = $request->status;

        $post->save();

        Session::flash('success','data successfully saved!');

        return redirect()->route('absensi.show', $post->id);
}
</code>```

I don't know if it posible get post request variables via $request->get("")

Body:
I'm trying to save variables from my view to controller and then save it in databases but im getting MethodNotAllowedHttpException.

Here are my view

<form method="POST" action="{{ route('absensi.store') }}">

NIM :

        <select name ="mahasiswasn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the Student Number">
        @foreach($nim as $nm)
          <option value="{{ $nm->nim }}">{{ $nm->nim}}</option>
        @endforeach
      </select>

 MK :

        <select name ="matkulsn" class="selectpicker" data-live-search="true" data-width="500px" title="Choose the subject">
        @foreach($matkul as $mkl)
          <option value="{{ $mkl->nama }}">{{ $mkl->nama}}</option>
        @endforeach
      </select>

        Hari :
        <input id="hari" name="hari" class="form-control">

        Status :
        <input id="status" name="status" class="form-control">

      <input type="submit" value="Add Absensi " class="btn btn-success btn-lg btn-block">
      <input type="hidden" name="_token" value="{{ Session::token() }}">

    </form>

My Controller (AbsensiController)

public function store(Request $request)
    {
           $this->validate($request,array(
                'nim' =>'required',
                'matkul' =>'required',
                'hari' =>'required',
                'status' =>'required'
                ));

            //store in database
            $post = new PostAbsensi;

            $post->nim = $request->get('mahasiswasn');
            $post->mk = $request->get('matkulsn');
            $post->hari = $request->get('hari');
            $post->status = $request->get('status');

            $post->save();

            Session::flash('success','data successfully saved!');

            return redirect()->route('absensi.show', $post->id);
    }

My Routes :

Route::resource('absensi','AbsensiController');

Please Help, thank you for your attention.

Edit :

Here are my other view(IndexAbsensi)

<form method="POST" action="{{ url('absensi.create') }}">
                      <input type="submit" value=" + Tambah Absensi " class="btn btn-success btn-lg btn-block">
                      <input type="hidden" name="_token" value="{{ csrf_token() }}">
  </form>

so my thought is that when i press the button it will go to the AbsensiController@create and then return my form view, however im also getting Methodnotallowedhttpexception with this.

Body:
can you try

public function store(Request $request)
{
       $this->validate($request,array(
            'nim' =>'required',
            'matkul' =>'required',
            'hari' =>'required',
            'status' =>'required'
            ));

        //store in database
        $post = new PostAbsensi;

        $post->nim = $request->mahasiswasn;
        $post->mk = $request->matkulsn;
        $post->hari = $request->hari;
        $post->status = $request->status;

        $post->save();

        Session::flash('success','data successfully saved!');

        return redirect()->route('absensi.show', $post->id);
}

I don't know if it posible get post request variables via $request->get("")


问:
AngularJS: Animate ng-hide / ng-show height of li by using css transitions
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

```<code>li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}
</code>```

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

答:
Just do it by animate max-height instead of height like in this DEMO PLNKR. In that way you are able to have a dynamic height of your element between 0 and your max-height property. There is no need for jQuery. You should avoid using jQuery or direct DOM-Injections in AngularJS applications.

```<code>li,
div {
  transition: all 1s linear;
  -webkit-transition: all 1s linear;
  border: 1px solid;
  overflow: hidden;
}

.work {
  border-color: green;
  max-height: 500px;
}

.no-work {
  border-color: red;
  max-height: 500px;
}

li.ng-hide,
div.ng-hide {
  max-height: 0;
}
</code>```

Body:
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

Body:
Just do it by animate max-height instead of height like in this DEMO PLNKR. In that way you are able to have a dynamic height of your element between 0 and your max-height property. There is no need for jQuery. You should avoid using jQuery or direct DOM-Injections in AngularJS applications.

li,
div {
  transition: all 1s linear;
  -webkit-transition: all 1s linear;
  border: 1px solid;
  overflow: hidden;
}

.work {
  border-color: green;
  max-height: 500px;
}

.no-work {
  border-color: red;
  max-height: 500px;
}

li.ng-hide,
div.ng-hide {
  max-height: 0;
}


问:
Construct an escaped string
I am looking for an alternative api in javascript for the StringEscapeUtils in java.

Basically it should be able to convert

input string:

He didn't say, "Stop!"

output string:

He didn't say, \"Stop!\"

Can we do the same using any underscore or any other util functions?

In underscore`s escape api,

var a = '"test"';
  _.escape(a)

returns

```<code>""test""
</code>```

But I wanted in the format \"test\"'

答:
If you just want to replace " with \", you can do this:

var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/"/g, '\\\"'));```
</div>
</div>
</p>

<p>If you want to escape other characters too, you can do something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/("|'|\\)/g, '\\\$1'));</code>```

Both examples are using RegExp replace, just different regular expressions used.

Title: Construct an escaped string

Body:
I am looking for an alternative api in javascript for the StringEscapeUtils in java.

Basically it should be able to convert

input string:

He didn't say, "Stop!"

output string:

He didn't say, \"Stop!\"

Can we do the same using any underscore or any other util functions?

In underscore`s escape api,

var a = '"test"';
  _.escape(a)

returns

""test""

But I wanted in the format \"test\"'

Body:
If you just want to replace " with \", you can do this:

var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/"/g, '\\\"'));

If you want to escape other characters too, you can do something like this:

var s = "He didn't say, \"Stop!\"";
console.log(s.replace(/("|'|\\)/g, '\\\$1'));

Both examples are using RegExp replace, just different regular expressions used.


问:
Get UserControl inside tabItem
I have a TabControl, with a template, like so :

```<code><TabControl ItemsSource="{Binding MyItems}" x:Name="tabs">
  <TabControl.Resources>
    <DataTemplate x:Key="contentTemplate" x:Name="contentTemplate" >
      <other:MyUserControl x:Name="mUserControl"  CustomData="{Binding}"/>
    </DataTemplate>
    <Style TargetType="{x:Type TabItem}">
      <Setter Property="Header" Value="{Binding Name}" />
      <Setter Property="ContentTemplate" Value="{StaticResource contentTemplate}"/>
    </Style>
  </TabControl.Resources>
</TabControl>
</code>```

MyItems is an ObservableCollection of custom objects.
When I call tabs.SelectedContent it returns an item.

I would like to get the UserControl MyUserControl contained in the contentTemplate DataTemplate.

Because mUserControl is in a template, I can't call it like mUserControl.doSomething().

I tried to use the templates "FindName" function :

```<code>ControlTemplate dt = tabs.Template;
MyUserControl mControl = (MyUserControl)dt.FindName("mUserControl", tabs);
</code>```

But it returns null.

I would like to access the MyUserControl object to call a function that will change it's state (show a control and hide another one).
This happens when the user clicks on a MenuItem (owned by the MainWindow), but the affected widget is the UserControl.

So, how do I get a reference to the MyUserControl object ?

答:
You can traverse your Visual tree from your TabControl deeper inside and you can get all your user controls which are inside it.

You should read about visual tree or answers like this:
Find control in the visual tree

Title: Get UserControl inside tabItem

Body:
I have a TabControl, with a template, like so :

<TabControl ItemsSource="{Binding MyItems}" x:Name="tabs">
  <TabControl.Resources>
    <DataTemplate x:Key="contentTemplate" x:Name="contentTemplate" >
      <other:MyUserControl x:Name="mUserControl"  CustomData="{Binding}"/>
    </DataTemplate>

  </TabControl.Resources>
</TabControl>

MyItems is an ObservableCollection of custom objects.
When I call tabs.SelectedContent it returns an item.

I would like to get the UserControl MyUserControl contained in the contentTemplate DataTemplate.

Because mUserControl is in a template, I can't call it like mUserControl.doSomething().

I tried to use the templates "FindName" function :

ControlTemplate dt = tabs.Template;
MyUserControl mControl = (MyUserControl)dt.FindName("mUserControl", tabs);

But it returns null.

I would like to access the MyUserControl object to call a function that will change it's state (show a control and hide another one).
This happens when the user clicks on a MenuItem (owned by the MainWindow), but the affected widget is the UserControl.

So, how do I get a reference to the MyUserControl object ?


问:
producer-consumer using synchronization
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

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

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

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

答:
you are actually not solving the producer/consumer problem but just walking around it :)
Your code works because of the timing and because of the fact if one of the two threads fails putting/retrieving the resource it asks for it basically sleeps for a while and tries again. Although this worsk (when you do not have to immediatly handle an event) it wastes CPU time.

That is why semaphores are strongly suggested to address this kind of issue as you can read here

http://en.wikipedia.org/wiki/Producer-consumer_problem

bye

Title: producer-consumer using synchronization

Body:
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

import java.util.*;

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

         }
         return false;
     }
}


问:
PHP converting hours and minutes into a decimal
I am calculating hours and minutes into variables but i would like to convert this into a decimal number

For example, 1 hour 30 minutes should display as 1.5 and 2 hours 15 minutes would display as 2.25

答:
This is so easy. Divide by 60.

```<code>function convertMinutesToDecimal($minutes)
{
    return $minutes / 60;
}

echo '15 mins is '.convertMinutesToDecimal(15)."\n";
echo '30 mins is '.convertMinutesToDecimal(30)."\n";
echo '45 mins is '.convertMinutesToDecimal(45)."\n";
</code>```

Output:

```<code>15 mins is 0.25
30 mins is 0.5
45 mins is 0.75
</code>```

Body:
This is so easy. Divide by 60.

function convertMinutesToDecimal($minutes)
{
    return $minutes / 60;
}

echo '15 mins is '.convertMinutesToDecimal(15)."\n";
echo '30 mins is '.convertMinutesToDecimal(30)."\n";
echo '45 mins is '.convertMinutesToDecimal(45)."\n";

Output:

15 mins is 0.25
30 mins is 0.5
45 mins is 0.75


问:
jQuery - unable to execute ajax request with authorization header
I have an ASP.NET Core API project running on my local IIS, and a client website running on development environment (http://localhost:53559). The API has a protected resource that I want to call with an authorization header.

On my ASP.NET API I've enabled CORS using:

```<code>services.AddCors();
app.UseCors(builder => builder.AllowAnyOrigin());
</code>```

My ajax call looks like this:

```<code>$.ajax({
    type: "GET",
    url: "http://localhost/MyApi/api/values",
    async: true,
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.withCredentials = true;
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});
</code>```

If I don't include a header in the request then I'm getting a 401 response as expected. And when looking at the request with Fiddler this is what I see in the request:

```<code>GET http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: */*
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
</code>```

But when I add my authorization header, I'm getting a 204 response and this is what I have on the request (which off-course doesn't work and doesn't look at all like a request I'm expecting to get - not GET call, no authorization header....):

```<code>OPTIONS http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6
</code>```

I'm using IdentityServer to handle authentication.

What am I missing here? why can't I send headers with the request?

答:
I've added the following to my web.config and it worked:</p>

```<code><add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
</code>```

Body:
I have an ASP.NET Core API project running on my local IIS, and a client website running on development environment (http://localhost:53559). The API has a protected resource that I want to call with an authorization header.

On my ASP.NET API I've enabled CORS using:

services.AddCors();
app.UseCors(builder => builder.AllowAnyOrigin());

My ajax call looks like this:

$.ajax({
    type: "GET",
    url: "http://localhost/MyApi/api/values",
    async: true,
    success: function (data) {
        setJsonResult(data);
        showResultPane("API request result");
    },
    error: function (obj, textStatus, errorThrown) {
        setHtmlResult("Error returned by API: " + errorThrown);
        showResultPane("Unauthorized request result");
    },
    beforeSend: function (request) {
        if (currentToken) {
            request.withCredentials = true;
            request.setRequestHeader("Authorization", "Bearer " + currentToken);
        }
    }
});

If I don't include a header in the request then I'm getting a 401 response as expected. And when looking at the request with Fiddler this is what I see in the request:

GET http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Accept: */*
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6

But when I add my authorization header, I'm getting a 204 response and this is what I have on the request (which off-course doesn't work and doesn't look at all like a request I'm expecting to get - not GET call, no authorization header....):

OPTIONS http://localhost/MyApi/api/values HTTP/1.1
Host: localhost
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:53559
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36     (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://localhost:53559/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,he;q=0.6

I'm using IdentityServer to handle authentication.

What am I missing here? why can't I send headers with the request?

Body:
I've added the following to my web.config and it worked:

<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />


问:
creating a shm file from kernel module
I am trying to open a shm file for data sharing between kernel and user process.
Below is my kernel module code.  Sys log output indicates that no errors were encountered.  Once the module is loaded, I don't see the file that I'm trying to create in /dev/shm.  What am I doing wrong?

```<code>#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/shmem_fs.h>

static int __init moduleLoader(void) {
    struct file *shfile;

    printk(KERN_INFO "shkmod is loading...\n");

    shfile = shmem_file_setup("MyShmFile",sizeof(int),0);
    printk("shmem_file_setup returned %p\n",shfile);
    if (IS_ERR(shfile))
        printk("shmem_file_setup returned error.\n");
    printk("shfile is: %s\n", shfile->f_path.dentry->d_name.name);

    printk(KERN_INFO "shkmod is done loading.\n");
    return 0;
}

static void __exit moduleUnloader(void) {
    printk(KERN_INFO "shkmod was unloaded.\n");
    return;
}

module_init(moduleLoader);
module_exit(moduleUnloader);

MODULE_AUTHOR("Yaron Shragai");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Lorem ipsum dolor sit amet");
</code>```

Here is the output in the sys log:

```<code>Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335482] shkmod is loading...
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335487] shmem_file_setup returned ffff8801fef53b00
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335488] shfile is: MyShmFile
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335488] shkmod is done loading.
</code>```

$ uname -a

Linux yaron-VirtualBox 4.4.0-57-generic #78-Ubuntu SMP Fri Dec 9 23:50:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

答:
```<code>/**
 * shmem_file_setup - get an unlinked file living in tmpfs
</code>```

The comment explicitly states the file is not going to appear anywhere.

```<code> * @name: name for dentry (to be seen in /proc/<pid>/maps
</code>```

... and the name is to have something to be shown in maps.

```<code> * @size: size to be set for the file
 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
 */
struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
{
        return __shmem_file_setup(name, size, flags, 0);
}
</code>```

It makes sense though. You did not specify any filesystem, just used a name which is a relative path to begin with. Why did you expect the file to show up in /dev specifically?

As usual the real question is what is the actual problem you are working on.

If it happens that a shared file is indeed the way to go, userspace should create one and tell the kernel to use it.

Title: creating a shm file from kernel module

Body:
I am trying to open a shm file for data sharing between kernel and user process.
Below is my kernel module code.  Sys log output indicates that no errors were encountered.  Once the module is loaded, I don't see the file that I'm trying to create in /dev/shm.  What am I doing wrong?

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/shmem_fs.h>

static int __init moduleLoader(void) {
    struct file *shfile;

    printk(KERN_INFO "shkmod is loading...\n");

    shfile = shmem_file_setup("MyShmFile",sizeof(int),0);
    printk("shmem_file_setup returned %p\n",shfile);
    if (IS_ERR(shfile))
        printk("shmem_file_setup returned error.\n");
    printk("shfile is: %s\n", shfile->f_path.dentry->d_name.name);

    printk(KERN_INFO "shkmod is done loading.\n");
    return 0;
}

static void __exit moduleUnloader(void) {
    printk(KERN_INFO "shkmod was unloaded.\n");
    return;
}

module_init(moduleLoader);
module_exit(moduleUnloader);

MODULE_AUTHOR("Yaron Shragai");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Lorem ipsum dolor sit amet");

Here is the output in the sys log:

Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335482] shkmod is loading...
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335487] shmem_file_setup returned ffff8801fef53b00
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335488] shfile is: MyShmFile
Jun  6 15:25:59 yaron-VirtualBox kernel: [457160.335488] shkmod is done loading.

$ uname -a

Linux yaron-VirtualBox 4.4.0-57-generic #78-Ubuntu SMP Fri Dec 9 23:50:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Body:
/**
 * shmem_file_setup - get an unlinked file living in tmpfs

The comment explicitly states the file is not going to appear anywhere.

 * @name: name for dentry (to be seen in /proc/<pid>/maps

... and the name is to have something to be shown in maps.

 * @size: size to be set for the file
 * @flags: VM_NORESERVE suppresses pre-accounting of the entire object size
 */
struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags)
{
        return __shmem_file_setup(name, size, flags, 0);
}

It makes sense though. You did not specify any filesystem, just used a name which is a relative path to begin with. Why did you expect the file to show up in /dev specifically?

As usual the real question is what is the actual problem you are working on.

If it happens that a shared file is indeed the way to go, userspace should create one and tell the kernel to use it.


问:
Why when creating new cube it's not always on the terrain position?
The TileMap

```<code>namespace CBX.TileMapping.Unity
{
    using UnityEngine;

    /// <summary>
    /// Provides a component for tile mapping.
    /// </summary>
    public class TileMap : MonoBehaviour
    {
        /// <summary>
        /// Gets or sets the number of rows of tiles.
        /// </summary>
        public int Rows;

        /// <summary>
        /// Gets or sets the number of columns of tiles.
        /// </summary>
        public int Columns;

        /// <summary>
        /// Gets or sets the value of the tile width.
        /// </summary>
        public float TileWidth = 1;

        /// <summary>
        /// Gets or sets the value of the tile height.
        /// </summary>
        public float TileHeight = 1;

        /// <summary>
        /// Used by editor components or game logic to indicate a tile location.
        /// </summary>
        /// <remarks>This will be hidden from the inspector window. See <see cref="HideInInspector"/></remarks>
        [HideInInspector]
        public Vector3 MarkerPosition;

        /// <summary>
        /// Initializes a new instance of the <see cref="TileMap"/> class.
        /// </summary>
        public TileMap()
        {
            this.Columns = 20;
            this.Rows = 10;
        }

        /// <summary>
        /// When the game object is selected this will draw the grid
        /// </summary>
        /// <remarks>Only called when in the Unity editor.</remarks>
        private void OnDrawGizmosSelected()
        {
            // store map width, height and position
            var mapWidth = this.Columns * this.TileWidth;
            var mapHeight = this.Rows * this.TileHeight;
            var position = this.transform.position;

            // draw layer border
            Gizmos.color = Color.white;
            Gizmos.DrawLine(position, position + new Vector3(mapWidth, 0, 0));
            Gizmos.DrawLine(position, position + new Vector3(0, mapHeight, 0));
            Gizmos.DrawLine(position + new Vector3(mapWidth, 0, 0), position + new Vector3(mapWidth, mapHeight, 0));
            Gizmos.DrawLine(position + new Vector3(0, mapHeight, 0), position + new Vector3(mapWidth, mapHeight, 0));

            // draw tile cells
            Gizmos.color = Color.grey;
            for (float i = 1; i < this.Columns; i++)
            {
                Gizmos.DrawLine(position + new Vector3(i * this.TileWidth, 0, 0), position + new Vector3(i * this.TileWidth, mapHeight, 0));
            }

            for (float i = 1; i < this.Rows; i++)
            {
                Gizmos.DrawLine(position + new Vector3(0, i * this.TileHeight, 0), position + new Vector3(mapWidth, i * this.TileHeight, 0));
            }

            // Draw marker position
            Gizmos.color = Color.red;
            Gizmos.DrawWireCube(this.MarkerPosition, new Vector3(this.TileWidth, this.TileHeight, 1) * 1.1f);
        }
    }
}
</code>```

And the TileMapEditor

```<code>namespace CBX.Unity.Editors.Editor
{
    using System;
    using CBX.TileMapping.Unity;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// Provides a editor for the <see cref="TileMap"/> component
    /// </summary>
    [CustomEditor(typeof(TileMap))]
    public class TileMapEditor : Editor
    {
        /// <summary>
        /// Holds the location of the mouse hit location
        /// </summary>
        private Vector3 mouseHitPos;

        /// <summary>
        /// Lets the Editor handle an event in the scene view.
        /// </summary>
        ///

        private void OnSceneGUI()
        {
            // if UpdateHitPosition return true we should update the scene views so that the marker will update in real time
            if (this.UpdateHitPosition())
            {
                SceneView.RepaintAll();
            }

            // Calculate the location of the marker based on the location of the mouse
            this.RecalculateMarkerPosition();

            // get a reference to the current event
            Event current = Event.current;

            // if the mouse is positioned over the layer allow drawing actions to occur
            if (this.IsMouseOnLayer())
            {
                // if mouse down or mouse drag event occurred
                if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag)
                {
                    if (current.button == 1)
                    {
                        // if right mouse button is pressed then we erase blocks
                        this.Erase();
                        current.Use();
                    }
                    else if (current.button == 0)
                    {
                        // if left mouse button is pressed then we draw blocks
                        this.Draw();
                        current.Use();
                    }
                }
            }

            // draw a UI tip in scene view informing user how to draw & erase tiles
            Handles.BeginGUI();
            GUI.Label(new Rect(10, Screen.height - 90, 100, 100), "LMB: Draw");
            GUI.Label(new Rect(10, Screen.height - 105, 100, 100), "RMB: Erase");
            Handles.EndGUI();
        }

        /// <summary>
        /// When the <see cref="GameObject"/> is selected set the current tool to the view tool.
        /// </summary>
        private void OnEnable()
        {
            Tools.current = Tool.View;
            Tools.viewTool = ViewTool.FPS;
        }

        /// <summary>
        /// Draws a block at the pre-calculated mouse hit position
        /// </summary>
        private void Draw()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if there is already a tile present and it is not a child of the game object we can just exit.
            if (cube != null && cube.transform.parent != map.transform)
            {
                return;
            }

            // if no game object was found we will create a cube
            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            // set the cubes position on the tile map
            var tilePositionInLocalSpace = new Vector3((tilePos.x * map.TileWidth) + (map.TileWidth / 2), (tilePos.y * map.TileHeight) + (map.TileHeight / 2));
            cube.transform.position = map.transform.position + tilePositionInLocalSpace;

            // we scale the cube to the tile size defined by the TileMap.TileWidth and TileMap.TileHeight fields
            cube.transform.localScale = new Vector3(map.TileWidth, map.TileHeight, 1);

            // set the cubes parent to the game object for organizational purposes
            cube.transform.parent = map.transform;

            // give the cube a name that represents it's location within the tile map
            cube.name = string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y);

            // give the cube a tag
            cube.tag = "GridObject";

            TerrainObjects(cube);
        }

        public void TerrainObjects(GameObject gameobject)
        {
            Terrain terrain = Terrain.activeTerrain;
            var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y));
            if (cube != null)
                return;

            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            cube.transform.position = new Vector3(terrain.transform.position.x + gameobject.transform.position.x, 0, terrain.transform.position.z + gameobject.transform.position.y);
            cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);

            cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y);
        }

        /// <summary>
        /// Erases a block at the pre-calculated mouse hit position
        /// </summary>
        private void Erase()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if a game object was found with the same name and it is a child we just destroy it immediately
            if (cube != null && cube.transform.parent == map.transform)
            {
                UnityEngine.Object.DestroyImmediate(cube);
            }
        }

        /// <summary>
        /// Calculates the location in tile coordinates (Column/Row) of the mouse position
        /// </summary>
        /// <returns>Returns a <see cref="Vector2"/> type representing the Column and Row where the mouse of positioned over.</returns>
        private Vector2 GetTilePositionFromMouseLocation()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // calculate column and row location from mouse hit location
            var pos = new Vector3(this.mouseHitPos.x / map.TileWidth, this.mouseHitPos.y / map.TileHeight, map.transform.position.z);

            // round the numbers to the nearest whole number using 5 decimal place precision
            pos = new Vector3((int)Math.Round(pos.x, 5, MidpointRounding.ToEven), (int)Math.Round(pos.y, 5, MidpointRounding.ToEven), 0);

            // do a check to ensure that the row and column are with the bounds of the tile map
            var col = (int)pos.x;
            var row = (int)pos.y;
            if (row < 0)
            {
                row = 0;
            }

            if (row > map.Rows - 1)
            {
                row = map.Rows - 1;
            }

            if (col < 0)
            {
                col = 0;
            }

            if (col > map.Columns - 1)
            {
                col = map.Columns - 1;
            }

            // return the column and row values
            return new Vector2(col, row);
        }

        /// <summary>
        /// Returns true or false depending if the mouse is positioned over the tile map.
        /// </summary>
        /// <returns>Will return true if the mouse is positioned over the tile map.</returns>
        private bool IsMouseOnLayer()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // return true or false depending if the mouse is positioned over the map
            return this.mouseHitPos.x > 0 && this.mouseHitPos.x < (map.Columns * map.TileWidth) &&
                   this.mouseHitPos.y > 0 && this.mouseHitPos.y < (map.Rows * map.TileHeight);
        }

        /// <summary>
        /// Recalculates the position of the marker based on the location of the mouse pointer.
        /// </summary>
        private void RecalculateMarkerPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // store the tile location (Column/Row) based on the current location of the mouse pointer
            var tilepos = this.GetTilePositionFromMouseLocation();

            // store the tile position in world space
            var pos = new Vector3(tilepos.x * map.TileWidth, tilepos.y * map.TileHeight, 0);

            // set the TileMap.MarkerPosition value
            map.MarkerPosition = map.transform.position + new Vector3(pos.x + (map.TileWidth / 2), pos.y + (map.TileHeight / 2), 0);
        }

        /// <summary>
        /// Calculates the position of the mouse over the tile map in local space coordinates.
        /// </summary>
        /// <returns>Returns true if the mouse is over the tile map.</returns>
        private bool UpdateHitPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // build a plane object that
            var p = new Plane(map.transform.TransformDirection(Vector3.forward), map.transform.position);

            // build a ray type from the current mouse position
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            // stores the hit location
            var hit = new Vector3();

            // stores the distance to the hit location
            float dist;

            // cast a ray to determine what location it intersects with the plane
            if (p.Raycast(ray, out dist))
            {
                // the ray hits the plane so we calculate the hit location in world space
                hit = ray.origin + (ray.direction.normalized * dist);
            }

            // convert the hit location from world space to local space
            var value = map.transform.InverseTransformPoint(hit);

            // if the value is different then the current mouse hit location set the
            // new mouse hit location and return true indicating a successful hit test
            if (value != this.mouseHitPos)
            {
                this.mouseHitPos = value;
                return true;
            }

            // return false if the hit test failed
            return false;
        }
    }
}
</code>```

This is the new method i added:
I want to translate the gameobject information like position,scale,rotation and create a copy on the terrain.

```<code>public void TerrainObjects(GameObject gameobject)
        {
            Terrain terrain = Terrain.activeTerrain;
            var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y));
            if (cube != null)
                return;

            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }
</code>```

The TileMap create a grid at some position.
I can move the grid around the space and if i move the grid the TileMap script is attached to a GameObject if i move this GameObject away from the terrain much away it will create the new cubes in the method TerrainObjects near the position of the GameObject where the TileMap is attached to.

But i want the cubes i create in TerrainObjects to be always on the terrain are and somehow to translate the position of the cubes on the grid(In TileMapEditor) to the position on the Terrain.

In the script TileMapEditor inside the Draw() at the bottom i'm calling the method TerrainObjects.

```<code>TerrainObjects(cube);
</code>```

Same idea/concept should be when I Erase() a cube/s from the grid.

The first screenshot is when the grid is near the terrain so the new cubes are on the terrain:

In the second screenshot i moved the grid far away from the terrain and the new cubes created near the grid not on the terrain:
I drawed new cubes and you can see where is the grid and where the new cubes are they are near the grid not the terrain.

答: When you're placing your cube on your terrain, you're adding the x, y and z values of the gameobject you've attached the GridEditor script to. I've a feeling that might be your issue. </p>

Body:
The TileMap

namespace CBX.TileMapping.Unity
{
    using UnityEngine;

    ///
    /// Provides a component for tile mapping.
    ///
    public class TileMap : MonoBehaviour
    {
        ///
        /// Gets or sets the number of rows of tiles.
        ///
        public int Rows;

        ///
        /// Gets or sets the number of columns of tiles.
        ///
        public int Columns;

        ///
        /// Gets or sets the value of the tile width.
        ///
        public float TileWidth = 1;

        ///
        /// Gets or sets the value of the tile height.
        ///
        public float TileHeight = 1;

        ///
        /// Used by editor components or game logic to indicate a tile location.
        ///
        /// <remarks>This will be hidden from the inspector window. See <see cref="HideInInspector"/></remarks>
        [HideInInspector]
        public Vector3 MarkerPosition;

        ///
        /// Initializes a new instance of the <see cref="TileMap"/> class.
        ///
        public TileMap()
        {
            this.Columns = 20;
            this.Rows = 10;
        }

        ///
        /// When the game object is selected this will draw the grid
        ///
        /// <remarks>Only called when in the Unity editor.</remarks>
        private void OnDrawGizmosSelected()
        {
            // store map width, height and position
            var mapWidth = this.Columns * this.TileWidth;
            var mapHeight = this.Rows * this.TileHeight;
            var position = this.transform.position;

            // draw layer border
            Gizmos.color = Color.white;
            Gizmos.DrawLine(position, position + new Vector3(mapWidth, 0, 0));
            Gizmos.DrawLine(position, position + new Vector3(0, mapHeight, 0));
            Gizmos.DrawLine(position + new Vector3(mapWidth, 0, 0), position + new Vector3(mapWidth, mapHeight, 0));
            Gizmos.DrawLine(position + new Vector3(0, mapHeight, 0), position + new Vector3(mapWidth, mapHeight, 0));

            // draw tile cells
            Gizmos.color = Color.grey;
            for (float i = 1; i < this.Columns; i++)
            {
                Gizmos.DrawLine(position + new Vector3(i * this.TileWidth, 0, 0), position + new Vector3(i * this.TileWidth, mapHeight, 0));
            }

            for (float i = 1; i < this.Rows; i++)
            {
                Gizmos.DrawLine(position + new Vector3(0, i * this.TileHeight, 0), position + new Vector3(mapWidth, i * this.TileHeight, 0));
            }

            // Draw marker position
            Gizmos.color = Color.red;
            Gizmos.DrawWireCube(this.MarkerPosition, new Vector3(this.TileWidth, this.TileHeight, 1) * 1.1f);
        }
    }
}

And the TileMapEditor

namespace CBX.Unity.Editors.Editor
{
    using System;
    using CBX.TileMapping.Unity;
    using UnityEditor;
    using UnityEngine;

    ///
    /// Provides a editor for the <see cref="TileMap"/> component
    ///
    [CustomEditor(typeof(TileMap))]
    public class TileMapEditor : Editor
    {
        ///
        /// Holds the location of the mouse hit location
        ///
        private Vector3 mouseHitPos;

        ///
        /// Lets the Editor handle an event in the scene view.
        ///
        ///

        private void OnSceneGUI()
        {
            // if UpdateHitPosition return true we should update the scene views so that the marker will update in real time
            if (this.UpdateHitPosition())
            {
                SceneView.RepaintAll();
            }

            // Calculate the location of the marker based on the location of the mouse
            this.RecalculateMarkerPosition();

            // get a reference to the current event
            Event current = Event.current;

            // if the mouse is positioned over the layer allow drawing actions to occur
            if (this.IsMouseOnLayer())
            {
                // if mouse down or mouse drag event occurred
                if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag)
                {
                    if (current.button == 1)
                    {
                        // if right mouse button is pressed then we erase blocks
                        this.Erase();
                        current.Use();
                    }
                    else if (current.button == 0)
                    {
                        // if left mouse button is pressed then we draw blocks
                        this.Draw();
                        current.Use();
                    }
                }
            }

            // draw a UI tip in scene view informing user how to draw & erase tiles
            Handles.BeginGUI();
            GUI.Label(new Rect(10, Screen.height - 90, 100, 100), "LMB: Draw");
            GUI.Label(new Rect(10, Screen.height - 105, 100, 100), "RMB: Erase");
            Handles.EndGUI();
        }

        ///
        /// When the <see cref="GameObject"/> is selected set the current tool to the view tool.
        ///
        private void OnEnable()
        {
            Tools.current = Tool.View;
            Tools.viewTool = ViewTool.FPS;
        }

        ///
        /// Draws a block at the pre-calculated mouse hit position
        ///
        private void Draw()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if there is already a tile present and it is not a child of the game object we can just exit.
            if (cube != null && cube.transform.parent != map.transform)
            {
                return;
            }

            // if no game object was found we will create a cube
            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            // set the cubes position on the tile map
            var tilePositionInLocalSpace = new Vector3((tilePos.x * map.TileWidth) + (map.TileWidth / 2), (tilePos.y * map.TileHeight) + (map.TileHeight / 2));
            cube.transform.position = map.transform.position + tilePositionInLocalSpace;

            // we scale the cube to the tile size defined by the TileMap.TileWidth and TileMap.TileHeight fields
            cube.transform.localScale = new Vector3(map.TileWidth, map.TileHeight, 1);

            // set the cubes parent to the game object for organizational purposes
            cube.transform.parent = map.transform;

            // give the cube a name that represents it's location within the tile map
            cube.name = string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y);

            // give the cube a tag
            cube.tag = "GridObject";

            TerrainObjects(cube);
        }

        public void TerrainObjects(GameObject gameobject)
        {
            Terrain terrain = Terrain.activeTerrain;
            var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y));
            if (cube != null)
                return;

            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

            cube.transform.position = new Vector3(terrain.transform.position.x + gameobject.transform.position.x, 0, terrain.transform.position.z + gameobject.transform.position.y);
            cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);

            cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y);
        }

        ///
        /// Erases a block at the pre-calculated mouse hit position
        ///
        private void Erase()
        {
            // get reference to the TileMap component
            var map = (TileMap)this.target;

            // Calculate the position of the mouse over the tile layer
            var tilePos = this.GetTilePositionFromMouseLocation();

            // Given the tile position check to see if a tile has already been created at that location
            var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

            // if a game object was found with the same name and it is a child we just destroy it immediately
            if (cube != null && cube.transform.parent == map.transform)
            {
                UnityEngine.Object.DestroyImmediate(cube);
            }
        }

        ///
        /// Calculates the location in tile coordinates (Column/Row) of the mouse position
        ///
        /// <returns>Returns a <see cref="Vector2"/> type representing the Column and Row where the mouse of positioned over.</returns>
        private Vector2 GetTilePositionFromMouseLocation()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // calculate column and row location from mouse hit location
            var pos = new Vector3(this.mouseHitPos.x / map.TileWidth, this.mouseHitPos.y / map.TileHeight, map.transform.position.z);

            // round the numbers to the nearest whole number using 5 decimal place precision
            pos = new Vector3((int)Math.Round(pos.x, 5, MidpointRounding.ToEven), (int)Math.Round(pos.y, 5, MidpointRounding.ToEven), 0);

            // do a check to ensure that the row and column are with the bounds of the tile map
            var col = (int)pos.x;
            var row = (int)pos.y;
            if (row < 0)
            {
                row = 0;
            }

            if (row > map.Rows - 1)
            {
                row = map.Rows - 1;
            }

            if (col < 0)
            {
                col = 0;
            }

            if (col > map.Columns - 1)
            {
                col = map.Columns - 1;
            }

            // return the column and row values
            return new Vector2(col, row);
        }

        ///
        /// Returns true or false depending if the mouse is positioned over the tile map.
        ///
        /// <returns>Will return true if the mouse is positioned over the tile map.</returns>
        private bool IsMouseOnLayer()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // return true or false depending if the mouse is positioned over the map
            return this.mouseHitPos.x > 0 && this.mouseHitPos.x < (map.Columns * map.TileWidth) &&
                   this.mouseHitPos.y > 0 && this.mouseHitPos.y < (map.Rows * map.TileHeight);
        }

        ///
        /// Recalculates the position of the marker based on the location of the mouse pointer.
        ///
        private void RecalculateMarkerPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // store the tile location (Column/Row) based on the current location of the mouse pointer
            var tilepos = this.GetTilePositionFromMouseLocation();

            // store the tile position in world space
            var pos = new Vector3(tilepos.x * map.TileWidth, tilepos.y * map.TileHeight, 0);

            // set the TileMap.MarkerPosition value
            map.MarkerPosition = map.transform.position + new Vector3(pos.x + (map.TileWidth / 2), pos.y + (map.TileHeight / 2), 0);
        }

        ///
        /// Calculates the position of the mouse over the tile map in local space coordinates.
        ///
        /// <returns>Returns true if the mouse is over the tile map.</returns>
        private bool UpdateHitPosition()
        {
            // get reference to the tile map component
            var map = (TileMap)this.target;

            // build a plane object that
            var p = new Plane(map.transform.TransformDirection(Vector3.forward), map.transform.position);

            // build a ray type from the current mouse position
            var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);

            // stores the hit location
            var hit = new Vector3();

            // stores the distance to the hit location
            float dist;

            // cast a ray to determine what location it intersects with the plane
            if (p.Raycast(ray, out dist))
            {
                // the ray hits the plane so we calculate the hit location in world space
                hit = ray.origin + (ray.direction.normalized * dist);
            }

            // convert the hit location from world space to local space
            var value = map.transform.InverseTransformPoint(hit);

            // if the value is different then the current mouse hit location set the
            // new mouse hit location and return true indicating a successful hit test
            if (value != this.mouseHitPos)
            {
                this.mouseHitPos = value;
                return true;
            }

            // return false if the hit test failed
            return false;
        }
    }
}

This is the new method i added:
I want to translate the gameobject information like position,scale,rotation and create a copy on the terrain.

public void TerrainObjects(GameObject gameobject)
        {
            Terrain terrain = Terrain.activeTerrain;
            var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y));
            if (cube != null)
                return;

            if (cube == null)
            {
                cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            }

The TileMap create a grid at some position.
I can move the grid around the space and if i move the grid the TileMap script is attached to a GameObject if i move this GameObject away from the terrain much away it will create the new cubes in the method TerrainObjects near the position of the GameObject where the TileMap is attached to.

But i want the cubes i create in TerrainObjects to be always on the terrain are and somehow to translate the position of the cubes on the grid(In TileMapEditor) to the position on the Terrain.

In the script TileMapEditor inside the Draw() at the bottom i'm calling the method TerrainObjects.

TerrainObjects(cube);

Same idea/concept should be when I Erase() a cube/s from the grid.

The first screenshot is when the grid is near the terrain so the new cubes are on the terrain:

In the second screenshot i moved the grid far away from the terrain and the new cubes created near the grid not on the terrain:
I drawed new cubes and you can see where is the grid and where the new cubes are they are near the grid not the terrain.


问:
Table with some columns in percent, the rest fluid
I have a table, where two columns will receive 30% of the space each:

```<code><td style="width: 30%;">
</code>```

The remaining columns should just equally share the remaining space. How do I accomplish this? Do I just give the remaining columns no widthat all?

答:
Yes, declaring no width would work (see snippet below).

 automatically adjusts width evenly unless otherwise declared (e.g. 	)

EDIT

When you put data in the fluid cells, they will adapt to the size of the data inside them. To keep them the same width as each other and wrap the text, you will need to declare a width percentage for the fluid cells.

Since we're already using 60% with the first two cells, we have 40% left. We will need to divide 40 by the number of extra cells to get the percentage value for their width.

Thanks to @Chiller for pointing this out!

table {
  height: 500px;
  width: 100%;
}

td {
  background: red;
  /* Edit - divide number of fluid cells by 40
  (because we're using 60% with the first two)
  in this example the number is just over 13) */
  width: 13%; /* the number we calculated */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td style="width: 30%;"></td>
    <td style="width: 30%;"></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table></code>```

Body:
I have a table, where two columns will receive 30% of the space each:

The remaining columns should just equally share the remaining space. How do I accomplish this? Do I just give the remaining columns no widthat all?

Body:
Yes, declaring no width would work (see snippet below).

<td> automatically adjusts width evenly unless otherwise declared (e.g. <td style="width: 30%;"></td>)

EDIT

When you put data in the fluid cells, they will adapt to the size of the data inside them. To keep them the same width as each other and wrap the text, you will need to declare a width percentage for the fluid cells.

Since we're already using 60% with the first two cells, we have 40% left. We will need to divide 40 by the number of extra cells to get the percentage value for their width.

Thanks to @Chiller for pointing this out!

table {
  height: 500px;
  width: 100%;
}

td {
  background: red;
  /* Edit - divide number of fluid cells by 40
  (because we're using 60% with the first two)
  in this example the number is just over 13) */
  width: 13%; /* the number we calculated */
}

<table>
  <tr>
    <td style="width: 30%;"></td>
    <td style="width: 30%;"></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>


问:
Creating Custom Operators in RxJava2?
I'm having trouble finding an example of how to make a custom operator with RxJava 2. I've considered a few approaches:

Using Observable.create, and then flatMaping on it from the source observable. I can get this working, but it doesn't quite feel right. I end up creating a static function which I provide the source Observable, and then flatMap on the source. In the OnSubscribe, I  then instantiate an object that I pass the emitter to, which handles and manages the Observable / Emitter (as it's not trivial, and I want everything as encapsulated as possible).

Creating an ObservableOperator and providing it to Observable.lift. I can't find any examples of this for RxJava 2. I had to debug into my own example to make sure my understanding of upstream and downstream were correct. Because I can't find any examples or documentation on this for RxJava 2 I'm a little worried I might accidentally do something I'm not supposed to.

Create my own Observable type. This seems to be how the underlying operators work, many of which extend AbstractObservableWithUpstream. There is a lot going on here though, and it seems easy to miss something or do something I shouldn't. I'm not sure if I'm supposed to take an approach like this or not. I stepped myself through the mental process, and it seems like it can get hairy pretty quickly.

I'm going to proceed forward with option #2, but thought it worthwhile to ask what the supported method for doing this was in RxJava2 and also find out if there was any documentation or examples for this.

答:
This may help you. I implement operator RxJava2 to handle APiError. I used lift operator.

See the example.

```<code>  public final class ApiClient implements ApiClientInterface {
    ...
      @NonNull
      @Override
      public Observable<ActivateResponse> activate(String email, EmailData emailLinkData) {
          return myApiService.activate(email, emailData)
                  .lift(getApiErrorTransformer())
                  .subscribeOn(Schedulers.io());
      }

      private <T>ApiErrorOperator<T> getApiErrorTransformer() {
          return new ApiErrorOperator<>(gson, networkService);
      }

  }
</code>```

And then you can find custom operator

```<code>    public final class ApiErrorOperator<T> implements ObservableOperator<T, T> {
        private static final String TAG = "ApiErrorOperator";
        private final Gson gson;
        private final NetworkService networkService;

        public ApiErrorOperator(@NonNull Gson gson, @NonNull NetworkService networkService) {
            this.gson = gson;
            this.networkService = networkService;
        }

        @Override
        public Observer<? super T> apply(Observer<? super T> observer) throws Exception {
            return new Observer<T>() {
                @Override
                public void onSubscribe(Disposable d) {
                    observer.onSubscribe(d);
                }

                @Override
                public void onNext(T value) {
                    observer.onNext(value);
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError", e);

                if (e instanceof HttpException) {
                        try {
                            HttpException error = (HttpException) e;
                            Response response = error.response();
                            String errorBody = response.errorBody().string();

                            ErrorResponse errorResponse = gson.fromJson(errorBody.trim(), ErrorResponse.class);
                            ApiException exception = new ApiException(errorResponse, response);

                            observer.onError(exception);
                        } catch (IOException exception) {
                            observer.onError(exception);
                        }

                    } else if (!networkService.isNetworkAvailable()) {
                        observer.onError(new NetworkException(ErrorResponse.builder()
                                .setErrorCode("")
                                .setDescription("No Network Connection Error")
                                .build()));
                    } else {
                        observer.onError(e);
                    }
                }

                @Override
                public void onComplete() {
                    observer.onComplete();
                }
            };
        }
    }
</code>```

Title: Creating Custom Operators in RxJava2?

Body:
This may help you. I implement operator RxJava2 to handle APiError. I used lift operator.

See the example.

  public final class ApiClient implements ApiClientInterface {
    ...
      @NonNull
      @Override
      public Observable<ActivateResponse> activate(String email, EmailData emailLinkData) {
          return myApiService.activate(email, emailData)
                  .lift(getApiErrorTransformer())
                  .subscribeOn(Schedulers.io());
      }

      private <T>ApiErrorOperator<T> getApiErrorTransformer() {
          return new ApiErrorOperator<>(gson, networkService);
      }

  }

And then you can find custom operator

    public final class ApiErrorOperator<T> implements ObservableOperator<T, T> {
        private static final String TAG = "ApiErrorOperator";
        private final Gson gson;
        private final NetworkService networkService;

        public ApiErrorOperator(@NonNull Gson gson, @NonNull NetworkService networkService) {
            this.gson = gson;
            this.networkService = networkService;
        }

        @Override
        public Observer<? super T> apply(Observer<? super T> observer) throws Exception {
            return new Observer<T>() {
                @Override
                public void onSubscribe(Disposable d) {
                    observer.onSubscribe(d);
                }

                @Override
                public void onNext(T value) {
                    observer.onNext(value);
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError", e);

                if (e instanceof HttpException) {
                        try {
                            HttpException error = (HttpException) e;
                            Response response = error.response();
                            String errorBody = response.errorBody().string();

                            ErrorResponse errorResponse = gson.fromJson(errorBody.trim(), ErrorResponse.class);
                            ApiException exception = new ApiException(errorResponse, response);

                            observer.onError(exception);
                        } catch (IOException exception) {
                            observer.onError(exception);
                        }

                    } else if (!networkService.isNetworkAvailable()) {
                        observer.onError(new NetworkException(ErrorResponse.builder()
                                .setErrorCode("")
                                .setDescription("No Network Connection Error")
                                .build()));
                    } else {
                        observer.onError(e);
                    }
                }

                @Override
                public void onComplete() {
                    observer.onComplete();
                }
            };
        }
    }