问:
Php search in database to show data, not working
i'm trying to display some data from my database, and i dosen't work when i try to display some of the data, specified by a search bar. Here is the code. I hope someone can fix my problem.

Ive tried for a few hours, but nothing seems to work.

I removed most of the html code, to even be able to post.

<?php
 include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>

    <form>
    <input type="text" name="search" placeholder="Search for graphicscard"/>
    <input type="submit" value="Search" />

<?php

?>

    </form>

Graphicscard
Coin
Hashrate
Bios-modded
Core-clock
Memory-clock
Power draw
Additional info

      <?
  if(isset($_POST['search'])) {
        $searchq = $_POST['search'];
        $searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);

        $query = mysqli_query("SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
        $count = mysqli_num_rows($queryQ);

            while ($row = mysqli_fetch_array($query)) {
                echo "
";
                echo "".$row['name']."	";
                echo "".$row['coin'] . "	";
                echo "".$row['hashrate'] . "	";
                echo "".$row['bios_mod'] . "	";
                echo "".$row['core_clock'] . "	";
                echo "".$row['memory_clock'] . "	";
                echo "".$row['power_draw'] . "	";
                echo "".$row['additional_info'] . "	";
                echo "
";
            }
        }

        ?>```

答:
Here is an alternative way:

```<code>select * from cards where name like 'ABC%'
union
select * from cards where coin like 'XYZ%'
union
select * from cards where gender like 'PQR%';
</code>```

Body:
Here is an alternative way:

select * from cards where name like 'ABC%'
union
select * from cards where coin like 'XYZ%'
union
select * from cards where gender like 'PQR%';


来源: stackexchange

问:
Write python dictionary into textfile
I want to write my python dictionary in a text file where each line contain one key and its value, with comma as separation. I am using the following code:

```<code>with open(compounds, 'w') as f:
    for key, value in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s:%s\n' % (key, value))
</code>```

But it returns me the following error TypeError: expected str, bytes or os.PathLike object, not list

答:
The problem is that compounds, where you initialize it, cannot be interpreted as a file path because it's a list.
Put this before that code:

compounds = "my_dict.txt"

This will write your dictionary in a file in the directory you're in. You can check the directory you're in, or change it with the os package.

ContentLicense: CC BY-SA 3.0

Title: Write python dictionary into textfile

Body:
I want to write my python dictionary in a text file where each line contain one key and its value, with comma as separation. I am using the following code:

with open(compounds, 'w') as f:
    for key, value in dict_NTID_IDs_in_EisDatabase.items():
        f.write('%s:%s\n' % (key, value))

But it returns me the following error TypeError: expected str, bytes or os.PathLike object, not list


问:
show a ViewController from a Detail View Controller in a UISplitViewController
My aim is: To show a popUpViewController in my project in which the user can add a "lesson" (adding a tableViewCell to a tableView) and then save it.
So when the user presses a button inside the DetailViewController of a UISplitViewController , the popUpViewController should show.
I also want the pop-up to be shown as fullscreen with just a small window in the middle and the rest should be black with 0.5 alpha, transparent.

My problem is: I can't find out how I have to show the popUp.

What I've tried and my results:

Tried: Showing it with present(Viewcontroller, animated:, completion: )

Result: It shows fullscreen but the other VC isnt visible in the background anymore.

Tried: The following snippet:

```<code>let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpVC") as! PopUpViewController

self.addChildViewController(popOverVC)
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)
</code>```

Result: The view isnt fullscreen but only the size of the detail View Controller (doesnt cover the part of the masterViewController on the left.

Thanks for your help.

答:
You might try again with present(Viewcontroller, animated:, completion: )
and using modalPresentationStyle with formSheet eg:

```<code>let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpVC") as! PopUpViewController
popOverVC.modalPresentationStyle = .formSheet
self.present(popOverVC, animated: true, completion: nil)
</code>```

Body:
My aim is: To show a popUpViewController in my project in which the user can add a "lesson" (adding a tableViewCell to a tableView) and then save it.
So when the user presses a button inside the DetailViewController of a UISplitViewController , the popUpViewController should show.
I also want the pop-up to be shown as fullscreen with just a small window in the middle and the rest should be black with 0.5 alpha, transparent.

My problem is: I can't find out how I have to show the popUp.

What I've tried and my results:

Tried: Showing it with present(Viewcontroller, animated:, completion: )

Result: It shows fullscreen but the other VC isnt visible in the background anymore.

Tried: The following snippet:

let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpVC") as! PopUpViewController

self.addChildViewController(popOverVC)
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)

Result: The view isnt fullscreen but only the size of the detail View Controller (doesnt cover the part of the masterViewController on the left.

Thanks for your help.

Body:
You might try again with present(Viewcontroller, animated:, completion: )
and using modalPresentationStyle with formSheet eg:

let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpVC") as! PopUpViewController
popOverVC.modalPresentationStyle = .formSheet
self.present(popOverVC, animated: true, completion: nil)


问:
Entity framework attach update not working
I'm trying to update a POCO object using entity framework in the following way:

```<code> context.Jobs.Attach(job);
 context.SaveChanges();
</code>```

That does not work. No error is thrown, it just isn't updating the values in the database.

I tried:

```<code>context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();
</code>```

Nothing wrongs, still no error and no updates.

答:
What about changing the ObjectState?

```<code>context.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);
</code>```

From MSDN: ObjectStateManager.ChangeObjectState Method.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to update a POCO object using entity framework in the following way:

 context.Jobs.Attach(job);
 context.SaveChanges();

That does not work. No error is thrown, it just isn't updating the values in the database.

I tried:

context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();

Nothing wrongs, still no error and no updates.

Body:
What about changing the ObjectState?

context.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);

From MSDN: ObjectStateManager.ChangeObjectState Method.


问:
Map Promise.all output with promises index
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

```<code>let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);
</code>```

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

```<code>[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]
</code>```

But I want data in this format:

```<code>[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]
</code>```

I am sure there must be a way to map every promise by user, but I am not aware of.

答:
We gonna create an array of user. Iterate over it to create an array of Promise we give to Promise.all. Then iterate on the answer to create an object that's matching the user with the associated answer from getUsersData.

Something to know about Promise.all is that the order of the returned data depends on the order of the promises given in entry of it.

```<code>const users = ['user1', 'user2', 'user3'];

const rets = await Promise.all(users.map(x => this.myApiHelper.getUsersData(x)));

const retWithUser = rets.map((x, xi) => ({
   user: users[xi],
   ret: x,
}));
</code>```

Here you have a great tutorial about Array methods (map, filter, some...).

Body:
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]

But I want data in this format:

[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]

I am sure there must be a way to map every promise by user, but I am not aware of.

Body:
We gonna create an array of user. Iterate over it to create an array of Promise we give to Promise.all. Then iterate on the answer to create an object that's matching the user with the associated answer from getUsersData.

Something to know about Promise.all is that the order of the returned data depends on the order of the promises given in entry of it.

const users = ['user1', 'user2', 'user3'];

const rets = await Promise.all(users.map(x => this.myApiHelper.getUsersData(x)));

const retWithUser = rets.map((x, xi) => ({
   user: users[xi],
   ret: x,
}));

Here you have a great tutorial about Array methods (map, filter, some...).


问:
How to subtract two DataFrame columns in Pandas
I want to do some basic calculations inside a pandas dataframe, but apparently pandas ignores empty rows. So let's assume my dataframe looks as follows:

```<code>ColA ColB
11    6
7
</code>```

Then doing df["ColC"] = df["ColA"].subtract(df["ColB"]) will yield

```<code>ColA ColB ColC
11    6    5
7
</code>```

Whereas I would want that ColC also has a "7" in this case.

What's the best way to do these calculations with DataFrames?

答:
I believe you need parameter fill_value=0:

```<code>df["ColC"] = df["ColA"].subtract(df["ColB"], fill_value=0)
</code>```

Body:
I want to do some basic calculations inside a pandas dataframe, but apparently pandas ignores empty rows. So let's assume my dataframe looks as follows:

ColA ColB
11    6
7

Then doing df["ColC"] = df["ColA"].subtract(df["ColB"]) will yield

ColA ColB ColC
11    6    5
7

Whereas I would want that ColC also has a "7" in this case.

What's the best way to do these calculations with DataFrames?

Body:
I believe you need parameter fill_value=0:

df["ColC"] = df["ColA"].subtract(df["ColB"], fill_value=0)


问:
Git bash console on windows does not start
While trying to start a git bash window on any folder in my windows 7 machine, the git bash window closes right away.

I do this by clicking on the "Git Bash" option in the context menu.

When I try to start the Git Bash the console window starts temporarily for a few seconds and exits with a
'logout' message.

I tried to go to the Git installed location and run the "Git Bash.lnk" which exits with this message:

```<code>D:\DevProgs\Installed\Git-1.7.11\Git>"Git Bash.lnk"
Welcome to Git (version 1.7.11-preview20120710)

Run 'git help git' to display the help index.
Run 'git help <command>' to display help for specific commands.

AD@AYUSMAN /
$ logout

D:\DevProgs\Installed\Git-1.7.11\Git>
</code>```

Is there something I am doing wrong? I had been able to use Git Bash without any issues on any folder so far.

System Info:
Windows 7 64 bit professional edition.
Git 1.7.11

答:
Fixed this by:

Open CMD as Admin

CD to the installation path of GitHub (e.g. CMDPRMPT> CD "C:\Program Files\Git")

Run "git-bash.exe" from command prompt

Right-click the GIT BASH icon on the taskbar and pin it so you can avoid steps 1-3 in the future.

OS Version: Windows 7

GIT version: 2.15.0

Hopefully this helps!

Body:
While trying to start a git bash window on any folder in my windows 7 machine, the git bash window closes right away.

I do this by clicking on the "Git Bash" option in the context menu.

When I try to start the Git Bash the console window starts temporarily for a few seconds and exits with a
'logout' message.

I tried to go to the Git installed location and run the "Git Bash.lnk" which exits with this message:

D:\DevProgs\Installed\Git-1.7.11\Git>"Git Bash.lnk"
Welcome to Git (version 1.7.11-preview20120710)

Run 'git help git' to display the help index.
Run 'git help <command>' to display help for specific commands.

AD@AYUSMAN /
$ logout

D:\DevProgs\Installed\Git-1.7.11\Git>

Is there something I am doing wrong? I had been able to use Git Bash without any issues on any folder so far.

System Info:
Windows 7 64 bit professional edition.
Git 1.7.11


问:
How to make work single table inheritance and attr_accessible?
In a rails application, I have a base model like this :

```<code>class User < ActiveRecord::Base
  attr_accessible :email, :name
end
</code>```

And an inheritance from this model, like this :

```<code>class Provider < User
  belongs_to :user

  attr_accessible :business_name, :contact_name, :business_phone_number,
    :business_email, :website, :user_id
end
</code>```

When I do :

```<code>Provider.new.user_id
</code>```

It say NoMethodError: undefined method 'user_id' for #<Provider:0x007f63ec8b3790>.

When I just do Provider.new I have this:

```<code>#<Provider id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, type: "Provider">
</code>```

This is a part of my schema.rb :

```<code>  create_table "providers", :force => true do |t|
    t.string  "business_name",         :null => false
    t.string  "contact_name",          :null => false
    t.string  "business_phone_number", :null => false
    t.string  "business_email",        :null => false
    t.string  "website"
    t.integer "user_id"
  end

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
  end
</code>```

As you can see, the attributes accessibles for Provider are not accessible. Do you have a solution?

Thanks!

答:
The same table is used at the database level. STI is achieved by adding a new column to the existing table. The new column usually named 'type' is used to hold the information whether it is a 'Provider' or 'User'

Here is how the the model queries translate to a sql query

When the User model is queried, as per your example, it searches 'users' table and includes all available type values in the condition

```<code>> User.first
SELECT  `users`.* FROM `users`  WHERE `users`.`type` IN ('User', 'Provider')  ORDER BY `users`.`id` ASC LIMIT 1
</code>```

When the Provider model is queried, type is set as 'Provider' in the condition and so the results get filtered. The underlying database table remains the same ie 'users'

```<code> > Provider.first
SELECT  `users`.* FROM `users`  WHERE `users`.`type` IN ('Provider')  ORDER BY `users`.`id` ASC LIMIT 1
</code>```

Body:
In a rails application, I have a base model like this :

class User < ActiveRecord::Base
  attr_accessible :email, :name
end

And an inheritance from this model, like this :

class Provider < User
  belongs_to :user

  attr_accessible :business_name, :contact_name, :business_phone_number,
    :business_email, :website, :user_id
end

When I do :

Provider.new.user_id

It say NoMethodError: undefined method 'user_id' for #<Provider:0x007f63ec8b3790>.

When I just do Provider.new I have this:

#<Provider id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, type: "Provider">

This is a part of my schema.rb :

  create_table "providers", :force => true do |t|
    t.string  "business_name",         :null => false
    t.string  "contact_name",          :null => false
    t.string  "business_phone_number", :null => false
    t.string  "business_email",        :null => false
    t.string  "website"
    t.integer "user_id"
  end

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
  end

As you can see, the attributes accessibles for Provider are not accessible. Do you have a solution?

Thanks!

Body:
The same table is used at the database level. STI is achieved by adding a new column to the existing table. The new column usually named 'type' is used to hold the information whether it is a 'Provider' or 'User'

Here is how the the model queries translate to a sql query

When the User model is queried, as per your example, it searches 'users' table and includes all available type values in the condition

> User.first
SELECT  `users`.* FROM `users`  WHERE `users`.`type` IN ('User', 'Provider')  ORDER BY `users`.`id` ASC LIMIT 1

When the Provider model is queried, type is set as 'Provider' in the condition and so the results get filtered. The underlying database table remains the same ie 'users'

 > Provider.first
SELECT  `users`.* FROM `users`  WHERE `users`.`type` IN ('Provider')  ORDER BY `users`.`id` ASC LIMIT 1


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答:
the jquery load function allows you to specify an element id to load

```<code>$('#result').load('ajax/test.html #container');
</code>```

http://api.jquery.com/load/

Body:
the jquery load function allows you to specify an element id to load

$('#result').load('ajax/test.html #container');

http://api.jquery.com/load/


问:
android.view.InflateException: Binary XML file line #142: Error inflating class TextView
currently I'm learning android developing, and I have one problem with Textview and I haven't any idea how to solve it.

```<code>07-13 10:46:00.240 16541-16541/sabo.idocs E/AndroidRuntime: FATAL EXCEPTION: main
Process: sabo.idocs, PID: 16541
android.view.InflateException: Binary XML file line #142: Error inflating class TextView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
    at sabo.idocs.main.menu.profile.Profile.onCreateView(Profile.java:82)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
    at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5356)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f020053 a=-1 r=0x7f020053}
    at android.content.res.Resources.loadDrawable(Resources.java:3014)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.TextView.<init>(TextView.java:1220)
    at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:62)
    at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:58)
    at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
    at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1026)
    at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1083)
    at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:173)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
    at sabo.idocs.main.menu.profile.Profile.onCreateView(Profile.java:82)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
    at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5356)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

and here my Textview:

```<code><TextView
    android:id="@+id/change_icon2"
    android:layout_alignTop="@+id/password_change_text"
    android:layout_toEndOf="@+id/view2"
    android:drawableRight="@drawable/arrow_right"
    android:padding="7dp"
    android:textAlignment="textEnd"
    android:layout_width="match_parent"
    android:layout_height="35dp" />
</code>```

And this is my fragment class:

```<code>public class Profile extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

private ImageView userAvatar;
private TextView userName;
private TextView passwordChange;
private EditText emailText;
private EditText mobilePhone;

private String path;

private OkHttpClient client;
private Request request;

private SwipeRefreshLayout swipeLayout;
private SharedPreferences sharedPreferences;
private RelativeLayout profileLayout;
private User user;

private static final int PICK_IMAGE_REQUEST = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View profile = inflater.inflate(R.layout.profile_fragment, container, false);

    profileLayout = (RelativeLayout)profile.findViewById(R.id.profile_layout);

    sharedPreferences = getContext().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);

    Gson gson = new Gson();
    String userData = sharedPreferences.getString(SingletonConstants.USER, "");
    user = gson.fromJson(userData, User.class);

    userAvatar = (ImageView)profile.findViewById(R.id.user_avatar);
    userAvatar.setScaleType(ImageView.ScaleType.CENTER_CROP);
    userName = (TextView)profile.findViewById(R.id.user_name);
    emailText = (EditText)profile.findViewById(R.id.email_json);
    mobilePhone = (EditText)profile.findViewById(R.id.mob_phone);
    passwordChange = (TextView)profile.findViewById(R.id.change_icon2);

    passwordChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), ProfilePassword.class);
            startActivity(intent);
        }
    });

    swipeLayout = (SwipeRefreshLayout) profile.findViewById(R.id.swipe_container_profile);
    swipeLayout.setOnRefreshListener(this);

    swipeLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_blue_bright, android.R.color.holo_orange_light);

    profileDefaults();
    onClick();
    return profile;
}
</code>```

Yes, I saw this question but in my case it doesn't work. Please help.

答: Try moving the image from drawable folder to mipmap. This worked for me.</p>

Body:
currently I'm learning android developing, and I have one problem with Textview and I haven't any idea how to solve it.

07-13 10:46:00.240 16541-16541/sabo.idocs E/AndroidRuntime: FATAL EXCEPTION: main
Process: sabo.idocs, PID: 16541
android.view.InflateException: Binary XML file line #142: Error inflating class TextView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
    at sabo.idocs.main.menu.profile.Profile.onCreateView(Profile.java:82)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
    at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5356)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f020053 a=-1 r=0x7f020053}
    at android.content.res.Resources.loadDrawable(Resources.java:3014)
    at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
    at android.widget.TextView.<init>(TextView.java:1220)
    at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:62)
    at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:58)
    at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
    at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1026)
    at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1083)
    at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:173)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:690)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
    at sabo.idocs.main.menu.profile.Profile.onCreateView(Profile.java:82)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
    at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5356)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
    at dalvik.system.NativeStart.main(Native Method)

and here my Textview:

<TextView
    android:id="@+id/change_icon2"
    android:layout_alignTop="@+id/password_change_text"
    android:layout_toEndOf="@+id/view2"
    android:drawableRight="@drawable/arrow_right"
    android:padding="7dp"
    android:textAlignment="textEnd"
    android:layout_width="match_parent"
    android:layout_height="35dp" />

And this is my fragment class:

public class Profile extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

private ImageView userAvatar;
private TextView userName;
private TextView passwordChange;
private EditText emailText;
private EditText mobilePhone;

private String path;

private OkHttpClient client;
private Request request;

private SwipeRefreshLayout swipeLayout;
private SharedPreferences sharedPreferences;
private RelativeLayout profileLayout;
private User user;

private static final int PICK_IMAGE_REQUEST = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View profile = inflater.inflate(R.layout.profile_fragment, container, false);

    profileLayout = (RelativeLayout)profile.findViewById(R.id.profile_layout);

    sharedPreferences = getContext().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);

    Gson gson = new Gson();
    String userData = sharedPreferences.getString(SingletonConstants.USER, "");
    user = gson.fromJson(userData, User.class);

    userAvatar = (ImageView)profile.findViewById(R.id.user_avatar);
    userAvatar.setScaleType(ImageView.ScaleType.CENTER_CROP);
    userName = (TextView)profile.findViewById(R.id.user_name);
    emailText = (EditText)profile.findViewById(R.id.email_json);
    mobilePhone = (EditText)profile.findViewById(R.id.mob_phone);
    passwordChange = (TextView)profile.findViewById(R.id.change_icon2);

    passwordChange.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), ProfilePassword.class);
            startActivity(intent);
        }
    });

    swipeLayout = (SwipeRefreshLayout) profile.findViewById(R.id.swipe_container_profile);
    swipeLayout.setOnRefreshListener(this);

    swipeLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_blue_bright, android.R.color.holo_orange_light);

    profileDefaults();
    onClick();
    return profile;
}

Yes, I saw this question but in my case it doesn't work. Please help.


问:
How to set AUTO_INCREMENT from another table
How can I set the AUTO_INCREMENT on CREATE TABLE or ALTER TABLE from another table?

I found this question, but not solved my issue:
How to Reset an MySQL AutoIncrement using a MAX value from another table?

I also tried this:

```<code>CREATE TABLE IF NOT EXISTS `table_name` (
  `id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
  `columnOne` tinyint(1) NOT NULL,
  `columnTwo` int(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM  `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');
</code>```

this:

```<code>ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM  `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');
</code>```

this:

```<code>CREATE TABLE IF NOT EXISTS `table_name` (
  `id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
  `columnOne` tinyint(1) NOT NULL,
  `columnTwo` int(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);
</code>```

and this:

```<code>ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);
</code>```

答:
```<code>SELECT `AUTO_INCREMENT` INTO @AutoInc
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'my_db' AND TABLE_NAME = 'old_table';

SET @s:=CONCAT('ALTER TABLE `my_db`.`new_table` AUTO_INCREMENT=', @AutoInc);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Body:
How can I set the AUTO_INCREMENT on CREATE TABLE or ALTER TABLE from another table?

I found this question, but not solved my issue:
How to Reset an MySQL AutoIncrement using a MAX value from another table?

I also tried this:

CREATE TABLE IF NOT EXISTS `table_name` (
  `id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
  `columnOne` tinyint(1) NOT NULL,
  `columnTwo` int(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM  `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');

this:

ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT `AUTO_INCREMENT` FROM  `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'database_name' AND `TABLE_NAME` = 'another_table_name');

this:

CREATE TABLE IF NOT EXISTS `table_name` (
  `id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
  `columnOne` tinyint(1) NOT NULL,
  `columnTwo` int(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);

and this:

ALTER TABLE `table_name` AUTO_INCREMENT=(SELECT (MAX(`id`)+1) FROM `another_table_name`);


问:
Pass data to model from controller in codeigniter
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

```<code>Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)
</code>```

controller:

```<code>public function postEnquiry()
{
    $data = $this->input->post();
    // echo "```";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}
```

<p>Model:</p>

```<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>
```

答:
First, you must define the variable then assign post values to variable and pass the arguments,</p>

```<code>public function postEnquiry()
{
    $this->load->model('Enquiry');
    $data = array();
    $data = $this->input->post();
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }
}

(OR)

// You can get post values from model directly
// 1.Controller
public function postEnquiry()
{
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry();
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }
}

// 2.Model
public function sendenquiry()
{
  echo '```'; print_r($this->input->post()); echo '```'; //post values
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting data from view using post method ie., in $data variable
and I need pass this  i.e, $data to model I have tried like below but it is showing like A PHP

Error was encountered Severity: Notice Message:  Undefined property:
  Post::$data Filename: core/Model.php Line Number: 77

Below is mycode:

Array
(
    [name] => Mohan
    [email] => mohan@gmail.com
    [phone] => 9739764966
    [location] => TEST
    [website] => 192.168.1.156
    [useragent] => Chrome
    [ipaddress] => 192.168.1.23
    [desc] => Bengaluru
    [captcha] => 20701449
    [captcha_word] => 20701449
    [submit] => Submit
)

controller:

public function postEnquiry()
{
    $data = $this->input->post();
    // echo "
";print_r($data);die;
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }

}

Model:

<?php
class Enquiry extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function sendenquiry($data)
    {
        print_r($data);die;
    }

}
?>

Body:
First, you must define the variable then assign post values to variable and pass the arguments,

public function postEnquiry()
{
    $this->load->model('Enquiry');
    $data = array();
    $data = $this->input->post();
    $result = $this->Enquiry->sendenquiry($data);
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }
}

(OR)

// You can get post values from model directly
// 1.Controller
public function postEnquiry()
{
    $this->load->model('Enquiry');
    $result = $this->Enquiry->sendenquiry();
    if($result){
        $this->session->set_flashdata('success','Sent Successfully');
        redirect(ROOT_PATH."/form");
    }
}

// 2.Model
public function sendenquiry()
{
  echo '<pre>'; print_r($this->input->post()); echo '</pre>'; //post values
}


问:
How to use component variable within css / style tag in Angular 2?
How can I use component variables within style TAG in Angular 2?

I do have an Angular 2 component for my header which I like to color depending on a users setting. Thus I'd like to assign an background and font color. While I know how to to this with an attribute binding to an element, I couldn't figure out how to use in a style tag.

Using attribute binding for style works well, however this gets pretty anoying for several subelements, especially if they are nested within other sub components. [ngStyle]= attribute is also only working on a single element.

```<code><header id="header" [style.background-color]="changeBackground()">
  <div>
    Some Text
    <a href="asdf">Some Link</a>
    <subcomponent></subcomponent>
  </div>
  <div> ... a lot mor stuff </div>
</header>
</code>```

Thus I'd like to add something like

```<code><style>
#header, #header a {
  color: {{mycolor}};
}
</style>
</code>```

to the html template. However this is not working

Similar Questions do not answer this question yet and only show attribute binding as a solution:

Angular2 dynamic change CSS property

Dynamically updating css in Angular 2

https://scotch.io/tutorials/all-the-ways-to-add-css-to-angular-2-components

https://coryrylan.com/blog/introduction-to-angular-2-ngclass-and-ngstyle

答:
Use NgStyle as explained in this answer

https://stackoverflow.com/a/41903349

in short

```<code><header id="header" [ngStyle]="getStyle()">
  <div>
    Some Text
    <a href="asdf">Some Link</a>
    <subcomponent></subcomponent>
  </div>
  <div> ... a lot mor stuff </div>
</header>
</code>```

and

```<code>getStyle(): any {
    return {"background-color" : this.changeBackgroundColor()};
}
</code>```

Body:
How can I use component variables within style TAG in Angular 2?

I do have an Angular 2 component for my header which I like to color depending on a users setting. Thus I'd like to assign an background and font color. While I know how to to this with an attribute binding to an element, I couldn't figure out how to use in a style tag.

Using attribute binding for style works well, however this gets pretty anoying for several subelements, especially if they are nested within other sub components. [ngStyle]= attribute is also only working on a single element.

    Some Text
    Some Link
    <subcomponent></subcomponent>

 ... a lot mor stuff

Thus I'd like to add something like

to the html template. However this is not working

Similar Questions do not answer this question yet and only show attribute binding as a solution:

Angular2 dynamic change CSS property

Dynamically updating css in Angular 2

https://scotch.io/tutorials/all-the-ways-to-add-css-to-angular-2-components

https://coryrylan.com/blog/introduction-to-angular-2-ngclass-and-ngstyle

Body:
Use NgStyle as explained in this answer

https://stackoverflow.com/a/41903349

in short

<header id="header" [ngStyle]="getStyle()">
  <div>
    Some Text
    <a href="asdf">Some Link</a>
    <subcomponent></subcomponent>
  </div>
  <div> ... a lot mor stuff </div>
</header>

and

getStyle(): any {
    return {"background-color" : this.changeBackgroundColor()};
}


问:
Fragment instantiation: Why isn't savedInstanceState bundle enough?
I've been using for a while the best practice recommended by Google of having a MyFragment.newInstance() static function. Though thinking about it, why can't we simplify it removing this static function, the call to onCreate to access the arguments, and only using one bundle to always save and retrieve the latest data when recreating the fragment ?

I made a simple test that seems to work just as fine as the slightly heavier current practice.

The state persisted after activity recreation, orientation change, and fragment re-creation in a FragmentStatePagerAdapter.

Am I missing anything?

```<code>public class TestFragment extends Fragment {

    private String fragmentText;

    public TestFragment() { } // Required empty public constructor

    @SuppressLint("ValidFragment")
    public TestFragment(String fragmentText) {
        // add here other init arguments
        // don't save them in any bundle yet
        this.fragmentText = fragmentText;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // retrieve all arguments here
            fragmentText = savedInstanceState.getString("fragmentText", fragmentText);
        }
        TextView textView = new TextView(getActivity());
        textView.setText(fragmentText);
        return textView;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // save everything here once, only when needed
        outState.putString("fragmentText", fragmentText);
    }

    // Add your setters to interact with the fragment
    // those changes will persists after fragment re-creation
    public void setFragmentText(String fragmentText) {
        this.fragmentText = fragmentText;
    }
}
</code>```

答: Because savedInstance doesn't call every time. It will be triggered when device screen will be rotated or when inner system kill application due to low memory and some more scenarios. So if you want to pass some values from activities to fragment or fragment to fragment you must have to pass it through Argument. There are plenty of others ways -> you can make static variable and store the value in it but thats not a perfect value to pass value -> it will consume lot of memory. So passing through argument is standard way

Body:
I've been using for a while the best practice recommended by Google of having a MyFragment.newInstance() static function. Though thinking about it, why can't we simplify it removing this static function, the call to onCreate to access the arguments, and only using one bundle to always save and retrieve the latest data when recreating the fragment ?

I made a simple test that seems to work just as fine as the slightly heavier current practice.

The state persisted after activity recreation, orientation change, and fragment re-creation in a FragmentStatePagerAdapter.

Am I missing anything?

public class TestFragment extends Fragment {

    private String fragmentText;

    public TestFragment() { } // Required empty public constructor

    @SuppressLint("ValidFragment")
    public TestFragment(String fragmentText) {
        // add here other init arguments
        // don't save them in any bundle yet
        this.fragmentText = fragmentText;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // retrieve all arguments here
            fragmentText = savedInstanceState.getString("fragmentText", fragmentText);
        }
        TextView textView = new TextView(getActivity());
        textView.setText(fragmentText);
        return textView;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // save everything here once, only when needed
        outState.putString("fragmentText", fragmentText);
    }

    // Add your setters to interact with the fragment
    // those changes will persists after fragment re-creation
    public void setFragmentText(String fragmentText) {
        this.fragmentText = fragmentText;
    }
}


问:
Reduce space between rows in CSS Grid
I'm wondering how to reduce the spacing between the rows? I've tried setting margins and paddings to 0, but nothing seems to be biting.

Destktop view on the left and mobile view on the right.

```<code>.content{
    margin: 0;
    padding: 0;
    width: 100%;
    display: grid;
    grid-gap: 5px;
    grid-template-columns: repeat(36, 1fr);
    justify-items: stretch;
    align-content: start;
    }

.one{
    grid-column: 1/37;
    width: 100%;
}

.two{
    grid-column: 1/11;

}
.three{
    grid-column: 12/24;
    justify-self: center;
    align-self: start;
    position: relative;
    bottom: 5px;
}
.four{
    grid-column: 25/37;
}
</code>```

Here's a link to a test site:
http://www.acm.no/test/valhall/

答:
That gap doesn't exist between rows. The rows are close together.

The gap is the result of the content inside the grid items not filling 100% height.

Then, you have a second element which takes up space at the bottom.

```<code><div class="ctrl">
</code>```

You need to decide what to do with that element. Consider absolute positioning to remove it from the document flow. Then it won't occupy any space in the layout.

In any case, without that element (and with the optional addition of vertical-align), the video fills up the grid item.

(Also look into the object-fit property for getting videos / images to fill up their containers.)

Title: Reduce space between rows in CSS Grid

Body:
I'm wondering how to reduce the spacing between the rows? I've tried setting margins and paddings to 0, but nothing seems to be biting.

Destktop view on the left and mobile view on the right.

.content{
    margin: 0;
    padding: 0;
    width: 100%;
    display: grid;
    grid-gap: 5px;
    grid-template-columns: repeat(36, 1fr);
    justify-items: stretch;
    align-content: start;
    }

.one{
    grid-column: 1/37;
    width: 100%;
}

.two{
    grid-column: 1/11;

}
.three{
    grid-column: 12/24;
    justify-self: center;
    align-self: start;
    position: relative;
    bottom: 5px;
}
.four{
    grid-column: 25/37;
}

Here's a link to a test site:
http://www.acm.no/test/valhall/

Body:
That gap doesn't exist between rows. The rows are close together.

The gap is the result of the content inside the grid items not filling 100% height.

Then, you have a second element which takes up space at the bottom.

<div class="ctrl">

You need to decide what to do with that element. Consider absolute positioning to remove it from the document flow. Then it won't occupy any space in the layout.

In any case, without that element (and with the optional addition of vertical-align), the video fills up the grid item.

(Also look into the object-fit property for getting videos / images to fill up their containers.)


问:
How to execute a same query for 7 days in Oracle sql developer
I have a query

```<code>select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);
</code>```

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

```<code>  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110
</code>```

Is it achievable ?

答:
I'd use something like</p>

```<code>with
  dates as (select trunc(sysdate) - rownum + 1 d# from dual connect by level <= 7)
select
  d.d#,
  sum(case when p.start_time is not null then 1 else 0 end)
from
  dates d,
  purchases p
where
  p.client_id (+) in (1, 54) and
  p.start_time (+) between d.d# and d.d# + 1/24
group by
  d#
order by
  d#
</code>```

Body:
I have a query

select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110

Is it achievable ?

Body:
I'd use something like

with
  dates as (select trunc(sysdate) - rownum + 1 d# from dual connect by level <= 7)
select
  d.d#,
  sum(case when p.start_time is not null then 1 else 0 end)
from
  dates d,
  purchases p
where
  p.client_id (+) in (1, 54) and
  p.start_time (+) between d.d# and d.d# + 1/24
group by
  d#
order by
  d#


问:
Thread not working as intended
I am pretty confuse why my program is not working as intended.

I have three similar function:

```<code>static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L2(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L2", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L3(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L3", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}
</code>```

Next I have a function for creating thread:

```<code>static void createKThread(void* (*a)(void *), void* (*b)(void *), void* (*c)(void *))

{
  pthread_t t1, t2, t3;
  int T1, T2, T3;

  T1 =  pthread_create(&t1, NULL, a, NULL);
  T2 =  pthread_create(&t2, NULL, b, NULL);
  T3 =  pthread_create(&td3, NULL, c, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  pthread_join(t3, NULL);

}
</code>```

In my main I am doing :

```<code>     int main(){

     Send2[0] = 'a';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

     Send2[0] = 'b';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //Second
     return 0;
     }
</code>```

My main program terminates after completion of the first function call `createKThread´. I can't figure out why, I would like the second function call to work and I would like to add more code to my main program. Please advice me on what I am doing wrongly.

答:
Here:

```<code> createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First
</code>```

your argument L1(&Send[0]) is evaluated by calling L1 with parameter &Send[0]. This is not what you want. You want to pass the function pointer L1 and the argument separately, i.e.:

```<code>createKThread(L1, &Send[0], L2, &Send[0], L3, &Send[0]);
</code>```

with

```<code>static void createKThread(void* (*a)(void *), void *aarg,
                          void* (*b)(void *), void *barg,
                          void* (*c)(void *), void *carg) {
    ...
    T1 =  pthread_create(&t1, NULL, a, aarg);
    ...
}
</code>```

etc. Then it should work as you expect.

As a side note: You should pay attention to crash messages (i.e. "Segmentation fault") or compiler warnings (enable all!) when debugging a problem.

Title: Thread not working as intended

Body:
I am pretty confuse why my program is not working as intended.

I have three similar function:

static void *L1(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L1", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L2(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L2", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

static void *L3(void *ptr )
{
    char *text = (char *)ptr;
    int ret;
    int fd = open("/dev/L3", O_RDWR);

    ret = write(fd, text, strlen(Send)); // Send string to LKM
}

Next I have a function for creating thread:

static void createKThread(void* (*a)(void *), void* (*b)(void *), void* (*c)(void *))

{
  pthread_t t1, t2, t3;
  int T1, T2, T3;

  T1 =  pthread_create(&t1, NULL, a, NULL);
  T2 =  pthread_create(&t2, NULL, b, NULL);
  T3 =  pthread_create(&td3, NULL, c, NULL);

  pthread_join(t1, NULL);
  pthread_join(t2, NULL);
  pthread_join(t3, NULL);

}

In my main I am doing :

     int main(){

     Send2[0] = 'a';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

     Send2[0] = 'b';
     createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //Second
     return 0;
     }

My main program terminates after completion of the first function call `createKThread´. I can't figure out why, I would like the second function call to work and I would like to add more code to my main program. Please advice me on what I am doing wrongly.

Body:
Here:

 createKThread(L1(&Send[0]), L2(&Send[0]), L3(&Send[0])); //First

your argument L1(&Send[0]) is evaluated by calling L1 with parameter &Send[0]. This is not what you want. You want to pass the function pointer L1 and the argument separately, i.e.:

createKThread(L1, &Send[0], L2, &Send[0], L3, &Send[0]);

with

static void createKThread(void* (*a)(void *), void *aarg,
                          void* (*b)(void *), void *barg,
                          void* (*c)(void *), void *carg) {
    ...
    T1 =  pthread_create(&t1, NULL, a, aarg);
    ...
}

etc. Then it should work as you expect.

As a side note: You should pay attention to crash messages (i.e. "Segmentation fault") or compiler warnings (enable all!) when debugging a problem.


问:
How can I disable selected attribute from select2() dropdown Jquery?
I know how to enable the selected attribute from dropdown; I can use this code :

```<code>$('select').select2();
</code>```

but my problem is how to disable it ? thx

答:
In selec2 site you can see options. There is "disabled" option for api. You can use like :</p>

```<code>$('#foo').select2({
    disabled: true
});
</code>```

Body:
I know how to enable the selected attribute from dropdown; I can use this code :

$('select').select2();

but my problem is how to disable it ? thx

Body:
In selec2 site you can see options. There is "disabled" option for api. You can use like :

$('#foo').select2({
    disabled: true
});


问:
CSV reference data in Azure Stream Analytics
I have a stream analytics application where events are JSON encoded and look like this

```<code>{customerID: 45, state:"S2" , timestamp:"2017-06-06 14:19:21.77"}
{customerID: 74, state:"S2" , timestamp:"2017-06-06 14:19:26.61"}
{customerID: 79, state:"S2" , timestamp:"2017-06-06 14:19:28.50"}
{customerID: 10, state:"D" , timestamp:"2017-06-06 14:19:31.79"}
{customerID: 70, state:"S2" , timestamp:"2017-06-06 14:19:31.93"}
{customerID: 37, state:"S2" , timestamp:"2017-06-06 14:19:32.17"}
{customerID: 41, state:"D" , timestamp:"2017-06-06 14:19:33.48"}
</code>```

I have reference data for customers in a CSV file that looks like this:

```<code>"CUST_ID", "Age", "Rich"
1, "50", "Y"
2, "22", "N"
</code>```

I load the data files in the aforementioned formats and test the following query

```<code>select A.[CUSTOMERID], A.[state], B.[AGE], B.[GENDER_CODE] from clickstream A timestamp by A.[TIMESTAMP] left join refdata B on A.[CUSTOMERID]=B.[CUST_ID]
</code>```

I get the following error message with no details:

Now, the same query works perfectly if the data reference data is represented as JSON. Is there a working example I can have a look at with CSV reference data?

答:
"Test" button with reference data didn't work for me at all. I had to use Azure Stream analytics tools for Visual Studio to test it in local environment.

Regarding an error in path pattern. I used YYYY-MM-DD and by default stream analytics used YYYY/MM/DD. When the job was running, I saw an exclamation mark next to input in Stream analytics dashboard.

To debug error you should click on reference data input in Stream Analytics overview and you should see warnings on its blade.

Mine warning was like:

Initializing input without a valid reference data blob for UTC time 11/14/2017 12:22:32 PM, example path: 'https://blabla.blob.core.windows.net/cohorts/2017/11/14/12-22/result.csv'

Body:
I have a stream analytics application where events are JSON encoded and look like this

{customerID: 45, state:"S2" , timestamp:"2017-06-06 14:19:21.77"}
{customerID: 74, state:"S2" , timestamp:"2017-06-06 14:19:26.61"}
{customerID: 79, state:"S2" , timestamp:"2017-06-06 14:19:28.50"}
{customerID: 10, state:"D" , timestamp:"2017-06-06 14:19:31.79"}
{customerID: 70, state:"S2" , timestamp:"2017-06-06 14:19:31.93"}
{customerID: 37, state:"S2" , timestamp:"2017-06-06 14:19:32.17"}
{customerID: 41, state:"D" , timestamp:"2017-06-06 14:19:33.48"}

I have reference data for customers in a CSV file that looks like this:

"CUST_ID", "Age", "Rich"
1, "50", "Y"
2, "22", "N"

I load the data files in the aforementioned formats and test the following query

select A.[CUSTOMERID], A.[state], B.[AGE], B.[GENDER_CODE] from clickstream A timestamp by A.[TIMESTAMP] left join refdata B on A.[CUSTOMERID]=B.[CUST_ID]

I get the following error message with no details:

Now, the same query works perfectly if the data reference data is represented as JSON. Is there a working example I can have a look at with CSV reference data?


问:
Memory leak c++ list of array
We have code like this:

```<code>  void main(){
  std::list<int *> ll;
  for(int i=0;i<100;i++)
   {
      int *a = new int[10000];
      ll.push_back(a);
   }
  for(int *b : ll)
  {
     delete [] b;
  }
 ll.clear();

}
</code>```

But the memory not free?
Why?
When run this code work correctly:

```<code>void main(){
 for(int i=0;i<100;i++)
 {
     int *a = new int[10000];
     delete [] a;
 }
}
</code>```

I monitor memory with top command in linux and system monitoring, so in first code in first for the memory was going up and after that i expect that in last for the app free the memory but not free memory.

答:
[I monitor memory] in linux with top command and system monitoring

This approach will not give you an accurate result. Linux top command tells you how much memory the process holds, which includes the memory the allocator requested from OS. top does not know how much of this memory has been given to your program by the allocator, and how much is kept for giving to your program in the future.

In order to check your program for memory leaks and other memory-related errors use a memory profiling tool, such as valgrind. The profiler would detect memory leaks, and inform you of the places in your program that allocated blocks of memory which were not returned back to the allocator.

Note: The reason your other code appears to work is that the allocator needs a lot less memory, because the same chunk of memory gets allocated and de-allocated repeatedly in the loop.

Title: Memory leak c++ list of array

Body:
We have code like this:

  void main(){
  std::list<int *> ll;
  for(int i=0;i<100;i++)
   {
      int *a = new int[10000];
      ll.push_back(a);
   }
  for(int *b : ll)
  {
     delete [] b;
  }
 ll.clear();

}

But the memory not free?
Why?
When run this code work correctly:

void main(){
 for(int i=0;i<100;i++)
 {
     int *a = new int[10000];
     delete [] a;
 }
}

I monitor memory with top command in linux and system monitoring, so in first code in first for the memory was going up and after that i expect that in last for the app free the memory but not free memory.


问:
Calculating the length of a segment in a logarithmic scale
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});```
</div>
</div>
</p>

<p>This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present. </p>

<p>I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)</p>

<p>How should I modify lineLen to use a logarithmic scale?</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 maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});</code>```

答:
You are scaling these numbers. Your starting set is the domain, what you end up with is the range. The shape of that transformation, it sounds like, will be either log or follow a power.

It turns out this is a very common problem in many fields, especially data visualization. That is why D3.js - THE data visualization tool - has everything you need to do this easily.

```<code> const x = d3.scale.log().range([0, events]);
</code>```

It's the right to for the job. And if you need to do some graphs, you're all set!

Body:
I want to calculate the length of a line for a series of events.

I'm doing this with the following code.

var maxLineLength = 20;
var lineLen = function(x, max) {
    return maxLineLength * (x / max);
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});

This works, but I'm using linear scaling, while I'd like to use logarithms, because I don't want small events to become too small numbers when big ones are present.

I modified the lineLen function as you can see below, but - obviously - it doesn't work for events equals to one, because the log of one is zero. I want to show events equals to one (opportunely scaled) and not make them become zero. I also need positive numbers to remain positive (0.1 becomes a negative number)

How should I modify lineLen to use a logarithmic scale?

var maxLineLength = 20;
var lineLen = function(x, max) {
   return maxLineLength * (Math.log(x) / Math.log(max));
}
var events = [0.1, 1, 5, 20, 50];
var max = Math.max.apply(null, events);
events.map(function (x) {
    console.log(lineLen(x, max));
});

Body:
You are scaling these numbers. Your starting set is the domain, what you end up with is the range. The shape of that transformation, it sounds like, will be either log or follow a power.

It turns out this is a very common problem in many fields, especially data visualization. That is why D3.js - THE data visualization tool - has everything you need to do this easily.

 const x = d3.scale.log().range([0, events]);

It's the right to for the job. And if you need to do some graphs, you're all set!


问:
Rcpp: call an R function from the Global Environment and use it in the C++ code
How can I call an R function that does not belong to any R package into a C++ code?. I can show you what I mean through a very semplicistic example. Suppose I have an R file where I write

```<code>myRfunction <- function(x){
 return(x+2)
}
</code>```

and I want to use it in a generic c++ code. So, I write something like

```<code>#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec myCppfunction(arma::vec y){
 arma::sec results = myRfunction(y);  /* Or whatever I have to do to call it! */
 return results;
}
</code>```

Can someone tell me how to do it? What is the general procedure? Thank you all.

答:
Example. In R:

```<code>> timesTwoR <- function(x) 2*x
</code>```

The cpp file:

```<code>#include <Rcpp.h>
using namespace Rcpp;

Function timesTwoFromR = Environment::global_env()["timesTwoR"];

// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
  return timesTwoFromR(x);
}
</code>```

Then, in R:

```<code>> timesTwo(42)
[1] 84
</code>```

Body:
How can I call an R function that does not belong to any R package into a C++ code?. I can show you what I mean through a very semplicistic example. Suppose I have an R file where I write

myRfunction <- function(x){
 return(x+2)
}

and I want to use it in a generic c++ code. So, I write something like

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
using namespace std;

// [[Rcpp::export]]

arma::vec myCppfunction(arma::vec y){
 arma::sec results = myRfunction(y);  /* Or whatever I have to do to call it! */
 return results;
}

Can someone tell me how to do it? What is the general procedure? Thank you all.

Body:
Example. In R:

> timesTwoR <- function(x) 2*x

The cpp file:

#include <Rcpp.h>
using namespace Rcpp;

Function timesTwoFromR = Environment::global_env()["timesTwoR"];

// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
  return timesTwoFromR(x);
}

Then, in R:

> timesTwo(42)
[1] 84


问:
Hot swapping in Spring Boot in Visual Studio Code
I just started a Spring Boot project with Angular 4. And for Angular I can run npm start so that NPM compiles every change. But I can't figure out how to do that for Spring Boot. I can find some sources for Eclipse/IntelliJ but I would like to stay with my Visual Studio Code editor.

答:
A little late for this but I was searching for the same and got here.
Maybe this could be useful for someone else.

The answer for that is in the documentation of spring.

Read here:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html

And then here:

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html

In case you have problems with the links...

If your'e using Maven just add this dependency in your pom:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
</code>```

Or if you're using Gradle:

```<code>dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}
</code>```

I hope this helps someone.

Body:
A little late for this but I was searching for the same and got here.
Maybe this could be useful for someone else.

The answer for that is in the documentation of spring.

Read here:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-hotswapping.html

And then here:

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html

In case you have problems with the links...

If your'e using Maven just add this dependency in your pom:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

Or if you're using Gradle:

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}

I hope this helps someone.


问:
Serialize closure without environment
I am serializing objects with the serialize function.

For example

```<code>serialize_object <- serialize(some_object, NULL)
</code>```

Now I have an issue with closures. For example:

```<code>closure <- function(){
  member <- NULL
  list(init=function(val){member <<- val})
}
closure_serialized <- serialize(closure(), NULL)
</code>```

This raw object closure_serialized is huge: some 200MB. I am quite sure that also the environment in which it is made is serialized. But I don't need its environment. I only need the closure and its contents.

Am I doing something wrong? Am I initializing or defining the closure in a wrong way? How can I make it only to serialize the closure and not the rest of the environment? Serializing closures from some packages do not have this effect, and I can not find the culprit.

答:
This is mainly because the definition of the closure is within a function.

```<code>fn <- function(){

    # make big variables

    closure <- function(){
      member <- NULL
      list(init=function(val){member <<- val})
    }

    closure_serialized <- serialize(closure(), NULL)
}

# serialize will copy the environment within the function in closure_serialized
fn()
</code>```

The serialize function will in that case copy the environment also. A "workaround" is to place the definition of the closure in the global environment.

```<code>closure <- function(){
  member <- NULL
  list(init=function(val){member <<- val})
}

fn <- function(){

    # make big variables

    closure_serialized <- serialize(closure(), NULL)
}

# serialize will not copy the global environment.
fn()
</code>```

The serialize doesn't copy .GlobalEnv environment. See also here for a related topic.

Title: Serialize closure without environment

Body:
I am serializing objects with the serialize function.

For example

serialize_object <- serialize(some_object, NULL)

Now I have an issue with closures. For example:

closure <- function(){
  member <- NULL
  list(init=function(val){member <<- val})
}
closure_serialized <- serialize(closure(), NULL)

This raw object closure_serialized is huge: some 200MB. I am quite sure that also the environment in which it is made is serialized. But I don't need its environment. I only need the closure and its contents.

Am I doing something wrong? Am I initializing or defining the closure in a wrong way? How can I make it only to serialize the closure and not the rest of the environment? Serializing closures from some packages do not have this effect, and I can not find the culprit.

Body:
This is mainly because the definition of the closure is within a function.

fn <- function(){

    # make big variables

    closure <- function(){
      member <- NULL
      list(init=function(val){member <<- val})
    }

    closure_serialized <- serialize(closure(), NULL)
}

# serialize will copy the environment within the function in closure_serialized
fn()

The serialize function will in that case copy the environment also. A "workaround" is to place the definition of the closure in the global environment.

closure <- function(){
  member <- NULL
  list(init=function(val){member <<- val})
}

fn <- function(){

    # make big variables

    closure_serialized <- serialize(closure(), NULL)
}

# serialize will not copy the global environment.
fn()

The serialize doesn't copy .GlobalEnv environment. See also here for a related topic.


问:
Entity framework attach update not working
I'm trying to update a POCO object using entity framework in the following way:

```<code> context.Jobs.Attach(job);
 context.SaveChanges();
</code>```

That does not work. No error is thrown, it just isn't updating the values in the database.

I tried:

```<code>context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();
</code>```

Nothing wrongs, still no error and no updates.

答: I guess you are working with detached object - check second part of this answer.</p>

Body:
I'm trying to update a POCO object using entity framework in the following way:

 context.Jobs.Attach(job);
 context.SaveChanges();

That does not work. No error is thrown, it just isn't updating the values in the database.

I tried:

context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();

Nothing wrongs, still no error and no updates.


问:
Android. HTTP error fetching URL. Status=403
I'm trying to get data from site.
When I use this code in Intellij IDEA everything works fine, but when I use this code in Android Studio and real device, I get:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403

Here is my code:

```<code>private static final String URL = "http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM";

private static final String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/52.0.2743.116 Safari/537.36";

Document document = Jsoup.connect(URL)
                        .userAgent(useragent)
                        .ignoreContentType(true)
                        .timeout(5000)
                        .execute() //  <-- on this line I get error
                        .parse();
</code>```

All information that I have found is only about "userAgent()" method, but It didn't help.

UPD: Sorry, it was my bad in question. Correct url: http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM, but I still have the same problem.

Error:  org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403,
  URL=http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM

答:
It's not a problem with Android.

Try to access the URL in your browser, it won't work either.

Be sure to verify that it is the correct URL you are trying to access.

Body:
I'm trying to get data from site.
When I use this code in Intellij IDEA everything works fine, but when I use this code in Android Studio and real device, I get:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403

Here is my code:

private static final String URL = "http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM";

private static final String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/52.0.2743.116 Safari/537.36";

Document document = Jsoup.connect(URL)
                        .userAgent(useragent)
                        .ignoreContentType(true)
                        .timeout(5000)
                        .execute() //  <-- on this line I get error
                        .parse();

All information that I have found is only about "userAgent()" method, but It didn't help.

UPD: Sorry, it was my bad in question. Correct url: http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM, but I still have the same problem.

Error:  org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403,
  URL=http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM


问:
QML use remaining width of last line in a Flow with multi-line Text
In QML, I want to fit some text into a limited amount of space. This text contains a localised, static and a variable part (a filename). The variable part is potentially too long to fit into the space I have and should be elided if that happens. The first part is allowed to wrap to a new line and being localised might do so or not.

My problem right now is the following: Both texts are in a Flow container, with the aim of appending the filename to the static text. However, if the first text part wraps, the whole text has the maximum width I have available and the filename will be put on a new line, even though the last line of the first part doesn't completely fill the space. See this image:

The code:

```<code>Flow {
    width: parent.width
    spacing: 4
    Text {
        width: (contentWidth <= parent.width) ? contentWidth : parent.width
        text: qsTr("A string that might or might not wrap, depending on localisation")
        wrapMode: Text.WordWrap
    }
    Text {
        width: (contentWidth <= parent.width) ? contentWidth : parent.width
        text: fileName
        color: customColor
        elide: Text.ElideMiddle
        // ... more options
        MouseArea {
            anchors.fill: parent
            onClicked: //stuff
        }
    }
}
</code>```

Is it possible to use the remaining space of the last line?

EDIT: This is how it's supposed to look:

答:
The only way I came up with is very hacky.

The problem is, the Text is one object, with a rectangular bounding box around. This bounding box is used by the Flow for the positioning.

The idea behind my hacky solution is, to break up the text in single words, that are then positioned by the Flow. Now the Flow knows where the last word ended and therefore is able to place the next Text right behind that.

```<code>Flow {
    id: flw
    property string text: "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    width: 300
    spacing: fnt.advanceWidth(' ')

    FontMetrics {
        id: fnt
    }

    Repeater {
        id: rep
        model: flw.text.split(' ')
        delegate: Text {
            font: fnt.font
            text: modelData
        }
    }

    Text {
        text: "C:/Some/Path/To/The/File/In/Question/File.extension"
        color: 'green'
        width: {
            var neighbor = rep.itemAt(rep.count - 1)
            parent.width - neighbor.x - neighbor.width - parent.spacing
        }
        elide: Text.ElideMiddle
    }
}
</code>```

Body:
In QML, I want to fit some text into a limited amount of space. This text contains a localised, static and a variable part (a filename). The variable part is potentially too long to fit into the space I have and should be elided if that happens. The first part is allowed to wrap to a new line and being localised might do so or not.

My problem right now is the following: Both texts are in a Flow container, with the aim of appending the filename to the static text. However, if the first text part wraps, the whole text has the maximum width I have available and the filename will be put on a new line, even though the last line of the first part doesn't completely fill the space. See this image:

The code:

Flow {
    width: parent.width
    spacing: 4
    Text {
        width: (contentWidth <= parent.width) ? contentWidth : parent.width
        text: qsTr("A string that might or might not wrap, depending on localisation")
        wrapMode: Text.WordWrap
    }
    Text {
        width: (contentWidth <= parent.width) ? contentWidth : parent.width
        text: fileName
        color: customColor
        elide: Text.ElideMiddle
        // ... more options
        MouseArea {
            anchors.fill: parent
            onClicked: //stuff
        }
    }
}

Is it possible to use the remaining space of the last line?

EDIT: This is how it's supposed to look:

Body:
The only way I came up with is very hacky.

The problem is, the Text is one object, with a rectangular bounding box around. This bounding box is used by the Flow for the positioning.

The idea behind my hacky solution is, to break up the text in single words, that are then positioned by the Flow. Now the Flow knows where the last word ended and therefore is able to place the next Text right behind that.

Flow {
    id: flw
    property string text: "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    width: 300
    spacing: fnt.advanceWidth(' ')

    FontMetrics {
        id: fnt
    }

    Repeater {
        id: rep
        model: flw.text.split(' ')
        delegate: Text {
            font: fnt.font
            text: modelData
        }
    }

    Text {
        text: "C:/Some/Path/To/The/File/In/Question/File.extension"
        color: 'green'
        width: {
            var neighbor = rep.itemAt(rep.count - 1)
            parent.width - neighbor.x - neighbor.width - parent.spacing
        }
        elide: Text.ElideMiddle
    }
}


问:
Modern C++: initialize constexpr tables
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

```<code>A[x] = f(A[x - 1]);
</code>```

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

```<code>const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}
</code>```

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

答:
One example:

```<code>#include <utility>

constexpr int f(int a) { return a + 1; }

template<int... Idxs>
constexpr void init(int* A, std::integer_sequence<int, Idxs...>) {
    auto discard = {A[Idxs] = f(A[Idxs - 1])...};
    static_cast<void>(discard);
}

int main() {
    int A[1024];
    A[0] = 1;
    init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
}
</code>```

Requires -ftemplate-depth=1026 g++ command line switch.

Example how to make it a static member:

```<code>struct B
{
    int A[1024];

    B() {
        A[0] = 1;
        init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
    };
};

struct C
{
    static B const b;
};

B const C::b;
</code>```

Title: Modern C++: initialize constexpr tables

Body:
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

A[x] = f(A[x - 1]);

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

Body:
One example:

#include <utility>

constexpr int f(int a) { return a + 1; }

template<int... Idxs>
constexpr void init(int* A, std::integer_sequence<int, Idxs...>) {
    auto discard = {A[Idxs] = f(A[Idxs - 1])...};
    static_cast<void>(discard);
}

int main() {
    int A[1024];
    A[0] = 1;
    init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
}

Requires -ftemplate-depth=1026 g++ command line switch.

Example how to make it a static member:

struct B
{
    int A[1024];

    B() {
        A[0] = 1;
        init(A + 1, std::make_integer_sequence<int, sizeof A / sizeof *A - 1>{});
    };
};

struct C
{
    static B const b;
};

B const C::b;


问:
SQL to group time series meeting a criteria, according to start and end time
I am analyzing power systems time series data, and I am trying to find the contiguous data points that meet a certain boolean flag.

I would like to query this table by returning the start and end time corresponding to the inflection points wherein the value changed from 1 to 0, and 0 to 1.

How should go about implementing the pseudo-sql code below?

```<code>SELECT Time
FROM InputTable
WHERE InputTable.Value = 1
INTO OutputTable??, TimeStart??, TimeEnd??;
</code>```

Input:

```<code>+-------+---------+------+
| Index |  Time   | Value|
+-------+---------+------+
|     0 | 00:00:01|   1  |
|     1 | 00:00:02|   1  |
|     2 | 00:00:03|   1  |
|     3 | 00:00:04|   0  |
|     4 | 00:00:05|   1  |
|     5 | 00:00:06|   1  |
|     6 | 00:00:07|   0  |
|     7 | 00:00:08|   1  |
+-------+---------+------+
</code>```

Output:

```<code>+-------+-----------+----------+
| Index | TimeStart | TimeEnd  |
+-------+-----------+----------+
|     0 | 00:00:01  | 00:00:03 |
|     1 | 00:00:05  | 00:00:06 |
|     2 | 00:00:08  | 00:00:08 |
+-------+-----------+----------+
</code>```

答:
You need to group the values based on adjacent "1"s.  This is tricky in MS Access.  One method that can be used in Access is to count the number of "0"s (or non-"1" values) before each row. </p>

```<code>select ind, min(time), max(time)
from (select t.*,
             (select 1 + count(*)
              from inputtable as t2
              where t2.value = 0 and t2.time < t.time
             ) as ind
      from inputtable as t
     ) as t
where value = 1
group by ind
</code>```

Body:
I am analyzing power systems time series data, and I am trying to find the contiguous data points that meet a certain boolean flag.

I would like to query this table by returning the start and end time corresponding to the inflection points wherein the value changed from 1 to 0, and 0 to 1.

How should go about implementing the pseudo-sql code below?

SELECT Time
FROM InputTable
WHERE InputTable.Value = 1
INTO OutputTable??, TimeStart??, TimeEnd??;

Input:

+-------+---------+------+
| Index |  Time   | Value|
+-------+---------+------+
|     0 | 00:00:01|   1  |
|     1 | 00:00:02|   1  |
|     2 | 00:00:03|   1  |
|     3 | 00:00:04|   0  |
|     4 | 00:00:05|   1  |
|     5 | 00:00:06|   1  |
|     6 | 00:00:07|   0  |
|     7 | 00:00:08|   1  |
+-------+---------+------+

Output:

+-------+-----------+----------+
| Index | TimeStart | TimeEnd  |
+-------+-----------+----------+
|     0 | 00:00:01  | 00:00:03 |
|     1 | 00:00:05  | 00:00:06 |
|     2 | 00:00:08  | 00:00:08 |
+-------+-----------+----------+

Body:
You need to group the values based on adjacent "1"s.  This is tricky in MS Access.  One method that can be used in Access is to count the number of "0"s (or non-"1" values) before each row.

select ind, min(time), max(time)
from (select t.*,
             (select 1 + count(*)
              from inputtable as t2
              where t2.value = 0 and t2.time < t.time
             ) as ind
      from inputtable as t
     ) as t
where value = 1
group by ind


问:
Hibernate Criteria: projection with joined entity
I'm trying to create a query with Criteria, but I don't succeed to map data from a joined entity.

With this Criteria query the id of the Order entity is override with the id of the ShippingCondition entity :

```<code>final Criteria criteria = session.createCriteria(Order.class, "o")
    .createAlias("o.shippingCondition", "sc", JoinType.INNER_JOIN)
    .setProjection(Projections.projectionList()
        .add(Projections.property("o.id"), "id")
        .add(Projections.property("o.orderNum"), "orderNum")
        .add(Projections.property("o.notes"), "notes")
        .add(Projections.property("sc.id"), "id"))
    .add(Restrictions.eq("o.id", id))
    .setResultTransformer(Transformers.aliasToBean(Order.class));

return (Order) criteria.uniqueResult();
</code>```

My entities :

```<code>@Table(name = "order", schema = "myschema")
public class Order {

    private Integer id;
    private String orderNum;
    private String notes;
    private ShippingCondition shippingCondition;
    ...
}

@Table(name = "shipping_condition", schema = "myschema")
public class ShippingCondition {

    private Integer id;
    private String shippingCondition;
    private Integer sorting;
    ...
}
</code>```

I have tryed to replace .add(Projections.property("sc.id"), "id") by .add(Projections.property("sc.id"), "shippingCondition.id") but then I get a ClassCastException (java.lang.ClassCastException: entity.Order cannot be cast to java.util.Map)

Do you have any idea how I can do that ?

Thanks

答:
Hibernate doesn't support nested projections. You will need to create DTO for that. You can extend DTO from Order class and add methods to set fields of ShippingCondition.

```<code>class OrderDto extends Order {

  public OrderDto() {
      setShippingCondition(new ShippingCondition());
  }

  public void setShippingConditionId(Integer id) {
      getShippingCondition().setId(id);
  }

}
</code>```

You can use a special nested transformer if you don't want to use DTO

How to transform a flat result set using Hibernate

Additional notes

JPA doesn't support any transformers at all. And it is hard to implement such transformer by consistent way. For example, my transformer doesn't support child collections like @OneToMany, only single associations. Also, you can't use nested projections with HQL, because HQL doesn't support parent.child aliases.

Body:
I'm trying to create a query with Criteria, but I don't succeed to map data from a joined entity.

With this Criteria query the id of the Order entity is override with the id of the ShippingCondition entity :

final Criteria criteria = session.createCriteria(Order.class, "o")
    .createAlias("o.shippingCondition", "sc", JoinType.INNER_JOIN)
    .setProjection(Projections.projectionList()
        .add(Projections.property("o.id"), "id")
        .add(Projections.property("o.orderNum"), "orderNum")
        .add(Projections.property("o.notes"), "notes")
        .add(Projections.property("sc.id"), "id"))
    .add(Restrictions.eq("o.id", id))
    .setResultTransformer(Transformers.aliasToBean(Order.class));

return (Order) criteria.uniqueResult();

My entities :

@Table(name = "order", schema = "myschema")
public class Order {

    private Integer id;
    private String orderNum;
    private String notes;
    private ShippingCondition shippingCondition;
    ...
}

@Table(name = "shipping_condition", schema = "myschema")
public class ShippingCondition {

    private Integer id;
    private String shippingCondition;
    private Integer sorting;
    ...
}

I have tryed to replace .add(Projections.property("sc.id"), "id") by .add(Projections.property("sc.id"), "shippingCondition.id") but then I get a ClassCastException (java.lang.ClassCastException: entity.Order cannot be cast to java.util.Map)

Do you have any idea how I can do that ?

Thanks

Body:
Hibernate doesn't support nested projections. You will need to create DTO for that. You can extend DTO from Order class and add methods to set fields of ShippingCondition.

class OrderDto extends Order {

  public OrderDto() {
      setShippingCondition(new ShippingCondition());
  }

  public void setShippingConditionId(Integer id) {
      getShippingCondition().setId(id);
  }

}

You can use a special nested transformer if you don't want to use DTO

How to transform a flat result set using Hibernate

Additional notes

JPA doesn't support any transformers at all. And it is hard to implement such transformer by consistent way. For example, my transformer doesn't support child collections like @OneToMany, only single associations. Also, you can't use nested projections with HQL, because HQL doesn't support parent.child aliases.